_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 |
|---|---|---|---|---|---|---|---|---|
ba162dd5c219790b009278beb6d91e956f1eb4528d7176b397c076e567e943a9 | jfeser/castor | project.mli | open Core
open Ast
val project_once :
params:Set.M(Name).t -> < refs : bool Map.M(Name).t ; .. > annot -> < > annot
val project :
params:Set.M(Name).t -> ?max_iters:int -> < .. > annot -> < > annot
| null | https://raw.githubusercontent.com/jfeser/castor/39005df41a094fee816e85c4c673bfdb223139f7/lib/project.mli | ocaml | open Core
open Ast
val project_once :
params:Set.M(Name).t -> < refs : bool Map.M(Name).t ; .. > annot -> < > annot
val project :
params:Set.M(Name).t -> ?max_iters:int -> < .. > annot -> < > annot
| |
3d3c1641edc22bf54f2f6190453d50205495d0f6eb7837087cebfc95a00de946 | NorfairKing/intray | OptParse.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module Intray.Web.Server.OptParse
( getSettings,
Settings (..),
)
where
import Autodocodec.Yaml
import Control.Arrow
import Control.Monad.Logger
import qualified Data.Text as T
import qualified Env
import Import
import Intray.Web.Server.OptParse.Types
import Options.Applicative
import qualified Options.Applicative.Help as OptParse
import Servant.Client
import qualified System.Environment as System
getSettings :: IO Settings
getSettings = do
flags <- getFlags
env <- getEnvironment
config <- getConfiguration flags env
combineToSettings flags env config
combineToSettings :: Flags -> Environment -> Maybe Configuration -> IO Settings
combineToSettings Flags {..} Environment {..} mConf = do
let mc :: (Configuration -> Maybe a) -> Maybe a
mc func = mConf >>= func
let setPort = fromMaybe 8080 $ flagPort <|> envPort <|> mc confPort
setAPIBaseUrl <- case flagAPIBaseUrl <|> envAPIBaseUrl <|> mc confAPIBaseUrl of
Nothing -> die "No API URL Configured. Try --help to see how to configure it."
Just burl -> pure burl
let setLogLevel = fromMaybe LevelInfo $ flagLogLevel <|> envLogLevel <|> mc confLogLevel
let setTracking = flagTracking <|> envTracking <|> mc confTracking
let setVerification = flagVerification <|> envVerification <|> mc confVerification
let setLoginCacheFile = fromMaybe "intray-web-server.db" $ flagLoginCacheFile <|> envLoginCacheFile <|> mc confLoginCacheFile
pure Settings {..}
getConfiguration :: Flags -> Environment -> IO (Maybe Configuration)
getConfiguration Flags {..} Environment {..} = do
configFile <- case flagConfigFile <|> envConfigFile of
Nothing -> getDefaultConfigFile
Just cf -> resolveFile' cf
readYamlConfigFile configFile
getDefaultConfigFile :: IO (Path Abs File)
getDefaultConfigFile = resolveFile' "config.yaml"
getEnvironment :: IO Environment
getEnvironment = Env.parse id environmentParser
environmentParser :: Env.Parser Env.Error Environment
environmentParser =
Env.prefixed "INTRAY_WEB_SERVER_" $
Environment
<$> optional (Env.var Env.str "CONFIG_FILE" (Env.help "Config file"))
<*> optional (Env.var Env.auto "PORT" (Env.help "port to run the web server on"))
<*> optional (Env.var Env.auto "LOG_LEVEL" (Env.help "minimal severity for log messages"))
<*> optional (Env.var (left (Env.UnreadError . show) . parseBaseUrl) "API_URL" (Env.help "base url for the api server to call"))
<*> optional (Env.var Env.str "ANALYTICS_TRACKING_ID" (Env.help "google analytics tracking id"))
<*> optional (Env.var Env.str "SEARCH_CONSOLE_VERIFICATION" (Env.help "google search console verification id"))
<*> optional (Env.var Env.str "LOGIN_CACHE_FILE" (Env.help "google search console verification id"))
getFlags :: IO Flags
getFlags = do
args <- System.getArgs
let result = runFlagsParser args
handleParseResult result
runFlagsParser :: [String] -> ParserResult Flags
runFlagsParser = execParserPure prefs_ flagsParser
where
prefs_ = defaultPrefs {prefShowHelpOnError = True, prefShowHelpOnEmpty = True}
flagsParser :: ParserInfo Flags
flagsParser = info (helper <*> parseFlags) (fullDesc <> footerDoc (Just $ OptParse.string footerStr))
where
footerStr =
unlines
[ Env.helpDoc environmentParser,
"",
"Configuration file format:",
T.unpack (renderColouredSchemaViaCodec @Configuration)
]
parseFlags :: Parser Flags
parseFlags =
Flags
<$> option
(Just <$> str)
(mconcat [long "config-file", value Nothing, metavar "FILEPATH", help "The config file"])
<*> optional
( option
auto
( mconcat
[ long "port",
metavar "PORT",
help "the port to serve on"
]
)
)
<*> optional
( option
(eitherReader $ left show . parseBaseUrl)
( mconcat
[ long "api-url",
metavar "URL",
help "the url to call the API server on"
]
)
)
<*> optional
( option
auto
( mconcat
[ long "log-level",
metavar "LOG_LEVEL",
help "the minimal severity for log messages"
]
)
)
<*> optional
( strOption
( mconcat
[ long "analytics-tracking-id",
metavar "TRACKING_ID",
help "The google analytics tracking ID"
]
)
)
<*> optional
( strOption
( mconcat
[ long "search-console-verification",
metavar "VERIFICATION_TAG",
help "The contents of the google search console verification tag"
]
)
)
<*> optional
( strOption
( mconcat
[ long "login-cache-file",
metavar "FILEPATH",
help "The file to store the login cache database in"
]
)
)
| null | https://raw.githubusercontent.com/NorfairKing/intray/2e6864fba2a21947a4da560b7186a4889f7db773/intray-web-server/src/Intray/Web/Server/OptParse.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
module Intray.Web.Server.OptParse
( getSettings,
Settings (..),
)
where
import Autodocodec.Yaml
import Control.Arrow
import Control.Monad.Logger
import qualified Data.Text as T
import qualified Env
import Import
import Intray.Web.Server.OptParse.Types
import Options.Applicative
import qualified Options.Applicative.Help as OptParse
import Servant.Client
import qualified System.Environment as System
getSettings :: IO Settings
getSettings = do
flags <- getFlags
env <- getEnvironment
config <- getConfiguration flags env
combineToSettings flags env config
combineToSettings :: Flags -> Environment -> Maybe Configuration -> IO Settings
combineToSettings Flags {..} Environment {..} mConf = do
let mc :: (Configuration -> Maybe a) -> Maybe a
mc func = mConf >>= func
let setPort = fromMaybe 8080 $ flagPort <|> envPort <|> mc confPort
setAPIBaseUrl <- case flagAPIBaseUrl <|> envAPIBaseUrl <|> mc confAPIBaseUrl of
Nothing -> die "No API URL Configured. Try --help to see how to configure it."
Just burl -> pure burl
let setLogLevel = fromMaybe LevelInfo $ flagLogLevel <|> envLogLevel <|> mc confLogLevel
let setTracking = flagTracking <|> envTracking <|> mc confTracking
let setVerification = flagVerification <|> envVerification <|> mc confVerification
let setLoginCacheFile = fromMaybe "intray-web-server.db" $ flagLoginCacheFile <|> envLoginCacheFile <|> mc confLoginCacheFile
pure Settings {..}
getConfiguration :: Flags -> Environment -> IO (Maybe Configuration)
getConfiguration Flags {..} Environment {..} = do
configFile <- case flagConfigFile <|> envConfigFile of
Nothing -> getDefaultConfigFile
Just cf -> resolveFile' cf
readYamlConfigFile configFile
getDefaultConfigFile :: IO (Path Abs File)
getDefaultConfigFile = resolveFile' "config.yaml"
getEnvironment :: IO Environment
getEnvironment = Env.parse id environmentParser
environmentParser :: Env.Parser Env.Error Environment
environmentParser =
Env.prefixed "INTRAY_WEB_SERVER_" $
Environment
<$> optional (Env.var Env.str "CONFIG_FILE" (Env.help "Config file"))
<*> optional (Env.var Env.auto "PORT" (Env.help "port to run the web server on"))
<*> optional (Env.var Env.auto "LOG_LEVEL" (Env.help "minimal severity for log messages"))
<*> optional (Env.var (left (Env.UnreadError . show) . parseBaseUrl) "API_URL" (Env.help "base url for the api server to call"))
<*> optional (Env.var Env.str "ANALYTICS_TRACKING_ID" (Env.help "google analytics tracking id"))
<*> optional (Env.var Env.str "SEARCH_CONSOLE_VERIFICATION" (Env.help "google search console verification id"))
<*> optional (Env.var Env.str "LOGIN_CACHE_FILE" (Env.help "google search console verification id"))
getFlags :: IO Flags
getFlags = do
args <- System.getArgs
let result = runFlagsParser args
handleParseResult result
runFlagsParser :: [String] -> ParserResult Flags
runFlagsParser = execParserPure prefs_ flagsParser
where
prefs_ = defaultPrefs {prefShowHelpOnError = True, prefShowHelpOnEmpty = True}
flagsParser :: ParserInfo Flags
flagsParser = info (helper <*> parseFlags) (fullDesc <> footerDoc (Just $ OptParse.string footerStr))
where
footerStr =
unlines
[ Env.helpDoc environmentParser,
"",
"Configuration file format:",
T.unpack (renderColouredSchemaViaCodec @Configuration)
]
parseFlags :: Parser Flags
parseFlags =
Flags
<$> option
(Just <$> str)
(mconcat [long "config-file", value Nothing, metavar "FILEPATH", help "The config file"])
<*> optional
( option
auto
( mconcat
[ long "port",
metavar "PORT",
help "the port to serve on"
]
)
)
<*> optional
( option
(eitherReader $ left show . parseBaseUrl)
( mconcat
[ long "api-url",
metavar "URL",
help "the url to call the API server on"
]
)
)
<*> optional
( option
auto
( mconcat
[ long "log-level",
metavar "LOG_LEVEL",
help "the minimal severity for log messages"
]
)
)
<*> optional
( strOption
( mconcat
[ long "analytics-tracking-id",
metavar "TRACKING_ID",
help "The google analytics tracking ID"
]
)
)
<*> optional
( strOption
( mconcat
[ long "search-console-verification",
metavar "VERIFICATION_TAG",
help "The contents of the google search console verification tag"
]
)
)
<*> optional
( strOption
( mconcat
[ long "login-cache-file",
metavar "FILEPATH",
help "The file to store the login cache database in"
]
)
)
|
30bc38e6caaa9419c0a224f370c8eff63de4b5c7490305e6a00222ff2e5b4af9 | mattmundell/nightshade | char.lisp | ;;; The x86 VM definition of character operations.
(in-package "X86")
;;;; Moves and coercions.
;;; Move a tagged char to an untagged representation.
;;;
(define-vop (move-to-base-char)
(:args (x :scs (any-reg control-stack) :target al))
(:temporary (:sc byte-reg :offset al-offset
:from (:argument 0) :to (:eval 0)) al)
(:ignore al)
(:temporary (:sc byte-reg :offset ah-offset :target y
:from (:argument 0) :to (:result 0)) ah)
(:results (y :scs (base-char-reg base-char-stack)))
(:note "character untagging")
(:generator 1
(move eax-tn x)
(move y ah)))
;;;
(define-move-vop move-to-base-char :move
(any-reg control-stack) (base-char-reg base-char-stack))
;;; Move an untagged char to a tagged representation.
;;;
(define-vop (move-from-base-char)
(:args (x :scs (base-char-reg base-char-stack) :target ah))
(:temporary (:sc byte-reg :offset al-offset :target y
:from (:argument 0) :to (:result 0)) al)
(:temporary (:sc byte-reg :offset ah-offset
:from (:argument 0) :to (:result 0)) ah)
(:results (y :scs (any-reg descriptor-reg control-stack)))
(:note "character tagging")
(:generator 1
(move ah x) ; maybe move char byte
(inst mov al base-char-type) ; #x86 to type bits
(inst and eax-tn #xffff) ; remove any junk bits
(move y eax-tn)))
;;;
(define-move-vop move-from-base-char :move
(base-char-reg base-char-stack) (any-reg descriptor-reg control-stack))
;;; Move untagged base-char values.
;;;
(define-vop (base-char-move)
(:args (x :target y
:scs (base-char-reg)
:load-if (not (location= x y))))
(:results (y :scs (base-char-reg base-char-stack)
:load-if (not (location= x y))))
(:note "character move")
(:effects)
(:affected)
(:generator 0
(move y x)))
;;;
(define-move-vop base-char-move :move
(base-char-reg) (base-char-reg base-char-stack))
;;; Move untagged base-char arguments/return-values.
;;;
(define-vop (move-base-char-argument)
(:args (x :target y
:scs (base-char-reg))
(fp :scs (any-reg)
:load-if (not (sc-is y base-char-reg))))
(:results (y))
(:note "character arg move")
(:generator 0
(sc-case y
(base-char-reg
(move y x))
(base-char-stack
(inst mov
(make-ea :byte :base fp :disp (- (* (1+ (tn-offset y)) 4)))
x)))))
;;;
(define-move-vop move-base-char-argument :move-argument
(any-reg base-char-reg) (base-char-reg))
;;; Use standard MOVE-ARGUMENT + coercion to move an untagged base-char
;;; to a descriptor passing location.
;;;
(define-move-vop move-argument :move-argument
(base-char-reg) (any-reg descriptor-reg))
;;;; Other operations.
(define-vop (char-code)
(:translate char-code)
(:policy :fast-safe)
(:args (ch :scs (base-char-reg base-char-stack)))
(:arg-types base-char)
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 1
(inst movzx res ch)))
(define-vop (code-char)
(:translate code-char)
(:policy :fast-safe)
(:args (code :scs (unsigned-reg unsigned-stack) :target eax))
(:arg-types positive-fixnum)
(:temporary (:sc unsigned-reg :offset eax-offset :target res
:from (:argument 0) :to (:result 0))
eax)
(:results (res :scs (base-char-reg)))
(:result-types base-char)
(:generator 1
(move eax code)
(move res al-tn)))
Comparison of base - chars .
;;;
(define-vop (base-char-compare)
(:args (x :scs (base-char-reg base-char-stack))
(y :scs (base-char-reg)
:load-if (not (and (sc-is x base-char-reg)
(sc-is y base-char-stack)))))
(:arg-types base-char base-char)
(:conditional)
(:info target not-p)
(:policy :fast-safe)
(:note "inline comparison")
(:variant-vars condition not-condition)
(:generator 3
(inst cmp x y)
(inst jmp (if not-p not-condition condition) target)))
(define-vop (fast-char=/base-char base-char-compare)
(:translate char=)
(:variant :e :ne))
(define-vop (fast-char</base-char base-char-compare)
(:translate char<)
(:variant :b :nb))
(define-vop (fast-char>/base-char base-char-compare)
(:translate char>)
(:variant :a :na))
| null | https://raw.githubusercontent.com/mattmundell/nightshade/d8abd7bd3424b95b70bed599e0cfe033e15299e0/src/compiler/x86/char.lisp | lisp | The x86 VM definition of character operations.
Moves and coercions.
Move a tagged char to an untagged representation.
Move an untagged char to a tagged representation.
maybe move char byte
#x86 to type bits
remove any junk bits
Move untagged base-char values.
Move untagged base-char arguments/return-values.
Use standard MOVE-ARGUMENT + coercion to move an untagged base-char
to a descriptor passing location.
Other operations.
|
(in-package "X86")
(define-vop (move-to-base-char)
(:args (x :scs (any-reg control-stack) :target al))
(:temporary (:sc byte-reg :offset al-offset
:from (:argument 0) :to (:eval 0)) al)
(:ignore al)
(:temporary (:sc byte-reg :offset ah-offset :target y
:from (:argument 0) :to (:result 0)) ah)
(:results (y :scs (base-char-reg base-char-stack)))
(:note "character untagging")
(:generator 1
(move eax-tn x)
(move y ah)))
(define-move-vop move-to-base-char :move
(any-reg control-stack) (base-char-reg base-char-stack))
(define-vop (move-from-base-char)
(:args (x :scs (base-char-reg base-char-stack) :target ah))
(:temporary (:sc byte-reg :offset al-offset :target y
:from (:argument 0) :to (:result 0)) al)
(:temporary (:sc byte-reg :offset ah-offset
:from (:argument 0) :to (:result 0)) ah)
(:results (y :scs (any-reg descriptor-reg control-stack)))
(:note "character tagging")
(:generator 1
(move y eax-tn)))
(define-move-vop move-from-base-char :move
(base-char-reg base-char-stack) (any-reg descriptor-reg control-stack))
(define-vop (base-char-move)
(:args (x :target y
:scs (base-char-reg)
:load-if (not (location= x y))))
(:results (y :scs (base-char-reg base-char-stack)
:load-if (not (location= x y))))
(:note "character move")
(:effects)
(:affected)
(:generator 0
(move y x)))
(define-move-vop base-char-move :move
(base-char-reg) (base-char-reg base-char-stack))
(define-vop (move-base-char-argument)
(:args (x :target y
:scs (base-char-reg))
(fp :scs (any-reg)
:load-if (not (sc-is y base-char-reg))))
(:results (y))
(:note "character arg move")
(:generator 0
(sc-case y
(base-char-reg
(move y x))
(base-char-stack
(inst mov
(make-ea :byte :base fp :disp (- (* (1+ (tn-offset y)) 4)))
x)))))
(define-move-vop move-base-char-argument :move-argument
(any-reg base-char-reg) (base-char-reg))
(define-move-vop move-argument :move-argument
(base-char-reg) (any-reg descriptor-reg))
(define-vop (char-code)
(:translate char-code)
(:policy :fast-safe)
(:args (ch :scs (base-char-reg base-char-stack)))
(:arg-types base-char)
(:results (res :scs (unsigned-reg)))
(:result-types positive-fixnum)
(:generator 1
(inst movzx res ch)))
(define-vop (code-char)
(:translate code-char)
(:policy :fast-safe)
(:args (code :scs (unsigned-reg unsigned-stack) :target eax))
(:arg-types positive-fixnum)
(:temporary (:sc unsigned-reg :offset eax-offset :target res
:from (:argument 0) :to (:result 0))
eax)
(:results (res :scs (base-char-reg)))
(:result-types base-char)
(:generator 1
(move eax code)
(move res al-tn)))
Comparison of base - chars .
(define-vop (base-char-compare)
(:args (x :scs (base-char-reg base-char-stack))
(y :scs (base-char-reg)
:load-if (not (and (sc-is x base-char-reg)
(sc-is y base-char-stack)))))
(:arg-types base-char base-char)
(:conditional)
(:info target not-p)
(:policy :fast-safe)
(:note "inline comparison")
(:variant-vars condition not-condition)
(:generator 3
(inst cmp x y)
(inst jmp (if not-p not-condition condition) target)))
(define-vop (fast-char=/base-char base-char-compare)
(:translate char=)
(:variant :e :ne))
(define-vop (fast-char</base-char base-char-compare)
(:translate char<)
(:variant :b :nb))
(define-vop (fast-char>/base-char base-char-compare)
(:translate char>)
(:variant :a :na))
|
8be81d3b49f7746cb5d2b5fefb3effb671ae10cb7dc7818ade4a042178f35948 | florence/cover | main.rkt | #lang racket/base
(require "cover.rkt" "format.rkt" "private/contracts.rkt" "private/format-utils.rkt"
"private/raw.rkt" racket/contract)
(define (not-impersonated/c c)
(and/c (lambda (v) (not (impersonator? v)))
c))
(provide
(contract-out
[coverage/c contract?]
[test-files! (->* () (#:submod (or/c symbol? (listof symbol?))
#:env environment?
#:dont-compile (listof path-string?))
#:rest
(listof (or/c path-string?
(list/c path-string?
(not-impersonated/c
(vectorof (not-impersonated/c string?) #:immutable #t)))))
any)]
[environment? (-> any/c any/c)]
[make-cover-environment (->* () (namespace?) environment?)]
[current-cover-environment (parameter/c environment?)]
[get-test-coverage (->* () (environment?) coverage/c)]
[irrelevant-submodules (parameter/c (or/c #f (listof symbol?)))]
[generate-html-coverage coverage-gen/c]
[generate-raw-coverage coverage-gen/c]))
| null | https://raw.githubusercontent.com/florence/cover/bc17e4e22d47b1da91ddaa5eafefe28f4675e85c/cover-lib/cover/main.rkt | racket | #lang racket/base
(require "cover.rkt" "format.rkt" "private/contracts.rkt" "private/format-utils.rkt"
"private/raw.rkt" racket/contract)
(define (not-impersonated/c c)
(and/c (lambda (v) (not (impersonator? v)))
c))
(provide
(contract-out
[coverage/c contract?]
[test-files! (->* () (#:submod (or/c symbol? (listof symbol?))
#:env environment?
#:dont-compile (listof path-string?))
#:rest
(listof (or/c path-string?
(list/c path-string?
(not-impersonated/c
(vectorof (not-impersonated/c string?) #:immutable #t)))))
any)]
[environment? (-> any/c any/c)]
[make-cover-environment (->* () (namespace?) environment?)]
[current-cover-environment (parameter/c environment?)]
[get-test-coverage (->* () (environment?) coverage/c)]
[irrelevant-submodules (parameter/c (or/c #f (listof symbol?)))]
[generate-html-coverage coverage-gen/c]
[generate-raw-coverage coverage-gen/c]))
| |
dd19912eca96518b1322fa261e67d0b8eaa71745891cb2beb220a16f9acda9ab | ih/ikarus.dev | nbody.scm | This benchmark was obtained from .
970215 / wdc Changed { box , unbox , set - box ! } to { list , car , set - car ! } ,
flushed # % prefixes , defined void ,
; and added nbody-benchmark.
; 981116 / wdc Replaced nbody-benchmark by main, added apply:+.
(define void
(let ((invisible (string->symbol "")))
(lambda () invisible)))
(define (apply:+ xs)
(do ((result 0.0 (FLOAT+ result (car xs)))
(xs xs (cdr xs)))
((null? xs) result)))
;; code is slightly broken...
(define vect (vector))
; minimal standard random number generator
32 bit integer version
cacm 31 10 , oct 88
;
(define *seed* (list 1))
(define (srand seed)
(set-car! *seed* seed))
(define (rand)
(let* ((hi (quotient (car *seed*) 127773))
(lo (modulo (car *seed*) 127773))
(test (- (* 16807 lo) (* 2836 hi))))
(if (> test 0)
(set-car! *seed* test)
(set-car! *seed* (+ test 2147483647)))
(car *seed*)))
;; return a random number in the interval [0,n)
(define random
(lambda (n)
(modulo (abs (rand)) n)))
(define (array-ref a . indices)
(let loop ((a a) (indices indices))
(if (null? indices)
a
(loop (vector-ref a (car indices)) (cdr indices)))))
(define (atan0 y x)
(if (and (= x y) (= x 0)) 0 (atan y x)))
;change this to desired precision
;measured in order of expansions calculated
(define precision 10)
;;; =========================================================
;;; Algorithm
;;; =========================================================
(define (cartesian-algorithm tree)
(up! tree
cartesian-make-multipole-expansion
cartesian-multipole-shift
cartesian-expansion-sum)
(down! tree
cartesian-multipole-to-local-convert
cartesian-local-shift
cartesian-eval-local-expansion
cartesian-expansion-sum
cartesian-zero-expansion))
(define (spherical-algorithm tree)
(up! tree
spherical-make-multipole-expansion
spherical-multipole-shift
spherical-expansion-sum)
(down! tree
spherical-multipole-to-local-convert
spherical-local-shift
spherical-eval-local-expansion
spherical-expansion-sum
spherical-zero-expansion))
;;; The upward path in the algorithm calculates
;;; multipole expansions at every node.
(define (up! tree
make-multipole-expansion
multipole-shift
expansion-sum)
(let loop ((node (tree-body tree)))
(define center (node-center node))
(if (leaf-node? node)
(let ((multipole-expansion
(expansion-sum
(map (lambda (particle)
(make-multipole-expansion
(pt- (particle-position particle) center)
(particle-strength particle)))
(node-particles node)))))
(set-node-multipole-expansion! node multipole-expansion)
(cons center multipole-expansion))
(let ((multipole-expansion
(expansion-sum
(map (lambda (child)
(define center-and-expansion (loop child))
(multipole-shift (pt- (car center-and-expansion)
center)
(cdr center-and-expansion)))
(node-children node)))))
(set-node-multipole-expansion! node multipole-expansion)
(cons center multipole-expansion)))))
;;; Downward path of the algorithm which calculates local expansionss
;;; at every node and accelerations and potentials at each particle.
(define (down! tree
multipole-to-local-convert
local-shift
eval-local-expansion
expansion-sum
zero-expansion)
(let loop ((node (tree-body tree))
(parent-local-expansion (zero-expansion))
(parent-center (node-center (tree-body tree))))
(let* ((center (node-center node))
(interactive-sum
(expansion-sum
(map (lambda (interactive)
(multipole-to-local-convert
(pt- (node-center interactive) center)
(node-multipole-expansion interactive)))
(node-interactive-field node))))
(local-expansion
(expansion-sum (list (local-shift (pt- center parent-center)
parent-local-expansion)
interactive-sum))))
(if (leaf-node? node)
(eval-potentials-and-accelerations
node
local-expansion
eval-local-expansion)
(for-each (lambda (child) (loop child local-expansion center))
(node-children node))))))
(define (eval-potentials-and-accelerations
node
local-expansion
eval-local-expansion)
(let ((center (node-center node))
(near-field (apply append (map node-particles
(node-near-field node)))))
(for-each (lambda (particle)
(let* ((pos (particle-position particle))
(far-field-accel-and-poten
(eval-local-expansion (pt- pos center)
local-expansion)))
(set-particle-acceleration!
particle
(pt+ (car far-field-accel-and-poten)
(sum-vectors
(map (lambda (near)
(direct-accel (pt- (particle-position near)
pos)
(particle-strength near)))
(nfilter near-field
(lambda (near)
(not (eq? near particle))))))))
(set-particle-potential!
particle
(+ (cdr far-field-accel-and-poten)
(apply:+ (map (lambda (near)
(direct-poten
(pt- (particle-position near) pos)
(particle-strength near)))
(nfilter near-field
(lambda (near)
(not
(eq? near particle))))))))))
(node-particles node))))
;;; ================================================================
;;; Expansion Theorems
;;; ================================================================
(define (cartesian-make-multipole-expansion pt strength)
(let ((-x (- (pt-x pt)))
(-y (- (pt-y pt)))
(-z (- (pt-z pt))))
(make-cartesian-expansion
(lambda (i j k) (* strength
(expt -x i)
(expt -y j)
(expt -z k)
(1/prod-fac i j k))))))
(define (spherical-make-multipole-expansion pt strength)
(let ((r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt)))
(make-spherical-expansion
(lambda (l m)
(* strength
(expt r l)
(eval-spherical-harmonic l (- m) theta phi))))))
;;; ==================================================================
;;; Shifting lemmas
;;; ==================================================================
;;; Shift multipole expansion
(define (cartesian-multipole-shift pt multipole-expansion)
(let ((pt-expansion (cartesian-make-multipole-expansion pt 1)))
(make-cartesian-expansion
(lambda (i j k)
(sum-3d i j k
(lambda (l m n)
(* (array-ref multipole-expansion l m n)
(array-ref pt-expansion (- i l) (- j m) (- k n)))))))))
(define (spherical-multipole-shift pt multipole-expansion)
(let ((r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt)))
(letrec ((foo (lambda (a b)
(if (< (* a b) 0)
(expt -1 (min (abs a) (abs b)))
1)))
(bar (lambda (a b)
(/ (expt -1 a)
(sqrt (* (fac (- a b)) (fac (+ a b))))))))
(let ((pt-expansion (make-spherical-expansion
(lambda (l m)
(* (eval-spherical-harmonic l m theta phi)
(bar l m)
(expt r l))))))
(make-spherical-expansion
(lambda (j k)
(sum-2d j
(lambda (l m)
(if (> (abs (- k m)) (- j l))
0
(* (spherical-ref multipole-expansion (- j l) (- k m))
(foo m (- k m))
(bar (- j l) (- k m))
(spherical-ref pt-expansion l (- m))
(/ (bar j k))))))))))))
;;; Convert multipole to local
(define (cartesian-multipole-to-local-convert pt multipole-expansion)
(define pt-expansion
(let* ((1/radius (/ (pt-r vect)))
(2cosines (pt-scalar* (* 2 1/radius) vect))
(x (pt-x 2cosines))
(y (pt-y 2cosines))
(z (pt-z 2cosines)))
(make-cartesian-expansion
(lambda (i j k)
(define ijk (+ i j k))
(* (expt -1 ijk)
(expt 1/radius (+ 1 ijk))
(prod-fac i j k)
(sum-3d (/ i 2) (/ j 2) (/ k 2)
(lambda (l m n)
(* (fac-1 (- ijk l m n))
(1/prod-fac l m n)
(1/prod-fac (- i (* 2 l))
(- j (* 2 m))
(- k (* 2 n)))
(expt x (- i (* 2 l)))
(expt y (- j (* 2 m)))
(expt z (- k (* 2 n)))))))))))
(make-cartesian-expansion
(lambda (i j k)
(sum2-3d (- precision i j k)
(lambda (l m n)
(* (array-ref multipole-expansion l m n)
(array-ref pt-expansion (+ i l) (+ j m) (+ k n))))))))
(define (spherical-multipole-to-local-convert pt multipole-expansion)
(let* ((r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt))
(foo (lambda (a b c)
(* (expt -1 b)
(if (> (* a c) 0)
(expt -1 (min (abs a) (abs c)))
1))))
(bar (lambda (a b)
(/ (expt -1 a)
(sqrt (* (fac (- a b)) (fac (+ a b)))))))
(pt-expansion (make-spherical-expansion
(lambda (l m)
(/ (eval-spherical-harmonic l m theta phi)
(bar l m)
(expt r (+ 1 l)))))))
(make-spherical-expansion
(lambda (j k)
(* (bar j k)
(sum-2d (- precision j 1)
(lambda (l m)
(* (spherical-ref multipole-expansion l m)
(foo k l m)
(bar l m)
(spherical-ref pt-expansion (+ j l) (- m k))))))))))
;;; Shift local expansion
(define (cartesian-local-shift pt local-expansion)
(let* ((x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt))
(expts (make-cartesian-expansion
(lambda (l m n) (* (expt x l)
(expt y m)
(expt z n))))))
(make-cartesian-expansion
(lambda (i j k)
(sum2-3d (- precision i j k)
(lambda (l m n)
(* (array-ref local-expansion (+ i l) (+ j m) (+ k n))
(array-ref expts l m n)
(1/prod-fac l m n))))))))
(define (spherical-local-shift pt local-expansion)
(let* ((pt (pt- (make-pt 0 0 0) pt))
(r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt))
(foo (lambda (a b c)
(* (expt -1 a)
(expt -1 (/ (+ (abs (- b c))
(abs b)
(- (abs c)))
2)))))
(bar (lambda (a b)
(/ (expt -1 a)
(sqrt (* (fac (- a b))
(fac (+ a b)))))))
(stuff (make-spherical-expansion
(lambda (l m)
(* (eval-spherical-harmonic l m theta phi)
(expt r l))))))
(make-spherical-expansion
(lambda (j k)
(sum2-2d j (lambda (l m)
(if (> (abs (- m k)) (- l j))
0
(* (spherical-ref local-expansion l m)
(bar (- l j) (- m k))
(bar j k)
(spherical-ref stuff (- l j) (- m k))
(/ (foo (- l j) (- m k) m) (bar l m))))))))))
;;; Evaluate the resulting local expansion at point pt.
(define (cartesian-eval-local-expansion pt local-expansion)
(let* ((x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt))
(local-expansion
(make-cartesian-expansion
(lambda (i j k)
(* (array-ref local-expansion i j k)
(1/prod-fac i j k)))))
(expts (make-cartesian-expansion
(lambda (i j k)
(* (expt x i) (expt y j) (expt z k))))))
(cons (make-pt
(sum2-3d (- precision 1)
(lambda (l m n)
(* (array-ref expts l m n)
(+ 1 l)
(array-ref local-expansion (+ 1 l) m n))))
(sum2-3d (- precision 1)
(lambda (l m n)
(* (array-ref expts l m n)
(+ 1 m)
(array-ref local-expansion l (+ 1 m) n))))
(sum2-3d (- precision 1)
(lambda (l m n)
(* (array-ref expts l m n)
(+ 1 n)
(array-ref local-expansion l m (+ 1 n))))))
(sum2-3d precision
(lambda (l m n)
(* (array-ref expts l m n)
(array-ref local-expansion l m n)))))))
(define (spherical-eval-local-expansion pt local-expansion)
(let* ((r (pt-r pt))
(x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt))
(rho-sq (+ (* x x) (* y y)))
(theta (pt-theta pt))
(phi (pt-phi pt))
(r-deriv
(real-part
(sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(expt r (- l 1))
l
(eval-spherical-harmonic l m theta phi))))))
(theta-deriv
(real-part
(sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(expt r l)
(eval-spher-harm-theta-deriv l m theta phi))))))
(phi-deriv
(real-part
(sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(expt r l)
(eval-spher-harm-phi-deriv l m theta phi)))))))
(cons (make-pt
(+ (* r-deriv (/ x r))
(* theta-deriv (/ x (sqrt rho-sq) (+ z (/ rho-sq z))))
(* phi-deriv -1 (/ y rho-sq)))
(+ (* r-deriv (/ y r))
(* theta-deriv (/ y (sqrt rho-sq) (+ z (/ rho-sq z))))
(/ phi-deriv x (+ 1 (/ (* y y) x x))))
(+ (* r-deriv (/ z r))
(* theta-deriv (/ -1 r r) (sqrt rho-sq))))
(real-part (sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(eval-spherical-harmonic l m theta phi)
(expt r l))))))))
;;; Direct calculation of acceleration and potential
(define (direct-accel pt strength)
(pt-scalar* (/ strength (expt (pt-r pt) 3))
pt))
(define (direct-poten pt strength)
(/ strength (pt-r pt)))
;;; =================================================================
;;; TREES NODES PARTICLES and POINTS
;;; =================================================================
(begin (begin (begin (define make-raw-tree
(lambda (tree-1 tree-2 tree-3)
(vector '<tree> tree-1 tree-2 tree-3)))
(define tree?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 4)
(eq? (vector-ref obj 0) '<tree>)
#f)
#f)))
(define tree-1
(lambda (obj)
(if (tree? obj)
(void)
(error
'tree-1
"~s is not a ~s"
obj
'<tree>))
(vector-ref obj 1)))
(define tree-2
(lambda (obj)
(if (tree? obj)
(void)
(error
'tree-2
"~s is not a ~s"
obj
'<tree>))
(vector-ref obj 2)))
(define tree-3
(lambda (obj)
(if (tree? obj)
(void)
(error
'tree-3
"~s is not a ~s"
obj
'<tree>))
(vector-ref obj 3)))
(define set-tree-1!
(lambda (obj newval)
(if (tree? obj)
(void)
(error
'set-tree-1!
"~s is not a ~s"
obj
'<tree>))
(vector-set! obj 1 newval)))
(define set-tree-2!
(lambda (obj newval)
(if (tree? obj)
(void)
(error
'set-tree-2!
"~s is not a ~s"
obj
'<tree>))
(vector-set! obj 2 newval)))
(define set-tree-3!
(lambda (obj newval)
(if (tree? obj)
(void)
(error
'set-tree-3!
"~s is not a ~s"
obj
'<tree>))
(vector-set! obj 3 newval))))
(define make-tree
(lambda (body low-left-front-vertex up-right-back-vertex)
((lambda ()
(make-raw-tree
body
low-left-front-vertex
up-right-back-vertex)))))
(define tree-body tree-1)
(define tree-low-left-front-vertex tree-2)
(define tree-up-right-back-vertex tree-3)
(define set-tree-body! set-tree-1!)
(define set-tree-low-left-front-vertex! set-tree-2!)
(define set-tree-up-right-back-vertex! set-tree-3!))
(begin (begin (define make-raw-node
(lambda (node-1
node-2
node-3
node-4
node-5
node-6
node-7
node-8)
(vector
'<node>
node-1
node-2
node-3
node-4
node-5
node-6
node-7
node-8)))
(define node?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 9)
(eq? (vector-ref obj 0) '<node>)
#f)
#f)))
(define node-1
(lambda (obj)
(if (node? obj)
(void)
(error
'node-1
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 1)))
(define node-2
(lambda (obj)
(if (node? obj)
(void)
(error
'node-2
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 2)))
(define node-3
(lambda (obj)
(if (node? obj)
(void)
(error
'node-3
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 3)))
(define node-4
(lambda (obj)
(if (node? obj)
(void)
(error
'node-4
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 4)))
(define node-5
(lambda (obj)
(if (node? obj)
(void)
(error
'node-5
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 5)))
(define node-6
(lambda (obj)
(if (node? obj)
(void)
(error
'node-6
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 6)))
(define node-7
(lambda (obj)
(if (node? obj)
(void)
(error
'node-7
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 7)))
(define node-8
(lambda (obj)
(if (node? obj)
(void)
(error
'node-8
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 8)))
(define set-node-1!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-1!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 1 newval)))
(define set-node-2!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-2!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 2 newval)))
(define set-node-3!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-3!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 3 newval)))
(define set-node-4!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-4!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 4 newval)))
(define set-node-5!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-5!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 5 newval)))
(define set-node-6!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-6!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 6 newval)))
(define set-node-7!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-7!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 7 newval)))
(define set-node-8!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-8!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 8 newval))))
(define make-node
(lambda (center
low-left-front-vertex
up-right-back-vertex
children
particles
multipole-expansion
near-field
interactive-field)
((lambda ()
(make-raw-node
center
low-left-front-vertex
up-right-back-vertex
children
particles
multipole-expansion
near-field
interactive-field)))))
(define node-center node-1)
(define node-low-left-front-vertex node-2)
(define node-up-right-back-vertex node-3)
(define node-children node-4)
(define node-particles node-5)
(define node-multipole-expansion node-6)
(define node-near-field node-7)
(define node-interactive-field node-8)
(define set-node-center! set-node-1!)
(define set-node-low-left-front-vertex! set-node-2!)
(define set-node-up-right-back-vertex! set-node-3!)
(define set-node-children! set-node-4!)
(define set-node-particles! set-node-5!)
(define set-node-multipole-expansion! set-node-6!)
(define set-node-near-field! set-node-7!)
(define set-node-interactive-field! set-node-8!))
(define leaf-node?
(lambda (node) (null? (node-children node))))
(begin (begin (define make-raw-particle
(lambda (particle-1
particle-2
particle-3
particle-4
particle-5
particle-6)
(vector
'<particle>
particle-1
particle-2
particle-3
particle-4
particle-5
particle-6)))
(define particle?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 7)
(eq? (vector-ref obj 0) '<particle>)
#f)
#f)))
(define particle-1
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-1
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 1)))
(define particle-2
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-2
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 2)))
(define particle-3
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-3
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 3)))
(define particle-4
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-4
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 4)))
(define particle-5
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-5
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 5)))
(define particle-6
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-6
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 6)))
(define set-particle-1!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-1!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 1 newval)))
(define set-particle-2!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-2!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 2 newval)))
(define set-particle-3!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-3!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 3 newval)))
(define set-particle-4!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-4!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 4 newval)))
(define set-particle-5!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-5!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 5 newval)))
(define set-particle-6!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-6!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 6 newval))))
(define make-particle
(lambda (position
acceleration
d-acceleration
potential
d-potential
strength)
((lambda ()
(make-raw-particle
position
acceleration
d-acceleration
potential
d-potential
strength)))))
(define particle-position particle-1)
(define particle-acceleration particle-2)
(define particle-d-acceleration particle-3)
(define particle-potential particle-4)
(define particle-d-potential particle-5)
(define particle-strength particle-6)
(define set-particle-position! set-particle-1!)
(define set-particle-acceleration! set-particle-2!)
(define set-particle-d-acceleration! set-particle-3!)
(define set-particle-potential! set-particle-4!)
(define set-particle-d-potential! set-particle-5!)
(define set-particle-strength! set-particle-6!))
(begin (begin (define make-raw-pt
(lambda (pt-1 pt-2 pt-3)
(vector '<pt> pt-1 pt-2 pt-3)))
(define pt?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 4)
(eq? (vector-ref obj 0) '<pt>)
#f)
#f)))
(define pt-1
(lambda (obj)
(if (pt? obj)
(void)
(error 'pt-1 "~s is not a ~s" obj '<pt>))
(vector-ref obj 1)))
(define pt-2
(lambda (obj)
(if (pt? obj)
(void)
(error 'pt-2 "~s is not a ~s" obj '<pt>))
(vector-ref obj 2)))
(define pt-3
(lambda (obj)
(if (pt? obj)
(void)
(error 'pt-3 "~s is not a ~s" obj '<pt>))
(vector-ref obj 3)))
(define set-pt-1!
(lambda (obj newval)
(if (pt? obj)
(void)
(error
'set-pt-1!
"~s is not a ~s"
obj
'<pt>))
(vector-set! obj 1 newval)))
(define set-pt-2!
(lambda (obj newval)
(if (pt? obj)
(void)
(error
'set-pt-2!
"~s is not a ~s"
obj
'<pt>))
(vector-set! obj 2 newval)))
(define set-pt-3!
(lambda (obj newval)
(if (pt? obj)
(void)
(error
'set-pt-3!
"~s is not a ~s"
obj
'<pt>))
(vector-set! obj 3 newval))))
(define make-pt
(lambda (x y z) ((lambda () (make-raw-pt x y z)))))
(define pt-x pt-1)
(define pt-y pt-2)
(define pt-z pt-3)
(define set-pt-x! set-pt-1!)
(define set-pt-y! set-pt-2!)
(define set-pt-z! set-pt-3!)))
;(define-structure (tree
; body
; low-left-front-vertex
; up-right-back-vertex))
;
;(define-structure (node
; center
; low-left-front-vertex
; up-right-back-vertex
; children
; particles
; multipole-expansion
; near-field
; interactive-field))
;
;(define (leaf-node? node)
; (null? (node-children node)))
;
;(define-structure (particle
; position
; acceleration
; d-acceleration
; potential
; d-potential
; strength))
;
;(define-structure (pt x y z))
;
(define (pt-r pt)
(sqrt (+ (* (pt-x pt) (pt-x pt))
(* (pt-y pt) (pt-y pt))
(* (pt-z pt) (pt-z pt)))))
(define (pt-theta pt)
(let ((x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt)))
(atan0 (sqrt (+ (* x x) (* y y))) z)))
(define (pt-phi pt)
(let ((x (pt-x pt)) (y (pt-y pt)))
(atan0 y x)))
(define (pt+ pt1 pt2)
(make-pt (+ (pt-x pt1) (pt-x pt2))
(+ (pt-y pt1) (pt-y pt2))
(+ (pt-z pt1) (pt-z pt2))))
(define (sum-vectors vectors)
(make-pt (apply:+ (map pt-x vectors))
(apply:+ (map pt-y vectors))
(apply:+ (map pt-z vectors))))
(define (pt- pt1 pt2)
(make-pt (- (pt-x pt1) (pt-x pt2))
(- (pt-y pt1) (pt-y pt2))
(- (pt-z pt1) (pt-z pt2))))
(define (pt-average pt1 pt2)
(pt-scalar* .5 (pt+ pt1 pt2)))
(define (pt-scalar* scalar pt)
(make-pt (* scalar (pt-x pt))
(* scalar (pt-y pt))
(* scalar (pt-z pt))))
(define (within-box? pt pt1 pt2)
(and (<= (pt-x pt) (pt-x pt2)) (> (pt-x pt) (pt-x pt1))
(<= (pt-y pt) (pt-y pt2)) (> (pt-y pt) (pt-y pt1))
(<= (pt-z pt) (pt-z pt2)) (> (pt-z pt) (pt-z pt1))))
;;; ==========================================================
;;; Useful Things
;;; ==========================================================
(define (nfilter list predicate)
(let loop ((list list))
(cond ((null? list) '())
((predicate (car list)) (cons (car list) (loop (cdr list))))
(else (loop (cdr list))))))
;;; array in the shape of a pyramid with each
;;; element a function of the indices
(define (make-cartesian-expansion func)
(let ((expansion (make-vector precision 0)))
(let loop1 ((i 0))
(if (= i precision)
expansion
(let ((foo (make-vector (- precision i) 0)))
(vector-set! expansion i foo)
(let loop2 ((j 0))
(if (= j (- precision i))
(loop1 (+ 1 i))
(let ((bar (make-vector (- precision i j) 0)))
(vector-set! foo j bar)
(let loop3 ((k 0))
(if (= k (- precision i j))
(loop2 (+ 1 j))
(begin (vector-set! bar k (func i j k))
(loop3 (+ 1 k)))))))))))))
;;; array in the shape of a triangle with each
;;; element a function of the indices
(define (make-spherical-expansion func)
(let ((expansion (make-vector precision 0)))
(let loop1 ((l 0))
(if (= l precision)
expansion
(let ((foo (make-vector (+ 1 l) 0)))
(vector-set! expansion l foo)
(let loop2 ((m 0))
(if (= m (+ 1 l))
(loop1 (+ 1 l))
(begin (vector-set! foo m (func l m))
(loop2 (+ 1 m))))))))))
(define (spherical-ref expansion l m)
(let ((conj (lambda (z) (make-rectangular (real-part z) (- (imag-part z))))))
(if (negative? m)
(conj (array-ref expansion l (- m)))
(array-ref expansion l m))))
(define (cartesian-expansion-sum expansions)
(make-cartesian-expansion
(lambda (i j k)
(apply:+ (map (lambda (expansion)
(array-ref expansion i j k))
expansions)))))
(define (spherical-expansion-sum expansions)
(make-spherical-expansion
(lambda (l m)
(apply:+ (map (lambda (expansion)
(spherical-ref expansion l m))
expansions)))))
(define (cartesian-zero-expansion)
(make-cartesian-expansion (lambda (i j k) 0)))
(define (spherical-zero-expansion)
(make-spherical-expansion (lambda (l m) 0)))
(define (sum-3d end1 end2 end3 func)
(let loop1 ((l 0) (sum 0))
(if (> l end1)
sum
(loop1
(+ 1 l)
(+ sum
(let loop2 ((m 0) (sum 0))
(if (> m end2)
sum
(loop2
(+ 1 m)
(+ sum
(let loop3 ((n 0) (sum 0))
(if (> n end3)
sum
(loop3 (+ 1 n)
(+ sum (func l m n))))))))))))))
(define (sum2-3d end func)
(let loop1 ((l 0) (sum 0))
(if (= l end)
sum
(loop1
(+ 1 l)
(+ sum
(let loop2 ((m 0) (sum 0))
(if (= (+ l m) end)
sum
(loop2
(+ 1 m)
(+ sum
(let loop3 ((n 0) (sum 0))
(if (= (+ l m n) end)
sum
(loop3 (+ 1 n)
(+ sum (func l m n))))))))))))))
(define (sum-2d end func)
(let loop1 ((l 0) (sum 0))
(if (> l end)
sum
(loop1 (+ 1 l)
(+ sum (let loop2 ((m (- l)) (sum 0))
(if (> m l)
sum
(loop2 (+ 1 m)
(+ sum (func l m))))))))))
(define (sum2-2d init func)
(let loop1 ((l init) (sum 0))
(if (= l precision)
sum
(loop1 (+ 1 l)
(+ sum (let loop2 ((m (- l)) (sum 0))
(if (> m l)
sum
(loop2 (+ 1 m)
(+ sum (func l m))))))))))
;;; Storing factorials in a table
(define fac
(let ((table (make-vector (* 4 precision) 0)))
(vector-set! table 0 1)
(let loop ((n 1))
(if (= n (* 4 precision))
(lambda (x) (vector-ref table x))
(begin (vector-set! table
n
(* n (vector-ref table (- n 1))))
(loop (+ 1 n)))))))
The table for ( * ( -0.5 ) ( -1.5 ) ( -2.5 ) ... ( + -0.5 -i 1 ) )
(define fac-1
(let ((table (make-vector precision 0)))
(vector-set! table 0 1)
(let loop ((n 1))
(if (= n precision)
(lambda (x) (vector-ref table x))
(begin (vector-set! table
n
(* (- .5 n)
(vector-ref table (- n 1))))
(loop (+ 1 n)))))))
(define fac-2
(let ((table (make-vector (* 4 precision) 0)))
(vector-set! table 0 1)
(let loop ((n 1))
(if (= n (* 4 precision))
(lambda (n) (if (< n 0)
1
(vector-ref table n)))
(begin (vector-set! table n (* (if (even? n) 1 n)
(vector-ref table (- n 1))))
(loop (+ 1 n)))))))
;;; Storing the products of factorials in a table.
(define prod-fac
(let ((table (make-cartesian-expansion
(lambda (i j k) (* (fac i) (fac j) (fac k))))))
(lambda (i j k) (array-ref table i j k))))
(define 1/prod-fac
(let ((table (make-cartesian-expansion
(lambda (i j k) (/ (prod-fac i j k))))))
(lambda (i j k) (array-ref table i j k))))
(define (assoc-legendre l m x)
(cond ((= l m) (* (expt -1 m)
(fac-2 (- (* 2 m) 1))
(expt (- 1 (* x x)) (/ m 2))))
((= l (+ 1 m)) (* x (+ 1 (* 2 m)) (assoc-legendre m m x)))
(else (/ (- (* x (- (* 2 l) 1) (assoc-legendre (- l 1) m x))
(* (+ l m -1) (assoc-legendre (- l 2) m x)))
(- l m)))))
(define (eval-spherical-harmonic l m theta phi)
(let ((mm (abs m)))
(* (sqrt (/ (fac (- l mm)) (fac (+ l mm))))
(assoc-legendre l mm (cos theta))
(make-polar 1 (* m phi)))))
(define (eval-spher-harm-phi-deriv l m theta phi)
(* (eval-spherical-harmonic l m theta phi)
m
(make-rectangular 0 1)))
(define (eval-spher-harm-theta-deriv l m theta phi)
(let ((mm (abs m)))
(* (sqrt (/ (fac (- l mm)) (fac (+ l mm))))
(make-polar 1 (* m phi))
(- (sin theta))
(assoc-legendre-deriv l mm (cos theta)))))
(define (assoc-legendre-deriv l m x)
(cond ((= l m) (* (expt -1 (+ 1 m))
(fac-2 (- (* 2 m) 1))
m
(expt (- 1 (* x x)) (- (/ m 2) 1))
x))
((= l (+ 1 m)) (* (+ 1 (* 2 m))
(+ (assoc-legendre m m x)
(* x (assoc-legendre-deriv m m x)))))
(else (/ (- (* (- (* 2 l) 1)
(+ (assoc-legendre (- l 1) m x)
(* x (assoc-legendre-deriv (- l 1) m x))))
(* (+ l m -1) (assoc-legendre-deriv (- l 2) m x)))
(- l m)))))
;;; ================================================================
;;; TREE CODE
;;; ================================================================
(define (build-tree height near-size)
(let* ((vertex1 (make-pt -10 -10 -10))
(vertex2 (make-pt 10 10 10))
(tree (make-tree '() vertex1 vertex2)))
(let loop ((level 0) (pt1 vertex1) (pt2 vertex2))
(let* ((half-diagonal (pt-scalar* .5 (pt- pt2 pt1)))
(diag-length/2 (pt-x half-diagonal)))
(insert-node tree level pt1 pt2)
(if (< level height)
(let ((child-pt1s
(map (lambda (offset)
(pt+ pt1 (pt-scalar* diag-length/2 offset)))
(list (make-pt 0 0 0)
(make-pt 0 0 1)
(make-pt 0 1 0)
(make-pt 1 0 0)
(make-pt 0 1 1)
(make-pt 1 0 1)
(make-pt 1 1 0)
(make-pt 1 1 1)))))
(for-each (lambda (child-pt1)
(loop (+ 1 level)
child-pt1
(pt+ child-pt1 half-diagonal)))
child-pt1s)))))
(calc-near-and-interaction tree near-size)
tree))
(define (insert-node tree level pt1 pt2)
(let* ((center (pt-average pt1 pt2))
(new-node (make-node center pt1 pt2 '() '() '() '() '())))
(letrec ((insert-internal (lambda (node depth)
(if (= level depth)
(set-node-children! node
(cons new-node
(node-children node)))
(insert-internal (find-child node center)
(+ 1 depth))))))
(if (= level 0)
(set-tree-body! tree new-node)
(insert-internal (tree-body tree) 1)))))
(define (find-child node pos)
(let loop ((children (node-children node)))
(let ((child (car children)))
(if (within-box? pos
(node-low-left-front-vertex child)
(node-up-right-back-vertex child))
child
(loop (cdr children))))))
(define (insert-particle tree particle)
(let* ((pos (particle-position particle)))
(letrec ((insert-internal (lambda (node)
(if (leaf-node? node)
(set-node-particles!
node
(cons particle (node-particles node)))
(insert-internal (find-child node pos))))))
(if (within-box? pos
(tree-low-left-front-vertex tree)
(tree-up-right-back-vertex tree))
(insert-internal (tree-body tree))
(error 'insert-particle "particle not within boundaries of tree" particle)))))
;;; This function finds the near and
;;; interaction fields for every node in the tree.
(define (calc-near-and-interaction tree near-size)
(set-node-near-field! (tree-body tree) (list (tree-body tree)))
(let loop ((node (tree-body tree)) (parent #f))
(if parent
(let* ((center (node-center node))
(dist (* near-size
(abs (- (pt-x center)
(pt-x (node-center parent)))))))
(for-each
(lambda (parent-near)
(let ((interactives (list '())))
(for-each
(lambda (child)
(if (> (pt-r (pt- center (node-center child))) dist)
(set-car! interactives (cons child (car interactives)))
(set-node-near-field!
node
(cons child (node-near-field node)))))
(node-children parent-near))
(set-node-interactive-field!
node
(append (car interactives) (node-interactive-field node)))))
(node-near-field parent))))
(for-each (lambda (child) (loop child node)) (node-children node))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; GO
(define (initial-particle x y z m)
(make-particle (make-pt x y z)
(make-pt 0 0 0)
(make-pt 0 0 0)
0 0 m))
(define (random-float bot top)
(+ (* (- top bot)
(/ (* (random 1000000) 1.0) 1000000.0))
bot))
(define (random-particle)
(make-particle (make-pt (random-float -10.0 10.0)
(random-float -10.0 10.0)
(random-float -10.0 10.0))
(make-pt 0 0 0)
(make-pt 0 0 0)
0 0 1.0))
(define *particles* (list '()))
(define (go depth precision n-particles)
(let ((tree (build-tree depth 27))
(particles (let next ((i 0) (ps '()))
(if (<= i n-particles)
(next (+ i 1) (cons (random-particle) ps))
ps))))
(for-each (lambda (p) (insert-particle tree p)) particles)
(cartesian-algorithm tree)
(set-car! *particles* particles)))
;;; virtual time for cartesian-algorithm step
( go 1 3 10 ) 0.31 seconds
( go 3 5 128 ) 1397.31
( go 3 5 256 ) 1625.29
( go 3 5 512 ) 2380.35
( go 2 5 128 ) 27.44 seconds
(define (main . args)
(run-benchmark
"nbody"
nbody-iters
(lambda () #t)
(lambda (i j k) (go i j k))
2 5 128))
| null | https://raw.githubusercontent.com/ih/ikarus.dev/8bb0c8e4d1122cf0f9aeb675cb51bc7df178959b/benchmarks.larceny/src/nbody.scm | scheme | and added nbody-benchmark.
981116 / wdc Replaced nbody-benchmark by main, added apply:+.
code is slightly broken...
minimal standard random number generator
return a random number in the interval [0,n)
change this to desired precision
measured in order of expansions calculated
=========================================================
Algorithm
=========================================================
The upward path in the algorithm calculates
multipole expansions at every node.
Downward path of the algorithm which calculates local expansionss
at every node and accelerations and potentials at each particle.
================================================================
Expansion Theorems
================================================================
==================================================================
Shifting lemmas
==================================================================
Shift multipole expansion
Convert multipole to local
Shift local expansion
Evaluate the resulting local expansion at point pt.
Direct calculation of acceleration and potential
=================================================================
TREES NODES PARTICLES and POINTS
=================================================================
(define-structure (tree
body
low-left-front-vertex
up-right-back-vertex))
(define-structure (node
center
low-left-front-vertex
up-right-back-vertex
children
particles
multipole-expansion
near-field
interactive-field))
(define (leaf-node? node)
(null? (node-children node)))
(define-structure (particle
position
acceleration
d-acceleration
potential
d-potential
strength))
(define-structure (pt x y z))
==========================================================
Useful Things
==========================================================
array in the shape of a pyramid with each
element a function of the indices
array in the shape of a triangle with each
element a function of the indices
Storing factorials in a table
Storing the products of factorials in a table.
================================================================
TREE CODE
================================================================
This function finds the near and
interaction fields for every node in the tree.
GO
virtual time for cartesian-algorithm step | This benchmark was obtained from .
970215 / wdc Changed { box , unbox , set - box ! } to { list , car , set - car ! } ,
flushed # % prefixes , defined void ,
(define void
(let ((invisible (string->symbol "")))
(lambda () invisible)))
(define (apply:+ xs)
(do ((result 0.0 (FLOAT+ result (car xs)))
(xs xs (cdr xs)))
((null? xs) result)))
(define vect (vector))
32 bit integer version
cacm 31 10 , oct 88
(define *seed* (list 1))
(define (srand seed)
(set-car! *seed* seed))
(define (rand)
(let* ((hi (quotient (car *seed*) 127773))
(lo (modulo (car *seed*) 127773))
(test (- (* 16807 lo) (* 2836 hi))))
(if (> test 0)
(set-car! *seed* test)
(set-car! *seed* (+ test 2147483647)))
(car *seed*)))
(define random
(lambda (n)
(modulo (abs (rand)) n)))
(define (array-ref a . indices)
(let loop ((a a) (indices indices))
(if (null? indices)
a
(loop (vector-ref a (car indices)) (cdr indices)))))
(define (atan0 y x)
(if (and (= x y) (= x 0)) 0 (atan y x)))
(define precision 10)
(define (cartesian-algorithm tree)
(up! tree
cartesian-make-multipole-expansion
cartesian-multipole-shift
cartesian-expansion-sum)
(down! tree
cartesian-multipole-to-local-convert
cartesian-local-shift
cartesian-eval-local-expansion
cartesian-expansion-sum
cartesian-zero-expansion))
(define (spherical-algorithm tree)
(up! tree
spherical-make-multipole-expansion
spherical-multipole-shift
spherical-expansion-sum)
(down! tree
spherical-multipole-to-local-convert
spherical-local-shift
spherical-eval-local-expansion
spherical-expansion-sum
spherical-zero-expansion))
(define (up! tree
make-multipole-expansion
multipole-shift
expansion-sum)
(let loop ((node (tree-body tree)))
(define center (node-center node))
(if (leaf-node? node)
(let ((multipole-expansion
(expansion-sum
(map (lambda (particle)
(make-multipole-expansion
(pt- (particle-position particle) center)
(particle-strength particle)))
(node-particles node)))))
(set-node-multipole-expansion! node multipole-expansion)
(cons center multipole-expansion))
(let ((multipole-expansion
(expansion-sum
(map (lambda (child)
(define center-and-expansion (loop child))
(multipole-shift (pt- (car center-and-expansion)
center)
(cdr center-and-expansion)))
(node-children node)))))
(set-node-multipole-expansion! node multipole-expansion)
(cons center multipole-expansion)))))
(define (down! tree
multipole-to-local-convert
local-shift
eval-local-expansion
expansion-sum
zero-expansion)
(let loop ((node (tree-body tree))
(parent-local-expansion (zero-expansion))
(parent-center (node-center (tree-body tree))))
(let* ((center (node-center node))
(interactive-sum
(expansion-sum
(map (lambda (interactive)
(multipole-to-local-convert
(pt- (node-center interactive) center)
(node-multipole-expansion interactive)))
(node-interactive-field node))))
(local-expansion
(expansion-sum (list (local-shift (pt- center parent-center)
parent-local-expansion)
interactive-sum))))
(if (leaf-node? node)
(eval-potentials-and-accelerations
node
local-expansion
eval-local-expansion)
(for-each (lambda (child) (loop child local-expansion center))
(node-children node))))))
(define (eval-potentials-and-accelerations
node
local-expansion
eval-local-expansion)
(let ((center (node-center node))
(near-field (apply append (map node-particles
(node-near-field node)))))
(for-each (lambda (particle)
(let* ((pos (particle-position particle))
(far-field-accel-and-poten
(eval-local-expansion (pt- pos center)
local-expansion)))
(set-particle-acceleration!
particle
(pt+ (car far-field-accel-and-poten)
(sum-vectors
(map (lambda (near)
(direct-accel (pt- (particle-position near)
pos)
(particle-strength near)))
(nfilter near-field
(lambda (near)
(not (eq? near particle))))))))
(set-particle-potential!
particle
(+ (cdr far-field-accel-and-poten)
(apply:+ (map (lambda (near)
(direct-poten
(pt- (particle-position near) pos)
(particle-strength near)))
(nfilter near-field
(lambda (near)
(not
(eq? near particle))))))))))
(node-particles node))))
(define (cartesian-make-multipole-expansion pt strength)
(let ((-x (- (pt-x pt)))
(-y (- (pt-y pt)))
(-z (- (pt-z pt))))
(make-cartesian-expansion
(lambda (i j k) (* strength
(expt -x i)
(expt -y j)
(expt -z k)
(1/prod-fac i j k))))))
(define (spherical-make-multipole-expansion pt strength)
(let ((r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt)))
(make-spherical-expansion
(lambda (l m)
(* strength
(expt r l)
(eval-spherical-harmonic l (- m) theta phi))))))
(define (cartesian-multipole-shift pt multipole-expansion)
(let ((pt-expansion (cartesian-make-multipole-expansion pt 1)))
(make-cartesian-expansion
(lambda (i j k)
(sum-3d i j k
(lambda (l m n)
(* (array-ref multipole-expansion l m n)
(array-ref pt-expansion (- i l) (- j m) (- k n)))))))))
(define (spherical-multipole-shift pt multipole-expansion)
(let ((r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt)))
(letrec ((foo (lambda (a b)
(if (< (* a b) 0)
(expt -1 (min (abs a) (abs b)))
1)))
(bar (lambda (a b)
(/ (expt -1 a)
(sqrt (* (fac (- a b)) (fac (+ a b))))))))
(let ((pt-expansion (make-spherical-expansion
(lambda (l m)
(* (eval-spherical-harmonic l m theta phi)
(bar l m)
(expt r l))))))
(make-spherical-expansion
(lambda (j k)
(sum-2d j
(lambda (l m)
(if (> (abs (- k m)) (- j l))
0
(* (spherical-ref multipole-expansion (- j l) (- k m))
(foo m (- k m))
(bar (- j l) (- k m))
(spherical-ref pt-expansion l (- m))
(/ (bar j k))))))))))))
(define (cartesian-multipole-to-local-convert pt multipole-expansion)
(define pt-expansion
(let* ((1/radius (/ (pt-r vect)))
(2cosines (pt-scalar* (* 2 1/radius) vect))
(x (pt-x 2cosines))
(y (pt-y 2cosines))
(z (pt-z 2cosines)))
(make-cartesian-expansion
(lambda (i j k)
(define ijk (+ i j k))
(* (expt -1 ijk)
(expt 1/radius (+ 1 ijk))
(prod-fac i j k)
(sum-3d (/ i 2) (/ j 2) (/ k 2)
(lambda (l m n)
(* (fac-1 (- ijk l m n))
(1/prod-fac l m n)
(1/prod-fac (- i (* 2 l))
(- j (* 2 m))
(- k (* 2 n)))
(expt x (- i (* 2 l)))
(expt y (- j (* 2 m)))
(expt z (- k (* 2 n)))))))))))
(make-cartesian-expansion
(lambda (i j k)
(sum2-3d (- precision i j k)
(lambda (l m n)
(* (array-ref multipole-expansion l m n)
(array-ref pt-expansion (+ i l) (+ j m) (+ k n))))))))
(define (spherical-multipole-to-local-convert pt multipole-expansion)
(let* ((r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt))
(foo (lambda (a b c)
(* (expt -1 b)
(if (> (* a c) 0)
(expt -1 (min (abs a) (abs c)))
1))))
(bar (lambda (a b)
(/ (expt -1 a)
(sqrt (* (fac (- a b)) (fac (+ a b)))))))
(pt-expansion (make-spherical-expansion
(lambda (l m)
(/ (eval-spherical-harmonic l m theta phi)
(bar l m)
(expt r (+ 1 l)))))))
(make-spherical-expansion
(lambda (j k)
(* (bar j k)
(sum-2d (- precision j 1)
(lambda (l m)
(* (spherical-ref multipole-expansion l m)
(foo k l m)
(bar l m)
(spherical-ref pt-expansion (+ j l) (- m k))))))))))
(define (cartesian-local-shift pt local-expansion)
(let* ((x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt))
(expts (make-cartesian-expansion
(lambda (l m n) (* (expt x l)
(expt y m)
(expt z n))))))
(make-cartesian-expansion
(lambda (i j k)
(sum2-3d (- precision i j k)
(lambda (l m n)
(* (array-ref local-expansion (+ i l) (+ j m) (+ k n))
(array-ref expts l m n)
(1/prod-fac l m n))))))))
(define (spherical-local-shift pt local-expansion)
(let* ((pt (pt- (make-pt 0 0 0) pt))
(r (pt-r pt))
(theta (pt-theta pt))
(phi (pt-phi pt))
(foo (lambda (a b c)
(* (expt -1 a)
(expt -1 (/ (+ (abs (- b c))
(abs b)
(- (abs c)))
2)))))
(bar (lambda (a b)
(/ (expt -1 a)
(sqrt (* (fac (- a b))
(fac (+ a b)))))))
(stuff (make-spherical-expansion
(lambda (l m)
(* (eval-spherical-harmonic l m theta phi)
(expt r l))))))
(make-spherical-expansion
(lambda (j k)
(sum2-2d j (lambda (l m)
(if (> (abs (- m k)) (- l j))
0
(* (spherical-ref local-expansion l m)
(bar (- l j) (- m k))
(bar j k)
(spherical-ref stuff (- l j) (- m k))
(/ (foo (- l j) (- m k) m) (bar l m))))))))))
(define (cartesian-eval-local-expansion pt local-expansion)
(let* ((x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt))
(local-expansion
(make-cartesian-expansion
(lambda (i j k)
(* (array-ref local-expansion i j k)
(1/prod-fac i j k)))))
(expts (make-cartesian-expansion
(lambda (i j k)
(* (expt x i) (expt y j) (expt z k))))))
(cons (make-pt
(sum2-3d (- precision 1)
(lambda (l m n)
(* (array-ref expts l m n)
(+ 1 l)
(array-ref local-expansion (+ 1 l) m n))))
(sum2-3d (- precision 1)
(lambda (l m n)
(* (array-ref expts l m n)
(+ 1 m)
(array-ref local-expansion l (+ 1 m) n))))
(sum2-3d (- precision 1)
(lambda (l m n)
(* (array-ref expts l m n)
(+ 1 n)
(array-ref local-expansion l m (+ 1 n))))))
(sum2-3d precision
(lambda (l m n)
(* (array-ref expts l m n)
(array-ref local-expansion l m n)))))))
(define (spherical-eval-local-expansion pt local-expansion)
(let* ((r (pt-r pt))
(x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt))
(rho-sq (+ (* x x) (* y y)))
(theta (pt-theta pt))
(phi (pt-phi pt))
(r-deriv
(real-part
(sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(expt r (- l 1))
l
(eval-spherical-harmonic l m theta phi))))))
(theta-deriv
(real-part
(sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(expt r l)
(eval-spher-harm-theta-deriv l m theta phi))))))
(phi-deriv
(real-part
(sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(expt r l)
(eval-spher-harm-phi-deriv l m theta phi)))))))
(cons (make-pt
(+ (* r-deriv (/ x r))
(* theta-deriv (/ x (sqrt rho-sq) (+ z (/ rho-sq z))))
(* phi-deriv -1 (/ y rho-sq)))
(+ (* r-deriv (/ y r))
(* theta-deriv (/ y (sqrt rho-sq) (+ z (/ rho-sq z))))
(/ phi-deriv x (+ 1 (/ (* y y) x x))))
(+ (* r-deriv (/ z r))
(* theta-deriv (/ -1 r r) (sqrt rho-sq))))
(real-part (sum-2d (- precision 1)
(lambda (l m)
(* (spherical-ref local-expansion l m)
(eval-spherical-harmonic l m theta phi)
(expt r l))))))))
(define (direct-accel pt strength)
(pt-scalar* (/ strength (expt (pt-r pt) 3))
pt))
(define (direct-poten pt strength)
(/ strength (pt-r pt)))
(begin (begin (begin (define make-raw-tree
(lambda (tree-1 tree-2 tree-3)
(vector '<tree> tree-1 tree-2 tree-3)))
(define tree?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 4)
(eq? (vector-ref obj 0) '<tree>)
#f)
#f)))
(define tree-1
(lambda (obj)
(if (tree? obj)
(void)
(error
'tree-1
"~s is not a ~s"
obj
'<tree>))
(vector-ref obj 1)))
(define tree-2
(lambda (obj)
(if (tree? obj)
(void)
(error
'tree-2
"~s is not a ~s"
obj
'<tree>))
(vector-ref obj 2)))
(define tree-3
(lambda (obj)
(if (tree? obj)
(void)
(error
'tree-3
"~s is not a ~s"
obj
'<tree>))
(vector-ref obj 3)))
(define set-tree-1!
(lambda (obj newval)
(if (tree? obj)
(void)
(error
'set-tree-1!
"~s is not a ~s"
obj
'<tree>))
(vector-set! obj 1 newval)))
(define set-tree-2!
(lambda (obj newval)
(if (tree? obj)
(void)
(error
'set-tree-2!
"~s is not a ~s"
obj
'<tree>))
(vector-set! obj 2 newval)))
(define set-tree-3!
(lambda (obj newval)
(if (tree? obj)
(void)
(error
'set-tree-3!
"~s is not a ~s"
obj
'<tree>))
(vector-set! obj 3 newval))))
(define make-tree
(lambda (body low-left-front-vertex up-right-back-vertex)
((lambda ()
(make-raw-tree
body
low-left-front-vertex
up-right-back-vertex)))))
(define tree-body tree-1)
(define tree-low-left-front-vertex tree-2)
(define tree-up-right-back-vertex tree-3)
(define set-tree-body! set-tree-1!)
(define set-tree-low-left-front-vertex! set-tree-2!)
(define set-tree-up-right-back-vertex! set-tree-3!))
(begin (begin (define make-raw-node
(lambda (node-1
node-2
node-3
node-4
node-5
node-6
node-7
node-8)
(vector
'<node>
node-1
node-2
node-3
node-4
node-5
node-6
node-7
node-8)))
(define node?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 9)
(eq? (vector-ref obj 0) '<node>)
#f)
#f)))
(define node-1
(lambda (obj)
(if (node? obj)
(void)
(error
'node-1
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 1)))
(define node-2
(lambda (obj)
(if (node? obj)
(void)
(error
'node-2
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 2)))
(define node-3
(lambda (obj)
(if (node? obj)
(void)
(error
'node-3
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 3)))
(define node-4
(lambda (obj)
(if (node? obj)
(void)
(error
'node-4
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 4)))
(define node-5
(lambda (obj)
(if (node? obj)
(void)
(error
'node-5
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 5)))
(define node-6
(lambda (obj)
(if (node? obj)
(void)
(error
'node-6
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 6)))
(define node-7
(lambda (obj)
(if (node? obj)
(void)
(error
'node-7
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 7)))
(define node-8
(lambda (obj)
(if (node? obj)
(void)
(error
'node-8
"~s is not a ~s"
obj
'<node>))
(vector-ref obj 8)))
(define set-node-1!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-1!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 1 newval)))
(define set-node-2!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-2!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 2 newval)))
(define set-node-3!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-3!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 3 newval)))
(define set-node-4!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-4!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 4 newval)))
(define set-node-5!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-5!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 5 newval)))
(define set-node-6!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-6!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 6 newval)))
(define set-node-7!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-7!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 7 newval)))
(define set-node-8!
(lambda (obj newval)
(if (node? obj)
(void)
(error
'set-node-8!
"~s is not a ~s"
obj
'<node>))
(vector-set! obj 8 newval))))
(define make-node
(lambda (center
low-left-front-vertex
up-right-back-vertex
children
particles
multipole-expansion
near-field
interactive-field)
((lambda ()
(make-raw-node
center
low-left-front-vertex
up-right-back-vertex
children
particles
multipole-expansion
near-field
interactive-field)))))
(define node-center node-1)
(define node-low-left-front-vertex node-2)
(define node-up-right-back-vertex node-3)
(define node-children node-4)
(define node-particles node-5)
(define node-multipole-expansion node-6)
(define node-near-field node-7)
(define node-interactive-field node-8)
(define set-node-center! set-node-1!)
(define set-node-low-left-front-vertex! set-node-2!)
(define set-node-up-right-back-vertex! set-node-3!)
(define set-node-children! set-node-4!)
(define set-node-particles! set-node-5!)
(define set-node-multipole-expansion! set-node-6!)
(define set-node-near-field! set-node-7!)
(define set-node-interactive-field! set-node-8!))
(define leaf-node?
(lambda (node) (null? (node-children node))))
(begin (begin (define make-raw-particle
(lambda (particle-1
particle-2
particle-3
particle-4
particle-5
particle-6)
(vector
'<particle>
particle-1
particle-2
particle-3
particle-4
particle-5
particle-6)))
(define particle?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 7)
(eq? (vector-ref obj 0) '<particle>)
#f)
#f)))
(define particle-1
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-1
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 1)))
(define particle-2
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-2
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 2)))
(define particle-3
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-3
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 3)))
(define particle-4
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-4
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 4)))
(define particle-5
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-5
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 5)))
(define particle-6
(lambda (obj)
(if (particle? obj)
(void)
(error
'particle-6
"~s is not a ~s"
obj
'<particle>))
(vector-ref obj 6)))
(define set-particle-1!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-1!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 1 newval)))
(define set-particle-2!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-2!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 2 newval)))
(define set-particle-3!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-3!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 3 newval)))
(define set-particle-4!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-4!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 4 newval)))
(define set-particle-5!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-5!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 5 newval)))
(define set-particle-6!
(lambda (obj newval)
(if (particle? obj)
(void)
(error
'set-particle-6!
"~s is not a ~s"
obj
'<particle>))
(vector-set! obj 6 newval))))
(define make-particle
(lambda (position
acceleration
d-acceleration
potential
d-potential
strength)
((lambda ()
(make-raw-particle
position
acceleration
d-acceleration
potential
d-potential
strength)))))
(define particle-position particle-1)
(define particle-acceleration particle-2)
(define particle-d-acceleration particle-3)
(define particle-potential particle-4)
(define particle-d-potential particle-5)
(define particle-strength particle-6)
(define set-particle-position! set-particle-1!)
(define set-particle-acceleration! set-particle-2!)
(define set-particle-d-acceleration! set-particle-3!)
(define set-particle-potential! set-particle-4!)
(define set-particle-d-potential! set-particle-5!)
(define set-particle-strength! set-particle-6!))
(begin (begin (define make-raw-pt
(lambda (pt-1 pt-2 pt-3)
(vector '<pt> pt-1 pt-2 pt-3)))
(define pt?
(lambda (obj)
(if (vector? obj)
(if (= (vector-length obj) 4)
(eq? (vector-ref obj 0) '<pt>)
#f)
#f)))
(define pt-1
(lambda (obj)
(if (pt? obj)
(void)
(error 'pt-1 "~s is not a ~s" obj '<pt>))
(vector-ref obj 1)))
(define pt-2
(lambda (obj)
(if (pt? obj)
(void)
(error 'pt-2 "~s is not a ~s" obj '<pt>))
(vector-ref obj 2)))
(define pt-3
(lambda (obj)
(if (pt? obj)
(void)
(error 'pt-3 "~s is not a ~s" obj '<pt>))
(vector-ref obj 3)))
(define set-pt-1!
(lambda (obj newval)
(if (pt? obj)
(void)
(error
'set-pt-1!
"~s is not a ~s"
obj
'<pt>))
(vector-set! obj 1 newval)))
(define set-pt-2!
(lambda (obj newval)
(if (pt? obj)
(void)
(error
'set-pt-2!
"~s is not a ~s"
obj
'<pt>))
(vector-set! obj 2 newval)))
(define set-pt-3!
(lambda (obj newval)
(if (pt? obj)
(void)
(error
'set-pt-3!
"~s is not a ~s"
obj
'<pt>))
(vector-set! obj 3 newval))))
(define make-pt
(lambda (x y z) ((lambda () (make-raw-pt x y z)))))
(define pt-x pt-1)
(define pt-y pt-2)
(define pt-z pt-3)
(define set-pt-x! set-pt-1!)
(define set-pt-y! set-pt-2!)
(define set-pt-z! set-pt-3!)))
(define (pt-r pt)
(sqrt (+ (* (pt-x pt) (pt-x pt))
(* (pt-y pt) (pt-y pt))
(* (pt-z pt) (pt-z pt)))))
(define (pt-theta pt)
(let ((x (pt-x pt))
(y (pt-y pt))
(z (pt-z pt)))
(atan0 (sqrt (+ (* x x) (* y y))) z)))
(define (pt-phi pt)
(let ((x (pt-x pt)) (y (pt-y pt)))
(atan0 y x)))
(define (pt+ pt1 pt2)
(make-pt (+ (pt-x pt1) (pt-x pt2))
(+ (pt-y pt1) (pt-y pt2))
(+ (pt-z pt1) (pt-z pt2))))
(define (sum-vectors vectors)
(make-pt (apply:+ (map pt-x vectors))
(apply:+ (map pt-y vectors))
(apply:+ (map pt-z vectors))))
(define (pt- pt1 pt2)
(make-pt (- (pt-x pt1) (pt-x pt2))
(- (pt-y pt1) (pt-y pt2))
(- (pt-z pt1) (pt-z pt2))))
(define (pt-average pt1 pt2)
(pt-scalar* .5 (pt+ pt1 pt2)))
(define (pt-scalar* scalar pt)
(make-pt (* scalar (pt-x pt))
(* scalar (pt-y pt))
(* scalar (pt-z pt))))
(define (within-box? pt pt1 pt2)
(and (<= (pt-x pt) (pt-x pt2)) (> (pt-x pt) (pt-x pt1))
(<= (pt-y pt) (pt-y pt2)) (> (pt-y pt) (pt-y pt1))
(<= (pt-z pt) (pt-z pt2)) (> (pt-z pt) (pt-z pt1))))
(define (nfilter list predicate)
(let loop ((list list))
(cond ((null? list) '())
((predicate (car list)) (cons (car list) (loop (cdr list))))
(else (loop (cdr list))))))
(define (make-cartesian-expansion func)
(let ((expansion (make-vector precision 0)))
(let loop1 ((i 0))
(if (= i precision)
expansion
(let ((foo (make-vector (- precision i) 0)))
(vector-set! expansion i foo)
(let loop2 ((j 0))
(if (= j (- precision i))
(loop1 (+ 1 i))
(let ((bar (make-vector (- precision i j) 0)))
(vector-set! foo j bar)
(let loop3 ((k 0))
(if (= k (- precision i j))
(loop2 (+ 1 j))
(begin (vector-set! bar k (func i j k))
(loop3 (+ 1 k)))))))))))))
(define (make-spherical-expansion func)
(let ((expansion (make-vector precision 0)))
(let loop1 ((l 0))
(if (= l precision)
expansion
(let ((foo (make-vector (+ 1 l) 0)))
(vector-set! expansion l foo)
(let loop2 ((m 0))
(if (= m (+ 1 l))
(loop1 (+ 1 l))
(begin (vector-set! foo m (func l m))
(loop2 (+ 1 m))))))))))
(define (spherical-ref expansion l m)
(let ((conj (lambda (z) (make-rectangular (real-part z) (- (imag-part z))))))
(if (negative? m)
(conj (array-ref expansion l (- m)))
(array-ref expansion l m))))
(define (cartesian-expansion-sum expansions)
(make-cartesian-expansion
(lambda (i j k)
(apply:+ (map (lambda (expansion)
(array-ref expansion i j k))
expansions)))))
(define (spherical-expansion-sum expansions)
(make-spherical-expansion
(lambda (l m)
(apply:+ (map (lambda (expansion)
(spherical-ref expansion l m))
expansions)))))
(define (cartesian-zero-expansion)
(make-cartesian-expansion (lambda (i j k) 0)))
(define (spherical-zero-expansion)
(make-spherical-expansion (lambda (l m) 0)))
(define (sum-3d end1 end2 end3 func)
(let loop1 ((l 0) (sum 0))
(if (> l end1)
sum
(loop1
(+ 1 l)
(+ sum
(let loop2 ((m 0) (sum 0))
(if (> m end2)
sum
(loop2
(+ 1 m)
(+ sum
(let loop3 ((n 0) (sum 0))
(if (> n end3)
sum
(loop3 (+ 1 n)
(+ sum (func l m n))))))))))))))
(define (sum2-3d end func)
(let loop1 ((l 0) (sum 0))
(if (= l end)
sum
(loop1
(+ 1 l)
(+ sum
(let loop2 ((m 0) (sum 0))
(if (= (+ l m) end)
sum
(loop2
(+ 1 m)
(+ sum
(let loop3 ((n 0) (sum 0))
(if (= (+ l m n) end)
sum
(loop3 (+ 1 n)
(+ sum (func l m n))))))))))))))
(define (sum-2d end func)
(let loop1 ((l 0) (sum 0))
(if (> l end)
sum
(loop1 (+ 1 l)
(+ sum (let loop2 ((m (- l)) (sum 0))
(if (> m l)
sum
(loop2 (+ 1 m)
(+ sum (func l m))))))))))
(define (sum2-2d init func)
(let loop1 ((l init) (sum 0))
(if (= l precision)
sum
(loop1 (+ 1 l)
(+ sum (let loop2 ((m (- l)) (sum 0))
(if (> m l)
sum
(loop2 (+ 1 m)
(+ sum (func l m))))))))))
(define fac
(let ((table (make-vector (* 4 precision) 0)))
(vector-set! table 0 1)
(let loop ((n 1))
(if (= n (* 4 precision))
(lambda (x) (vector-ref table x))
(begin (vector-set! table
n
(* n (vector-ref table (- n 1))))
(loop (+ 1 n)))))))
The table for ( * ( -0.5 ) ( -1.5 ) ( -2.5 ) ... ( + -0.5 -i 1 ) )
(define fac-1
(let ((table (make-vector precision 0)))
(vector-set! table 0 1)
(let loop ((n 1))
(if (= n precision)
(lambda (x) (vector-ref table x))
(begin (vector-set! table
n
(* (- .5 n)
(vector-ref table (- n 1))))
(loop (+ 1 n)))))))
(define fac-2
(let ((table (make-vector (* 4 precision) 0)))
(vector-set! table 0 1)
(let loop ((n 1))
(if (= n (* 4 precision))
(lambda (n) (if (< n 0)
1
(vector-ref table n)))
(begin (vector-set! table n (* (if (even? n) 1 n)
(vector-ref table (- n 1))))
(loop (+ 1 n)))))))
(define prod-fac
(let ((table (make-cartesian-expansion
(lambda (i j k) (* (fac i) (fac j) (fac k))))))
(lambda (i j k) (array-ref table i j k))))
(define 1/prod-fac
(let ((table (make-cartesian-expansion
(lambda (i j k) (/ (prod-fac i j k))))))
(lambda (i j k) (array-ref table i j k))))
(define (assoc-legendre l m x)
(cond ((= l m) (* (expt -1 m)
(fac-2 (- (* 2 m) 1))
(expt (- 1 (* x x)) (/ m 2))))
((= l (+ 1 m)) (* x (+ 1 (* 2 m)) (assoc-legendre m m x)))
(else (/ (- (* x (- (* 2 l) 1) (assoc-legendre (- l 1) m x))
(* (+ l m -1) (assoc-legendre (- l 2) m x)))
(- l m)))))
(define (eval-spherical-harmonic l m theta phi)
(let ((mm (abs m)))
(* (sqrt (/ (fac (- l mm)) (fac (+ l mm))))
(assoc-legendre l mm (cos theta))
(make-polar 1 (* m phi)))))
(define (eval-spher-harm-phi-deriv l m theta phi)
(* (eval-spherical-harmonic l m theta phi)
m
(make-rectangular 0 1)))
(define (eval-spher-harm-theta-deriv l m theta phi)
(let ((mm (abs m)))
(* (sqrt (/ (fac (- l mm)) (fac (+ l mm))))
(make-polar 1 (* m phi))
(- (sin theta))
(assoc-legendre-deriv l mm (cos theta)))))
(define (assoc-legendre-deriv l m x)
(cond ((= l m) (* (expt -1 (+ 1 m))
(fac-2 (- (* 2 m) 1))
m
(expt (- 1 (* x x)) (- (/ m 2) 1))
x))
((= l (+ 1 m)) (* (+ 1 (* 2 m))
(+ (assoc-legendre m m x)
(* x (assoc-legendre-deriv m m x)))))
(else (/ (- (* (- (* 2 l) 1)
(+ (assoc-legendre (- l 1) m x)
(* x (assoc-legendre-deriv (- l 1) m x))))
(* (+ l m -1) (assoc-legendre-deriv (- l 2) m x)))
(- l m)))))
(define (build-tree height near-size)
(let* ((vertex1 (make-pt -10 -10 -10))
(vertex2 (make-pt 10 10 10))
(tree (make-tree '() vertex1 vertex2)))
(let loop ((level 0) (pt1 vertex1) (pt2 vertex2))
(let* ((half-diagonal (pt-scalar* .5 (pt- pt2 pt1)))
(diag-length/2 (pt-x half-diagonal)))
(insert-node tree level pt1 pt2)
(if (< level height)
(let ((child-pt1s
(map (lambda (offset)
(pt+ pt1 (pt-scalar* diag-length/2 offset)))
(list (make-pt 0 0 0)
(make-pt 0 0 1)
(make-pt 0 1 0)
(make-pt 1 0 0)
(make-pt 0 1 1)
(make-pt 1 0 1)
(make-pt 1 1 0)
(make-pt 1 1 1)))))
(for-each (lambda (child-pt1)
(loop (+ 1 level)
child-pt1
(pt+ child-pt1 half-diagonal)))
child-pt1s)))))
(calc-near-and-interaction tree near-size)
tree))
(define (insert-node tree level pt1 pt2)
(let* ((center (pt-average pt1 pt2))
(new-node (make-node center pt1 pt2 '() '() '() '() '())))
(letrec ((insert-internal (lambda (node depth)
(if (= level depth)
(set-node-children! node
(cons new-node
(node-children node)))
(insert-internal (find-child node center)
(+ 1 depth))))))
(if (= level 0)
(set-tree-body! tree new-node)
(insert-internal (tree-body tree) 1)))))
(define (find-child node pos)
(let loop ((children (node-children node)))
(let ((child (car children)))
(if (within-box? pos
(node-low-left-front-vertex child)
(node-up-right-back-vertex child))
child
(loop (cdr children))))))
(define (insert-particle tree particle)
(let* ((pos (particle-position particle)))
(letrec ((insert-internal (lambda (node)
(if (leaf-node? node)
(set-node-particles!
node
(cons particle (node-particles node)))
(insert-internal (find-child node pos))))))
(if (within-box? pos
(tree-low-left-front-vertex tree)
(tree-up-right-back-vertex tree))
(insert-internal (tree-body tree))
(error 'insert-particle "particle not within boundaries of tree" particle)))))
(define (calc-near-and-interaction tree near-size)
(set-node-near-field! (tree-body tree) (list (tree-body tree)))
(let loop ((node (tree-body tree)) (parent #f))
(if parent
(let* ((center (node-center node))
(dist (* near-size
(abs (- (pt-x center)
(pt-x (node-center parent)))))))
(for-each
(lambda (parent-near)
(let ((interactives (list '())))
(for-each
(lambda (child)
(if (> (pt-r (pt- center (node-center child))) dist)
(set-car! interactives (cons child (car interactives)))
(set-node-near-field!
node
(cons child (node-near-field node)))))
(node-children parent-near))
(set-node-interactive-field!
node
(append (car interactives) (node-interactive-field node)))))
(node-near-field parent))))
(for-each (lambda (child) (loop child node)) (node-children node))))
(define (initial-particle x y z m)
(make-particle (make-pt x y z)
(make-pt 0 0 0)
(make-pt 0 0 0)
0 0 m))
(define (random-float bot top)
(+ (* (- top bot)
(/ (* (random 1000000) 1.0) 1000000.0))
bot))
(define (random-particle)
(make-particle (make-pt (random-float -10.0 10.0)
(random-float -10.0 10.0)
(random-float -10.0 10.0))
(make-pt 0 0 0)
(make-pt 0 0 0)
0 0 1.0))
(define *particles* (list '()))
(define (go depth precision n-particles)
(let ((tree (build-tree depth 27))
(particles (let next ((i 0) (ps '()))
(if (<= i n-particles)
(next (+ i 1) (cons (random-particle) ps))
ps))))
(for-each (lambda (p) (insert-particle tree p)) particles)
(cartesian-algorithm tree)
(set-car! *particles* particles)))
( go 1 3 10 ) 0.31 seconds
( go 3 5 128 ) 1397.31
( go 3 5 256 ) 1625.29
( go 3 5 512 ) 2380.35
( go 2 5 128 ) 27.44 seconds
(define (main . args)
(run-benchmark
"nbody"
nbody-iters
(lambda () #t)
(lambda (i j k) (go i j k))
2 5 128))
|
caa62a568fab25cd749182904cb7db57c004323283021f8877e87a49f215004a | commsor/titanoboa | cache.clj | Copyright ( c ) Commsor Inc. All rights reserved .
; The use and distribution terms for this software are covered by the
; GNU Affero General Public License v3.0 (/#AGPL)
; which can be found in the 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 titanoboa.cache
(:require [com.stuartsierra.component :as component]
[clojure.tools.logging :as log]))
TODO do nt use separate eviction - agent - just use metadata to mark jobs for eviction in the job - cache - agent - > this will eliminate the race condition or need for STM
(defrecord CacheEvictionComponent [thread-handle eviction-interval eviction-age eviction-agent job-cache-agent]
component/Lifecycle
(start [this]
(log/info "Starting CacheEvictionComponent...")
(if thread-handle
this
(let [th (Thread. (fn[]
(log/info "Starting CacheEvictionComponent thread [" (.getName (Thread/currentThread)) "].")
(loop [t (.getTime (java.util.Date.))]
(let [keys-to-evict (->> @eviction-agent
vec
(filter (fn [[k v]]
(>= (- t (.getTime v)) eviction-age)))
(mapv first))]
(when (and keys-to-evict (not-empty keys-to-evict))
(log/info "Evicting jobs from cache: [" keys-to-evict "].")
NOTE : since STM is not used there will be race conditions , but since the cache is used only for GUI some inconsistencies are considered acceptable :
(send job-cache-agent #(apply dissoc % keys-to-evict))
(send eviction-agent #(apply dissoc % keys-to-evict))))
(Thread/sleep eviction-interval)
(recur (.getTime (java.util.Date.)))))
(str "CacheEvictionComponent thread " (rand-int 9)))]
(.start th)
(assoc this
:thread-handle th))))
(stop [this]
(log/info "Stopping CacheEvictionComponent thread [" (.getName thread-handle) "]...")
(if thread-handle (.interrupt thread-handle))
(assoc this
:thread-handle nil))) | null | https://raw.githubusercontent.com/commsor/titanoboa/ffe3e1e58f89169092d7b6a3a45e1707a0ecc9ee/src/clj/titanoboa/cache.clj | clojure | The use and distribution terms for this software are covered by the
GNU Affero General Public License v3.0 (/#AGPL)
which can be found in the 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 ) Commsor Inc. All rights reserved .
(ns titanoboa.cache
(:require [com.stuartsierra.component :as component]
[clojure.tools.logging :as log]))
TODO do nt use separate eviction - agent - just use metadata to mark jobs for eviction in the job - cache - agent - > this will eliminate the race condition or need for STM
(defrecord CacheEvictionComponent [thread-handle eviction-interval eviction-age eviction-agent job-cache-agent]
component/Lifecycle
(start [this]
(log/info "Starting CacheEvictionComponent...")
(if thread-handle
this
(let [th (Thread. (fn[]
(log/info "Starting CacheEvictionComponent thread [" (.getName (Thread/currentThread)) "].")
(loop [t (.getTime (java.util.Date.))]
(let [keys-to-evict (->> @eviction-agent
vec
(filter (fn [[k v]]
(>= (- t (.getTime v)) eviction-age)))
(mapv first))]
(when (and keys-to-evict (not-empty keys-to-evict))
(log/info "Evicting jobs from cache: [" keys-to-evict "].")
NOTE : since STM is not used there will be race conditions , but since the cache is used only for GUI some inconsistencies are considered acceptable :
(send job-cache-agent #(apply dissoc % keys-to-evict))
(send eviction-agent #(apply dissoc % keys-to-evict))))
(Thread/sleep eviction-interval)
(recur (.getTime (java.util.Date.)))))
(str "CacheEvictionComponent thread " (rand-int 9)))]
(.start th)
(assoc this
:thread-handle th))))
(stop [this]
(log/info "Stopping CacheEvictionComponent thread [" (.getName thread-handle) "]...")
(if thread-handle (.interrupt thread-handle))
(assoc this
:thread-handle nil))) |
b410f65fba7c10535bdc4400f62c021c70e8bf8ffbdc94e2a3f5bb529cb71585 | mishadoff/project-euler | problem013.clj | (ns project-euler.problem013)
Elapsed time : 24.427424 msecs
(defn euler-013 []
(read-string
(apply str (take 10 (str (reduce + (map bigint (re-seq #"\w+" (slurp "res/problem013.txt"))))))))) | null | https://raw.githubusercontent.com/mishadoff/project-euler/45642adf29626d3752227c5a342886b33c70b337/src/project_euler/problem013.clj | clojure | (ns project-euler.problem013)
Elapsed time : 24.427424 msecs
(defn euler-013 []
(read-string
(apply str (take 10 (str (reduce + (map bigint (re-seq #"\w+" (slurp "res/problem013.txt"))))))))) | |
3ca23ad37f0c46e6e08cc876d7de33c4210fa44b538fab06a8f886fdf96e2adf | complyue/hadui | HaduiMonad.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE BlockArguments #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE FlexibleContexts #
# LANGUAGE ExistentialQuantification #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
{-# LANGUAGE BangPatterns #-}
# LANGUAGE LambdaCase #
# LANGUAGE QuasiQuotes #
-- | Hadui runtime
module HaduiMonad
( UIO(..)
, UserInterfaceOutput(..)
, runUIO
, mustUIO
, initUIO
, withHaduiFront
)
where
import RIO
import System.IO.Unsafe
import Data.Dynamic ( Dynamic(..) )
import qualified GHC
import qualified GhcMonad as GHC
import qualified Network.WebSockets as WS
import HaduiCfg
| The monad for User Interface Output
UIO is output only , conversely to IO ( which stands for Input / Output ) ,
user inputs shall be facilitated with a registry of ' MVar 's ,
those get filled with ' IoC ' from UI widgets .
newtype UIO a = UIO { unUIO :: ReaderT UserInterfaceOutput IO a }
deriving (Functor, Applicative, Monad,
MonadReader UserInterfaceOutput,
MonadIO, MonadThrow, MonadFail)
instance PrimMonad UIO where
type PrimState UIO = PrimState IO
primitive = UIO . ReaderT . const . primitive
instance HasLogFunc UserInterfaceOutput where
logFuncL = lens haduiBackendLogFunc (\x y -> x { haduiBackendLogFunc = y })
| Run a ' UIO ' action within any ' MonadIO ' given a ' uio ' env .
runUIO :: MonadIO m => UserInterfaceOutput -> UIO a -> m a
runUIO uio (UIO (ReaderT f)) = liftIO (f uio)
| Every statement being executed dynamically by , is unlifted
with this function into IO monad under the hood .
--
-- This very explicitly hints the expected monad type in the dynamic
-- compilation of such statements.
mustUIO :: UIO a -> IO ()
mustUIO m = do
uio <- readIORef _globalUIO
!_v <- runUIO uio m -- force it to be evaluated
pure ()
_globalUIO :: IORef UserInterfaceOutput
# NOINLINE _ globalUIO #
_globalUIO = unsafePerformIO $ newIORef undefined
| env of the UIO monad
data UserInterfaceOutput = UserInterfaceOutput {
-- | root directory of the stack project of matter
haduiProjectRoot :: !FilePath
-- | configuration loaded from `hadui.yaml` at project root
, haduiConfig :: !HaduiConfig
-- | arbitrary state managed by convention of the project
, haduiAppData :: !(MVar (Maybe Dynamic))
| Global Interpreter Lock similar to Python 's , but serializes
-- executions of ws packets only, a single ws packet can trigger
-- fully fledged concurrency and parallelism in contrast to Python.
--
If a UIO action starts concurrent compution threads , and such
-- a thread shall comm back to its originating ws, it must save
-- the contextual websocket in GIL atm it's started.
, haduiGIL :: !(MVar WS.Connection)
| the underlying log function to implement rio 's
, haduiBackendLogFunc :: !LogFunc
| GHC session used to execute statements by dynamic compilation
, haduiGhcSession :: !GHC.Session
}
| Initialize global UIO context with the calling
initUIO :: GHC.Ghc UserInterfaceOutput
initUIO = do
ghcSession <- GHC.reifyGhc return
uio <- liftIO $ do
prj <- loadHaduiConfig
appData <- newMVar Nothing
gil <- newEmptyMVar
let !cfg = haduiCfg prj
lo <- haduiBackendLogOpts cfg
-- may need to teardown 'lf' on process exit, once the log target
-- needs that, not needed as far as we only log to stderr.
(lf, _ :: IO ()) <- newLogFunc lo
return UserInterfaceOutput { haduiProjectRoot = projectRoot prj
, haduiConfig = cfg
, haduiAppData = appData
, haduiGIL = gil
, haduiBackendLogFunc = lf
, haduiGhcSession = ghcSession
}
make module ' UIO ' in scope implicitly
GHC.getContext
>>= GHC.setContext
. ((GHC.IIDecl $ GHC.simpleImportDecl $ GHC.mkModuleName "UIO") :)
-- to allow string and number literals without explicit type anno
_ <- GHC.runDecls "default (Text,Int,Double)"
XXX this does not work , have to use -fbreak - on - error on launching cmdl
--
-- break on error/exception to print error location for debuggability
-- dynFlags <- GHC.getSessionDynFlags
let dynFlags ' = dynFlags & GHC.setGeneralFlag ' GHC.Opt_BreakOnError
-- -- stop only on uncaught exceptions with mere above,
-- -- following enables stop on any exception:
-- . ' GHC.Opt_BreakOnException
-- _ <- GHC.setSessionDynFlags dynFlags'
liftIO $ writeIORef _globalUIO uio
return uio
| Execute a UIO action with the specified ws for current context .
--
-- Note this is designed to be called from forked threads by wsc actions.
-- The wsc argument to use here is normally captured from 'haduiGIL' atm
-- the calling thread is started.
--
-- NEVER call this from threads directly triggered by UI, or it's deadlock.
withHaduiFront :: WS.Connection -> UIO a -> UIO a
withHaduiFront wsc action = do
uio <- ask
let gil = haduiGIL uio
bracket_ (liftIO $ putMVar gil wsc) (liftIO $ takeMVar gil) action
| null | https://raw.githubusercontent.com/complyue/hadui/de221a453f32e02c50de52daf936b694267282c2/hadui/src/HaduiMonad.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# LANGUAGE BangPatterns #
| Hadui runtime
This very explicitly hints the expected monad type in the dynamic
compilation of such statements.
force it to be evaluated
| root directory of the stack project of matter
| configuration loaded from `hadui.yaml` at project root
| arbitrary state managed by convention of the project
executions of ws packets only, a single ws packet can trigger
fully fledged concurrency and parallelism in contrast to Python.
a thread shall comm back to its originating ws, it must save
the contextual websocket in GIL atm it's started.
may need to teardown 'lf' on process exit, once the log target
needs that, not needed as far as we only log to stderr.
to allow string and number literals without explicit type anno
break on error/exception to print error location for debuggability
dynFlags <- GHC.getSessionDynFlags
-- stop only on uncaught exceptions with mere above,
-- following enables stop on any exception:
. ' GHC.Opt_BreakOnException
_ <- GHC.setSessionDynFlags dynFlags'
Note this is designed to be called from forked threads by wsc actions.
The wsc argument to use here is normally captured from 'haduiGIL' atm
the calling thread is started.
NEVER call this from threads directly triggered by UI, or it's deadlock. | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE BlockArguments #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE FlexibleContexts #
# LANGUAGE ExistentialQuantification #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE LambdaCase #
# LANGUAGE QuasiQuotes #
module HaduiMonad
( UIO(..)
, UserInterfaceOutput(..)
, runUIO
, mustUIO
, initUIO
, withHaduiFront
)
where
import RIO
import System.IO.Unsafe
import Data.Dynamic ( Dynamic(..) )
import qualified GHC
import qualified GhcMonad as GHC
import qualified Network.WebSockets as WS
import HaduiCfg
| The monad for User Interface Output
UIO is output only , conversely to IO ( which stands for Input / Output ) ,
user inputs shall be facilitated with a registry of ' MVar 's ,
those get filled with ' IoC ' from UI widgets .
newtype UIO a = UIO { unUIO :: ReaderT UserInterfaceOutput IO a }
deriving (Functor, Applicative, Monad,
MonadReader UserInterfaceOutput,
MonadIO, MonadThrow, MonadFail)
instance PrimMonad UIO where
type PrimState UIO = PrimState IO
primitive = UIO . ReaderT . const . primitive
instance HasLogFunc UserInterfaceOutput where
logFuncL = lens haduiBackendLogFunc (\x y -> x { haduiBackendLogFunc = y })
| Run a ' UIO ' action within any ' MonadIO ' given a ' uio ' env .
runUIO :: MonadIO m => UserInterfaceOutput -> UIO a -> m a
runUIO uio (UIO (ReaderT f)) = liftIO (f uio)
| Every statement being executed dynamically by , is unlifted
with this function into IO monad under the hood .
mustUIO :: UIO a -> IO ()
mustUIO m = do
uio <- readIORef _globalUIO
pure ()
_globalUIO :: IORef UserInterfaceOutput
# NOINLINE _ globalUIO #
_globalUIO = unsafePerformIO $ newIORef undefined
| env of the UIO monad
data UserInterfaceOutput = UserInterfaceOutput {
haduiProjectRoot :: !FilePath
, haduiConfig :: !HaduiConfig
, haduiAppData :: !(MVar (Maybe Dynamic))
| Global Interpreter Lock similar to Python 's , but serializes
If a UIO action starts concurrent compution threads , and such
, haduiGIL :: !(MVar WS.Connection)
| the underlying log function to implement rio 's
, haduiBackendLogFunc :: !LogFunc
| GHC session used to execute statements by dynamic compilation
, haduiGhcSession :: !GHC.Session
}
| Initialize global UIO context with the calling
initUIO :: GHC.Ghc UserInterfaceOutput
initUIO = do
ghcSession <- GHC.reifyGhc return
uio <- liftIO $ do
prj <- loadHaduiConfig
appData <- newMVar Nothing
gil <- newEmptyMVar
let !cfg = haduiCfg prj
lo <- haduiBackendLogOpts cfg
(lf, _ :: IO ()) <- newLogFunc lo
return UserInterfaceOutput { haduiProjectRoot = projectRoot prj
, haduiConfig = cfg
, haduiAppData = appData
, haduiGIL = gil
, haduiBackendLogFunc = lf
, haduiGhcSession = ghcSession
}
make module ' UIO ' in scope implicitly
GHC.getContext
>>= GHC.setContext
. ((GHC.IIDecl $ GHC.simpleImportDecl $ GHC.mkModuleName "UIO") :)
_ <- GHC.runDecls "default (Text,Int,Double)"
XXX this does not work , have to use -fbreak - on - error on launching cmdl
let dynFlags ' = dynFlags & GHC.setGeneralFlag ' GHC.Opt_BreakOnError
liftIO $ writeIORef _globalUIO uio
return uio
| Execute a UIO action with the specified ws for current context .
withHaduiFront :: WS.Connection -> UIO a -> UIO a
withHaduiFront wsc action = do
uio <- ask
let gil = haduiGIL uio
bracket_ (liftIO $ putMVar gil wsc) (liftIO $ takeMVar gil) action
|
39c71fef0ba8dedbe70ecf9a844d6b2e51a5c1d069cc85e374d676ee54c9b686 | ghc/packages-Cabal | App.hs | module App where
import Database.MySQL
import Database.PostgreSQL
import qualified Mine.MySQL
import qualified Mine.PostgreSQL
app = Mine.MySQL.mine ++ " " ++ Mine.PostgreSQL.mine
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/Backpack/Includes2/src/App.hs | haskell | module App where
import Database.MySQL
import Database.PostgreSQL
import qualified Mine.MySQL
import qualified Mine.PostgreSQL
app = Mine.MySQL.mine ++ " " ++ Mine.PostgreSQL.mine
| |
cacc9655b517818b480fd5e5bbb3d71c90c9e815bd56b97881c2299e3a25d999 | vlstill/hsExprTest | simple-1.nok.hs | f = False
| null | https://raw.githubusercontent.com/vlstill/hsExprTest/391fc823c1684ec248ac8f76412fefeffb791865/test/simple-1.nok.hs | haskell | f = False
| |
d410affa330d3e9ed9c8ec3f8a9bb332b92fe26c2d1e858a97c40d0c3816194c | ocaml-flambda/flambda-backend | parseflambda.ml | open Import
let get_global_info = Flambda2.get_global_info
let check_invariants program =
try () (* Flambda_unit.invariant program *)
with exn ->
Format.eprintf "Program which failed invariant check:@ %a\n%!"
Flambda_unit.print program;
raise exn
let parse_flambda filename =
match Parse_flambda.parse_fexpr filename with
| Ok unit ->
let comp_unit =
Parse_flambda.make_compilation_unit ~extension:".fl" ~filename ()
in
Compilation_unit.set_current comp_unit;
Format.printf "%a@.@." Print_fexpr.flambda_unit unit;
let fl2 = Fexpr_to_flambda.conv comp_unit unit in
Format.printf "flambda:@.%a@.@." Flambda_unit.print fl2;
check_invariants fl2;
let cmx_loader = Flambda_cmx.create_loader ~get_global_info in
let { Simplify.unit = fl2'; _ } = Simplify.run ~cmx_loader ~round:1 fl2 in
Format.printf "simplify:@.%a@." Flambda_unit.print fl2';
let fl3 = Flambda_to_fexpr.conv fl2' in
Format.printf "back to fexpr:@.%a@." Print_fexpr.flambda_unit fl3;
fl3
| Error e ->
Test_utils.dump_error e;
exit 1
let _ =
let file = Sys.argv.(1) in
let ext = Filename.extension file in
match ext with
| ".fl" -> parse_flambda file
| _ -> Misc.fatal_errorf "Unrecognized extension %s" ext
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/3bdcccae8391bb86e54d8116521e5fbe28e97d48/middle_end/flambda2/tests/tools/parseflambda.ml | ocaml | Flambda_unit.invariant program | open Import
let get_global_info = Flambda2.get_global_info
let check_invariants program =
with exn ->
Format.eprintf "Program which failed invariant check:@ %a\n%!"
Flambda_unit.print program;
raise exn
let parse_flambda filename =
match Parse_flambda.parse_fexpr filename with
| Ok unit ->
let comp_unit =
Parse_flambda.make_compilation_unit ~extension:".fl" ~filename ()
in
Compilation_unit.set_current comp_unit;
Format.printf "%a@.@." Print_fexpr.flambda_unit unit;
let fl2 = Fexpr_to_flambda.conv comp_unit unit in
Format.printf "flambda:@.%a@.@." Flambda_unit.print fl2;
check_invariants fl2;
let cmx_loader = Flambda_cmx.create_loader ~get_global_info in
let { Simplify.unit = fl2'; _ } = Simplify.run ~cmx_loader ~round:1 fl2 in
Format.printf "simplify:@.%a@." Flambda_unit.print fl2';
let fl3 = Flambda_to_fexpr.conv fl2' in
Format.printf "back to fexpr:@.%a@." Print_fexpr.flambda_unit fl3;
fl3
| Error e ->
Test_utils.dump_error e;
exit 1
let _ =
let file = Sys.argv.(1) in
let ext = Filename.extension file in
match ext with
| ".fl" -> parse_flambda file
| _ -> Misc.fatal_errorf "Unrecognized extension %s" ext
|
7bdfc328037e38cc5dabe8c3ce9effa8f1b9eb699149eb9e75f1b2a3c6a6f169 | c4-project/c4f | input.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Stdio
type t = File of Fpath.t | Stdin of {file_type: string option}
[@@deriving variants]
(* overrides to lift options into optional arguments *)
let stdin ?file_type () : t = stdin ~file_type
let file_type : t -> string option = function
| File fp ->
Option.some_if (Fpath.exists_ext fp)
(String.lstrip ~drop:(Char.equal '.') (Fpath.get_ext fp))
| Stdin sd -> sd.file_type
include Io_common.Make (struct
type nonrec t = t
let of_fpath : Fpath.t -> t = file
let to_fpath_opt : t -> Fpath.t option = function
| File f -> Some f
| Stdin _ -> None
let std () = stdin ()
let std_name = "stdin"
end)
let with_input (src : t) ~(f : Stdio.In_channel.t -> 'a Or_error.t) :
'a Or_error.t =
Or_error.(
match src with
| File file ->
let s = Fpath.to_string file in
tag_arg
(try_with_join (fun _ -> In_channel.with_file s ~f))
"While reading from file:" s [%sexp_of: string]
| Stdin _ ->
tag ~tag:"While reading from standard input:"
(try_with_join (fun _ -> f In_channel.stdin)))
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/plumbing/src/input.ml | ocaml | overrides to lift options into optional arguments | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Stdio
type t = File of Fpath.t | Stdin of {file_type: string option}
[@@deriving variants]
let stdin ?file_type () : t = stdin ~file_type
let file_type : t -> string option = function
| File fp ->
Option.some_if (Fpath.exists_ext fp)
(String.lstrip ~drop:(Char.equal '.') (Fpath.get_ext fp))
| Stdin sd -> sd.file_type
include Io_common.Make (struct
type nonrec t = t
let of_fpath : Fpath.t -> t = file
let to_fpath_opt : t -> Fpath.t option = function
| File f -> Some f
| Stdin _ -> None
let std () = stdin ()
let std_name = "stdin"
end)
let with_input (src : t) ~(f : Stdio.In_channel.t -> 'a Or_error.t) :
'a Or_error.t =
Or_error.(
match src with
| File file ->
let s = Fpath.to_string file in
tag_arg
(try_with_join (fun _ -> In_channel.with_file s ~f))
"While reading from file:" s [%sexp_of: string]
| Stdin _ ->
tag ~tag:"While reading from standard input:"
(try_with_join (fun _ -> f In_channel.stdin)))
|
3b4121c59ca8a82f065f31d5335f50b13a4d8ea6586646fb05166b2d7194d1bb | hyperfiddle/electric | analyzer.clj | (ns hyperfiddle.electric.impl.analyzer
"Utilities to analyze and transform Clojure/Script code (not Electric code).
Use case: support `clojure.core/fn` in an Electric program.
Long term goal is to build a unified Clojure/Script code walker and get rid of tools.analyzer deps."
(:require [clojure.tools.analyzer.passes.jvm.emit-form :as emit-form]
[clojure.tools.analyzer.ast :as clj-ast]
[clojure.tools.analyzer.jvm :as clj]
[cljs.analyzer.api :as cljs]
[cljs.analyzer :as cljs-ana]
[cljs.analyzer.passes :as cljs-ast]
[hyperfiddle.logger :as log]))
(defn walk-clj "Prewalk a clj ast" [ast f] (clj-ast/prewalk ast f))
(defn walk-cljs "Prewalk a cljs ast" [ast f] (cljs-ast/walk ast [(fn [env ast opts] (f ast))]))
(defn analyze-clj "Analyze a clj form to ast without any passes." [env form]
(binding [clj/run-passes identity]
(clj/analyze form env)))
(defn analyze-cljs "Analyze a cljs form to ast without any passes." [env form]
(binding [cljs-ana/*passes* []]
(walk-cljs (cljs/analyze env form)
(fn [ast]
(case (:op ast)
:binding (let [var-info (get-in ast [:init :info])]
(if (some? (:hyperfiddle.electric.impl.compiler/node var-info))
(throw (ex-info (str "`"(:name var-info) "` is an Electric var and cannot be bound from a Clojure context.")
(merge {:file (:file (:meta (:ns env)))}
(select-keys ast #{:file :line}))))
ast))
ast)))))
(defn specialize-clj-ast-op [ast]
(update ast :op (fn [op] (case op
:const ::const
op))))
(defn emit-clj [ast]
(emit-form/emit-form (walk-clj ast specialize-clj-ast-op)))
(defmethod emit-form/-emit-form ::const
[{:keys [type val] :as ast} opts]
(if (= type :class)
(symbol (.getName ^Class val))
(emit-form/-emit-form (assoc ast :op :const) opts)))
(declare emit-cljs)
(defn emit-cljs-method [{:keys [variadic? params body]}]
(list (if variadic?
(-> (into [] (map :name) (pop params))
(conj '& (-> params peek :name)))
(into [] (map :name) params)) (emit-cljs body)))
;; Adapted from leonoel/injure
(defn emit-cljs "Emit cljs code from a cljs.analyzer AST."
[ast]
(case (:op ast)
:let
(list 'let (into [] (mapcat
(fn [{:keys [name init]}]
[name (emit-cljs init)]))
(:bindings ast))
(emit-cljs (:body ast)))
:loop
(list 'loop (into [] (mapcat
(fn [{:keys [name init]}]
[name (emit-cljs init)]))
(:bindings ast))
(emit-cljs (:body ast)))
:recur
(cons 'recur (map emit-cljs (:exprs ast)))
:invoke
(map emit-cljs (cons (:fn ast) (:args ast)))
:fn
(cons 'fn (concat (when-some [l (:local ast)] [(:name l)])
(map emit-cljs-method (:methods ast))))
:letfn
(list 'letfn (into [] (map (fn [{:keys [name init]}]
(cons name (map emit-cljs-method (:methods init)))))
(:bindings ast))
(emit-cljs (:body ast)))
:try
`(~'try ~(emit-cljs (:body ast))
~@(when-not (= :throw (:op (:catch ast)))
(let [name (get-in ast [:name])]
[(list 'catch :default name (emit-cljs (:catch ast)))]))
~@(when-some [f (:finally ast)]
[(list 'finally (emit-cljs f))]))
:throw
(list 'throw (emit-cljs (:exception ast)))
:new
(cons 'new (map emit-cljs (cons (:class ast) (:args ast))))
:def
(list 'def (emit-cljs (:var ast)) (emit-cljs (:init ast)))
:set!
(list 'set! (emit-cljs (:target ast)) (emit-cljs (:val ast)))
:js
(list* 'js* (or (:code ast) (apply str (interpose "~{}" (:segs ast)))) (map emit-cljs (:args ast)))
:do
(cons 'do (conj (mapv emit-cljs (:statements ast)) (emit-cljs (:ret ast))))
:map
(zipmap (map emit-cljs (:keys ast)) (map emit-cljs (:vals ast)))
:set
(into #{} (map emit-cljs) (:items ast))
(:vec :vector)
(into [] (map emit-cljs) (:items ast))
:list `(list ~@ (map emit-cljs (:items ast)))
:js-array `(cljs.core/array ~@(map emit-cljs (:items ast)))
:js-object `(cljs.core/js-obj ~@(interleave (:keys ast) (map emit-cljs (:vals ast))))
:if
(list 'if (emit-cljs (:test ast)) (emit-cljs (:then ast)) (emit-cljs (:else ast)))
:case
(list* 'case (emit-cljs (:test ast))
(-> []
(into (mapcat (fn [{:keys [tests then]}]
[(map :form tests) (emit-cljs (:then then))]))
(:nodes ast))
(conj (emit-cljs (:default ast)))))
:host-field
(list '. (emit-cljs (:target ast)) (symbol (str "-" (name (:field ast)))))
:host-call
(list* '. (emit-cljs (:target ast)) (:method ast) (map emit-cljs (:args ast)))
:with-meta `(with-meta ~(emit-cljs (:expr ast)) ~(emit-cljs (:meta ast)))
:the-var `(var ~(-> ast :var :form))
(:js-var :var :local :const :quote) (:form ast)
;; :binding ; Handled in let and fn
;; :case-node ; Handled in :case
;; :case-test
;; :case-then
;; :fn-method ; Handled in fn
;; :no-op ; Unknown use case
: defrecord ; Wo n’t be supported
;; :ns
;; :ns*
(do (hyperfiddle.logger/warn "This cljs form is not supported yet. Please log a ticket." {:op (:op ast) :form (:form ast)})
(:form ast))))
| null | https://raw.githubusercontent.com/hyperfiddle/electric/398158cb49ec1c459927e9d6719b9ea16685b21f/src/hyperfiddle/electric/impl/analyzer.clj | clojure | Adapted from leonoel/injure
:binding ; Handled in let and fn
:case-node ; Handled in :case
:case-test
:case-then
:fn-method ; Handled in fn
:no-op ; Unknown use case
Wo n’t be supported
:ns
:ns* | (ns hyperfiddle.electric.impl.analyzer
"Utilities to analyze and transform Clojure/Script code (not Electric code).
Use case: support `clojure.core/fn` in an Electric program.
Long term goal is to build a unified Clojure/Script code walker and get rid of tools.analyzer deps."
(:require [clojure.tools.analyzer.passes.jvm.emit-form :as emit-form]
[clojure.tools.analyzer.ast :as clj-ast]
[clojure.tools.analyzer.jvm :as clj]
[cljs.analyzer.api :as cljs]
[cljs.analyzer :as cljs-ana]
[cljs.analyzer.passes :as cljs-ast]
[hyperfiddle.logger :as log]))
(defn walk-clj "Prewalk a clj ast" [ast f] (clj-ast/prewalk ast f))
(defn walk-cljs "Prewalk a cljs ast" [ast f] (cljs-ast/walk ast [(fn [env ast opts] (f ast))]))
(defn analyze-clj "Analyze a clj form to ast without any passes." [env form]
(binding [clj/run-passes identity]
(clj/analyze form env)))
(defn analyze-cljs "Analyze a cljs form to ast without any passes." [env form]
(binding [cljs-ana/*passes* []]
(walk-cljs (cljs/analyze env form)
(fn [ast]
(case (:op ast)
:binding (let [var-info (get-in ast [:init :info])]
(if (some? (:hyperfiddle.electric.impl.compiler/node var-info))
(throw (ex-info (str "`"(:name var-info) "` is an Electric var and cannot be bound from a Clojure context.")
(merge {:file (:file (:meta (:ns env)))}
(select-keys ast #{:file :line}))))
ast))
ast)))))
(defn specialize-clj-ast-op [ast]
(update ast :op (fn [op] (case op
:const ::const
op))))
(defn emit-clj [ast]
(emit-form/emit-form (walk-clj ast specialize-clj-ast-op)))
(defmethod emit-form/-emit-form ::const
[{:keys [type val] :as ast} opts]
(if (= type :class)
(symbol (.getName ^Class val))
(emit-form/-emit-form (assoc ast :op :const) opts)))
(declare emit-cljs)
(defn emit-cljs-method [{:keys [variadic? params body]}]
(list (if variadic?
(-> (into [] (map :name) (pop params))
(conj '& (-> params peek :name)))
(into [] (map :name) params)) (emit-cljs body)))
(defn emit-cljs "Emit cljs code from a cljs.analyzer AST."
[ast]
(case (:op ast)
:let
(list 'let (into [] (mapcat
(fn [{:keys [name init]}]
[name (emit-cljs init)]))
(:bindings ast))
(emit-cljs (:body ast)))
:loop
(list 'loop (into [] (mapcat
(fn [{:keys [name init]}]
[name (emit-cljs init)]))
(:bindings ast))
(emit-cljs (:body ast)))
:recur
(cons 'recur (map emit-cljs (:exprs ast)))
:invoke
(map emit-cljs (cons (:fn ast) (:args ast)))
:fn
(cons 'fn (concat (when-some [l (:local ast)] [(:name l)])
(map emit-cljs-method (:methods ast))))
:letfn
(list 'letfn (into [] (map (fn [{:keys [name init]}]
(cons name (map emit-cljs-method (:methods init)))))
(:bindings ast))
(emit-cljs (:body ast)))
:try
`(~'try ~(emit-cljs (:body ast))
~@(when-not (= :throw (:op (:catch ast)))
(let [name (get-in ast [:name])]
[(list 'catch :default name (emit-cljs (:catch ast)))]))
~@(when-some [f (:finally ast)]
[(list 'finally (emit-cljs f))]))
:throw
(list 'throw (emit-cljs (:exception ast)))
:new
(cons 'new (map emit-cljs (cons (:class ast) (:args ast))))
:def
(list 'def (emit-cljs (:var ast)) (emit-cljs (:init ast)))
:set!
(list 'set! (emit-cljs (:target ast)) (emit-cljs (:val ast)))
:js
(list* 'js* (or (:code ast) (apply str (interpose "~{}" (:segs ast)))) (map emit-cljs (:args ast)))
:do
(cons 'do (conj (mapv emit-cljs (:statements ast)) (emit-cljs (:ret ast))))
:map
(zipmap (map emit-cljs (:keys ast)) (map emit-cljs (:vals ast)))
:set
(into #{} (map emit-cljs) (:items ast))
(:vec :vector)
(into [] (map emit-cljs) (:items ast))
:list `(list ~@ (map emit-cljs (:items ast)))
:js-array `(cljs.core/array ~@(map emit-cljs (:items ast)))
:js-object `(cljs.core/js-obj ~@(interleave (:keys ast) (map emit-cljs (:vals ast))))
:if
(list 'if (emit-cljs (:test ast)) (emit-cljs (:then ast)) (emit-cljs (:else ast)))
:case
(list* 'case (emit-cljs (:test ast))
(-> []
(into (mapcat (fn [{:keys [tests then]}]
[(map :form tests) (emit-cljs (:then then))]))
(:nodes ast))
(conj (emit-cljs (:default ast)))))
:host-field
(list '. (emit-cljs (:target ast)) (symbol (str "-" (name (:field ast)))))
:host-call
(list* '. (emit-cljs (:target ast)) (:method ast) (map emit-cljs (:args ast)))
:with-meta `(with-meta ~(emit-cljs (:expr ast)) ~(emit-cljs (:meta ast)))
:the-var `(var ~(-> ast :var :form))
(:js-var :var :local :const :quote) (:form ast)
(do (hyperfiddle.logger/warn "This cljs form is not supported yet. Please log a ticket." {:op (:op ast) :form (:form ast)})
(:form ast))))
|
ec056e7e3130d345b6c1d2b43503ef827df344f06c42ecc5457afd275b789ba1 | sneeuwballen/zipperposition | testMultiset.ml |
open Logtk
module Q = QCheck
module M = Multiset.Make(struct
type t = int
let compare i j=Pervasives.compare i j
end)
(* for testing *)
let m_test = Alcotest.testable (M.pp Fmt.int) M.equal
let z_test = Alcotest.testable Z.pp_print Z.equal
let f x y =
if x = y then Comparison.Eq
else if x < y then Lt
else Gt
let test_max = "multiset.max", `Quick, fun()->
let m = M.of_list [1;2;2;3;1] in
Alcotest.(check m_test) "must be equal" (M.of_list [3]) (M.max f m)
let test_compare = "multiset.compare", `Quick, fun()->
let m1 = M.of_list [1;1;2;3] in
let m2 = M.of_list [1;2;2;3] in
Alcotest.(check (module Comparison)) "must be lt"
Comparison.Lt (M.compare_partial f m1 m2);
Alcotest.(check bool) "ord" true (M.compare m1 m2 < 0);
()
let test_cardinal_size = "multiset.size", `Quick, fun()->
let m = M.of_coeffs [1, Z.(of_int 2); 3, Z.(of_int 40)] in
Alcotest.(check int) "size=2" 2 (M.size m);
Alcotest.(check z_test) "cardinal=42" Z.(of_int 42) (M.cardinal m);
()
let _sign = function
| 0 -> 0
| n when n < 0 -> -1
| _ -> 1
let gen1 =
let pp1 = CCFormat.to_string (M.pp CCFormat.int) in
let shrink_z z =
try Z.to_int_exn z |> Q.Shrink.int |> Q.Iter.map Z.of_int
with _ -> Q.Iter.empty
in
let shrink2 = Q.Shrink.pair Q.Shrink.nil shrink_z in
let shrink l =
M.to_list l
|> Q.Shrink.(list ~shrink:shrink2)
|> Q.Iter.map M.of_coeffs
in
Q.(small_list small_int
|> map M.of_list
|> set_print pp1
|> set_shrink shrink)
let compare_and_partial =
(* "naive" comparison function (using the general ordering on multisets) *)
let compare' m1 m2 =
let f x y = Comparison.of_total (CCInt.compare x y) in
Comparison.to_total (M.compare_partial f m1 m2)
in
let prop (m1,m2) =
_sign (compare' m1 m2) = _sign (M.compare m1 m2)
in
QCheck.Test.make
~name:"multiset_compare_and_compare_partial" ~long_factor:3 ~count:1000
(Q.pair gen1 gen1) prop
(* partial order for tests *)
let partial_ord (x:int) y =
if x=y then Comparison.Eq
else if (x/5=y/5 && x mod 5 <> y mod 5) then Incomparable
else CCInt.compare (x/5) (y/5) |> Comparison.of_total
let compare_partial_sym =
let prop (m1,m2) =
let c1 = M.compare_partial partial_ord m1 m2 in
let c2 = Comparison.opp (M.compare_partial partial_ord m2 m1) in
if c1=c2
then true
else Q.Test.fail_reportf "comparison: %a vs %a" Comparison.pp c1 Comparison.pp c2
in
QCheck.Test.make
~name:"multiset_compare_partial_sym" ~long_factor:3 ~count:13_000
Q.(pair gen1 gen1) prop
let compare_partial_trans =
let prop (m1,m2,m3) =
let c1 = M.compare_partial partial_ord m1 m2 in
let c2 = M.compare_partial partial_ord m2 m3 in
let c3 = M.compare_partial partial_ord m1 m3 in
begin match c1, c2, c3 with
| Comparison.Incomparable, _, _
| _, Comparison.Incomparable, _
| _, _, Comparison.Incomparable
| Leq, _, _
| _, Leq, _
| _, _, Leq
| Geq, _, _
| _, Geq, _
| _, _, Geq
| Lt, Gt, _
| Gt, Lt, _ -> Q.assume_fail() (* ignore *)
| Eq, Eq, Eq -> true
| Gt, Gt, Gt
| Gt, Eq, Gt
| Eq, Gt, Gt -> true
| Lt, Lt, Lt
| Lt, Eq, Lt
| Eq, Lt, Lt -> true
| Lt, _, Eq
| Gt, _, Eq
| _, Lt, Eq
| _, Gt, Eq
| (Eq | Lt), Lt, Gt
| (Eq | Gt), Gt, Lt
| Lt, Eq, Gt
| Gt, Eq, Lt
| Eq, Eq, (Lt | Gt)
->
Q.Test.fail_reportf
"comp %a %a %a" Comparison.pp c1 Comparison.pp c2 Comparison.pp c3
end
in
QCheck.Test.make
~name:"multiset_compare_partial_trans" ~long_factor:3 ~count:13_000
(Q.triple gen1 gen1 gen1) prop
let max_seq_correct =
let prop m =
let l1 = M.max_seq partial_ord m |> Iter.map fst |> Iter.to_list in
let l2 = M.to_list m |> List.map fst
|> List.filter (fun x -> M.is_max partial_ord x m) in
if l1=l2 then true
else Q.Test.fail_reportf "@[max_seq %a,@ max %a@]"
CCFormat.Dump.(list int) l1
CCFormat.Dump.(list int) l2
in
Q.Test.make ~name:"multiset_max_seq" ~long_factor:5 ~count:10_000 gen1 prop
let max_is_max =
let pp = CCFormat.to_string (M.pp CCFormat.int) in
let gen = Q.(map M.of_list (list small_int)) in
let gen = Q.set_print pp gen in
let prop m =
let f x y = Comparison.of_total (Pervasives.compare x y) in
let l = M.max f m |> M.to_list |> List.map fst in
List.for_all (fun x -> M.is_max f x m) l
in
Q.Test.make
~name:"multiset_max_l_is_max" ~long_factor:3 ~count:1000
gen prop
let suite =
[ test_max;
test_compare;
test_cardinal_size;
]
let props =
[ compare_and_partial;
compare_partial_sym;
compare_partial_trans;
max_is_max;
max_seq_correct;
]
| null | https://raw.githubusercontent.com/sneeuwballen/zipperposition/4a3290cbc9a9ca0d8bd46f5db709a9e866920312/tests/testMultiset.ml | ocaml | for testing
"naive" comparison function (using the general ordering on multisets)
partial order for tests
ignore |
open Logtk
module Q = QCheck
module M = Multiset.Make(struct
type t = int
let compare i j=Pervasives.compare i j
end)
let m_test = Alcotest.testable (M.pp Fmt.int) M.equal
let z_test = Alcotest.testable Z.pp_print Z.equal
let f x y =
if x = y then Comparison.Eq
else if x < y then Lt
else Gt
let test_max = "multiset.max", `Quick, fun()->
let m = M.of_list [1;2;2;3;1] in
Alcotest.(check m_test) "must be equal" (M.of_list [3]) (M.max f m)
let test_compare = "multiset.compare", `Quick, fun()->
let m1 = M.of_list [1;1;2;3] in
let m2 = M.of_list [1;2;2;3] in
Alcotest.(check (module Comparison)) "must be lt"
Comparison.Lt (M.compare_partial f m1 m2);
Alcotest.(check bool) "ord" true (M.compare m1 m2 < 0);
()
let test_cardinal_size = "multiset.size", `Quick, fun()->
let m = M.of_coeffs [1, Z.(of_int 2); 3, Z.(of_int 40)] in
Alcotest.(check int) "size=2" 2 (M.size m);
Alcotest.(check z_test) "cardinal=42" Z.(of_int 42) (M.cardinal m);
()
let _sign = function
| 0 -> 0
| n when n < 0 -> -1
| _ -> 1
let gen1 =
let pp1 = CCFormat.to_string (M.pp CCFormat.int) in
let shrink_z z =
try Z.to_int_exn z |> Q.Shrink.int |> Q.Iter.map Z.of_int
with _ -> Q.Iter.empty
in
let shrink2 = Q.Shrink.pair Q.Shrink.nil shrink_z in
let shrink l =
M.to_list l
|> Q.Shrink.(list ~shrink:shrink2)
|> Q.Iter.map M.of_coeffs
in
Q.(small_list small_int
|> map M.of_list
|> set_print pp1
|> set_shrink shrink)
let compare_and_partial =
let compare' m1 m2 =
let f x y = Comparison.of_total (CCInt.compare x y) in
Comparison.to_total (M.compare_partial f m1 m2)
in
let prop (m1,m2) =
_sign (compare' m1 m2) = _sign (M.compare m1 m2)
in
QCheck.Test.make
~name:"multiset_compare_and_compare_partial" ~long_factor:3 ~count:1000
(Q.pair gen1 gen1) prop
let partial_ord (x:int) y =
if x=y then Comparison.Eq
else if (x/5=y/5 && x mod 5 <> y mod 5) then Incomparable
else CCInt.compare (x/5) (y/5) |> Comparison.of_total
let compare_partial_sym =
let prop (m1,m2) =
let c1 = M.compare_partial partial_ord m1 m2 in
let c2 = Comparison.opp (M.compare_partial partial_ord m2 m1) in
if c1=c2
then true
else Q.Test.fail_reportf "comparison: %a vs %a" Comparison.pp c1 Comparison.pp c2
in
QCheck.Test.make
~name:"multiset_compare_partial_sym" ~long_factor:3 ~count:13_000
Q.(pair gen1 gen1) prop
let compare_partial_trans =
let prop (m1,m2,m3) =
let c1 = M.compare_partial partial_ord m1 m2 in
let c2 = M.compare_partial partial_ord m2 m3 in
let c3 = M.compare_partial partial_ord m1 m3 in
begin match c1, c2, c3 with
| Comparison.Incomparable, _, _
| _, Comparison.Incomparable, _
| _, _, Comparison.Incomparable
| Leq, _, _
| _, Leq, _
| _, _, Leq
| Geq, _, _
| _, Geq, _
| _, _, Geq
| Lt, Gt, _
| Eq, Eq, Eq -> true
| Gt, Gt, Gt
| Gt, Eq, Gt
| Eq, Gt, Gt -> true
| Lt, Lt, Lt
| Lt, Eq, Lt
| Eq, Lt, Lt -> true
| Lt, _, Eq
| Gt, _, Eq
| _, Lt, Eq
| _, Gt, Eq
| (Eq | Lt), Lt, Gt
| (Eq | Gt), Gt, Lt
| Lt, Eq, Gt
| Gt, Eq, Lt
| Eq, Eq, (Lt | Gt)
->
Q.Test.fail_reportf
"comp %a %a %a" Comparison.pp c1 Comparison.pp c2 Comparison.pp c3
end
in
QCheck.Test.make
~name:"multiset_compare_partial_trans" ~long_factor:3 ~count:13_000
(Q.triple gen1 gen1 gen1) prop
let max_seq_correct =
let prop m =
let l1 = M.max_seq partial_ord m |> Iter.map fst |> Iter.to_list in
let l2 = M.to_list m |> List.map fst
|> List.filter (fun x -> M.is_max partial_ord x m) in
if l1=l2 then true
else Q.Test.fail_reportf "@[max_seq %a,@ max %a@]"
CCFormat.Dump.(list int) l1
CCFormat.Dump.(list int) l2
in
Q.Test.make ~name:"multiset_max_seq" ~long_factor:5 ~count:10_000 gen1 prop
let max_is_max =
let pp = CCFormat.to_string (M.pp CCFormat.int) in
let gen = Q.(map M.of_list (list small_int)) in
let gen = Q.set_print pp gen in
let prop m =
let f x y = Comparison.of_total (Pervasives.compare x y) in
let l = M.max f m |> M.to_list |> List.map fst in
List.for_all (fun x -> M.is_max f x m) l
in
Q.Test.make
~name:"multiset_max_l_is_max" ~long_factor:3 ~count:1000
gen prop
let suite =
[ test_max;
test_compare;
test_cardinal_size;
]
let props =
[ compare_and_partial;
compare_partial_sym;
compare_partial_trans;
max_is_max;
max_seq_correct;
]
|
c6bef44debc0e35b41462f8bc9646b12a379dfb7df8b83c73aa159ef1cc46d56 | alanz/ghc-exactprint | Undefined10.hs |
Copyright 2013 - 2015
License : BSD3 ( see BSD3-LICENSE.txt file )
Copyright 2013-2015 Mario Blazevic
License: BSD3 (see BSD3-LICENSE.txt file)
-}
| This module defines the ' FactorialMonoid ' class and some of its instances .
--
{-# LANGUAGE Haskell2010, Trustworthy #-}
module Data.Monoid.Factorial (
-- * Classes
FactorialMonoid(..), StableFactorialMonoid,
-- * Monad function equivalents
mapM, mapM_
)
where
import Prelude hiding (break, drop, dropWhile, foldl, foldMap, foldr, last, length, map, mapM, mapM_, max, min,
null, reverse, span, splitAt, take, takeWhile)
import Control.Arrow (first)
import qualified Control.Monad as Monad
import Data.Monoid (Monoid (..), Dual(..), Sum(..), Product(..), Endo(Endo, appEndo))
import qualified Data.Foldable as Foldable
import qualified Data.List as List
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as LazyByteString
import qualified Data.Text as Text
import qualified Data.Text.Lazy as LazyText
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IntSet
import qualified Data.Map as Map
import qualified Data.Sequence as Sequence
import qualified Data.Set as Set
import qualified Data.Vector as Vector
import Data.Int (Int64)
import Data.Numbers.Primes (primeFactors)
import Data.Monoid.Null (MonoidNull(null), PositiveMonoid)
-- | Class of monoids that can be split into irreducible (/i.e./, atomic or prime) 'factors' in a unique way. Factors of
-- a 'Product' are literally its prime factors:
--
prop > factors ( Product 12 ) = = [ Product 2 , Product 2 , Product 3 ]
--
Factors of a list are /not/ its elements but all its single - item sublists :
--
prop > factors " abc " = = [ " a " , " b " , " c " ]
--
-- The methods of this class satisfy the following laws:
--
-- > mconcat . factors == id
-- > null == List.null . factors
> List.all ( \prime- > factors prime = = [ prime ] ) . factors
> factors = = unfoldr splitPrimePrefix = = List.reverse . ( fmap swap . splitPrimeSuffix )
-- > reverse == mconcat . List.reverse . factors
> primePrefix = = maybe fst . splitPrimePrefix
> = = maybe mempty snd . splitPrimeSuffix
> inits = = List.map mconcat . List.tails . factors
> tails = = List.map mconcat . List.tails . factors
-- > foldl f a == List.foldl f a . factors
-- > foldl' f a == List.foldl' f a . factors
-- > foldr f a == List.foldr f a . factors
> span p m = = ( mconcat l , ) where ( l , r ) = ( factors m )
-- > List.all (List.all (not . pred) . factors) . split pred
-- > mconcat . intersperse prime . split (== prime) == id
> splitAt i m = = ( mconcat l , ) where ( l , r ) = List.splitAt i ( factors m )
> ( ) ( const $ bool Nothing ( Maybe ( ) ) . p ) m = = ( takeWhile p m , , ( ) )
> spanMaybe s0 ( \s m- > Just $ f s m ) m0 = = ( m0 , , foldl f s0 m0 )
> let ( prefix , suffix , s ' ) = s f m
> = foldl ( Just s )
-- > g s m = s >>= flip f m
> in all ( ( Nothing = =) . ) ( inits prefix )
> & & prefix = = last ( filter ( isJust . foldMaybe ) $ inits m )
-- > && Just s' == foldMaybe prefix
-- > && m == prefix <> suffix
--
-- A minimal instance definition must implement 'factors' or 'splitPrimePrefix'. Other methods are provided and should
-- be implemented only for performance reasons.
class MonoidNull m => FactorialMonoid m where
| Returns a list of all prime factors ; inverse of mconcat .
factors :: m -> [m]
| The prime prefix , ' ' if none .
primePrefix :: m -> m
| The prime suffix , ' ' if none .
primeSuffix :: m -> m
| Splits the argument into its prime prefix and the remaining suffix . Returns ' Nothing ' for ' ' .
splitPrimePrefix :: m -> Maybe (m, m)
| Splits the argument into its prime suffix and the remaining prefix . Returns ' Nothing ' for ' ' .
splitPrimeSuffix :: m -> Maybe (m, m)
| Returns the list of all prefixes of the argument , ' ' first .
inits :: m -> [m]
| Returns the list of all suffixes of the argument , ' ' last .
tails :: m -> [m]
-- | Like 'List.foldl' from "Data.List" on the list of 'primes'.
foldl :: (a -> m -> a) -> a -> m -> a
-- | Like 'List.foldl'' from "Data.List" on the list of 'primes'.
foldl' :: (a -> m -> a) -> a -> m -> a
| Like ' List.foldr ' from " Data . List " on the list of ' primes ' .
foldr :: (m -> a -> a) -> a -> m -> a
-- | The 'length' of the list of 'primes'.
length :: m -> Int
-- | Generalizes 'foldMap' from "Data.Foldable", except the function arguments are prime factors rather than the
-- structure elements.
foldMap :: Monoid n => (m -> n) -> m -> n
-- | Like 'List.span' from "Data.List" on the list of 'primes'.
span :: (m -> Bool) -> m -> (m, m)
-- | Equivalent to 'List.break' from "Data.List".
break :: (m -> Bool) -> m -> (m, m)
-- | Splits the monoid into components delimited by prime separators satisfying the given predicate. The primes
-- satisfying the predicate are not a part of the result.
split :: (m -> Bool) -> m -> [m]
| Equivalent to ' ' from " Data . List " .
takeWhile :: (m -> Bool) -> m -> m
-- | Equivalent to 'List.dropWhile' from "Data.List".
dropWhile :: (m -> Bool) -> m -> m
-- | A stateful variant of 'span', threading the result of the test function as long as it returns 'Just'.
spanMaybe :: s -> (s -> m -> Maybe s) -> m -> (m, m, s)
-- | Strict version of 'spanMaybe'.
spanMaybe' :: s -> (s -> m -> Maybe s) -> m -> (m, m, s)
-- | Like 'List.splitAt' from "Data.List" on the list of 'primes'.
splitAt :: Int -> m -> (m, m)
| Equivalent to ' List.drop ' from " Data . List " .
drop :: Int -> m -> m
-- | Equivalent to 'List.take' from "Data.List".
take :: Int -> m -> m
-- | Equivalent to 'List.reverse' from "Data.List".
reverse :: m -> m
factors = List.unfoldr splitPrimePrefix
primePrefix = maybe mempty fst . splitPrimePrefix
primeSuffix = maybe mempty snd . splitPrimeSuffix
splitPrimePrefix x = case factors x
of [] -> Nothing
prefix : rest -> Just (prefix, mconcat rest)
splitPrimeSuffix x = case factors x
of [] -> Nothing
fs -> Just (mconcat (List.init fs), List.last fs)
inits = foldr (\m l-> mempty : List.map (mappend m) l) [mempty]
tails m = m : maybe [] (tails . snd) (splitPrimePrefix m)
foldl f f0 = List.foldl f f0 . factors
foldl' f f0 = List.foldl' f f0 . factors
foldr f f0 = List.foldr f f0 . factors
length = List.length . factors
foldMap f = foldr (mappend . f) mempty
span p m0 = spanAfter id m0
where spanAfter f m = case splitPrimePrefix m
of Just (prime, rest) | p prime -> spanAfter (f . mappend prime) rest
_ -> (f mempty, m)
break = span . (not .)
spanMaybe s0 f m0 = spanAfter id s0 m0
where spanAfter g s m = case splitPrimePrefix m
of Just (prime, rest) | Just s' <- f s prime -> spanAfter (g . mappend prime) s' rest
| otherwise -> (g mempty, m, s)
Nothing -> (m0, m, s)
spanMaybe' s0 f m0 = spanAfter id s0 m0
where spanAfter g s m = seq s $
case splitPrimePrefix m
of Just (prime, rest) | Just s' <- f s prime -> spanAfter (g . mappend prime) s' rest
| otherwise -> (g mempty, m, s)
Nothing -> (m0, m, s)
split p m = prefix : splitRest
where (prefix, rest) = break p m
splitRest = case splitPrimePrefix rest
of Nothing -> []
Just (_, tl) -> split p tl
takeWhile p = fst . span p
dropWhile p = snd . span p
splitAt n0 m0 | n0 <= 0 = (mempty, m0)
| otherwise = split' n0 id m0
where split' 0 f m = (f mempty, m)
split' n f m = case splitPrimePrefix m
of Nothing -> (f mempty, m)
Just (prime, rest) -> split' (pred n) (f . mappend prime) rest
drop n p = snd (splitAt n p)
take n p = fst (splitAt n p)
reverse = mconcat . List.reverse . factors
# MINIMAL factors | splitPrimePrefix #
| A subclass of ' FactorialMonoid ' whose instances satisfy this additional law :
--
-- > factors (a <> b) == factors a <> factors b
class (FactorialMonoid m, PositiveMonoid m) => StableFactorialMonoid m
instance FactorialMonoid () where
factors () = []
primePrefix () = ()
primeSuffix () = ()
splitPrimePrefix () = Nothing
splitPrimeSuffix () = Nothing
length () = 0
reverse = id
instance FactorialMonoid a => FactorialMonoid (Dual a) where
factors (Dual a) = fmap Dual (reverse $ factors a)
length (Dual a) = length a
primePrefix (Dual a) = Dual (primeSuffix a)
primeSuffix (Dual a) = Dual (primePrefix a)
splitPrimePrefix (Dual a) = case splitPrimeSuffix a
of Nothing -> Nothing
Just (p, s) -> Just (Dual s, Dual p)
splitPrimeSuffix (Dual a) = case splitPrimePrefix a
of Nothing -> Nothing
Just (p, s) -> Just (Dual s, Dual p)
inits (Dual a) = fmap Dual (reverse $ tails a)
tails (Dual a) = fmap Dual (reverse $ inits a)
reverse (Dual a) = Dual (reverse a)
instance (Integral a, Eq a) => FactorialMonoid (Sum a) where
primePrefix (Sum a) = Sum (signum a )
primeSuffix = primePrefix
splitPrimePrefix (Sum 0) = Nothing
splitPrimePrefix (Sum a) = Just (Sum (signum a), Sum (a - signum a))
splitPrimeSuffix (Sum 0) = Nothing
splitPrimeSuffix (Sum a) = Just (Sum (a - signum a), Sum (signum a))
length (Sum a) = abs (fromIntegral a)
reverse = id
instance Integral a => FactorialMonoid (Product a) where
factors (Product a) = List.map Product (primeFactors a)
reverse = id
instance FactorialMonoid a => FactorialMonoid (Maybe a) where
factors Nothing = []
factors (Just a) | null a = [Just a]
| otherwise = List.map Just (factors a)
length Nothing = 0
length (Just a) | null a = 1
| otherwise = length a
reverse = fmap reverse
instance (FactorialMonoid a, FactorialMonoid b) => FactorialMonoid (a, b) where
factors (a, b) = List.map (\a1-> (a1, mempty)) (factors a) ++ List.map ((,) mempty) (factors b)
primePrefix (a, b) | null a = (a, primePrefix b)
| otherwise = (primePrefix a, mempty)
primeSuffix (a, b) | null b = (primeSuffix a, b)
| otherwise = (mempty, primeSuffix b)
splitPrimePrefix (a, b) = case (splitPrimePrefix a, splitPrimePrefix b)
of (Just (ap, as), _) -> Just ((ap, mempty), (as, b))
(Nothing, Just (bp, bs)) -> Just ((a, bp), (a, bs))
(Nothing, Nothing) -> Nothing
splitPrimeSuffix (a, b) = case (splitPrimeSuffix a, splitPrimeSuffix b)
of (_, Just (bp, bs)) -> Just ((a, bp), (mempty, bs))
(Just (ap, as), Nothing) -> Just ((ap, b), (as, b))
(Nothing, Nothing) -> Nothing
inits (a, b) = List.map (flip (,) mempty) (inits a) ++ List.map ((,) a) (List.tail $ inits b)
tails (a, b) = List.map (flip (,) b) (tails a) ++ List.map ((,) mempty) (List.tail $ tails b)
foldl f a0 (x, y) = foldl f2 (foldl f1 a0 x) y
where f1 a = f a . fromFst
f2 a = f a . fromSnd
foldl' f a0 (x, y) = a' `seq` foldl' f2 a' y
where f1 a = f a . fromFst
f2 a = f a . fromSnd
a' = foldl' f1 a0 x
foldr f a (x, y) = foldr (f . fromFst) (foldr (f . fromSnd) a y) x
foldMap f (x, y) = foldMap (f . fromFst) x `mappend` foldMap (f . fromSnd) y
length (a, b) = length a + length b
span p (x, y) = ((xp, yp), (xs, ys))
where (xp, xs) = span (p . fromFst) x
(yp, ys) | null xs = span (p . fromSnd) y
| otherwise = (mempty, y)
spanMaybe s0 f (x, y) | null xs = ((xp, yp), (xs, ys), s2)
| otherwise = ((xp, mempty), (xs, y), s1)
where (xp, xs, s1) = spanMaybe s0 (\s-> f s . fromFst) x
(yp, ys, s2) = spanMaybe s1 (\s-> f s . fromSnd) y
spanMaybe' s0 f (x, y) | null xs = ((xp, yp), (xs, ys), s2)
| otherwise = ((xp, mempty), (xs, y), s1)
where (xp, xs, s1) = spanMaybe' s0 (\s-> f s . fromFst) x
(yp, ys, s2) = spanMaybe' s1 (\s-> f s . fromSnd) y
split p (x0, y0) = fst $ List.foldr combine (ys, False) xs
where xs = List.map fromFst $ split (p . fromFst) x0
ys = List.map fromSnd $ split (p . fromSnd) y0
combine x (~(y:rest), False) = (mappend x y : rest, True)
combine x (rest, True) = (x:rest, True)
splitAt n (x, y) = ((xp, yp), (xs, ys))
where (xp, xs) = splitAt n x
(yp, ys) | null xs = splitAt (n - length x) y
| otherwise = (mempty, y)
reverse (a, b) = (reverse a, reverse b)
# INLINE fromFst #
fromFst :: Monoid b => a -> (a, b)
fromFst a = (a, mempty)
# INLINE fromSnd #
fromSnd :: Monoid a => b -> (a, b)
fromSnd b = (mempty, b)
instance FactorialMonoid [x] where
factors xs = List.map (:[]) xs
primePrefix [] = []
primePrefix (x:_) = [x]
primeSuffix [] = []
primeSuffix xs = [List.last xs]
splitPrimePrefix [] = Nothing
splitPrimePrefix (x:xs) = Just ([x], xs)
splitPrimeSuffix [] = Nothing
splitPrimeSuffix xs = Just (splitLast id xs)
where splitLast f last@[_] = (f [], last)
splitLast f ~(x:rest) = splitLast (f . (x:)) rest
inits = List.inits
tails = List.tails
foldl _ a [] = a
foldl f a (x:xs) = foldl f (f a [x]) xs
foldl' _ a [] = a
foldl' f a (x:xs) = let a' = f a [x] in a' `seq` foldl' f a' xs
foldr _ f0 [] = f0
foldr f f0 (x:xs) = f [x] (foldr f f0 xs)
length = List.length
foldMap f = mconcat . List.map (f . (:[]))
break f = List.break (f . (:[]))
span f = List.span (f . (:[]))
dropWhile f = List.dropWhile (f . (:[]))
takeWhile f = List.takeWhile (f . (:[]))
spanMaybe s0 f l = (prefix' [], suffix' [], s')
where (prefix', suffix', s', _) = List.foldl' g (id, id, s0, True) l
g (prefix, suffix, s1, live) x | live, Just s2 <- f s1 [x] = (prefix . (x:), id, s2, True)
| otherwise = (prefix, suffix . (x:), s1, False)
spanMaybe' s0 f l = (prefix' [], suffix' [], s')
where (prefix', suffix', s', _) = List.foldl' g (id, id, s0, True) l
g (prefix, suffix, s1, live) x | live, Just s2 <- f s1 [x] = seq s2 $ (prefix . (x:), id, s2, True)
| otherwise = (prefix, suffix . (x:), s1, False)
splitAt = List.splitAt
drop = List.drop
take = List.take
reverse = List.reverse
instance FactorialMonoid ByteString.ByteString where
factors x = factorize (ByteString.length x) x
where factorize 0 _ = []
factorize n xs = xs1 : factorize (pred n) xs'
where (xs1, xs') = ByteString.splitAt 1 xs
primePrefix = ByteString.take 1
primeSuffix x = ByteString.drop (ByteString.length x - 1) x
splitPrimePrefix x = if ByteString.null x then Nothing else Just (ByteString.splitAt 1 x)
splitPrimeSuffix x = if ByteString.null x then Nothing else Just (ByteString.splitAt (ByteString.length x - 1) x)
inits = ByteString.inits
tails = ByteString.tails
foldl f = ByteString.foldl f'
where f' a byte = f a (ByteString.singleton byte)
foldl' f = ByteString.foldl' f'
where f' a byte = f a (ByteString.singleton byte)
foldr f = ByteString.foldr (f . ByteString.singleton)
break f = ByteString.break (f . ByteString.singleton)
span f = ByteString.span (f . ByteString.singleton)
spanMaybe s0 f b = case ByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- ByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s) | Just s' <- f s (ByteString.singleton w) = let i' = succ i :: Int in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f b = case ByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- ByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s) | Just s' <- f s (ByteString.singleton w) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
dropWhile f = ByteString.dropWhile (f . ByteString.singleton)
takeWhile f = ByteString.takeWhile (f . ByteString.singleton)
length = ByteString.length
split f = ByteString.splitWith f'
where f' = f . ByteString.singleton
splitAt = ByteString.splitAt
drop = ByteString.drop
take = ByteString.take
reverse = ByteString.reverse
instance FactorialMonoid LazyByteString.ByteString where
factors x = factorize (LazyByteString.length x) x
where factorize 0 _ = []
factorize n xs = xs1 : factorize (pred n) xs'
where (xs1, xs') = LazyByteString.splitAt 1 xs
primePrefix = LazyByteString.take 1
primeSuffix x = LazyByteString.drop (LazyByteString.length x - 1) x
splitPrimePrefix x = if LazyByteString.null x then Nothing
else Just (LazyByteString.splitAt 1 x)
splitPrimeSuffix x = if LazyByteString.null x then Nothing
else Just (LazyByteString.splitAt (LazyByteString.length x - 1) x)
inits = LazyByteString.inits
tails = LazyByteString.tails
foldl f = LazyByteString.foldl f'
where f' a byte = f a (LazyByteString.singleton byte)
foldl' f = LazyByteString.foldl' f'
where f' a byte = f a (LazyByteString.singleton byte)
foldr f = LazyByteString.foldr f'
where f' byte a = f (LazyByteString.singleton byte) a
length = fromIntegral . LazyByteString.length
break f = LazyByteString.break (f . LazyByteString.singleton)
span f = LazyByteString.span (f . LazyByteString.singleton)
spanMaybe s0 f b = case LazyByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- LazyByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s) | Just s' <- f s (LazyByteString.singleton w) = let i' = succ i :: Int64 in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f b = case LazyByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- LazyByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s)
| Just s' <- f s (LazyByteString.singleton w) = let i' = succ i :: Int64 in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
dropWhile f = LazyByteString.dropWhile (f . LazyByteString.singleton)
takeWhile f = LazyByteString.takeWhile (f . LazyByteString.singleton)
split f = LazyByteString.splitWith f'
where f' = f . LazyByteString.singleton
splitAt = LazyByteString.splitAt . fromIntegral
drop n = LazyByteString.drop (fromIntegral n)
take n = LazyByteString.take (fromIntegral n)
reverse = LazyByteString.reverse
instance FactorialMonoid Text.Text where
factors = Text.chunksOf 1
primePrefix = Text.take 1
primeSuffix x = if Text.null x then Text.empty else Text.singleton (Text.last x)
splitPrimePrefix = fmap (first Text.singleton) . Text.uncons
splitPrimeSuffix x = if Text.null x then Nothing else Just (Text.init x, Text.singleton (Text.last x))
inits = Text.inits
tails = Text.tails
foldl f = Text.foldl f'
where f' a char = f a (Text.singleton char)
foldl' f = Text.foldl' f'
where f' a char = f a (Text.singleton char)
foldr f = Text.foldr f'
where f' char a = f (Text.singleton char) a
length = Text.length
span f = Text.span (f . Text.singleton)
break f = Text.break (f . Text.singleton)
dropWhile f = Text.dropWhile (f . Text.singleton)
takeWhile f = Text.takeWhile (f . Text.singleton)
spanMaybe s0 f t = case Text.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- Text.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (Text.singleton c) = let i' = succ i :: Int in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f t = case Text.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- Text.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (Text.singleton c) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
split f = Text.split f'
where f' = f . Text.singleton
splitAt = Text.splitAt
drop = Text.drop
take = Text.take
reverse = Text.reverse
instance FactorialMonoid LazyText.Text where
factors = LazyText.chunksOf 1
primePrefix = LazyText.take 1
primeSuffix x = if LazyText.null x then LazyText.empty else LazyText.singleton (LazyText.last x)
splitPrimePrefix = fmap (first LazyText.singleton) . LazyText.uncons
splitPrimeSuffix x = if LazyText.null x
then Nothing
else Just (LazyText.init x, LazyText.singleton (LazyText.last x))
inits = LazyText.inits
tails = LazyText.tails
foldl f = LazyText.foldl f'
where f' a char = f a (LazyText.singleton char)
foldl' f = LazyText.foldl' f'
where f' a char = f a (LazyText.singleton char)
foldr f = LazyText.foldr f'
where f' char a = f (LazyText.singleton char) a
length = fromIntegral . LazyText.length
span f = LazyText.span (f . LazyText.singleton)
break f = LazyText.break (f . LazyText.singleton)
dropWhile f = LazyText.dropWhile (f . LazyText.singleton)
takeWhile f = LazyText.takeWhile (f . LazyText.singleton)
spanMaybe s0 f t = case LazyText.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- LazyText.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (LazyText.singleton c) = let i' = succ i :: Int64 in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f t = case LazyText.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- LazyText.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (LazyText.singleton c) = let i' = succ i :: Int64 in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
split f = LazyText.split f'
where f' = f . LazyText.singleton
splitAt = LazyText.splitAt . fromIntegral
drop n = LazyText.drop (fromIntegral n)
take n = LazyText.take (fromIntegral n)
reverse = LazyText.reverse
instance Ord k => FactorialMonoid (Map.Map k v) where
factors = List.map (uncurry Map.singleton) . Map.toAscList
primePrefix map | Map.null map = map
| otherwise = uncurry Map.singleton $ Map.findMin map
primeSuffix map | Map.null map = map
| otherwise = uncurry Map.singleton $ Map.findMax map
splitPrimePrefix = fmap singularize . Map.minViewWithKey
where singularize ((k, v), rest) = (Map.singleton k v, rest)
splitPrimeSuffix = fmap singularize . Map.maxViewWithKey
where singularize ((k, v), rest) = (rest, Map.singleton k v)
foldl f = Map.foldlWithKey f'
where f' a k v = f a (Map.singleton k v)
foldl' f = Map.foldlWithKey' f'
where f' a k v = f a (Map.singleton k v)
foldr f = Map.foldrWithKey f'
where f' k v a = f (Map.singleton k v) a
length = Map.size
reverse = id
instance FactorialMonoid (IntMap.IntMap a) where
factors = List.map (uncurry IntMap.singleton) . IntMap.toAscList
primePrefix map | IntMap.null map = map
| otherwise = uncurry IntMap.singleton $ IntMap.findMin map
primeSuffix map | IntMap.null map = map
| otherwise = uncurry IntMap.singleton $ IntMap.findMax map
splitPrimePrefix = fmap singularize . IntMap.minViewWithKey
where singularize ((k, v), rest) = (IntMap.singleton k v, rest)
splitPrimeSuffix = fmap singularize . IntMap.maxViewWithKey
where singularize ((k, v), rest) = (rest, IntMap.singleton k v)
foldl f = IntMap.foldlWithKey f'
where f' a k v = f a (IntMap.singleton k v)
foldl' f = IntMap.foldlWithKey' f'
where f' a k v = f a (IntMap.singleton k v)
foldr f = IntMap.foldrWithKey f'
where f' k v a = f (IntMap.singleton k v) a
length = IntMap.size
reverse = id
instance FactorialMonoid IntSet.IntSet where
factors = List.map IntSet.singleton . IntSet.toAscList
primePrefix set | IntSet.null set = set
| otherwise = IntSet.singleton $ IntSet.findMin set
primeSuffix set | IntSet.null set = set
| otherwise = IntSet.singleton $ IntSet.findMax set
splitPrimePrefix = fmap singularize . IntSet.minView
where singularize (min, rest) = (IntSet.singleton min, rest)
splitPrimeSuffix = fmap singularize . IntSet.maxView
where singularize (max, rest) = (rest, IntSet.singleton max)
foldl f = IntSet.foldl f'
where f' a b = f a (IntSet.singleton b)
foldl' f = IntSet.foldl' f'
where f' a b = f a (IntSet.singleton b)
foldr f = IntSet.foldr f'
where f' a b = f (IntSet.singleton a) b
length = IntSet.size
reverse = id
instance FactorialMonoid (Sequence.Seq a) where
factors = List.map Sequence.singleton . Foldable.toList
primePrefix = Sequence.take 1
primeSuffix q = Sequence.drop (Sequence.length q - 1) q
splitPrimePrefix q = case Sequence.viewl q
of Sequence.EmptyL -> Nothing
hd Sequence.:< rest -> Just (Sequence.singleton hd, rest)
splitPrimeSuffix q = case Sequence.viewr q
of Sequence.EmptyR -> Nothing
rest Sequence.:> last -> Just (rest, Sequence.singleton last)
inits = Foldable.toList . Sequence.inits
tails = Foldable.toList . Sequence.tails
foldl f = Foldable.foldl f'
where f' a b = f a (Sequence.singleton b)
foldl' f = Foldable.foldl' f'
where f' a b = f a (Sequence.singleton b)
foldr f = Foldable.foldr f'
where f' a b = f (Sequence.singleton a) b
span f = Sequence.spanl (f . Sequence.singleton)
break f = Sequence.breakl (f . Sequence.singleton)
dropWhile f = Sequence.dropWhileL (f . Sequence.singleton)
takeWhile f = Sequence.takeWhileL (f . Sequence.singleton)
spanMaybe s0 f b = case Foldable.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- Sequence.splitAt i b -> (prefix, suffix, s')
where g x cont (i, s) | Just s' <- f s (Sequence.singleton x) = let i' = succ i :: Int in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f b = case Foldable.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- Sequence.splitAt i b -> (prefix, suffix, s')
where g x cont (i, s) | Just s' <- f s (Sequence.singleton x) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
splitAt = Sequence.splitAt
drop = Sequence.drop
take = Sequence.take
length = Sequence.length
reverse = Sequence.reverse
instance Ord a => FactorialMonoid (Set.Set a) where
factors = List.map Set.singleton . Set.toAscList
primePrefix set | Set.null set = set
| otherwise = Set.singleton $ Set.findMin set
primeSuffix set | Set.null set = set
| otherwise = Set.singleton $ Set.findMax set
splitPrimePrefix = fmap singularize . Set.minView
where singularize (min, rest) = (Set.singleton min, rest)
splitPrimeSuffix = fmap singularize . Set.maxView
where singularize (max, rest) = (rest, Set.singleton max)
foldl f = Foldable.foldl f'
where f' a b = f a (Set.singleton b)
foldl' f = Foldable.foldl' f'
where f' a b = f a (Set.singleton b)
foldr f = Foldable.foldr f'
where f' a b = f (Set.singleton a) b
length = Set.size
reverse = id
instance FactorialMonoid (Vector.Vector a) where
factors x = factorize (Vector.length x) x
where factorize 0 _ = []
factorize n xs = xs1 : factorize (pred n) xs'
where (xs1, xs') = Vector.splitAt 1 xs
primePrefix = Vector.take 1
primeSuffix x = Vector.drop (Vector.length x - 1) x
splitPrimePrefix x = if Vector.null x then Nothing else Just (Vector.splitAt 1 x)
splitPrimeSuffix x = if Vector.null x then Nothing else Just (Vector.splitAt (Vector.length x - 1) x)
inits x0 = initsWith x0 []
where initsWith x rest | Vector.null x = x:rest
| otherwise = initsWith (Vector.unsafeInit x) (x:rest)
tails x = x : if Vector.null x then [] else tails (Vector.unsafeTail x)
foldl f = Vector.foldl f'
where f' a byte = f a (Vector.singleton byte)
foldl' f = Vector.foldl' f'
where f' a byte = f a (Vector.singleton byte)
foldr f = Vector.foldr f'
where f' byte a = f (Vector.singleton byte) a
break f = Vector.break (f . Vector.singleton)
span f = Vector.span (f . Vector.singleton)
dropWhile f = Vector.dropWhile (f . Vector.singleton)
takeWhile f = Vector.takeWhile (f . Vector.singleton)
spanMaybe s0 f v = case Vector.ifoldr g Left v s0
of Left s' -> (v, Vector.empty, s')
Right (i, s') | (prefix, suffix) <- Vector.splitAt i v -> (prefix, suffix, s')
where g i x cont s | Just s' <- f s (Vector.singleton x) = cont s'
| otherwise = Right (i, s)
spanMaybe' s0 f v = case Vector.ifoldr' g Left v s0
of Left s' -> (v, Vector.empty, s')
Right (i, s') | (prefix, suffix) <- Vector.splitAt i v -> (prefix, suffix, s')
where g i x cont s | Just s' <- f s (Vector.singleton x) = seq s' (cont s')
| otherwise = Right (i, s)
splitAt = Vector.splitAt
drop = Vector.drop
take = Vector.take
length = Vector.length
reverse = Vector.reverse
instance StableFactorialMonoid ()
instance StableFactorialMonoid a => StableFactorialMonoid (Dual a)
instance StableFactorialMonoid [x]
instance StableFactorialMonoid ByteString.ByteString
instance StableFactorialMonoid LazyByteString.ByteString
instance StableFactorialMonoid Text.Text
instance StableFactorialMonoid LazyText.Text
instance StableFactorialMonoid (Sequence.Seq a)
instance StableFactorialMonoid (Vector.Vector a)
-- | A 'Monad.mapM' equivalent.
mapM :: (FactorialMonoid a, Monoid b, Monad m) => (a -> m b) -> a -> m b
mapM f = ($ return mempty) . appEndo . foldMap (Endo . Monad.liftM2 mappend . f)
-- | A 'Monad.mapM_' equivalent.
mapM_ :: (FactorialMonoid a, Monad m) => (a -> m b) -> a -> m ()
mapM_ f = foldr ((>>) . f) (return ())
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc710/Undefined10.hs | haskell |
# LANGUAGE Haskell2010, Trustworthy #
* Classes
* Monad function equivalents
| Class of monoids that can be split into irreducible (/i.e./, atomic or prime) 'factors' in a unique way. Factors of
a 'Product' are literally its prime factors:
The methods of this class satisfy the following laws:
> mconcat . factors == id
> null == List.null . factors
> reverse == mconcat . List.reverse . factors
> foldl f a == List.foldl f a . factors
> foldl' f a == List.foldl' f a . factors
> foldr f a == List.foldr f a . factors
> List.all (List.all (not . pred) . factors) . split pred
> mconcat . intersperse prime . split (== prime) == id
> g s m = s >>= flip f m
> && Just s' == foldMaybe prefix
> && m == prefix <> suffix
A minimal instance definition must implement 'factors' or 'splitPrimePrefix'. Other methods are provided and should
be implemented only for performance reasons.
| Like 'List.foldl' from "Data.List" on the list of 'primes'.
| Like 'List.foldl'' from "Data.List" on the list of 'primes'.
| The 'length' of the list of 'primes'.
| Generalizes 'foldMap' from "Data.Foldable", except the function arguments are prime factors rather than the
structure elements.
| Like 'List.span' from "Data.List" on the list of 'primes'.
| Equivalent to 'List.break' from "Data.List".
| Splits the monoid into components delimited by prime separators satisfying the given predicate. The primes
satisfying the predicate are not a part of the result.
| Equivalent to 'List.dropWhile' from "Data.List".
| A stateful variant of 'span', threading the result of the test function as long as it returns 'Just'.
| Strict version of 'spanMaybe'.
| Like 'List.splitAt' from "Data.List" on the list of 'primes'.
| Equivalent to 'List.take' from "Data.List".
| Equivalent to 'List.reverse' from "Data.List".
> factors (a <> b) == factors a <> factors b
| A 'Monad.mapM' equivalent.
| A 'Monad.mapM_' equivalent. |
Copyright 2013 - 2015
License : BSD3 ( see BSD3-LICENSE.txt file )
Copyright 2013-2015 Mario Blazevic
License: BSD3 (see BSD3-LICENSE.txt file)
-}
| This module defines the ' FactorialMonoid ' class and some of its instances .
module Data.Monoid.Factorial (
FactorialMonoid(..), StableFactorialMonoid,
mapM, mapM_
)
where
import Prelude hiding (break, drop, dropWhile, foldl, foldMap, foldr, last, length, map, mapM, mapM_, max, min,
null, reverse, span, splitAt, take, takeWhile)
import Control.Arrow (first)
import qualified Control.Monad as Monad
import Data.Monoid (Monoid (..), Dual(..), Sum(..), Product(..), Endo(Endo, appEndo))
import qualified Data.Foldable as Foldable
import qualified Data.List as List
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as LazyByteString
import qualified Data.Text as Text
import qualified Data.Text.Lazy as LazyText
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IntSet
import qualified Data.Map as Map
import qualified Data.Sequence as Sequence
import qualified Data.Set as Set
import qualified Data.Vector as Vector
import Data.Int (Int64)
import Data.Numbers.Primes (primeFactors)
import Data.Monoid.Null (MonoidNull(null), PositiveMonoid)
prop > factors ( Product 12 ) = = [ Product 2 , Product 2 , Product 3 ]
Factors of a list are /not/ its elements but all its single - item sublists :
prop > factors " abc " = = [ " a " , " b " , " c " ]
> List.all ( \prime- > factors prime = = [ prime ] ) . factors
> factors = = unfoldr splitPrimePrefix = = List.reverse . ( fmap swap . splitPrimeSuffix )
> primePrefix = = maybe fst . splitPrimePrefix
> = = maybe mempty snd . splitPrimeSuffix
> inits = = List.map mconcat . List.tails . factors
> tails = = List.map mconcat . List.tails . factors
> span p m = = ( mconcat l , ) where ( l , r ) = ( factors m )
> splitAt i m = = ( mconcat l , ) where ( l , r ) = List.splitAt i ( factors m )
> ( ) ( const $ bool Nothing ( Maybe ( ) ) . p ) m = = ( takeWhile p m , , ( ) )
> spanMaybe s0 ( \s m- > Just $ f s m ) m0 = = ( m0 , , foldl f s0 m0 )
> let ( prefix , suffix , s ' ) = s f m
> = foldl ( Just s )
> in all ( ( Nothing = =) . ) ( inits prefix )
> & & prefix = = last ( filter ( isJust . foldMaybe ) $ inits m )
class MonoidNull m => FactorialMonoid m where
| Returns a list of all prime factors ; inverse of mconcat .
factors :: m -> [m]
| The prime prefix , ' ' if none .
primePrefix :: m -> m
| The prime suffix , ' ' if none .
primeSuffix :: m -> m
| Splits the argument into its prime prefix and the remaining suffix . Returns ' Nothing ' for ' ' .
splitPrimePrefix :: m -> Maybe (m, m)
| Splits the argument into its prime suffix and the remaining prefix . Returns ' Nothing ' for ' ' .
splitPrimeSuffix :: m -> Maybe (m, m)
| Returns the list of all prefixes of the argument , ' ' first .
inits :: m -> [m]
| Returns the list of all suffixes of the argument , ' ' last .
tails :: m -> [m]
foldl :: (a -> m -> a) -> a -> m -> a
foldl' :: (a -> m -> a) -> a -> m -> a
| Like ' List.foldr ' from " Data . List " on the list of ' primes ' .
foldr :: (m -> a -> a) -> a -> m -> a
length :: m -> Int
foldMap :: Monoid n => (m -> n) -> m -> n
span :: (m -> Bool) -> m -> (m, m)
break :: (m -> Bool) -> m -> (m, m)
split :: (m -> Bool) -> m -> [m]
| Equivalent to ' ' from " Data . List " .
takeWhile :: (m -> Bool) -> m -> m
dropWhile :: (m -> Bool) -> m -> m
spanMaybe :: s -> (s -> m -> Maybe s) -> m -> (m, m, s)
spanMaybe' :: s -> (s -> m -> Maybe s) -> m -> (m, m, s)
splitAt :: Int -> m -> (m, m)
| Equivalent to ' List.drop ' from " Data . List " .
drop :: Int -> m -> m
take :: Int -> m -> m
reverse :: m -> m
factors = List.unfoldr splitPrimePrefix
primePrefix = maybe mempty fst . splitPrimePrefix
primeSuffix = maybe mempty snd . splitPrimeSuffix
splitPrimePrefix x = case factors x
of [] -> Nothing
prefix : rest -> Just (prefix, mconcat rest)
splitPrimeSuffix x = case factors x
of [] -> Nothing
fs -> Just (mconcat (List.init fs), List.last fs)
inits = foldr (\m l-> mempty : List.map (mappend m) l) [mempty]
tails m = m : maybe [] (tails . snd) (splitPrimePrefix m)
foldl f f0 = List.foldl f f0 . factors
foldl' f f0 = List.foldl' f f0 . factors
foldr f f0 = List.foldr f f0 . factors
length = List.length . factors
foldMap f = foldr (mappend . f) mempty
span p m0 = spanAfter id m0
where spanAfter f m = case splitPrimePrefix m
of Just (prime, rest) | p prime -> spanAfter (f . mappend prime) rest
_ -> (f mempty, m)
break = span . (not .)
spanMaybe s0 f m0 = spanAfter id s0 m0
where spanAfter g s m = case splitPrimePrefix m
of Just (prime, rest) | Just s' <- f s prime -> spanAfter (g . mappend prime) s' rest
| otherwise -> (g mempty, m, s)
Nothing -> (m0, m, s)
spanMaybe' s0 f m0 = spanAfter id s0 m0
where spanAfter g s m = seq s $
case splitPrimePrefix m
of Just (prime, rest) | Just s' <- f s prime -> spanAfter (g . mappend prime) s' rest
| otherwise -> (g mempty, m, s)
Nothing -> (m0, m, s)
split p m = prefix : splitRest
where (prefix, rest) = break p m
splitRest = case splitPrimePrefix rest
of Nothing -> []
Just (_, tl) -> split p tl
takeWhile p = fst . span p
dropWhile p = snd . span p
splitAt n0 m0 | n0 <= 0 = (mempty, m0)
| otherwise = split' n0 id m0
where split' 0 f m = (f mempty, m)
split' n f m = case splitPrimePrefix m
of Nothing -> (f mempty, m)
Just (prime, rest) -> split' (pred n) (f . mappend prime) rest
drop n p = snd (splitAt n p)
take n p = fst (splitAt n p)
reverse = mconcat . List.reverse . factors
# MINIMAL factors | splitPrimePrefix #
| A subclass of ' FactorialMonoid ' whose instances satisfy this additional law :
class (FactorialMonoid m, PositiveMonoid m) => StableFactorialMonoid m
instance FactorialMonoid () where
factors () = []
primePrefix () = ()
primeSuffix () = ()
splitPrimePrefix () = Nothing
splitPrimeSuffix () = Nothing
length () = 0
reverse = id
instance FactorialMonoid a => FactorialMonoid (Dual a) where
factors (Dual a) = fmap Dual (reverse $ factors a)
length (Dual a) = length a
primePrefix (Dual a) = Dual (primeSuffix a)
primeSuffix (Dual a) = Dual (primePrefix a)
splitPrimePrefix (Dual a) = case splitPrimeSuffix a
of Nothing -> Nothing
Just (p, s) -> Just (Dual s, Dual p)
splitPrimeSuffix (Dual a) = case splitPrimePrefix a
of Nothing -> Nothing
Just (p, s) -> Just (Dual s, Dual p)
inits (Dual a) = fmap Dual (reverse $ tails a)
tails (Dual a) = fmap Dual (reverse $ inits a)
reverse (Dual a) = Dual (reverse a)
instance (Integral a, Eq a) => FactorialMonoid (Sum a) where
primePrefix (Sum a) = Sum (signum a )
primeSuffix = primePrefix
splitPrimePrefix (Sum 0) = Nothing
splitPrimePrefix (Sum a) = Just (Sum (signum a), Sum (a - signum a))
splitPrimeSuffix (Sum 0) = Nothing
splitPrimeSuffix (Sum a) = Just (Sum (a - signum a), Sum (signum a))
length (Sum a) = abs (fromIntegral a)
reverse = id
instance Integral a => FactorialMonoid (Product a) where
factors (Product a) = List.map Product (primeFactors a)
reverse = id
instance FactorialMonoid a => FactorialMonoid (Maybe a) where
factors Nothing = []
factors (Just a) | null a = [Just a]
| otherwise = List.map Just (factors a)
length Nothing = 0
length (Just a) | null a = 1
| otherwise = length a
reverse = fmap reverse
instance (FactorialMonoid a, FactorialMonoid b) => FactorialMonoid (a, b) where
factors (a, b) = List.map (\a1-> (a1, mempty)) (factors a) ++ List.map ((,) mempty) (factors b)
primePrefix (a, b) | null a = (a, primePrefix b)
| otherwise = (primePrefix a, mempty)
primeSuffix (a, b) | null b = (primeSuffix a, b)
| otherwise = (mempty, primeSuffix b)
splitPrimePrefix (a, b) = case (splitPrimePrefix a, splitPrimePrefix b)
of (Just (ap, as), _) -> Just ((ap, mempty), (as, b))
(Nothing, Just (bp, bs)) -> Just ((a, bp), (a, bs))
(Nothing, Nothing) -> Nothing
splitPrimeSuffix (a, b) = case (splitPrimeSuffix a, splitPrimeSuffix b)
of (_, Just (bp, bs)) -> Just ((a, bp), (mempty, bs))
(Just (ap, as), Nothing) -> Just ((ap, b), (as, b))
(Nothing, Nothing) -> Nothing
inits (a, b) = List.map (flip (,) mempty) (inits a) ++ List.map ((,) a) (List.tail $ inits b)
tails (a, b) = List.map (flip (,) b) (tails a) ++ List.map ((,) mempty) (List.tail $ tails b)
foldl f a0 (x, y) = foldl f2 (foldl f1 a0 x) y
where f1 a = f a . fromFst
f2 a = f a . fromSnd
foldl' f a0 (x, y) = a' `seq` foldl' f2 a' y
where f1 a = f a . fromFst
f2 a = f a . fromSnd
a' = foldl' f1 a0 x
foldr f a (x, y) = foldr (f . fromFst) (foldr (f . fromSnd) a y) x
foldMap f (x, y) = foldMap (f . fromFst) x `mappend` foldMap (f . fromSnd) y
length (a, b) = length a + length b
span p (x, y) = ((xp, yp), (xs, ys))
where (xp, xs) = span (p . fromFst) x
(yp, ys) | null xs = span (p . fromSnd) y
| otherwise = (mempty, y)
spanMaybe s0 f (x, y) | null xs = ((xp, yp), (xs, ys), s2)
| otherwise = ((xp, mempty), (xs, y), s1)
where (xp, xs, s1) = spanMaybe s0 (\s-> f s . fromFst) x
(yp, ys, s2) = spanMaybe s1 (\s-> f s . fromSnd) y
spanMaybe' s0 f (x, y) | null xs = ((xp, yp), (xs, ys), s2)
| otherwise = ((xp, mempty), (xs, y), s1)
where (xp, xs, s1) = spanMaybe' s0 (\s-> f s . fromFst) x
(yp, ys, s2) = spanMaybe' s1 (\s-> f s . fromSnd) y
split p (x0, y0) = fst $ List.foldr combine (ys, False) xs
where xs = List.map fromFst $ split (p . fromFst) x0
ys = List.map fromSnd $ split (p . fromSnd) y0
combine x (~(y:rest), False) = (mappend x y : rest, True)
combine x (rest, True) = (x:rest, True)
splitAt n (x, y) = ((xp, yp), (xs, ys))
where (xp, xs) = splitAt n x
(yp, ys) | null xs = splitAt (n - length x) y
| otherwise = (mempty, y)
reverse (a, b) = (reverse a, reverse b)
# INLINE fromFst #
fromFst :: Monoid b => a -> (a, b)
fromFst a = (a, mempty)
# INLINE fromSnd #
fromSnd :: Monoid a => b -> (a, b)
fromSnd b = (mempty, b)
instance FactorialMonoid [x] where
factors xs = List.map (:[]) xs
primePrefix [] = []
primePrefix (x:_) = [x]
primeSuffix [] = []
primeSuffix xs = [List.last xs]
splitPrimePrefix [] = Nothing
splitPrimePrefix (x:xs) = Just ([x], xs)
splitPrimeSuffix [] = Nothing
splitPrimeSuffix xs = Just (splitLast id xs)
where splitLast f last@[_] = (f [], last)
splitLast f ~(x:rest) = splitLast (f . (x:)) rest
inits = List.inits
tails = List.tails
foldl _ a [] = a
foldl f a (x:xs) = foldl f (f a [x]) xs
foldl' _ a [] = a
foldl' f a (x:xs) = let a' = f a [x] in a' `seq` foldl' f a' xs
foldr _ f0 [] = f0
foldr f f0 (x:xs) = f [x] (foldr f f0 xs)
length = List.length
foldMap f = mconcat . List.map (f . (:[]))
break f = List.break (f . (:[]))
span f = List.span (f . (:[]))
dropWhile f = List.dropWhile (f . (:[]))
takeWhile f = List.takeWhile (f . (:[]))
spanMaybe s0 f l = (prefix' [], suffix' [], s')
where (prefix', suffix', s', _) = List.foldl' g (id, id, s0, True) l
g (prefix, suffix, s1, live) x | live, Just s2 <- f s1 [x] = (prefix . (x:), id, s2, True)
| otherwise = (prefix, suffix . (x:), s1, False)
spanMaybe' s0 f l = (prefix' [], suffix' [], s')
where (prefix', suffix', s', _) = List.foldl' g (id, id, s0, True) l
g (prefix, suffix, s1, live) x | live, Just s2 <- f s1 [x] = seq s2 $ (prefix . (x:), id, s2, True)
| otherwise = (prefix, suffix . (x:), s1, False)
splitAt = List.splitAt
drop = List.drop
take = List.take
reverse = List.reverse
instance FactorialMonoid ByteString.ByteString where
factors x = factorize (ByteString.length x) x
where factorize 0 _ = []
factorize n xs = xs1 : factorize (pred n) xs'
where (xs1, xs') = ByteString.splitAt 1 xs
primePrefix = ByteString.take 1
primeSuffix x = ByteString.drop (ByteString.length x - 1) x
splitPrimePrefix x = if ByteString.null x then Nothing else Just (ByteString.splitAt 1 x)
splitPrimeSuffix x = if ByteString.null x then Nothing else Just (ByteString.splitAt (ByteString.length x - 1) x)
inits = ByteString.inits
tails = ByteString.tails
foldl f = ByteString.foldl f'
where f' a byte = f a (ByteString.singleton byte)
foldl' f = ByteString.foldl' f'
where f' a byte = f a (ByteString.singleton byte)
foldr f = ByteString.foldr (f . ByteString.singleton)
break f = ByteString.break (f . ByteString.singleton)
span f = ByteString.span (f . ByteString.singleton)
spanMaybe s0 f b = case ByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- ByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s) | Just s' <- f s (ByteString.singleton w) = let i' = succ i :: Int in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f b = case ByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- ByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s) | Just s' <- f s (ByteString.singleton w) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
dropWhile f = ByteString.dropWhile (f . ByteString.singleton)
takeWhile f = ByteString.takeWhile (f . ByteString.singleton)
length = ByteString.length
split f = ByteString.splitWith f'
where f' = f . ByteString.singleton
splitAt = ByteString.splitAt
drop = ByteString.drop
take = ByteString.take
reverse = ByteString.reverse
instance FactorialMonoid LazyByteString.ByteString where
factors x = factorize (LazyByteString.length x) x
where factorize 0 _ = []
factorize n xs = xs1 : factorize (pred n) xs'
where (xs1, xs') = LazyByteString.splitAt 1 xs
primePrefix = LazyByteString.take 1
primeSuffix x = LazyByteString.drop (LazyByteString.length x - 1) x
splitPrimePrefix x = if LazyByteString.null x then Nothing
else Just (LazyByteString.splitAt 1 x)
splitPrimeSuffix x = if LazyByteString.null x then Nothing
else Just (LazyByteString.splitAt (LazyByteString.length x - 1) x)
inits = LazyByteString.inits
tails = LazyByteString.tails
foldl f = LazyByteString.foldl f'
where f' a byte = f a (LazyByteString.singleton byte)
foldl' f = LazyByteString.foldl' f'
where f' a byte = f a (LazyByteString.singleton byte)
foldr f = LazyByteString.foldr f'
where f' byte a = f (LazyByteString.singleton byte) a
length = fromIntegral . LazyByteString.length
break f = LazyByteString.break (f . LazyByteString.singleton)
span f = LazyByteString.span (f . LazyByteString.singleton)
spanMaybe s0 f b = case LazyByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- LazyByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s) | Just s' <- f s (LazyByteString.singleton w) = let i' = succ i :: Int64 in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f b = case LazyByteString.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- LazyByteString.splitAt i b -> (prefix, suffix, s')
where g w cont (i, s)
| Just s' <- f s (LazyByteString.singleton w) = let i' = succ i :: Int64 in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
dropWhile f = LazyByteString.dropWhile (f . LazyByteString.singleton)
takeWhile f = LazyByteString.takeWhile (f . LazyByteString.singleton)
split f = LazyByteString.splitWith f'
where f' = f . LazyByteString.singleton
splitAt = LazyByteString.splitAt . fromIntegral
drop n = LazyByteString.drop (fromIntegral n)
take n = LazyByteString.take (fromIntegral n)
reverse = LazyByteString.reverse
instance FactorialMonoid Text.Text where
factors = Text.chunksOf 1
primePrefix = Text.take 1
primeSuffix x = if Text.null x then Text.empty else Text.singleton (Text.last x)
splitPrimePrefix = fmap (first Text.singleton) . Text.uncons
splitPrimeSuffix x = if Text.null x then Nothing else Just (Text.init x, Text.singleton (Text.last x))
inits = Text.inits
tails = Text.tails
foldl f = Text.foldl f'
where f' a char = f a (Text.singleton char)
foldl' f = Text.foldl' f'
where f' a char = f a (Text.singleton char)
foldr f = Text.foldr f'
where f' char a = f (Text.singleton char) a
length = Text.length
span f = Text.span (f . Text.singleton)
break f = Text.break (f . Text.singleton)
dropWhile f = Text.dropWhile (f . Text.singleton)
takeWhile f = Text.takeWhile (f . Text.singleton)
spanMaybe s0 f t = case Text.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- Text.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (Text.singleton c) = let i' = succ i :: Int in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f t = case Text.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- Text.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (Text.singleton c) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
split f = Text.split f'
where f' = f . Text.singleton
splitAt = Text.splitAt
drop = Text.drop
take = Text.take
reverse = Text.reverse
instance FactorialMonoid LazyText.Text where
factors = LazyText.chunksOf 1
primePrefix = LazyText.take 1
primeSuffix x = if LazyText.null x then LazyText.empty else LazyText.singleton (LazyText.last x)
splitPrimePrefix = fmap (first LazyText.singleton) . LazyText.uncons
splitPrimeSuffix x = if LazyText.null x
then Nothing
else Just (LazyText.init x, LazyText.singleton (LazyText.last x))
inits = LazyText.inits
tails = LazyText.tails
foldl f = LazyText.foldl f'
where f' a char = f a (LazyText.singleton char)
foldl' f = LazyText.foldl' f'
where f' a char = f a (LazyText.singleton char)
foldr f = LazyText.foldr f'
where f' char a = f (LazyText.singleton char) a
length = fromIntegral . LazyText.length
span f = LazyText.span (f . LazyText.singleton)
break f = LazyText.break (f . LazyText.singleton)
dropWhile f = LazyText.dropWhile (f . LazyText.singleton)
takeWhile f = LazyText.takeWhile (f . LazyText.singleton)
spanMaybe s0 f t = case LazyText.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- LazyText.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (LazyText.singleton c) = let i' = succ i :: Int64 in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f t = case LazyText.foldr g id t (0, s0)
of (i, s') | (prefix, suffix) <- LazyText.splitAt i t -> (prefix, suffix, s')
where g c cont (i, s) | Just s' <- f s (LazyText.singleton c) = let i' = succ i :: Int64 in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
split f = LazyText.split f'
where f' = f . LazyText.singleton
splitAt = LazyText.splitAt . fromIntegral
drop n = LazyText.drop (fromIntegral n)
take n = LazyText.take (fromIntegral n)
reverse = LazyText.reverse
instance Ord k => FactorialMonoid (Map.Map k v) where
factors = List.map (uncurry Map.singleton) . Map.toAscList
primePrefix map | Map.null map = map
| otherwise = uncurry Map.singleton $ Map.findMin map
primeSuffix map | Map.null map = map
| otherwise = uncurry Map.singleton $ Map.findMax map
splitPrimePrefix = fmap singularize . Map.minViewWithKey
where singularize ((k, v), rest) = (Map.singleton k v, rest)
splitPrimeSuffix = fmap singularize . Map.maxViewWithKey
where singularize ((k, v), rest) = (rest, Map.singleton k v)
foldl f = Map.foldlWithKey f'
where f' a k v = f a (Map.singleton k v)
foldl' f = Map.foldlWithKey' f'
where f' a k v = f a (Map.singleton k v)
foldr f = Map.foldrWithKey f'
where f' k v a = f (Map.singleton k v) a
length = Map.size
reverse = id
instance FactorialMonoid (IntMap.IntMap a) where
factors = List.map (uncurry IntMap.singleton) . IntMap.toAscList
primePrefix map | IntMap.null map = map
| otherwise = uncurry IntMap.singleton $ IntMap.findMin map
primeSuffix map | IntMap.null map = map
| otherwise = uncurry IntMap.singleton $ IntMap.findMax map
splitPrimePrefix = fmap singularize . IntMap.minViewWithKey
where singularize ((k, v), rest) = (IntMap.singleton k v, rest)
splitPrimeSuffix = fmap singularize . IntMap.maxViewWithKey
where singularize ((k, v), rest) = (rest, IntMap.singleton k v)
foldl f = IntMap.foldlWithKey f'
where f' a k v = f a (IntMap.singleton k v)
foldl' f = IntMap.foldlWithKey' f'
where f' a k v = f a (IntMap.singleton k v)
foldr f = IntMap.foldrWithKey f'
where f' k v a = f (IntMap.singleton k v) a
length = IntMap.size
reverse = id
instance FactorialMonoid IntSet.IntSet where
factors = List.map IntSet.singleton . IntSet.toAscList
primePrefix set | IntSet.null set = set
| otherwise = IntSet.singleton $ IntSet.findMin set
primeSuffix set | IntSet.null set = set
| otherwise = IntSet.singleton $ IntSet.findMax set
splitPrimePrefix = fmap singularize . IntSet.minView
where singularize (min, rest) = (IntSet.singleton min, rest)
splitPrimeSuffix = fmap singularize . IntSet.maxView
where singularize (max, rest) = (rest, IntSet.singleton max)
foldl f = IntSet.foldl f'
where f' a b = f a (IntSet.singleton b)
foldl' f = IntSet.foldl' f'
where f' a b = f a (IntSet.singleton b)
foldr f = IntSet.foldr f'
where f' a b = f (IntSet.singleton a) b
length = IntSet.size
reverse = id
instance FactorialMonoid (Sequence.Seq a) where
factors = List.map Sequence.singleton . Foldable.toList
primePrefix = Sequence.take 1
primeSuffix q = Sequence.drop (Sequence.length q - 1) q
splitPrimePrefix q = case Sequence.viewl q
of Sequence.EmptyL -> Nothing
hd Sequence.:< rest -> Just (Sequence.singleton hd, rest)
splitPrimeSuffix q = case Sequence.viewr q
of Sequence.EmptyR -> Nothing
rest Sequence.:> last -> Just (rest, Sequence.singleton last)
inits = Foldable.toList . Sequence.inits
tails = Foldable.toList . Sequence.tails
foldl f = Foldable.foldl f'
where f' a b = f a (Sequence.singleton b)
foldl' f = Foldable.foldl' f'
where f' a b = f a (Sequence.singleton b)
foldr f = Foldable.foldr f'
where f' a b = f (Sequence.singleton a) b
span f = Sequence.spanl (f . Sequence.singleton)
break f = Sequence.breakl (f . Sequence.singleton)
dropWhile f = Sequence.dropWhileL (f . Sequence.singleton)
takeWhile f = Sequence.takeWhileL (f . Sequence.singleton)
spanMaybe s0 f b = case Foldable.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- Sequence.splitAt i b -> (prefix, suffix, s')
where g x cont (i, s) | Just s' <- f s (Sequence.singleton x) = let i' = succ i :: Int in seq i' $ cont (i', s')
| otherwise = (i, s)
spanMaybe' s0 f b = case Foldable.foldr g id b (0, s0)
of (i, s') | (prefix, suffix) <- Sequence.splitAt i b -> (prefix, suffix, s')
where g x cont (i, s) | Just s' <- f s (Sequence.singleton x) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s')
| otherwise = (i, s)
splitAt = Sequence.splitAt
drop = Sequence.drop
take = Sequence.take
length = Sequence.length
reverse = Sequence.reverse
instance Ord a => FactorialMonoid (Set.Set a) where
factors = List.map Set.singleton . Set.toAscList
primePrefix set | Set.null set = set
| otherwise = Set.singleton $ Set.findMin set
primeSuffix set | Set.null set = set
| otherwise = Set.singleton $ Set.findMax set
splitPrimePrefix = fmap singularize . Set.minView
where singularize (min, rest) = (Set.singleton min, rest)
splitPrimeSuffix = fmap singularize . Set.maxView
where singularize (max, rest) = (rest, Set.singleton max)
foldl f = Foldable.foldl f'
where f' a b = f a (Set.singleton b)
foldl' f = Foldable.foldl' f'
where f' a b = f a (Set.singleton b)
foldr f = Foldable.foldr f'
where f' a b = f (Set.singleton a) b
length = Set.size
reverse = id
instance FactorialMonoid (Vector.Vector a) where
factors x = factorize (Vector.length x) x
where factorize 0 _ = []
factorize n xs = xs1 : factorize (pred n) xs'
where (xs1, xs') = Vector.splitAt 1 xs
primePrefix = Vector.take 1
primeSuffix x = Vector.drop (Vector.length x - 1) x
splitPrimePrefix x = if Vector.null x then Nothing else Just (Vector.splitAt 1 x)
splitPrimeSuffix x = if Vector.null x then Nothing else Just (Vector.splitAt (Vector.length x - 1) x)
inits x0 = initsWith x0 []
where initsWith x rest | Vector.null x = x:rest
| otherwise = initsWith (Vector.unsafeInit x) (x:rest)
tails x = x : if Vector.null x then [] else tails (Vector.unsafeTail x)
foldl f = Vector.foldl f'
where f' a byte = f a (Vector.singleton byte)
foldl' f = Vector.foldl' f'
where f' a byte = f a (Vector.singleton byte)
foldr f = Vector.foldr f'
where f' byte a = f (Vector.singleton byte) a
break f = Vector.break (f . Vector.singleton)
span f = Vector.span (f . Vector.singleton)
dropWhile f = Vector.dropWhile (f . Vector.singleton)
takeWhile f = Vector.takeWhile (f . Vector.singleton)
spanMaybe s0 f v = case Vector.ifoldr g Left v s0
of Left s' -> (v, Vector.empty, s')
Right (i, s') | (prefix, suffix) <- Vector.splitAt i v -> (prefix, suffix, s')
where g i x cont s | Just s' <- f s (Vector.singleton x) = cont s'
| otherwise = Right (i, s)
spanMaybe' s0 f v = case Vector.ifoldr' g Left v s0
of Left s' -> (v, Vector.empty, s')
Right (i, s') | (prefix, suffix) <- Vector.splitAt i v -> (prefix, suffix, s')
where g i x cont s | Just s' <- f s (Vector.singleton x) = seq s' (cont s')
| otherwise = Right (i, s)
splitAt = Vector.splitAt
drop = Vector.drop
take = Vector.take
length = Vector.length
reverse = Vector.reverse
instance StableFactorialMonoid ()
instance StableFactorialMonoid a => StableFactorialMonoid (Dual a)
instance StableFactorialMonoid [x]
instance StableFactorialMonoid ByteString.ByteString
instance StableFactorialMonoid LazyByteString.ByteString
instance StableFactorialMonoid Text.Text
instance StableFactorialMonoid LazyText.Text
instance StableFactorialMonoid (Sequence.Seq a)
instance StableFactorialMonoid (Vector.Vector a)
mapM :: (FactorialMonoid a, Monoid b, Monad m) => (a -> m b) -> a -> m b
mapM f = ($ return mempty) . appEndo . foldMap (Endo . Monad.liftM2 mappend . f)
mapM_ :: (FactorialMonoid a, Monad m) => (a -> m b) -> a -> m ()
mapM_ f = foldr ((>>) . f) (return ())
|
5d5c765d7cab7e8d589b8f75446a3629a1f6b880531d0d14fb0773d2a13fb9a8 | foreverbell/project-euler-solutions | 216.hs | import Common.Numbers.Primes (primesTo)
import Common.Numbers.Numbers (tonelliShanks)
import Common.Utils (isqrt)
import Control.Monad (forM_)
import Data.Maybe (fromJust)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
solve :: Int -> Int
solve n = length $ filter id vs
where
ps = filter (\p -> p `rem` 8 == 1 || p `rem` 8 == 7) $ primesTo $ isqrt (2*n*n)
vs = drop 2 $ V.toList $ V.create $ do
vs <- MV.replicate (n+1) True
forM_ ps $ \p -> do
let pick m = min m (p-m)
let m = pick $ fromJust $ tonelliShanks ((p+1) `quot` 2) p
let check = if 2*m*m-1 == p then drop 1 else id
let excludes = check [m, m + p .. n] ++ dropWhile (<=0) [-m, -m + p .. n]
forM_ excludes $ \i -> do
MV.write vs i False
return vs
main = print $ solve 50000000
| null | https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/216.hs | haskell | import Common.Numbers.Primes (primesTo)
import Common.Numbers.Numbers (tonelliShanks)
import Common.Utils (isqrt)
import Control.Monad (forM_)
import Data.Maybe (fromJust)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
solve :: Int -> Int
solve n = length $ filter id vs
where
ps = filter (\p -> p `rem` 8 == 1 || p `rem` 8 == 7) $ primesTo $ isqrt (2*n*n)
vs = drop 2 $ V.toList $ V.create $ do
vs <- MV.replicate (n+1) True
forM_ ps $ \p -> do
let pick m = min m (p-m)
let m = pick $ fromJust $ tonelliShanks ((p+1) `quot` 2) p
let check = if 2*m*m-1 == p then drop 1 else id
let excludes = check [m, m + p .. n] ++ dropWhile (<=0) [-m, -m + p .. n]
forM_ excludes $ \i -> do
MV.write vs i False
return vs
main = print $ solve 50000000
| |
fb3dbe956ab6bfaac87579d5547352813fcebee4c16181891eb1ca9e2a97b2bd | BillHallahan/G2 | TestZeno.hs | {-# LANGUAGE BangPatterns #-}
module Zeno where
import Prelude
( Eq
, Ord
, Show
, iterate
, (!!)
, fmap
, Bool(..)
, div
, return
, (.)
, (||)
, (==)
, ($)
)
-- code here adapted from HipSpec.hs
infix 1 =:=
infixr 0 ==>
-- simplification to remove Prop type
given :: Bool -> Bool -> Bool
given pb pa = (not pb) || pa
givenBool :: Bool -> Bool -> Bool
givenBool = given
(==>) :: Bool -> Bool -> Bool
(==>) = given
proveBool :: Bool -> Bool
proveBool lhs = lhs =:= True
(=:=) :: Eq a => a -> a -> Bool
(=:=) = (==)
-- everything here mainly copied from HipSpec, with some simplifications
data Nat = S Nat | Z
deriving (Eq,Show,Ord)
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving (Eq,Ord,Show)
-- Boolean functions
not :: Bool -> Bool
not True = False
not False = True
(&&) :: Bool -> Bool -> Bool
True && True = True
_ && _ = False
-- Natural numbers
Z === Z = True
Z === _ = False
(S _) === Z = False
(S x) === (S y) = x === y
Z <= _ = True
_ <= Z = False
(S x) <= (S y) = x <= y
_ < Z = False
Z < _ = True
(S x) < (S y) = x < y
Z + y = y
(S x) + y = S (x + y)
Z - _ = Z
x - Z = x
(S x) - (S y) = x - y
min Z y = Z
min (S x) Z = Z
min (S x) (S y) = S (min x y)
max Z y = y
max x Z = x
max (S x) (S y) = S (max x y)
-- List functions
null :: [a] -> Bool
null [] = True
null _ = False
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]
zip [] _ = []
zip _ [] = []
zip (x:xs) (y:ys) = (x, y) : (zip xs ys)
delete :: Nat -> [Nat] -> [Nat]
delete _ [] = []
delete n (x:xs) =
case n === x of
True -> delete n xs
False -> x : (delete n xs)
len :: [a] -> Nat
len [] = Z
len (_:xs) = S (len xs)
elem :: Nat -> [Nat] -> Bool
elem _ [] = False
elem n (x:xs) =
case n === x of
True -> True
False -> elem n xs
drop Z xs = xs
drop _ [] = []
drop (S x) (_:xs) = drop x xs
take Z _ = []
take _ [] = []
take (S x) (y:ys) = y : (take x ys)
count :: Nat -> [Nat] -> Nat
count x [] = Z
count x (y:ys) =
case x === y of
True -> S (count x ys)
_ -> count x ys
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = (f x) : (map f xs)
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile _ [] = []
takeWhile p (x:xs) =
case p x of
True -> x : (takeWhile p xs)
_ -> []
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile _ [] = []
dropWhile p (x:xs) =
case p x of
True -> dropWhile p xs
_ -> x:xs
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs) =
case p x of
True -> x : (filter p xs)
_ -> filter p xs
butlast :: [a] -> [a]
butlast [] = []
butlast [x] = []
butlast (x:xs) = x:(butlast xs)
last :: [Nat] -> Nat
last [] = Z
last [x] = x
last (x:xs) = last xs
sorted :: [Nat] -> Bool
sorted [] = True
sorted [x] = True
sorted (x:y:ys) = (x <= y) && sorted (y:ys)
insort :: Nat -> [Nat] -> [Nat]
insort n [] = [n]
insort n (x:xs) =
case n <= x of
True -> n : x : xs
_ -> x : (insort n xs)
ins :: Nat -> [Nat] -> [Nat]
ins n [] = [n]
ins n (x:xs) =
case n < x of
True -> n : x : xs
_ -> x : (ins n xs)
ins1 :: Nat -> [Nat] -> [Nat]
ins1 n [] = [n]
ins1 n (x:xs) =
case n === x of
True -> x : xs
_ -> x : (ins1 n xs)
sort :: [Nat] -> [Nat]
sort [] = []
sort (x:xs) = insort x (sort xs)
butlastConcat :: [a] -> [a] -> [a]
butlastConcat xs [] = butlast xs
butlastConcat xs ys = xs ++ butlast ys
lastOfTwo :: [Nat] -> [Nat] -> Nat
lastOfTwo xs [] = last xs
lastOfTwo _ ys = last ys
zipConcat :: a -> [a] -> [b] -> [(a, b)]
zipConcat _ _ [] = []
zipConcat x xs (y:ys) = (x, y) : zip xs ys
height :: Tree a -> Nat
height Leaf = Z
height (Node l x r) = S (max (height l) (height r))
mirror :: Tree a -> Tree a
mirror Leaf = Leaf
mirror (Node l x r) = Node (mirror r) x (mirror l)
prop_01 n xs
= (take n xs ++ drop n xs =:= xs)
prop_02 n xs ys
= (count n xs + count n ys =:= count n (xs ++ ys))
prop_03 n xs ys
= proveBool (count n xs <= count n (xs ++ ys))
prop_04 n xs
= (S (count n xs) =:= count n (n : xs))
prop_05 n x xs
= n =:= x ==> S (count n xs) =:= count n (x : xs)
prop_06 n m
= (n - (n + m) =:= Z)
prop_07 n m
= ((n + m) - n =:= m)
prop_08 k m n
= ((k + m) - (k + n) =:= m - n)
prop_09 i j k
= ((i - j) - k =:= i - (j + k))
prop_10 m
= (m - m =:= Z)
prop_11 xs
= (drop Z xs =:= xs)
prop_12 n f xs
= (drop n (map f xs) =:= map f (drop n xs))
prop_13 n x xs
= (drop (S n) (x : xs) =:= drop n xs)
prop_14 p xs ys
= (filter p (xs ++ ys) =:= (filter p xs) ++ (filter p ys))
prop_15 x xs
= (len (ins x xs) =:= S (len xs))
prop_16 x xs
= xs =:= [] ==> last (x:xs) =:= x
prop_17 n
= (n <= Z =:= n === Z)
prop_18 i m
= proveBool (i < S (i + m))
prop_19 n xs
= (len (drop n xs) =:= len xs - n)
prop_20 xs
= (len (sort xs) =:= len xs)
prop_21 n m
= proveBool (n <= (n + m))
prop_22 a b c
= (max (max a b) c =:= max a (max b c))
prop_23 a b
= (max a b =:= max b a)
prop_24 a b
= ((max a b) === a =:= b <= a)
prop_25 a b
= ((max a b) === b =:= a <= b)
prop_26 x xs ys
= givenBool (x `elem` xs)
( proveBool (x `elem` (xs ++ ys)) )
prop_27 x xs ys
= givenBool (x `elem` ys)
( proveBool (x `elem` (xs ++ ys)) )
prop_28 x xs
= proveBool (x `elem` (xs ++ [x]))
prop_29 x xs
= proveBool (x `elem` ins1 x xs)
prop_30 x xs
= proveBool (x `elem` ins x xs)
prop_31 a b c
= (min (min a b) c =:= min a (min b c))
prop_32 a b
= (min a b =:= min b a)
prop_33 a b
= (min a b === a =:= a <= b)
prop_34 a b
= (min a b === b =:= b <= a)
prop_35 xs
= (dropWhile (\_ -> False) xs =:= xs)
prop_36 xs
= (takeWhile (\_ -> True) xs =:= xs)
prop_37 x xs
= proveBool (not (x `elem` delete x xs))
prop_38 n xs
= (count n (xs ++ [n]) =:= S (count n xs))
prop_39 n x xs
= (count n [x] + count n xs =:= count n (x:xs))
prop_40 xs
= (take Z xs =:= [])
prop_41 n f xs
= (take n (map f xs) =:= map f (take n xs))
prop_42 n x xs
= (take (S n) (x:xs) =:= x : (take n xs))
prop_43 p xs
= (takeWhile p xs ++ dropWhile p xs =:= xs)
prop_44 x xs ys
= (zip (x:xs) ys =:= zipConcat x xs ys)
prop_45 x y xs ys
= (zip (x:xs) (y:ys) =:= (x, y) : zip xs ys)
{-
prop_46 xs
= (zip [] xs =:= [])
-}
prop_47 a
= (height (mirror a) =:= height a)
prop_48 xs
= givenBool (not (null xs))
( (butlast xs ++ [last xs] =:= xs) )
prop_49 xs ys
= (butlast (xs ++ ys) =:= butlastConcat xs ys)
prop_50 xs
= (butlast xs =:= take (len xs - S Z) xs)
prop_51 xs x
= (butlast (xs ++ [x]) =:= xs)
prop_52 n xs
= (count n xs =:= count n (rev xs))
prop_53 n xs
= (count n xs =:= count n (sort xs))
prop_54 n m
= ((m + n) - n =:= m)
prop_55 n xs ys
= (drop n (xs ++ ys) =:= drop n xs ++ drop (n - len xs) ys)
prop_56 n m xs
= (drop n (drop m xs) =:= drop (n + m) xs)
prop_57 n m xs
= (drop n (take m xs) =:= take (m - n) (drop n xs))
prop_58 n xs ys
= (drop n (zip xs ys) =:= zip (drop n xs) (drop n ys))
prop_59 xs ys
= ys =:= [] ==> last (xs ++ ys) =:= last xs
prop_60 xs ys
= givenBool (not (null ys))
( (last (xs ++ ys) =:= last ys) )
prop_61 xs ys
= (last (xs ++ ys) =:= lastOfTwo xs ys)
prop_62 xs x
= givenBool (not (null xs))
( (last (x:xs) =:= last xs) )
prop_63 n xs
= givenBool (n < len xs)
( (last (drop n xs) =:= last xs) )
prop_64 x xs
= (last (xs ++ [x]) =:= x)
prop_65 i m =
proveBool (i < S (m + i))
prop_66 p xs
= proveBool (len (filter p xs) <= len xs)
prop_67 xs
= (len (butlast xs) =:= len xs - S Z)
prop_68 n xs
= proveBool (len (delete n xs) <= len xs)
prop_69 n m
= proveBool (n <= (m + n))
prop_70 m n
= givenBool (m <= n)
( proveBool (m <= S n) )
prop_71 x y xs
= given (x === y =:= False)
( (elem x (ins y xs) =:= elem x xs) )
prop_72 i xs
= (rev (drop i xs) =:= take (len xs - i) (rev xs))
prop_73 p xs
= (rev (filter p xs) =:= filter p (rev xs))
prop_74 i xs
= (rev (take i xs) =:= drop (len xs - i) (rev xs))
prop_75 n m xs
= (count n xs + count n [m] =:= count n (m : xs))
prop_76 n m xs
= given (n === m =:= False)
( (count n (xs ++ [m]) =:= count n xs) )
prop_77 x xs
= givenBool (sorted xs)
( proveBool (sorted (insort x xs)) )
prop_78 xs
= proveBool (sorted (sort xs))
prop_79 m n k
= ((S m - n) - S k =:= (m - n) - k)
prop_80 n xs ys
= (take n (xs ++ ys) =:= take n xs ++ take (n - len xs) ys)
prop_81 n m xs {- ys -}
= (take n (drop m xs) =:= drop m (take (n + m) xs))
prop_82 n xs ys
= (take n (zip xs ys) =:= zip (take n xs) (take n ys))
prop_83 xs ys zs
= (zip (xs ++ ys) zs =:=
zip xs (take (len xs) zs) ++ zip ys (drop (len xs) zs))
prop_84 xs ys zs
= (zip xs (ys ++ zs) =:=
zip (take (len ys) xs) ys ++ zip (drop (len ys) xs) zs)
prop_85 xs ys
= (len xs =:= len ys) ==>
(zip (rev xs) (rev ys) =:= rev (zip xs ys))
prop_01 :: Eq a => Nat -> [a] -> Bool
prop_02 :: Nat -> [Nat] -> [Nat] -> Bool
prop_03 :: Nat -> [Nat] -> [Nat] -> Bool
prop_04 :: Nat -> [Nat] -> Bool
prop_06 :: Nat -> Nat -> Bool
prop_07 :: Nat -> Nat -> Bool
prop_08 :: Nat -> Nat -> Nat -> Bool
prop_09 :: Nat -> Nat -> Nat -> Bool
prop_10 :: Nat -> Bool
prop_11 :: Eq a => [a] -> Bool
prop_12 :: Eq a => Eq a1 => Nat -> (a1 -> a) -> [a1] -> Bool
prop_13 :: Eq a => Nat -> a -> [a] -> Bool
prop_14 :: Eq a => (a -> Bool) -> [a] -> [a] -> Bool
prop_15 :: Nat -> [Nat] -> Bool
prop_17 :: Nat -> Bool
prop_18 :: Nat -> Nat -> Bool
prop_19 :: Eq a => Nat -> [a] -> Bool
prop_20 :: [Nat] -> Bool
prop_21 :: Nat -> Nat -> Bool
prop_22 :: Nat -> Nat -> Nat -> Bool
prop_23 :: Nat -> Nat -> Bool
prop_24 :: Nat -> Nat -> Bool
prop_25 :: Nat -> Nat -> Bool
prop_28 :: Nat -> [Nat] -> Bool
prop_29 :: Nat -> [Nat] -> Bool
prop_30 :: Nat -> [Nat] -> Bool
prop_31 :: Nat -> Nat -> Nat -> Bool
prop_32 :: Nat -> Nat -> Bool
prop_33 :: Nat -> Nat -> Bool
prop_34 :: Nat -> Nat -> Bool
prop_35 :: Eq a => [a] -> Bool
prop_36 :: Eq a => [a] -> Bool
prop_37 :: Nat -> [Nat] -> Bool
prop_38 :: Nat -> [Nat] -> Bool
prop_39 :: Nat -> Nat -> [Nat] -> Bool
prop_40 :: Eq a => [a] -> Bool
prop_41 :: Eq a => Eq a1 => Nat -> (a1 -> a) -> [a1] -> Bool
prop_42 :: Eq a => Nat -> a -> [a] -> Bool
prop_43 :: Eq a => (a -> Bool) -> [a] -> Bool
prop_44 :: Eq a => Eq b => a -> [a] -> [b] -> Bool
prop_45 :: Eq a => Eq b => a -> b -> [a] -> [b] -> Bool
--prop_46 :: Eq b => [b] -> Bool
prop_47 :: Eq a => Tree a -> Bool
prop_49 :: Eq a => [a] -> [a] -> Bool
prop_50 :: Eq a => [a] -> Bool
prop_51 :: Eq a => [a] -> a -> Bool
prop_52 :: Nat -> [Nat] -> Bool
prop_53 :: Nat -> [Nat] -> Bool
prop_54 :: Nat -> Nat -> Bool
prop_55 :: Eq a => Nat -> [a] -> [a] -> Bool
prop_56 :: Eq a => Nat -> Nat -> [a] -> Bool
prop_57 :: Eq a => Nat -> Nat -> [a] -> Bool
prop_58 :: Eq a => Eq b => Nat -> [a] -> [b] -> Bool
prop_64 :: Nat -> [Nat] -> Bool
prop_65 :: Nat -> Nat -> Bool
prop_66 :: Eq a => (a -> Bool) -> [a] -> Bool
prop_67 :: Eq a => [a] -> Bool
prop_68 :: Nat -> [Nat] -> Bool
prop_69 :: Nat -> Nat -> Bool
prop_72 :: Eq a => Nat -> [a] -> Bool
prop_73 :: Eq a => (a -> Bool) -> [a] -> Bool
prop_74 :: Eq a => Nat -> [a] -> Bool
prop_75 :: Nat -> Nat -> [Nat] -> Bool
prop_78 :: [Nat] -> Bool
prop_79 :: Nat -> Nat -> Nat -> Bool
prop_80 :: Eq a => Nat -> [a] -> [a] -> Bool
prop_81 :: Eq a => Nat -> Nat -> [a] -> Bool
prop_82 :: Eq a => Eq b => Nat -> [a] -> [b] -> Bool
prop_83 :: Eq a => Eq b => [a] -> [a] -> [b] -> Bool
prop_84 :: Eq a => Eq a1 => [a] -> [a1] -> [a1] -> Bool
prop_85 :: Eq a => Eq b => [a] -> [b] -> Bool
swapped side for 04
# RULES
" p01 " forall n xs . take n xs + + drop n xs = xs
" p02 " forall n xs ys . count n xs + count n ys = count n ( xs + + ys )
" p04 " forall n xs . count n ( n : xs ) = S ( count n xs )
" p06 " forall n m . n - ( n + m ) = Z
" p07 " forall n m . ( n + m ) - n = m
" p08 " forall k m n . ( k + m ) - ( k + n ) = m - n
" p09 " forall i j k . ( i - j ) - k = i - ( j + k )
" p10 " forall m . m - m = Z
" p11 " forall xs . drop Z xs = xs
" p12 " forall f n xs . drop n ( map f xs ) = map f ( drop n xs )
" p13 " forall n x xs . drop ( S n ) ( x : xs ) = drop n xs
" p14 " forall p xs ys . filter p ( xs + + ys ) = ( filter p xs ) + + ( filter p ys )
" p15 " forall x xs . len ( ins x xs ) = S ( len xs )
" p17 " forall n . n < = Z = n = = = Z
" p19 " forall n xs . len ( drop n xs ) = len xs - n
" p20 " forall xs . len ( sort xs ) = len xs
" p22 " forall a b c . ( max a b ) c = max a ( max b c )
" p23 " forall a b . a b = max b a
" p24 " forall a b . ( a b ) = = = a = b < = a
" p25 " forall a b . ( a b ) = = = b = a < = b
" p31 " forall a b c . min ( min a b ) c = min a ( min b c )
" p32 " forall a b . min a b = min b a
" p33 " forall a b . min a b = = = a = a < = b
" p34 " forall a b . min a b = = = b = b < = a
" p35 " forall xs . ( \ _ - > False ) xs = xs
" p36 " forall xs . ( \ _ - > True ) xs = xs
" p38 " forall n xs . count n ( xs + + [ n ] ) = S ( count n xs )
" p39 " forall n x xs . count n [ x ] + count n xs = count n ( x : xs )
" p40 " forall xs . take Z xs = [ ]
" p41 " forall f n xs . take n ( map f xs ) = map f ( take n xs )
" p42 " forall n x xs . take ( S n ) ( x : xs ) = x : ( take n xs )
" p43 " forall p xs .
" p44 " forall x xs ys . zip ( x : xs ) ys = zipConcat x xs ys
" p45 " forall x y xs ys . zip ( x : xs ) ( y : ys ) = ( x , y ) : zip xs ys
" p46 " forall xs . zip [ ] xs = [ ]
" p47 " forall a . height ( mirror a ) = height a
" p49 " forall xs ys . ( xs + + ys ) =
" p50 " forall xs . butlast xs = take ( len xs - S Z ) xs
" p51 " forall x xs . ( xs + + [ x ] ) = xs
" p52 " forall n xs . count n xs = count n ( rev xs )
" p53 " forall n xs . count n xs = count n ( sort xs )
" p54 " forall n m . ( m + n ) - n = m
" p55 " forall n xs ys . drop n ( xs + + ys ) = drop n xs + + drop ( n - len xs ) ys
" p56 " forall n m xs . drop n ( drop m xs ) = drop ( n + m ) xs
" p57 " forall n m xs . drop n ( take m xs ) = take ( m - n ) ( drop n xs )
" p58 " forall n xs ys . drop n ( zip xs ys ) = zip ( drop n xs ) ( drop n ys )
" p61 " forall xs ys . last ( xs + + ys ) =
" p64 " forall x xs . last ( xs + + [ x ] ) = x
" p67 " forall xs . len ( butlast xs ) = len xs - S Z
" p72 " forall i xs . rev ( drop i xs ) = take ( len xs - i ) ( rev xs )
" p73 " forall p xs . rev ( filter p xs ) = filter p ( rev xs )
" p74 " forall i xs . rev ( take i xs ) = drop ( len xs - i ) ( rev xs )
" p75 " forall n m xs . count n xs + count n [ m ] = count n ( m : xs )
" p79 " forall m n k . ( S m - n ) - S k = ( m - n ) - k
" p80 " forall n xs ys . take n ( xs + + ys ) = take n xs + + take ( n - len xs ) ys
" p81 " forall n m xs . take n ( drop m xs ) = drop m ( take ( n + m ) xs )
" p82 " forall n xs ys . take n ( zip xs ys ) = zip ( take n xs ) ( take n ys )
" p83 " forall xs ys zs . zip ( xs + + ys ) zs = zip xs ( take ( len xs ) zs ) + + zip ys ( drop ( len xs ) zs )
" p84 " forall xs ys zs . zip xs ( ys + + zs ) = zip ( take ( len ys ) xs ) ys + + zip ( drop ( len ys ) xs ) zs
#
"p01" forall n xs . take n xs ++ drop n xs = xs
"p02" forall n xs ys . count n xs + count n ys = count n (xs ++ ys)
"p04" forall n xs . count n (n : xs) = S (count n xs)
"p06" forall n m . n - (n + m) = Z
"p07" forall n m . (n + m) - n = m
"p08" forall k m n . (k + m) - (k + n) = m - n
"p09" forall i j k . (i - j) - k = i - (j + k)
"p10" forall m . m - m = Z
"p11" forall xs . drop Z xs = xs
"p12" forall f n xs . drop n (map f xs) = map f (drop n xs)
"p13" forall n x xs . drop (S n) (x : xs) = drop n xs
"p14" forall p xs ys . filter p (xs ++ ys) = (filter p xs) ++ (filter p ys)
"p15" forall x xs . len (ins x xs) = S (len xs)
"p17" forall n . n <= Z = n === Z
"p19" forall n xs . len (drop n xs) = len xs - n
"p20" forall xs . len (sort xs) = len xs
"p22" forall a b c . max (max a b) c = max a (max b c)
"p23" forall a b . max a b = max b a
"p24" forall a b . (max a b) === a = b <= a
"p25" forall a b . (max a b) === b = a <= b
"p31" forall a b c . min (min a b) c = min a (min b c)
"p32" forall a b . min a b = min b a
"p33" forall a b . min a b === a = a <= b
"p34" forall a b . min a b === b = b <= a
"p35" forall xs . dropWhile (\_ -> False) xs = xs
"p36" forall xs . takeWhile (\_ -> True) xs = xs
"p38" forall n xs . count n (xs ++ [n]) = S (count n xs)
"p39" forall n x xs . count n [x] + count n xs = count n (x:xs)
"p40" forall xs . take Z xs = []
"p41" forall f n xs . take n (map f xs) = map f (take n xs)
"p42" forall n x xs . take (S n) (x:xs) = x : (take n xs)
"p43" forall p xs . takeWhile p xs ++ dropWhile p xs = xs
"p44" forall x xs ys . zip (x:xs) ys = zipConcat x xs ys
"p45" forall x y xs ys . zip (x:xs) (y:ys) = (x, y) : zip xs ys
"p46" forall xs . zip [] xs = []
"p47" forall a . height (mirror a) = height a
"p49" forall xs ys . butlast (xs ++ ys) = butlastConcat xs ys
"p50" forall xs . butlast xs = take (len xs - S Z) xs
"p51" forall x xs . butlast (xs ++ [x]) = xs
"p52" forall n xs . count n xs = count n (rev xs)
"p53" forall n xs . count n xs = count n (sort xs)
"p54" forall n m . (m + n) - n = m
"p55" forall n xs ys . drop n (xs ++ ys) = drop n xs ++ drop (n - len xs) ys
"p56" forall n m xs . drop n (drop m xs) = drop (n + m) xs
"p57" forall n m xs . drop n (take m xs) = take (m - n) (drop n xs)
"p58" forall n xs ys . drop n (zip xs ys) = zip (drop n xs) (drop n ys)
"p61" forall xs ys . last (xs ++ ys) = lastOfTwo xs ys
"p64" forall x xs . last (xs ++ [x]) = x
"p67" forall xs . len (butlast xs) = len xs - S Z
"p72" forall i xs . rev (drop i xs) = take (len xs - i) (rev xs)
"p73" forall p xs . rev (filter p xs) = filter p (rev xs)
"p74" forall i xs . rev (take i xs) = drop (len xs - i) (rev xs)
"p75" forall n m xs . count n xs + count n [m] = count n (m : xs)
"p79" forall m n k . (S m - n) - S k = (m - n) - k
"p80" forall n xs ys . take n (xs ++ ys) = take n xs ++ take (n - len xs) ys
"p81" forall n m xs . take n (drop m xs) = drop m (take (n + m) xs)
"p82" forall n xs ys . take n (zip xs ys) = zip (take n xs) (take n ys)
"p83" forall xs ys zs . zip (xs ++ ys) zs = zip xs (take (len xs) zs) ++ zip ys (drop (len xs) zs)
"p84" forall xs ys zs . zip xs (ys ++ zs) = zip (take (len ys) xs) ys ++ zip (drop (len ys) xs) zs
#-}
-- the theorems that don't fit the ordinary equivalence format
# RULES
" p03 " forall n xs ys . prop_03 n xs ys = True
" p05 " forall n x xs . prop_05 n x xs = True
" p16 " forall x xs . prop_16 x xs = True
" p18 " forall i m . prop_18 i m = True
" p21 " forall n m . prop_21 n m = True
" p26 " forall x xs ys . prop_26 x xs ys = True
" p27 " forall x xs ys . prop_27 x xs ys = True
" p28 " forall x xs . prop_28 x xs = True
" p29 " forall x xs . prop_29 x xs = True
" p30 " forall x xs . prop_30 x xs = True
" p37 " forall x xs . prop_37 x xs = True
" p48 " forall xs . prop_48 xs = True
" p59 " forall xs ys . = True
" p60 " forall xs ys . prop_60 xs ys = True
" p62 " forall xs x . prop_62 xs x = True
" p63 " forall n xs . prop_63 n xs = True
" p65 " forall i m . = True
" p66 " forall p xs . prop_66 p xs = True
" p68 " forall n xs . prop_68 n xs = True
" p69 " forall n m . prop_69 n m = True
" p70 " forall m n . prop_70 m n = True
" p71 " forall x y xs . y xs = True
" p76 " forall n m xs . prop_76 n m xs = True
" p77 " forall x xs . prop_77 x xs = True
" p78 " forall xs . prop_78 xs = True
" p85 " forall xs ys . = True
#
"p03" forall n xs ys . prop_03 n xs ys = True
"p05" forall n x xs . prop_05 n x xs = True
"p16" forall x xs . prop_16 x xs = True
"p18" forall i m . prop_18 i m = True
"p21" forall n m . prop_21 n m = True
"p26" forall x xs ys . prop_26 x xs ys = True
"p27" forall x xs ys . prop_27 x xs ys = True
"p28" forall x xs . prop_28 x xs = True
"p29" forall x xs . prop_29 x xs = True
"p30" forall x xs . prop_30 x xs = True
"p37" forall x xs . prop_37 x xs = True
"p48" forall xs . prop_48 xs = True
"p59" forall xs ys . prop_59 xs ys = True
"p60" forall xs ys . prop_60 xs ys = True
"p62" forall xs x . prop_62 xs x = True
"p63" forall n xs . prop_63 n xs = True
"p65" forall i m . prop_65 i m = True
"p66" forall p xs . prop_66 p xs = True
"p68" forall n xs . prop_68 n xs = True
"p69" forall n m . prop_69 n m = True
"p70" forall m n . prop_70 m n = True
"p71" forall x y xs . prop_71 x y xs = True
"p76" forall n m xs . prop_76 n m xs = True
"p77" forall x xs . prop_77 x xs = True
"p78" forall xs . prop_78 xs = True
"p85" forall xs ys . prop_85 xs ys = True
#-}
# RULES
" p03fin " forall n xs ys . ( prop_03 n xs ys ) = walkNatList xs True
" p03finB " forall n xs ys . walkNat n ( prop_03 n xs ys ) = walkNat n ( walkList xs True )
" p04fin " forall n xs . count n ( n : xs ) = walkNat n ( S ( count n xs ) )
" p05finE " forall n x xs . walkNat n ( walkList xs ( prop_05 n x xs ) ) = walkNat n ( walkList xs True )
" p05finF " forall n x xs . walkNat x ( walkList xs ( prop_05 n x xs ) ) = walkNat x ( walkList xs True )
" p06fin " forall n m . n - ( n + m ) = walkNat n Z
" p07fin " forall n m . ( n + m ) - n = walkNat n m
" p08fin " forall k m n . ( k + m ) - ( k + n ) = walkNat k ( m - n )
" p10fin " forall m . m - m = walkNat m Z
" p15finA " forall x xs . walkNatList xs ( len ( ins x xs ) ) = walkNatList xs $ S ( len xs )
" p15finB " forall x xs . walkNat x ( walkList xs ( len ( ins x xs ) ) ) = walkNat x $ walkList xs $ S ( len xs )
" p16finA " forall x xs . walkNat x ( prop_16 x xs ) = walkNat x True
" p18fin " forall i m . prop_18 i m = walkNat i True
" p20finA " forall xs . walkNatList xs ( len ( sort xs ) ) = walkNatList xs ( len xs )
" p21fin " forall n m . prop_21 n m = walkNat n True
" p24fin " forall a b . ( a b ) = = = a = walkNat a ( b < = a )
" p25fin " forall a b . ( a b ) = = = b = walkNat b ( a < = b )
" p26finA " forall x xs ys . ( prop_26 x xs ys ) = walkNatList xs True
" p26finB " forall x xs ys . walkNat x ( walkList xs ( prop_26 x xs ys ) ) = walkNat x $ walkList xs True
" p27finA " forall x xs ys . walkNat x ( walkList xs ( walkList ys ( prop_27 x xs ys ) ) ) = walkNat x $ walkList xs $ walkList ys True
" p28finA " forall x xs . walkList xs ( prop_28 x xs ) = walkNat x $ walkList xs True
" p29finA " forall x xs . walkList xs ( prop_29 x xs ) = walkNat x $ walkList xs True
" p30finA " forall x xs . walkList xs ( prop_30 x xs ) = walkNat x $ walkList xs True
" p37finB " forall x xs . walkNatList xs ( prop_37 x xs ) = walkNatList xs True
" p37finC " forall x xs . walkNat x ( prop_37 x xs ) = walkNat x $ walkList xs True
" p38finB " forall n xs . walkList xs ( count n ( xs + + [ n ] ) ) = walkNat n $ walkList xs $ S ( count n xs )
" p48finB " forall xs . walkNatList xs ( prop_48 xs ) = walkNatList xs True
" p52finA " forall n xs . walkNatList xs ( count n xs ) = walkNatList xs ( count n ( rev xs ) )
" p53finA " forall n xs . walkNatList xs ( count n xs ) = walkNatList xs ( count n ( sort xs ) )
" p54fin " forall n m . ( m + n ) - n = walkNat n m
" p57finA " forall n m xs . walkNat n ( drop n ( take m xs ) ) = walkNat n ( take ( m - n ) ( drop n xs ) )
" p57finB " forall n m xs . ( drop n ( take m xs ) ) = walkNat m ( take ( m - n ) ( drop n xs ) )
" p59finA " forall xs ys . ( prop_59 xs ys ) = walkNatList xs True
" p60finB " forall xs ys . walkList xs ( walkNatList ys ( prop_60 xs ys ) ) = walkList xs $ walkNatList ys True
" p61fin " forall xs ys . last ( xs + + ys ) = walkList xs ( lastOfTwo xs ys )
" p62finA " forall xs x . walkNatList xs ( prop_62 xs x ) = walkNatList xs True
" p63finA " forall n xs . walkNatList xs ( prop_63 n xs ) = walkNatList xs True
" p64fin " forall x xs . last ( xs + + [ x ] ) = walkList xs x
" p65finA " forall i m . = walkNat i True
" p66fin " forall p xs . prop_66 p xs = walkList xs True
" p68finA " forall n xs . walkNat n ( prop_68 n xs ) = walkNat n $ walkList xs True
" p68finB " forall n xs . walkNatList xs ( prop_68 n xs ) = walkNatList xs True
" p69finA " forall n m . prop_69 n m = walkNat n True
" p70finC " forall m n . walkNat m ( prop_70 m n ) = walkNat m True
" p70finD " forall m n . walkNat n ( prop_70 m n ) = walkNat n True
" p71finA " forall x y xs . walkNatList xs ( prop_71 x y xs ) = walkNat x $ walkNatList xs True
" p71finB " forall x y xs . walkNatList xs ( prop_71 x y xs ) = walkNat y $ walkNatList xs True
" p75fin " forall n m xs . count n xs + count n [ m ] = walkList xs $ count n ( m : xs )
" p76finB " forall n m xs . walkList xs ( prop_76 n m xs ) = walkNat n $ walkList xs True
" p76finC " forall n m xs . walkNatList xs ( prop_76 n m xs ) = walkNat m $ walkNatList xs True
" p77finA " forall x xs . walkNatList xs ( prop_77 x xs ) = walkNatList xs True
" p78finB " forall xs . walkNatList xs ( prop_78 xs ) = walkNatList xs True
" p81fin " forall n m xs . ( take n ( drop m xs ) ) = drop m ( take ( n + m ) xs )
" p81finA " forall n m xs . walkList xs ( take n ( drop m xs ) ) = drop m ( take ( n + m ) xs )
" p85finB " forall xs ys . walkList xs ( prop_85 xs ys ) = walkList xs True
" p85finC " forall xs ys . walkList ys ( ) = walkList ys True
#
"p03fin" forall n xs ys . walkNatList xs (prop_03 n xs ys) = walkNatList xs True
"p03finB" forall n xs ys . walkNat n (prop_03 n xs ys) = walkNat n (walkList xs True)
"p04fin" forall n xs . count n (n : xs) = walkNat n (S (count n xs))
"p05finE" forall n x xs . walkNat n (walkList xs (prop_05 n x xs)) = walkNat n (walkList xs True)
"p05finF" forall n x xs . walkNat x (walkList xs (prop_05 n x xs)) = walkNat x (walkList xs True)
"p06fin" forall n m . n - (n + m) = walkNat n Z
"p07fin" forall n m . (n + m) - n = walkNat n m
"p08fin" forall k m n . (k + m) - (k + n) = walkNat k (m - n)
"p10fin" forall m . m - m = walkNat m Z
"p15finA" forall x xs . walkNatList xs (len (ins x xs)) = walkNatList xs $ S (len xs)
"p15finB" forall x xs . walkNat x (walkList xs (len (ins x xs))) = walkNat x $ walkList xs $ S (len xs)
"p16finA" forall x xs . walkNat x (prop_16 x xs) = walkNat x True
"p18fin" forall i m . prop_18 i m = walkNat i True
"p20finA" forall xs . walkNatList xs (len (sort xs)) = walkNatList xs (len xs)
"p21fin" forall n m . prop_21 n m = walkNat n True
"p24fin" forall a b . (max a b) === a = walkNat a (b <= a)
"p25fin" forall a b . (max a b) === b = walkNat b (a <= b)
"p26finA" forall x xs ys . walkNatList xs (prop_26 x xs ys) = walkNatList xs True
"p26finB" forall x xs ys . walkNat x (walkList xs (prop_26 x xs ys)) = walkNat x $ walkList xs True
"p27finA" forall x xs ys . walkNat x (walkList xs (walkList ys (prop_27 x xs ys))) = walkNat x $ walkList xs $ walkList ys True
"p28finA" forall x xs . walkList xs (prop_28 x xs) = walkNat x $ walkList xs True
"p29finA" forall x xs . walkList xs (prop_29 x xs) = walkNat x $ walkList xs True
"p30finA" forall x xs . walkList xs (prop_30 x xs) = walkNat x $ walkList xs True
"p37finB" forall x xs . walkNatList xs (prop_37 x xs) = walkNatList xs True
"p37finC" forall x xs . walkNat x (prop_37 x xs) = walkNat x $ walkList xs True
"p38finB" forall n xs . walkList xs (count n (xs ++ [n])) = walkNat n $ walkList xs $ S (count n xs)
"p48finB" forall xs . walkNatList xs (prop_48 xs) = walkNatList xs True
"p52finA" forall n xs . walkNatList xs (count n xs) = walkNatList xs (count n (rev xs))
"p53finA" forall n xs . walkNatList xs (count n xs) = walkNatList xs (count n (sort xs))
"p54fin" forall n m . (m + n) - n = walkNat n m
"p57finA" forall n m xs . walkNat n (drop n (take m xs)) = walkNat n (take (m - n) (drop n xs))
"p57finB" forall n m xs . walkNat m (drop n (take m xs)) = walkNat m (take (m - n) (drop n xs))
"p59finA" forall xs ys . walkNatList xs (prop_59 xs ys) = walkNatList xs True
"p60finB" forall xs ys . walkList xs (walkNatList ys (prop_60 xs ys)) = walkList xs $ walkNatList ys True
"p61fin" forall xs ys . last (xs ++ ys) = walkList xs (lastOfTwo xs ys)
"p62finA" forall xs x . walkNatList xs (prop_62 xs x) = walkNatList xs True
"p63finA" forall n xs . walkNatList xs (prop_63 n xs) = walkNatList xs True
"p64fin" forall x xs . last (xs ++ [x]) = walkList xs x
"p65finA" forall i m . prop_65 i m = walkNat i True
"p66fin" forall p xs . prop_66 p xs = walkList xs True
"p68finA" forall n xs . walkNat n (prop_68 n xs) = walkNat n $ walkList xs True
"p68finB" forall n xs . walkNatList xs (prop_68 n xs) = walkNatList xs True
"p69finA" forall n m . prop_69 n m = walkNat n True
"p70finC" forall m n . walkNat m (prop_70 m n) = walkNat m True
"p70finD" forall m n . walkNat n (prop_70 m n) = walkNat n True
"p71finA" forall x y xs . walkNatList xs (prop_71 x y xs) = walkNat x $ walkNatList xs True
"p71finB" forall x y xs . walkNatList xs (prop_71 x y xs) = walkNat y $ walkNatList xs True
"p75fin" forall n m xs . count n xs + count n [m] = walkList xs $ count n (m : xs)
"p76finB" forall n m xs . walkList xs (prop_76 n m xs) = walkNat n $ walkList xs True
"p76finC" forall n m xs . walkNatList xs (prop_76 n m xs) = walkNat m $ walkNatList xs True
"p77finA" forall x xs . walkNatList xs (prop_77 x xs) = walkNatList xs True
"p78finB" forall xs . walkNatList xs (prop_78 xs) = walkNatList xs True
"p81fin" forall n m xs . walkNat m (take n (drop m xs)) = drop m (take (n + m) xs)
"p81finA" forall n m xs . walkList xs (take n (drop m xs)) = drop m (take (n + m) xs)
"p85finB" forall xs ys . walkList xs (prop_85 xs ys) = walkList xs True
"p85finC" forall xs ys . walkList ys (prop_85 xs ys) = walkList ys True
#-}
walkNat :: Nat -> a -> a
walkNat Z a = a
walkNat (S x) a = walkNat x a
walkList :: [a] -> b -> b
walkList [] a = a
walkList (_:xs) a = walkList xs a
walkNatList :: [Nat] -> a -> a
walkNatList xs a = case xs of
[] -> a
y:ys -> walkNat y $ walkNatList ys a
| null | https://raw.githubusercontent.com/BillHallahan/G2/8b2a2be28ec9b8ccbce9a0da137d4da99001eeab/tests/RewriteVerify/Correct/TestZeno.hs | haskell | # LANGUAGE BangPatterns #
code here adapted from HipSpec.hs
simplification to remove Prop type
everything here mainly copied from HipSpec, with some simplifications
Boolean functions
Natural numbers
List functions
prop_46 xs
= (zip [] xs =:= [])
ys
prop_46 :: Eq b => [b] -> Bool
the theorems that don't fit the ordinary equivalence format |
module Zeno where
import Prelude
( Eq
, Ord
, Show
, iterate
, (!!)
, fmap
, Bool(..)
, div
, return
, (.)
, (||)
, (==)
, ($)
)
infix 1 =:=
infixr 0 ==>
given :: Bool -> Bool -> Bool
given pb pa = (not pb) || pa
givenBool :: Bool -> Bool -> Bool
givenBool = given
(==>) :: Bool -> Bool -> Bool
(==>) = given
proveBool :: Bool -> Bool
proveBool lhs = lhs =:= True
(=:=) :: Eq a => a -> a -> Bool
(=:=) = (==)
data Nat = S Nat | Z
deriving (Eq,Show,Ord)
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving (Eq,Ord,Show)
not :: Bool -> Bool
not True = False
not False = True
(&&) :: Bool -> Bool -> Bool
True && True = True
_ && _ = False
Z === Z = True
Z === _ = False
(S _) === Z = False
(S x) === (S y) = x === y
Z <= _ = True
_ <= Z = False
(S x) <= (S y) = x <= y
_ < Z = False
Z < _ = True
(S x) < (S y) = x < y
Z + y = y
(S x) + y = S (x + y)
Z - _ = Z
x - Z = x
(S x) - (S y) = x - y
min Z y = Z
min (S x) Z = Z
min (S x) (S y) = S (min x y)
max Z y = y
max x Z = x
max (S x) (S y) = S (max x y)
null :: [a] -> Bool
null [] = True
null _ = False
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]
zip [] _ = []
zip _ [] = []
zip (x:xs) (y:ys) = (x, y) : (zip xs ys)
delete :: Nat -> [Nat] -> [Nat]
delete _ [] = []
delete n (x:xs) =
case n === x of
True -> delete n xs
False -> x : (delete n xs)
len :: [a] -> Nat
len [] = Z
len (_:xs) = S (len xs)
elem :: Nat -> [Nat] -> Bool
elem _ [] = False
elem n (x:xs) =
case n === x of
True -> True
False -> elem n xs
drop Z xs = xs
drop _ [] = []
drop (S x) (_:xs) = drop x xs
take Z _ = []
take _ [] = []
take (S x) (y:ys) = y : (take x ys)
count :: Nat -> [Nat] -> Nat
count x [] = Z
count x (y:ys) =
case x === y of
True -> S (count x ys)
_ -> count x ys
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = (f x) : (map f xs)
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile _ [] = []
takeWhile p (x:xs) =
case p x of
True -> x : (takeWhile p xs)
_ -> []
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile _ [] = []
dropWhile p (x:xs) =
case p x of
True -> dropWhile p xs
_ -> x:xs
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter p (x:xs) =
case p x of
True -> x : (filter p xs)
_ -> filter p xs
butlast :: [a] -> [a]
butlast [] = []
butlast [x] = []
butlast (x:xs) = x:(butlast xs)
last :: [Nat] -> Nat
last [] = Z
last [x] = x
last (x:xs) = last xs
sorted :: [Nat] -> Bool
sorted [] = True
sorted [x] = True
sorted (x:y:ys) = (x <= y) && sorted (y:ys)
insort :: Nat -> [Nat] -> [Nat]
insort n [] = [n]
insort n (x:xs) =
case n <= x of
True -> n : x : xs
_ -> x : (insort n xs)
ins :: Nat -> [Nat] -> [Nat]
ins n [] = [n]
ins n (x:xs) =
case n < x of
True -> n : x : xs
_ -> x : (ins n xs)
ins1 :: Nat -> [Nat] -> [Nat]
ins1 n [] = [n]
ins1 n (x:xs) =
case n === x of
True -> x : xs
_ -> x : (ins1 n xs)
sort :: [Nat] -> [Nat]
sort [] = []
sort (x:xs) = insort x (sort xs)
butlastConcat :: [a] -> [a] -> [a]
butlastConcat xs [] = butlast xs
butlastConcat xs ys = xs ++ butlast ys
lastOfTwo :: [Nat] -> [Nat] -> Nat
lastOfTwo xs [] = last xs
lastOfTwo _ ys = last ys
zipConcat :: a -> [a] -> [b] -> [(a, b)]
zipConcat _ _ [] = []
zipConcat x xs (y:ys) = (x, y) : zip xs ys
height :: Tree a -> Nat
height Leaf = Z
height (Node l x r) = S (max (height l) (height r))
mirror :: Tree a -> Tree a
mirror Leaf = Leaf
mirror (Node l x r) = Node (mirror r) x (mirror l)
prop_01 n xs
= (take n xs ++ drop n xs =:= xs)
prop_02 n xs ys
= (count n xs + count n ys =:= count n (xs ++ ys))
prop_03 n xs ys
= proveBool (count n xs <= count n (xs ++ ys))
prop_04 n xs
= (S (count n xs) =:= count n (n : xs))
prop_05 n x xs
= n =:= x ==> S (count n xs) =:= count n (x : xs)
prop_06 n m
= (n - (n + m) =:= Z)
prop_07 n m
= ((n + m) - n =:= m)
prop_08 k m n
= ((k + m) - (k + n) =:= m - n)
prop_09 i j k
= ((i - j) - k =:= i - (j + k))
prop_10 m
= (m - m =:= Z)
prop_11 xs
= (drop Z xs =:= xs)
prop_12 n f xs
= (drop n (map f xs) =:= map f (drop n xs))
prop_13 n x xs
= (drop (S n) (x : xs) =:= drop n xs)
prop_14 p xs ys
= (filter p (xs ++ ys) =:= (filter p xs) ++ (filter p ys))
prop_15 x xs
= (len (ins x xs) =:= S (len xs))
prop_16 x xs
= xs =:= [] ==> last (x:xs) =:= x
prop_17 n
= (n <= Z =:= n === Z)
prop_18 i m
= proveBool (i < S (i + m))
prop_19 n xs
= (len (drop n xs) =:= len xs - n)
prop_20 xs
= (len (sort xs) =:= len xs)
prop_21 n m
= proveBool (n <= (n + m))
prop_22 a b c
= (max (max a b) c =:= max a (max b c))
prop_23 a b
= (max a b =:= max b a)
prop_24 a b
= ((max a b) === a =:= b <= a)
prop_25 a b
= ((max a b) === b =:= a <= b)
prop_26 x xs ys
= givenBool (x `elem` xs)
( proveBool (x `elem` (xs ++ ys)) )
prop_27 x xs ys
= givenBool (x `elem` ys)
( proveBool (x `elem` (xs ++ ys)) )
prop_28 x xs
= proveBool (x `elem` (xs ++ [x]))
prop_29 x xs
= proveBool (x `elem` ins1 x xs)
prop_30 x xs
= proveBool (x `elem` ins x xs)
prop_31 a b c
= (min (min a b) c =:= min a (min b c))
prop_32 a b
= (min a b =:= min b a)
prop_33 a b
= (min a b === a =:= a <= b)
prop_34 a b
= (min a b === b =:= b <= a)
prop_35 xs
= (dropWhile (\_ -> False) xs =:= xs)
prop_36 xs
= (takeWhile (\_ -> True) xs =:= xs)
prop_37 x xs
= proveBool (not (x `elem` delete x xs))
prop_38 n xs
= (count n (xs ++ [n]) =:= S (count n xs))
prop_39 n x xs
= (count n [x] + count n xs =:= count n (x:xs))
prop_40 xs
= (take Z xs =:= [])
prop_41 n f xs
= (take n (map f xs) =:= map f (take n xs))
prop_42 n x xs
= (take (S n) (x:xs) =:= x : (take n xs))
prop_43 p xs
= (takeWhile p xs ++ dropWhile p xs =:= xs)
prop_44 x xs ys
= (zip (x:xs) ys =:= zipConcat x xs ys)
prop_45 x y xs ys
= (zip (x:xs) (y:ys) =:= (x, y) : zip xs ys)
prop_47 a
= (height (mirror a) =:= height a)
prop_48 xs
= givenBool (not (null xs))
( (butlast xs ++ [last xs] =:= xs) )
prop_49 xs ys
= (butlast (xs ++ ys) =:= butlastConcat xs ys)
prop_50 xs
= (butlast xs =:= take (len xs - S Z) xs)
prop_51 xs x
= (butlast (xs ++ [x]) =:= xs)
prop_52 n xs
= (count n xs =:= count n (rev xs))
prop_53 n xs
= (count n xs =:= count n (sort xs))
prop_54 n m
= ((m + n) - n =:= m)
prop_55 n xs ys
= (drop n (xs ++ ys) =:= drop n xs ++ drop (n - len xs) ys)
prop_56 n m xs
= (drop n (drop m xs) =:= drop (n + m) xs)
prop_57 n m xs
= (drop n (take m xs) =:= take (m - n) (drop n xs))
prop_58 n xs ys
= (drop n (zip xs ys) =:= zip (drop n xs) (drop n ys))
prop_59 xs ys
= ys =:= [] ==> last (xs ++ ys) =:= last xs
prop_60 xs ys
= givenBool (not (null ys))
( (last (xs ++ ys) =:= last ys) )
prop_61 xs ys
= (last (xs ++ ys) =:= lastOfTwo xs ys)
prop_62 xs x
= givenBool (not (null xs))
( (last (x:xs) =:= last xs) )
prop_63 n xs
= givenBool (n < len xs)
( (last (drop n xs) =:= last xs) )
prop_64 x xs
= (last (xs ++ [x]) =:= x)
prop_65 i m =
proveBool (i < S (m + i))
prop_66 p xs
= proveBool (len (filter p xs) <= len xs)
prop_67 xs
= (len (butlast xs) =:= len xs - S Z)
prop_68 n xs
= proveBool (len (delete n xs) <= len xs)
prop_69 n m
= proveBool (n <= (m + n))
prop_70 m n
= givenBool (m <= n)
( proveBool (m <= S n) )
prop_71 x y xs
= given (x === y =:= False)
( (elem x (ins y xs) =:= elem x xs) )
prop_72 i xs
= (rev (drop i xs) =:= take (len xs - i) (rev xs))
prop_73 p xs
= (rev (filter p xs) =:= filter p (rev xs))
prop_74 i xs
= (rev (take i xs) =:= drop (len xs - i) (rev xs))
prop_75 n m xs
= (count n xs + count n [m] =:= count n (m : xs))
prop_76 n m xs
= given (n === m =:= False)
( (count n (xs ++ [m]) =:= count n xs) )
prop_77 x xs
= givenBool (sorted xs)
( proveBool (sorted (insort x xs)) )
prop_78 xs
= proveBool (sorted (sort xs))
prop_79 m n k
= ((S m - n) - S k =:= (m - n) - k)
prop_80 n xs ys
= (take n (xs ++ ys) =:= take n xs ++ take (n - len xs) ys)
= (take n (drop m xs) =:= drop m (take (n + m) xs))
prop_82 n xs ys
= (take n (zip xs ys) =:= zip (take n xs) (take n ys))
prop_83 xs ys zs
= (zip (xs ++ ys) zs =:=
zip xs (take (len xs) zs) ++ zip ys (drop (len xs) zs))
prop_84 xs ys zs
= (zip xs (ys ++ zs) =:=
zip (take (len ys) xs) ys ++ zip (drop (len ys) xs) zs)
prop_85 xs ys
= (len xs =:= len ys) ==>
(zip (rev xs) (rev ys) =:= rev (zip xs ys))
prop_01 :: Eq a => Nat -> [a] -> Bool
prop_02 :: Nat -> [Nat] -> [Nat] -> Bool
prop_03 :: Nat -> [Nat] -> [Nat] -> Bool
prop_04 :: Nat -> [Nat] -> Bool
prop_06 :: Nat -> Nat -> Bool
prop_07 :: Nat -> Nat -> Bool
prop_08 :: Nat -> Nat -> Nat -> Bool
prop_09 :: Nat -> Nat -> Nat -> Bool
prop_10 :: Nat -> Bool
prop_11 :: Eq a => [a] -> Bool
prop_12 :: Eq a => Eq a1 => Nat -> (a1 -> a) -> [a1] -> Bool
prop_13 :: Eq a => Nat -> a -> [a] -> Bool
prop_14 :: Eq a => (a -> Bool) -> [a] -> [a] -> Bool
prop_15 :: Nat -> [Nat] -> Bool
prop_17 :: Nat -> Bool
prop_18 :: Nat -> Nat -> Bool
prop_19 :: Eq a => Nat -> [a] -> Bool
prop_20 :: [Nat] -> Bool
prop_21 :: Nat -> Nat -> Bool
prop_22 :: Nat -> Nat -> Nat -> Bool
prop_23 :: Nat -> Nat -> Bool
prop_24 :: Nat -> Nat -> Bool
prop_25 :: Nat -> Nat -> Bool
prop_28 :: Nat -> [Nat] -> Bool
prop_29 :: Nat -> [Nat] -> Bool
prop_30 :: Nat -> [Nat] -> Bool
prop_31 :: Nat -> Nat -> Nat -> Bool
prop_32 :: Nat -> Nat -> Bool
prop_33 :: Nat -> Nat -> Bool
prop_34 :: Nat -> Nat -> Bool
prop_35 :: Eq a => [a] -> Bool
prop_36 :: Eq a => [a] -> Bool
prop_37 :: Nat -> [Nat] -> Bool
prop_38 :: Nat -> [Nat] -> Bool
prop_39 :: Nat -> Nat -> [Nat] -> Bool
prop_40 :: Eq a => [a] -> Bool
prop_41 :: Eq a => Eq a1 => Nat -> (a1 -> a) -> [a1] -> Bool
prop_42 :: Eq a => Nat -> a -> [a] -> Bool
prop_43 :: Eq a => (a -> Bool) -> [a] -> Bool
prop_44 :: Eq a => Eq b => a -> [a] -> [b] -> Bool
prop_45 :: Eq a => Eq b => a -> b -> [a] -> [b] -> Bool
prop_47 :: Eq a => Tree a -> Bool
prop_49 :: Eq a => [a] -> [a] -> Bool
prop_50 :: Eq a => [a] -> Bool
prop_51 :: Eq a => [a] -> a -> Bool
prop_52 :: Nat -> [Nat] -> Bool
prop_53 :: Nat -> [Nat] -> Bool
prop_54 :: Nat -> Nat -> Bool
prop_55 :: Eq a => Nat -> [a] -> [a] -> Bool
prop_56 :: Eq a => Nat -> Nat -> [a] -> Bool
prop_57 :: Eq a => Nat -> Nat -> [a] -> Bool
prop_58 :: Eq a => Eq b => Nat -> [a] -> [b] -> Bool
prop_64 :: Nat -> [Nat] -> Bool
prop_65 :: Nat -> Nat -> Bool
prop_66 :: Eq a => (a -> Bool) -> [a] -> Bool
prop_67 :: Eq a => [a] -> Bool
prop_68 :: Nat -> [Nat] -> Bool
prop_69 :: Nat -> Nat -> Bool
prop_72 :: Eq a => Nat -> [a] -> Bool
prop_73 :: Eq a => (a -> Bool) -> [a] -> Bool
prop_74 :: Eq a => Nat -> [a] -> Bool
prop_75 :: Nat -> Nat -> [Nat] -> Bool
prop_78 :: [Nat] -> Bool
prop_79 :: Nat -> Nat -> Nat -> Bool
prop_80 :: Eq a => Nat -> [a] -> [a] -> Bool
prop_81 :: Eq a => Nat -> Nat -> [a] -> Bool
prop_82 :: Eq a => Eq b => Nat -> [a] -> [b] -> Bool
prop_83 :: Eq a => Eq b => [a] -> [a] -> [b] -> Bool
prop_84 :: Eq a => Eq a1 => [a] -> [a1] -> [a1] -> Bool
prop_85 :: Eq a => Eq b => [a] -> [b] -> Bool
swapped side for 04
# RULES
" p01 " forall n xs . take n xs + + drop n xs = xs
" p02 " forall n xs ys . count n xs + count n ys = count n ( xs + + ys )
" p04 " forall n xs . count n ( n : xs ) = S ( count n xs )
" p06 " forall n m . n - ( n + m ) = Z
" p07 " forall n m . ( n + m ) - n = m
" p08 " forall k m n . ( k + m ) - ( k + n ) = m - n
" p09 " forall i j k . ( i - j ) - k = i - ( j + k )
" p10 " forall m . m - m = Z
" p11 " forall xs . drop Z xs = xs
" p12 " forall f n xs . drop n ( map f xs ) = map f ( drop n xs )
" p13 " forall n x xs . drop ( S n ) ( x : xs ) = drop n xs
" p14 " forall p xs ys . filter p ( xs + + ys ) = ( filter p xs ) + + ( filter p ys )
" p15 " forall x xs . len ( ins x xs ) = S ( len xs )
" p17 " forall n . n < = Z = n = = = Z
" p19 " forall n xs . len ( drop n xs ) = len xs - n
" p20 " forall xs . len ( sort xs ) = len xs
" p22 " forall a b c . ( max a b ) c = max a ( max b c )
" p23 " forall a b . a b = max b a
" p24 " forall a b . ( a b ) = = = a = b < = a
" p25 " forall a b . ( a b ) = = = b = a < = b
" p31 " forall a b c . min ( min a b ) c = min a ( min b c )
" p32 " forall a b . min a b = min b a
" p33 " forall a b . min a b = = = a = a < = b
" p34 " forall a b . min a b = = = b = b < = a
" p35 " forall xs . ( \ _ - > False ) xs = xs
" p36 " forall xs . ( \ _ - > True ) xs = xs
" p38 " forall n xs . count n ( xs + + [ n ] ) = S ( count n xs )
" p39 " forall n x xs . count n [ x ] + count n xs = count n ( x : xs )
" p40 " forall xs . take Z xs = [ ]
" p41 " forall f n xs . take n ( map f xs ) = map f ( take n xs )
" p42 " forall n x xs . take ( S n ) ( x : xs ) = x : ( take n xs )
" p43 " forall p xs .
" p44 " forall x xs ys . zip ( x : xs ) ys = zipConcat x xs ys
" p45 " forall x y xs ys . zip ( x : xs ) ( y : ys ) = ( x , y ) : zip xs ys
" p46 " forall xs . zip [ ] xs = [ ]
" p47 " forall a . height ( mirror a ) = height a
" p49 " forall xs ys . ( xs + + ys ) =
" p50 " forall xs . butlast xs = take ( len xs - S Z ) xs
" p51 " forall x xs . ( xs + + [ x ] ) = xs
" p52 " forall n xs . count n xs = count n ( rev xs )
" p53 " forall n xs . count n xs = count n ( sort xs )
" p54 " forall n m . ( m + n ) - n = m
" p55 " forall n xs ys . drop n ( xs + + ys ) = drop n xs + + drop ( n - len xs ) ys
" p56 " forall n m xs . drop n ( drop m xs ) = drop ( n + m ) xs
" p57 " forall n m xs . drop n ( take m xs ) = take ( m - n ) ( drop n xs )
" p58 " forall n xs ys . drop n ( zip xs ys ) = zip ( drop n xs ) ( drop n ys )
" p61 " forall xs ys . last ( xs + + ys ) =
" p64 " forall x xs . last ( xs + + [ x ] ) = x
" p67 " forall xs . len ( butlast xs ) = len xs - S Z
" p72 " forall i xs . rev ( drop i xs ) = take ( len xs - i ) ( rev xs )
" p73 " forall p xs . rev ( filter p xs ) = filter p ( rev xs )
" p74 " forall i xs . rev ( take i xs ) = drop ( len xs - i ) ( rev xs )
" p75 " forall n m xs . count n xs + count n [ m ] = count n ( m : xs )
" p79 " forall m n k . ( S m - n ) - S k = ( m - n ) - k
" p80 " forall n xs ys . take n ( xs + + ys ) = take n xs + + take ( n - len xs ) ys
" p81 " forall n m xs . take n ( drop m xs ) = drop m ( take ( n + m ) xs )
" p82 " forall n xs ys . take n ( zip xs ys ) = zip ( take n xs ) ( take n ys )
" p83 " forall xs ys zs . zip ( xs + + ys ) zs = zip xs ( take ( len xs ) zs ) + + zip ys ( drop ( len xs ) zs )
" p84 " forall xs ys zs . zip xs ( ys + + zs ) = zip ( take ( len ys ) xs ) ys + + zip ( drop ( len ys ) xs ) zs
#
"p01" forall n xs . take n xs ++ drop n xs = xs
"p02" forall n xs ys . count n xs + count n ys = count n (xs ++ ys)
"p04" forall n xs . count n (n : xs) = S (count n xs)
"p06" forall n m . n - (n + m) = Z
"p07" forall n m . (n + m) - n = m
"p08" forall k m n . (k + m) - (k + n) = m - n
"p09" forall i j k . (i - j) - k = i - (j + k)
"p10" forall m . m - m = Z
"p11" forall xs . drop Z xs = xs
"p12" forall f n xs . drop n (map f xs) = map f (drop n xs)
"p13" forall n x xs . drop (S n) (x : xs) = drop n xs
"p14" forall p xs ys . filter p (xs ++ ys) = (filter p xs) ++ (filter p ys)
"p15" forall x xs . len (ins x xs) = S (len xs)
"p17" forall n . n <= Z = n === Z
"p19" forall n xs . len (drop n xs) = len xs - n
"p20" forall xs . len (sort xs) = len xs
"p22" forall a b c . max (max a b) c = max a (max b c)
"p23" forall a b . max a b = max b a
"p24" forall a b . (max a b) === a = b <= a
"p25" forall a b . (max a b) === b = a <= b
"p31" forall a b c . min (min a b) c = min a (min b c)
"p32" forall a b . min a b = min b a
"p33" forall a b . min a b === a = a <= b
"p34" forall a b . min a b === b = b <= a
"p35" forall xs . dropWhile (\_ -> False) xs = xs
"p36" forall xs . takeWhile (\_ -> True) xs = xs
"p38" forall n xs . count n (xs ++ [n]) = S (count n xs)
"p39" forall n x xs . count n [x] + count n xs = count n (x:xs)
"p40" forall xs . take Z xs = []
"p41" forall f n xs . take n (map f xs) = map f (take n xs)
"p42" forall n x xs . take (S n) (x:xs) = x : (take n xs)
"p43" forall p xs . takeWhile p xs ++ dropWhile p xs = xs
"p44" forall x xs ys . zip (x:xs) ys = zipConcat x xs ys
"p45" forall x y xs ys . zip (x:xs) (y:ys) = (x, y) : zip xs ys
"p46" forall xs . zip [] xs = []
"p47" forall a . height (mirror a) = height a
"p49" forall xs ys . butlast (xs ++ ys) = butlastConcat xs ys
"p50" forall xs . butlast xs = take (len xs - S Z) xs
"p51" forall x xs . butlast (xs ++ [x]) = xs
"p52" forall n xs . count n xs = count n (rev xs)
"p53" forall n xs . count n xs = count n (sort xs)
"p54" forall n m . (m + n) - n = m
"p55" forall n xs ys . drop n (xs ++ ys) = drop n xs ++ drop (n - len xs) ys
"p56" forall n m xs . drop n (drop m xs) = drop (n + m) xs
"p57" forall n m xs . drop n (take m xs) = take (m - n) (drop n xs)
"p58" forall n xs ys . drop n (zip xs ys) = zip (drop n xs) (drop n ys)
"p61" forall xs ys . last (xs ++ ys) = lastOfTwo xs ys
"p64" forall x xs . last (xs ++ [x]) = x
"p67" forall xs . len (butlast xs) = len xs - S Z
"p72" forall i xs . rev (drop i xs) = take (len xs - i) (rev xs)
"p73" forall p xs . rev (filter p xs) = filter p (rev xs)
"p74" forall i xs . rev (take i xs) = drop (len xs - i) (rev xs)
"p75" forall n m xs . count n xs + count n [m] = count n (m : xs)
"p79" forall m n k . (S m - n) - S k = (m - n) - k
"p80" forall n xs ys . take n (xs ++ ys) = take n xs ++ take (n - len xs) ys
"p81" forall n m xs . take n (drop m xs) = drop m (take (n + m) xs)
"p82" forall n xs ys . take n (zip xs ys) = zip (take n xs) (take n ys)
"p83" forall xs ys zs . zip (xs ++ ys) zs = zip xs (take (len xs) zs) ++ zip ys (drop (len xs) zs)
"p84" forall xs ys zs . zip xs (ys ++ zs) = zip (take (len ys) xs) ys ++ zip (drop (len ys) xs) zs
#-}
# RULES
" p03 " forall n xs ys . prop_03 n xs ys = True
" p05 " forall n x xs . prop_05 n x xs = True
" p16 " forall x xs . prop_16 x xs = True
" p18 " forall i m . prop_18 i m = True
" p21 " forall n m . prop_21 n m = True
" p26 " forall x xs ys . prop_26 x xs ys = True
" p27 " forall x xs ys . prop_27 x xs ys = True
" p28 " forall x xs . prop_28 x xs = True
" p29 " forall x xs . prop_29 x xs = True
" p30 " forall x xs . prop_30 x xs = True
" p37 " forall x xs . prop_37 x xs = True
" p48 " forall xs . prop_48 xs = True
" p59 " forall xs ys . = True
" p60 " forall xs ys . prop_60 xs ys = True
" p62 " forall xs x . prop_62 xs x = True
" p63 " forall n xs . prop_63 n xs = True
" p65 " forall i m . = True
" p66 " forall p xs . prop_66 p xs = True
" p68 " forall n xs . prop_68 n xs = True
" p69 " forall n m . prop_69 n m = True
" p70 " forall m n . prop_70 m n = True
" p71 " forall x y xs . y xs = True
" p76 " forall n m xs . prop_76 n m xs = True
" p77 " forall x xs . prop_77 x xs = True
" p78 " forall xs . prop_78 xs = True
" p85 " forall xs ys . = True
#
"p03" forall n xs ys . prop_03 n xs ys = True
"p05" forall n x xs . prop_05 n x xs = True
"p16" forall x xs . prop_16 x xs = True
"p18" forall i m . prop_18 i m = True
"p21" forall n m . prop_21 n m = True
"p26" forall x xs ys . prop_26 x xs ys = True
"p27" forall x xs ys . prop_27 x xs ys = True
"p28" forall x xs . prop_28 x xs = True
"p29" forall x xs . prop_29 x xs = True
"p30" forall x xs . prop_30 x xs = True
"p37" forall x xs . prop_37 x xs = True
"p48" forall xs . prop_48 xs = True
"p59" forall xs ys . prop_59 xs ys = True
"p60" forall xs ys . prop_60 xs ys = True
"p62" forall xs x . prop_62 xs x = True
"p63" forall n xs . prop_63 n xs = True
"p65" forall i m . prop_65 i m = True
"p66" forall p xs . prop_66 p xs = True
"p68" forall n xs . prop_68 n xs = True
"p69" forall n m . prop_69 n m = True
"p70" forall m n . prop_70 m n = True
"p71" forall x y xs . prop_71 x y xs = True
"p76" forall n m xs . prop_76 n m xs = True
"p77" forall x xs . prop_77 x xs = True
"p78" forall xs . prop_78 xs = True
"p85" forall xs ys . prop_85 xs ys = True
#-}
# RULES
" p03fin " forall n xs ys . ( prop_03 n xs ys ) = walkNatList xs True
" p03finB " forall n xs ys . walkNat n ( prop_03 n xs ys ) = walkNat n ( walkList xs True )
" p04fin " forall n xs . count n ( n : xs ) = walkNat n ( S ( count n xs ) )
" p05finE " forall n x xs . walkNat n ( walkList xs ( prop_05 n x xs ) ) = walkNat n ( walkList xs True )
" p05finF " forall n x xs . walkNat x ( walkList xs ( prop_05 n x xs ) ) = walkNat x ( walkList xs True )
" p06fin " forall n m . n - ( n + m ) = walkNat n Z
" p07fin " forall n m . ( n + m ) - n = walkNat n m
" p08fin " forall k m n . ( k + m ) - ( k + n ) = walkNat k ( m - n )
" p10fin " forall m . m - m = walkNat m Z
" p15finA " forall x xs . walkNatList xs ( len ( ins x xs ) ) = walkNatList xs $ S ( len xs )
" p15finB " forall x xs . walkNat x ( walkList xs ( len ( ins x xs ) ) ) = walkNat x $ walkList xs $ S ( len xs )
" p16finA " forall x xs . walkNat x ( prop_16 x xs ) = walkNat x True
" p18fin " forall i m . prop_18 i m = walkNat i True
" p20finA " forall xs . walkNatList xs ( len ( sort xs ) ) = walkNatList xs ( len xs )
" p21fin " forall n m . prop_21 n m = walkNat n True
" p24fin " forall a b . ( a b ) = = = a = walkNat a ( b < = a )
" p25fin " forall a b . ( a b ) = = = b = walkNat b ( a < = b )
" p26finA " forall x xs ys . ( prop_26 x xs ys ) = walkNatList xs True
" p26finB " forall x xs ys . walkNat x ( walkList xs ( prop_26 x xs ys ) ) = walkNat x $ walkList xs True
" p27finA " forall x xs ys . walkNat x ( walkList xs ( walkList ys ( prop_27 x xs ys ) ) ) = walkNat x $ walkList xs $ walkList ys True
" p28finA " forall x xs . walkList xs ( prop_28 x xs ) = walkNat x $ walkList xs True
" p29finA " forall x xs . walkList xs ( prop_29 x xs ) = walkNat x $ walkList xs True
" p30finA " forall x xs . walkList xs ( prop_30 x xs ) = walkNat x $ walkList xs True
" p37finB " forall x xs . walkNatList xs ( prop_37 x xs ) = walkNatList xs True
" p37finC " forall x xs . walkNat x ( prop_37 x xs ) = walkNat x $ walkList xs True
" p38finB " forall n xs . walkList xs ( count n ( xs + + [ n ] ) ) = walkNat n $ walkList xs $ S ( count n xs )
" p48finB " forall xs . walkNatList xs ( prop_48 xs ) = walkNatList xs True
" p52finA " forall n xs . walkNatList xs ( count n xs ) = walkNatList xs ( count n ( rev xs ) )
" p53finA " forall n xs . walkNatList xs ( count n xs ) = walkNatList xs ( count n ( sort xs ) )
" p54fin " forall n m . ( m + n ) - n = walkNat n m
" p57finA " forall n m xs . walkNat n ( drop n ( take m xs ) ) = walkNat n ( take ( m - n ) ( drop n xs ) )
" p57finB " forall n m xs . ( drop n ( take m xs ) ) = walkNat m ( take ( m - n ) ( drop n xs ) )
" p59finA " forall xs ys . ( prop_59 xs ys ) = walkNatList xs True
" p60finB " forall xs ys . walkList xs ( walkNatList ys ( prop_60 xs ys ) ) = walkList xs $ walkNatList ys True
" p61fin " forall xs ys . last ( xs + + ys ) = walkList xs ( lastOfTwo xs ys )
" p62finA " forall xs x . walkNatList xs ( prop_62 xs x ) = walkNatList xs True
" p63finA " forall n xs . walkNatList xs ( prop_63 n xs ) = walkNatList xs True
" p64fin " forall x xs . last ( xs + + [ x ] ) = walkList xs x
" p65finA " forall i m . = walkNat i True
" p66fin " forall p xs . prop_66 p xs = walkList xs True
" p68finA " forall n xs . walkNat n ( prop_68 n xs ) = walkNat n $ walkList xs True
" p68finB " forall n xs . walkNatList xs ( prop_68 n xs ) = walkNatList xs True
" p69finA " forall n m . prop_69 n m = walkNat n True
" p70finC " forall m n . walkNat m ( prop_70 m n ) = walkNat m True
" p70finD " forall m n . walkNat n ( prop_70 m n ) = walkNat n True
" p71finA " forall x y xs . walkNatList xs ( prop_71 x y xs ) = walkNat x $ walkNatList xs True
" p71finB " forall x y xs . walkNatList xs ( prop_71 x y xs ) = walkNat y $ walkNatList xs True
" p75fin " forall n m xs . count n xs + count n [ m ] = walkList xs $ count n ( m : xs )
" p76finB " forall n m xs . walkList xs ( prop_76 n m xs ) = walkNat n $ walkList xs True
" p76finC " forall n m xs . walkNatList xs ( prop_76 n m xs ) = walkNat m $ walkNatList xs True
" p77finA " forall x xs . walkNatList xs ( prop_77 x xs ) = walkNatList xs True
" p78finB " forall xs . walkNatList xs ( prop_78 xs ) = walkNatList xs True
" p81fin " forall n m xs . ( take n ( drop m xs ) ) = drop m ( take ( n + m ) xs )
" p81finA " forall n m xs . walkList xs ( take n ( drop m xs ) ) = drop m ( take ( n + m ) xs )
" p85finB " forall xs ys . walkList xs ( prop_85 xs ys ) = walkList xs True
" p85finC " forall xs ys . walkList ys ( ) = walkList ys True
#
"p03fin" forall n xs ys . walkNatList xs (prop_03 n xs ys) = walkNatList xs True
"p03finB" forall n xs ys . walkNat n (prop_03 n xs ys) = walkNat n (walkList xs True)
"p04fin" forall n xs . count n (n : xs) = walkNat n (S (count n xs))
"p05finE" forall n x xs . walkNat n (walkList xs (prop_05 n x xs)) = walkNat n (walkList xs True)
"p05finF" forall n x xs . walkNat x (walkList xs (prop_05 n x xs)) = walkNat x (walkList xs True)
"p06fin" forall n m . n - (n + m) = walkNat n Z
"p07fin" forall n m . (n + m) - n = walkNat n m
"p08fin" forall k m n . (k + m) - (k + n) = walkNat k (m - n)
"p10fin" forall m . m - m = walkNat m Z
"p15finA" forall x xs . walkNatList xs (len (ins x xs)) = walkNatList xs $ S (len xs)
"p15finB" forall x xs . walkNat x (walkList xs (len (ins x xs))) = walkNat x $ walkList xs $ S (len xs)
"p16finA" forall x xs . walkNat x (prop_16 x xs) = walkNat x True
"p18fin" forall i m . prop_18 i m = walkNat i True
"p20finA" forall xs . walkNatList xs (len (sort xs)) = walkNatList xs (len xs)
"p21fin" forall n m . prop_21 n m = walkNat n True
"p24fin" forall a b . (max a b) === a = walkNat a (b <= a)
"p25fin" forall a b . (max a b) === b = walkNat b (a <= b)
"p26finA" forall x xs ys . walkNatList xs (prop_26 x xs ys) = walkNatList xs True
"p26finB" forall x xs ys . walkNat x (walkList xs (prop_26 x xs ys)) = walkNat x $ walkList xs True
"p27finA" forall x xs ys . walkNat x (walkList xs (walkList ys (prop_27 x xs ys))) = walkNat x $ walkList xs $ walkList ys True
"p28finA" forall x xs . walkList xs (prop_28 x xs) = walkNat x $ walkList xs True
"p29finA" forall x xs . walkList xs (prop_29 x xs) = walkNat x $ walkList xs True
"p30finA" forall x xs . walkList xs (prop_30 x xs) = walkNat x $ walkList xs True
"p37finB" forall x xs . walkNatList xs (prop_37 x xs) = walkNatList xs True
"p37finC" forall x xs . walkNat x (prop_37 x xs) = walkNat x $ walkList xs True
"p38finB" forall n xs . walkList xs (count n (xs ++ [n])) = walkNat n $ walkList xs $ S (count n xs)
"p48finB" forall xs . walkNatList xs (prop_48 xs) = walkNatList xs True
"p52finA" forall n xs . walkNatList xs (count n xs) = walkNatList xs (count n (rev xs))
"p53finA" forall n xs . walkNatList xs (count n xs) = walkNatList xs (count n (sort xs))
"p54fin" forall n m . (m + n) - n = walkNat n m
"p57finA" forall n m xs . walkNat n (drop n (take m xs)) = walkNat n (take (m - n) (drop n xs))
"p57finB" forall n m xs . walkNat m (drop n (take m xs)) = walkNat m (take (m - n) (drop n xs))
"p59finA" forall xs ys . walkNatList xs (prop_59 xs ys) = walkNatList xs True
"p60finB" forall xs ys . walkList xs (walkNatList ys (prop_60 xs ys)) = walkList xs $ walkNatList ys True
"p61fin" forall xs ys . last (xs ++ ys) = walkList xs (lastOfTwo xs ys)
"p62finA" forall xs x . walkNatList xs (prop_62 xs x) = walkNatList xs True
"p63finA" forall n xs . walkNatList xs (prop_63 n xs) = walkNatList xs True
"p64fin" forall x xs . last (xs ++ [x]) = walkList xs x
"p65finA" forall i m . prop_65 i m = walkNat i True
"p66fin" forall p xs . prop_66 p xs = walkList xs True
"p68finA" forall n xs . walkNat n (prop_68 n xs) = walkNat n $ walkList xs True
"p68finB" forall n xs . walkNatList xs (prop_68 n xs) = walkNatList xs True
"p69finA" forall n m . prop_69 n m = walkNat n True
"p70finC" forall m n . walkNat m (prop_70 m n) = walkNat m True
"p70finD" forall m n . walkNat n (prop_70 m n) = walkNat n True
"p71finA" forall x y xs . walkNatList xs (prop_71 x y xs) = walkNat x $ walkNatList xs True
"p71finB" forall x y xs . walkNatList xs (prop_71 x y xs) = walkNat y $ walkNatList xs True
"p75fin" forall n m xs . count n xs + count n [m] = walkList xs $ count n (m : xs)
"p76finB" forall n m xs . walkList xs (prop_76 n m xs) = walkNat n $ walkList xs True
"p76finC" forall n m xs . walkNatList xs (prop_76 n m xs) = walkNat m $ walkNatList xs True
"p77finA" forall x xs . walkNatList xs (prop_77 x xs) = walkNatList xs True
"p78finB" forall xs . walkNatList xs (prop_78 xs) = walkNatList xs True
"p81fin" forall n m xs . walkNat m (take n (drop m xs)) = drop m (take (n + m) xs)
"p81finA" forall n m xs . walkList xs (take n (drop m xs)) = drop m (take (n + m) xs)
"p85finB" forall xs ys . walkList xs (prop_85 xs ys) = walkList xs True
"p85finC" forall xs ys . walkList ys (prop_85 xs ys) = walkList ys True
#-}
walkNat :: Nat -> a -> a
walkNat Z a = a
walkNat (S x) a = walkNat x a
walkList :: [a] -> b -> b
walkList [] a = a
walkList (_:xs) a = walkList xs a
walkNatList :: [Nat] -> a -> a
walkNatList xs a = case xs of
[] -> a
y:ys -> walkNat y $ walkNatList ys a
|
d6091c06d3bde7031b0058e369532c87d77ede536d970c9db0bc7608bad2af71 | jsthomas/tidy_email | tidy_email_sendgrid.mli | type config = {
* An alphanumeric string found on the console .
base_url : string; (** e.g. *)
}
type http_post =
?body:Cohttp_lwt.Body.t ->
?headers:Cohttp.Header.t ->
Uri.t ->
(Cohttp.Response.t * Cohttp_lwt.Body.t) Lwt.t
val backend :
?client:http_post -> config -> Tidy_email.Email.t -> (unit, string) Lwt_result.t
* If the underlying request to 's API is unsuccessful , the
response body is provided in the result .
client allows the user to customize how their HTTP post is
performed . Most users will want to use the default .
response body is provided in the result.
client allows the user to customize how their HTTP post is
performed. Most users will want to use the default. *)
| null | https://raw.githubusercontent.com/jsthomas/tidy_email/7ead0e446c2f22808332964870fc2356deb9c8bb/sendgrid/src/tidy_email_sendgrid.mli | ocaml | * e.g. | type config = {
* An alphanumeric string found on the console .
}
type http_post =
?body:Cohttp_lwt.Body.t ->
?headers:Cohttp.Header.t ->
Uri.t ->
(Cohttp.Response.t * Cohttp_lwt.Body.t) Lwt.t
val backend :
?client:http_post -> config -> Tidy_email.Email.t -> (unit, string) Lwt_result.t
* If the underlying request to 's API is unsuccessful , the
response body is provided in the result .
client allows the user to customize how their HTTP post is
performed . Most users will want to use the default .
response body is provided in the result.
client allows the user to customize how their HTTP post is
performed. Most users will want to use the default. *)
|
2ff955107a75d651665f112e5f23fdee0f63aa4d76c5354596690330650eedbc | janestreet/universe | msgpack.ml | open Base
module Message = Message
module Internal = struct
module Parser = Parser
module Serializer = Serializer
end
module Custom = struct
type t = Message.custom =
{ type_id : int
; data : Bytes.t
}
[@@deriving sexp, equal]
end
type t = Message.t =
| Nil
| Integer of int
| Int64 of Int64.t
| UInt64 of Int64.t
| Boolean of bool
| Floating of float
| Array of t list
| Map of (t * t) list
| String of string
| Binary of Bytes.t
| Extension of Custom.t
[@@deriving sexp, equal]
let t_of_string = Parser.parse
let t_of_string_exn s = Or_error.ok_exn (Parser.parse s)
let string_of_t_exn = Serializer.message_to_string_exn
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/vcaml/msgpack/src/msgpack.ml | ocaml | open Base
module Message = Message
module Internal = struct
module Parser = Parser
module Serializer = Serializer
end
module Custom = struct
type t = Message.custom =
{ type_id : int
; data : Bytes.t
}
[@@deriving sexp, equal]
end
type t = Message.t =
| Nil
| Integer of int
| Int64 of Int64.t
| UInt64 of Int64.t
| Boolean of bool
| Floating of float
| Array of t list
| Map of (t * t) list
| String of string
| Binary of Bytes.t
| Extension of Custom.t
[@@deriving sexp, equal]
let t_of_string = Parser.parse
let t_of_string_exn s = Or_error.ok_exn (Parser.parse s)
let string_of_t_exn = Serializer.message_to_string_exn
| |
c77337dd8356a0a926132114739ae11f9605eb3a8107f108b81150dd7262c8e9 | philnguyen/soft-contract | quick-sample.rkt | #lang racket/base
(provide quick-sample)
;; -----------------------------------------------------------------------------
(require
require-typed-check
racket/file
)
(require (only-in "quads.rkt"
( - > * ( QuadAttrs ) # : rest USQ Quad ) )
block-break ;(-> QuadAttrs Quad))
( - > * ( QuadAttrs ) # : rest USQ Quad ) )
column-break ;(-> Quad))
page-break ;(-> Quad))
word ;(-> QuadAttrs String Quad))
))
;; =============================================================================
(define (quick-sample)
(block '((measure . 240.0) (font . "Times New Roman") (leading . 16.0) (vmeasure . 300.0) (size . 13.5) (x-align . justify) (x-align-last-line . left))
(box '((width . 15.0)))
(block '()
(block '((weight . bold)) "Hot " (word '((size . 22.0)) "D") "ang, My Fellow Americans.")
" This "
(block '((no-break . #t)) "is some truly")
" nonsense generated from my typesetting system, which is called Quad. I’m writing this in a source file in DrRacket. When I click [Run], a PDF pops out. Not bad\u200a—\u200aand no LaTeX needed. Quad, however, does use the fancy linebreaking algorithm developed for TeX. (It also includes a faster linebreaking algorithm for when speed is more important than quality.) Of course, it can also handle "
(block '((font . "Courier")) "different fonts,")
(block '((style . italic)) " styles, ")
(word '((size . 14.0) (weight . bold)) "and sizes-")
" within the same line. As you can see, it can also justify paragraphs."
(block-break '())
(box '((width . 15.0)))
(block '() "“Each horizontal row represents " (box '((color . "Red") (background . "Yellow")) "an OS-level thread,") " and the colored dots represent important events in the execution of the program (they are color-coded to distinguish one event type from another). The upper-left blue dot in the timeline represents the future’s creation. The future executes for a brief period (represented by a green bar in the second line) on thread 1, and then pauses to allow the runtime thread to perform a future-unsafe operation.")
(column-break)
(box '((width . 15.0)))
(block '() "In the Racket implementation, future-unsafe operations fall into one of two categories. A blocking operation halts the evaluation of the future, and will not allow it to continue until it is touched. After the operation completes within touch, the remainder of the future’s work will be evaluated sequentially by the runtime thread. A synchronized operation also halts the future, but the runtime thread may perform the operation at any time and, once completed, the future may continue running in parallel. Memory allocation and JIT compilation are two common examples of synchronized operations." (page-break) "another page"))))
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/gradual-typing-benchmarks/quadBG/quick-sample.rkt | racket | -----------------------------------------------------------------------------
(-> QuadAttrs Quad))
(-> Quad))
(-> Quad))
(-> QuadAttrs String Quad))
============================================================================= | #lang racket/base
(provide quick-sample)
(require
require-typed-check
racket/file
)
(require (only-in "quads.rkt"
( - > * ( QuadAttrs ) # : rest USQ Quad ) )
( - > * ( QuadAttrs ) # : rest USQ Quad ) )
))
(define (quick-sample)
(block '((measure . 240.0) (font . "Times New Roman") (leading . 16.0) (vmeasure . 300.0) (size . 13.5) (x-align . justify) (x-align-last-line . left))
(box '((width . 15.0)))
(block '()
(block '((weight . bold)) "Hot " (word '((size . 22.0)) "D") "ang, My Fellow Americans.")
" This "
(block '((no-break . #t)) "is some truly")
" nonsense generated from my typesetting system, which is called Quad. I’m writing this in a source file in DrRacket. When I click [Run], a PDF pops out. Not bad\u200a—\u200aand no LaTeX needed. Quad, however, does use the fancy linebreaking algorithm developed for TeX. (It also includes a faster linebreaking algorithm for when speed is more important than quality.) Of course, it can also handle "
(block '((font . "Courier")) "different fonts,")
(block '((style . italic)) " styles, ")
(word '((size . 14.0) (weight . bold)) "and sizes-")
" within the same line. As you can see, it can also justify paragraphs."
(block-break '())
(box '((width . 15.0)))
(block '() "“Each horizontal row represents " (box '((color . "Red") (background . "Yellow")) "an OS-level thread,") " and the colored dots represent important events in the execution of the program (they are color-coded to distinguish one event type from another). The upper-left blue dot in the timeline represents the future’s creation. The future executes for a brief period (represented by a green bar in the second line) on thread 1, and then pauses to allow the runtime thread to perform a future-unsafe operation.")
(column-break)
(box '((width . 15.0)))
(block '() "In the Racket implementation, future-unsafe operations fall into one of two categories. A blocking operation halts the evaluation of the future, and will not allow it to continue until it is touched. After the operation completes within touch, the remainder of the future’s work will be evaluated sequentially by the runtime thread. A synchronized operation also halts the future, but the runtime thread may perform the operation at any time and, once completed, the future may continue running in parallel. Memory allocation and JIT compilation are two common examples of synchronized operations." (page-break) "another page"))))
|
8cbb2dda4b686e68a4a919986566aa8164707afa17de03b673db7dcc73f4e6f2 | mpickering/apply-refact | Import6.hs | import A; import A hiding (C) | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Import6.hs | haskell | import A; import A hiding (C) | |
125937f857c5bed0abd195c8fe812945c51bf0f46e22bb8284359901bbab4357 | cs340ppp/lectures | Lect05Spec.hs | module Lect05Spec (spec) where
import Test.Hspec
import Test.HUnit
import Test.HUnit.Approx
import Test.QuickCheck
import Control.Exception
import Lect05 (c2k, c2f, f2c, mySum, quadRoots)
import Test.Hspec.QuickCheck (prop)
spec :: Spec
spec = describe "Lect05" $ do
describe "Celsius conversions" $ do
describe "c2k" $ do
it "works for known examples" $ do
c2k 0 `shouldBe` 273.15
c2k 100 `shouldBe` 373.15
it "fails for sub-abs-zero temperatures" $ do
evaluate (c2k (-274)) `shouldThrow` anyException
describe "c2f" $ do
it "works for known examples" $ do
c2f 0 `shouldBe` 32
c2f 100 `shouldBe` 212
c2f 500.1 `shouldSatisfy` (=~= 932.18)
describe "f2c" $ do
it "works for known examples" $ do
f2c 32 `shouldBe` 0
f2c 212 `shouldBe` 100
f2c 932.18 `shouldSatisfy` (=~= 500.1)
describe "mySum" $ do
it "matches the reference implementation" $
property prop_sum
it "demonstrates distributivity w.r.t. multiplication" $
property prop_distMultOverAdd
it "demonstrates commutativity" $
property prop_commAdd
describe "quadRoots" $ do
it "works for known examples" $ do
quadRoots 1 3 2 `shouldMatchTuple` (-1, -2)
quadRoots 1 4 4 `shouldMatchTuple` (-2, -2)
quadRoots 1 5 6 `shouldMatchTuple` (-2, -3)
it "fails when non-real roots exist" $ do
evaluate (quadRoots 1 0 1) `shouldThrow` anyException
it "works correctly with perfect squares" $
property prop_perfSquare
it "works correctly with factorable quadratic equations" $
property prop_solvesFactored
infix 4 =~=
(=~=) :: (Floating a, Ord a) => a -> a -> Bool
x =~= y = abs (x - y) < 0.0001
shouldMatchTuple :: (Eq a, Show a) => (a, a) -> (a, a) -> Expectation
shouldMatchTuple (x1, x2) (y1, y2) = [x1, x2] `shouldMatchList` [y1, y2]
prop_c2f2c :: Double -> Bool
prop_c2f2c c = f2c (c2f c) =~= c
cTemp :: Gen Double
cTemp = choose (-273.15, 1000)
prop_c2f2c' :: Property
prop_c2f2c' = forAll cTemp prop_c2f2c
prop_c2f2c'' :: Double -> Property
prop_c2f2c'' c = c >= -273.15 ==> f2c (c2f c) =~= c
prop_sum :: [Integer] -> Bool
prop_sum xs = mySum xs == sum xs
prop_distMultOverAdd :: Integer -> [Integer] -> Bool
prop_distMultOverAdd n xs = mySum [n*x | x <- xs] == n * mySum xs
prop_commAdd :: [Integer] -> Property
prop_commAdd xs = forAll (shuffle xs) (\ys -> mySum xs == mySum ys)
prop_perfSquare :: Double -> Bool
prop_perfSquare f = r1 =~= r2
where b = 2*f
c = f^2
(r1,r2) = quadRoots 1 b c
prop_solvesFactored :: Double -> Double -> Bool
prop_solvesFactored f1 f2 = r1^2 + b*r1 + c =~= 0
&& r2^2 + b*r2 + c =~= 0
where b = f1 + f2
c = f1 * f2
(r1,r2) = quadRoots 1 b c
| null | https://raw.githubusercontent.com/cs340ppp/lectures/acdf855cea9b0344b07919803eadf82c9a2964de/test/Lect05Spec.hs | haskell | module Lect05Spec (spec) where
import Test.Hspec
import Test.HUnit
import Test.HUnit.Approx
import Test.QuickCheck
import Control.Exception
import Lect05 (c2k, c2f, f2c, mySum, quadRoots)
import Test.Hspec.QuickCheck (prop)
spec :: Spec
spec = describe "Lect05" $ do
describe "Celsius conversions" $ do
describe "c2k" $ do
it "works for known examples" $ do
c2k 0 `shouldBe` 273.15
c2k 100 `shouldBe` 373.15
it "fails for sub-abs-zero temperatures" $ do
evaluate (c2k (-274)) `shouldThrow` anyException
describe "c2f" $ do
it "works for known examples" $ do
c2f 0 `shouldBe` 32
c2f 100 `shouldBe` 212
c2f 500.1 `shouldSatisfy` (=~= 932.18)
describe "f2c" $ do
it "works for known examples" $ do
f2c 32 `shouldBe` 0
f2c 212 `shouldBe` 100
f2c 932.18 `shouldSatisfy` (=~= 500.1)
describe "mySum" $ do
it "matches the reference implementation" $
property prop_sum
it "demonstrates distributivity w.r.t. multiplication" $
property prop_distMultOverAdd
it "demonstrates commutativity" $
property prop_commAdd
describe "quadRoots" $ do
it "works for known examples" $ do
quadRoots 1 3 2 `shouldMatchTuple` (-1, -2)
quadRoots 1 4 4 `shouldMatchTuple` (-2, -2)
quadRoots 1 5 6 `shouldMatchTuple` (-2, -3)
it "fails when non-real roots exist" $ do
evaluate (quadRoots 1 0 1) `shouldThrow` anyException
it "works correctly with perfect squares" $
property prop_perfSquare
it "works correctly with factorable quadratic equations" $
property prop_solvesFactored
infix 4 =~=
(=~=) :: (Floating a, Ord a) => a -> a -> Bool
x =~= y = abs (x - y) < 0.0001
shouldMatchTuple :: (Eq a, Show a) => (a, a) -> (a, a) -> Expectation
shouldMatchTuple (x1, x2) (y1, y2) = [x1, x2] `shouldMatchList` [y1, y2]
prop_c2f2c :: Double -> Bool
prop_c2f2c c = f2c (c2f c) =~= c
cTemp :: Gen Double
cTemp = choose (-273.15, 1000)
prop_c2f2c' :: Property
prop_c2f2c' = forAll cTemp prop_c2f2c
prop_c2f2c'' :: Double -> Property
prop_c2f2c'' c = c >= -273.15 ==> f2c (c2f c) =~= c
prop_sum :: [Integer] -> Bool
prop_sum xs = mySum xs == sum xs
prop_distMultOverAdd :: Integer -> [Integer] -> Bool
prop_distMultOverAdd n xs = mySum [n*x | x <- xs] == n * mySum xs
prop_commAdd :: [Integer] -> Property
prop_commAdd xs = forAll (shuffle xs) (\ys -> mySum xs == mySum ys)
prop_perfSquare :: Double -> Bool
prop_perfSquare f = r1 =~= r2
where b = 2*f
c = f^2
(r1,r2) = quadRoots 1 b c
prop_solvesFactored :: Double -> Double -> Bool
prop_solvesFactored f1 f2 = r1^2 + b*r1 + c =~= 0
&& r2^2 + b*r2 + c =~= 0
where b = f1 + f2
c = f1 * f2
(r1,r2) = quadRoots 1 b c
| |
7ecd83df5eda0ff9621a0645e844e2da95335cd655a9aed1d41fb2e5b0950a07 | atlas-engineer/cl-readability | package.lisp | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(defpackage #:readability
(:use #:cl)
(:import-from #:serapeum #:export-always))
| null | https://raw.githubusercontent.com/atlas-engineer/cl-readability/6a5ff00618aea0ea0ae29aacfbbb1ed8202c20ed/package.lisp | lisp | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(defpackage #:readability
(:use #:cl)
(:import-from #:serapeum #:export-always))
| |
a3e556433125572786d69610feb2292fecc83aefb3cffa02302c0752d3d4d7de | finkel-lang/finkel | sige.hs | (42 :: Int) -- Haskell
| null | https://raw.githubusercontent.com/finkel-lang/finkel/c3c7729d5228bd7e0cf76e8ff05fe2f79a0ec0a2/doc/include/language-syntax/expr/sige.hs | haskell | Haskell | |
c5fd3b74d1fc91069c4d2db4cfff6d44a9421ffe2871d2c77c16c34c8d1dd7af | facebook/duckling | Tests.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Numeral.AR.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Numeral.AR.Corpus
import Duckling.Testing.Asserts
import Duckling.Testing.Types hiding (examples)
import qualified Duckling.Numeral.AR.EG.Corpus as EG
tests :: TestTree
tests = testGroup "AR Tests"
[ makeCorpusTest [Seal Numeral] corpus
, localeTests
]
localeTests :: TestTree
localeTests = testGroup "Locale Tests"
[ testGroup "AR_EG Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeEG EG.allExamples
]
]
where
localeEG = makeLocale AR $ Just EG
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Numeral/AR/Tests.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Numeral.AR.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Numeral.AR.Corpus
import Duckling.Testing.Asserts
import Duckling.Testing.Types hiding (examples)
import qualified Duckling.Numeral.AR.EG.Corpus as EG
tests :: TestTree
tests = testGroup "AR Tests"
[ makeCorpusTest [Seal Numeral] corpus
, localeTests
]
localeTests :: TestTree
localeTests = testGroup "Locale Tests"
[ testGroup "AR_EG Tests"
[ makeCorpusTest [Seal Numeral] $ withLocale corpus localeEG EG.allExamples
]
]
where
localeEG = makeLocale AR $ Just EG
|
8532ef3857f40195792255c24d5f4a3621432e6d1a1cd514412b7a8821f63087 | lambdacube3d/lambdacube-edsl | ParseTrifecta.hs | # LANGUAGE GeneralizedNewtypeDeriving #
import Data.ByteString.Char8 (unpack,pack)
import qualified Data.ByteString.Char8 as BS
import Text.PrettyPrint.ANSI.Leijen (pretty)
import Data.Monoid
import Control.Applicative
import Text.Trifecta
import Text.Trifecta.Indentation as I
import Text.Trifecta.Delta
import Text.Parser.Token.Style
import qualified Data.HashSet as HashSet
import Control.Monad
import Text.Parser.LookAhead
import Compositional hiding (test)
type Indentation = Int
data IndentationRel = Eq | Any | Const Indentation | Ge | Gt deriving ( Show , Eq )
class IndentationParsing m where
localTokenMode : : ( IndentationRel - > IndentationRel ) - > m a - > m a
localIndentation : : IndentationRel - > m a - > m a
absoluteIndentation : : m a - > m a
ignoreAbsoluteIndentation : : m a - > m a
localAbsoluteIndentation : : m a - > m a
type Indentation = Int
data IndentationRel = Eq | Any | Const Indentation | Ge | Gt deriving (Show, Eq)
class IndentationParsing m where
localTokenMode :: (IndentationRel -> IndentationRel) -> m a -> m a
localIndentation :: IndentationRel -> m a -> m a
absoluteIndentation :: m a -> m a
ignoreAbsoluteIndentation :: m a -> m a
localAbsoluteIndentation :: m a -> m a
-}
type P a = IndentationParserT Char (LCParser Parser) a
newtype LCParser p a = LCParser { runLCParser :: p a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, Parsing, CharParsing, LookAheadParsing, DeltaParsing)
instance TokenParsing p => TokenParsing (LCParser p) where
someSpace = LCParser $ buildSomeSpaceParser someSpace lcCommentStyle
nesting = LCParser . nesting . runLCParser
highlight h = LCParser . highlight h . runLCParser
semi = token $ char ';' <?> ";"
token p = p <* whiteSpace
buildSomeSpaceParser : : = > m ( ) - > CommentStyle - > m ( )
: : TokenParsing m = > IdentifierStyle m
lcSpace =
lcCommentStyle = haskellCommentStyle
lcIdents = haskell98Idents { _styleReserved = HashSet.fromList reservedIdents }
where
reservedIdents =
[ "let"
, "upper"
, "in"
, "add"
, "show"
, "read"
]
kw w = reserve lcIdents w
op w = reserve haskellOps w
var :: P String
var = ident lcIdents
lit :: P Lit
lit = LFloat <$ try double <|> LInt <$ integer <|> LChar <$ charLiteral
letin :: P Exp
letin = do
localIndentation Ge $ do
l <- kw "let" *> (localIndentation Gt $ localAbsoluteIndentation $ some def) -- WORKS
a <- kw "in" *> (localIndentation Gt expr)
return $ foldr ($) a l
def :: P (Exp -> Exp)
def = (\p1 n a d p2 e -> ELet (p1,p2) n (foldr (args (p1,p2)) d a) e) <$> position <*> var <*> many var <* kw "=" <*> localIndentation Gt expr <*> position
where
args r n e = ELam r n e
expr :: P Exp
expr = lam <|> letin <|> formula
formula = (\p1 l p2 -> foldl1 (EApp (p1,p2)) l) <$> position <*> some atom <*> position
atom =
(\p1 f p2 -> EPrimFun (p1,p2) f) <$> position <*> primFun <*> position <|>
(\p1 l p2 -> ELit (p1,p2) l) <$> position <*> lit <*> position <|>
(\p1 v p2 -> EVar (p1,p2) v) <$> position <*> var <*> position <|>
(\p1 v p2 -> if length v == 1 then head v else ETuple (p1,p2) v) <$> position <*> parens (commaSep expr) <*> position <|>
parens expr
primFun = PUpper <$ kw "upper" <|>
PAddI <$ kw "add" <|>
PShow <$ kw "show" <|>
PRead <$ kw "read"
lam :: P Exp
lam = (\p1 n e p2 -> ELam (p1,p2) n e) <$> position <* op "\\" <*> var <* op "->" <*> expr <*> position
indentState = mkIndentationState 0 infIndentation True Ge
test' = test "example01.lc"
test :: String -> IO ()
test fname = do
src <- BS.readFile fname
case parseByteString (runLCParser $ evalIndentationParserT (whiteSpace *> expr <* eof) indentState) (Directed (pack fname) 0 0 0 0) src of
Failure m -> print m
Success e -> do
--let r = render s
print $ pretty $ delta r
--print $ pretty r
print e
case inference src e of
Right t -> putStrLn $ show t
Left m -> putStrLn $ "error: " ++ m
| null | https://raw.githubusercontent.com/lambdacube3d/lambdacube-edsl/4347bb0ed344e71c0333136cf2e162aec5941df7/typesystem/ParseTrifecta.hs | haskell | WORKS
let r = render s
print $ pretty r | # LANGUAGE GeneralizedNewtypeDeriving #
import Data.ByteString.Char8 (unpack,pack)
import qualified Data.ByteString.Char8 as BS
import Text.PrettyPrint.ANSI.Leijen (pretty)
import Data.Monoid
import Control.Applicative
import Text.Trifecta
import Text.Trifecta.Indentation as I
import Text.Trifecta.Delta
import Text.Parser.Token.Style
import qualified Data.HashSet as HashSet
import Control.Monad
import Text.Parser.LookAhead
import Compositional hiding (test)
type Indentation = Int
data IndentationRel = Eq | Any | Const Indentation | Ge | Gt deriving ( Show , Eq )
class IndentationParsing m where
localTokenMode : : ( IndentationRel - > IndentationRel ) - > m a - > m a
localIndentation : : IndentationRel - > m a - > m a
absoluteIndentation : : m a - > m a
ignoreAbsoluteIndentation : : m a - > m a
localAbsoluteIndentation : : m a - > m a
type Indentation = Int
data IndentationRel = Eq | Any | Const Indentation | Ge | Gt deriving (Show, Eq)
class IndentationParsing m where
localTokenMode :: (IndentationRel -> IndentationRel) -> m a -> m a
localIndentation :: IndentationRel -> m a -> m a
absoluteIndentation :: m a -> m a
ignoreAbsoluteIndentation :: m a -> m a
localAbsoluteIndentation :: m a -> m a
-}
type P a = IndentationParserT Char (LCParser Parser) a
newtype LCParser p a = LCParser { runLCParser :: p a }
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, Parsing, CharParsing, LookAheadParsing, DeltaParsing)
instance TokenParsing p => TokenParsing (LCParser p) where
someSpace = LCParser $ buildSomeSpaceParser someSpace lcCommentStyle
nesting = LCParser . nesting . runLCParser
highlight h = LCParser . highlight h . runLCParser
semi = token $ char ';' <?> ";"
token p = p <* whiteSpace
buildSomeSpaceParser : : = > m ( ) - > CommentStyle - > m ( )
: : TokenParsing m = > IdentifierStyle m
lcSpace =
lcCommentStyle = haskellCommentStyle
lcIdents = haskell98Idents { _styleReserved = HashSet.fromList reservedIdents }
where
reservedIdents =
[ "let"
, "upper"
, "in"
, "add"
, "show"
, "read"
]
kw w = reserve lcIdents w
op w = reserve haskellOps w
var :: P String
var = ident lcIdents
lit :: P Lit
lit = LFloat <$ try double <|> LInt <$ integer <|> LChar <$ charLiteral
letin :: P Exp
letin = do
localIndentation Ge $ do
a <- kw "in" *> (localIndentation Gt expr)
return $ foldr ($) a l
def :: P (Exp -> Exp)
def = (\p1 n a d p2 e -> ELet (p1,p2) n (foldr (args (p1,p2)) d a) e) <$> position <*> var <*> many var <* kw "=" <*> localIndentation Gt expr <*> position
where
args r n e = ELam r n e
expr :: P Exp
expr = lam <|> letin <|> formula
formula = (\p1 l p2 -> foldl1 (EApp (p1,p2)) l) <$> position <*> some atom <*> position
atom =
(\p1 f p2 -> EPrimFun (p1,p2) f) <$> position <*> primFun <*> position <|>
(\p1 l p2 -> ELit (p1,p2) l) <$> position <*> lit <*> position <|>
(\p1 v p2 -> EVar (p1,p2) v) <$> position <*> var <*> position <|>
(\p1 v p2 -> if length v == 1 then head v else ETuple (p1,p2) v) <$> position <*> parens (commaSep expr) <*> position <|>
parens expr
primFun = PUpper <$ kw "upper" <|>
PAddI <$ kw "add" <|>
PShow <$ kw "show" <|>
PRead <$ kw "read"
lam :: P Exp
lam = (\p1 n e p2 -> ELam (p1,p2) n e) <$> position <* op "\\" <*> var <* op "->" <*> expr <*> position
indentState = mkIndentationState 0 infIndentation True Ge
test' = test "example01.lc"
test :: String -> IO ()
test fname = do
src <- BS.readFile fname
case parseByteString (runLCParser $ evalIndentationParserT (whiteSpace *> expr <* eof) indentState) (Directed (pack fname) 0 0 0 0) src of
Failure m -> print m
Success e -> do
print $ pretty $ delta r
print e
case inference src e of
Right t -> putStrLn $ show t
Left m -> putStrLn $ "error: " ++ m
|
6f09e82716020b70c2fd1ce16c821f367aa175aa7477e47a61c1664da8574412 | KeepSafe/measure | ring_test.clj | Copyright 2014 KeepSafe Software , Inc
;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -2.0
;;
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns measure.ring-test
(:require [clojure.test :refer :all]
[measure.core :as m]
[measure.ring :refer :all]))
(deftest status-meters
(testing "Creating a handler registers status meters"
(let [r (m/registry)
h (with-measurements identity r)
meters (.getMeters r)]
(is (.containsKey meters "responses.1XX"))
(is (.containsKey meters "responses.2XX"))
(is (.containsKey meters "responses.3XX"))
(is (.containsKey meters "responses.4XX"))
(is (.containsKey meters "responses.5XX"))))
(testing "When a request yields an in-spec HTTP response, marks the right meter"
(let [r (m/registry)
f (constantly {:status (+ 100 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.1XX")))))
(let [r (m/registry)
f (constantly {:status (+ 200 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.2XX")))))
(let [r (m/registry)
f (constantly {:status (+ 300 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.3XX")))))
(let [r (m/registry)
f (constantly {:status (+ 400 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.4XX")))))
(let [r (m/registry)
f (constantly {:status (+ 500 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.5XX"))))))
(testing "When a request yields a non-spec HTTP status, nothing gets marked."
(let [r (m/registry)
f (constantly {:status 600})
h (with-measurements f r)]
(h :some-request)
(doseq [meter (.values (.getMeters r))]
(is (= 0 (m/value meter))))))
(testing "When an exception is thrown, the 5XX meter is marked"
(let [r (m/registry)
f (fn [&] (throw (Exception. "BOOM")))
h (with-measurements f r)]
(try (h :some-request)
(is false "Expected an exception")
(catch Exception e
(is (= 1 (m/value (m/meter r "responses.5XX")))))))))
(deftest method-meters
(testing "Given ring-specified HTTP methods, the appropriate meters are marked."
(let [r (m/registry)
f (constantly {:status 200})
h (with-measurements f r)
request! (fn [method] (h {:request-method method}))]
(request! :get)
(request! :put)
(request! :post)
(request! :delete)
(request! :head)
(request! :options)
(is (= 1 (m/value (m/meter r "requests.gets"))))
(is (= 1 (m/value (m/meter r "requests.puts"))))
(is (= 1 (m/value (m/meter r "requests.posts"))))
(is (= 1 (m/value (m/meter r "requests.heads"))))
(is (= 1 (m/value (m/meter r "requests.deletes"))))
(is (= 1 (m/value (m/meter r "requests.options")))))))
| null | https://raw.githubusercontent.com/KeepSafe/measure/88fa7dfd572493034c6bc5bdb3a4ede1ad33e2aa/test/measure/ring_test.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright 2014 KeepSafe Software , Inc
distributed under the License is distributed on an " AS IS " BASIS ,
(ns measure.ring-test
(:require [clojure.test :refer :all]
[measure.core :as m]
[measure.ring :refer :all]))
(deftest status-meters
(testing "Creating a handler registers status meters"
(let [r (m/registry)
h (with-measurements identity r)
meters (.getMeters r)]
(is (.containsKey meters "responses.1XX"))
(is (.containsKey meters "responses.2XX"))
(is (.containsKey meters "responses.3XX"))
(is (.containsKey meters "responses.4XX"))
(is (.containsKey meters "responses.5XX"))))
(testing "When a request yields an in-spec HTTP response, marks the right meter"
(let [r (m/registry)
f (constantly {:status (+ 100 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.1XX")))))
(let [r (m/registry)
f (constantly {:status (+ 200 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.2XX")))))
(let [r (m/registry)
f (constantly {:status (+ 300 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.3XX")))))
(let [r (m/registry)
f (constantly {:status (+ 400 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.4XX")))))
(let [r (m/registry)
f (constantly {:status (+ 500 (rand-int 100))})
h (with-measurements f r)]
(h :some-request)
(is (= 1 (m/value (m/meter r "responses.5XX"))))))
(testing "When a request yields a non-spec HTTP status, nothing gets marked."
(let [r (m/registry)
f (constantly {:status 600})
h (with-measurements f r)]
(h :some-request)
(doseq [meter (.values (.getMeters r))]
(is (= 0 (m/value meter))))))
(testing "When an exception is thrown, the 5XX meter is marked"
(let [r (m/registry)
f (fn [&] (throw (Exception. "BOOM")))
h (with-measurements f r)]
(try (h :some-request)
(is false "Expected an exception")
(catch Exception e
(is (= 1 (m/value (m/meter r "responses.5XX")))))))))
(deftest method-meters
(testing "Given ring-specified HTTP methods, the appropriate meters are marked."
(let [r (m/registry)
f (constantly {:status 200})
h (with-measurements f r)
request! (fn [method] (h {:request-method method}))]
(request! :get)
(request! :put)
(request! :post)
(request! :delete)
(request! :head)
(request! :options)
(is (= 1 (m/value (m/meter r "requests.gets"))))
(is (= 1 (m/value (m/meter r "requests.puts"))))
(is (= 1 (m/value (m/meter r "requests.posts"))))
(is (= 1 (m/value (m/meter r "requests.heads"))))
(is (= 1 (m/value (m/meter r "requests.deletes"))))
(is (= 1 (m/value (m/meter r "requests.options")))))))
|
bd5f735b3af455ed8d049cc9b23f2fc62d40afe820f926bbd13a559a5efac42a | MastodonC/kixi.hecuba | test_runner.cljs | (ns test-runner
(:require [cljs.test :refer-macros [run-tests]]
[kixi.hecuba.profiles.form-test]
[kixi.hecuba.tabs.hierarchy.profiles-test]))
(enable-console-print!)
(defn runner []
(println "Runner starts")
(if (cljs.test/successful?
(run-tests
'kixi.hecuba.profiles.form-test
'kixi.hecuba.tabs.hierarchy.profiles-test))
0
1))
| null | https://raw.githubusercontent.com/MastodonC/kixi.hecuba/467400bbe670e74420a2711f7d49e869ab2b3e21/test/cljs/test_runner.cljs | clojure | (ns test-runner
(:require [cljs.test :refer-macros [run-tests]]
[kixi.hecuba.profiles.form-test]
[kixi.hecuba.tabs.hierarchy.profiles-test]))
(enable-console-print!)
(defn runner []
(println "Runner starts")
(if (cljs.test/successful?
(run-tests
'kixi.hecuba.profiles.form-test
'kixi.hecuba.tabs.hierarchy.profiles-test))
0
1))
| |
b5854d21e576756c20e5510a3faa9592ad5a8c672c14ad3c575b5be0eed8d22e | bellkev/dacom | db.clj | Copyright ( c ) 2014 . All rights reserved .
See the file license.txt for copying permission .
(ns dacom.db
"-of-datomic/blob/master/src/datomic/samples/io.clj
and
-of-datomic/blob/master/src/datomic/samples/schema.clj"
(:require [datomic.api :as d :refer [db q]]
[clojure.java.io :as io]
[dacom.config :refer [read-config]])
(:import datomic.Util))
;===============================================================================
; io utils
;===============================================================================
(defn read-all
"Read all forms in f, where f is any resource that can
be opened by io/reader"
[f]
(Util/readAll (io/reader f)))
(defn transact-all
"Load and run all transactions from f, where f is any
resource that can be opened by io/reader."
[conn f]
(doseq [txd (read-all f)]
(d/transact conn txd))
:done)
;===============================================================================
; schema utils
;===============================================================================
(defn cardinality
"Returns the cardinality (:db.cardinality/one or
:db.cardinality/many) of the attribute"
[db attr]
(->>
(d/q '[:find ?v
:in $ ?attr
:where
[?attr :db/cardinality ?card]
[?card :db/ident ?v]]
db attr)
ffirst))
(defn has-attribute?
"Does database have an attribute named attr-name?"
[db attr-name]
(-> (d/entity db attr-name)
:db.install/_attribute
boolean))
(defn has-schema?
"Does database have a schema named schema-name installed?
Uses schema-attr (an attribute of transactions!) to track
which schema names are installed."
[db schema-attr schema-name]
(and (has-attribute? db schema-attr)
(-> (d/q '[:find ?e
:in $ ?sa ?sn
:where [?e ?sa ?sn]]
db schema-attr schema-name)
seq boolean)))
(defn- ensure-schema-attribute
"Ensure that schema-attr, a keyword-valued attribute used
as a value on transactions to track named schemas, is
installed in database."
[conn schema-attr]
(when-not (has-attribute? (d/db conn) schema-attr)
(d/transact conn [{:db/id #db/id[:db.part/db]
:db/ident schema-attr
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/doc "Name of schema installed by this transaction"
:db/index true
:db.install/_attribute :db.part/db}])))
(defn ensure-schemas
"Ensure that schemas are installed.
schema-attr a keyword valued attribute of a transaction,
naming the schema
schema-map a map from schema names to schema installation
maps. A schema installation map contains two
keys: :txes is the data to install, and :requires
is a list of other schema names that must also
be installed
schema-names the names of schemas to install"
[conn schema-attr schema-map & schema-names]
(ensure-schema-attribute conn schema-attr)
(doseq [schema-name schema-names]
(if (has-schema? (d/db conn) schema-attr schema-name)
(println "Schema" schema-name "already installed")
(let [{:keys [requires txes]} (get schema-map schema-name)]
(println "Installing schema" schema-name "...")
(apply ensure-schemas conn schema-attr schema-map requires)
(if txes
(doseq [tx txes]
hrm , could mark the last tx specially
(d/transact conn (cons {:db/id #db/id [:db.part/tx]
schema-attr schema-name}
tx)))
(throw (ex-info (str "No data provided for schema" schema-name)
{:schema/missing schema-name})))))))
;===============================================================================
; install schema and sample data
;===============================================================================
(def db-uri (:datomic-uri (read-config)))
(d/create-database db-uri)
(def conn
(d/connect db-uri))
(def schema-map (first (read-all "db-resources/schema.edn")))
(defn install-schema []
(ensure-schemas conn :dacom/all-tx-tag schema-map :dacom/all))
(defn install-message []
(let [result (q '[:find ?e :where [?e :demo/message]] (db conn))]
(if (ffirst result)
(println "Demo message already installed")
(do
(println "Installing demo message...")
(d/transact conn [{:db/id (d/tempid :db.part/user)
:demo/message "Hello, from Datomic"}])))))
(defn -main [& args]
(install-schema)
(install-message)
(System/exit 0)) | null | https://raw.githubusercontent.com/bellkev/dacom/f4bc93b0b9899a8db3475ef7c2d2ff628f6b8818/utils/src/dacom/db.clj | clojure | ===============================================================================
io utils
===============================================================================
===============================================================================
schema utils
===============================================================================
===============================================================================
install schema and sample data
=============================================================================== | Copyright ( c ) 2014 . All rights reserved .
See the file license.txt for copying permission .
(ns dacom.db
"-of-datomic/blob/master/src/datomic/samples/io.clj
and
-of-datomic/blob/master/src/datomic/samples/schema.clj"
(:require [datomic.api :as d :refer [db q]]
[clojure.java.io :as io]
[dacom.config :refer [read-config]])
(:import datomic.Util))
(defn read-all
"Read all forms in f, where f is any resource that can
be opened by io/reader"
[f]
(Util/readAll (io/reader f)))
(defn transact-all
"Load and run all transactions from f, where f is any
resource that can be opened by io/reader."
[conn f]
(doseq [txd (read-all f)]
(d/transact conn txd))
:done)
(defn cardinality
"Returns the cardinality (:db.cardinality/one or
:db.cardinality/many) of the attribute"
[db attr]
(->>
(d/q '[:find ?v
:in $ ?attr
:where
[?attr :db/cardinality ?card]
[?card :db/ident ?v]]
db attr)
ffirst))
(defn has-attribute?
"Does database have an attribute named attr-name?"
[db attr-name]
(-> (d/entity db attr-name)
:db.install/_attribute
boolean))
(defn has-schema?
"Does database have a schema named schema-name installed?
Uses schema-attr (an attribute of transactions!) to track
which schema names are installed."
[db schema-attr schema-name]
(and (has-attribute? db schema-attr)
(-> (d/q '[:find ?e
:in $ ?sa ?sn
:where [?e ?sa ?sn]]
db schema-attr schema-name)
seq boolean)))
(defn- ensure-schema-attribute
"Ensure that schema-attr, a keyword-valued attribute used
as a value on transactions to track named schemas, is
installed in database."
[conn schema-attr]
(when-not (has-attribute? (d/db conn) schema-attr)
(d/transact conn [{:db/id #db/id[:db.part/db]
:db/ident schema-attr
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/doc "Name of schema installed by this transaction"
:db/index true
:db.install/_attribute :db.part/db}])))
(defn ensure-schemas
"Ensure that schemas are installed.
schema-attr a keyword valued attribute of a transaction,
naming the schema
schema-map a map from schema names to schema installation
maps. A schema installation map contains two
keys: :txes is the data to install, and :requires
is a list of other schema names that must also
be installed
schema-names the names of schemas to install"
[conn schema-attr schema-map & schema-names]
(ensure-schema-attribute conn schema-attr)
(doseq [schema-name schema-names]
(if (has-schema? (d/db conn) schema-attr schema-name)
(println "Schema" schema-name "already installed")
(let [{:keys [requires txes]} (get schema-map schema-name)]
(println "Installing schema" schema-name "...")
(apply ensure-schemas conn schema-attr schema-map requires)
(if txes
(doseq [tx txes]
hrm , could mark the last tx specially
(d/transact conn (cons {:db/id #db/id [:db.part/tx]
schema-attr schema-name}
tx)))
(throw (ex-info (str "No data provided for schema" schema-name)
{:schema/missing schema-name})))))))
(def db-uri (:datomic-uri (read-config)))
(d/create-database db-uri)
(def conn
(d/connect db-uri))
(def schema-map (first (read-all "db-resources/schema.edn")))
(defn install-schema []
(ensure-schemas conn :dacom/all-tx-tag schema-map :dacom/all))
(defn install-message []
(let [result (q '[:find ?e :where [?e :demo/message]] (db conn))]
(if (ffirst result)
(println "Demo message already installed")
(do
(println "Installing demo message...")
(d/transact conn [{:db/id (d/tempid :db.part/user)
:demo/message "Hello, from Datomic"}])))))
(defn -main [& args]
(install-schema)
(install-message)
(System/exit 0)) |
f634ef32610c18bd8338dd3ad400d1a0a3bbc754d20bd550d1f3248681e2c172 | coot/ghc-tags-plugin | Main.hs | {-# LANGUAGE RankNTypes #-}
{-# OPTIONS -Wno-orphans #-}
module Main (main) where
import Control.Exception
import Control.DeepSeq
import Control.Monad.State.Strict
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Builder as BB
import Data.Either (rights)
import Data.Foldable (traverse_)
import Data.Maybe (mapMaybe)
import qualified Data.Text.Encoding as Text
import System.IO
import System.FilePath.ByteString (RawFilePath)
import qualified Pipes as Pipes
import qualified Pipes.Attoparsec as Pipes.AP
import qualified Pipes.ByteString as Pipes.BS
import Criterion
import Criterion.Main
import GhcTags.Tag
import GhcTags.Stream
import qualified GhcTags.CTag as CTag
evalListWith :: (forall b. a -> b -> b) -> [a] -> ()
evalListWith _seq_ [] = ()
evalListWith seq_ (a : as) = a `seq_` (evalListWith seq_ as) `seq` ()
evalEither :: Either a b -> x -> x
evalEither (Left a) x = a `seq` x
evalEither (Right b) x = b `seq` x
evalTags :: Either String [Either CTag.Header CTag] -> ()
evalTags = either (`seq` ()) (evalListWith evalEither)
newtype TagsNF = TagsNF [CTag]
instance NFData TagsNF where
rnf (TagsNF tags) = evalListWith seq tags
main :: IO ()
main = defaultMain
[ bgroup "Parse tags"
381 tags
env (BS.readFile "ghc-tags-test/test/golden/io-sim-classes.tags") $ \bs ->
bench "parse io-sim-classes.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
6767 tags
env (BS.readFile "ghc-tags-test/test/golden/ouroboros-consensus.tags") $ \bs ->
bench "parse ouroboros-consensus.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
12549 tags
env (BS.readFile "ghc-tags-test/bench/data.tags") $ \bs ->
bench "data.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
23741 tags
env (BS.readFile "ghc-tags-test/test/golden/vim.tags") $ \bs ->
bench "parse vim.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
]
, bgroup "read parse & format"
[ bench "io-sim-classes.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/test/golden/io-sim-classes.tags"
, bench "ouroboros-consensus.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/test/golden/ouroboros-consensus.tags"
, bench "data.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/bench/data.tags"
, bench "vim.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/test/golden/vim.tags"
]
, bgroup "stream parse & format"
[ bench "io-sim-classes.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/test/golden/io-sim-classes.tags"
, bench "ouroboros-consensus.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/test/golden/ouroboros-consensus.tags"
, bench "data.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/bench/data.tags"
, bench "vim.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/test/golden/vim.tags"
]
, bgroup "end-to-end"
[ env
(do
bs <- BS.readFile "ghc-tags-test/test/golden/io-sim-classes.tags"
Right tags <- fmap (mapMaybe (either (const Nothing) Just))
<$> CTag.parseTagsFile bs
return (encodeTagFilePath (tagFilePath (head tags)), TagsNF tags)
)
$ \ ~(modPath, TagsNF tags) ->
bgroup "small"
[ bench "streamTags" (whnfAppIO (benchStreamTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
, bench "readTags" (whnfAppIO (benchReadTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
]
, env
(do
bs <- BS.readFile "ghc-tags-test/test/golden/ouroboros-network.tags"
Right tags <- fmap (mapMaybe (either (const Nothing) Just))
<$> CTag.parseTagsFile bs
return (encodeTagFilePath (tagFilePath (head tags)), TagsNF tags)
)
$ \ ~(modPath, TagsNF tags) ->
bgroup "medium"
[ bench "streamTags" (whnfAppIO (benchStreamTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
, bench "readTags" (whnfAppIO (benchReadTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
]
]
]
benchReadParseFormat :: FilePath -> IO BSL.ByteString
benchReadParseFormat path = do
bs <- BS.readFile path
res <- CTag.parseTagsFile bs
case res of
Left err -> throwIO (userError err)
Right tags -> pure $ BB.toLazyByteString (CTag.formatTagsFile tags)
benchStreamParseFormat :: FilePath -> IO ()
benchStreamParseFormat fp =
withFile "/dev/null" WriteMode $ \devNull ->
withFile fp ReadMode $ \h ->
Pipes.void $ Pipes.runEffect $ Pipes.for
(Pipes.AP.parsed
CTag.parseTag
(Pipes.BS.fromHandle h `Pipes.for` Pipes.yield))
(\tag ->
(Pipes.BS.fromLazy (BB.toLazyByteString (CTag.formatTag tag)))
Pipes.>->
Pipes.BS.toHandle devNull)
benchStreamTags :: FilePath -> RawFilePath -> [CTag] -> IO ()
benchStreamTags filePath modPath tags =
withFile filePath ReadMode $ \readHandle ->
withFile "/tmp/bench.stream.tags" WriteMode $ \writeHandle -> do
let producer :: Pipes.Producer ByteString IO ()
producer = void (Pipes.BS.fromHandle readHandle)
-- gags pipe
pipe :: Pipes.Effect (StateT [CTag] IO) ()
pipe =
Pipes.for
(Pipes.hoist Pipes.lift
$ tagParser
(either (const Nothing) Just <$> CTag.parseTagLine)
producer)
(runCombineTagsPipe writeHandle CTag.compareTags CTag.formatTag modPath)
tags' <- execStateT (Pipes.runEffect pipe) tags
traverse_ (BSL.hPut writeHandle . BB.toLazyByteString . CTag.formatTag) tags'
benchReadTags :: FilePath -> RawFilePath -> [CTag] -> IO ()
benchReadTags filePath modPath tags = do
withFile filePath ReadMode $ \readHandle ->
withFile "/tmp/bench.stream.tags" WriteMode $ \writeHandle -> do
Right tags' <-
BS.hGetContents readHandle >>= CTag.parseTagsFile
let tags'' = combineTags CTag.compareTags modPath tags (rights tags')
BB.hPutBuilder writeHandle (CTag.formatTagsFile (Right `map` tags''))
encodeTagFilePath :: TagFilePath -> RawFilePath
encodeTagFilePath = Text.encodeUtf8 . getRawFilePath
| null | https://raw.githubusercontent.com/coot/ghc-tags-plugin/9e3005b676e03c6102c29fd6e8539d4053571e53/ghc-tags-test/bench/Main.hs | haskell | # LANGUAGE RankNTypes #
# OPTIONS -Wno-orphans #
gags pipe |
module Main (main) where
import Control.Exception
import Control.DeepSeq
import Control.Monad.State.Strict
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Builder as BB
import Data.Either (rights)
import Data.Foldable (traverse_)
import Data.Maybe (mapMaybe)
import qualified Data.Text.Encoding as Text
import System.IO
import System.FilePath.ByteString (RawFilePath)
import qualified Pipes as Pipes
import qualified Pipes.Attoparsec as Pipes.AP
import qualified Pipes.ByteString as Pipes.BS
import Criterion
import Criterion.Main
import GhcTags.Tag
import GhcTags.Stream
import qualified GhcTags.CTag as CTag
evalListWith :: (forall b. a -> b -> b) -> [a] -> ()
evalListWith _seq_ [] = ()
evalListWith seq_ (a : as) = a `seq_` (evalListWith seq_ as) `seq` ()
evalEither :: Either a b -> x -> x
evalEither (Left a) x = a `seq` x
evalEither (Right b) x = b `seq` x
evalTags :: Either String [Either CTag.Header CTag] -> ()
evalTags = either (`seq` ()) (evalListWith evalEither)
newtype TagsNF = TagsNF [CTag]
instance NFData TagsNF where
rnf (TagsNF tags) = evalListWith seq tags
main :: IO ()
main = defaultMain
[ bgroup "Parse tags"
381 tags
env (BS.readFile "ghc-tags-test/test/golden/io-sim-classes.tags") $ \bs ->
bench "parse io-sim-classes.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
6767 tags
env (BS.readFile "ghc-tags-test/test/golden/ouroboros-consensus.tags") $ \bs ->
bench "parse ouroboros-consensus.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
12549 tags
env (BS.readFile "ghc-tags-test/bench/data.tags") $ \bs ->
bench "data.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
23741 tags
env (BS.readFile "ghc-tags-test/test/golden/vim.tags") $ \bs ->
bench "parse vim.tags" $
whnfAppIO (fmap evalTags . CTag.parseTagsFile) bs
]
, bgroup "read parse & format"
[ bench "io-sim-classes.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/test/golden/io-sim-classes.tags"
, bench "ouroboros-consensus.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/test/golden/ouroboros-consensus.tags"
, bench "data.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/bench/data.tags"
, bench "vim.tags" $
nfIO $ benchReadParseFormat "ghc-tags-test/test/golden/vim.tags"
]
, bgroup "stream parse & format"
[ bench "io-sim-classes.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/test/golden/io-sim-classes.tags"
, bench "ouroboros-consensus.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/test/golden/ouroboros-consensus.tags"
, bench "data.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/bench/data.tags"
, bench "vim.tags" $
nfIO $ benchStreamParseFormat "ghc-tags-test/test/golden/vim.tags"
]
, bgroup "end-to-end"
[ env
(do
bs <- BS.readFile "ghc-tags-test/test/golden/io-sim-classes.tags"
Right tags <- fmap (mapMaybe (either (const Nothing) Just))
<$> CTag.parseTagsFile bs
return (encodeTagFilePath (tagFilePath (head tags)), TagsNF tags)
)
$ \ ~(modPath, TagsNF tags) ->
bgroup "small"
[ bench "streamTags" (whnfAppIO (benchStreamTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
, bench "readTags" (whnfAppIO (benchReadTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
]
, env
(do
bs <- BS.readFile "ghc-tags-test/test/golden/ouroboros-network.tags"
Right tags <- fmap (mapMaybe (either (const Nothing) Just))
<$> CTag.parseTagsFile bs
return (encodeTagFilePath (tagFilePath (head tags)), TagsNF tags)
)
$ \ ~(modPath, TagsNF tags) ->
bgroup "medium"
[ bench "streamTags" (whnfAppIO (benchStreamTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
, bench "readTags" (whnfAppIO (benchReadTags "ghc-tags-test/test/golden/vim.tags" modPath) tags)
]
]
]
benchReadParseFormat :: FilePath -> IO BSL.ByteString
benchReadParseFormat path = do
bs <- BS.readFile path
res <- CTag.parseTagsFile bs
case res of
Left err -> throwIO (userError err)
Right tags -> pure $ BB.toLazyByteString (CTag.formatTagsFile tags)
benchStreamParseFormat :: FilePath -> IO ()
benchStreamParseFormat fp =
withFile "/dev/null" WriteMode $ \devNull ->
withFile fp ReadMode $ \h ->
Pipes.void $ Pipes.runEffect $ Pipes.for
(Pipes.AP.parsed
CTag.parseTag
(Pipes.BS.fromHandle h `Pipes.for` Pipes.yield))
(\tag ->
(Pipes.BS.fromLazy (BB.toLazyByteString (CTag.formatTag tag)))
Pipes.>->
Pipes.BS.toHandle devNull)
benchStreamTags :: FilePath -> RawFilePath -> [CTag] -> IO ()
benchStreamTags filePath modPath tags =
withFile filePath ReadMode $ \readHandle ->
withFile "/tmp/bench.stream.tags" WriteMode $ \writeHandle -> do
let producer :: Pipes.Producer ByteString IO ()
producer = void (Pipes.BS.fromHandle readHandle)
pipe :: Pipes.Effect (StateT [CTag] IO) ()
pipe =
Pipes.for
(Pipes.hoist Pipes.lift
$ tagParser
(either (const Nothing) Just <$> CTag.parseTagLine)
producer)
(runCombineTagsPipe writeHandle CTag.compareTags CTag.formatTag modPath)
tags' <- execStateT (Pipes.runEffect pipe) tags
traverse_ (BSL.hPut writeHandle . BB.toLazyByteString . CTag.formatTag) tags'
benchReadTags :: FilePath -> RawFilePath -> [CTag] -> IO ()
benchReadTags filePath modPath tags = do
withFile filePath ReadMode $ \readHandle ->
withFile "/tmp/bench.stream.tags" WriteMode $ \writeHandle -> do
Right tags' <-
BS.hGetContents readHandle >>= CTag.parseTagsFile
let tags'' = combineTags CTag.compareTags modPath tags (rights tags')
BB.hPutBuilder writeHandle (CTag.formatTagsFile (Right `map` tags''))
encodeTagFilePath :: TagFilePath -> RawFilePath
encodeTagFilePath = Text.encodeUtf8 . getRawFilePath
|
157fbe5a42974f44969cbf1e58a0bc01b33a635cfcb513741f17e6057505e7de | dmvianna/haskellbook | Ch24-ini.hs | # LANGUAGE OverloadedStrings , QuasiQuotes #
module Data.Ini where
import Control.Applicative
import Data.ByteString hiding (foldr)
import Data.Char (isAlpha)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text.IO as TIO
import Test.Hspec
import Text.RawString.QQ
import Text.Trifecta
headerEx :: ByteString
headerEx = "[blah]"
-- "[blah]" -> Section "blah"
newtype Header = Header String deriving (Eq, Ord, Show)
parseBracketPair :: Parser a -> Parser a
parseBracketPair p = char '[' *> p <* char ']'
-- these operators mean the brackets will be
-- parsed and then discarded
but the p will remain as our result
parseHeader :: Parser Header
parseHeader =
parseBracketPair (Header <$> some letter)
assignmentEx :: ByteString
assignmentEx = "woot=1"
type Name = String
type Value = String
type Assignments = Map Name Value
parseAssignment :: Parser (Name, Value)
parseAssignment = do
name <- some letter
_ <- char '='
val <- some (noneOf "\n")
skipEOL -- important!
return (name, val)
-- / Skip end of line and whitespace beyond.
skipEOL :: Parser ()
skipEOL = skipMany (oneOf "\n")
commentEx :: ByteString
commentEx = "; last modified 1 April 2001 by John Doe"
commentEx' :: ByteString
commentEx' = "; blah\n; woot\n \n;hah"
-- / Skip comments starting at the beginning of the line.
skipComments :: Parser ()
skipComments =
skipMany (do _ <- char ';' <|> char '#'
skipMany (noneOf "\n")
skipEOL)
sectionEx :: ByteString
sectionEx =
"; ignore me\n[states]\nChris=Texas"
sectionEx' :: ByteString
sectionEx' = [r|
; ignore me
[states]
Chris=Texas
|]
sectionEx'' :: ByteString
sectionEx'' = [r|
; comment
[section]
host=wikipedia.org
alias=claw
[whatisit]
red=intoothandclaw
|]
data Section = Section Header Assignments deriving (Eq, Show)
newtype Config = Config (Map Header Assignments) deriving (Eq, Show)
skipWhiteSpace :: Parser ()
skipWhiteSpace =
skipMany (char ' ' <|> char '\n')
parseSection :: Parser Section
parseSection = do
skipWhiteSpace
skipComments
h <- parseHeader
skipEOL
assignments <- some parseAssignment
return $ Section h (M.fromList assignments)
rollup :: Section
-> Map Header Assignments
-> Map Header Assignments
rollup (Section h a) m = M.insert h a m
parseIni :: Parser Config
parseIni = do
sections <- some parseSection
let mapOfSections =
foldr rollup M.empty sections
return (Config mapOfSections)
maybeSuccess :: Result a -> Maybe a
maybeSuccess (Success a) = Just a
maybeSuccess _ = Nothing
main :: IO ()
main = hspec $ do
describe "Assignment Parsing" $
it "can parse a simple assignment" $ do
let m = parseByteString parseAssignment
mempty assignmentEx
r' = maybeSuccess m
print m
r' `shouldBe` Just ("woot", "1")
describe "Header Parsing" $
it "can parse a simple header" $ do
let m = parseByteString parseHeader mempty headerEx
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Comment parsing" $
it "Can skip a comment before a header" $ do
let p = skipComments >> parseHeader
i = "; woot\n[blah]"
m = parseByteString p mempty i
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Section parsing" $
it "Can parse a simple section" $ do
let m = parseByteString parseSection
mempty sectionEx
r' = maybeSuccess m
states = M.fromList [("Chris","Texas")]
expected' = Just (Section
(Header "states")
states)
print m
r' `shouldBe` expected'
describe "INI parsing" $
it "Can parse multiple sections" $ do
let m = parseByteString parseIni mempty sectionEx''
r' = maybeSuccess m
sectionValues = M.fromList
[ ("alias","claw")
, ("host", "wikipedia.org")]
whatisitValues = M.fromList
[("red", "intoothandclaw")]
expected' = Just (Config
(M.fromList
[ (Header "section"
, sectionValues)
, (Header "whatisit"
, whatisitValues)]))
print m
r' `shouldBe` expected'
| null | https://raw.githubusercontent.com/dmvianna/haskellbook/b1fdce66283ccf3e740db0bb1ad9730a7669d1fc/src/Ch24-ini.hs | haskell | "[blah]" -> Section "blah"
these operators mean the brackets will be
parsed and then discarded
important!
/ Skip end of line and whitespace beyond.
/ Skip comments starting at the beginning of the line. | # LANGUAGE OverloadedStrings , QuasiQuotes #
module Data.Ini where
import Control.Applicative
import Data.ByteString hiding (foldr)
import Data.Char (isAlpha)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text.IO as TIO
import Test.Hspec
import Text.RawString.QQ
import Text.Trifecta
headerEx :: ByteString
headerEx = "[blah]"
newtype Header = Header String deriving (Eq, Ord, Show)
parseBracketPair :: Parser a -> Parser a
parseBracketPair p = char '[' *> p <* char ']'
but the p will remain as our result
parseHeader :: Parser Header
parseHeader =
parseBracketPair (Header <$> some letter)
assignmentEx :: ByteString
assignmentEx = "woot=1"
type Name = String
type Value = String
type Assignments = Map Name Value
parseAssignment :: Parser (Name, Value)
parseAssignment = do
name <- some letter
_ <- char '='
val <- some (noneOf "\n")
return (name, val)
skipEOL :: Parser ()
skipEOL = skipMany (oneOf "\n")
commentEx :: ByteString
commentEx = "; last modified 1 April 2001 by John Doe"
commentEx' :: ByteString
commentEx' = "; blah\n; woot\n \n;hah"
skipComments :: Parser ()
skipComments =
skipMany (do _ <- char ';' <|> char '#'
skipMany (noneOf "\n")
skipEOL)
sectionEx :: ByteString
sectionEx =
"; ignore me\n[states]\nChris=Texas"
sectionEx' :: ByteString
sectionEx' = [r|
; ignore me
[states]
Chris=Texas
|]
sectionEx'' :: ByteString
sectionEx'' = [r|
; comment
[section]
host=wikipedia.org
alias=claw
[whatisit]
red=intoothandclaw
|]
data Section = Section Header Assignments deriving (Eq, Show)
newtype Config = Config (Map Header Assignments) deriving (Eq, Show)
skipWhiteSpace :: Parser ()
skipWhiteSpace =
skipMany (char ' ' <|> char '\n')
parseSection :: Parser Section
parseSection = do
skipWhiteSpace
skipComments
h <- parseHeader
skipEOL
assignments <- some parseAssignment
return $ Section h (M.fromList assignments)
rollup :: Section
-> Map Header Assignments
-> Map Header Assignments
rollup (Section h a) m = M.insert h a m
parseIni :: Parser Config
parseIni = do
sections <- some parseSection
let mapOfSections =
foldr rollup M.empty sections
return (Config mapOfSections)
maybeSuccess :: Result a -> Maybe a
maybeSuccess (Success a) = Just a
maybeSuccess _ = Nothing
main :: IO ()
main = hspec $ do
describe "Assignment Parsing" $
it "can parse a simple assignment" $ do
let m = parseByteString parseAssignment
mempty assignmentEx
r' = maybeSuccess m
print m
r' `shouldBe` Just ("woot", "1")
describe "Header Parsing" $
it "can parse a simple header" $ do
let m = parseByteString parseHeader mempty headerEx
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Comment parsing" $
it "Can skip a comment before a header" $ do
let p = skipComments >> parseHeader
i = "; woot\n[blah]"
m = parseByteString p mempty i
r' = maybeSuccess m
print m
r' `shouldBe` Just (Header "blah")
describe "Section parsing" $
it "Can parse a simple section" $ do
let m = parseByteString parseSection
mempty sectionEx
r' = maybeSuccess m
states = M.fromList [("Chris","Texas")]
expected' = Just (Section
(Header "states")
states)
print m
r' `shouldBe` expected'
describe "INI parsing" $
it "Can parse multiple sections" $ do
let m = parseByteString parseIni mempty sectionEx''
r' = maybeSuccess m
sectionValues = M.fromList
[ ("alias","claw")
, ("host", "wikipedia.org")]
whatisitValues = M.fromList
[("red", "intoothandclaw")]
expected' = Just (Config
(M.fromList
[ (Header "section"
, sectionValues)
, (Header "whatisit"
, whatisitValues)]))
print m
r' `shouldBe` expected'
|
de79885ba92741156ea036b05ade600590dce08239c8656ec0880f921a544333 | leanprover/tc | Name.hs | |
Module : . Name
Description : Hierarchical names
Copyright : ( c ) , 2016
License : GPL-3
Maintainer :
API for hierarchical names
Module : Kernel.Name
Description : Hierarchical names
Copyright : (c) Daniel Selsam, 2016
License : GPL-3
Maintainer :
API for hierarchical names
-}
module Kernel.Name (
Name
, noName
, mkName, mkSystemNameI, mkSystemNameS
, nameRConsI, nameRConsS
) where
import Kernel.Name.Internal
| null | https://raw.githubusercontent.com/leanprover/tc/250a568346f29ae27190fccee169ba10002c7399/src/Kernel/Name.hs | haskell | |
Module : . Name
Description : Hierarchical names
Copyright : ( c ) , 2016
License : GPL-3
Maintainer :
API for hierarchical names
Module : Kernel.Name
Description : Hierarchical names
Copyright : (c) Daniel Selsam, 2016
License : GPL-3
Maintainer :
API for hierarchical names
-}
module Kernel.Name (
Name
, noName
, mkName, mkSystemNameI, mkSystemNameS
, nameRConsI, nameRConsS
) where
import Kernel.Name.Internal
| |
b97cc2572b040416173fc2ebb32b00cee0f669fa70964c9193a6d394152318d1 | Verites/verigraph | TypedGraph.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
| Basic building blocks for writing graphs with the Dot syntax .
This contains only the basic building blocks of to Dot syntax ,
and it does _ _ not _ _ provide conventions to print particular
kinds of graphs .
This contains only the basic building blocks of to Dot syntax,
and it does __not__ provide conventions to print particular
kinds of graphs.
-}
module Image.Dot.TypedGraph
( NamingContext(..)
, makeNamingContext
, typedGraph
, typedGraphMorphism
, graphRule
, sndOrderRule
) where
import Data.Text.Prettyprint.Doc (Doc, Pretty (..), (<+>), (<>))
import qualified Data.Text.Prettyprint.Doc as PP
import Abstract.Category
import Category.TypedGraphRule
import qualified Data.Graphs as Graph
import Data.TypedGraph
import Data.TypedGraph.Morphism
import qualified Image.Dot.Prettyprint as Dot
import Rewriting.DPO.TypedGraph
import Rewriting.DPO.TypedGraphRule
data NamingContext n e ann = Ctx
{ getNodeTypeName :: Graph.NodeInContext (Maybe n) (Maybe e) -> Doc ann
, getEdgeTypeName :: Graph.EdgeInContext (Maybe n) (Maybe e) -> Doc ann
, getNodeName :: Doc ann -> NodeInContext n e -> Doc ann
, getNodeLabel :: Doc ann -> NodeInContext n e -> Maybe (Doc ann)
, getEdgeLabel :: Doc ann -> EdgeInContext n e -> Maybe (Doc ann)
}
-- TODO: move this to XML parsing module
makeNamingContext :: [(String, String)] -> NamingContext n e ann
makeNamingContext assocList = Ctx
{ getNodeTypeName = nameForId . normalizeId . nodeId
, getEdgeTypeName = nameForId . normalizeId . edgeId
, getNodeName = \idPrefix (Node n _, _, _) -> idPrefix <> pretty n
, getNodeLabel = \_ (_,Node ntype _,_) -> Just . nameForId $ normalizeId ntype
, getEdgeLabel = \_ (_,_,Edge etype _ _ _,_) -> Just . nameForId $ normalizeId etype
}
where
nodeId (node, _) = Graph.nodeId node
edgeId (_, edge, _) = Graph.edgeId edge
normalizeId id = "I" ++ show id
nameForId id =
case lookup id assocList of
Nothing -> error $ "Name for '" ++ id ++ "' not found."
Just name -> pretty $ takeWhile (/= '%') name
-- | Create a dotfile representation of the given typed graph, labeling nodes with their types
typedGraph :: NamingContext n e ann -> Doc ann -> TypedGraph n e -> Doc ann
typedGraph context name graph = Dot.digraph name (typedGraphBody context name graph)
typedGraphBody :: NamingContext n e ann -> Doc ann -> TypedGraph n e -> [Doc ann]
typedGraphBody context idPrefix graph =
nodeAttrs : map prettyNode (nodes graph) ++ map prettyEdge (edges graph)
where
nodeAttrs = "node" <+> Dot.attrList [("shape", "box")]
prettyNode (Node n _, _) = Dot.node name attrs
where
node = lookupNodeInContext n graph
Just name = getNodeName context idPrefix <$> node
attrs = case getNodeLabel context idPrefix =<< node of
Nothing -> []
Just label -> [("label", PP.dquotes label)]
prettyEdge (Edge e src tgt _, _) =
Dot.dirEdge srcName tgtName attrs
where
Just srcName = getNodeName context idPrefix <$> lookupNodeInContext src graph
Just tgtName = getNodeName context idPrefix <$> lookupNodeInContext tgt graph
attrs = case getEdgeLabel context idPrefix =<< lookupEdgeInContext e graph of
Nothing -> []
Just label -> [("label", PP.dquotes label)]
-- | Create a dotfile representation of the given typed graph morphism
typedGraphMorphism :: NamingContext n e ann -> Doc ann -> TypedGraphMorphism n e -> Doc ann
typedGraphMorphism context name morphism = Dot.digraph name (typedGraphMorphismBody context morphism)
typedGraphMorphismBody :: NamingContext n e ann -> TypedGraphMorphism n e -> [Doc ann]
typedGraphMorphismBody context morphism =
Dot.subgraph "dom" (typedGraphBody context "dom" (domain morphism))
: Dot.subgraph "cod" (typedGraphBody context "cod" (codomain morphism))
: map (prettyNodeMapping [("style", "dotted")] "dom" "cod") (nodeMapping morphism)
prettyNodeMapping :: (Pretty a) => [(Doc ann, Doc ann)] -> Doc ann -> Doc ann -> (a, a) -> Doc ann
prettyNodeMapping attrs idSrc idTgt (src, tgt) =
Dot.dirEdge (idSrc <> pretty src) (idTgt <> pretty tgt) attrs
-- | Create a dotfile representation of the given graph rule
graphRule :: NamingContext n e ann -> Doc ann -> TypedGraphRule n e -> Doc ann
graphRule context ruleName rule = Dot.digraph ruleName (graphRuleBody context ruleName rule)
graphRuleBody :: NamingContext n e ann -> Doc ann -> TypedGraphRule n e -> [Doc ann]
graphRuleBody context ruleName rule =
Dot.subgraph leftName (typedGraphBody context leftName (leftObject rule))
: Dot.subgraph interfaceName (typedGraphBody context interfaceName (interfaceObject rule))
: Dot.subgraph rightName (typedGraphBody context rightName (rightObject rule))
: map (prettyNodeMapping [("style", "dotted")] interfaceName leftName)
(nodeMapping $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dotted"), ("dir", "back")] interfaceName rightName)
(nodeMapping $ rightMorphism rule)
where
(leftName, interfaceName, rightName) = ("L_" <> ruleName, "K_" <> ruleName, "R_" <> ruleName)
| Create a dotfile representation of the given second - order rule
sndOrderRule :: NamingContext n e ann -> Doc ann -> SndOrderRule n e -> Doc ann
sndOrderRule context ruleName rule = Dot.digraph ruleName (sndOrderRuleBody context ruleName rule)
sndOrderRuleBody :: NamingContext n e ann -> Doc ann -> SndOrderRule n e -> [Doc ann]
sndOrderRuleBody context ruleName rule =
Dot.subgraph leftName (graphRuleBody context leftName (leftObject rule))
: Dot.subgraph interfaceName (graphRuleBody context interfaceName (interfaceObject rule))
: Dot.subgraph rightName (graphRuleBody context rightName (rightObject rule))
: map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KL") (ruleName <> "LL"))
(nodeMapping . mappingLeft $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KK") (ruleName <> "LK"))
(nodeMapping . mappingInterface $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KR") (ruleName <> "LR"))
(nodeMapping . mappingRight $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KL") (ruleName <> "RL"))
(nodeMapping . mappingLeft $ rightMorphism rule)
++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KK") (ruleName <> "RK"))
(nodeMapping . mappingInterface $ rightMorphism rule)
++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KR") (ruleName <> "RR"))
(nodeMapping . mappingRight $ rightMorphism rule)
where
(leftName, interfaceName, rightName) = ("L_" <> ruleName, "K_" <> ruleName, "R_" <> ruleName)
prettyNodeMapping attrs idSrc idTgt (src, tgt) =
Dot.dirEdge (idSrc <> pretty src) (idTgt <> pretty tgt) attrs
| null | https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/src/library/Image/Dot/TypedGraph.hs | haskell | # LANGUAGE OverloadedStrings #
TODO: move this to XML parsing module
| Create a dotfile representation of the given typed graph, labeling nodes with their types
| Create a dotfile representation of the given typed graph morphism
| Create a dotfile representation of the given graph rule | # LANGUAGE FlexibleContexts #
| Basic building blocks for writing graphs with the Dot syntax .
This contains only the basic building blocks of to Dot syntax ,
and it does _ _ not _ _ provide conventions to print particular
kinds of graphs .
This contains only the basic building blocks of to Dot syntax,
and it does __not__ provide conventions to print particular
kinds of graphs.
-}
module Image.Dot.TypedGraph
( NamingContext(..)
, makeNamingContext
, typedGraph
, typedGraphMorphism
, graphRule
, sndOrderRule
) where
import Data.Text.Prettyprint.Doc (Doc, Pretty (..), (<+>), (<>))
import qualified Data.Text.Prettyprint.Doc as PP
import Abstract.Category
import Category.TypedGraphRule
import qualified Data.Graphs as Graph
import Data.TypedGraph
import Data.TypedGraph.Morphism
import qualified Image.Dot.Prettyprint as Dot
import Rewriting.DPO.TypedGraph
import Rewriting.DPO.TypedGraphRule
data NamingContext n e ann = Ctx
{ getNodeTypeName :: Graph.NodeInContext (Maybe n) (Maybe e) -> Doc ann
, getEdgeTypeName :: Graph.EdgeInContext (Maybe n) (Maybe e) -> Doc ann
, getNodeName :: Doc ann -> NodeInContext n e -> Doc ann
, getNodeLabel :: Doc ann -> NodeInContext n e -> Maybe (Doc ann)
, getEdgeLabel :: Doc ann -> EdgeInContext n e -> Maybe (Doc ann)
}
makeNamingContext :: [(String, String)] -> NamingContext n e ann
makeNamingContext assocList = Ctx
{ getNodeTypeName = nameForId . normalizeId . nodeId
, getEdgeTypeName = nameForId . normalizeId . edgeId
, getNodeName = \idPrefix (Node n _, _, _) -> idPrefix <> pretty n
, getNodeLabel = \_ (_,Node ntype _,_) -> Just . nameForId $ normalizeId ntype
, getEdgeLabel = \_ (_,_,Edge etype _ _ _,_) -> Just . nameForId $ normalizeId etype
}
where
nodeId (node, _) = Graph.nodeId node
edgeId (_, edge, _) = Graph.edgeId edge
normalizeId id = "I" ++ show id
nameForId id =
case lookup id assocList of
Nothing -> error $ "Name for '" ++ id ++ "' not found."
Just name -> pretty $ takeWhile (/= '%') name
typedGraph :: NamingContext n e ann -> Doc ann -> TypedGraph n e -> Doc ann
typedGraph context name graph = Dot.digraph name (typedGraphBody context name graph)
typedGraphBody :: NamingContext n e ann -> Doc ann -> TypedGraph n e -> [Doc ann]
typedGraphBody context idPrefix graph =
nodeAttrs : map prettyNode (nodes graph) ++ map prettyEdge (edges graph)
where
nodeAttrs = "node" <+> Dot.attrList [("shape", "box")]
prettyNode (Node n _, _) = Dot.node name attrs
where
node = lookupNodeInContext n graph
Just name = getNodeName context idPrefix <$> node
attrs = case getNodeLabel context idPrefix =<< node of
Nothing -> []
Just label -> [("label", PP.dquotes label)]
prettyEdge (Edge e src tgt _, _) =
Dot.dirEdge srcName tgtName attrs
where
Just srcName = getNodeName context idPrefix <$> lookupNodeInContext src graph
Just tgtName = getNodeName context idPrefix <$> lookupNodeInContext tgt graph
attrs = case getEdgeLabel context idPrefix =<< lookupEdgeInContext e graph of
Nothing -> []
Just label -> [("label", PP.dquotes label)]
typedGraphMorphism :: NamingContext n e ann -> Doc ann -> TypedGraphMorphism n e -> Doc ann
typedGraphMorphism context name morphism = Dot.digraph name (typedGraphMorphismBody context morphism)
typedGraphMorphismBody :: NamingContext n e ann -> TypedGraphMorphism n e -> [Doc ann]
typedGraphMorphismBody context morphism =
Dot.subgraph "dom" (typedGraphBody context "dom" (domain morphism))
: Dot.subgraph "cod" (typedGraphBody context "cod" (codomain morphism))
: map (prettyNodeMapping [("style", "dotted")] "dom" "cod") (nodeMapping morphism)
prettyNodeMapping :: (Pretty a) => [(Doc ann, Doc ann)] -> Doc ann -> Doc ann -> (a, a) -> Doc ann
prettyNodeMapping attrs idSrc idTgt (src, tgt) =
Dot.dirEdge (idSrc <> pretty src) (idTgt <> pretty tgt) attrs
graphRule :: NamingContext n e ann -> Doc ann -> TypedGraphRule n e -> Doc ann
graphRule context ruleName rule = Dot.digraph ruleName (graphRuleBody context ruleName rule)
graphRuleBody :: NamingContext n e ann -> Doc ann -> TypedGraphRule n e -> [Doc ann]
graphRuleBody context ruleName rule =
Dot.subgraph leftName (typedGraphBody context leftName (leftObject rule))
: Dot.subgraph interfaceName (typedGraphBody context interfaceName (interfaceObject rule))
: Dot.subgraph rightName (typedGraphBody context rightName (rightObject rule))
: map (prettyNodeMapping [("style", "dotted")] interfaceName leftName)
(nodeMapping $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dotted"), ("dir", "back")] interfaceName rightName)
(nodeMapping $ rightMorphism rule)
where
(leftName, interfaceName, rightName) = ("L_" <> ruleName, "K_" <> ruleName, "R_" <> ruleName)
| Create a dotfile representation of the given second - order rule
sndOrderRule :: NamingContext n e ann -> Doc ann -> SndOrderRule n e -> Doc ann
sndOrderRule context ruleName rule = Dot.digraph ruleName (sndOrderRuleBody context ruleName rule)
sndOrderRuleBody :: NamingContext n e ann -> Doc ann -> SndOrderRule n e -> [Doc ann]
sndOrderRuleBody context ruleName rule =
Dot.subgraph leftName (graphRuleBody context leftName (leftObject rule))
: Dot.subgraph interfaceName (graphRuleBody context interfaceName (interfaceObject rule))
: Dot.subgraph rightName (graphRuleBody context rightName (rightObject rule))
: map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KL") (ruleName <> "LL"))
(nodeMapping . mappingLeft $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KK") (ruleName <> "LK"))
(nodeMapping . mappingInterface $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dashed")] (ruleName <> "KR") (ruleName <> "LR"))
(nodeMapping . mappingRight $ leftMorphism rule)
++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KL") (ruleName <> "RL"))
(nodeMapping . mappingLeft $ rightMorphism rule)
++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KK") (ruleName <> "RK"))
(nodeMapping . mappingInterface $ rightMorphism rule)
++ map (prettyNodeMapping [("style", "dashed"), ("dir", "back")] (ruleName <> "KR") (ruleName <> "RR"))
(nodeMapping . mappingRight $ rightMorphism rule)
where
(leftName, interfaceName, rightName) = ("L_" <> ruleName, "K_" <> ruleName, "R_" <> ruleName)
prettyNodeMapping attrs idSrc idTgt (src, tgt) =
Dot.dirEdge (idSrc <> pretty src) (idTgt <> pretty tgt) attrs
|
23f265fc4e4c0f299e2d36681988fbe4be6bfa0427aad0848efdb79d0663efb1 | backtracking/functory | test.ml | (**************************************************************************)
(* *)
(* Functory: a distributed computing library for OCaml *)
Copyright ( C ) 2010- and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(* *)
(**************************************************************************)
open Format
let () =
Arg.parse
["-d", Arg.Unit (fun () -> Functory.Control.set_debug true),
"sets the debug flag";]
(fun _ -> ())
"test: usage:"
module type MF = sig
type t
val map : f:(t -> t) -> t list -> t list
val map_local_fold :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val map_remote_fold :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val map_fold_ac :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val map_fold_a :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val compute :
worker:('a -> 'b) ->
master:('a * 'c -> 'b -> ('a * 'c) list) -> ('a * 'c) list -> unit
end
module TestInt(X : MF with type t = int) = struct
open X
let f x = x+1
let fold = (+)
let () =
let l = [1;2;3;4;5] and r = 20 in
printf " map@.";
assert (map f l = [2;3;4;5;6]);
printf " map_local_fold@.";
assert (map_local_fold ~f ~fold 0 l = r);
printf " map_remote_fold@.";
assert (map_remote_fold ~f ~fold 0 l = r);
printf " map_fold_ac@.";
assert (map_fold_ac ~f ~fold 0 l = r);
printf " map_fold_a@.";
assert (map_fold_a ~f ~fold 0 l = r);
printf " master@.";
assert (
let res = ref 0 in
compute
~worker:f
~master:(fun (x,y) z ->
assert (z = x+1 && x = y);
res := !res + z;
if x = 3 then [4,4] else [])
[1,1; 2,2; 3,3];
!res = 14);
()
end
module TestString(X : MF with type t = string) = struct
open X
let f s = s ^ "."
let fold = (^)
let () =
let l = ["a"; "bb"; "ccc"; "dddd"] in
assert (map f l = ["a."; "bb."; "ccc."; "dddd."]);
let check r =
String.length r = 14 &&
List.for_all
(fun x ->
let i = String.index r x.[0] in
let n = String.length x in
String.sub r i n = x && r.[i + n] = '.')
l
in
printf " map_local_fold@.";
assert (check (map_local_fold ~f ~fold "" l));
printf " map_remote_fold@.";
assert (check (map_remote_fold ~f ~fold "" l));
printf " map_fold_ac@.";
assert (check (map_fold_ac ~f ~fold "" l));
printf " map_fold_a@.";
assert (map_fold_a ~f ~fold "" l = "a.bb.ccc.dddd.");
()
end
* * *
module TestMR(X :
sig
val map_reduce :
map:('v1 - > ( ' k2 * ' v2 ) list ) - >
reduce:('k2 - > ' v2 list list - > ' v2 list ) - >
' v1 list - > ( ' k2 * ' v2 list ) list
end ) = struct
let text = " En l'année 1872 , la maison portant le numéro 7 de Saville - row , Burlington Gardens -- maison dans laquelle en 1814 -- , était habitée par , esq . , l'un des membres les plus singuliers et les plus remarqués du Reform - Club de Londres , attirer l'attention .
A l'un des plus grands , succédait donc ce Phileas , personnage énigmatique , do nt on ne savait rien , sinon que c'était un fort galant homme et l'un des plus beaux gentlemen de la haute société anglaise . "
let is_char j = match text.[j ] with
| ' ' | ' , ' | ' . ' | ' \ '' | ' - ' - > false
| _ - > true
let words =
let n = String.length text in
let rec split acc i =
let rec next j =
if j = n || not ( is_char j ) then
j , String.sub text i ( j - i )
else
next ( j + 1 )
in
let rec adv i = if i < n & & not ( is_char i ) then adv ( i+1 ) else i in
if i = n then acc else let i , s = next i in split ( s : : acc ) ( adv i )
in
split [ ] 0
let chunk_size = words / 3
let rec create_chunk acc i = function
| [ ] - > acc , [ ]
| l when i = 0 - > acc , l
| x : : l - > create_chunk ( x : : acc ) ( i - 1 ) l
let rec split acc l =
if l = [ ] then acc
else let c , l = create_chunk [ ] chunk_size l in split ( c : : acc ) l
let chunks = split [ ] words
let ( ) = printf " "
let merge l1 l2 =
let rec merge acc = function
| [ ] , l | l , [ ] - >
acc l
| x1 : : r1 , ( x2 : : _ as l2 ) when x1 < = x2 - >
merge ( x1 : : acc ) ( r1 , l2 )
| l1 , x2 : : r2 - >
merge ( x2 : : acc ) ( l1 , r2 )
in
merge [ ] ( l1 , l2 )
let > List.map ( fun x - > x,1 ) w )
~reduce:(fun _ l - > [ List.fold_left ( + ) 0 ( List.flatten l ) ] )
chunks
let ( ) =
assert ( List.assoc " l " wc = [ 6 ] ) ;
assert ( List.assoc " " wc = [ 2 ] )
end
* *
module TestMR(X :
sig
val map_reduce :
map:('v1 -> ('k2 * 'v2) list) ->
reduce:('k2 -> 'v2 list list -> 'v2 list) ->
'v1 list -> ('k2 * 'v2 list) list
end) = struct
let text = "En l'année 1872, la maison portant le numéro 7 de Saville-row, Burlington Gardens -- maison dans laquelle Sheridan mourut en 1814 --, était habitée par Phileas Fogg, esq., l'un des membres les plus singuliers et les plus remarqués du Reform-Club de Londres, bien qu'il semblât prendre à tâche de ne rien faire qui pût attirer l'attention.
A l'un des plus grands orateurs qui honorent l'Angleterre, succédait donc ce Phileas Fogg, personnage énigmatique, dont on ne savait rien, sinon que c'était un fort galant homme et l'un des plus beaux gentlemen de la haute société anglaise."
let is_char j = match text.[j] with
| ' ' | ',' | '.' | '\'' | '-' -> false
| _ -> true
let words =
let n = String.length text in
let rec split acc i =
let rec next j =
if j = n || not (is_char j) then
j, String.sub text i (j - i)
else
next (j + 1)
in
let rec adv i = if i < n && not (is_char i) then adv (i+1) else i in
if i = n then acc else let i, s = next i in split (s :: acc) (adv i)
in
split [] 0
let chunk_size = List.length words / 3
let rec create_chunk acc i = function
| [] -> acc, []
| l when i = 0 -> acc, l
| x :: l -> create_chunk (x :: acc) (i - 1) l
let rec split acc l =
if l = [] then acc
else let c, l = create_chunk [] chunk_size l in split (c :: acc) l
let chunks = split [] words
let () = printf " map_reduce@."
let merge l1 l2 =
let rec merge acc = function
| [], l | l, [] ->
List.rev_append acc l
| x1 :: r1, (x2 :: _ as l2) when x1 <= x2 ->
merge (x1 :: acc) (r1, l2)
| l1, x2 :: r2 ->
merge (x2 :: acc) (l1, r2)
in
merge [] (l1, l2)
let wc =
X.map_reduce
~map:(fun w -> List.map (fun x -> x,1) w)
~reduce:(fun _ l -> [List.fold_left (+) 0 (List.flatten l)])
chunks
let () =
assert (List.assoc "l" wc = [6]);
assert (List.assoc "Fogg" wc = [2])
end
***)
let () = printf "Sequential@."
module TestIntSeq =
TestInt(struct type t = int include Functory.Sequential end)
module TestStringSeq =
TestString(struct type t = string include Functory.Sequential end)
module TestMRSeq =
TestMR(Functory . Sequential )
let () = printf "Cores@."
let () = Functory.Cores.set_number_of_cores 2
module TestIntCores =
TestInt(struct type t = int include Functory.Cores end)
module TestStringCores =
TestString(struct type t = string include Functory.Cores end)
(* module TestMRCores = *)
TestMR(Functory . Cores )
let () = printf "Network@."
let () = Functory.Network.declare_workers ~n:2 "localhost"
module TestIntNetwork =
TestInt(struct type t = int include Functory.Network.Same end)
(* module TestStringNetwork = *)
TestString(struct type t = string include Functory . Network . Same end )
module TestStringNetworkStr =
TestString(struct type t = string include Functory . Network . end )
* * * * * * * * * *
let rec compute x = if x < = 1 then 1 else x * compute ( x-1 )
( * let n = map_fold_a ~map : compute ) 0 [ 1;2;3;4;5;6;7;8;9 ]
let rec compute x = if x <= 1 then 1 else x * compute (x-1)
(* let n = map_fold_a ~map:compute ~fold:(+) 0 [1;2;3;4;5;6;7;8;9] *)
(* let () = printf "%d@." n *)
let f x = sprintf ".%d." x
let s = map_fold_a ~map:f ~fold:(^) "" [1;2;3;4;5;6;7]
let () = printf "%s@." s; exit 0
let l = map compute [1;2;3;4]
let () = List.iter (fun s -> printf "%d@." s) l; printf "---@."
let l = map compute l
let () = List.iter (fun s -> printf "%d@." s) l; printf "---@."
let compute s =
let rec fib n = if n <= 1 then 1 else fib (n-1) + fib (n-2) in
string_of_int (fib (int_of_string s))
let l = map compute ["10"; "20"; "15"]
let () = List.iter (fun s -> printf "%s@." s) l; printf "---@."
let l = map compute ["10"; "20"; "15"]
let () = List.iter (fun s -> printf "%s@." s) l; printf "---@."
let l = map compute ["5"; "6"; "7"; "8"; "9"; "10"; "11"; "12"; "13";
"20"; "30"; "40"; ]
let () = List.iter (fun s -> printf "%s@." s) l
************)
| null | https://raw.githubusercontent.com/backtracking/functory/75368305a853a90ebea9e306d82e4ef32649d1ce/test.ml | ocaml | ************************************************************************
Functory: a distributed computing library for OCaml
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software 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.
************************************************************************
module TestMRCores =
module TestStringNetwork =
let n = map_fold_a ~map:compute ~fold:(+) 0 [1;2;3;4;5;6;7;8;9]
let () = printf "%d@." n | Copyright ( C ) 2010- and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
open Format
let () =
Arg.parse
["-d", Arg.Unit (fun () -> Functory.Control.set_debug true),
"sets the debug flag";]
(fun _ -> ())
"test: usage:"
module type MF = sig
type t
val map : f:(t -> t) -> t list -> t list
val map_local_fold :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val map_remote_fold :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val map_fold_ac :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val map_fold_a :
f:(t -> t) -> fold:(t -> t -> t) -> t -> t list -> t
val compute :
worker:('a -> 'b) ->
master:('a * 'c -> 'b -> ('a * 'c) list) -> ('a * 'c) list -> unit
end
module TestInt(X : MF with type t = int) = struct
open X
let f x = x+1
let fold = (+)
let () =
let l = [1;2;3;4;5] and r = 20 in
printf " map@.";
assert (map f l = [2;3;4;5;6]);
printf " map_local_fold@.";
assert (map_local_fold ~f ~fold 0 l = r);
printf " map_remote_fold@.";
assert (map_remote_fold ~f ~fold 0 l = r);
printf " map_fold_ac@.";
assert (map_fold_ac ~f ~fold 0 l = r);
printf " map_fold_a@.";
assert (map_fold_a ~f ~fold 0 l = r);
printf " master@.";
assert (
let res = ref 0 in
compute
~worker:f
~master:(fun (x,y) z ->
assert (z = x+1 && x = y);
res := !res + z;
if x = 3 then [4,4] else [])
[1,1; 2,2; 3,3];
!res = 14);
()
end
module TestString(X : MF with type t = string) = struct
open X
let f s = s ^ "."
let fold = (^)
let () =
let l = ["a"; "bb"; "ccc"; "dddd"] in
assert (map f l = ["a."; "bb."; "ccc."; "dddd."]);
let check r =
String.length r = 14 &&
List.for_all
(fun x ->
let i = String.index r x.[0] in
let n = String.length x in
String.sub r i n = x && r.[i + n] = '.')
l
in
printf " map_local_fold@.";
assert (check (map_local_fold ~f ~fold "" l));
printf " map_remote_fold@.";
assert (check (map_remote_fold ~f ~fold "" l));
printf " map_fold_ac@.";
assert (check (map_fold_ac ~f ~fold "" l));
printf " map_fold_a@.";
assert (map_fold_a ~f ~fold "" l = "a.bb.ccc.dddd.");
()
end
* * *
module TestMR(X :
sig
val map_reduce :
map:('v1 - > ( ' k2 * ' v2 ) list ) - >
reduce:('k2 - > ' v2 list list - > ' v2 list ) - >
' v1 list - > ( ' k2 * ' v2 list ) list
end ) = struct
let text = " En l'année 1872 , la maison portant le numéro 7 de Saville - row , Burlington Gardens -- maison dans laquelle en 1814 -- , était habitée par , esq . , l'un des membres les plus singuliers et les plus remarqués du Reform - Club de Londres , attirer l'attention .
A l'un des plus grands , succédait donc ce Phileas , personnage énigmatique , do nt on ne savait rien , sinon que c'était un fort galant homme et l'un des plus beaux gentlemen de la haute société anglaise . "
let is_char j = match text.[j ] with
| ' ' | ' , ' | ' . ' | ' \ '' | ' - ' - > false
| _ - > true
let words =
let n = String.length text in
let rec split acc i =
let rec next j =
if j = n || not ( is_char j ) then
j , String.sub text i ( j - i )
else
next ( j + 1 )
in
let rec adv i = if i < n & & not ( is_char i ) then adv ( i+1 ) else i in
if i = n then acc else let i , s = next i in split ( s : : acc ) ( adv i )
in
split [ ] 0
let chunk_size = words / 3
let rec create_chunk acc i = function
| [ ] - > acc , [ ]
| l when i = 0 - > acc , l
| x : : l - > create_chunk ( x : : acc ) ( i - 1 ) l
let rec split acc l =
if l = [ ] then acc
else let c , l = create_chunk [ ] chunk_size l in split ( c : : acc ) l
let chunks = split [ ] words
let ( ) = printf " "
let merge l1 l2 =
let rec merge acc = function
| [ ] , l | l , [ ] - >
acc l
| x1 : : r1 , ( x2 : : _ as l2 ) when x1 < = x2 - >
merge ( x1 : : acc ) ( r1 , l2 )
| l1 , x2 : : r2 - >
merge ( x2 : : acc ) ( l1 , r2 )
in
merge [ ] ( l1 , l2 )
let > List.map ( fun x - > x,1 ) w )
~reduce:(fun _ l - > [ List.fold_left ( + ) 0 ( List.flatten l ) ] )
chunks
let ( ) =
assert ( List.assoc " l " wc = [ 6 ] ) ;
assert ( List.assoc " " wc = [ 2 ] )
end
* *
module TestMR(X :
sig
val map_reduce :
map:('v1 -> ('k2 * 'v2) list) ->
reduce:('k2 -> 'v2 list list -> 'v2 list) ->
'v1 list -> ('k2 * 'v2 list) list
end) = struct
let text = "En l'année 1872, la maison portant le numéro 7 de Saville-row, Burlington Gardens -- maison dans laquelle Sheridan mourut en 1814 --, était habitée par Phileas Fogg, esq., l'un des membres les plus singuliers et les plus remarqués du Reform-Club de Londres, bien qu'il semblât prendre à tâche de ne rien faire qui pût attirer l'attention.
A l'un des plus grands orateurs qui honorent l'Angleterre, succédait donc ce Phileas Fogg, personnage énigmatique, dont on ne savait rien, sinon que c'était un fort galant homme et l'un des plus beaux gentlemen de la haute société anglaise."
let is_char j = match text.[j] with
| ' ' | ',' | '.' | '\'' | '-' -> false
| _ -> true
let words =
let n = String.length text in
let rec split acc i =
let rec next j =
if j = n || not (is_char j) then
j, String.sub text i (j - i)
else
next (j + 1)
in
let rec adv i = if i < n && not (is_char i) then adv (i+1) else i in
if i = n then acc else let i, s = next i in split (s :: acc) (adv i)
in
split [] 0
let chunk_size = List.length words / 3
let rec create_chunk acc i = function
| [] -> acc, []
| l when i = 0 -> acc, l
| x :: l -> create_chunk (x :: acc) (i - 1) l
let rec split acc l =
if l = [] then acc
else let c, l = create_chunk [] chunk_size l in split (c :: acc) l
let chunks = split [] words
let () = printf " map_reduce@."
let merge l1 l2 =
let rec merge acc = function
| [], l | l, [] ->
List.rev_append acc l
| x1 :: r1, (x2 :: _ as l2) when x1 <= x2 ->
merge (x1 :: acc) (r1, l2)
| l1, x2 :: r2 ->
merge (x2 :: acc) (l1, r2)
in
merge [] (l1, l2)
let wc =
X.map_reduce
~map:(fun w -> List.map (fun x -> x,1) w)
~reduce:(fun _ l -> [List.fold_left (+) 0 (List.flatten l)])
chunks
let () =
assert (List.assoc "l" wc = [6]);
assert (List.assoc "Fogg" wc = [2])
end
***)
let () = printf "Sequential@."
module TestIntSeq =
TestInt(struct type t = int include Functory.Sequential end)
module TestStringSeq =
TestString(struct type t = string include Functory.Sequential end)
module TestMRSeq =
TestMR(Functory . Sequential )
let () = printf "Cores@."
let () = Functory.Cores.set_number_of_cores 2
module TestIntCores =
TestInt(struct type t = int include Functory.Cores end)
module TestStringCores =
TestString(struct type t = string include Functory.Cores end)
TestMR(Functory . Cores )
let () = printf "Network@."
let () = Functory.Network.declare_workers ~n:2 "localhost"
module TestIntNetwork =
TestInt(struct type t = int include Functory.Network.Same end)
TestString(struct type t = string include Functory . Network . Same end )
module TestStringNetworkStr =
TestString(struct type t = string include Functory . Network . end )
* * * * * * * * * *
let rec compute x = if x < = 1 then 1 else x * compute ( x-1 )
( * let n = map_fold_a ~map : compute ) 0 [ 1;2;3;4;5;6;7;8;9 ]
let rec compute x = if x <= 1 then 1 else x * compute (x-1)
let f x = sprintf ".%d." x
let s = map_fold_a ~map:f ~fold:(^) "" [1;2;3;4;5;6;7]
let () = printf "%s@." s; exit 0
let l = map compute [1;2;3;4]
let () = List.iter (fun s -> printf "%d@." s) l; printf "---@."
let l = map compute l
let () = List.iter (fun s -> printf "%d@." s) l; printf "---@."
let compute s =
let rec fib n = if n <= 1 then 1 else fib (n-1) + fib (n-2) in
string_of_int (fib (int_of_string s))
let l = map compute ["10"; "20"; "15"]
let () = List.iter (fun s -> printf "%s@." s) l; printf "---@."
let l = map compute ["10"; "20"; "15"]
let () = List.iter (fun s -> printf "%s@." s) l; printf "---@."
let l = map compute ["5"; "6"; "7"; "8"; "9"; "10"; "11"; "12"; "13";
"20"; "30"; "40"; ]
let () = List.iter (fun s -> printf "%s@." s) l
************)
|
aed95942261db22d839a1f7abf797364f390693cf58077316d3c21b2272d1ee6 | schell/editor | Shape.hs | # LANGUAGE OverloadedStrings , TemplateHaskell #
module Graphics.Rendering.Shader.Shape (
module T,
makeShapeShaderProgram,
bindAndBufferVertsUVs,
bindAndBufferVertsColors
) where
import Graphics.Utils
import Graphics.Rendering.Shader.Utils
import Graphics.Rendering.Shader.Shape.Types as T
import Graphics.Rendering.OpenGL hiding (Bitmap, Matrix)
import Graphics.Rendering.OpenGL.Raw (glUniformMatrix4fv)
import Foreign
import Control.Monad
import Graphics.Rendering.Shader.TH
import qualified Data.ByteString as B
-- | Compiles, validates and returns a shader for rendering text with.
makeShapeShaderProgram :: IO ShapeShaderProgram
makeShapeShaderProgram = do
v <- makeShader VertexShader vertSrc
f <- makeShader FragmentShader fragSrc
p <- makeProgram [v,f] [ ("position", positionLocation)
, ("color", colorLocation)
, ("uv", uvLocation)
]
currentProgram $= Just p
printError
UniformLocation mv <- get $ uniformLocation p "modelview"
UniformLocation pj <- get $ uniformLocation p "projection"
let updateMV mat = withArray mat $ \ptr ->
glUniformMatrix4fv mv 1 1 ptr
updatePJ mat = withArray mat $ \ptr ->
glUniformMatrix4fv pj 1 1 ptr
sLoc <- get $ uniformLocation p "sampler"
tLoc <- get $ uniformLocation p "isTextured"
let updateSampler s = uniform sLoc $= s
return ShapeShaderProgram { _program = p
, _setProjection = updatePJ
, _setModelview = updateMV
, _setSampler = updateSampler
, _setIsTextured = updateIsTextured tLoc
}
-- | Updates the shader to accept either uv coords if textured or color
-- values if not. Assumes a shape shader program is set as the current
-- program.
updateIsTextured :: UniformLocation -> Bool -> IO ()
updateIsTextured uloc isTextured = do
when isTextured $ do
vertexAttribArray colorLocation $= Disabled
vertexAttribArray uvLocation $= Enabled
unless isTextured $ do
vertexAttribArray colorLocation $= Enabled
vertexAttribArray uvLocation $= Disabled
uniform uloc $= (Index1 $ if isTextured then 1 else 0 :: GLint)
-- | GLSL Source code for a shape vertex shader.
vertSrc :: B.ByteString
vertSrc = $(embedFile "shaders/shapeshader.vert")
-- | GLSL Source code for a shape fragment shader.
fragSrc :: B.ByteString
fragSrc = $(embedFile "shaders/shapeshader.frag")
positionLocation :: AttribLocation
positionLocation = AttribLocation 0
colorLocation :: AttribLocation
colorLocation = AttribLocation 1
uvLocation :: AttribLocation
uvLocation = AttribLocation 2
-- | Vertex descriptor for a shape vertex shader.
vertDescriptor :: VertexArrayDescriptor [Float]
vertDescriptor = VertexArrayDescriptor 2 Float 0 nullPtr
-- | UV descriptor for a shape vertex shader.
uvDescriptor :: VertexArrayDescriptor [Float]
uvDescriptor = vertDescriptor
-- | Color descriptor for a shape vertex shader.
colorDescriptor :: VertexArrayDescriptor [Float]
colorDescriptor = VertexArrayDescriptor 4 Float 0 nullPtr
-- | Binds and buffers vertices and uv coords to be used with a text
-- shader. This assumes that a text shader program is the current program.
bindAndBufferVertsUVs :: [GLfloat] -> [GLfloat] -> IO (BufferObject, BufferObject)
bindAndBufferVertsUVs vts uvs = do
[i,j] <- genObjectNames 2
bindVBO i vertDescriptor positionLocation
withArray vts $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList vts, ptr, StaticDraw)
bindVBO j uvDescriptor uvLocation
withArray uvs $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList uvs, ptr, StaticDraw)
return (i,j)
bindAndBufferVertsColors :: [GLfloat] -> [GLfloat] -> IO (BufferObject, BufferObject)
bindAndBufferVertsColors vts cs = do
[i,j] <- genObjectNames 2
bindVBO i vertDescriptor positionLocation
withArray vts $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList vts, ptr, StaticDraw)
bindVBO j colorDescriptor colorLocation
withArray cs $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList cs, ptr, StaticDraw)
return (i,j)
| null | https://raw.githubusercontent.com/schell/editor/0f0d2eb67df19e8285c6aaeeeca96bff3110f68d/src/Graphics/Rendering/Shader/Shape.hs | haskell | | Compiles, validates and returns a shader for rendering text with.
| Updates the shader to accept either uv coords if textured or color
values if not. Assumes a shape shader program is set as the current
program.
| GLSL Source code for a shape vertex shader.
| GLSL Source code for a shape fragment shader.
| Vertex descriptor for a shape vertex shader.
| UV descriptor for a shape vertex shader.
| Color descriptor for a shape vertex shader.
| Binds and buffers vertices and uv coords to be used with a text
shader. This assumes that a text shader program is the current program. | # LANGUAGE OverloadedStrings , TemplateHaskell #
module Graphics.Rendering.Shader.Shape (
module T,
makeShapeShaderProgram,
bindAndBufferVertsUVs,
bindAndBufferVertsColors
) where
import Graphics.Utils
import Graphics.Rendering.Shader.Utils
import Graphics.Rendering.Shader.Shape.Types as T
import Graphics.Rendering.OpenGL hiding (Bitmap, Matrix)
import Graphics.Rendering.OpenGL.Raw (glUniformMatrix4fv)
import Foreign
import Control.Monad
import Graphics.Rendering.Shader.TH
import qualified Data.ByteString as B
makeShapeShaderProgram :: IO ShapeShaderProgram
makeShapeShaderProgram = do
v <- makeShader VertexShader vertSrc
f <- makeShader FragmentShader fragSrc
p <- makeProgram [v,f] [ ("position", positionLocation)
, ("color", colorLocation)
, ("uv", uvLocation)
]
currentProgram $= Just p
printError
UniformLocation mv <- get $ uniformLocation p "modelview"
UniformLocation pj <- get $ uniformLocation p "projection"
let updateMV mat = withArray mat $ \ptr ->
glUniformMatrix4fv mv 1 1 ptr
updatePJ mat = withArray mat $ \ptr ->
glUniformMatrix4fv pj 1 1 ptr
sLoc <- get $ uniformLocation p "sampler"
tLoc <- get $ uniformLocation p "isTextured"
let updateSampler s = uniform sLoc $= s
return ShapeShaderProgram { _program = p
, _setProjection = updatePJ
, _setModelview = updateMV
, _setSampler = updateSampler
, _setIsTextured = updateIsTextured tLoc
}
updateIsTextured :: UniformLocation -> Bool -> IO ()
updateIsTextured uloc isTextured = do
when isTextured $ do
vertexAttribArray colorLocation $= Disabled
vertexAttribArray uvLocation $= Enabled
unless isTextured $ do
vertexAttribArray colorLocation $= Enabled
vertexAttribArray uvLocation $= Disabled
uniform uloc $= (Index1 $ if isTextured then 1 else 0 :: GLint)
vertSrc :: B.ByteString
vertSrc = $(embedFile "shaders/shapeshader.vert")
fragSrc :: B.ByteString
fragSrc = $(embedFile "shaders/shapeshader.frag")
positionLocation :: AttribLocation
positionLocation = AttribLocation 0
colorLocation :: AttribLocation
colorLocation = AttribLocation 1
uvLocation :: AttribLocation
uvLocation = AttribLocation 2
vertDescriptor :: VertexArrayDescriptor [Float]
vertDescriptor = VertexArrayDescriptor 2 Float 0 nullPtr
uvDescriptor :: VertexArrayDescriptor [Float]
uvDescriptor = vertDescriptor
colorDescriptor :: VertexArrayDescriptor [Float]
colorDescriptor = VertexArrayDescriptor 4 Float 0 nullPtr
bindAndBufferVertsUVs :: [GLfloat] -> [GLfloat] -> IO (BufferObject, BufferObject)
bindAndBufferVertsUVs vts uvs = do
[i,j] <- genObjectNames 2
bindVBO i vertDescriptor positionLocation
withArray vts $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList vts, ptr, StaticDraw)
bindVBO j uvDescriptor uvLocation
withArray uvs $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList uvs, ptr, StaticDraw)
return (i,j)
bindAndBufferVertsColors :: [GLfloat] -> [GLfloat] -> IO (BufferObject, BufferObject)
bindAndBufferVertsColors vts cs = do
[i,j] <- genObjectNames 2
bindVBO i vertDescriptor positionLocation
withArray vts $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList vts, ptr, StaticDraw)
bindVBO j colorDescriptor colorLocation
withArray cs $ \ptr -> do
bufferData ArrayBuffer $= (sizeOfList cs, ptr, StaticDraw)
return (i,j)
|
262efe743680e201c8de7d822aeb75acd68d59358ebd54e6c5288bc22234d833 | mflatt/profj | parsers.scm | (module parsers scheme/base
(require "parser-units.scm"
scheme/unit
(only-in (lib "combinator-unit.ss" "combinator-parser") err^))
(provide parse-beginner parse-intermediate parse-intermediate+access parse-advanced
parse-beginner-interact parse-intermediate-interact parse-advanced-interact)
(define (trim-string s f l)
(substring s f (- (string-length s) l)))
(define-values/invoke-unit beginner-definitions-parser@
(import)
(export (prefix beginner-def: parsers^) (prefix beginner-def: err^) token-proc^))
(define-values/invoke-unit beginner-interactions-parsers@
(import)
(export (prefix beginner-int: parsers^) (prefix beginner-int: err^)))
(define-values/invoke-unit intermediate-definitions-parser@
(import)
(export (prefix intermediate-def: parsers^) (prefix intermediate-def: err^)))
(define-values/invoke-unit intermediate-interactions-parsers@
(import)
(export (prefix intermediate-int: parsers^) (prefix intermediate-int: err^)))
(define-values/invoke-unit intermediate+access-definitions-parser@
(import)
(export (prefix intermediate+acc-def: parsers^) (prefix intermediate+acc-def: err^)))
(define-values/invoke-unit intermediate+access-interactions-parsers@
(import)
(export (prefix intermediate+acc-int: parsers^) (prefix intermediate+acc-int: err^)))
(define-values/invoke-unit advanced-definitions-parser@
(import)
(export (prefix advanced-def: parsers^) (prefix advanced-def: err^)))
(define-values/invoke-unit advanced-interactions-parsers@
(import)
(export (prefix advanced-int: parsers^) (prefix advanced-int: err^) ))
(define (parse parser err? err-src err-msg)
(lambda (program-stream location)
(let ([output (parser (old-tokens->new program-stream) location)])
(and (err? output) (list (err-msg output) (err-src output))))))
(define parse-beginner (parse beginner-def:parse-program
beginner-def:err? beginner-def:err-msg beginner-def:err-src))
(define parse-intermediate (parse intermediate-def:parse-program
intermediate-def:err? intermediate-def:err-msg intermediate-def:err-src))
(define parse-intermediate+access (parse intermediate+acc-def:parse-program
intermediate+acc-def:err? intermediate+acc-def:err-msg intermediate+acc-def:err-src))
(define parse-advanced (parse advanced-def:parse-program
advanced-def:err? advanced-def:err-msg advanced-def:err-src))
(define parse-beginner-interact (parse beginner-int:parse-program
beginner-int:err? beginner-int:err-msg beginner-int:err-src))
(define parse-intermediate-interact (parse intermediate-int:parse-program
intermediate-int:err? intermediate-int:err-msg intermediate-int:err-src))
(define parse-advanced-interact (parse advanced-int:parse-program
advanced-int:err? advanced-int:err-msg advanced-int:err-src))
)
| null | https://raw.githubusercontent.com/mflatt/profj/cf2a5bd0c3243b4dd3a72093ae5eee8e8291a41d/profj/comb-parsers/parsers.scm | scheme | (module parsers scheme/base
(require "parser-units.scm"
scheme/unit
(only-in (lib "combinator-unit.ss" "combinator-parser") err^))
(provide parse-beginner parse-intermediate parse-intermediate+access parse-advanced
parse-beginner-interact parse-intermediate-interact parse-advanced-interact)
(define (trim-string s f l)
(substring s f (- (string-length s) l)))
(define-values/invoke-unit beginner-definitions-parser@
(import)
(export (prefix beginner-def: parsers^) (prefix beginner-def: err^) token-proc^))
(define-values/invoke-unit beginner-interactions-parsers@
(import)
(export (prefix beginner-int: parsers^) (prefix beginner-int: err^)))
(define-values/invoke-unit intermediate-definitions-parser@
(import)
(export (prefix intermediate-def: parsers^) (prefix intermediate-def: err^)))
(define-values/invoke-unit intermediate-interactions-parsers@
(import)
(export (prefix intermediate-int: parsers^) (prefix intermediate-int: err^)))
(define-values/invoke-unit intermediate+access-definitions-parser@
(import)
(export (prefix intermediate+acc-def: parsers^) (prefix intermediate+acc-def: err^)))
(define-values/invoke-unit intermediate+access-interactions-parsers@
(import)
(export (prefix intermediate+acc-int: parsers^) (prefix intermediate+acc-int: err^)))
(define-values/invoke-unit advanced-definitions-parser@
(import)
(export (prefix advanced-def: parsers^) (prefix advanced-def: err^)))
(define-values/invoke-unit advanced-interactions-parsers@
(import)
(export (prefix advanced-int: parsers^) (prefix advanced-int: err^) ))
(define (parse parser err? err-src err-msg)
(lambda (program-stream location)
(let ([output (parser (old-tokens->new program-stream) location)])
(and (err? output) (list (err-msg output) (err-src output))))))
(define parse-beginner (parse beginner-def:parse-program
beginner-def:err? beginner-def:err-msg beginner-def:err-src))
(define parse-intermediate (parse intermediate-def:parse-program
intermediate-def:err? intermediate-def:err-msg intermediate-def:err-src))
(define parse-intermediate+access (parse intermediate+acc-def:parse-program
intermediate+acc-def:err? intermediate+acc-def:err-msg intermediate+acc-def:err-src))
(define parse-advanced (parse advanced-def:parse-program
advanced-def:err? advanced-def:err-msg advanced-def:err-src))
(define parse-beginner-interact (parse beginner-int:parse-program
beginner-int:err? beginner-int:err-msg beginner-int:err-src))
(define parse-intermediate-interact (parse intermediate-int:parse-program
intermediate-int:err? intermediate-int:err-msg intermediate-int:err-src))
(define parse-advanced-interact (parse advanced-int:parse-program
advanced-int:err? advanced-int:err-msg advanced-int:err-src))
)
| |
caa2ebba0376aa56d48a2b73db5201dd06d031b892802f6333f54b7ef4548508 | amperity/envoy | core.clj | (ns envoy.core
"Core environment handling namespace."
(:require
[clojure.tools.logging :as log]
[environ.core :as environ]
[envoy.check :as check :refer [behave!]]
[envoy.types :as types]))
(def known-vars
"Map of environment keywords to a definition map which may contain a
`:description` and optionally a `:type` for auto-coercion."
{})
(def variable-schema
"Simple key->predicate schema for variable definitions."
{:ns symbol?
:line number?
:description string?
:type types/value-types
:parser fn?
:default any?
:missing check/behavior-types})
# # Var Declaration
(defn- declared-location
"Returns a string naming the location an env variable was declared."
[properties]
(let [ns-sym (:ns properties)
ns-line (:line properties)]
(some-> ns-sym (cond-> ns-line (str ":" ns-line)))))
(defn- validate-attr!
"Checks whether the given variable property matches the declared schema. No
effect if no schema is found. Returns true if the value is valid."
[env-key prop-key properties]
(if-let [pred (and (contains? properties prop-key)
(variable-schema prop-key))]
(let [value (get properties prop-key)]
(if (pred value)
true
(log/warnf
"Environment variable %s (%s) declares invalid value %s for property %s (failed %s)"
env-key (declared-location properties) (pr-str value) prop-key pred)))
true))
(defn declare-env-attr!
"Helper function which adds elements to the `variable-schema` map."
[prop-key pred]
;; Check existing variables.
(doseq [[env-key properties] known-vars]
(validate-attr! env-key prop-key properties))
;; Update schema map.
(alter-var-root #'variable-schema assoc prop-key pred))
(defn declare-env-var!
"Helper function for the `defenv` macro. Declares properties for an
environment variable, checking various schema properties."
[env-key properties]
;; Check for previous declarations.
(when-let [extant (get known-vars env-key)]
(when (not= (:ns extant) (:ns properties))
(log/warnf "Environment variable definition for %s at %s is overriding existing definition from %s"
env-key
(declared-location properties)
(declared-location extant))))
;; Check property schemas.
(doseq [prop-key (keys properties)]
(validate-attr! env-key prop-key properties))
;; Update known variables map.
(-> #'known-vars
(alter-var-root assoc env-key properties)
(get env-key)))
(defmacro defenv
"Define a new environment variable used by the system."
[env-key description & {:as opts}]
`(declare-env-var!
~env-key
(assoc ~opts
:ns '~(symbol (str *ns*))
:line ~(:line (meta &form))
:description ~description)))
# # Access Behavior
(def accesses
"Atom containing access counts for all environment maps."
(atom {} :validator #(and (map? %)
(every? keyword? (keys %))
(every? number? (vals %)))))
(defn clear-accesses!
"Resets the variable accesses map to an empty state."
[]
(swap! accesses empty))
(defn- on-access!
"Called when a variable is accessed in the environment map with the key and
original (string) config value. Returns the processed value."
[k v]
;; Update access counter.
(swap! accesses update k (fnil inc 0))
;; Look up variable definition.
(if-let [definition (get known-vars k)]
(if (some? v)
;; Parse the string value with custom parser or for known types.
(if-let [parser (:parser definition)]
(parser v)
(if-let [type-key (:type definition)]
(types/parse type-key v)
v))
(if-let [default (:default definition)]
(do
(log/infof "Environment variable %s has no value, using default '%s'"
k default)
default)
;; Check if the var has missing behavior.
(behave! :missing-access (:missing definition)
"Access to env variable %s which has no value" k)))
;; No definition found for key.
(do
(behave! :undeclared-access "Access to undeclared env variable %s" k)
v)))
(defn- on-override!
"Called when a variable is overridden in the environment map with the key,
old value, and new value. Returns the new value to use."
[k v1 v2]
;; Look up variable definition.
(let [definition (get known-vars k)]
(when-not definition
(behave! :undeclared-override "Overriding undeclared env variable %s" k))
v2))
;; ## Environment Map
(deftype EnvironmentMap
[config _meta]
java.lang.Object
(toString
[this]
(str "EnvironmentMap " config))
(equals
[this that]
(boolean
(or (identical? this that)
(when (identical? (class this) (class that))
(= config (.config ^EnvironmentMap that))))))
(hashCode
[this]
(hash [(class this) config]))
clojure.lang.IObj
(meta
[this]
_meta)
(withMeta
[this meta-map]
(EnvironmentMap. config meta-map))
clojure.lang.IFn
(invoke
[this k]
(.valAt this k))
(invoke
[this k not-found]
(.valAt this k not-found))
(applyTo
[this args]
(case (count args)
1 (.valAt this (first args))
2 (.valAt this (first args) (second args))
(throw (clojure.lang.ArityException. (count args) "EnvironmentMap.applyTo"))))
clojure.lang.ILookup
(valAt
[this k]
(.valAt this k nil))
(valAt
[this k not-found]
(on-access! k (get config k not-found)))
clojure.lang.IPersistentMap
(count
[this]
(count config))
(empty
[this]
(EnvironmentMap. (empty config) _meta))
(cons
[this element]
(EnvironmentMap. (conj config element) _meta))
(equiv
[this that]
(.equals this that))
(containsKey
[this k]
(contains? config k))
(entryAt
[this k]
(when-some [v (.valAt this k)]
(clojure.lang.MapEntry. k v)))
(seq
[this]
(seq config))
(iterator
[this]
(clojure.lang.RT/iter (seq config)))
(assoc
[this k v]
(EnvironmentMap.
(update config k #(on-override! k % v))
_meta))
(without
[this k]
(on-override! k (get config k) nil)
(EnvironmentMap. (dissoc config k) _meta)))
(defmethod print-method EnvironmentMap
[v ^java.io.Writer w]
(.write w (str v)))
;; Remove automatic constructor function.
(ns-unmap *ns* '->EnvironmentMap)
(defn ^:no-doc env-map
"Constructs a new environment map."
([]
(env-map {}))
([config]
{:pre [(map? config)
(every? keyword? (keys config))
(every? string? (vals config))]}
(EnvironmentMap. config nil)))
(def env
"Global default environment map as loaded by `environ.core`."
(env-map environ/env))
(defn set-env!
"Updates the global environment map with a new value for the given variable.
This should generally only be used from a REPL, and will not affect the actual
system environment!"
[var-key value & kvs]
(alter-var-root #'env #(apply assoc % var-key value kvs))
nil)
| null | https://raw.githubusercontent.com/amperity/envoy/898ff9262b7a7bff9d666041974b97986faee471/src/envoy/core.clj | clojure | Check existing variables.
Update schema map.
Check for previous declarations.
Check property schemas.
Update known variables map.
Update access counter.
Look up variable definition.
Parse the string value with custom parser or for known types.
Check if the var has missing behavior.
No definition found for key.
Look up variable definition.
## Environment Map
Remove automatic constructor function. | (ns envoy.core
"Core environment handling namespace."
(:require
[clojure.tools.logging :as log]
[environ.core :as environ]
[envoy.check :as check :refer [behave!]]
[envoy.types :as types]))
(def known-vars
"Map of environment keywords to a definition map which may contain a
`:description` and optionally a `:type` for auto-coercion."
{})
(def variable-schema
"Simple key->predicate schema for variable definitions."
{:ns symbol?
:line number?
:description string?
:type types/value-types
:parser fn?
:default any?
:missing check/behavior-types})
# # Var Declaration
(defn- declared-location
"Returns a string naming the location an env variable was declared."
[properties]
(let [ns-sym (:ns properties)
ns-line (:line properties)]
(some-> ns-sym (cond-> ns-line (str ":" ns-line)))))
(defn- validate-attr!
"Checks whether the given variable property matches the declared schema. No
effect if no schema is found. Returns true if the value is valid."
[env-key prop-key properties]
(if-let [pred (and (contains? properties prop-key)
(variable-schema prop-key))]
(let [value (get properties prop-key)]
(if (pred value)
true
(log/warnf
"Environment variable %s (%s) declares invalid value %s for property %s (failed %s)"
env-key (declared-location properties) (pr-str value) prop-key pred)))
true))
(defn declare-env-attr!
"Helper function which adds elements to the `variable-schema` map."
[prop-key pred]
(doseq [[env-key properties] known-vars]
(validate-attr! env-key prop-key properties))
(alter-var-root #'variable-schema assoc prop-key pred))
(defn declare-env-var!
"Helper function for the `defenv` macro. Declares properties for an
environment variable, checking various schema properties."
[env-key properties]
(when-let [extant (get known-vars env-key)]
(when (not= (:ns extant) (:ns properties))
(log/warnf "Environment variable definition for %s at %s is overriding existing definition from %s"
env-key
(declared-location properties)
(declared-location extant))))
(doseq [prop-key (keys properties)]
(validate-attr! env-key prop-key properties))
(-> #'known-vars
(alter-var-root assoc env-key properties)
(get env-key)))
(defmacro defenv
"Define a new environment variable used by the system."
[env-key description & {:as opts}]
`(declare-env-var!
~env-key
(assoc ~opts
:ns '~(symbol (str *ns*))
:line ~(:line (meta &form))
:description ~description)))
# # Access Behavior
(def accesses
"Atom containing access counts for all environment maps."
(atom {} :validator #(and (map? %)
(every? keyword? (keys %))
(every? number? (vals %)))))
(defn clear-accesses!
"Resets the variable accesses map to an empty state."
[]
(swap! accesses empty))
(defn- on-access!
"Called when a variable is accessed in the environment map with the key and
original (string) config value. Returns the processed value."
[k v]
(swap! accesses update k (fnil inc 0))
(if-let [definition (get known-vars k)]
(if (some? v)
(if-let [parser (:parser definition)]
(parser v)
(if-let [type-key (:type definition)]
(types/parse type-key v)
v))
(if-let [default (:default definition)]
(do
(log/infof "Environment variable %s has no value, using default '%s'"
k default)
default)
(behave! :missing-access (:missing definition)
"Access to env variable %s which has no value" k)))
(do
(behave! :undeclared-access "Access to undeclared env variable %s" k)
v)))
(defn- on-override!
"Called when a variable is overridden in the environment map with the key,
old value, and new value. Returns the new value to use."
[k v1 v2]
(let [definition (get known-vars k)]
(when-not definition
(behave! :undeclared-override "Overriding undeclared env variable %s" k))
v2))
(deftype EnvironmentMap
[config _meta]
java.lang.Object
(toString
[this]
(str "EnvironmentMap " config))
(equals
[this that]
(boolean
(or (identical? this that)
(when (identical? (class this) (class that))
(= config (.config ^EnvironmentMap that))))))
(hashCode
[this]
(hash [(class this) config]))
clojure.lang.IObj
(meta
[this]
_meta)
(withMeta
[this meta-map]
(EnvironmentMap. config meta-map))
clojure.lang.IFn
(invoke
[this k]
(.valAt this k))
(invoke
[this k not-found]
(.valAt this k not-found))
(applyTo
[this args]
(case (count args)
1 (.valAt this (first args))
2 (.valAt this (first args) (second args))
(throw (clojure.lang.ArityException. (count args) "EnvironmentMap.applyTo"))))
clojure.lang.ILookup
(valAt
[this k]
(.valAt this k nil))
(valAt
[this k not-found]
(on-access! k (get config k not-found)))
clojure.lang.IPersistentMap
(count
[this]
(count config))
(empty
[this]
(EnvironmentMap. (empty config) _meta))
(cons
[this element]
(EnvironmentMap. (conj config element) _meta))
(equiv
[this that]
(.equals this that))
(containsKey
[this k]
(contains? config k))
(entryAt
[this k]
(when-some [v (.valAt this k)]
(clojure.lang.MapEntry. k v)))
(seq
[this]
(seq config))
(iterator
[this]
(clojure.lang.RT/iter (seq config)))
(assoc
[this k v]
(EnvironmentMap.
(update config k #(on-override! k % v))
_meta))
(without
[this k]
(on-override! k (get config k) nil)
(EnvironmentMap. (dissoc config k) _meta)))
(defmethod print-method EnvironmentMap
[v ^java.io.Writer w]
(.write w (str v)))
(ns-unmap *ns* '->EnvironmentMap)
(defn ^:no-doc env-map
"Constructs a new environment map."
([]
(env-map {}))
([config]
{:pre [(map? config)
(every? keyword? (keys config))
(every? string? (vals config))]}
(EnvironmentMap. config nil)))
(def env
"Global default environment map as loaded by `environ.core`."
(env-map environ/env))
(defn set-env!
"Updates the global environment map with a new value for the given variable.
This should generally only be used from a REPL, and will not affect the actual
system environment!"
[var-key value & kvs]
(alter-var-root #'env #(apply assoc % var-key value kvs))
nil)
|
fe10f09cd524e743986231cd2ad897eee05d6bddda5b31e8fa19bcad3eeb5c7b | acowley/Frames | UncurryFoldNoHeader.hs | # LANGUAGE DataKinds , FlexibleContexts , QuasiQuotes , TemplateHaskell , TypeApplications #
module UncurryFoldNoHeader where
import qualified Control.Foldl as L
import Data.Vinyl.Curry ( runcurryX )
import Frames
import Frames.TH ( rowGen
, RowGen(..)
)
Data set from
tableTypes' (rowGen "test/data/prestigeNoHeader.csv")
{ rowTypeName = "NoH"
, columnNames = [ "Job", "Schooling", "Money", "Females"
, "Respect", "Census", "Category" ]
, tablePrefix = "NoHead"}
loadRows :: IO (Frame NoH)
loadRows = inCoreAoS (readTableOpt noHParser "test/data/prestigeNoHeader.csv")
-- | Compute the ratio of money to respect for a record containing
-- only those fields.
ratio :: Record '[NoHeadMoney, NoHeadRespect] -> Double
ratio = runcurryX (\m r -> fromIntegral m / r)
averageRatio :: IO Double
averageRatio = L.fold (L.premap (ratio . rcast) avg) <$> loadRows
where avg = (/) <$> L.sum <*> L.genericLength
| null | https://raw.githubusercontent.com/acowley/Frames/aeca953fe608de38d827b8a078ebf2d329edae04/test/UncurryFoldNoHeader.hs | haskell | | Compute the ratio of money to respect for a record containing
only those fields. | # LANGUAGE DataKinds , FlexibleContexts , QuasiQuotes , TemplateHaskell , TypeApplications #
module UncurryFoldNoHeader where
import qualified Control.Foldl as L
import Data.Vinyl.Curry ( runcurryX )
import Frames
import Frames.TH ( rowGen
, RowGen(..)
)
Data set from
tableTypes' (rowGen "test/data/prestigeNoHeader.csv")
{ rowTypeName = "NoH"
, columnNames = [ "Job", "Schooling", "Money", "Females"
, "Respect", "Census", "Category" ]
, tablePrefix = "NoHead"}
loadRows :: IO (Frame NoH)
loadRows = inCoreAoS (readTableOpt noHParser "test/data/prestigeNoHeader.csv")
ratio :: Record '[NoHeadMoney, NoHeadRespect] -> Double
ratio = runcurryX (\m r -> fromIntegral m / r)
averageRatio :: IO Double
averageRatio = L.fold (L.premap (ratio . rcast) avg) <$> loadRows
where avg = (/) <$> L.sum <*> L.genericLength
|
8f7d58ead2ffa786bc7d6872a01d8d5c5f16bba3a60a236b5acb20b13f9e5e2a | SimulaVR/godot-haskell | LightOccluder2D.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.LightOccluder2D
(Godot.Core.LightOccluder2D._poly_changed,
Godot.Core.LightOccluder2D.get_occluder_light_mask,
Godot.Core.LightOccluder2D.get_occluder_polygon,
Godot.Core.LightOccluder2D.set_occluder_light_mask,
Godot.Core.LightOccluder2D.set_occluder_polygon)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Node2D()
instance NodeProperty LightOccluder2D "light_mask" Int 'False where
nodeProperty
= (get_occluder_light_mask,
wrapDroppingSetter set_occluder_light_mask, Nothing)
instance NodeProperty LightOccluder2D "occluder" OccluderPolygon2D
'False
where
nodeProperty
= (get_occluder_polygon, wrapDroppingSetter set_occluder_polygon,
Nothing)
# NOINLINE bindLightOccluder2D__poly_changed #
bindLightOccluder2D__poly_changed :: MethodBind
bindLightOccluder2D__poly_changed
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "_poly_changed" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_poly_changed ::
(LightOccluder2D :< cls, Object :< cls) => cls -> IO ()
_poly_changed cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D__poly_changed
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "_poly_changed" '[] (IO ())
where
nodeMethod = Godot.Core.LightOccluder2D._poly_changed
# NOINLINE bindLightOccluder2D_get_occluder_light_mask #
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
bindLightOccluder2D_get_occluder_light_mask :: MethodBind
bindLightOccluder2D_get_occluder_light_mask
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "get_occluder_light_mask" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
get_occluder_light_mask ::
(LightOccluder2D :< cls, Object :< cls) => cls -> IO Int
get_occluder_light_mask cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_get_occluder_light_mask
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "get_occluder_light_mask" '[]
(IO Int)
where
nodeMethod = Godot.Core.LightOccluder2D.get_occluder_light_mask
# NOINLINE bindLightOccluder2D_get_occluder_polygon #
| The @OccluderPolygon2D@ used to compute the shadow .
bindLightOccluder2D_get_occluder_polygon :: MethodBind
bindLightOccluder2D_get_occluder_polygon
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "get_occluder_polygon" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The @OccluderPolygon2D@ used to compute the shadow .
get_occluder_polygon ::
(LightOccluder2D :< cls, Object :< cls) =>
cls -> IO OccluderPolygon2D
get_occluder_polygon cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_get_occluder_polygon
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "get_occluder_polygon" '[]
(IO OccluderPolygon2D)
where
nodeMethod = Godot.Core.LightOccluder2D.get_occluder_polygon
# NOINLINE bindLightOccluder2D_set_occluder_light_mask #
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
bindLightOccluder2D_set_occluder_light_mask :: MethodBind
bindLightOccluder2D_set_occluder_light_mask
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "set_occluder_light_mask" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
set_occluder_light_mask ::
(LightOccluder2D :< cls, Object :< cls) => cls -> Int -> IO ()
set_occluder_light_mask cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_set_occluder_light_mask
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "set_occluder_light_mask"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.LightOccluder2D.set_occluder_light_mask
# NOINLINE bindLightOccluder2D_set_occluder_polygon #
| The @OccluderPolygon2D@ used to compute the shadow .
bindLightOccluder2D_set_occluder_polygon :: MethodBind
bindLightOccluder2D_set_occluder_polygon
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "set_occluder_polygon" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The @OccluderPolygon2D@ used to compute the shadow .
set_occluder_polygon ::
(LightOccluder2D :< cls, Object :< cls) =>
cls -> OccluderPolygon2D -> IO ()
set_occluder_polygon cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_set_occluder_polygon
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "set_occluder_polygon"
'[OccluderPolygon2D]
(IO ())
where
nodeMethod = Godot.Core.LightOccluder2D.set_occluder_polygon | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/LightOccluder2D.hs | haskell | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.LightOccluder2D
(Godot.Core.LightOccluder2D._poly_changed,
Godot.Core.LightOccluder2D.get_occluder_light_mask,
Godot.Core.LightOccluder2D.get_occluder_polygon,
Godot.Core.LightOccluder2D.set_occluder_light_mask,
Godot.Core.LightOccluder2D.set_occluder_polygon)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Node2D()
instance NodeProperty LightOccluder2D "light_mask" Int 'False where
nodeProperty
= (get_occluder_light_mask,
wrapDroppingSetter set_occluder_light_mask, Nothing)
instance NodeProperty LightOccluder2D "occluder" OccluderPolygon2D
'False
where
nodeProperty
= (get_occluder_polygon, wrapDroppingSetter set_occluder_polygon,
Nothing)
# NOINLINE bindLightOccluder2D__poly_changed #
bindLightOccluder2D__poly_changed :: MethodBind
bindLightOccluder2D__poly_changed
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "_poly_changed" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_poly_changed ::
(LightOccluder2D :< cls, Object :< cls) => cls -> IO ()
_poly_changed cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D__poly_changed
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "_poly_changed" '[] (IO ())
where
nodeMethod = Godot.Core.LightOccluder2D._poly_changed
# NOINLINE bindLightOccluder2D_get_occluder_light_mask #
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
bindLightOccluder2D_get_occluder_light_mask :: MethodBind
bindLightOccluder2D_get_occluder_light_mask
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "get_occluder_light_mask" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
get_occluder_light_mask ::
(LightOccluder2D :< cls, Object :< cls) => cls -> IO Int
get_occluder_light_mask cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_get_occluder_light_mask
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "get_occluder_light_mask" '[]
(IO Int)
where
nodeMethod = Godot.Core.LightOccluder2D.get_occluder_light_mask
# NOINLINE bindLightOccluder2D_get_occluder_polygon #
| The @OccluderPolygon2D@ used to compute the shadow .
bindLightOccluder2D_get_occluder_polygon :: MethodBind
bindLightOccluder2D_get_occluder_polygon
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "get_occluder_polygon" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The @OccluderPolygon2D@ used to compute the shadow .
get_occluder_polygon ::
(LightOccluder2D :< cls, Object :< cls) =>
cls -> IO OccluderPolygon2D
get_occluder_polygon cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_get_occluder_polygon
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "get_occluder_polygon" '[]
(IO OccluderPolygon2D)
where
nodeMethod = Godot.Core.LightOccluder2D.get_occluder_polygon
# NOINLINE bindLightOccluder2D_set_occluder_light_mask #
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
bindLightOccluder2D_set_occluder_light_mask :: MethodBind
bindLightOccluder2D_set_occluder_light_mask
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "set_occluder_light_mask" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The 's light mask . The LightOccluder2D will cast shadows only from Light2D(s ) that have the same light mask(s ) .
set_occluder_light_mask ::
(LightOccluder2D :< cls, Object :< cls) => cls -> Int -> IO ()
set_occluder_light_mask cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_set_occluder_light_mask
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "set_occluder_light_mask"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.LightOccluder2D.set_occluder_light_mask
# NOINLINE bindLightOccluder2D_set_occluder_polygon #
| The @OccluderPolygon2D@ used to compute the shadow .
bindLightOccluder2D_set_occluder_polygon :: MethodBind
bindLightOccluder2D_set_occluder_polygon
= unsafePerformIO $
withCString "LightOccluder2D" $
\ clsNamePtr ->
withCString "set_occluder_polygon" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The @OccluderPolygon2D@ used to compute the shadow .
set_occluder_polygon ::
(LightOccluder2D :< cls, Object :< cls) =>
cls -> OccluderPolygon2D -> IO ()
set_occluder_polygon cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindLightOccluder2D_set_occluder_polygon
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod LightOccluder2D "set_occluder_polygon"
'[OccluderPolygon2D]
(IO ())
where
nodeMethod = Godot.Core.LightOccluder2D.set_occluder_polygon | |
9b7ed3c485cd7c8369945e63f33a5d750b9b30e5f54f7ca016f1a5894ddbd809 | bdeket/rktsicm | matcher.rkt | #lang racket/base
(require rackunit
"../../simplify/matcher.rkt"
"../helper.rkt")
(define the-tests
(test-suite
"simplify/matcher"
(check-equal? ((match:->combinators '(a ((? b) 2 3) 1 c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
'(succeed ((b . 1)) ()))
(check-equal? ((match:->combinators `(a ((? b ,number?) 2 3) 1 c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
'(succeed ((b . 1)) ()))
(check-equal? ((match:->combinators `(a ((? b ,symbol?) 2 3) 1 c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
#f)
(check-equal? ((match:->combinators '(a ((? b) 2 3) (? b) c))
'((a (1 2 3) 2 c))
'()
(lambda (x y) `(succeed ,x ,y)))
#f)
(check-equal? ((match:->combinators '(a ((? b) 2 3) (? b) c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
'(succeed ((b . 1)) ()))
(check-equal? ((match:->combinators '(a (?? x) (?? y) (?? x) c))
'((a b b b b b b c))
'()
(lambda (x y) #f))
#f)
bdk ; ; the same as above but testing intermediate stages
(check-equal? (accumulate pp
((match:->combinators '(a (?? x) (?? y) (?? x) c))
'((a b b b b b b c))
'()
(lambda (x y)
(pp `(succeed ,x ,y))
#f)))
'((succeed ((y . #((b b b b b b c) (c))) (x . #((b b b b b b c) (b b b b b b c)))) ())
(succeed ((y . #((b b b b b c) (b c))) (x . #((b b b b b b c) (b b b b b c)))) ())
(succeed ((y . #((b b b b c) (b b c))) (x . #((b b b b b b c) (b b b b c)))) ())
(succeed ((y . #((b b b c) (b b b c))) (x . #((b b b b b b c) (b b b c)))) ())))
(test-case
"palindrome"
(define (palindrome? x)
((match:->combinators '((?? x) ($$ x)))
(list x) '() (lambda (x y) (null? y))))
(check-true (palindrome? '(a b c c b a)))
(check-false (palindrome? '(a b c c a b))))
))
(module+ test
(require rackunit/text-ui)
(run-tests the-tests)) | null | https://raw.githubusercontent.com/bdeket/rktsicm/9a6177d98040f058214add392bd791f5259b83b5/rktsicm/sicm/tests/simplify/matcher.rkt | racket | ; the same as above but testing intermediate stages | #lang racket/base
(require rackunit
"../../simplify/matcher.rkt"
"../helper.rkt")
(define the-tests
(test-suite
"simplify/matcher"
(check-equal? ((match:->combinators '(a ((? b) 2 3) 1 c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
'(succeed ((b . 1)) ()))
(check-equal? ((match:->combinators `(a ((? b ,number?) 2 3) 1 c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
'(succeed ((b . 1)) ()))
(check-equal? ((match:->combinators `(a ((? b ,symbol?) 2 3) 1 c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
#f)
(check-equal? ((match:->combinators '(a ((? b) 2 3) (? b) c))
'((a (1 2 3) 2 c))
'()
(lambda (x y) `(succeed ,x ,y)))
#f)
(check-equal? ((match:->combinators '(a ((? b) 2 3) (? b) c))
'((a (1 2 3) 1 c))
'()
(lambda (x y) `(succeed ,x ,y)))
'(succeed ((b . 1)) ()))
(check-equal? ((match:->combinators '(a (?? x) (?? y) (?? x) c))
'((a b b b b b b c))
'()
(lambda (x y) #f))
#f)
(check-equal? (accumulate pp
((match:->combinators '(a (?? x) (?? y) (?? x) c))
'((a b b b b b b c))
'()
(lambda (x y)
(pp `(succeed ,x ,y))
#f)))
'((succeed ((y . #((b b b b b b c) (c))) (x . #((b b b b b b c) (b b b b b b c)))) ())
(succeed ((y . #((b b b b b c) (b c))) (x . #((b b b b b b c) (b b b b b c)))) ())
(succeed ((y . #((b b b b c) (b b c))) (x . #((b b b b b b c) (b b b b c)))) ())
(succeed ((y . #((b b b c) (b b b c))) (x . #((b b b b b b c) (b b b c)))) ())))
(test-case
"palindrome"
(define (palindrome? x)
((match:->combinators '((?? x) ($$ x)))
(list x) '() (lambda (x y) (null? y))))
(check-true (palindrome? '(a b c c b a)))
(check-false (palindrome? '(a b c c a b))))
))
(module+ test
(require rackunit/text-ui)
(run-tests the-tests)) |
0bdbda97c98c4e401fc6ea4d1c84e584bf9aa72920a9ee011bae8a258773b7ba | google/codeworld | Types.hs | {-# LANGUAGE OverloadedStrings #-}
Copyright 2020 The CodeWorld Authors . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2020 The CodeWorld Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Blocks.Types (setBlockTypes, getTypeBlocks) where
import Blockly.DesignBlock
import Blockly.Event
import Blockly.General
import Data.List (intersperse)
import qualified Data.Text as T
colorPicture = Color 160
colorNumber = Color 210
colorProgram = Color 0
colorColor = Color 290
colorPoly = Color 180
colorBool = Color 100
colorText = Color 45
typePicture = Picture
typeNumber = Number
typeProgram = Program
typeColor = Col
typeBool = Truth
typeText = Str
typeComment = Comment
inlineDef = Inline True
icon :: T.Text -> Field
icon name = FieldImage ("ims/" `T.append` name) 20 20
standardFunction cwName funcName ico types [] color tooltip =
DesignBlock cwName (Function funcName types) [header] inlineDef color (Tooltip tooltip)
where
header = case ico of
Just i -> Dummy [TextE funcName, icon i]
Nothing -> Dummy [TextE funcName]
standardFunction cwName funcName ico types inputNames color tooltip =
DesignBlock
cwName
(Function funcName types)
(header : (argInputs ++ [Dummy [Text ")"]]))
inlineDef
color
(Tooltip tooltip)
where
header = case ico of
Just i -> Value (head inputNames) [Text "(", TextE funcName, icon i]
Nothing -> Value (head inputNames) [Text "(", TextE funcName]
argInputs = map (\name -> Value name [Text ","]) (tail inputNames)
-- PICTURE ----------------------------------------------
cwBlank = standardFunction "cwBlank" "blank" Nothing [Picture] [] colorPicture "Blank picture"
cwCoordinatePlane = standardFunction "cwCoordinatePlane" "coordinatePlane" Nothing [Picture] [] colorPicture "Picture of coordinate plane"
cwCodeWorldLogo = standardFunction "cwCodeWorldLogo" "codeWorldLogo" Nothing [Picture] [] colorPicture "Picture of CodeWorld logo"
cwLettering =
standardFunction
"cwLettering"
"lettering"
Nothing
[typeText, Picture]
["TEXT"]
colorPicture
"Picture of text"
cwDrawingOf =
DesignBlock
"cwDrawingOf"
(Top "drawingOf" [typePicture, typeProgram])
[Value "VALUE" [Text "(", TextE "drawingOf", icon "shape-plus.svg"], Dummy [Text ")"]]
inlineDef
colorProgram
(Tooltip "Displays a drawing of a picture")
cwCircle = standardFunction "cwCircle" "circle" Nothing [typeNumber, typePicture] ["RADIUS"] colorPicture "Picture of a circle"
cwThickCircle =
standardFunction
"cwThickCircle"
"thickCircle"
Nothing
[typeNumber, typeNumber, typePicture]
["RADIUS", "LINEWIDTH"]
colorPicture
"Picture of a circle with a border"
cwSolidCircle =
standardFunction
"cwSolidCircle"
"solidCircle"
Nothing
[typeNumber, typePicture]
["RADIUS"]
colorPicture
"Picture of a solid circle"
cwRectangle =
standardFunction
"cwRectangle"
"rectangle"
Nothing
[typeNumber, typeNumber, typePicture]
["WIDTH", "HEIGHT"]
colorPicture
"Picture of a rectangle"
cwThickRectangle =
standardFunction
"cwThickRectangle"
"thickRectangle"
Nothing
[typeNumber, typeNumber, typeNumber, typePicture]
["WIDTH", "HEIGHT", "LINEWIDTH"]
colorPicture
"Picture of a rectangle with a border"
cwSolidRectangle =
standardFunction
"cwSolidRectangle"
"solidRectangle"
Nothing
[typeNumber, typeNumber, typePicture]
["WIDTH", "HEIGHT"]
colorPicture
"Picture of a solid rectangle"
cwArc =
standardFunction
"cwArc"
"arc"
Nothing
[typeNumber, typeNumber, typeNumber, typePicture]
["STARTANGLE", "ENDANGLE", "RADIUS"]
colorPicture
"A thin arc"
cwSector =
standardFunction
"cwSector"
"sector"
Nothing
[typeNumber, typeNumber, typeNumber, typePicture]
["STARTANGLE", "ENDANGLE", "RADIUS"]
colorPicture
"A solid sector of a circle"
cwThickArc =
standardFunction
"cwThickArc"
"thickArc"
Nothing
[typeNumber, typeNumber, typeNumber, typeNumber, typePicture]
["STARTANGLE", "ENDANGLE", "RADIUS", "LINEWIDTH"]
colorPicture
"An arc with variable line width"
-- Transformations -----------------------------------------------
cwColored =
standardFunction
"cwColored"
"colored"
(Just "format-color-fill.svg")
[typePicture, typeColor, typePicture]
["PICTURE", "COLOR"]
colorPicture
"A colored picture"
cwTranslate =
standardFunction
"cwTranslate"
"translated"
(Just "cursor-move.svg")
[typePicture, typeNumber, typeNumber, typePicture]
["PICTURE", "X", "Y"]
colorPicture
"A translated picture"
cwScale =
standardFunction
"cwScale"
"scaled"
(Just "move-resize-variant.svg")
[typePicture, typeNumber, typeNumber, typePicture]
["PICTURE", "HORZ", "VERTZ"]
colorPicture
"A scaled picture"
cwRotate =
standardFunction
"cwRotate"
"rotated"
(Just "rotate-3d.svg")
[typePicture, typeNumber, typePicture]
["PICTURE", "ANGLE"]
colorPicture
"A rotated picture"
-- NUMBERS ---------------------------------------------
numAdd =
DesignBlock
"numAdd"
(Function "+" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "+"]
]
(Inline True)
colorNumber
(Tooltip "Add two numbers")
numSub =
DesignBlock
"numSub"
(Function "-" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "-"]
]
(Inline True)
colorNumber
(Tooltip "Subtract two numbers")
numMult =
DesignBlock
"numMult"
(Function "*" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\xD7"]
]
(Inline True)
colorNumber
(Tooltip "Multiply two numbers")
numDiv =
DesignBlock
"numDiv"
(Function "/" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\xF7"]
]
(Inline True)
colorNumber
(Tooltip "Divide two numbers")
numExp =
DesignBlock
"numExp"
(Function "^" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "^"]
]
(Inline True)
colorNumber
(Tooltip "Raise a number to a power")
numMax =
standardFunction
"numMax"
"max"
(Just "arrow-up.svg")
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The maximum of two numbers"
numMin =
standardFunction
"numMin"
"min"
(Just "arrow-down.svg")
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"Take the minimum of two numbers"
numOpposite =
standardFunction
"numOpposite"
"opposite"
(Just "minus-box.svg")
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The opposite of a number"
numAbs =
standardFunction
"numAbs"
"abs"
Nothing
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The absolute value of a number"
numRound =
standardFunction
"numRound"
"rounded"
Nothing
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The rounded value of a number"
numReciprocal =
standardFunction
"numReciprocal"
"reciprocal"
Nothing
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The reciprocal of a number"
numQuot =
standardFunction
"numQuot"
"quotient"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The integer part when dividing two numbers"
numRem =
standardFunction
"numRem"
"remainder"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The remainder when dividing two numbers"
numPi =
DesignBlock
"numPi"
(Function "pi" [typeNumber])
[ Dummy
[TextE "\x3C0"]
]
inlineDef
colorNumber
(Tooltip "The number pi, 3.1415..")
numSqrt =
DesignBlock
"numSqrt"
(Function "sqrt" [typeNumber, typeNumber])
[Value "NUM" [TextE "\x221A"], Dummy []]
(Inline True)
colorNumber
(Tooltip "Gives the square root of a number")
numGCD =
standardFunction
"numGCD"
"gcd"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The greatest common demonitator between two numbers"
numLCM =
standardFunction
"numLCM"
"lcm"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The least common multiple between two numbers"
numSin =
standardFunction
"numSin"
"sin"
Nothing
[typeNumber, typeNumber]
["VAL"]
colorNumber
"The sine of an angle"
numCos =
standardFunction
"numCos"
"cos"
Nothing
[typeNumber, typeNumber]
["VAL"]
colorNumber
"The cosine of an angle"
-- TEXT ------------------------------------------------
txtPrinted =
standardFunction
"txtPrinted"
"printed"
Nothing
[typeNumber, typeText]
["TEXT"]
colorText
"The text value of a number"
txtLowercase =
standardFunction
"txtLowercase"
"lowercase"
Nothing
[typeText, typeText]
["TEXT"]
colorText
"The text in lowercase"
txtUppercase =
standardFunction
"txtUppercase"
"uppercase"
Nothing
[typeText, typeText]
["TEXT"]
colorText
"The text in uppercase"
-- COLORS ----------------------------------------------
cwBlue = standardFunction "cwBlue" "blue" Nothing [typeColor] [] colorColor "The color blue"
cwRed = standardFunction "cwRed" "red" Nothing [typeColor] [] colorColor "The color red"
cwGreen = standardFunction "cwGreen" "green" Nothing [typeColor] [] colorColor "The color green"
cwOrange = standardFunction "cwOrange" "orange" Nothing [typeColor] [] colorColor "The color orange"
cwBrown = standardFunction "cwBrown" "brown" Nothing [typeColor] [] colorColor "The color brown"
cwBlack = standardFunction "cwBlack" "black" Nothing [typeColor] [] colorColor "The color black"
cwWhite = standardFunction "cwWhite" "white" Nothing [typeColor] [] colorColor "The color white"
cwCyan = standardFunction "cwCyan" "cyan" Nothing [typeColor] [] colorColor "The color cyan"
cwMagenta = standardFunction "cwMagenta" "magenta" Nothing [typeColor] [] colorColor "The color magenta"
cwYellow = standardFunction "cwYellow" "yellow" Nothing [typeColor] [] colorColor "The color yellow"
cwAquamarine = standardFunction "cwAquamarine" "aquamarine" Nothing [typeColor] [] colorColor "The color aquamarine"
cwAzure = standardFunction "cwAzure" "azure" Nothing [typeColor] [] colorColor "The color azure"
cwViolet = standardFunction "cwViolet" "violet" Nothing [typeColor] [] colorColor "The color violet"
cwChartreuse = standardFunction "cwChartreuse" "chartreuse" Nothing [typeColor] [] colorColor "The color chartreuse"
cwRose = standardFunction "cwRose" "rose" Nothing [typeColor] [] colorColor "The color rose"
cwPink = standardFunction "cwPink" "pink" Nothing [typeColor] [] colorColor "The color pink"
cwPurple = standardFunction "cwPurple" "purple" Nothing [typeColor] [] colorColor "The color purple"
cwGray = standardFunction "cwGray" "gray" Nothing [typeNumber] [] colorColor "The color gray"
cwMixed =
standardFunction
"cwMixed"
"mixed"
(Just "pot-mix.svg")
[List typeColor, typeColor]
["COL"]
colorColor
"Mix of a list of colors"
cwLight =
standardFunction
"cwLight"
"light"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A lighter color"
cwDark =
standardFunction
"cwDark"
"dark"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A darker color"
cwBright =
standardFunction
"cwBright"
"bright"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A brighter color"
cwDull =
standardFunction
"cwDull"
"dull"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A more dull color"
cwTranslucent =
standardFunction
"cwTranslucent"
"translucent"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A more translucent color"
cwRGB =
standardFunction
"cwRGB"
"RGB"
Nothing
[typeNumber, typeNumber, typeNumber, typeColor]
["RED", "GREEN", "BLUE"]
colorColor
"Makes a color with the given red, green, and blue portions"
cwRGBA =
standardFunction
"cwRGBA"
"RGBA"
Nothing
[typeNumber, typeNumber, typeNumber, typeNumber, typeColor]
["RED", "GREEN", "BLUE", "ALPHA"]
colorColor
"Makes a color with the given red, green, blue and alpha portions"
cwHSL =
standardFunction
"cwHSL"
"HSL"
Nothing
[typeNumber, typeNumber, typeNumber, typeColor]
["HUE", "SAT", "LUM"]
colorColor
"Makes a color with the given hue angle, saturation, and luminosity"
-- LOGIC -------------------------------------------
conIf =
DesignBlock
"conIf"
(Function "if" [typeBool, Poly "a", Poly "a", Poly "a"])
[ Value "IF" [TextE "if"],
Value "THEN" [Text "then"],
Value "ELSE" [Text "else"]
]
inlineDef
colorPoly
(Tooltip "if condition is true then give a else b")
conAnd =
DesignBlock
"conAnd"
(Function "&&" [typeBool, typeBool, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "and"]
]
(Inline True)
colorBool
(Tooltip "Logical AND operation")
conOr =
DesignBlock
"conOr"
(Function "||" [typeBool, typeBool, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "or"]
]
(Inline True)
colorBool
(Tooltip "Logical OR operation")
conNot =
standardFunction
"conNot"
"not"
Nothing
[typeBool, typeBool]
["VALUE"]
colorBool
"Negation of logical value"
conEq =
DesignBlock
"conEq"
(Function "==" [Poly "a", Poly "a", typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "="]
]
(Inline True)
colorBool
(Tooltip "Are two items equal")
conNeq =
DesignBlock
"conNeq"
(Function "/=" [Poly "a", Poly "a", typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\x2260"]
]
(Inline True)
colorBool
(Tooltip "Are two items not equal")
conTrue = standardFunction "conTrue" "True" Nothing [typeBool] [] colorBool "True logic value"
conFalse = standardFunction "conFalse" "False" Nothing [typeBool] [] colorBool "False logic value"
conGreater =
DesignBlock
"conGreater"
(Function ">" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE ">"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is greater than the other")
conGeq =
DesignBlock
"conGeq"
(Function ">=" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\x2265"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is greater than or equal to ther other")
conLess =
DesignBlock
"conLess"
(Function "<" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "<"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is less than the other")
conLeq =
DesignBlock
"conLeq"
(Function "<=" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\x2264"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is less than or equal to ther other")
conEven =
standardFunction
"conEven"
"even"
Nothing
[typeNumber, typeBool]
["VALUE"]
colorBool
"True if the number is even"
conOdd =
standardFunction
"conOdd"
"odd"
Nothing
[typeNumber, typeBool]
["VALUE"]
colorBool
"True if the number is odd"
conStartWith =
standardFunction
"conStartWith"
"startsWith"
Nothing
[typeText, typeText, typeBool]
["TEXTMAIN", "TEXTTEST"]
colorBool
"Test whether the text starts with the characters of the other text"
conEndWith =
standardFunction
"conEndWith"
"endsWith"
Nothing
[typeText, typeText, typeBool]
["TEXTMAIN", "TEXTTEST"]
colorBool
"Test whether the text ends with the characters of the other text"
-- LISTS ----------------------------------------------
lstGenNum =
DesignBlock
"lstGenNum"
(Function ".." [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [Text "["],
Value "RIGHT" [TextE ".."],
Dummy [Text "]"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is greater than the other")
comment =
DesignBlock
"comment"
None
[Dummy [TextInput "" "TEXT", TextE "--"]]
inlineDef
(Color 260)
(Tooltip "Enter a comment")
getTypeBlocks :: [T.Text]
getTypeBlocks = map (\(DesignBlock name _ _ _ _ _) -> name) blockTypes
blockTypes =
[ -- PICTURE
cwBlank,
cwCoordinatePlane,
cwCodeWorldLogo,
cwLettering,
cwDrawingOf,
cwCircle,
cwThickCircle,
cwSolidCircle,
cwRectangle,
cwThickRectangle,
cwSolidRectangle,
cwArc,
cwSector,
cwThickArc,
TRANSFORMATIONS
cwColored,
cwTranslate,
cwRotate,
cwScale,
-- NUMBERS
,
numAdd,
numSub,
numMult,
numDiv,
numExp,
numMax,
numMin,
numOpposite,
numAbs,
numRound,
numReciprocal,
numQuot,
numRem,
numPi,
numSqrt,
numGCD,
numLCM,
numSin,
numCos,
-- TEXT
txtPrinted,
txtLowercase,
txtUppercase,
-- COLORS
cwBlue,
cwRed,
cwGreen,
cwBrown,
cwOrange,
cwBlack,
cwWhite,
cwCyan,
cwMagenta,
cwYellow,
cwAquamarine,
cwAzure,
cwViolet,
cwChartreuse,
cwRose,
cwPink,
cwPurple,
cwGray,
cwMixed,
cwLight,
cwDark,
cwBright,
cwDull,
cwTranslucent,
cwRGBA,
cwRGB,
cwHSL,
-- LOGIC
-- ,conIf
conAnd,
conOr,
conNot,
conEq,
conNeq,
conTrue,
conFalse,
conGreater,
conGeq,
conLess,
conLeq,
conEven,
conOdd,
conStartWith,
conEndWith,
comment
]
Assigns CodeGen functions defined here to the Blockly Javascript Code
-- generator
setBlockTypes :: IO ()
setBlockTypes = mapM_ setBlockType blockTypes
| null | https://raw.githubusercontent.com/google/codeworld/77b0863075be12e3bc5f182a53fcc38b038c3e16/funblocks-client/src/Blocks/Types.hs | haskell | # LANGUAGE OverloadedStrings #
PICTURE ----------------------------------------------
Transformations -----------------------------------------------
NUMBERS ---------------------------------------------
TEXT ------------------------------------------------
COLORS ----------------------------------------------
LOGIC -------------------------------------------
LISTS ----------------------------------------------
PICTURE
NUMBERS
TEXT
COLORS
LOGIC
,conIf
generator |
Copyright 2020 The CodeWorld Authors . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2020 The CodeWorld Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Blocks.Types (setBlockTypes, getTypeBlocks) where
import Blockly.DesignBlock
import Blockly.Event
import Blockly.General
import Data.List (intersperse)
import qualified Data.Text as T
colorPicture = Color 160
colorNumber = Color 210
colorProgram = Color 0
colorColor = Color 290
colorPoly = Color 180
colorBool = Color 100
colorText = Color 45
typePicture = Picture
typeNumber = Number
typeProgram = Program
typeColor = Col
typeBool = Truth
typeText = Str
typeComment = Comment
inlineDef = Inline True
icon :: T.Text -> Field
icon name = FieldImage ("ims/" `T.append` name) 20 20
standardFunction cwName funcName ico types [] color tooltip =
DesignBlock cwName (Function funcName types) [header] inlineDef color (Tooltip tooltip)
where
header = case ico of
Just i -> Dummy [TextE funcName, icon i]
Nothing -> Dummy [TextE funcName]
standardFunction cwName funcName ico types inputNames color tooltip =
DesignBlock
cwName
(Function funcName types)
(header : (argInputs ++ [Dummy [Text ")"]]))
inlineDef
color
(Tooltip tooltip)
where
header = case ico of
Just i -> Value (head inputNames) [Text "(", TextE funcName, icon i]
Nothing -> Value (head inputNames) [Text "(", TextE funcName]
argInputs = map (\name -> Value name [Text ","]) (tail inputNames)
cwBlank = standardFunction "cwBlank" "blank" Nothing [Picture] [] colorPicture "Blank picture"
cwCoordinatePlane = standardFunction "cwCoordinatePlane" "coordinatePlane" Nothing [Picture] [] colorPicture "Picture of coordinate plane"
cwCodeWorldLogo = standardFunction "cwCodeWorldLogo" "codeWorldLogo" Nothing [Picture] [] colorPicture "Picture of CodeWorld logo"
cwLettering =
standardFunction
"cwLettering"
"lettering"
Nothing
[typeText, Picture]
["TEXT"]
colorPicture
"Picture of text"
cwDrawingOf =
DesignBlock
"cwDrawingOf"
(Top "drawingOf" [typePicture, typeProgram])
[Value "VALUE" [Text "(", TextE "drawingOf", icon "shape-plus.svg"], Dummy [Text ")"]]
inlineDef
colorProgram
(Tooltip "Displays a drawing of a picture")
cwCircle = standardFunction "cwCircle" "circle" Nothing [typeNumber, typePicture] ["RADIUS"] colorPicture "Picture of a circle"
cwThickCircle =
standardFunction
"cwThickCircle"
"thickCircle"
Nothing
[typeNumber, typeNumber, typePicture]
["RADIUS", "LINEWIDTH"]
colorPicture
"Picture of a circle with a border"
cwSolidCircle =
standardFunction
"cwSolidCircle"
"solidCircle"
Nothing
[typeNumber, typePicture]
["RADIUS"]
colorPicture
"Picture of a solid circle"
cwRectangle =
standardFunction
"cwRectangle"
"rectangle"
Nothing
[typeNumber, typeNumber, typePicture]
["WIDTH", "HEIGHT"]
colorPicture
"Picture of a rectangle"
cwThickRectangle =
standardFunction
"cwThickRectangle"
"thickRectangle"
Nothing
[typeNumber, typeNumber, typeNumber, typePicture]
["WIDTH", "HEIGHT", "LINEWIDTH"]
colorPicture
"Picture of a rectangle with a border"
cwSolidRectangle =
standardFunction
"cwSolidRectangle"
"solidRectangle"
Nothing
[typeNumber, typeNumber, typePicture]
["WIDTH", "HEIGHT"]
colorPicture
"Picture of a solid rectangle"
cwArc =
standardFunction
"cwArc"
"arc"
Nothing
[typeNumber, typeNumber, typeNumber, typePicture]
["STARTANGLE", "ENDANGLE", "RADIUS"]
colorPicture
"A thin arc"
cwSector =
standardFunction
"cwSector"
"sector"
Nothing
[typeNumber, typeNumber, typeNumber, typePicture]
["STARTANGLE", "ENDANGLE", "RADIUS"]
colorPicture
"A solid sector of a circle"
cwThickArc =
standardFunction
"cwThickArc"
"thickArc"
Nothing
[typeNumber, typeNumber, typeNumber, typeNumber, typePicture]
["STARTANGLE", "ENDANGLE", "RADIUS", "LINEWIDTH"]
colorPicture
"An arc with variable line width"
cwColored =
standardFunction
"cwColored"
"colored"
(Just "format-color-fill.svg")
[typePicture, typeColor, typePicture]
["PICTURE", "COLOR"]
colorPicture
"A colored picture"
cwTranslate =
standardFunction
"cwTranslate"
"translated"
(Just "cursor-move.svg")
[typePicture, typeNumber, typeNumber, typePicture]
["PICTURE", "X", "Y"]
colorPicture
"A translated picture"
cwScale =
standardFunction
"cwScale"
"scaled"
(Just "move-resize-variant.svg")
[typePicture, typeNumber, typeNumber, typePicture]
["PICTURE", "HORZ", "VERTZ"]
colorPicture
"A scaled picture"
cwRotate =
standardFunction
"cwRotate"
"rotated"
(Just "rotate-3d.svg")
[typePicture, typeNumber, typePicture]
["PICTURE", "ANGLE"]
colorPicture
"A rotated picture"
numAdd =
DesignBlock
"numAdd"
(Function "+" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "+"]
]
(Inline True)
colorNumber
(Tooltip "Add two numbers")
numSub =
DesignBlock
"numSub"
(Function "-" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "-"]
]
(Inline True)
colorNumber
(Tooltip "Subtract two numbers")
numMult =
DesignBlock
"numMult"
(Function "*" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\xD7"]
]
(Inline True)
colorNumber
(Tooltip "Multiply two numbers")
numDiv =
DesignBlock
"numDiv"
(Function "/" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\xF7"]
]
(Inline True)
colorNumber
(Tooltip "Divide two numbers")
numExp =
DesignBlock
"numExp"
(Function "^" [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [],
Value "RIGHT" [TextE "^"]
]
(Inline True)
colorNumber
(Tooltip "Raise a number to a power")
numMax =
standardFunction
"numMax"
"max"
(Just "arrow-up.svg")
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The maximum of two numbers"
numMin =
standardFunction
"numMin"
"min"
(Just "arrow-down.svg")
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"Take the minimum of two numbers"
numOpposite =
standardFunction
"numOpposite"
"opposite"
(Just "minus-box.svg")
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The opposite of a number"
numAbs =
standardFunction
"numAbs"
"abs"
Nothing
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The absolute value of a number"
numRound =
standardFunction
"numRound"
"rounded"
Nothing
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The rounded value of a number"
numReciprocal =
standardFunction
"numReciprocal"
"reciprocal"
Nothing
[typeNumber, typeNumber]
["NUM"]
colorNumber
"The reciprocal of a number"
numQuot =
standardFunction
"numQuot"
"quotient"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The integer part when dividing two numbers"
numRem =
standardFunction
"numRem"
"remainder"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The remainder when dividing two numbers"
numPi =
DesignBlock
"numPi"
(Function "pi" [typeNumber])
[ Dummy
[TextE "\x3C0"]
]
inlineDef
colorNumber
(Tooltip "The number pi, 3.1415..")
numSqrt =
DesignBlock
"numSqrt"
(Function "sqrt" [typeNumber, typeNumber])
[Value "NUM" [TextE "\x221A"], Dummy []]
(Inline True)
colorNumber
(Tooltip "Gives the square root of a number")
numGCD =
standardFunction
"numGCD"
"gcd"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The greatest common demonitator between two numbers"
numLCM =
standardFunction
"numLCM"
"lcm"
Nothing
[typeNumber, typeNumber, typeNumber]
["LEFT", "RIGHT"]
colorNumber
"The least common multiple between two numbers"
numSin =
standardFunction
"numSin"
"sin"
Nothing
[typeNumber, typeNumber]
["VAL"]
colorNumber
"The sine of an angle"
numCos =
standardFunction
"numCos"
"cos"
Nothing
[typeNumber, typeNumber]
["VAL"]
colorNumber
"The cosine of an angle"
txtPrinted =
standardFunction
"txtPrinted"
"printed"
Nothing
[typeNumber, typeText]
["TEXT"]
colorText
"The text value of a number"
txtLowercase =
standardFunction
"txtLowercase"
"lowercase"
Nothing
[typeText, typeText]
["TEXT"]
colorText
"The text in lowercase"
txtUppercase =
standardFunction
"txtUppercase"
"uppercase"
Nothing
[typeText, typeText]
["TEXT"]
colorText
"The text in uppercase"
cwBlue = standardFunction "cwBlue" "blue" Nothing [typeColor] [] colorColor "The color blue"
cwRed = standardFunction "cwRed" "red" Nothing [typeColor] [] colorColor "The color red"
cwGreen = standardFunction "cwGreen" "green" Nothing [typeColor] [] colorColor "The color green"
cwOrange = standardFunction "cwOrange" "orange" Nothing [typeColor] [] colorColor "The color orange"
cwBrown = standardFunction "cwBrown" "brown" Nothing [typeColor] [] colorColor "The color brown"
cwBlack = standardFunction "cwBlack" "black" Nothing [typeColor] [] colorColor "The color black"
cwWhite = standardFunction "cwWhite" "white" Nothing [typeColor] [] colorColor "The color white"
cwCyan = standardFunction "cwCyan" "cyan" Nothing [typeColor] [] colorColor "The color cyan"
cwMagenta = standardFunction "cwMagenta" "magenta" Nothing [typeColor] [] colorColor "The color magenta"
cwYellow = standardFunction "cwYellow" "yellow" Nothing [typeColor] [] colorColor "The color yellow"
cwAquamarine = standardFunction "cwAquamarine" "aquamarine" Nothing [typeColor] [] colorColor "The color aquamarine"
cwAzure = standardFunction "cwAzure" "azure" Nothing [typeColor] [] colorColor "The color azure"
cwViolet = standardFunction "cwViolet" "violet" Nothing [typeColor] [] colorColor "The color violet"
cwChartreuse = standardFunction "cwChartreuse" "chartreuse" Nothing [typeColor] [] colorColor "The color chartreuse"
cwRose = standardFunction "cwRose" "rose" Nothing [typeColor] [] colorColor "The color rose"
cwPink = standardFunction "cwPink" "pink" Nothing [typeColor] [] colorColor "The color pink"
cwPurple = standardFunction "cwPurple" "purple" Nothing [typeColor] [] colorColor "The color purple"
cwGray = standardFunction "cwGray" "gray" Nothing [typeNumber] [] colorColor "The color gray"
cwMixed =
standardFunction
"cwMixed"
"mixed"
(Just "pot-mix.svg")
[List typeColor, typeColor]
["COL"]
colorColor
"Mix of a list of colors"
cwLight =
standardFunction
"cwLight"
"light"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A lighter color"
cwDark =
standardFunction
"cwDark"
"dark"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A darker color"
cwBright =
standardFunction
"cwBright"
"bright"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A brighter color"
cwDull =
standardFunction
"cwDull"
"dull"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A more dull color"
cwTranslucent =
standardFunction
"cwTranslucent"
"translucent"
Nothing
[typeColor, typeColor]
["COL"]
colorColor
"A more translucent color"
cwRGB =
standardFunction
"cwRGB"
"RGB"
Nothing
[typeNumber, typeNumber, typeNumber, typeColor]
["RED", "GREEN", "BLUE"]
colorColor
"Makes a color with the given red, green, and blue portions"
cwRGBA =
standardFunction
"cwRGBA"
"RGBA"
Nothing
[typeNumber, typeNumber, typeNumber, typeNumber, typeColor]
["RED", "GREEN", "BLUE", "ALPHA"]
colorColor
"Makes a color with the given red, green, blue and alpha portions"
cwHSL =
standardFunction
"cwHSL"
"HSL"
Nothing
[typeNumber, typeNumber, typeNumber, typeColor]
["HUE", "SAT", "LUM"]
colorColor
"Makes a color with the given hue angle, saturation, and luminosity"
conIf =
DesignBlock
"conIf"
(Function "if" [typeBool, Poly "a", Poly "a", Poly "a"])
[ Value "IF" [TextE "if"],
Value "THEN" [Text "then"],
Value "ELSE" [Text "else"]
]
inlineDef
colorPoly
(Tooltip "if condition is true then give a else b")
conAnd =
DesignBlock
"conAnd"
(Function "&&" [typeBool, typeBool, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "and"]
]
(Inline True)
colorBool
(Tooltip "Logical AND operation")
conOr =
DesignBlock
"conOr"
(Function "||" [typeBool, typeBool, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "or"]
]
(Inline True)
colorBool
(Tooltip "Logical OR operation")
conNot =
standardFunction
"conNot"
"not"
Nothing
[typeBool, typeBool]
["VALUE"]
colorBool
"Negation of logical value"
conEq =
DesignBlock
"conEq"
(Function "==" [Poly "a", Poly "a", typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "="]
]
(Inline True)
colorBool
(Tooltip "Are two items equal")
conNeq =
DesignBlock
"conNeq"
(Function "/=" [Poly "a", Poly "a", typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\x2260"]
]
(Inline True)
colorBool
(Tooltip "Are two items not equal")
conTrue = standardFunction "conTrue" "True" Nothing [typeBool] [] colorBool "True logic value"
conFalse = standardFunction "conFalse" "False" Nothing [typeBool] [] colorBool "False logic value"
conGreater =
DesignBlock
"conGreater"
(Function ">" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE ">"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is greater than the other")
conGeq =
DesignBlock
"conGeq"
(Function ">=" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\x2265"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is greater than or equal to ther other")
conLess =
DesignBlock
"conLess"
(Function "<" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "<"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is less than the other")
conLeq =
DesignBlock
"conLeq"
(Function "<=" [typeNumber, typeNumber, typeBool])
[ Value "LEFT" [],
Value "RIGHT" [TextE "\x2264"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is less than or equal to ther other")
conEven =
standardFunction
"conEven"
"even"
Nothing
[typeNumber, typeBool]
["VALUE"]
colorBool
"True if the number is even"
conOdd =
standardFunction
"conOdd"
"odd"
Nothing
[typeNumber, typeBool]
["VALUE"]
colorBool
"True if the number is odd"
conStartWith =
standardFunction
"conStartWith"
"startsWith"
Nothing
[typeText, typeText, typeBool]
["TEXTMAIN", "TEXTTEST"]
colorBool
"Test whether the text starts with the characters of the other text"
conEndWith =
standardFunction
"conEndWith"
"endsWith"
Nothing
[typeText, typeText, typeBool]
["TEXTMAIN", "TEXTTEST"]
colorBool
"Test whether the text ends with the characters of the other text"
lstGenNum =
DesignBlock
"lstGenNum"
(Function ".." [typeNumber, typeNumber, typeNumber])
[ Value "LEFT" [Text "["],
Value "RIGHT" [TextE ".."],
Dummy [Text "]"]
]
(Inline True)
colorBool
(Tooltip "Tells whether one number is greater than the other")
comment =
DesignBlock
"comment"
None
[Dummy [TextInput "" "TEXT", TextE "--"]]
inlineDef
(Color 260)
(Tooltip "Enter a comment")
getTypeBlocks :: [T.Text]
getTypeBlocks = map (\(DesignBlock name _ _ _ _ _) -> name) blockTypes
blockTypes =
cwBlank,
cwCoordinatePlane,
cwCodeWorldLogo,
cwLettering,
cwDrawingOf,
cwCircle,
cwThickCircle,
cwSolidCircle,
cwRectangle,
cwThickRectangle,
cwSolidRectangle,
cwArc,
cwSector,
cwThickArc,
TRANSFORMATIONS
cwColored,
cwTranslate,
cwRotate,
cwScale,
,
numAdd,
numSub,
numMult,
numDiv,
numExp,
numMax,
numMin,
numOpposite,
numAbs,
numRound,
numReciprocal,
numQuot,
numRem,
numPi,
numSqrt,
numGCD,
numLCM,
numSin,
numCos,
txtPrinted,
txtLowercase,
txtUppercase,
cwBlue,
cwRed,
cwGreen,
cwBrown,
cwOrange,
cwBlack,
cwWhite,
cwCyan,
cwMagenta,
cwYellow,
cwAquamarine,
cwAzure,
cwViolet,
cwChartreuse,
cwRose,
cwPink,
cwPurple,
cwGray,
cwMixed,
cwLight,
cwDark,
cwBright,
cwDull,
cwTranslucent,
cwRGBA,
cwRGB,
cwHSL,
conAnd,
conOr,
conNot,
conEq,
conNeq,
conTrue,
conFalse,
conGreater,
conGeq,
conLess,
conLeq,
conEven,
conOdd,
conStartWith,
conEndWith,
comment
]
Assigns CodeGen functions defined here to the Blockly Javascript Code
setBlockTypes :: IO ()
setBlockTypes = mapM_ setBlockType blockTypes
|
cf008f360284bdc94d8481a7f03707613f9497f47370cdc2460bd705ea920234 | mario-goulart/fu | command-line.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Command line argument handling for R7RS Scheme.
;;;
See README and for more information .
;;;
This software is written by < > and
;;; placed in the Public Domain. All warranties are disclaimed.
;;;
;;
;; `match-option` matches a single option specification against a list
;; of command line arguments.
;;
;; If the given `arguments` don't match the `specification`, an error is
;; signaled. Otherwise, the matching items in `arguments` are collected
;; into an association pair and the continuation `continue` is called
;; with the list of remaining items and resulting pair as arguments.
;;
;; This procedure is internal to command-line.sld.
;;
(define (match-option specification arguments continue)
(let lp ((spec (cdr specification))
(args (cdr arguments))
(cont (lambda (args vals)
(continue args (cons (car specification) vals)))))
(cond ((null? spec)
(cont args (list)))
((null? args)
(error "Insufficient arguments for command line option"
(car specification)))
((string=? "--" (car args))
(error "Invalid value for command line option"
(car specification)))
((pair? spec)
(if (pair? (car spec)) ; Nested option specs aren't supported.
(error "Invalid command line option specification" specification)
(lp (car spec)
(list (car args))
(lambda (_ head)
(lp (cdr spec)
(cdr args)
(lambda (args tail)
(cont args (cons head tail))))))))
((procedure? spec)
(cont (cdr args) (spec (car args))))
(else
(cont (cdr args) (car args))))))
;;
;; `normalize-grammar` compiles an options grammar into a standardized
;; format. Currently, this means splitting any option specifications
;; whose `car` is a list into multiple entries, allowing the following
;; abbreviated syntax for option aliases:
;;
( normalize - grammar ' ( ( ( --foo --bar --baz ) . qux ) ) )
; = > ( ( --foo . qux )
( --bar . qux )
;; (--baz . qux))
;;
;; This procedure is internal to command-line.sld.
;;
(define normalize-grammar
(letrec ((fold (lambda (f a l)
(if (pair? l) (fold f (f a (car l)) (cdr l)) a))))
(lambda (grammar)
(fold (lambda (a g)
(if (pair? g)
(let ((n (car g))
(s (cdr g)))
(if (list? n)
(append (map (lambda (k) (cons k s)) n) a)
(cons g a)))
(error "Invalid command line option specification" g)))
'()
(reverse grammar)))))
;;
;; `parse-command-line` parses a program's command line arguments into
;; an association list according to an S-expressive options grammar.
;;
It takes one required and two optional arguments : an option matching
;; procedure, an S-expressive options `grammar`, and a list of command
;; line argument strings. If `matcher` is not given a basic string
;; comparison is used, while `arguments` defaults to the value of `(cdr
;; (command-line))`.
;;
;; `grammar` is a finite list of pairs whose `car`s are symbols and
whose ` cdr`s are pairs or atoms . All other ` car`s in the grammar must
;; be atoms; grammars may not be nested.
;;
;; The given `arguments` are matched as symbols against the `car`s of
;; the options grammar. When a match is found, an association from the
;; matched symbol to the arguments immediately following the matched
;; item in the arguments list is added, following the form of the
;; matched pair.
;;
;; (parse-command-line
;; '("foo" "bar")
;; '((foo . bar))) ; => ((foo . "bar")
;; (--))
;;
;; (parse-command-line
;; '("foo" "bar" "baz" "qux")
;; '((foo)
;; (bar baz qux))) ; => ((foo)
;; (bar "baz" "qux")
;; (--))
;;
;; Unmatched arguments are added to the resulting association list under
;; the key `--`. Similarly, any arguments following a `"--"` in the
;; arguments list are treated as unmatched.
;;
;; (parse-command-line
;; '("foo" "bar" "baz")
;; '((foo . bar))) ; => ((foo . "bar")
;; (-- "baz"))
;;
;; (parse-command-line
;; '("foo" "bar" "--" "baz" "qux")
;; '((foo . bar)
( baz . qux ) ) ) ; = > ( ( foo . " bar " )
;; (-- "baz" "qux"))
;;
;; In a matched options form, procedures are replaced by the result of
;; invoking that procedure on the corresponding item in the arguments
;; list. All other objects are replaced by the corresponding argument
;; string directly.
;;
;; (parse-command-line
' ( " foo " " bar " " 42 " " qux " )
;; `((foo ,list ,string->number ,string->symbol)))
; = > ( ( foo ( " bar " ) 42 qux )
;; (--))
;;
(define parse-command-line
(case-lambda
((grammar)
(parse-command-line (lambda _ #f) (cdr (command-line)) grammar))
((arguments grammar)
(parse-command-line (lambda _ #f) arguments grammar))
((matcher arguments grammar)
(let ((grammar (normalize-grammar grammar)))
(let lp ((args arguments)
(unmatched (list))
(matched (list)))
(if (null? args)
(reverse (cons (cons '-- (reverse unmatched)) matched))
(let ((arg (car args))
(cont (lambda (args vals)
(lp args unmatched (cons vals matched)))))
(cond ;; Simple match.
((assq (string->symbol arg) grammar) =>
(lambda (spec)
(match-option spec args cont)))
;; Custom match (via `matcher` procedure).
((matcher arg grammar) =>
(lambda (handler)
(handler args (lambda (spec args)
(match-option spec args cont)))))
;; Treat all arguments following "--" as unmatched.
((string=? "--" arg)
(lp (list) (append (reverse (cdr args)) unmatched) matched))
;; An unmatched argument.
(else
(lp (cdr args) (cons arg unmatched) matched))))))))))
| null | https://raw.githubusercontent.com/mario-goulart/fu/a04e716a9753642fee67c55738876db8858d7b61/command-line.scm | scheme |
Command line argument handling for R7RS Scheme.
placed in the Public Domain. All warranties are disclaimed.
`match-option` matches a single option specification against a list
of command line arguments.
If the given `arguments` don't match the `specification`, an error is
signaled. Otherwise, the matching items in `arguments` are collected
into an association pair and the continuation `continue` is called
with the list of remaining items and resulting pair as arguments.
This procedure is internal to command-line.sld.
Nested option specs aren't supported.
`normalize-grammar` compiles an options grammar into a standardized
format. Currently, this means splitting any option specifications
whose `car` is a list into multiple entries, allowing the following
abbreviated syntax for option aliases:
= > ( ( --foo . qux )
(--baz . qux))
This procedure is internal to command-line.sld.
`parse-command-line` parses a program's command line arguments into
an association list according to an S-expressive options grammar.
procedure, an S-expressive options `grammar`, and a list of command
line argument strings. If `matcher` is not given a basic string
comparison is used, while `arguments` defaults to the value of `(cdr
(command-line))`.
`grammar` is a finite list of pairs whose `car`s are symbols and
be atoms; grammars may not be nested.
The given `arguments` are matched as symbols against the `car`s of
the options grammar. When a match is found, an association from the
matched symbol to the arguments immediately following the matched
item in the arguments list is added, following the form of the
matched pair.
(parse-command-line
'("foo" "bar")
'((foo . bar))) ; => ((foo . "bar")
(--))
(parse-command-line
'("foo" "bar" "baz" "qux")
'((foo)
(bar baz qux))) ; => ((foo)
(bar "baz" "qux")
(--))
Unmatched arguments are added to the resulting association list under
the key `--`. Similarly, any arguments following a `"--"` in the
arguments list are treated as unmatched.
(parse-command-line
'("foo" "bar" "baz")
'((foo . bar))) ; => ((foo . "bar")
(-- "baz"))
(parse-command-line
'("foo" "bar" "--" "baz" "qux")
'((foo . bar)
= > ( ( foo . " bar " )
(-- "baz" "qux"))
In a matched options form, procedures are replaced by the result of
invoking that procedure on the corresponding item in the arguments
list. All other objects are replaced by the corresponding argument
string directly.
(parse-command-line
`((foo ,list ,string->number ,string->symbol)))
= > ( ( foo ( " bar " ) 42 qux )
(--))
Simple match.
Custom match (via `matcher` procedure).
Treat all arguments following "--" as unmatched.
An unmatched argument. | See README and for more information .
This software is written by < > and
(define (match-option specification arguments continue)
(let lp ((spec (cdr specification))
(args (cdr arguments))
(cont (lambda (args vals)
(continue args (cons (car specification) vals)))))
(cond ((null? spec)
(cont args (list)))
((null? args)
(error "Insufficient arguments for command line option"
(car specification)))
((string=? "--" (car args))
(error "Invalid value for command line option"
(car specification)))
((pair? spec)
(error "Invalid command line option specification" specification)
(lp (car spec)
(list (car args))
(lambda (_ head)
(lp (cdr spec)
(cdr args)
(lambda (args tail)
(cont args (cons head tail))))))))
((procedure? spec)
(cont (cdr args) (spec (car args))))
(else
(cont (cdr args) (car args))))))
( normalize - grammar ' ( ( ( --foo --bar --baz ) . qux ) ) )
( --bar . qux )
(define normalize-grammar
(letrec ((fold (lambda (f a l)
(if (pair? l) (fold f (f a (car l)) (cdr l)) a))))
(lambda (grammar)
(fold (lambda (a g)
(if (pair? g)
(let ((n (car g))
(s (cdr g)))
(if (list? n)
(append (map (lambda (k) (cons k s)) n) a)
(cons g a)))
(error "Invalid command line option specification" g)))
'()
(reverse grammar)))))
It takes one required and two optional arguments : an option matching
whose ` cdr`s are pairs or atoms . All other ` car`s in the grammar must
' ( " foo " " bar " " 42 " " qux " )
(define parse-command-line
(case-lambda
((grammar)
(parse-command-line (lambda _ #f) (cdr (command-line)) grammar))
((arguments grammar)
(parse-command-line (lambda _ #f) arguments grammar))
((matcher arguments grammar)
(let ((grammar (normalize-grammar grammar)))
(let lp ((args arguments)
(unmatched (list))
(matched (list)))
(if (null? args)
(reverse (cons (cons '-- (reverse unmatched)) matched))
(let ((arg (car args))
(cont (lambda (args vals)
(lp args unmatched (cons vals matched)))))
((assq (string->symbol arg) grammar) =>
(lambda (spec)
(match-option spec args cont)))
((matcher arg grammar) =>
(lambda (handler)
(handler args (lambda (spec args)
(match-option spec args cont)))))
((string=? "--" arg)
(lp (list) (append (reverse (cdr args)) unmatched) matched))
(else
(lp (cdr args) (cons arg unmatched) matched))))))))))
|
aab2f576538c4a6672188843537a288da145fb6a055ec24d690c92dca9cf93d5 | david-vanderson/warp | server.rkt | #lang racket/base
(require racket/tcp
racket/async-channel)
(require "defs.rkt"
"utils.rkt"
"change.rkt"
"physics.rkt"
"quadtree.rkt"
"ships.rkt"
"pilot.rkt"
"warp.rkt"
"plasma.rkt"
"explosion.rkt"
"pbolt.rkt"
"missile.rkt"
"cannon.rkt"
"shield.rkt"
"scenario.rkt"
"upgrade.rkt")
(provide start-server)
; client connected, we are waiting for their player name
(define CLIENT_STATUS_NEW 0)
; client needs whole ownspace, don't send any updates until then
; - changing the scenario puts everybody here
(define CLIENT_STATUS_WAITING_FOR_SPACE 1)
; normal operation, send updates
(define CLIENT_STATUS_OK 2)
(struct client (status player in-port out-port in-t out-t) #:mutable #:prefab)
(define (client-id c) (ob-id (client-player c)))
(define server-listener #f)
(define clients '())
(define ownspace #f)
(define (scenario-on-tick change-scenario!) '())
(define (scenario-on-message cmd change-scenario!) '())
(define scenario-on-player-restart #f)
; debugging
(define spacebox #f)
; called once on every object
; return a list of changes
(define (upkeep! space o)
(define changes '())
(cond
((and (ship? o)
(warping? o)
(outside? space o))
; stop warp for any ships that hit the edge of space
(append! changes (command (ob-id o) #f 'warp 'stop)))
((probe? o)
(define t (ship-tool o 'endrc))
(when (and t
(tool-rc t)
((tool-rc t) . <= . (/ (obj-age space o) 1000.0)))
(define player (findf (lambda (x) (equal? (player-rcid x) (ob-id o)))
(space-players space)))
(append! changes (endrc (and player (ob-id player)) (ob-id o)))))
((cannonball? o)
(when ((obj-age space o) . > . 30000.0)
(append! changes (chdam (ob-id o) (ship-maxcon o) #f))))
((missile? o)
(define t (ship-tool o 'endrc))
(when ((tool-rc t) . <= . (/ (obj-age space o) 1000.0))
(append! changes (chdam (ob-id o) (ship-maxcon o) #f)))))
changes)
; return a list of already applied updates
(define (run-ai! space qt)
(define updates '())
(define stacks (search space space ai-ship? #t))
(define delay 0)
if we have n't seen this ship before , set ai runtime to 0
(for ((s (in-list stacks)))
(define changes '())
(define ship (car s))
(when (and (obj-alive? ship)
((- (space-time space) (ship-ai-time ship)) . > . (ship-ai-freq ship)))
(set-ship-ai-time! ship (+ (space-time space) delay)) ; set runtime
push ais away from running in the same tick
( printf " running ai for ship ~a\n " ( ship - name ship ) )
; run this ship's ai
(when (and (ship-tool ship 'engine)
(ship-tool ship 'steer))
(when (not (missile? ship))
(append! changes (pilot-ai-strategy! space qt s)))
(when (and (ship-flying? ship)
(or (missile? ship)
(ship-strategy ship)))
(append! changes (pilot-ai-fly! space qt s))))
(when (ship-tool ship 'pbolt)
(append! changes (pbolt-ai! qt s)))
(when (ship-tool ship 'cannon)
(append! changes (cannon-ai! qt s)))
(when (cannonball? ship)
(append! changes (cannonball-ai! qt s)))
(when (ship-tool ship 'missile)
(append! changes (missile-ai! space qt s)))
)
; if the ai does something that adds to space-objects (like launching)
then add those to the quadtree so later ais see it
(define (addf o)
(add-to-qt! ownspace qt o))
(append! updates (apply-all-changes! ownspace changes "server" #:addf addf)))
;(printf "ran ~a ai\n" (/ delay TICK))
updates)
(define updates '())
(define (remove-client cid)
(define c (findf (lambda (o) (= cid (client-id o))) clients))
(when c
(define name (player-name (client-player c)))
(printf "server (~a) removing client ~a ~a\n" (length clients) (client-id c) name)
(define m (make-message ownspace (format "Player Left: ~a" name)))
(append! updates
(apply-all-changes! ownspace
(list (chrm (client-id c)) m)
"server"))
(close-input-port (client-in-port c))
(with-handlers ((exn:fail:network? (lambda (exn) #f)))
(close-output-port (client-out-port c)))
(kill-thread (client-in-t c))
(kill-thread (client-out-t c))
(set! clients (remove c clients))))
for debugging to artificially introduce lag from server->client
;(define delay-ch (make-async-channel))
;(thread
; (lambda ()
( define delay 250.0 )
; (define count 0)
; (let loop ()
; (define vs (async-channel-get delay-ch))
; (define d (- delay (- (current-milliseconds) (car vs))))
; ;(printf "delaying ~a\n" d)
; (when (d . > . 0)
( sleep ( / d 1000.0 ) ) )
( thread - send ( cadr vs ) ( caddr vs ) )
( set ! count ( + 1 count ) )
# ; ( when (= 0 ( modulo count 600 ) )
( if ( equal ? 0.0 delay )
( set ! delay 400.0 )
( set ! delay 0.0 ) )
( printf " delay set to ~a\n " delay ) )
; (loop))))
(define (send-to-client c v)
(thread-send (client-out-t c) v)
;(async-channel-put delay-ch (list (current-milliseconds) (client-out-t c) v))
)
(define previous-physics-time #f)
(define (server-loop)
(define time-tick 0)
(define time-commands 0)
(define time-effects 0)
(define time-hook 0)
(define time-ai 0)
(define time-output 0)
(define current-time (current-milliseconds))
(when (not previous-physics-time)
(set! previous-physics-time current-time))
; process new clients
(when (tcp-accept-ready? server-listener)
(define-values (in out) (tcp-accept server-listener))
(when (and in out)
(set-tcp-nodelay! out #t)
(define cid (next-id))
(define c (client CLIENT_STATUS_NEW
; send version in the player name field
(player cid VERSION #f 0 '() #f #f)
in out
(make-in-thread cid in (current-thread))
(make-out-thread cid out (current-thread))))
(printf "server (~a) accepting new client ~a\n" (length clients) cid)
(send-to-client c (serialize (client-player c))) ; assign an id
(prepend! clients c))
)
; simulation tick
(define tick? #t)
(when ((- current-time previous-physics-time) . < . TICK)
;(printf "server woke up too early, no tick\n")
(set! tick? #f))
(when tick?
(define qt #f)
; physics
(timeit time-tick
(set! previous-physics-time (+ previous-physics-time TICK))
(define-values (qt2 updates2)
(tick-space! ownspace apply-all-changes!))
(set! qt qt2)
(append! updates updates2)
)
(define (addf o)
(add-to-qt! ownspace qt o))
; process player commands
(timeit time-commands
(let loop ()
(define v (thread-try-receive))
(when v
(define cid (car v))
(define u (cdr v))
(cond
((not u)
(remove-client cid))
((and (update? u)
(not (null? (update-changes u)))
(player? (car (update-changes u))))
(define p (car (update-changes u)))
(define name (player-name p))
(define c (findf (lambda (o) (= cid (client-id o))) clients))
(cond
((not (equal? VERSION (ob-id p)))
(printf "server version ~a dropping client id ~a version ~a : ~a\n"
VERSION cid (ob-id p) name)
(remove-client cid))
(else
(set-player-name! (client-player c) name)
(printf "server client ~a named ~a\n" cid name)
(set-client-status! c CLIENT_STATUS_WAITING_FOR_SPACE)
(append! updates
(apply-all-changes! ownspace (list (chadd (client-player c) #f))
"server" #:addf addf))
(define m (make-message ownspace (format "New Player: ~a" name)))
(append! updates (apply-all-changes! ownspace (list m) "server" #:addf addf)))))
((update? u)
(cond
((not (equal? (space-id ownspace) (update-id u)))
(printf "server dropping update id ~a from ~a for old space (needed ~a)\n"
(update-id u) cid (space-id ownspace)))
(else
(when (and (update-time u) ((- (space-time ownspace) (update-time u)) . > . 200))
(printf "~a : client ~a is behind ~a\n" (space-time ownspace) cid
(- (space-time ownspace) (update-time u))))
(for ((ch (in-list (update-changes u))))
(cond
((and (anncmd? ch)
(or (not SERVER_LOCKDOWN?)
(equal? cid (anncmd-pid ch))))
(define changes
(scenario-on-message ownspace ch change-scenario!))
(append! updates (apply-all-changes! ownspace changes "server" #:addf addf)))
((or (not SERVER_LOCKDOWN?)
(and (chmov? ch) (equal? cid (chmov-id ch)))
(and (command? ch) (equal? cid (command-id ch)))
(and (endrc? ch) (equal? cid (endrc-pid ch)))
(and (endcb? ch) (equal? cid (endcb-pid ch))))
(define pids '())
(define command-changes
(apply-all-changes! ownspace (list ch) "server"
#:addf addf
#:on-player-restart
(lambda (pid) (append! pids pid))))
(append! updates command-changes)
(when scenario-on-player-restart
(for ((pid (in-list pids)))
(define changes (scenario-on-player-restart ownspace pid))
(append! updates (apply-all-changes! ownspace changes
"server" #:addf addf)))))
(else
(printf "server got unauthorized update from client ~a : ~v\n" cid ch)))))))
(else
(printf "server got unexpected data ~v\n" u)))
(loop)))
)
(timeit time-effects
(for ((o (space-objects ownspace))
#:when (obj-alive? o))
(define precs (upkeep! ownspace o))
(define cs (apply-all-changes! ownspace precs "server" #:addf addf))
(append! updates cs))
; find out if any player's rc objects went away
(for ((p (space-players ownspace))
#:when (and (player-rcid p)
(not (find-id ownspace ownspace (player-rcid p)))))
(define cs (apply-all-changes! ownspace (list (endrc (ob-id p) #f)) "server" #:addf addf))
(append! updates cs))
)
; scenario hook
(timeit time-hook
(define ups (scenario-on-tick ownspace qt change-scenario!))
(append! updates (apply-all-changes! ownspace ups "server" #:addf addf))
)
; ai
(timeit time-ai
; run-ai! returns already-applied changes
(append! updates (run-ai! ownspace qt))
)
;(outputtime "server"
; (space-time ownspace)
; time-ai)
; cull dead
(set-space-objects! ownspace (filter obj-alive? (space-objects ownspace)))
(timeit time-output
; send any 0-time posvels and least-recently sent
(define oldest #f)
(define pvupdates '())
;(printf "pvts (~a) :" (space-time ownspace))
(for ((o (space-objects ownspace))
#:when (and (obj? o)
(obj-posvel o)
(posvel-t (obj-posvel o))))
(define pv (obj-posvel o))
;(printf " ~a" (posvel-t pv))
(cond ((equal? #t (posvel-t pv))
(set-posvel-t! pv (space-time ownspace))
(prepend! pvupdates (pvupdate (ob-id o) pv)))
#;((or (not oldest)
(< (- (space-time ownspace) (posvel-t (obj-posvel oldest)))
(- (space-time ownspace) (posvel-t pv))))
(set! oldest o))))
;(printf "\n")
#;(when oldest
(define old-t (- (space-time ownspace) (posvel-t (obj-posvel oldest))))
(when (and (old-t . > . 5000)
(time-for (space-time ownspace) 1000))
(printf "server oldest posvel is ~a\n" old-t))
(set-posvel-t! (obj-posvel oldest) (space-time ownspace))
(set! pvupdates (cons (pvupdate (ob-id oldest) (obj-posvel oldest)) pvupdates)))
; make total update message
(define u (update (space-id ownspace) (space-time ownspace) updates pvupdates))
; reset this before trying to send, so we can accumulate
; client-disconnect updates if there's an error
(set! updates '())
;(printf "~a server queuing time ~v\n" (current-milliseconds) (update-time u))
; to-bytes also serves to copy the info in u so it doesn't change
; because send-to-client is asynchronous
(define msg (serialize u))
(for ((c clients)
#:when (= (client-status c) CLIENT_STATUS_OK))
(send-to-client c msg))
)
)
; send to any clients that need a whole ownspace
; - either new clients or the scenario changed
(define msg #f)
(for ((c clients)
#:when (= (client-status c) CLIENT_STATUS_WAITING_FOR_SPACE))
(when (not msg)
(set! msg (serialize ownspace)))
( printf " server sending ownspace to client ~a ~a\n "
; (client-id c) (player-name (client-player c)))
(send-to-client c msg)
(set-client-status! c CLIENT_STATUS_OK))
; housekeeping
(flush-output)
(collect-garbage 'incremental)
; sleep so we don't hog the whole racket vm
(define sleep-time (- (+ previous-physics-time TICK 1)
(current-milliseconds)))
(cond
((sleep-time . > . 0)
(sleep (/ sleep-time 1000.0)))
(else
(printf "~a : server sleep-time ~a num objects ~a\n"
(space-time ownspace) sleep-time (length (space-objects ownspace)))
(outputtime "server"
(space-time ownspace)
time-commands
time-tick
time-effects
time-hook
time-ai
time-output)
))
(server-loop))
(define (change-scenario! (scenario sc-pick))
(define-values (newspace on-tick on-message on-player-restart)
(scenario ownspace scenario-on-tick scenario-on-message scenario-on-player-restart))
;(printf "start ownspace ~v\n" new-space)
(set! ownspace newspace)
(set! scenario-on-tick on-tick)
(set! scenario-on-message on-message)
(set! scenario-on-player-restart on-player-restart)
; junk any updates we've already processed on the old space
(set! updates '())
(for ((c clients))
(set-client-status! c CLIENT_STATUS_WAITING_FOR_SPACE))
; debugging
(when spacebox
(set-box! spacebox ownspace)))
(define (start-server (port PORT) #:scenario (scenario sc-pick) #:spacebox (spbox #f))
(load-ships!)
(change-scenario! scenario)
(set! spacebox spbox)
(set! server-listener (tcp-listen port 100 #t))
(printf "waiting for clients...\n")
(server-loop))
(module+ main
(start-server
;#:scenario testing-scenario
))
| null | https://raw.githubusercontent.com/david-vanderson/warp/cdc1d0bd942780fb5360dc6a34a2a06cf9518408/server.rkt | racket | client connected, we are waiting for their player name
client needs whole ownspace, don't send any updates until then
- changing the scenario puts everybody here
normal operation, send updates
debugging
called once on every object
return a list of changes
stop warp for any ships that hit the edge of space
return a list of already applied updates
set runtime
run this ship's ai
if the ai does something that adds to space-objects (like launching)
(printf "ran ~a ai\n" (/ delay TICK))
(define delay-ch (make-async-channel))
(thread
(lambda ()
(define count 0)
(let loop ()
(define vs (async-channel-get delay-ch))
(define d (- delay (- (current-milliseconds) (car vs))))
;(printf "delaying ~a\n" d)
(when (d . > . 0)
( when (= 0 ( modulo count 600 ) )
(loop))))
(async-channel-put delay-ch (list (current-milliseconds) (client-out-t c) v))
process new clients
send version in the player name field
assign an id
simulation tick
(printf "server woke up too early, no tick\n")
physics
process player commands
find out if any player's rc objects went away
scenario hook
ai
run-ai! returns already-applied changes
(outputtime "server"
(space-time ownspace)
time-ai)
cull dead
send any 0-time posvels and least-recently sent
(printf "pvts (~a) :" (space-time ownspace))
(printf " ~a" (posvel-t pv))
((or (not oldest)
(printf "\n")
(when oldest
make total update message
reset this before trying to send, so we can accumulate
client-disconnect updates if there's an error
(printf "~a server queuing time ~v\n" (current-milliseconds) (update-time u))
to-bytes also serves to copy the info in u so it doesn't change
because send-to-client is asynchronous
send to any clients that need a whole ownspace
- either new clients or the scenario changed
(client-id c) (player-name (client-player c)))
housekeeping
sleep so we don't hog the whole racket vm
(printf "start ownspace ~v\n" new-space)
junk any updates we've already processed on the old space
debugging
#:scenario testing-scenario | #lang racket/base
(require racket/tcp
racket/async-channel)
(require "defs.rkt"
"utils.rkt"
"change.rkt"
"physics.rkt"
"quadtree.rkt"
"ships.rkt"
"pilot.rkt"
"warp.rkt"
"plasma.rkt"
"explosion.rkt"
"pbolt.rkt"
"missile.rkt"
"cannon.rkt"
"shield.rkt"
"scenario.rkt"
"upgrade.rkt")
(provide start-server)
(define CLIENT_STATUS_NEW 0)
(define CLIENT_STATUS_WAITING_FOR_SPACE 1)
(define CLIENT_STATUS_OK 2)
(struct client (status player in-port out-port in-t out-t) #:mutable #:prefab)
(define (client-id c) (ob-id (client-player c)))
(define server-listener #f)
(define clients '())
(define ownspace #f)
(define (scenario-on-tick change-scenario!) '())
(define (scenario-on-message cmd change-scenario!) '())
(define scenario-on-player-restart #f)
(define spacebox #f)
(define (upkeep! space o)
(define changes '())
(cond
((and (ship? o)
(warping? o)
(outside? space o))
(append! changes (command (ob-id o) #f 'warp 'stop)))
((probe? o)
(define t (ship-tool o 'endrc))
(when (and t
(tool-rc t)
((tool-rc t) . <= . (/ (obj-age space o) 1000.0)))
(define player (findf (lambda (x) (equal? (player-rcid x) (ob-id o)))
(space-players space)))
(append! changes (endrc (and player (ob-id player)) (ob-id o)))))
((cannonball? o)
(when ((obj-age space o) . > . 30000.0)
(append! changes (chdam (ob-id o) (ship-maxcon o) #f))))
((missile? o)
(define t (ship-tool o 'endrc))
(when ((tool-rc t) . <= . (/ (obj-age space o) 1000.0))
(append! changes (chdam (ob-id o) (ship-maxcon o) #f)))))
changes)
(define (run-ai! space qt)
(define updates '())
(define stacks (search space space ai-ship? #t))
(define delay 0)
if we have n't seen this ship before , set ai runtime to 0
(for ((s (in-list stacks)))
(define changes '())
(define ship (car s))
(when (and (obj-alive? ship)
((- (space-time space) (ship-ai-time ship)) . > . (ship-ai-freq ship)))
push ais away from running in the same tick
( printf " running ai for ship ~a\n " ( ship - name ship ) )
(when (and (ship-tool ship 'engine)
(ship-tool ship 'steer))
(when (not (missile? ship))
(append! changes (pilot-ai-strategy! space qt s)))
(when (and (ship-flying? ship)
(or (missile? ship)
(ship-strategy ship)))
(append! changes (pilot-ai-fly! space qt s))))
(when (ship-tool ship 'pbolt)
(append! changes (pbolt-ai! qt s)))
(when (ship-tool ship 'cannon)
(append! changes (cannon-ai! qt s)))
(when (cannonball? ship)
(append! changes (cannonball-ai! qt s)))
(when (ship-tool ship 'missile)
(append! changes (missile-ai! space qt s)))
)
then add those to the quadtree so later ais see it
(define (addf o)
(add-to-qt! ownspace qt o))
(append! updates (apply-all-changes! ownspace changes "server" #:addf addf)))
updates)
(define updates '())
(define (remove-client cid)
(define c (findf (lambda (o) (= cid (client-id o))) clients))
(when c
(define name (player-name (client-player c)))
(printf "server (~a) removing client ~a ~a\n" (length clients) (client-id c) name)
(define m (make-message ownspace (format "Player Left: ~a" name)))
(append! updates
(apply-all-changes! ownspace
(list (chrm (client-id c)) m)
"server"))
(close-input-port (client-in-port c))
(with-handlers ((exn:fail:network? (lambda (exn) #f)))
(close-output-port (client-out-port c)))
(kill-thread (client-in-t c))
(kill-thread (client-out-t c))
(set! clients (remove c clients))))
for debugging to artificially introduce lag from server->client
( define delay 250.0 )
( sleep ( / d 1000.0 ) ) )
( thread - send ( cadr vs ) ( caddr vs ) )
( set ! count ( + 1 count ) )
( if ( equal ? 0.0 delay )
( set ! delay 400.0 )
( set ! delay 0.0 ) )
( printf " delay set to ~a\n " delay ) )
(define (send-to-client c v)
(thread-send (client-out-t c) v)
)
(define previous-physics-time #f)
(define (server-loop)
(define time-tick 0)
(define time-commands 0)
(define time-effects 0)
(define time-hook 0)
(define time-ai 0)
(define time-output 0)
(define current-time (current-milliseconds))
(when (not previous-physics-time)
(set! previous-physics-time current-time))
(when (tcp-accept-ready? server-listener)
(define-values (in out) (tcp-accept server-listener))
(when (and in out)
(set-tcp-nodelay! out #t)
(define cid (next-id))
(define c (client CLIENT_STATUS_NEW
(player cid VERSION #f 0 '() #f #f)
in out
(make-in-thread cid in (current-thread))
(make-out-thread cid out (current-thread))))
(printf "server (~a) accepting new client ~a\n" (length clients) cid)
(prepend! clients c))
)
(define tick? #t)
(when ((- current-time previous-physics-time) . < . TICK)
(set! tick? #f))
(when tick?
(define qt #f)
(timeit time-tick
(set! previous-physics-time (+ previous-physics-time TICK))
(define-values (qt2 updates2)
(tick-space! ownspace apply-all-changes!))
(set! qt qt2)
(append! updates updates2)
)
(define (addf o)
(add-to-qt! ownspace qt o))
(timeit time-commands
(let loop ()
(define v (thread-try-receive))
(when v
(define cid (car v))
(define u (cdr v))
(cond
((not u)
(remove-client cid))
((and (update? u)
(not (null? (update-changes u)))
(player? (car (update-changes u))))
(define p (car (update-changes u)))
(define name (player-name p))
(define c (findf (lambda (o) (= cid (client-id o))) clients))
(cond
((not (equal? VERSION (ob-id p)))
(printf "server version ~a dropping client id ~a version ~a : ~a\n"
VERSION cid (ob-id p) name)
(remove-client cid))
(else
(set-player-name! (client-player c) name)
(printf "server client ~a named ~a\n" cid name)
(set-client-status! c CLIENT_STATUS_WAITING_FOR_SPACE)
(append! updates
(apply-all-changes! ownspace (list (chadd (client-player c) #f))
"server" #:addf addf))
(define m (make-message ownspace (format "New Player: ~a" name)))
(append! updates (apply-all-changes! ownspace (list m) "server" #:addf addf)))))
((update? u)
(cond
((not (equal? (space-id ownspace) (update-id u)))
(printf "server dropping update id ~a from ~a for old space (needed ~a)\n"
(update-id u) cid (space-id ownspace)))
(else
(when (and (update-time u) ((- (space-time ownspace) (update-time u)) . > . 200))
(printf "~a : client ~a is behind ~a\n" (space-time ownspace) cid
(- (space-time ownspace) (update-time u))))
(for ((ch (in-list (update-changes u))))
(cond
((and (anncmd? ch)
(or (not SERVER_LOCKDOWN?)
(equal? cid (anncmd-pid ch))))
(define changes
(scenario-on-message ownspace ch change-scenario!))
(append! updates (apply-all-changes! ownspace changes "server" #:addf addf)))
((or (not SERVER_LOCKDOWN?)
(and (chmov? ch) (equal? cid (chmov-id ch)))
(and (command? ch) (equal? cid (command-id ch)))
(and (endrc? ch) (equal? cid (endrc-pid ch)))
(and (endcb? ch) (equal? cid (endcb-pid ch))))
(define pids '())
(define command-changes
(apply-all-changes! ownspace (list ch) "server"
#:addf addf
#:on-player-restart
(lambda (pid) (append! pids pid))))
(append! updates command-changes)
(when scenario-on-player-restart
(for ((pid (in-list pids)))
(define changes (scenario-on-player-restart ownspace pid))
(append! updates (apply-all-changes! ownspace changes
"server" #:addf addf)))))
(else
(printf "server got unauthorized update from client ~a : ~v\n" cid ch)))))))
(else
(printf "server got unexpected data ~v\n" u)))
(loop)))
)
(timeit time-effects
(for ((o (space-objects ownspace))
#:when (obj-alive? o))
(define precs (upkeep! ownspace o))
(define cs (apply-all-changes! ownspace precs "server" #:addf addf))
(append! updates cs))
(for ((p (space-players ownspace))
#:when (and (player-rcid p)
(not (find-id ownspace ownspace (player-rcid p)))))
(define cs (apply-all-changes! ownspace (list (endrc (ob-id p) #f)) "server" #:addf addf))
(append! updates cs))
)
(timeit time-hook
(define ups (scenario-on-tick ownspace qt change-scenario!))
(append! updates (apply-all-changes! ownspace ups "server" #:addf addf))
)
(timeit time-ai
(append! updates (run-ai! ownspace qt))
)
(set-space-objects! ownspace (filter obj-alive? (space-objects ownspace)))
(timeit time-output
(define oldest #f)
(define pvupdates '())
(for ((o (space-objects ownspace))
#:when (and (obj? o)
(obj-posvel o)
(posvel-t (obj-posvel o))))
(define pv (obj-posvel o))
(cond ((equal? #t (posvel-t pv))
(set-posvel-t! pv (space-time ownspace))
(prepend! pvupdates (pvupdate (ob-id o) pv)))
(< (- (space-time ownspace) (posvel-t (obj-posvel oldest)))
(- (space-time ownspace) (posvel-t pv))))
(set! oldest o))))
(define old-t (- (space-time ownspace) (posvel-t (obj-posvel oldest))))
(when (and (old-t . > . 5000)
(time-for (space-time ownspace) 1000))
(printf "server oldest posvel is ~a\n" old-t))
(set-posvel-t! (obj-posvel oldest) (space-time ownspace))
(set! pvupdates (cons (pvupdate (ob-id oldest) (obj-posvel oldest)) pvupdates)))
(define u (update (space-id ownspace) (space-time ownspace) updates pvupdates))
(set! updates '())
(define msg (serialize u))
(for ((c clients)
#:when (= (client-status c) CLIENT_STATUS_OK))
(send-to-client c msg))
)
)
(define msg #f)
(for ((c clients)
#:when (= (client-status c) CLIENT_STATUS_WAITING_FOR_SPACE))
(when (not msg)
(set! msg (serialize ownspace)))
( printf " server sending ownspace to client ~a ~a\n "
(send-to-client c msg)
(set-client-status! c CLIENT_STATUS_OK))
(flush-output)
(collect-garbage 'incremental)
(define sleep-time (- (+ previous-physics-time TICK 1)
(current-milliseconds)))
(cond
((sleep-time . > . 0)
(sleep (/ sleep-time 1000.0)))
(else
(printf "~a : server sleep-time ~a num objects ~a\n"
(space-time ownspace) sleep-time (length (space-objects ownspace)))
(outputtime "server"
(space-time ownspace)
time-commands
time-tick
time-effects
time-hook
time-ai
time-output)
))
(server-loop))
(define (change-scenario! (scenario sc-pick))
(define-values (newspace on-tick on-message on-player-restart)
(scenario ownspace scenario-on-tick scenario-on-message scenario-on-player-restart))
(set! ownspace newspace)
(set! scenario-on-tick on-tick)
(set! scenario-on-message on-message)
(set! scenario-on-player-restart on-player-restart)
(set! updates '())
(for ((c clients))
(set-client-status! c CLIENT_STATUS_WAITING_FOR_SPACE))
(when spacebox
(set-box! spacebox ownspace)))
(define (start-server (port PORT) #:scenario (scenario sc-pick) #:spacebox (spbox #f))
(load-ships!)
(change-scenario! scenario)
(set! spacebox spbox)
(set! server-listener (tcp-listen port 100 #t))
(printf "waiting for clients...\n")
(server-loop))
(module+ main
(start-server
))
|
0ae1b28212ca36a2120b800b00264c1e04f0bafefbca5e2e8c55dd9d36c0925f | mishun/tangles | Test.hs | module Math.Topology.KnotTh.ChordDiagram.Test
( test
) where
import Control.Monad (forM_)
import Text.Printf
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit hiding (Test, test)
import Math.Topology.KnotTh.ChordDiagram
import Math.Topology.KnotTh.ChordDiagram.Lyndon
import Math.Topology.KnotTh.Algebra.Dihedral
naiveMinShift :: (Ord a) => [a] -> [a]
naiveMinShift [] = []
naiveMinShift l = minimum [ let (a, b) = splitAt i l in b ++ a | i <- [0 .. length l]]
minShiftIsOk :: [Int] -> Bool
minShiftIsOk list = snd (minimumCyclicShift list) == naiveMinShift list
test :: Test
test =
let testGenerator gen list =
forM_ list $ \ (n, expected) ->
let total = countChordDiagrams (gen n) :: Int
in assertEqual (printf "for n = %i" n) expected total
in testGroup "Chord Diagrams"
[ testCase "Numbers of non-planar chord diagrams" $
testGenerator generateNonPlanarRaw
[ (0, 1), (1, 0), (2, 1), (3, 2), (4, 7), (5, 29), (6, 196), (7, 1788), (8, 21994) ]
, testCase "Numbers of bicolourable non-planar chord diagrams" $
testGenerator generateBicolourableNonPlanarRaw
[ (0, 1), (1, 0), (2, 0), (3, 1), (4, 1), (5, 4), (6, 9), (7, 43), (8, 198), (9, 1435) ]
, testCase "Numbers of quasi-tree chord diagrams" $
testGenerator generateQuasiTreesRaw
[ (0, 1), (1, 0), (2, 1), (3, 1), (4, 4), (5, 18), (6, 116), (7, 1060), (8, 13019) ]
, testCase "Symmetry group information" $
forM_ [1 .. 9] $ \ !n ->
forM_ (listChordDiagrams $ generateNonPlanarRaw n) $ \ (cd, (mirror, period)) -> do
assertEqual (printf "%s period" (show cd)) (naivePeriodOf cd) period
let expectedMirror = mirrorIt cd `elem` map (`rotateBy` cd) [0 .. rotationOrder cd - 1]
assertEqual (printf "%s mirror" (show cd)) expectedMirror mirror
, testGroup "String combinatorial functions tests"
[ testProperty "Minimal cyclic shift" minShiftIsOk
, let list = [6, 4, 3, 4, 5, 3, 3, 1] :: [Int]
in testCase (printf "Test minimal cyclic shift of %s" $ show list) $
snd (minimumCyclicShift list) @?= naiveMinShift list
]
]
| null | https://raw.githubusercontent.com/mishun/tangles/9af39dd48e3dcc5e3944f8d060c8769ff3d81d02/test/Math/Topology/KnotTh/ChordDiagram/Test.hs | haskell | module Math.Topology.KnotTh.ChordDiagram.Test
( test
) where
import Control.Monad (forM_)
import Text.Printf
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit hiding (Test, test)
import Math.Topology.KnotTh.ChordDiagram
import Math.Topology.KnotTh.ChordDiagram.Lyndon
import Math.Topology.KnotTh.Algebra.Dihedral
naiveMinShift :: (Ord a) => [a] -> [a]
naiveMinShift [] = []
naiveMinShift l = minimum [ let (a, b) = splitAt i l in b ++ a | i <- [0 .. length l]]
minShiftIsOk :: [Int] -> Bool
minShiftIsOk list = snd (minimumCyclicShift list) == naiveMinShift list
test :: Test
test =
let testGenerator gen list =
forM_ list $ \ (n, expected) ->
let total = countChordDiagrams (gen n) :: Int
in assertEqual (printf "for n = %i" n) expected total
in testGroup "Chord Diagrams"
[ testCase "Numbers of non-planar chord diagrams" $
testGenerator generateNonPlanarRaw
[ (0, 1), (1, 0), (2, 1), (3, 2), (4, 7), (5, 29), (6, 196), (7, 1788), (8, 21994) ]
, testCase "Numbers of bicolourable non-planar chord diagrams" $
testGenerator generateBicolourableNonPlanarRaw
[ (0, 1), (1, 0), (2, 0), (3, 1), (4, 1), (5, 4), (6, 9), (7, 43), (8, 198), (9, 1435) ]
, testCase "Numbers of quasi-tree chord diagrams" $
testGenerator generateQuasiTreesRaw
[ (0, 1), (1, 0), (2, 1), (3, 1), (4, 4), (5, 18), (6, 116), (7, 1060), (8, 13019) ]
, testCase "Symmetry group information" $
forM_ [1 .. 9] $ \ !n ->
forM_ (listChordDiagrams $ generateNonPlanarRaw n) $ \ (cd, (mirror, period)) -> do
assertEqual (printf "%s period" (show cd)) (naivePeriodOf cd) period
let expectedMirror = mirrorIt cd `elem` map (`rotateBy` cd) [0 .. rotationOrder cd - 1]
assertEqual (printf "%s mirror" (show cd)) expectedMirror mirror
, testGroup "String combinatorial functions tests"
[ testProperty "Minimal cyclic shift" minShiftIsOk
, let list = [6, 4, 3, 4, 5, 3, 3, 1] :: [Int]
in testCase (printf "Test minimal cyclic shift of %s" $ show list) $
snd (minimumCyclicShift list) @?= naiveMinShift list
]
]
| |
f040a3aeebed8c419bbb843b0ee5ef9e96cae085fc155eaed3957e745560d54a | lambe-lang/compiler | entry.mli | module type API = sig
type t
type 'a p
val keywords : string list
val main : t p
end
| null | https://raw.githubusercontent.com/lambe-lang/compiler/79d7937c06ca30e231855ec4ce99012ca0395cd5/attic/lib/syntax/entry.mli | ocaml | module type API = sig
type t
type 'a p
val keywords : string list
val main : t p
end
| |
63a079335aa11129deb09dd0e2f64ba9cb9d5fe2520baf19b40bb192e397d319 | alanz/ghc-exactprint | GADTContext.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE ImplicitParams #
# LANGUAGE QuasiQuotes #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
data StackItem a where
Snum :: forall a. Fractional a => a -> StackItem a
Sop :: OpDesc -> StackItem a
deriving instance Show a => Show (StackItem a)
type MPI = ?mpi_secret :: MPISecret
mkPoli = mkBila . map ((,,(),,()) <$> P.base <*> P.pos <*> P.form)
data MaybeDefault v where
SetTo :: forall v . ( Eq v, Show v ) => !v -> MaybeDefault v
SetTo4 :: forall v a. (( Eq v, Show v ) => v -> MaybeDefault v
-> a -> MaybeDefault [a])
TestParens :: (forall v . (Eq v) => MaybeDefault v)
TestParens2 :: (forall v . ((Eq v)) => MaybeDefault v)
TestParens3 :: (forall v . (((Eq v)) => (MaybeDefault v)))
TestParens4 :: (forall v . (((Eq v)) => (MaybeDefault v -> MaybeDefault v)))
data T a where
K1 :: forall a. Ord a => { x :: [a], y :: Int } -> T a
K2 :: forall a. ((Ord a)) => { x :: ([a]), y :: ((Int)) } -> T a
K3 :: forall a. ((Ord a)) => { x :: ([a]), y :: ((Int)) } -> (T a)
K4 :: (forall a. Ord a => { x :: [a], y :: Int } -> T a)
[t| Map.Map T.Text $tc |]
bar $( [p| x |] ) = x
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/pre-ghc90/GADTContext.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE GADTs # | # LANGUAGE ImplicitParams #
# LANGUAGE QuasiQuotes #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
data StackItem a where
Snum :: forall a. Fractional a => a -> StackItem a
Sop :: OpDesc -> StackItem a
deriving instance Show a => Show (StackItem a)
type MPI = ?mpi_secret :: MPISecret
mkPoli = mkBila . map ((,,(),,()) <$> P.base <*> P.pos <*> P.form)
data MaybeDefault v where
SetTo :: forall v . ( Eq v, Show v ) => !v -> MaybeDefault v
SetTo4 :: forall v a. (( Eq v, Show v ) => v -> MaybeDefault v
-> a -> MaybeDefault [a])
TestParens :: (forall v . (Eq v) => MaybeDefault v)
TestParens2 :: (forall v . ((Eq v)) => MaybeDefault v)
TestParens3 :: (forall v . (((Eq v)) => (MaybeDefault v)))
TestParens4 :: (forall v . (((Eq v)) => (MaybeDefault v -> MaybeDefault v)))
data T a where
K1 :: forall a. Ord a => { x :: [a], y :: Int } -> T a
K2 :: forall a. ((Ord a)) => { x :: ([a]), y :: ((Int)) } -> T a
K3 :: forall a. ((Ord a)) => { x :: ([a]), y :: ((Int)) } -> (T a)
K4 :: (forall a. Ord a => { x :: [a], y :: Int } -> T a)
[t| Map.Map T.Text $tc |]
bar $( [p| x |] ) = x
|
21a178c4cc05bc849fd2e41aeef95fa98053d6df44c053a7117c2b33d6c38782 | jgdavey/kevin | home.clj | (ns kevin.routes.home
(:require [compojure.core :refer :all]
[datomic.api :as d]
[noir.util.cache :refer [cache!]]
[kevin.core :as s]
[kevin.views :as views]))
10 minutes
(noir.util.cache/set-size! 1000)
(defn home []
(cache! :home
(views/main-template
:body (views/form "Kevin Bacon (I)" nil nil))))
(defn- cache-key [search hard-mode]
(conj (mapv :actor-id (first search)) hard-mode))
(defn search [context {:keys [person1 person2 hard-mode] :as params}]
(let [db (-> context :db :conn d/db)
search (s/search db person1 person2)
hard-mode? (boolean (seq hard-mode))]
(if (= 1 (count search))
(cache! (cache-key search hard-mode?)
(views/results-page (s/annotate-search db (first search) hard-mode?)))
(views/disambiguate search params))))
(defn home-routes [context]
(routes
(HEAD "/" [] "") ;; heartbeat response
(GET "/" [] (home))
(GET "/search" {params :params} (search context params))))
| null | https://raw.githubusercontent.com/jgdavey/kevin/b4263c932b733c4e0b7729573cdc4550e69ddfa2/src/kevin/routes/home.clj | clojure | heartbeat response | (ns kevin.routes.home
(:require [compojure.core :refer :all]
[datomic.api :as d]
[noir.util.cache :refer [cache!]]
[kevin.core :as s]
[kevin.views :as views]))
10 minutes
(noir.util.cache/set-size! 1000)
(defn home []
(cache! :home
(views/main-template
:body (views/form "Kevin Bacon (I)" nil nil))))
(defn- cache-key [search hard-mode]
(conj (mapv :actor-id (first search)) hard-mode))
(defn search [context {:keys [person1 person2 hard-mode] :as params}]
(let [db (-> context :db :conn d/db)
search (s/search db person1 person2)
hard-mode? (boolean (seq hard-mode))]
(if (= 1 (count search))
(cache! (cache-key search hard-mode?)
(views/results-page (s/annotate-search db (first search) hard-mode?)))
(views/disambiguate search params))))
(defn home-routes [context]
(routes
(GET "/" [] (home))
(GET "/search" {params :params} (search context params))))
|
e3e1573e76a412fd7d2e00e221a1d96786dcfbe207b526b96f940fe70bd76800 | input-output-hk/project-icarus-importer | Resolved.hs | -- | Resolved blocks and transactions
module Cardano.Wallet.Kernel.DB.Resolved (
-- * Resolved blocks and transactions
ResolvedInput
, ResolvedTx(..)
, ResolvedBlock(..)
-- ** Lenses
, rtxInputs
, rtxOutputs
, rbTxs
) where
import Universum
import Control.Lens.TH (makeLenses)
import qualified Data.Map as Map
import Data.SafeCopy (base, deriveSafeCopy)
import qualified Data.Text.Buildable
import Formatting (bprint, (%))
import Serokell.Util (listJson, mapJson)
import qualified Pos.Core as Core
import qualified Pos.Txp as Core
import Cardano.Wallet.Kernel.DB.InDb
{-------------------------------------------------------------------------------
Resolved blocks and transactions
-------------------------------------------------------------------------------}
-- | Resolved input
--
A transaction input @(h , i)@ points to the @i@th output of the transaction
with hash @h@ , which is not particularly informative . The corresponding
-- 'ResolvedInput' is obtained by looking up what that output actually is.
type ResolvedInput = Core.TxOutAux
-- | (Unsigned) transaction with inputs resolved
--
NOTE : We can not recover the original transaction from a ' ResolvedTx ' .
-- Any information needed inside the wallet kernel must be explicitly
-- represented here.
data ResolvedTx = ResolvedTx {
-- | Transaction inputs
_rtxInputs :: InDb (NonEmpty (Core.TxIn, ResolvedInput))
-- | Transaction outputs
, _rtxOutputs :: InDb Core.Utxo
}
-- | (Unsigned block) containing resolved transactions
--
-- NOTE: We cannot recover the original block from a 'ResolvedBlock'.
-- Any information needed inside the wallet kernel must be explicitly
-- represented here.
data ResolvedBlock = ResolvedBlock {
-- | Transactions in the block
_rbTxs :: [ResolvedTx]
}
makeLenses ''ResolvedTx
makeLenses ''ResolvedBlock
deriveSafeCopy 1 'base ''ResolvedTx
deriveSafeCopy 1 'base ''ResolvedBlock
{-------------------------------------------------------------------------------
Pretty-printing
-------------------------------------------------------------------------------}
instance Buildable ResolvedTx where
build ResolvedTx{..} = bprint
( "ResolvedTx "
% "{ inputs: " % mapJson
% ", outputs: " % mapJson
% "}"
)
(Map.fromList (toList (_rtxInputs ^. fromDb)))
(_rtxOutputs ^. fromDb)
instance Buildable ResolvedBlock where
build ResolvedBlock{..} = bprint
( "ResolvedBlock "
% "{ txs: " % listJson
% "}"
)
_rbTxs
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/src/Cardano/Wallet/Kernel/DB/Resolved.hs | haskell | | Resolved blocks and transactions
* Resolved blocks and transactions
** Lenses
------------------------------------------------------------------------------
Resolved blocks and transactions
------------------------------------------------------------------------------
| Resolved input
'ResolvedInput' is obtained by looking up what that output actually is.
| (Unsigned) transaction with inputs resolved
Any information needed inside the wallet kernel must be explicitly
represented here.
| Transaction inputs
| Transaction outputs
| (Unsigned block) containing resolved transactions
NOTE: We cannot recover the original block from a 'ResolvedBlock'.
Any information needed inside the wallet kernel must be explicitly
represented here.
| Transactions in the block
------------------------------------------------------------------------------
Pretty-printing
------------------------------------------------------------------------------ | module Cardano.Wallet.Kernel.DB.Resolved (
ResolvedInput
, ResolvedTx(..)
, ResolvedBlock(..)
, rtxInputs
, rtxOutputs
, rbTxs
) where
import Universum
import Control.Lens.TH (makeLenses)
import qualified Data.Map as Map
import Data.SafeCopy (base, deriveSafeCopy)
import qualified Data.Text.Buildable
import Formatting (bprint, (%))
import Serokell.Util (listJson, mapJson)
import qualified Pos.Core as Core
import qualified Pos.Txp as Core
import Cardano.Wallet.Kernel.DB.InDb
A transaction input @(h , i)@ points to the @i@th output of the transaction
with hash @h@ , which is not particularly informative . The corresponding
type ResolvedInput = Core.TxOutAux
NOTE : We can not recover the original transaction from a ' ResolvedTx ' .
data ResolvedTx = ResolvedTx {
_rtxInputs :: InDb (NonEmpty (Core.TxIn, ResolvedInput))
, _rtxOutputs :: InDb Core.Utxo
}
data ResolvedBlock = ResolvedBlock {
_rbTxs :: [ResolvedTx]
}
makeLenses ''ResolvedTx
makeLenses ''ResolvedBlock
deriveSafeCopy 1 'base ''ResolvedTx
deriveSafeCopy 1 'base ''ResolvedBlock
instance Buildable ResolvedTx where
build ResolvedTx{..} = bprint
( "ResolvedTx "
% "{ inputs: " % mapJson
% ", outputs: " % mapJson
% "}"
)
(Map.fromList (toList (_rtxInputs ^. fromDb)))
(_rtxOutputs ^. fromDb)
instance Buildable ResolvedBlock where
build ResolvedBlock{..} = bprint
( "ResolvedBlock "
% "{ txs: " % listJson
% "}"
)
_rbTxs
|
4f0b2322210af1e6ddc449c999b1df4031fa3f196cbcbc393aca05b7fd3b0b24 | YoshikuniJujo/test_haskell | Vertex.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE GeneralizedNewtypeDeriving , DeriveGeneric #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Vertex where
import GHC.Generics
import Foreign.Storable
import Foreign.Storable.SizeAlignment
import qualified Gpu.Vulkan.Enum as Vk
import qualified Gpu.Vulkan.Pipeline.VertexInputState as Vk.Ppl.VertexInputSt
import qualified Cglm
import qualified Foreign.Storable.Generic
data Vertex = Vertex {
vertexPos :: Pos,
vertexColor :: Color,
vertexTexCoord :: TexCoord }
deriving (Show, Eq, Ord, Generic)
newtype Pos = Pos Cglm.Vec3
deriving (Show, Eq, Ord, Storable, Vk.Ppl.VertexInputSt.Formattable)
newtype TexCoord = TexCoord Cglm.Vec2
deriving (Show, Eq, Ord, Storable, Vk.Ppl.VertexInputSt.Formattable)
instance Storable Vertex where
sizeOf = Foreign.Storable.Generic.gSizeOf
alignment = Foreign.Storable.Generic.gAlignment
peek = Foreign.Storable.Generic.gPeek
poke = Foreign.Storable.Generic.gPoke
instance SizeAlignmentList Vertex
instance SizeAlignmentListUntil Pos Vertex
instance SizeAlignmentListUntil Color Vertex
instance SizeAlignmentListUntil TexCoord Vertex
instance Vk.Ppl.VertexInputSt.Formattable Cglm.Vec2 where
formatOf = Vk.FormatR32g32Sfloat
instance Vk.Ppl.VertexInputSt.Formattable Cglm.Vec3 where
formatOf = Vk.FormatR32g32b32Sfloat
instance Foreign.Storable.Generic.G Vertex where
newtype Color = Color Cglm.Vec3
deriving (Show, Eq, Ord, Storable, Vk.Ppl.VertexInputSt.Formattable)
| null | https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/b2f0c0c97b8a549c0bfb59578f7669aa54f1f7d5/themes/gui/vulkan/try-my-vulkan-snd/src/Vertex.hs | haskell | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE GeneralizedNewtypeDeriving , DeriveGeneric #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Vertex where
import GHC.Generics
import Foreign.Storable
import Foreign.Storable.SizeAlignment
import qualified Gpu.Vulkan.Enum as Vk
import qualified Gpu.Vulkan.Pipeline.VertexInputState as Vk.Ppl.VertexInputSt
import qualified Cglm
import qualified Foreign.Storable.Generic
data Vertex = Vertex {
vertexPos :: Pos,
vertexColor :: Color,
vertexTexCoord :: TexCoord }
deriving (Show, Eq, Ord, Generic)
newtype Pos = Pos Cglm.Vec3
deriving (Show, Eq, Ord, Storable, Vk.Ppl.VertexInputSt.Formattable)
newtype TexCoord = TexCoord Cglm.Vec2
deriving (Show, Eq, Ord, Storable, Vk.Ppl.VertexInputSt.Formattable)
instance Storable Vertex where
sizeOf = Foreign.Storable.Generic.gSizeOf
alignment = Foreign.Storable.Generic.gAlignment
peek = Foreign.Storable.Generic.gPeek
poke = Foreign.Storable.Generic.gPoke
instance SizeAlignmentList Vertex
instance SizeAlignmentListUntil Pos Vertex
instance SizeAlignmentListUntil Color Vertex
instance SizeAlignmentListUntil TexCoord Vertex
instance Vk.Ppl.VertexInputSt.Formattable Cglm.Vec2 where
formatOf = Vk.FormatR32g32Sfloat
instance Vk.Ppl.VertexInputSt.Formattable Cglm.Vec3 where
formatOf = Vk.FormatR32g32b32Sfloat
instance Foreign.Storable.Generic.G Vertex where
newtype Color = Color Cglm.Vec3
deriving (Show, Eq, Ord, Storable, Vk.Ppl.VertexInputSt.Formattable)
| |
cce2cfced769c42d10f87983919d493e0a25947e65bf2102f274f9c366d53b47 | liquidz/antq | github_action.clj | (ns antq.upgrade.github-action
(:require
[antq.dep.github-action :as dep.gh-action]
[antq.log :as log]
[antq.upgrade :as upgrade]
[clojure.string :as str]
[rewrite-indented.zip :as ri.zip]))
(defn- update-action-version
[new-version]
(fn [using-line]
(str/replace using-line #"@[^\s]+" (str "@" new-version))))
(defn- update-value
[new-value]
(fn [line]
(str/replace line #"([^:]+\s*:\s*['\"]?)[^\s'\"]+(['\"]?)"
(str "$1" new-value "$2"))))
(defn- action?
[action-name]
(let [re (re-pattern (str "uses\\s*:\\s*" action-name))]
#(some? (re-seq re %))))
(defmulti upgrade-dep
(fn [_loc version-checked-dep]
(dep.gh-action/get-type version-checked-dep)))
(defmethod upgrade-dep :default
[_ version-checked-dep]
(log/error (format "%s: Not supported."
(dep.gh-action/get-type version-checked-dep))))
(defmethod upgrade-dep "uses"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc (action? (:name version-checked-dep)))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc #(= "steps:" %)))
(ri.zip/update (update-action-version (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade-dep "DeLaGuardo/setup-clojure"
[loc version-checked-dep]
(let [target-re (case (:name version-checked-dep)
"clojure/brew-install" #"cli\s*:"
"technomancy/leiningen" #"lein\s*:"
"boot-clj/boot" #"boot\s*:"
nil)]
(if-not target-re
(log/error (format "%s: Unexpected name for setup-clojure"
(:name version-checked-dep)))
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc #(re-seq target-re %))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "DeLaGuardo/setup-clojure")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))))
(defmethod upgrade-dep "DeLaGuardo/setup-clj-kondo"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc #(re-seq #"version\s*:" %))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "DeLaGuardo/setup-clj-kondo")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade-dep "DeLaGuardo/setup-graalvm"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (or (ri.zip/find-next-string loc #(re-seq #"graalvm\s*:" %))
(ri.zip/find-next-string loc #(re-seq #"graalvm-version\s*:" %)))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "DeLaGuardo/setup-graalvm")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade-dep "0918nobita/setup-cljstyle"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc #(re-seq #"cljstyle-version\s*:" %))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "0918nobita/setup-cljstyle")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade/upgrader :github-action
[version-checked-dep]
(some-> (:file version-checked-dep)
(ri.zip/of-file)
(upgrade-dep version-checked-dep)
(ri.zip/root-string)))
| null | https://raw.githubusercontent.com/liquidz/antq/71563266d314cffb69862684de5af75182ee1daf/src/antq/upgrade/github_action.clj | clojure | (ns antq.upgrade.github-action
(:require
[antq.dep.github-action :as dep.gh-action]
[antq.log :as log]
[antq.upgrade :as upgrade]
[clojure.string :as str]
[rewrite-indented.zip :as ri.zip]))
(defn- update-action-version
[new-version]
(fn [using-line]
(str/replace using-line #"@[^\s]+" (str "@" new-version))))
(defn- update-value
[new-value]
(fn [line]
(str/replace line #"([^:]+\s*:\s*['\"]?)[^\s'\"]+(['\"]?)"
(str "$1" new-value "$2"))))
(defn- action?
[action-name]
(let [re (re-pattern (str "uses\\s*:\\s*" action-name))]
#(some? (re-seq re %))))
(defmulti upgrade-dep
(fn [_loc version-checked-dep]
(dep.gh-action/get-type version-checked-dep)))
(defmethod upgrade-dep :default
[_ version-checked-dep]
(log/error (format "%s: Not supported."
(dep.gh-action/get-type version-checked-dep))))
(defmethod upgrade-dep "uses"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc (action? (:name version-checked-dep)))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc #(= "steps:" %)))
(ri.zip/update (update-action-version (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade-dep "DeLaGuardo/setup-clojure"
[loc version-checked-dep]
(let [target-re (case (:name version-checked-dep)
"clojure/brew-install" #"cli\s*:"
"technomancy/leiningen" #"lein\s*:"
"boot-clj/boot" #"boot\s*:"
nil)]
(if-not target-re
(log/error (format "%s: Unexpected name for setup-clojure"
(:name version-checked-dep)))
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc #(re-seq target-re %))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "DeLaGuardo/setup-clojure")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))))
(defmethod upgrade-dep "DeLaGuardo/setup-clj-kondo"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc #(re-seq #"version\s*:" %))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "DeLaGuardo/setup-clj-kondo")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade-dep "DeLaGuardo/setup-graalvm"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (or (ri.zip/find-next-string loc #(re-seq #"graalvm\s*:" %))
(ri.zip/find-next-string loc #(re-seq #"graalvm-version\s*:" %)))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "DeLaGuardo/setup-graalvm")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade-dep "0918nobita/setup-cljstyle"
[loc version-checked-dep]
(loop [loc loc]
(if-let [loc (ri.zip/find-next-string loc #(re-seq #"cljstyle-version\s*:" %))]
(recur (cond-> loc
(some? (ri.zip/find-ancestor-string loc (action? "0918nobita/setup-cljstyle")))
(ri.zip/update (update-value (:latest-version version-checked-dep)))
:always
(ri.zip/next)))
(ri.zip/move-to-root loc))))
(defmethod upgrade/upgrader :github-action
[version-checked-dep]
(some-> (:file version-checked-dep)
(ri.zip/of-file)
(upgrade-dep version-checked-dep)
(ri.zip/root-string)))
| |
f838e6e5464aa01efa1aa62b5be1e332d8f3c251583663c3ecbab5cecc38c134 | ocramz/taco-hs | Shape.hs | module Data.Tensor.Internal.Shape
-- (
Sh ( .. ) , mkSh , mkShD , , shDiff ,
Shape ( .. ) , rank , dim , Z , (: # ) , (: . )
-- )
(module X)
where
import Data.Tensor.Internal.Shape.Types as X
| null | https://raw.githubusercontent.com/ocramz/taco-hs/19d208e2ddc628835a816568cd32029fb0b85048/src/Data/Tensor/Internal/Shape.hs | haskell | (
) | module Data.Tensor.Internal.Shape
Sh ( .. ) , mkSh , mkShD , , shDiff ,
Shape ( .. ) , rank , dim , Z , (: # ) , (: . )
(module X)
where
import Data.Tensor.Internal.Shape.Types as X
|
aa91c59a976315a2d26ba2a3d23e2ea5f4db2dc2ba57106f1a893d6eb378e9e0 | eggzilla/Genbank | SequenceExtractor.hs | # LANGUAGE RecordWildCards #
{-# LANGUAGE DeriveDataTypeable #-}
-- | Extract sequence from genbank file
module Main where
import System.Console.CmdArgs
import Biobase.Genbank.Tools
import Biobase.Genbank.Import
import Data.Either.Unwrap
import Biobase.Fasta.Strict
import qualified Biobase.Types.BioSequence as BS
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.ByteString.Char8 as B
import Paths_Genbank (version)
import Data.Version (showVersion)
data Options = Options
{ inputFilePath :: String,
outputFilePath :: String
} deriving (Show,Data,Typeable)
options :: Options
options = Options
{ inputFilePath = def &= name "i" &= help "Path to input fasta file",
outputFilePath = def &= name "o" &= help "Path to output file"
} &= summary ("Genbank sequence extractor " ++ genbankVersion) &= help "Florian Eggenhofer - 2019-2020" &= verbosity
main :: IO ()
main = do
Options{..} <- cmdArgs options
parsedInput <- readGenbank inputFilePath
if isRight parsedInput
then do
let rightInput = (fromRight parsedInput)
let rawheader = L.unpack (accession rightInput)
let gbkheader = BS.SequenceIdentifier (B.pack rawheader)
let gbkseqdata = (origin rightInput)
let gbkfasta = Fasta gbkheader gbkseqdata
writeFile outputFilePath (B.unpack (fastaToByteString 80 gbkfasta))
else (print (fromLeft parsedInput))
genbankVersion :: String
genbankVersion = showVersion Paths_Genbank.version | null | https://raw.githubusercontent.com/eggzilla/Genbank/cb4aa68357cae4905c4199447492602d5858d3dd/Biobase/Genbank/SequenceExtractor.hs | haskell | # LANGUAGE DeriveDataTypeable #
| Extract sequence from genbank file | # LANGUAGE RecordWildCards #
module Main where
import System.Console.CmdArgs
import Biobase.Genbank.Tools
import Biobase.Genbank.Import
import Data.Either.Unwrap
import Biobase.Fasta.Strict
import qualified Biobase.Types.BioSequence as BS
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.ByteString.Char8 as B
import Paths_Genbank (version)
import Data.Version (showVersion)
data Options = Options
{ inputFilePath :: String,
outputFilePath :: String
} deriving (Show,Data,Typeable)
options :: Options
options = Options
{ inputFilePath = def &= name "i" &= help "Path to input fasta file",
outputFilePath = def &= name "o" &= help "Path to output file"
} &= summary ("Genbank sequence extractor " ++ genbankVersion) &= help "Florian Eggenhofer - 2019-2020" &= verbosity
main :: IO ()
main = do
Options{..} <- cmdArgs options
parsedInput <- readGenbank inputFilePath
if isRight parsedInput
then do
let rightInput = (fromRight parsedInput)
let rawheader = L.unpack (accession rightInput)
let gbkheader = BS.SequenceIdentifier (B.pack rawheader)
let gbkseqdata = (origin rightInput)
let gbkfasta = Fasta gbkheader gbkseqdata
writeFile outputFilePath (B.unpack (fastaToByteString 80 gbkfasta))
else (print (fromLeft parsedInput))
genbankVersion :: String
genbankVersion = showVersion Paths_Genbank.version |
9c10aa6735d9928adacb2c3c3d35792cd9dca8e5623533474c7d05a59b8306fe | cbaggers/tamei | functions.impure.lisp | (uiop:define-package #:tamei.functions.impure (:use :cl)
(:export
;;
;; Arrays
:adjust-array
:vector-pop
:vector-push
:vector-push-extend
;;
System Construction
:compile-file-pathname
:load
:require
:provide
;;
;; Evaluation and Compilation
:compile
:compile-file
:eval
:macroexpand
:macroexpand-1
:proclaim
;;
;; Reader
:make-dispatch-macro-character
:set-dispatch-macro-character
:set-macro-character
:set-syntax-from-char
;;
;; Streams
:file-length
:listen
:open
:peek-char
:read
:read-byte
:read-char
:read-char-no-hang
:read-delimited-list
:read-from-string
:read-line
:read-preserving-whitespace
:read-sequence
:unread-char
:write
:write-byte
:write-char
:write-line
:write-sequence
:write-string
:write-to-string
:clear-input
:clear-output
:finish-output
:force-output
:fresh-line
:get-output-stream-string
:make-synonym-stream
:terpri
:y-or-n-p
:yes-or-no-p
;;
;; Symbols
:makunbound
:set
:remprop
:boundp
:symbol-function
:symbol-value
:gentemp
;;
Data Flow & Controlo
:fmakunbound
:fdefinition
:fboundp
;;
;; Printer
:copy-pprint-dispatch
:pprint
:pprint-dispatch
:pprint-fill
:pprint-indent
:pprint-linear
:pprint-newline
:pprint-tab
:pprint-tabular
:prin1
:prin1-to-string
:princ
:princ-to-string
:print
:print-not-readable-object
:format
:set-pprint-dispatch
;;
;; Strings
:nstring-capitalize
:nstring-downcase
:nstring-upcase
;;
;; Numbers
:random
;;
Conses
:nset-difference
:nset-exclusive-or
:nunion
:nsublis
:nsubst
:nsubst-if
:nsubst-if-not
:mapcan
:mapcon
:mapl
:revappend
:rplaca
:rplacd
;;
;; Sequences
:delete
:delete-duplicates
:delete-if
:delete-if-not
:nsubstitute
:nsubstitute-if
:nsubstitute-if-not
:nreverse
:replace
:stable-sort
:sort
:map-into
:merge
:fill
;;
;; Files
:delete-file
:file-position
:file-write-date
:probe-file
:rename-file
:truename
:directory
:ensure-directories-exist
;;
;; Packages
:list-all-packages
:make-package
:find-all-symbols
:export
:import
:intern
:delete-package
:find-package
:rename-package
:unuse-package
:use-package
:unexport
:unintern
:shadow
:shadowing-import
;;
;; Filenames
:load-logical-pathname-translations
:logical-pathname
:make-pathname
:user-homedir-pathname
:enough-namestring
;;
;; Conditions
:invoke-restart
:use-value
:cerror
:error
:method-combination-error
:abort
:break
:compute-restarts
:continue
:find-restart
:invoke-restart-interactively
:invoke-debugger
:muffle-warning
:warn
:signal
:store-value
;;
;; Objects
:ensure-generic-function
:slot-makunbound
;;
;; Environment
:describe
:disassemble
:ed
:get-decoded-time
:get-internal-real-time
:get-internal-run-time
:get-universal-time
:apropos
:apropos-list
:inspect
:dribble
:room
:sleep
;;
;; Hash Table
:clrhash
:remhash))
| null | https://raw.githubusercontent.com/cbaggers/tamei/e3c6500bd01a4c8af86e85839c31272b38f4f89b/functions.impure.lisp | lisp |
Arrays
Evaluation and Compilation
Reader
Streams
Symbols
Printer
Strings
Numbers
Sequences
Files
Packages
Filenames
Conditions
Objects
Environment
Hash Table | (uiop:define-package #:tamei.functions.impure (:use :cl)
(:export
:adjust-array
:vector-pop
:vector-push
:vector-push-extend
System Construction
:compile-file-pathname
:load
:require
:provide
:compile
:compile-file
:eval
:macroexpand
:macroexpand-1
:proclaim
:make-dispatch-macro-character
:set-dispatch-macro-character
:set-macro-character
:set-syntax-from-char
:file-length
:listen
:open
:peek-char
:read
:read-byte
:read-char
:read-char-no-hang
:read-delimited-list
:read-from-string
:read-line
:read-preserving-whitespace
:read-sequence
:unread-char
:write
:write-byte
:write-char
:write-line
:write-sequence
:write-string
:write-to-string
:clear-input
:clear-output
:finish-output
:force-output
:fresh-line
:get-output-stream-string
:make-synonym-stream
:terpri
:y-or-n-p
:yes-or-no-p
:makunbound
:set
:remprop
:boundp
:symbol-function
:symbol-value
:gentemp
Data Flow & Controlo
:fmakunbound
:fdefinition
:fboundp
:copy-pprint-dispatch
:pprint
:pprint-dispatch
:pprint-fill
:pprint-indent
:pprint-linear
:pprint-newline
:pprint-tab
:pprint-tabular
:prin1
:prin1-to-string
:princ
:princ-to-string
:print
:print-not-readable-object
:format
:set-pprint-dispatch
:nstring-capitalize
:nstring-downcase
:nstring-upcase
:random
Conses
:nset-difference
:nset-exclusive-or
:nunion
:nsublis
:nsubst
:nsubst-if
:nsubst-if-not
:mapcan
:mapcon
:mapl
:revappend
:rplaca
:rplacd
:delete
:delete-duplicates
:delete-if
:delete-if-not
:nsubstitute
:nsubstitute-if
:nsubstitute-if-not
:nreverse
:replace
:stable-sort
:sort
:map-into
:merge
:fill
:delete-file
:file-position
:file-write-date
:probe-file
:rename-file
:truename
:directory
:ensure-directories-exist
:list-all-packages
:make-package
:find-all-symbols
:export
:import
:intern
:delete-package
:find-package
:rename-package
:unuse-package
:use-package
:unexport
:unintern
:shadow
:shadowing-import
:load-logical-pathname-translations
:logical-pathname
:make-pathname
:user-homedir-pathname
:enough-namestring
:invoke-restart
:use-value
:cerror
:error
:method-combination-error
:abort
:break
:compute-restarts
:continue
:find-restart
:invoke-restart-interactively
:invoke-debugger
:muffle-warning
:warn
:signal
:store-value
:ensure-generic-function
:slot-makunbound
:describe
:disassemble
:ed
:get-decoded-time
:get-internal-real-time
:get-internal-run-time
:get-universal-time
:apropos
:apropos-list
:inspect
:dribble
:room
:sleep
:clrhash
:remhash))
|
7507b84ad0bdbc9cb5a4ffff36ab06b4d912189b99e74a9ee23e6468c7a675dd | marigold-dev/deku | named_pipe.ml | module String_map = Map.Make (String)
let file_descriptor_map = ref String_map.empty
let get_pipe_pair_file_descriptors ~is_chain path =
match String_map.find_opt path !file_descriptor_map with
| Some file_descriptors -> file_descriptors
| None ->
let vm_to_chain_path = path ^ "_read" in
let chain_to_vm_path = path ^ "_write" in
let vm_to_chain_permission, chain_to_vm_permission =
if is_chain then ([ Unix.O_RDONLY ], [ Unix.O_WRONLY ])
else ([ Unix.O_WRONLY ], [ Unix.O_RDONLY ])
in
let vm_to_chain =
Unix.openfile vm_to_chain_path vm_to_chain_permission 0o666
in
let chain_to_vm =
Unix.openfile chain_to_vm_path chain_to_vm_permission 0o666
in
file_descriptor_map :=
String_map.add path (vm_to_chain, chain_to_vm) !file_descriptor_map;
(vm_to_chain, chain_to_vm)
let make_pipe_pair path =
let permissions = 0o600 in
if not (Sys.file_exists (path ^ "_read")) then
Unix.mkfifo (path ^ "_read") permissions;
if not (Sys.file_exists (path ^ "_write")) then
Unix.mkfifo (path ^ "_write") permissions
| null | https://raw.githubusercontent.com/marigold-dev/deku/21ec2bf05ce688c5b6012be16545175e75403f06/deku-p/src/core/external_vm/named_pipe.ml | ocaml | module String_map = Map.Make (String)
let file_descriptor_map = ref String_map.empty
let get_pipe_pair_file_descriptors ~is_chain path =
match String_map.find_opt path !file_descriptor_map with
| Some file_descriptors -> file_descriptors
| None ->
let vm_to_chain_path = path ^ "_read" in
let chain_to_vm_path = path ^ "_write" in
let vm_to_chain_permission, chain_to_vm_permission =
if is_chain then ([ Unix.O_RDONLY ], [ Unix.O_WRONLY ])
else ([ Unix.O_WRONLY ], [ Unix.O_RDONLY ])
in
let vm_to_chain =
Unix.openfile vm_to_chain_path vm_to_chain_permission 0o666
in
let chain_to_vm =
Unix.openfile chain_to_vm_path chain_to_vm_permission 0o666
in
file_descriptor_map :=
String_map.add path (vm_to_chain, chain_to_vm) !file_descriptor_map;
(vm_to_chain, chain_to_vm)
let make_pipe_pair path =
let permissions = 0o600 in
if not (Sys.file_exists (path ^ "_read")) then
Unix.mkfifo (path ^ "_read") permissions;
if not (Sys.file_exists (path ^ "_write")) then
Unix.mkfifo (path ^ "_write") permissions
| |
6d3aebd0507b99d65638d9afd9e8bf4d7f5c1feaf6aa77e1cb87870896a58a00 | mtolly/onyxite-customs | BandKeys.hs | {- |
BAND KEYS
-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DerivingVia #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Onyx.Harmonix.GH2.BandKeys where
import Control.Monad.Codec
import qualified Data.EventList.Relative.TimeBody as RTB
import GHC.Generics (Generic)
import Onyx.DeriveHelpers
import Onyx.Harmonix.GH2.PartGuitar (Tempo (..))
import Onyx.MIDI.Read
data BandKeysTrack t = BandKeysTrack
{ keysTempo :: RTB.T t Tempo
, keysIdle :: RTB.T t ()
, keysPlay :: RTB.T t ()
} deriving (Eq, Ord, Show, Generic)
deriving (Semigroup, Monoid, Mergeable) via GenericMerge (BandKeysTrack t)
instance TraverseTrack BandKeysTrack where
traverseTrack fn (BandKeysTrack a b c) = BandKeysTrack
<$> fn a <*> fn b <*> fn c
instance ParseTrack BandKeysTrack where
parseTrack = do
keysTempo <- keysTempo =. command
-- didn't actually see double tempo on keys
keysIdle <- keysIdle =. commandMatch ["idle"]
keysPlay <- keysPlay =. commandMatch ["play"]
return BandKeysTrack{..}
| null | https://raw.githubusercontent.com/mtolly/onyxite-customs/0c8acd6248fe92ea0d994b18b551973816adf85b/haskell/packages/onyx-lib/src/Onyx/Harmonix/GH2/BandKeys.hs | haskell | |
BAND KEYS
# LANGUAGE OverloadedStrings #
didn't actually see double tempo on keys | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DerivingVia #
# LANGUAGE RecordWildCards #
module Onyx.Harmonix.GH2.BandKeys where
import Control.Monad.Codec
import qualified Data.EventList.Relative.TimeBody as RTB
import GHC.Generics (Generic)
import Onyx.DeriveHelpers
import Onyx.Harmonix.GH2.PartGuitar (Tempo (..))
import Onyx.MIDI.Read
data BandKeysTrack t = BandKeysTrack
{ keysTempo :: RTB.T t Tempo
, keysIdle :: RTB.T t ()
, keysPlay :: RTB.T t ()
} deriving (Eq, Ord, Show, Generic)
deriving (Semigroup, Monoid, Mergeable) via GenericMerge (BandKeysTrack t)
instance TraverseTrack BandKeysTrack where
traverseTrack fn (BandKeysTrack a b c) = BandKeysTrack
<$> fn a <*> fn b <*> fn c
instance ParseTrack BandKeysTrack where
parseTrack = do
keysTempo <- keysTempo =. command
keysIdle <- keysIdle =. commandMatch ["idle"]
keysPlay <- keysPlay =. commandMatch ["play"]
return BandKeysTrack{..}
|
d553186ff9776a9144a9dd68806a46b4e4e668656c4a7f1ee4b3c00bda0581fe | cosmos72/hyperluminal-mem | struct.lisp | ;; -*- lisp -*-
;; This file is part of Hyperluminal-mem.
Copyright ( c ) 2013 - 2015
;;
;; This library is free software: you can redistribute it and/or
modify it under the terms of the Lisp Lesser General Public License
;; (), known as the LLGPL.
;;
;; This library is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty
;; of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
;; See the Lisp Lesser General Public License for more details.
(in-package :hyperluminal-mem-ffi)
#-abcl
(defmacro ffi-defstruct (name-and-options &body fields)
`(cffi:defcstruct ,name-and-options ,@fields))
| null | https://raw.githubusercontent.com/cosmos72/hyperluminal-mem/29c23361260e3a94fb1e09f3fdeab469b035504d/ffi/struct.lisp | lisp | -*- lisp -*-
This file is part of Hyperluminal-mem.
This library is free software: you can redistribute it and/or
(), known as the LLGPL.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the Lisp Lesser General Public License for more details. |
Copyright ( c ) 2013 - 2015
modify it under the terms of the Lisp Lesser General Public License
(in-package :hyperluminal-mem-ffi)
#-abcl
(defmacro ffi-defstruct (name-and-options &body fields)
`(cffi:defcstruct ,name-and-options ,@fields))
|
cc4693a02a807bce7c6da7f719f04c4e090501a7736e28ffcbf003bd437b67dd | vasilisp/inez | solver.ml | open Core.Std
open Terminology
open Core . Int_replace_polymorphic_compare
let dbg = false
module Make
(S : Imt_intf.S_access)
(I : Id.S) =
struct
open Logic
module Matching = Flat.Matching(M)
module Conv = Flat.Conv(I)(M)
module Linear = Flat.Linear(I)
module P = Pre.Make(I)
type c = I.c
type 't term = (I.c, 't) M.t
type formula = I.c A.t Formula.t
(*
Types come with boilerplate for comparison and sexp conversion.
Type_conv can generate these automatically, but it breaks module
definitions and recursive modules.
*)
let hashable_ivar = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = S.compare_ivar;
sexp_of_t = S.sexp_of_ivar
}
let hashable_bvar = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = S.compare_bvar;
sexp_of_t = S.sexp_of_bvar
}
type fid = I.c Id.Box_arrow.t
with compare, sexp_of
let hashable_fid = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_fid;
sexp_of_t = sexp_of_fid
}
type iid = (I.c, int) Id.t
with compare, sexp_of
let hashable_iid = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_iid;
sexp_of_t = sexp_of_iid
}
type bid = (I.c, bool) Id.t
with compare, sexp_of
let hashable_bid = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_bid;
sexp_of_t = sexp_of_bid
}
type ovar = S.ivar option offset
with compare, sexp_of
type bg_call = S.f * ovar list
with compare, sexp_of
let compare_bg_call =
Tuple2.compare
~cmp1:S.compare_f
~cmp2:(List.compare compare_ovar)
let sexp_of_bg_call =
Tuple2.sexp_of_t S.sexp_of_f (List.sexp_of_t sexp_of_ovar)
let hashable_bg_call = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_bg_call;
sexp_of_t = sexp_of_bg_call;
}
type bg_isum = S.ivar isum
with compare, sexp_of
let hashable_bg_isum = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_bg_isum;
sexp_of_t = sexp_of_bg_isum;
}
let flat_sum_negate (l, x) =
List.map l ~f:(Tuple2.map1 ~f:Int63.neg), Int63.neg x
(* optional var, possibly negated (S_Pos None means true) *)
type xvar = S.bvar option signed
with compare, sexp_of
let xtrue = S_Pos None
let xfalse = S_Neg None
(* axiom-related datatypes *)
type int_id = (I.c, int) Id.t
with compare, sexp_of
type axiom_id = int
type bind_key = int_id list
with compare, sexp_of
type bind_data = (I.c, int) M.t list list
(* context *)
type ctx = {
r_ctx : S.ctx;
r_pre_ctx : P.ctx;
r_ivar_m : (iid, S.ivar) Hashtbl.t;
r_bvar_m : (bid, S.bvar) Hashtbl.t;
r_iid_m : (S.ivar, iid) Hashtbl.t;
r_bid_m : (S.bvar, bid) Hashtbl.t;
r_xvar_m : (P.formula, xvar) Hashtbl.t;
r_fun_m : (fid, S.f) Hashtbl.t;
r_call_m : (bg_call, S.ivar) Hashtbl.t;
r_sum_m : (P.sum, S.ivar iexpr) Hashtbl.t;
r_var_of_sum_m : (bg_isum, S.ivar) Hashtbl.t;
r_ovar_of_iite_m : (P.iite, ovar) Hashtbl.t;
r_patt_m :
(c Id.Box_arrow.t, (axiom_id * c Flat.Box.t) list) Hashtbl.t;
r_bind_m :
(axiom_id, (bind_key, bind_data) Hashtbl.t) Hashtbl.t;
r_axiom_m : (axiom_id, c Axiom.Flat.t) Hashtbl.t;
r_q : P.formula Dequeue.t;
mutable r_ground_l : (I.c, int) M.t list;
mutable r_obj : P.term option;
mutable r_fun_cnt : int;
mutable r_axiom_cnt : int;
mutable r_unsat : bool
}
let make_ctx s = {
r_ctx = s;
r_pre_ctx = P.make_ctx ();
r_ivar_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_iid;
r_bvar_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_bid;
r_iid_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_ivar;
r_bid_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_bvar;
r_xvar_m =
Hashtbl.create () ~size:10240 ~hashable:P.hashable_formula;
r_fun_m =
Hashtbl.create () ~size:512 ~hashable:hashable_fid;
r_call_m =
Hashtbl.create () ~size:2048 ~hashable:hashable_bg_call;
r_sum_m =
Hashtbl.create () ~size:2048 ~hashable:P.hashable_sum;
r_var_of_sum_m =
Hashtbl.create () ~size:2048 ~hashable:hashable_bg_isum;
r_ovar_of_iite_m =
Hashtbl.create () ~size:2048 ~hashable:P.hashable_iite;
r_axiom_m = Hashtbl.Poly.create () ~size:512;
r_patt_m = Hashtbl.Poly.create () ~size:1024;
r_bind_m = Hashtbl.Poly.create () ~size:4096;
r_q = Dequeue.create () ~initial_length:63;
r_ground_l = [];
r_obj = None;
r_fun_cnt = 0;
r_axiom_cnt = 0;
r_unsat = false;
}
let get_f ({r_ctx; r_fun_m; r_fun_cnt} as r)
(Id.Box_arrow.Box id' as id) =
let default =
let t = I.type_of_t id' in
fun () ->
let s = Printf.sprintf "f_%d" r_fun_cnt in
r.r_fun_cnt <- r.r_fun_cnt + 1;
S.new_f r_ctx s (Type.count_arrows t) in
Hashtbl.find_or_add r_fun_m id ~default
let get_axiom_id ({r_axiom_cnt} as r) =
r.r_axiom_cnt <- r.r_axiom_cnt + 1;
r_axiom_cnt
let ivar_of_iid {r_ctx; r_ivar_m; r_iid_m} x =
let default () =
let v = S.new_ivar r_ctx in
Hashtbl.replace r_iid_m v x; v in
Hashtbl.find_or_add r_ivar_m x ~default
let bvar_of_bid {r_ctx; r_bvar_m; r_bid_m} x =
let default () =
let v = S.new_bvar r_ctx in
Hashtbl.replace r_bid_m v x; v in
Hashtbl.find_or_add r_bvar_m x ~default
let iid_of_ivar {r_iid_m} = Hashtbl.find r_iid_m
let bid_of_bvar {r_bid_m} = Hashtbl.find r_bid_m
(* linearizing terms and formulas: utilities before we get into the
mutually recursive part *)
let snot = function
| S_Pos x -> S_Neg x
| S_Neg x -> S_Pos x
let negate_isum =
List.map ~f:(Tuple2.map1 ~f:Int63.neg)
(* linearizing terms and formulas: mutual recursion, because terms
contain formulas and vice versa *)
let rec iexpr_of_sum ({r_sum_m} as r) (l, o) =
let l, o' =
let default () =
let f (l, o) (c, t) =
match ovar_of_flat_term_base r t with
| Some v, x ->
(c, v) :: l, Int63.(o + c * x)
| None, x ->
l, Int63.(o + c * x)
and init = [], Int63.zero in
List.fold_left ~init ~f l in
Hashtbl.find_or_add r_sum_m l ~default in
l, Int63.(o' + o)
and iexpr_of_flat_term r = function
| P.G_Sum s ->
iexpr_of_sum r s
| P.G_Base b ->
match ovar_of_flat_term_base r b with
| Some v, x ->
[Int63.one, v], x
| None, x ->
[], x
and blast_le ?v ({r_ctx} as r) s =
let l, o = iexpr_of_sum r s
and v = match v with Some v -> v | _ -> S.new_bvar r_ctx in
S.add_indicator r_ctx (S_Pos v) l Int63.(neg o);
S.add_indicator r_ctx (S_Neg v) (negate_isum l) Int63.(o - one);
S_Pos (Some v)
and blast_eq ({r_ctx} as r) s =
let l, o = iexpr_of_sum r s in
let l_neg = negate_isum l in
let b = S.new_bvar r_ctx in
let b_lt = S_Pos (S.new_bvar r_ctx)
and b_gt = S_Pos (S.new_bvar r_ctx)
and b_eq = S_Pos b in
S.add_indicator r_ctx b_eq l (Int63.neg o);
S.add_indicator r_ctx b_eq l_neg o;
S.add_indicator r_ctx b_lt l Int63.(neg o - one);
S.add_indicator r_ctx b_gt l_neg Int63.(o - one);
S.add_clause r_ctx [b_eq; b_lt; b_gt];
S_Pos (Some b)
and var_of_app ?lb ?ub ({r_ctx; r_call_m} as r) f_id l =
let f = get_f r f_id
and l = List.map l ~f:(ovar_of_ibeither r) in
let default () =
let v = S.new_ivar r_ctx ?lb ?ub in
S.add_call r_ctx (Some v, Int63.zero) f l;
v in
Hashtbl.find_or_add r_call_m (f, l) ~default
and var_of_bool_app r f_id l =
(let lb = Int63.zero and ub = Int63.one in
var_of_app ~lb ~ub r f_id l) |>
S.bvar_of_ivar
and blast_ite_branch ({r_ctx} as r) xv v e =
let l, o = iexpr_of_flat_term r e in
let l = (Int63.minus_one, v) :: l in
S.add_indicator r_ctx xv l (Int63.neg o);
S.add_indicator r_ctx xv (negate_isum l) o
and ovar_of_ite ({r_ctx; r_ovar_of_iite_m} as r) ((g, s, t) as i) =
let default () =
match xvar_of_formula_doit r g with
| S_Pos None ->
ovar_of_term r s
| S_Neg None ->
ovar_of_term r t
| S_Pos (Some bv) ->
let v = S.new_ivar r_ctx in
blast_ite_branch r (S_Pos bv) v s;
blast_ite_branch r (S_Neg bv) v t;
Some v, Int63.zero
| S_Neg (Some bv) ->
let v = S.new_ivar r_ctx in
blast_ite_branch r (S_Neg bv) v s;
blast_ite_branch r (S_Pos bv) v t;
Some v, Int63.zero in
Hashtbl.find_or_add r_ovar_of_iite_m i ~default
and ovar_of_flat_term_base r = function
| P.B_Var v ->
Some (ivar_of_iid r v), Int63.zero
| P.B_Formula g ->
ovar_of_formula r g
| P.B_App (f_id, l) ->
Some (var_of_app r f_id l), Int63.zero
| P.B_Ite i ->
ovar_of_ite r i
and ovar_of_sum {r_ctx; r_var_of_sum_m} = function
| [], o ->
None, o
| [c, x], o when Int63.(c = one) ->
Some x, o
| l, o ->
let v =
let default () =
let v = S.new_ivar r_ctx in
S.add_eq r_ctx ((Int63.minus_one, v) :: l) Int63.zero;
v in
Hashtbl.find_or_add r_var_of_sum_m l ~default in
Some v, o
and ovar_of_term r = function
| P.G_Base b ->
ovar_of_flat_term_base r b
| P.G_Sum s ->
iexpr_of_sum r s |> ovar_of_sum r
and ovar_of_formula ({r_ctx} as r) g =
match xvar_of_formula_doit r g with
| S_Pos (Some v) ->
Some (S.ivar_of_bvar v), Int63.zero
| S_Pos None ->
None, Int63.one
| S_Neg v ->
(let f v = S.ivar_of_bvar (S.negate_bvar r_ctx v) in
Option.map v ~f), Int63.zero
and ovar_of_ibeither ({r_ctx} as r) = function
| H_Int (P.G_Base b) ->
ovar_of_flat_term_base r b
| H_Int (P.G_Sum s) ->
iexpr_of_sum r s |> ovar_of_sum r
| H_Bool g ->
ovar_of_formula r g
and blast_atom ({r_ctx} as r) = function
| P.G_Base t, O'_Le ->
blast_le r ([Int63.one, t], Int63.zero)
| P.G_Sum s, O'_Le ->
blast_le r s
| P.G_Base t, O'_Eq ->
blast_eq r ([Int63.one, t], Int63.zero)
| P.G_Sum s, O'_Eq ->
blast_eq r s
and blast_conjunction_map r acc = function
| g :: tail ->
(match xvar_of_formula_doit r g with
| S_Pos (Some x) ->
blast_conjunction_map r (S_Pos x :: acc) tail
| S_Pos None ->
blast_conjunction_map r acc tail
| S_Neg (Some x) ->
blast_conjunction_map r (S_Neg x :: acc) tail
| S_Neg None ->
None)
| [] ->
Some acc
and blast_conjunction_reduce {r_ctx} = function
| [] ->
xtrue
| [S_Pos x] ->
S_Pos (Some x)
| [S_Neg x] ->
S_Neg (Some x)
| l ->
let rval = S.new_bvar r_ctx in
(let f v = S.add_clause r_ctx [S_Neg rval; v] in
List.iter l ~f);
S.add_clause r_ctx (S_Pos rval :: List.map l ~f:snot);
S_Pos (Some rval)
and blast_conjunction r l =
blast_conjunction_map r [] l |>
(let f = blast_conjunction_reduce r and default = xfalse in
Option.value_map ~f ~default)
and blast_formula r = function
| P.U_Not _
| P.U_Ite (_, _, _) ->
raise (Unreachable.Exn _here_)
| P.U_Var v ->
S_Pos (Some (bvar_of_bid r v))
| P.U_App (f_id, l) ->
S_Pos (Some (var_of_bool_app r f_id l))
| P.U_Atom (t, o) ->
blast_atom r (t, o)
| P.U_And l ->
blast_conjunction r l
and xvar_of_formula_doit ({r_ctx; r_xvar_m} as r) = function
| P.U_Not g ->
snot (xvar_of_formula_doit r g)
| P.U_Ite (q, g, h) ->
let v = P.ff_ite q g h |> xvar_of_formula_doit r in
(match v with
| S_Pos (Some v) | S_Neg (Some v) ->
S.set_bvar_priority r_ctx v 20;
| _ ->
());
v
| g ->
let default () = blast_formula r g in
Hashtbl.find_or_add r_xvar_m g ~default
let assert_ivar_equal_constant {r_ctx} v c =
S.add_eq r_ctx [Int63.one, v] c
let assert_ivar_le_constant {r_ctx} v c =
S.add_le r_ctx [Int63.one, v] c
let assert_bvar_equal_constant {r_ctx} v c =
let v = S.ivar_of_bvar v
and c = Int63.(if c then one else zero) in
S.add_eq r_ctx [Int63.one, v] c
let finally_assert_unit ({r_ctx} as r) = function
| S_Pos (Some v) ->
assert_bvar_equal_constant r v true
| S_Neg (Some v) ->
assert_bvar_equal_constant r v false
| S_Pos None ->
()
| S_Neg None ->
r.r_unsat <- true
let rec finally_assert_formula ({r_ctx} as r) = function
| P.U_And l ->
List.iter l ~f:(finally_assert_formula r)
| P.U_Not (P.U_And l) ->
let f = function
| [] ->
r.r_unsat <- true
| [S_Pos v] ->
assert_bvar_equal_constant r v false
| [S_Neg v] ->
assert_bvar_equal_constant r v true
| l ->
(let f = snot in List.map l ~f) |> S.add_clause r_ctx in
Option.iter (blast_conjunction_map r [] l) ~f
| P.U_Var v ->
assert_bvar_equal_constant r (bvar_of_bid r v) true
| P.U_App (f_id, l) ->
let v = var_of_bool_app r f_id l in
assert_bvar_equal_constant r v true
| P.U_Atom (P.G_Sum s, O'_Le) ->
let l, o = iexpr_of_sum r s in
S.add_le r_ctx l (Int63.neg o)
| P.U_Atom (P.G_Sum s, O'_Eq) ->
let l, o = iexpr_of_sum r s in
S.add_eq r_ctx l (Int63.neg o)
| P.U_Atom (P.G_Base a, O'_Le) ->
(match ovar_of_flat_term_base r a with
| None, o when Int63.(o > zero) ->
r.r_unsat <- true
| None, _ ->
()
| Some v, o ->
assert_ivar_le_constant r v (Int63.neg o))
| P.U_Atom (P.G_Base a, O'_Eq) ->
(match ovar_of_flat_term_base r a with
| None, o when Int63.(o = zero) ->
()
| None, _ ->
r.r_unsat <- true
| Some v, o ->
assert_ivar_equal_constant r v (Int63.neg o))
| g ->
xvar_of_formula_doit r g |> finally_assert_unit r
let negate_bvar {r_ctx} =
S.negate_bvar r_ctx
let xvar_of_formula ({r_pre_ctx} as r) g =
let g = P.flatten_formula r_pre_ctx g in
lazy (xvar_of_formula_doit r g)
let xvar_of_term ({r_pre_ctx} as r) m =
let m = P.flatten_bool_term r_pre_ctx m in
lazy (xvar_of_formula_doit r m)
let ovar_of_term ({r_pre_ctx} as r) m =
let m = P.flatten_int_term r_pre_ctx m in
lazy (ovar_of_term r m)
let bvar_of_id = bvar_of_bid
let write_bg_ctx {r_ctx} =
S.write_ctx r_ctx
let bg_assert_all_cached ({r_q} as r) =
Dequeue.iter r_q ~f:(finally_assert_formula r);
Dequeue.clear r_q
let add_objective ({r_obj; r_pre_ctx} as r) o =
match r_obj with
| None ->
let m = P.flatten_int_term r_pre_ctx o in
r.r_obj <- Some m; `Ok
| Some _ ->
`Duplicate
let deref_int {r_ctx; r_ivar_m} id =
Option.(Hashtbl.find r_ivar_m id >>= S.ideref r_ctx)
let deref_bool {r_ctx; r_bvar_m} id =
Option.(Hashtbl.find r_bvar_m id >>= S.bderef r_ctx)
(* local axioms implementation *)
let bind_for_axiom {r_axiom_m; r_bind_m} axiom_id bindings =
let key, data = List.unzip bindings
and axiom = Hashtbl.find r_axiom_m axiom_id in
let q, _, _ = Option.value_exn axiom ~here:_here_ in
assert
(let f id =
let f id' = compare_int_id id id' = 0 in
List.exists q ~f in
List.for_all key ~f);
let h =
let default () = Hashtbl.Poly.create () ~size:128 in
Hashtbl.find_or_add r_bind_m axiom_id ~default
and f = function
| Some l ->
Some
(if let f = (=) data in List.exists l ~f then
l
else
data :: l)
| None ->
Some [data] in
Hashtbl.change h key f
let register_app_for_axioms ({r_patt_m} as r) (m : (c, int) M.t) =
match m with
| M.M_App (a, b) ->
Option.value_exn ~here:_here_ (M.fun_id_of_app m) |>
Hashtbl.find r_patt_m |>
let f (axiom_id, Flat.Box.Box pattern) =
let f l =
let f = function
| `Bool (_, _) ->
FIXME : let 's deal with integers first
raise (Unreachable.Exn _here_)
| `Int (id, m) ->
id, m
and f' =
let cmp (id1, _) (id2, _) =
compare_int_id id1 id2 in
List.sort ~cmp in
List.map l ~f |> f' |> bind_for_axiom r axiom_id in
Matching.do_for_match m ~pattern ~f in
let f = List.iter ~f in
Option.iter ~f
| _ ->
raise (Unreachable.Exn _here_)
let rec register_apps_term :
type s. ctx -> (I.c, s) M.t -> unit =
fun r -> function
| M.M_Int _ ->
()
| M.M_Var _ ->
()
| M.M_Bool g ->
register_apps_formula r g
| M.M_Sum (a, b) ->
register_apps_term r a; register_apps_term r b
| M.M_Prod (_, a) ->
register_apps_term r a
| M.M_Ite (g, a, b) ->
register_apps_formula r g;
register_apps_term r a;
register_apps_term r b
| M.M_App (a, b) as m ->
(match M.type_of_t m with
| Type.Y_Int ->
register_app_for_axioms r m
| _ ->
());
register_apps_term r a;
register_apps_term r b
and register_apps_formula r =
let f a ~polarity =
match a with
| A.A_Bool m ->
register_apps_term r m
| A.A_Le m | A.A_Eq m ->
register_apps_term r m
and polarity = `Both in
Formula.iter_atoms ~f ~polarity
let register_axiom_terms {r_patt_m} id axiom =
let open Flat in
let f = function
| M_Var _ ->
()
| M_App (_, _) as m ->
let key = Option.value_exn (fun_id_of_app m) ~here:_here_
and data = id, Flat.Box.Box m in
Hashtbl.add_multi r_patt_m ~key ~data in
Axiom.Flat.iter_subterms axiom ~f
let instantiate r (l, o) ~bindings =
let f (l, s) (c, m) =
Conv.term_of_t m ~bindings |>
ovar_of_term r |>
Lazy.force |>
function
| Some v, o ->
(c, v) :: l, Int63.(s + c * o)
| None, o ->
l, Int63.(s + c * o)
and init = [], o in
List.fold_left l ~f ~init
let bindings_of_substitution =
let f x = `Int x in
List.map ~f
let rec iter_substitutions r axiom_id h keys ~f ~bound =
match keys with
| a :: d ->
let l = Option.value_exn (Hashtbl.find h a) ~here:_here_
and f a' =
let bound =
Option.value_exn (List.zip a a') ~here:_here_ |>
List.append bound in
iter_substitutions r axiom_id h d ~f ~bound in
List.iter l ~f
| [] ->
f (List.rev bound)
let iter_substitutions ({r_axiom_m; r_bind_m} as r) axiom_id ~f =
let f h =
let bound = [] in
iter_substitutions r axiom_id h (Hashtbl.keys h) ~f ~bound in
Option.iter (Hashtbl.find r_bind_m axiom_id) ~f
let encode_all_axiom_instances ({r_ctx; r_axiom_m} as r) =
let cnt = ref 0 in
let f ~key ~data:(q, l, c) =
let f s =
let bindings = bindings_of_substitution s in
let f (a, b) =
let f x =
instantiate r ~bindings x |> ovar_of_sum r in
let v_a, o_a = f a in
f b, (v_a, Int63.(o_a - one)) in
let l = List.map l ~f
and c =
instantiate r ~bindings c |> ovar_of_sum r in
let l = (c, (None, Int63.zero)) :: l in
S.add_diffs_disjunction r_ctx l;
incr cnt in
iter_substitutions r key ~f in
Hashtbl.iter r_axiom_m ~f;
if dbg then Printf.printf "[INFO] %d axiom instances\n%!" !cnt
let cut_of_term m ~bindings =
let open Option in
let f acc c m =
acc >>= (fun (l, bindings) ->
Conv.t_of_term m ~bindings >>| (fun (m, bindings) ->
(c, m) :: l, bindings))
and f_offset acc o =
acc >>| (fun (l, bindings) -> (l, o), bindings)
and init = Some ([], bindings)
and factor = Int63.one in
M.fold_sum_terms m ~f ~f_offset ~init ~factor
let negate_cut (l, o) =
let f (c, x) = Int63.(~-) c, x
and o = Int63.(~-) o in
List.map l ~f, o
let linearize_iexpr (l, o) ~quantified ~map ~copies =
let l, map, copies =
let f (l, map, copies) (c, under) =
let under, map, copies =
Linear.linearize under ~quantified ~under ~map ~copies in
(c, under) :: l, map, copies
and init = [], map, copies in
List.fold_left l ~init ~f in
let l = List.rev l in
(l, o), map, copies
let linearize_axiom (quantified, h, cut) =
let map = Map.Poly.empty and copies = [] in
let h, map, copies =
let f (l, map, copies) (a, b) =
let a, map, copies =
linearize_iexpr a ~quantified ~map ~copies in
let b, map, copies =
linearize_iexpr b ~quantified ~map ~copies in
(a, b) :: l, map, copies
and init = [], map, copies in
List.fold_left h ~f ~init in
let cut, map, copies =
linearize_iexpr cut ~quantified ~map ~copies in
let h =
let f (a, b) =
let open Int63 in
([one, Flat.M_Var a], zero),
([one, Flat.M_Var b], zero) in
List.rev_map_append copies (List.rev_map_append copies h ~f)
~f:(Fn.compose f Tuple.T2.swap)
and quantified =
let f (id, _) = id in
List.rev_map_append copies quantified ~f in
quantified, h, cut
let flatten_axiom (q, (l, (c1, c2, op))) =
let open Option in (
let f acc (m1, m2, op) =
acc >>= (fun (l, bindings) ->
Conv.sum_of_term m1 ~bindings >>= (fun (s1, bindings) ->
Conv.sum_of_term m2 ~bindings >>| (fun (s2, bindings) ->
(match op with
| Terminology.O'_Le ->
(s1, s2) :: l
| Terminology.O'_Eq ->
(s1, s2) :: (s2, s1) :: l), bindings)))
and init = Some ([], []) in
List.fold_left l ~init ~f) >>= (fun (init, bindings) ->
M.(c1 - c2) |>
cut_of_term ~bindings >>| (fun (c, bindings) ->
let q =
let f = Tuple.T2.get1 in
List.rev_map_append bindings q ~f
and h =
let f acc (id, def) =
let e = Int63.([one, Flat.M_Var id], zero) in
(e, def) :: (def, e) :: acc in
List.fold_left bindings ~f ~init in
(match op with
| Terminology.O'_Le ->
[q, h, c]
| Terminology.O'_Eq ->
[q, h, c; q, h, negate_cut c])))
let rec int_args :
type s t .
(I.c, s -> t) M.t -> acc:(I.c, int) M.t list ->
(I.c, int) M.t list =
fun m ~acc ->
match m with
| M.M_App (f, x) ->
(match M.type_of_t x with
| Type.Y_Int ->
let acc = x :: acc in
int_args f ~acc
| _ ->
int_args f ~acc)
| M.M_Var _ ->
acc
let rec maximal_ground_subterms :
type s . ctx -> I.c Axiom.quantified list ->
(I.c, s) M.t -> acc:(I.c, int) M.t list ->
bool * (I.c, int) M.t list =
fun r q m ~acc ->
match m with
| M.M_Bool _ ->
false, acc
| M.M_Ite _ ->
false, acc
| M.M_Int _ ->
true, acc
| M.M_Sum (a, b) ->
let a_b, acc = maximal_ground_subterms r q a ~acc in
let b_b, acc = maximal_ground_subterms r q b ~acc in
(match a_b, b_b with
| true, true ->
true, acc
| true, false ->
false, a :: acc
| false, true ->
false, b :: acc
| _, _ ->
false, acc)
| M.M_App (a, b) ->
let a_b, acc = maximal_ground_subterms r q a ~acc in
let b_b, acc = maximal_ground_subterms r q b ~acc in
(match a_b, b_b with
| true, true ->
true, acc
| false, true ->
false,
(match M.type_of_t b with
| Type.Y_Int ->
b :: acc
| _ ->
acc)
| true, false ->
false, int_args a ~acc
| _, _ ->
false, acc)
| M.M_Prod (_, a) ->
maximal_ground_subterms r q a ~acc
| M.M_Var v ->
(match Id.type_of_t v with
| Type.Y_Int ->
let f = (=) v in
not (List.exists q ~f), acc
| Type.Y_Int_Arrow _ ->
true, acc
| Type.Y_Bool_Arrow _ ->
true, acc
| _ ->
false, acc)
let record_axiom_ground_terms r ((q, _) as axiom) =
let l =
let f acc m =
let b, acc = maximal_ground_subterms r q m ~acc in
if b then m :: acc else acc
and init = [] in
Axiom.X.fold_terms axiom ~f ~init in
let l =
let f = function
| M.M_App (_, _) ->
true
| _ ->
false in
List.filter l ~f in
r.r_ground_l <- List.append l r.r_ground_l
let assert_axiom ({r_axiom_m} as r) axiom =
record_axiom_ground_terms r axiom;
match flatten_axiom axiom with
| Some axioms ->
let f axiom =
let axiom = linearize_axiom axiom in
let id = get_axiom_id r in
Hashtbl.replace r_axiom_m id axiom;
register_axiom_terms r id axiom in
List.iter axioms ~f; `Ok
| None ->
`Unsupported
let assert_formula ({r_pre_ctx; r_q} as r) g =
register_apps_formula r g;
P.flatten_formula r_pre_ctx g |> Dequeue.enqueue_back r_q
let solve ({r_ctx; r_obj; r_ground_l} as r) =
bg_assert_all_cached r;
(let f = register_apps_term r in
List.iter r_ground_l ~f);
encode_all_axiom_instances r;
match r_obj, r.r_unsat with
| _, true ->
R_Unsat
| Some o, false ->
let l, _ = iexpr_of_flat_term r o in
(match S.add_objective r_ctx l with
| `Duplicate ->
raise (Unreachable.Exn _here_)
| `Ok ->
S.solve r_ctx)
| None, false ->
S.solve r_ctx
end
| null | https://raw.githubusercontent.com/vasilisp/inez/3bbbbb82a12918c1557f5fb0b49a8c73ab8d6da1/frontend/solver.ml | ocaml |
Types come with boilerplate for comparison and sexp conversion.
Type_conv can generate these automatically, but it breaks module
definitions and recursive modules.
optional var, possibly negated (S_Pos None means true)
axiom-related datatypes
context
linearizing terms and formulas: utilities before we get into the
mutually recursive part
linearizing terms and formulas: mutual recursion, because terms
contain formulas and vice versa
local axioms implementation | open Core.Std
open Terminology
open Core . Int_replace_polymorphic_compare
let dbg = false
module Make
(S : Imt_intf.S_access)
(I : Id.S) =
struct
open Logic
module Matching = Flat.Matching(M)
module Conv = Flat.Conv(I)(M)
module Linear = Flat.Linear(I)
module P = Pre.Make(I)
type c = I.c
type 't term = (I.c, 't) M.t
type formula = I.c A.t Formula.t
let hashable_ivar = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = S.compare_ivar;
sexp_of_t = S.sexp_of_ivar
}
let hashable_bvar = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = S.compare_bvar;
sexp_of_t = S.sexp_of_bvar
}
type fid = I.c Id.Box_arrow.t
with compare, sexp_of
let hashable_fid = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_fid;
sexp_of_t = sexp_of_fid
}
type iid = (I.c, int) Id.t
with compare, sexp_of
let hashable_iid = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_iid;
sexp_of_t = sexp_of_iid
}
type bid = (I.c, bool) Id.t
with compare, sexp_of
let hashable_bid = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_bid;
sexp_of_t = sexp_of_bid
}
type ovar = S.ivar option offset
with compare, sexp_of
type bg_call = S.f * ovar list
with compare, sexp_of
let compare_bg_call =
Tuple2.compare
~cmp1:S.compare_f
~cmp2:(List.compare compare_ovar)
let sexp_of_bg_call =
Tuple2.sexp_of_t S.sexp_of_f (List.sexp_of_t sexp_of_ovar)
let hashable_bg_call = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_bg_call;
sexp_of_t = sexp_of_bg_call;
}
type bg_isum = S.ivar isum
with compare, sexp_of
let hashable_bg_isum = {
Hashtbl.Hashable.
hash = Hashtbl.hash;
compare = compare_bg_isum;
sexp_of_t = sexp_of_bg_isum;
}
let flat_sum_negate (l, x) =
List.map l ~f:(Tuple2.map1 ~f:Int63.neg), Int63.neg x
type xvar = S.bvar option signed
with compare, sexp_of
let xtrue = S_Pos None
let xfalse = S_Neg None
type int_id = (I.c, int) Id.t
with compare, sexp_of
type axiom_id = int
type bind_key = int_id list
with compare, sexp_of
type bind_data = (I.c, int) M.t list list
type ctx = {
r_ctx : S.ctx;
r_pre_ctx : P.ctx;
r_ivar_m : (iid, S.ivar) Hashtbl.t;
r_bvar_m : (bid, S.bvar) Hashtbl.t;
r_iid_m : (S.ivar, iid) Hashtbl.t;
r_bid_m : (S.bvar, bid) Hashtbl.t;
r_xvar_m : (P.formula, xvar) Hashtbl.t;
r_fun_m : (fid, S.f) Hashtbl.t;
r_call_m : (bg_call, S.ivar) Hashtbl.t;
r_sum_m : (P.sum, S.ivar iexpr) Hashtbl.t;
r_var_of_sum_m : (bg_isum, S.ivar) Hashtbl.t;
r_ovar_of_iite_m : (P.iite, ovar) Hashtbl.t;
r_patt_m :
(c Id.Box_arrow.t, (axiom_id * c Flat.Box.t) list) Hashtbl.t;
r_bind_m :
(axiom_id, (bind_key, bind_data) Hashtbl.t) Hashtbl.t;
r_axiom_m : (axiom_id, c Axiom.Flat.t) Hashtbl.t;
r_q : P.formula Dequeue.t;
mutable r_ground_l : (I.c, int) M.t list;
mutable r_obj : P.term option;
mutable r_fun_cnt : int;
mutable r_axiom_cnt : int;
mutable r_unsat : bool
}
let make_ctx s = {
r_ctx = s;
r_pre_ctx = P.make_ctx ();
r_ivar_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_iid;
r_bvar_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_bid;
r_iid_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_ivar;
r_bid_m =
Hashtbl.create () ~size:10240 ~hashable:hashable_bvar;
r_xvar_m =
Hashtbl.create () ~size:10240 ~hashable:P.hashable_formula;
r_fun_m =
Hashtbl.create () ~size:512 ~hashable:hashable_fid;
r_call_m =
Hashtbl.create () ~size:2048 ~hashable:hashable_bg_call;
r_sum_m =
Hashtbl.create () ~size:2048 ~hashable:P.hashable_sum;
r_var_of_sum_m =
Hashtbl.create () ~size:2048 ~hashable:hashable_bg_isum;
r_ovar_of_iite_m =
Hashtbl.create () ~size:2048 ~hashable:P.hashable_iite;
r_axiom_m = Hashtbl.Poly.create () ~size:512;
r_patt_m = Hashtbl.Poly.create () ~size:1024;
r_bind_m = Hashtbl.Poly.create () ~size:4096;
r_q = Dequeue.create () ~initial_length:63;
r_ground_l = [];
r_obj = None;
r_fun_cnt = 0;
r_axiom_cnt = 0;
r_unsat = false;
}
let get_f ({r_ctx; r_fun_m; r_fun_cnt} as r)
(Id.Box_arrow.Box id' as id) =
let default =
let t = I.type_of_t id' in
fun () ->
let s = Printf.sprintf "f_%d" r_fun_cnt in
r.r_fun_cnt <- r.r_fun_cnt + 1;
S.new_f r_ctx s (Type.count_arrows t) in
Hashtbl.find_or_add r_fun_m id ~default
let get_axiom_id ({r_axiom_cnt} as r) =
r.r_axiom_cnt <- r.r_axiom_cnt + 1;
r_axiom_cnt
let ivar_of_iid {r_ctx; r_ivar_m; r_iid_m} x =
let default () =
let v = S.new_ivar r_ctx in
Hashtbl.replace r_iid_m v x; v in
Hashtbl.find_or_add r_ivar_m x ~default
let bvar_of_bid {r_ctx; r_bvar_m; r_bid_m} x =
let default () =
let v = S.new_bvar r_ctx in
Hashtbl.replace r_bid_m v x; v in
Hashtbl.find_or_add r_bvar_m x ~default
let iid_of_ivar {r_iid_m} = Hashtbl.find r_iid_m
let bid_of_bvar {r_bid_m} = Hashtbl.find r_bid_m
let snot = function
| S_Pos x -> S_Neg x
| S_Neg x -> S_Pos x
let negate_isum =
List.map ~f:(Tuple2.map1 ~f:Int63.neg)
let rec iexpr_of_sum ({r_sum_m} as r) (l, o) =
let l, o' =
let default () =
let f (l, o) (c, t) =
match ovar_of_flat_term_base r t with
| Some v, x ->
(c, v) :: l, Int63.(o + c * x)
| None, x ->
l, Int63.(o + c * x)
and init = [], Int63.zero in
List.fold_left ~init ~f l in
Hashtbl.find_or_add r_sum_m l ~default in
l, Int63.(o' + o)
and iexpr_of_flat_term r = function
| P.G_Sum s ->
iexpr_of_sum r s
| P.G_Base b ->
match ovar_of_flat_term_base r b with
| Some v, x ->
[Int63.one, v], x
| None, x ->
[], x
and blast_le ?v ({r_ctx} as r) s =
let l, o = iexpr_of_sum r s
and v = match v with Some v -> v | _ -> S.new_bvar r_ctx in
S.add_indicator r_ctx (S_Pos v) l Int63.(neg o);
S.add_indicator r_ctx (S_Neg v) (negate_isum l) Int63.(o - one);
S_Pos (Some v)
and blast_eq ({r_ctx} as r) s =
let l, o = iexpr_of_sum r s in
let l_neg = negate_isum l in
let b = S.new_bvar r_ctx in
let b_lt = S_Pos (S.new_bvar r_ctx)
and b_gt = S_Pos (S.new_bvar r_ctx)
and b_eq = S_Pos b in
S.add_indicator r_ctx b_eq l (Int63.neg o);
S.add_indicator r_ctx b_eq l_neg o;
S.add_indicator r_ctx b_lt l Int63.(neg o - one);
S.add_indicator r_ctx b_gt l_neg Int63.(o - one);
S.add_clause r_ctx [b_eq; b_lt; b_gt];
S_Pos (Some b)
and var_of_app ?lb ?ub ({r_ctx; r_call_m} as r) f_id l =
let f = get_f r f_id
and l = List.map l ~f:(ovar_of_ibeither r) in
let default () =
let v = S.new_ivar r_ctx ?lb ?ub in
S.add_call r_ctx (Some v, Int63.zero) f l;
v in
Hashtbl.find_or_add r_call_m (f, l) ~default
and var_of_bool_app r f_id l =
(let lb = Int63.zero and ub = Int63.one in
var_of_app ~lb ~ub r f_id l) |>
S.bvar_of_ivar
and blast_ite_branch ({r_ctx} as r) xv v e =
let l, o = iexpr_of_flat_term r e in
let l = (Int63.minus_one, v) :: l in
S.add_indicator r_ctx xv l (Int63.neg o);
S.add_indicator r_ctx xv (negate_isum l) o
and ovar_of_ite ({r_ctx; r_ovar_of_iite_m} as r) ((g, s, t) as i) =
let default () =
match xvar_of_formula_doit r g with
| S_Pos None ->
ovar_of_term r s
| S_Neg None ->
ovar_of_term r t
| S_Pos (Some bv) ->
let v = S.new_ivar r_ctx in
blast_ite_branch r (S_Pos bv) v s;
blast_ite_branch r (S_Neg bv) v t;
Some v, Int63.zero
| S_Neg (Some bv) ->
let v = S.new_ivar r_ctx in
blast_ite_branch r (S_Neg bv) v s;
blast_ite_branch r (S_Pos bv) v t;
Some v, Int63.zero in
Hashtbl.find_or_add r_ovar_of_iite_m i ~default
and ovar_of_flat_term_base r = function
| P.B_Var v ->
Some (ivar_of_iid r v), Int63.zero
| P.B_Formula g ->
ovar_of_formula r g
| P.B_App (f_id, l) ->
Some (var_of_app r f_id l), Int63.zero
| P.B_Ite i ->
ovar_of_ite r i
and ovar_of_sum {r_ctx; r_var_of_sum_m} = function
| [], o ->
None, o
| [c, x], o when Int63.(c = one) ->
Some x, o
| l, o ->
let v =
let default () =
let v = S.new_ivar r_ctx in
S.add_eq r_ctx ((Int63.minus_one, v) :: l) Int63.zero;
v in
Hashtbl.find_or_add r_var_of_sum_m l ~default in
Some v, o
and ovar_of_term r = function
| P.G_Base b ->
ovar_of_flat_term_base r b
| P.G_Sum s ->
iexpr_of_sum r s |> ovar_of_sum r
and ovar_of_formula ({r_ctx} as r) g =
match xvar_of_formula_doit r g with
| S_Pos (Some v) ->
Some (S.ivar_of_bvar v), Int63.zero
| S_Pos None ->
None, Int63.one
| S_Neg v ->
(let f v = S.ivar_of_bvar (S.negate_bvar r_ctx v) in
Option.map v ~f), Int63.zero
and ovar_of_ibeither ({r_ctx} as r) = function
| H_Int (P.G_Base b) ->
ovar_of_flat_term_base r b
| H_Int (P.G_Sum s) ->
iexpr_of_sum r s |> ovar_of_sum r
| H_Bool g ->
ovar_of_formula r g
and blast_atom ({r_ctx} as r) = function
| P.G_Base t, O'_Le ->
blast_le r ([Int63.one, t], Int63.zero)
| P.G_Sum s, O'_Le ->
blast_le r s
| P.G_Base t, O'_Eq ->
blast_eq r ([Int63.one, t], Int63.zero)
| P.G_Sum s, O'_Eq ->
blast_eq r s
and blast_conjunction_map r acc = function
| g :: tail ->
(match xvar_of_formula_doit r g with
| S_Pos (Some x) ->
blast_conjunction_map r (S_Pos x :: acc) tail
| S_Pos None ->
blast_conjunction_map r acc tail
| S_Neg (Some x) ->
blast_conjunction_map r (S_Neg x :: acc) tail
| S_Neg None ->
None)
| [] ->
Some acc
and blast_conjunction_reduce {r_ctx} = function
| [] ->
xtrue
| [S_Pos x] ->
S_Pos (Some x)
| [S_Neg x] ->
S_Neg (Some x)
| l ->
let rval = S.new_bvar r_ctx in
(let f v = S.add_clause r_ctx [S_Neg rval; v] in
List.iter l ~f);
S.add_clause r_ctx (S_Pos rval :: List.map l ~f:snot);
S_Pos (Some rval)
and blast_conjunction r l =
blast_conjunction_map r [] l |>
(let f = blast_conjunction_reduce r and default = xfalse in
Option.value_map ~f ~default)
and blast_formula r = function
| P.U_Not _
| P.U_Ite (_, _, _) ->
raise (Unreachable.Exn _here_)
| P.U_Var v ->
S_Pos (Some (bvar_of_bid r v))
| P.U_App (f_id, l) ->
S_Pos (Some (var_of_bool_app r f_id l))
| P.U_Atom (t, o) ->
blast_atom r (t, o)
| P.U_And l ->
blast_conjunction r l
and xvar_of_formula_doit ({r_ctx; r_xvar_m} as r) = function
| P.U_Not g ->
snot (xvar_of_formula_doit r g)
| P.U_Ite (q, g, h) ->
let v = P.ff_ite q g h |> xvar_of_formula_doit r in
(match v with
| S_Pos (Some v) | S_Neg (Some v) ->
S.set_bvar_priority r_ctx v 20;
| _ ->
());
v
| g ->
let default () = blast_formula r g in
Hashtbl.find_or_add r_xvar_m g ~default
let assert_ivar_equal_constant {r_ctx} v c =
S.add_eq r_ctx [Int63.one, v] c
let assert_ivar_le_constant {r_ctx} v c =
S.add_le r_ctx [Int63.one, v] c
let assert_bvar_equal_constant {r_ctx} v c =
let v = S.ivar_of_bvar v
and c = Int63.(if c then one else zero) in
S.add_eq r_ctx [Int63.one, v] c
let finally_assert_unit ({r_ctx} as r) = function
| S_Pos (Some v) ->
assert_bvar_equal_constant r v true
| S_Neg (Some v) ->
assert_bvar_equal_constant r v false
| S_Pos None ->
()
| S_Neg None ->
r.r_unsat <- true
let rec finally_assert_formula ({r_ctx} as r) = function
| P.U_And l ->
List.iter l ~f:(finally_assert_formula r)
| P.U_Not (P.U_And l) ->
let f = function
| [] ->
r.r_unsat <- true
| [S_Pos v] ->
assert_bvar_equal_constant r v false
| [S_Neg v] ->
assert_bvar_equal_constant r v true
| l ->
(let f = snot in List.map l ~f) |> S.add_clause r_ctx in
Option.iter (blast_conjunction_map r [] l) ~f
| P.U_Var v ->
assert_bvar_equal_constant r (bvar_of_bid r v) true
| P.U_App (f_id, l) ->
let v = var_of_bool_app r f_id l in
assert_bvar_equal_constant r v true
| P.U_Atom (P.G_Sum s, O'_Le) ->
let l, o = iexpr_of_sum r s in
S.add_le r_ctx l (Int63.neg o)
| P.U_Atom (P.G_Sum s, O'_Eq) ->
let l, o = iexpr_of_sum r s in
S.add_eq r_ctx l (Int63.neg o)
| P.U_Atom (P.G_Base a, O'_Le) ->
(match ovar_of_flat_term_base r a with
| None, o when Int63.(o > zero) ->
r.r_unsat <- true
| None, _ ->
()
| Some v, o ->
assert_ivar_le_constant r v (Int63.neg o))
| P.U_Atom (P.G_Base a, O'_Eq) ->
(match ovar_of_flat_term_base r a with
| None, o when Int63.(o = zero) ->
()
| None, _ ->
r.r_unsat <- true
| Some v, o ->
assert_ivar_equal_constant r v (Int63.neg o))
| g ->
xvar_of_formula_doit r g |> finally_assert_unit r
let negate_bvar {r_ctx} =
S.negate_bvar r_ctx
let xvar_of_formula ({r_pre_ctx} as r) g =
let g = P.flatten_formula r_pre_ctx g in
lazy (xvar_of_formula_doit r g)
let xvar_of_term ({r_pre_ctx} as r) m =
let m = P.flatten_bool_term r_pre_ctx m in
lazy (xvar_of_formula_doit r m)
let ovar_of_term ({r_pre_ctx} as r) m =
let m = P.flatten_int_term r_pre_ctx m in
lazy (ovar_of_term r m)
let bvar_of_id = bvar_of_bid
let write_bg_ctx {r_ctx} =
S.write_ctx r_ctx
let bg_assert_all_cached ({r_q} as r) =
Dequeue.iter r_q ~f:(finally_assert_formula r);
Dequeue.clear r_q
let add_objective ({r_obj; r_pre_ctx} as r) o =
match r_obj with
| None ->
let m = P.flatten_int_term r_pre_ctx o in
r.r_obj <- Some m; `Ok
| Some _ ->
`Duplicate
let deref_int {r_ctx; r_ivar_m} id =
Option.(Hashtbl.find r_ivar_m id >>= S.ideref r_ctx)
let deref_bool {r_ctx; r_bvar_m} id =
Option.(Hashtbl.find r_bvar_m id >>= S.bderef r_ctx)
let bind_for_axiom {r_axiom_m; r_bind_m} axiom_id bindings =
let key, data = List.unzip bindings
and axiom = Hashtbl.find r_axiom_m axiom_id in
let q, _, _ = Option.value_exn axiom ~here:_here_ in
assert
(let f id =
let f id' = compare_int_id id id' = 0 in
List.exists q ~f in
List.for_all key ~f);
let h =
let default () = Hashtbl.Poly.create () ~size:128 in
Hashtbl.find_or_add r_bind_m axiom_id ~default
and f = function
| Some l ->
Some
(if let f = (=) data in List.exists l ~f then
l
else
data :: l)
| None ->
Some [data] in
Hashtbl.change h key f
let register_app_for_axioms ({r_patt_m} as r) (m : (c, int) M.t) =
match m with
| M.M_App (a, b) ->
Option.value_exn ~here:_here_ (M.fun_id_of_app m) |>
Hashtbl.find r_patt_m |>
let f (axiom_id, Flat.Box.Box pattern) =
let f l =
let f = function
| `Bool (_, _) ->
FIXME : let 's deal with integers first
raise (Unreachable.Exn _here_)
| `Int (id, m) ->
id, m
and f' =
let cmp (id1, _) (id2, _) =
compare_int_id id1 id2 in
List.sort ~cmp in
List.map l ~f |> f' |> bind_for_axiom r axiom_id in
Matching.do_for_match m ~pattern ~f in
let f = List.iter ~f in
Option.iter ~f
| _ ->
raise (Unreachable.Exn _here_)
let rec register_apps_term :
type s. ctx -> (I.c, s) M.t -> unit =
fun r -> function
| M.M_Int _ ->
()
| M.M_Var _ ->
()
| M.M_Bool g ->
register_apps_formula r g
| M.M_Sum (a, b) ->
register_apps_term r a; register_apps_term r b
| M.M_Prod (_, a) ->
register_apps_term r a
| M.M_Ite (g, a, b) ->
register_apps_formula r g;
register_apps_term r a;
register_apps_term r b
| M.M_App (a, b) as m ->
(match M.type_of_t m with
| Type.Y_Int ->
register_app_for_axioms r m
| _ ->
());
register_apps_term r a;
register_apps_term r b
and register_apps_formula r =
let f a ~polarity =
match a with
| A.A_Bool m ->
register_apps_term r m
| A.A_Le m | A.A_Eq m ->
register_apps_term r m
and polarity = `Both in
Formula.iter_atoms ~f ~polarity
let register_axiom_terms {r_patt_m} id axiom =
let open Flat in
let f = function
| M_Var _ ->
()
| M_App (_, _) as m ->
let key = Option.value_exn (fun_id_of_app m) ~here:_here_
and data = id, Flat.Box.Box m in
Hashtbl.add_multi r_patt_m ~key ~data in
Axiom.Flat.iter_subterms axiom ~f
let instantiate r (l, o) ~bindings =
let f (l, s) (c, m) =
Conv.term_of_t m ~bindings |>
ovar_of_term r |>
Lazy.force |>
function
| Some v, o ->
(c, v) :: l, Int63.(s + c * o)
| None, o ->
l, Int63.(s + c * o)
and init = [], o in
List.fold_left l ~f ~init
let bindings_of_substitution =
let f x = `Int x in
List.map ~f
let rec iter_substitutions r axiom_id h keys ~f ~bound =
match keys with
| a :: d ->
let l = Option.value_exn (Hashtbl.find h a) ~here:_here_
and f a' =
let bound =
Option.value_exn (List.zip a a') ~here:_here_ |>
List.append bound in
iter_substitutions r axiom_id h d ~f ~bound in
List.iter l ~f
| [] ->
f (List.rev bound)
let iter_substitutions ({r_axiom_m; r_bind_m} as r) axiom_id ~f =
let f h =
let bound = [] in
iter_substitutions r axiom_id h (Hashtbl.keys h) ~f ~bound in
Option.iter (Hashtbl.find r_bind_m axiom_id) ~f
let encode_all_axiom_instances ({r_ctx; r_axiom_m} as r) =
let cnt = ref 0 in
let f ~key ~data:(q, l, c) =
let f s =
let bindings = bindings_of_substitution s in
let f (a, b) =
let f x =
instantiate r ~bindings x |> ovar_of_sum r in
let v_a, o_a = f a in
f b, (v_a, Int63.(o_a - one)) in
let l = List.map l ~f
and c =
instantiate r ~bindings c |> ovar_of_sum r in
let l = (c, (None, Int63.zero)) :: l in
S.add_diffs_disjunction r_ctx l;
incr cnt in
iter_substitutions r key ~f in
Hashtbl.iter r_axiom_m ~f;
if dbg then Printf.printf "[INFO] %d axiom instances\n%!" !cnt
let cut_of_term m ~bindings =
let open Option in
let f acc c m =
acc >>= (fun (l, bindings) ->
Conv.t_of_term m ~bindings >>| (fun (m, bindings) ->
(c, m) :: l, bindings))
and f_offset acc o =
acc >>| (fun (l, bindings) -> (l, o), bindings)
and init = Some ([], bindings)
and factor = Int63.one in
M.fold_sum_terms m ~f ~f_offset ~init ~factor
let negate_cut (l, o) =
let f (c, x) = Int63.(~-) c, x
and o = Int63.(~-) o in
List.map l ~f, o
let linearize_iexpr (l, o) ~quantified ~map ~copies =
let l, map, copies =
let f (l, map, copies) (c, under) =
let under, map, copies =
Linear.linearize under ~quantified ~under ~map ~copies in
(c, under) :: l, map, copies
and init = [], map, copies in
List.fold_left l ~init ~f in
let l = List.rev l in
(l, o), map, copies
let linearize_axiom (quantified, h, cut) =
let map = Map.Poly.empty and copies = [] in
let h, map, copies =
let f (l, map, copies) (a, b) =
let a, map, copies =
linearize_iexpr a ~quantified ~map ~copies in
let b, map, copies =
linearize_iexpr b ~quantified ~map ~copies in
(a, b) :: l, map, copies
and init = [], map, copies in
List.fold_left h ~f ~init in
let cut, map, copies =
linearize_iexpr cut ~quantified ~map ~copies in
let h =
let f (a, b) =
let open Int63 in
([one, Flat.M_Var a], zero),
([one, Flat.M_Var b], zero) in
List.rev_map_append copies (List.rev_map_append copies h ~f)
~f:(Fn.compose f Tuple.T2.swap)
and quantified =
let f (id, _) = id in
List.rev_map_append copies quantified ~f in
quantified, h, cut
let flatten_axiom (q, (l, (c1, c2, op))) =
let open Option in (
let f acc (m1, m2, op) =
acc >>= (fun (l, bindings) ->
Conv.sum_of_term m1 ~bindings >>= (fun (s1, bindings) ->
Conv.sum_of_term m2 ~bindings >>| (fun (s2, bindings) ->
(match op with
| Terminology.O'_Le ->
(s1, s2) :: l
| Terminology.O'_Eq ->
(s1, s2) :: (s2, s1) :: l), bindings)))
and init = Some ([], []) in
List.fold_left l ~init ~f) >>= (fun (init, bindings) ->
M.(c1 - c2) |>
cut_of_term ~bindings >>| (fun (c, bindings) ->
let q =
let f = Tuple.T2.get1 in
List.rev_map_append bindings q ~f
and h =
let f acc (id, def) =
let e = Int63.([one, Flat.M_Var id], zero) in
(e, def) :: (def, e) :: acc in
List.fold_left bindings ~f ~init in
(match op with
| Terminology.O'_Le ->
[q, h, c]
| Terminology.O'_Eq ->
[q, h, c; q, h, negate_cut c])))
let rec int_args :
type s t .
(I.c, s -> t) M.t -> acc:(I.c, int) M.t list ->
(I.c, int) M.t list =
fun m ~acc ->
match m with
| M.M_App (f, x) ->
(match M.type_of_t x with
| Type.Y_Int ->
let acc = x :: acc in
int_args f ~acc
| _ ->
int_args f ~acc)
| M.M_Var _ ->
acc
let rec maximal_ground_subterms :
type s . ctx -> I.c Axiom.quantified list ->
(I.c, s) M.t -> acc:(I.c, int) M.t list ->
bool * (I.c, int) M.t list =
fun r q m ~acc ->
match m with
| M.M_Bool _ ->
false, acc
| M.M_Ite _ ->
false, acc
| M.M_Int _ ->
true, acc
| M.M_Sum (a, b) ->
let a_b, acc = maximal_ground_subterms r q a ~acc in
let b_b, acc = maximal_ground_subterms r q b ~acc in
(match a_b, b_b with
| true, true ->
true, acc
| true, false ->
false, a :: acc
| false, true ->
false, b :: acc
| _, _ ->
false, acc)
| M.M_App (a, b) ->
let a_b, acc = maximal_ground_subterms r q a ~acc in
let b_b, acc = maximal_ground_subterms r q b ~acc in
(match a_b, b_b with
| true, true ->
true, acc
| false, true ->
false,
(match M.type_of_t b with
| Type.Y_Int ->
b :: acc
| _ ->
acc)
| true, false ->
false, int_args a ~acc
| _, _ ->
false, acc)
| M.M_Prod (_, a) ->
maximal_ground_subterms r q a ~acc
| M.M_Var v ->
(match Id.type_of_t v with
| Type.Y_Int ->
let f = (=) v in
not (List.exists q ~f), acc
| Type.Y_Int_Arrow _ ->
true, acc
| Type.Y_Bool_Arrow _ ->
true, acc
| _ ->
false, acc)
let record_axiom_ground_terms r ((q, _) as axiom) =
let l =
let f acc m =
let b, acc = maximal_ground_subterms r q m ~acc in
if b then m :: acc else acc
and init = [] in
Axiom.X.fold_terms axiom ~f ~init in
let l =
let f = function
| M.M_App (_, _) ->
true
| _ ->
false in
List.filter l ~f in
r.r_ground_l <- List.append l r.r_ground_l
let assert_axiom ({r_axiom_m} as r) axiom =
record_axiom_ground_terms r axiom;
match flatten_axiom axiom with
| Some axioms ->
let f axiom =
let axiom = linearize_axiom axiom in
let id = get_axiom_id r in
Hashtbl.replace r_axiom_m id axiom;
register_axiom_terms r id axiom in
List.iter axioms ~f; `Ok
| None ->
`Unsupported
let assert_formula ({r_pre_ctx; r_q} as r) g =
register_apps_formula r g;
P.flatten_formula r_pre_ctx g |> Dequeue.enqueue_back r_q
let solve ({r_ctx; r_obj; r_ground_l} as r) =
bg_assert_all_cached r;
(let f = register_apps_term r in
List.iter r_ground_l ~f);
encode_all_axiom_instances r;
match r_obj, r.r_unsat with
| _, true ->
R_Unsat
| Some o, false ->
let l, _ = iexpr_of_flat_term r o in
(match S.add_objective r_ctx l with
| `Duplicate ->
raise (Unreachable.Exn _here_)
| `Ok ->
S.solve r_ctx)
| None, false ->
S.solve r_ctx
end
|
7f5041f55d42b62c8cfacda0687a5040f26f4330c32d57c9070b19dfb4528663 | melhadad/fuf | quicklisp.lisp | ;;;;
This is quicklisp.lisp , the quickstart file for Quicklisp . To use
;;;; it, start Lisp, then (load "quicklisp.lisp")
;;;;
Quicklisp is beta software and comes with no warranty of any kind .
;;;;
For more information about the Quicklisp beta , see :
;;;;
/
;;;;
If you have any questions or comments about Quicklisp , please
;;;; contact:
;;;;
< >
;;;;
(cl:in-package #:cl-user)
(cl:defpackage #:qlqs-user
(:use #:cl))
(cl:in-package #:qlqs-user)
(defpackage #:qlqs-impl
(:use #:cl)
(:export #:*implementation*)
(:export #:definterface
#:defimplementation)
(:export #:lisp
#:abcl
#:allegro
#:ccl
#:clisp
#:cmucl
#:cormanlisp
#:ecl
#:gcl
#:lispworks
#:scl
#:sbcl))
(defpackage #:qlqs-impl-util
(:use #:cl #:qlqs-impl)
(:export #:call-with-quiet-compilation))
(defpackage #:qlqs-network
(:use #:cl #:qlqs-impl)
(:export #:open-connection
#:write-octets
#:read-octets
#:close-connection
#:with-connection))
(defpackage #:qlqs-progress
(:use #:cl)
(:export #:make-progress-bar
#:start-display
#:update-progress
#:finish-display))
(defpackage #:qlqs-http
(:use #:cl #:qlqs-network #:qlqs-progress)
(:export #:fetch
#:*proxy-url*
#:*maximum-redirects*
#:*default-url-defaults*))
(defpackage #:qlqs-minitar
(:use #:cl)
(:export #:tarball-contents
#:unpack-tarball))
(defpackage #:quicklisp-quickstart
(:use #:cl #:qlqs-impl #:qlqs-impl-util #:qlqs-http #:qlqs-minitar)
(:export #:install
#:*proxy-url*
#:*asdf-url*
#:*quicklisp-tar-url*
#:*setup-url*
#:*after-load-message*
#:*after-initial-setup-message*))
;;;
;;; Defining implementation-specific packages and functionality
;;;
(in-package #:qlqs-impl)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun error-unimplemented (&rest args)
(declare (ignore args))
(error "Not implemented")))
(defmacro neuter-package (name)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(let ((definition (fdefinition 'error-unimplemented)))
(do-external-symbols (symbol ,(string name))
(unless (fboundp symbol)
(setf (fdefinition symbol) definition))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun feature-expression-passes-p (expression)
(cond ((keywordp expression)
(member expression *features*))
((consp expression)
(case (first expression)
(or
(some 'feature-expression-passes-p (rest expression)))
(and
(every 'feature-expression-passes-p (rest expression)))))
(t (error "Unrecognized feature expression -- ~S" expression)))))
(defmacro define-implementation-package (feature package-name &rest options)
(let* ((output-options '((:use)
(:export #:lisp)))
(prep (cdr (assoc :prep options)))
(class-option (cdr (assoc :class options)))
(class (first class-option))
(superclasses (rest class-option))
(import-options '())
(effectivep (feature-expression-passes-p feature)))
(dolist (option options)
(ecase (first option)
((:prep :class))
((:import-from
:import)
(push option import-options))
((:export
:shadow
:intern
:documentation)
(push option output-options))
((:reexport-from)
(push (cons :export (cddr option)) output-options)
(push (cons :import-from (cdr option)) import-options))))
`(eval-when (:compile-toplevel :load-toplevel :execute)
,@(when effectivep
prep)
(defclass ,class ,superclasses ())
(defpackage ,package-name ,@output-options
,@(when effectivep
import-options))
,@(when effectivep
`((setf *implementation* (make-instance ',class))))
,@(unless effectivep
`((neuter-package ,package-name))))))
(defmacro definterface (name lambda-list &body options)
(let* ((forbidden (intersection lambda-list lambda-list-keywords))
(gf-options (remove :implementation options :key #'first))
(implementations (set-difference options gf-options)))
(when forbidden
(error "~S not allowed in definterface lambda list" forbidden))
(flet ((method-option (class body)
`(:method ((*implementation* ,class) ,@lambda-list)
,@body)))
(let ((generic-name (intern (format nil "%~A" name))))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defgeneric ,generic-name (lisp ,@lambda-list)
,@gf-options
,@(mapcar (lambda (implementation)
(destructuring-bind (class &rest body)
(rest implementation)
(method-option class body)))
implementations))
(defun ,name ,lambda-list
(,generic-name *implementation* ,@lambda-list)))))))
(defmacro defimplementation (name-and-options
lambda-list &body body)
(destructuring-bind (name &key (for t) qualifier)
(if (consp name-and-options)
name-and-options
(list name-and-options))
(unless for
(error "You must specify an implementation name."))
(let ((generic-name (find-symbol (format nil "%~A" name))))
(unless (and generic-name
(fboundp generic-name))
(error "~S does not name an implementation function" name))
`(defmethod ,generic-name
,@(when qualifier (list qualifier))
,(list* `(*implementation* ,for) lambda-list) ,@body))))
Bootstrap implementations
(defvar *implementation* nil)
(defclass lisp () ())
Allegro Common Lisp
(define-implementation-package :allegro #:qlqs-allegro
(:documentation
"Allegro Common Lisp - /")
(:class allegro)
(:reexport-from #:socket
#:make-socket)
(:reexport-from #:excl
#:read-vector))
Armed Bear Common Lisp
(define-implementation-package :abcl #:qlqs-abcl
(:documentation
"Armed Bear Common Lisp - -lisp.net/project/armedbear/")
(:class abcl)
(:reexport-from #:system
#:make-socket
#:get-socket-stream))
;;; Clozure CL
(define-implementation-package :ccl #:qlqs-ccl
(:documentation
"Clozure Common Lisp - ")
(:class ccl)
(:reexport-from #:ccl
#:make-socket))
GNU CLISP
(define-implementation-package :clisp #:qlqs-clisp
(:documentation "GNU CLISP - /")
(:class clisp)
(:reexport-from #:socket
#:socket-connect)
(:reexport-from #:ext
#:read-byte-sequence))
CMUCL
(define-implementation-package :cmu #:qlqs-cmucl
(:documentation "CMU Common Lisp - /")
(:class cmucl)
(:reexport-from #:ext
#:*gc-verbose*)
(:reexport-from #:system
#:make-fd-stream)
(:reexport-from #:extensions
#:connect-to-inet-socket))
(defvar qlqs-cmucl:*gc-verbose* nil)
ECL
(define-implementation-package :ecl #:qlqs-ecl
(:documentation "ECL - /")
(:class ecl)
(:prep
(require 'sockets))
(:intern #:host-network-address)
(:reexport-from #:sb-bsd-sockets
#:get-host-by-name
#:host-ent-address
#:socket-connect
#:socket-make-stream
#:inet-socket))
LispWorks
(define-implementation-package :lispworks #:qlqs-lispworks
(:documentation "LispWorks - /")
(:class lispworks)
(:prep
(require "comm"))
(:reexport-from #:comm
#:open-tcp-stream
#:get-host-entry))
SBCL
(define-implementation-package :sbcl #:qlqs-sbcl
(:class sbcl)
(:documentation
"Steel Bank Common Lisp - /")
(:prep
(require 'sb-bsd-sockets))
(:intern #:host-network-address)
(:reexport-from #:sb-ext
#:compiler-note)
(:reexport-from #:sb-bsd-sockets
#:get-host-by-name
#:inet-socket
#:host-ent-address
#:socket-connect
#:socket-make-stream))
;;;
;;; Utility function
;;;
(in-package #:qlqs-impl-util)
(definterface call-with-quiet-compilation (fun)
(:implementation t
(let ((*load-verbose* nil)
(*compile-verbose* nil)
(*load-print* nil)
(*compile-print* nil))
(handler-bind ((warning #'muffle-warning))
(funcall fun)))))
(defimplementation (call-with-quiet-compilation :for sbcl :qualifier :around)
(fun)
(declare (ignorable fun))
(handler-bind ((qlqs-sbcl:compiler-note #'muffle-warning))
(call-next-method)))
(defimplementation (call-with-quiet-compilation :for cmucl :qualifier :around)
(fun)
(declare (ignorable fun))
(let ((qlqs-cmucl:*gc-verbose* nil))
(call-next-method)))
;;;
;;; Low-level networking implementations
;;;
(in-package #:qlqs-network)
(definterface host-address (host)
(:implementation t
host)
(:implementation sbcl
(qlqs-sbcl:host-ent-address (qlqs-sbcl:get-host-by-name host))))
(definterface open-connection (host port)
(:implementation t
(declare (ignorable host port))
(error "Sorry, quicklisp in implementation ~S is not supported yet."
(lisp-implementation-type)))
(:implementation allegro
(qlqs-allegro:make-socket :remote-host host
:remote-port port))
(:implementation abcl
(let ((socket (qlqs-abcl:make-socket host port)))
(qlqs-abcl:get-socket-stream socket :element-type '(unsigned-byte 8))))
(:implementation ccl
(qlqs-ccl:make-socket :remote-host host
:remote-port port))
(:implementation clisp
(qlqs-clisp:socket-connect port host :element-type '(unsigned-byte 8)))
(:implementation cmucl
(let ((fd (qlqs-cmucl:connect-to-inet-socket host port)))
(qlqs-cmucl:make-fd-stream fd
:element-type '(unsigned-byte 8)
:binary-stream-p t
:input t
:output t)))
(:implementation ecl
(let* ((endpoint (qlqs-ecl:host-ent-address
(qlqs-ecl:get-host-by-name host)))
(socket (make-instance 'qlqs-ecl:inet-socket
:protocol :tcp
:type :stream)))
(qlqs-ecl:socket-connect socket endpoint port)
(qlqs-ecl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full)))
(:implementation lispworks
(qlqs-lispworks:open-tcp-stream host port
:direction :io
:read-timeout nil
:element-type '(unsigned-byte 8)
:timeout 5))
(:implementation sbcl
(let* ((endpoint (qlqs-sbcl:host-ent-address
(qlqs-sbcl:get-host-by-name host)))
(socket (make-instance 'qlqs-sbcl:inet-socket
:protocol :tcp
:type :stream)))
(qlqs-sbcl:socket-connect socket endpoint port)
(qlqs-sbcl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full))))
(definterface read-octets (buffer connection)
(:implementation t
(read-sequence buffer connection))
(:implementation allegro
(qlqs-allegro:read-vector buffer connection))
(:implementation clisp
(qlqs-clisp:read-byte-sequence buffer connection
:no-hang nil
:interactive t)))
(definterface write-octets (buffer connection)
(:implementation t
(write-sequence buffer connection)
(finish-output connection)))
(definterface close-connection (connection)
(:implementation t
(ignore-errors (close connection))))
(definterface call-with-connection (host port fun)
(:implementation t
(let (connection)
(unwind-protect
(progn
(setf connection (open-connection host port))
(funcall fun connection))
(when connection
(close connection))))))
(defmacro with-connection ((connection host port) &body body)
`(call-with-connection ,host ,port (lambda (,connection) ,@body)))
;;;
;;; A text progress bar
;;;
(in-package #:qlqs-progress)
(defclass progress-bar ()
((start-time
:initarg :start-time
:accessor start-time)
(end-time
:initarg :end-time
:accessor end-time)
(progress-character
:initarg :progress-character
:accessor progress-character)
(character-count
:initarg :character-count
:accessor character-count
:documentation "How many characters wide is the progress bar?")
(characters-so-far
:initarg :characters-so-far
:accessor characters-so-far)
(update-interval
:initarg :update-interval
:accessor update-interval
:documentation "Update the progress bar display after this many
internal-time units.")
(last-update-time
:initarg :last-update-time
:accessor last-update-time
:documentation "The display was last updated at this time.")
(total
:initarg :total
:accessor total
:documentation "The total number of units tracked by this progress bar.")
(progress
:initarg :progress
:accessor progress
:documentation "How far in the progress are we?")
(pending
:initarg :pending
:accessor pending
:documentation "How many raw units should be tracked in the next
display update?"))
(:default-initargs
:progress-character #\=
:character-count 50
:characters-so-far 0
:update-interval (floor internal-time-units-per-second 4)
:last-update-time 0
:total 0
:progress 0
:pending 0))
(defgeneric start-display (progress-bar))
(defgeneric update-progress (progress-bar unit-count))
(defgeneric update-display (progress-bar))
(defgeneric finish-display (progress-bar))
(defgeneric elapsed-time (progress-bar))
(defgeneric units-per-second (progress-bar))
(defmethod start-display (progress-bar)
(setf (last-update-time progress-bar) (get-internal-real-time))
(setf (start-time progress-bar) (get-internal-real-time))
(fresh-line)
(finish-output))
(defmethod update-display (progress-bar)
(incf (progress progress-bar) (pending progress-bar))
(setf (pending progress-bar) 0)
(setf (last-update-time progress-bar) (get-internal-real-time))
(let* ((showable (floor (character-count progress-bar)
(/ (total progress-bar) (progress progress-bar))))
(needed (- showable (characters-so-far progress-bar))))
(setf (characters-so-far progress-bar) showable)
(dotimes (i needed)
(write-char (progress-character progress-bar)))
(finish-output)))
(defmethod update-progress (progress-bar unit-count)
(incf (pending progress-bar) unit-count)
(let ((now (get-internal-real-time)))
(when (< (update-interval progress-bar)
(- now (last-update-time progress-bar)))
(update-display progress-bar))))
(defmethod finish-display (progress-bar)
(update-display progress-bar)
(setf (end-time progress-bar) (get-internal-real-time))
(terpri)
(format t "~:D bytes in ~$ seconds (~$KB/sec)"
(total progress-bar)
(elapsed-time progress-bar)
(/ (units-per-second progress-bar) 1024))
(finish-output))
(defmethod elapsed-time (progress-bar)
(/ (- (end-time progress-bar) (start-time progress-bar))
internal-time-units-per-second))
(defmethod units-per-second (progress-bar)
(if (plusp (elapsed-time progress-bar))
(/ (total progress-bar) (elapsed-time progress-bar))
0))
(defun kb/sec (progress-bar)
(/ (units-per-second progress-bar) 1024))
(defparameter *uncertain-progress-chars* "?")
(defclass uncertain-size-progress-bar (progress-bar)
((progress-char-index
:initarg :progress-char-index
:accessor progress-char-index)
(units-per-char
:initarg :units-per-char
:accessor units-per-char))
(:default-initargs
:total 0
:progress-char-index 0
:units-per-char (floor (expt 1024 2) 50)))
(defmethod update-progress :after ((progress-bar uncertain-size-progress-bar)
unit-count)
(incf (total progress-bar) unit-count))
(defmethod progress-character ((progress-bar uncertain-size-progress-bar))
(let ((index (progress-char-index progress-bar)))
(prog1
(char *uncertain-progress-chars* index)
(setf (progress-char-index progress-bar)
(mod (1+ index) (length *uncertain-progress-chars*))))))
(defmethod update-display ((progress-bar uncertain-size-progress-bar))
(setf (last-update-time progress-bar) (get-internal-real-time))
(multiple-value-bind (chars pend)
(floor (pending progress-bar) (units-per-char progress-bar))
(setf (pending progress-bar) pend)
(dotimes (i chars)
(write-char (progress-character progress-bar))
(incf (characters-so-far progress-bar))
(when (<= (character-count progress-bar)
(characters-so-far progress-bar))
(terpri)
(setf (characters-so-far progress-bar) 0)
(finish-output)))
(finish-output)))
(defun make-progress-bar (total)
(if (or (not total) (zerop total))
(make-instance 'uncertain-size-progress-bar)
(make-instance 'progress-bar :total total)))
;;;
;;; A simple HTTP client
;;;
(in-package #:qlqs-http)
;;; Octet data
(deftype octet ()
'(unsigned-byte 8))
(defun make-octet-vector (size)
(make-array size :element-type 'octet
:initial-element 0))
(defun octet-vector (&rest octets)
(make-array (length octets) :element-type 'octet
:initial-contents octets))
;;; ASCII characters as integers
(defun acode (char)
(cond ((eql char :cr)
13)
((eql char :lf)
10)
(t
(let ((code (char-code char)))
(if (<= 0 code 127)
code
(error "Character ~S is not in the ASCII character set"
char))))))
(defvar *whitespace*
(list (acode #\Space) (acode #\Tab) (acode :cr) (acode :lf)))
(defun whitep (code)
(member code *whitespace*))
(defun ascii-vector (string)
(let ((vector (make-octet-vector (length string))))
(loop for char across string
for code = (char-code char)
for i from 0
if (< 127 code) do
(error "Invalid character for ASCII -- ~A" char)
else
do (setf (aref vector i) code))
vector))
(defun ascii-subseq (vector start end)
"Return a subseq of octet-specialized VECTOR as a string."
(let ((string (make-string (- end start))))
(loop for i from 0
for j from start below end
do (setf (char string i) (code-char (aref vector j))))
string))
(defun ascii-downcase (code)
(if (<= 65 code 90)
(+ code 32)
code))
(defun ascii-equal (a b)
(eql (ascii-downcase a) (ascii-downcase b)))
(defmacro acase (value &body cases)
(flet ((convert-case-keys (keys)
(mapcar (lambda (key)
(etypecase key
(integer key)
(character (char-code key))
(symbol
(ecase key
(:cr 13)
(:lf 10)
((t) t)))))
(if (consp keys) keys (list keys)))))
`(case ,value
,@(mapcar (lambda (case)
(destructuring-bind (keys &rest body)
case
`(,(if (eql keys t)
t
(convert-case-keys keys))
,@body)))
cases))))
;;; Pattern matching (for finding headers)
(defclass matcher ()
((pattern
:initarg :pattern
:reader pattern)
(pos
:initform 0
:accessor match-pos)
(matchedp
:initform nil
:accessor matchedp)))
(defun reset-match (matcher)
(setf (match-pos matcher) 0
(matchedp matcher) nil))
(define-condition match-failure (error) ())
(defun match (matcher input &key (start 0) end error)
(let ((i start)
(end (or end (length input)))
(match-end (length (pattern matcher))))
(with-slots (pattern pos)
matcher
(loop
(cond ((= pos match-end)
(let ((match-start (- i pos)))
(setf pos 0)
(setf (matchedp matcher) t)
(return (values match-start (+ match-start match-end)))))
((= i end)
(return nil))
((= (aref pattern pos)
(aref input i))
(incf i)
(incf pos))
(t
(if error
(error 'match-failure)
(if (zerop pos)
(incf i)
(setf pos 0)))))))))
(defun ascii-matcher (string)
(make-instance 'matcher
:pattern (ascii-vector string)))
(defun octet-matcher (&rest octets)
(make-instance 'matcher
:pattern (apply 'octet-vector octets)))
(defun acode-matcher (&rest codes)
(make-instance 'matcher
:pattern (make-array (length codes)
:element-type 'octet
:initial-contents
(mapcar 'acode codes))))
" Connection Buffers " are a kind of callback - driven ,
;;; pattern-matching chunky stream. Callbacks can be called for a
certain number of octets or until one or more patterns are seen in
the input . cbufs automatically refill themselves from a
;;; connection as needed.
(defvar *cbuf-buffer-size* 8192)
(define-condition end-of-data (error) ())
(defclass cbuf ()
((data
:initarg :data
:accessor data)
(connection
:initarg :connection
:accessor connection)
(start
:initarg :start
:accessor start)
(end
:initarg :end
:accessor end)
(eofp
:initarg :eofp
:accessor eofp))
(:default-initargs
:data (make-octet-vector *cbuf-buffer-size*)
:connection nil
:start 0
:end 0
:eofp nil)
(:documentation "A CBUF is a connection buffer that keeps track of
incoming data from a connection. Several functions make it easy to
treat a CBUF as a kind of chunky, callback-driven stream."))
(define-condition cbuf-progress ()
((size
:initarg :size
:accessor cbuf-progress-size
:initform 0)))
(defun call-processor (fun cbuf start end)
(signal 'cbuf-progress :size (- end start))
(funcall fun (data cbuf) start end))
(defun make-cbuf (connection)
(make-instance 'cbuf :connection connection))
(defun make-stream-writer (stream)
"Create a callback for writing data to STREAM."
(lambda (data start end)
(write-sequence data stream :start start :end end)))
(defgeneric size (cbuf)
(:method ((cbuf cbuf))
(- (end cbuf) (start cbuf))))
(defgeneric emptyp (cbuf)
(:method ((cbuf cbuf))
(zerop (size cbuf))))
(defgeneric refill (cbuf)
(:method ((cbuf cbuf))
(when (eofp cbuf)
(error 'end-of-data))
(setf (start cbuf) 0)
(setf (end cbuf)
(read-octets (data cbuf)
(connection cbuf)))
(cond ((emptyp cbuf)
(setf (eofp cbuf) t)
(error 'end-of-data))
(t (size cbuf)))))
(defun process-all (fun cbuf)
(unless (emptyp cbuf)
(call-processor fun cbuf (start cbuf) (end cbuf))))
(defun multi-cmatch (matchers cbuf)
(let (start end)
(dolist (matcher matchers (values start end))
(multiple-value-bind (s e)
(match matcher (data cbuf)
:start (start cbuf)
:end (end cbuf))
(when (and s (or (null start) (< s start)))
(setf start s
end e))))))
(defun cmatch (matcher cbuf)
(if (consp matcher)
(multi-cmatch matcher cbuf)
(match matcher (data cbuf) :start (start cbuf) :end (end cbuf))))
(defun call-until-end (fun cbuf)
(handler-case
(loop
(process-all fun cbuf)
(refill cbuf))
(end-of-data ()
(return-from call-until-end))))
(defun show-cbuf (context cbuf)
(format t "cbuf: ~A ~D - ~D~%" context (start cbuf) (end cbuf)))
(defun call-for-n-octets (n fun cbuf)
(let ((remaining n))
(loop
(when (<= remaining (size cbuf))
(let ((end (+ (start cbuf) remaining)))
(call-processor fun cbuf (start cbuf) end)
(setf (start cbuf) end)
(return)))
(process-all fun cbuf)
(decf remaining (size cbuf))
(refill cbuf))))
(defun call-until-matching (matcher fun cbuf)
(loop
(multiple-value-bind (start end)
(cmatch matcher cbuf)
(when start
(call-processor fun cbuf (start cbuf) end)
(setf (start cbuf) end)
(return)))
(process-all fun cbuf)
(refill cbuf)))
(defun ignore-data (data start end)
(declare (ignore data start end)))
(defun skip-until-matching (matcher cbuf)
(call-until-matching matcher 'ignore-data cbuf))
;;; Creating HTTP requests as octet buffers
(defclass octet-sink ()
((storage
:initarg :storage
:accessor storage))
(:default-initargs
:storage (make-array 1024 :element-type 'octet
:fill-pointer 0
:adjustable t))
(:documentation "A simple stream-like target for collecting
octets."))
(defun add-octet (octet sink)
(vector-push-extend octet (storage sink)))
(defun add-octets (octets sink &key (start 0) end)
(setf end (or end (length octets)))
(loop for i from start below end
do (add-octet (aref octets i) sink)))
(defun add-string (string sink)
(loop for char across string
for code = (char-code char)
do (add-octet code sink)))
(defun add-strings (sink &rest strings)
(mapc (lambda (string) (add-string string sink)) strings))
(defun add-newline (sink)
(add-octet 13 sink)
(add-octet 10 sink))
(defun sink-buffer (sink)
(subseq (storage sink) 0))
(defvar *proxy-url* nil)
(defun full-proxy-path (host port path)
(format nil "~:[http~;https~]://~A~:[:~D~;~*~]~A"
(= port 443)
host
(or (= port 80)
(= port 443))
port
path))
(defun make-request-buffer (host port path &key (method "GET"))
(setf method (string method))
(when *proxy-url*
(setf path (full-proxy-path host port path)))
(let ((sink (make-instance 'octet-sink)))
(flet ((add-line (&rest strings)
(apply #'add-strings sink strings)
(add-newline sink)))
(add-line method " " path " HTTP/1.1")
(add-line "Host: " host (if (= port 80) ""
(format nil ":~D" port)))
(add-line "Connection: close")
;; FIXME: get this version string from somewhere else.
(add-line "User-Agent: quicklisp-bootstrap/2011040600")
(add-newline sink)
(sink-buffer sink))))
(defun sink-until-matching (matcher cbuf)
(let ((sink (make-instance 'octet-sink)))
(call-until-matching
matcher
(lambda (buffer start end)
(add-octets buffer sink :start start :end end))
cbuf)
(sink-buffer sink)))
;;; HTTP headers
(defclass header ()
((data
:initarg :data
:accessor data)
(status
:initarg :status
:accessor status)
(name-starts
:initarg :name-starts
:accessor name-starts)
(name-ends
:initarg :name-ends
:accessor name-ends)
(value-starts
:initarg :value-starts
:accessor value-starts)
(value-ends
:initarg :value-ends
:accessor value-ends)))
(defmethod print-object ((header header) stream)
(print-unreadable-object (header stream :type t)
(prin1 (status header) stream)))
(defun matches-at (pattern target pos)
(= (mismatch pattern target :start2 pos) (length pattern)))
(defun header-value-indexes (field-name header)
(loop with data = (data header)
with pattern = (ascii-vector (string-downcase field-name))
for start across (name-starts header)
for i from 0
when (matches-at pattern data start)
return (values (aref (value-starts header) i)
(aref (value-ends header) i))))
(defun ascii-header-value (field-name header)
(multiple-value-bind (start end)
(header-value-indexes field-name header)
(when start
(ascii-subseq (data header) start end))))
(defun all-field-names (header)
(map 'list
(lambda (start end)
(ascii-subseq (data header) start end))
(name-starts header)
(name-ends header)))
(defun headers-alist (header)
(mapcar (lambda (name)
(cons name (ascii-header-value name header)))
(all-field-names header)))
(defmethod describe-object :after ((header header) stream)
(format stream "~&Decoded headers:~% ~S~%" (headers-alist header)))
(defun content-length (header)
(let ((field-value (ascii-header-value "content-length" header)))
(when field-value
(let ((value (ignore-errors (parse-integer field-value))))
(or value
(error "Content-Length header field value is not a number -- ~A"
field-value))))))
(defun chunkedp (header)
(string= (ascii-header-value "transfer-encoding" header) "chunked"))
(defun location (header)
(ascii-header-value "location" header))
(defun status-code (vector)
(let* ((space (position (acode #\Space) vector))
(c1 (- (aref vector (incf space)) 48))
(c2 (- (aref vector (incf space)) 48))
(c3 (- (aref vector (incf space)) 48)))
(+ (* c1 100)
(* c2 10)
(* c3 1))))
(defun force-downcase-field-names (header)
(loop with data = (data header)
for start across (name-starts header)
for end across (name-ends header)
do (loop for i from start below end
for code = (aref data i)
do (setf (aref data i) (ascii-downcase code)))))
(defun skip-white-forward (pos vector)
(position-if-not 'whitep vector :start pos))
(defun skip-white-backward (pos vector)
(let ((nonwhite (position-if-not 'whitep vector :end pos :from-end t)))
(if nonwhite
(1+ nonwhite)
pos)))
(defun contract-field-value-indexes (header)
"Header field values exclude leading and trailing whitespace; adjust
the indexes in the header accordingly."
(loop with starts = (value-starts header)
with ends = (value-ends header)
with data = (data header)
for i from 0
for start across starts
for end across ends
do
(setf (aref starts i) (skip-white-forward start data))
(setf (aref ends i) (skip-white-backward end data))))
(defun next-line-pos (vector)
(let ((pos 0))
(labels ((finish (&optional (i pos))
(return-from next-line-pos i))
(after-cr (code)
(acase code
(:lf (finish pos))
(t (finish (1- pos)))))
(pending (code)
(acase code
(:cr #'after-cr)
(:lf (finish pos))
(t #'pending))))
(let ((state #'pending))
(loop
(setf state (funcall state (aref vector pos)))
(incf pos))))))
(defun make-hvector ()
(make-array 16 :fill-pointer 0 :adjustable t))
(defun process-header (vector)
"Create a HEADER instance from the octet data in VECTOR."
(let* ((name-starts (make-hvector))
(name-ends (make-hvector))
(value-starts (make-hvector))
(value-ends (make-hvector))
(header (make-instance 'header
:data vector
:status 999
:name-starts name-starts
:name-ends name-ends
:value-starts value-starts
:value-ends value-ends))
(mark nil)
(pos (next-line-pos vector)))
(unless pos
(error "Unable to process HTTP header"))
(setf (status header) (status-code vector))
(labels ((save (value vector)
(vector-push-extend value vector))
(mark ()
(setf mark pos))
(clear-mark ()
(setf mark nil))
(finish ()
(if mark
(save mark value-ends)
(save pos value-ends))
(force-downcase-field-names header)
(contract-field-value-indexes header)
(return-from process-header header))
(in-new-line (code)
(acase code
((#\Tab #\Space) (setf mark nil) #'in-value)
(t
(when mark
(save mark value-ends))
(clear-mark)
(save pos name-starts)
(in-name code))))
(after-cr (code)
(acase code
(:lf #'in-new-line)
(t (in-new-line code))))
(pending-value (code)
(acase code
((#\Tab #\Space) #'pending-value)
(:cr #'after-cr)
(:lf #'in-new-line)
(t (save pos value-starts) #'in-value)))
(in-name (code)
(acase code
(#\:
(save pos name-ends)
(save (1+ pos) value-starts)
#'in-value)
((:cr :lf)
(finish))
((#\Tab #\Space)
(error "Unexpected whitespace in header field name"))
(t
(unless (<= 0 code 127)
(error "Unexpected non-ASCII header field name"))
#'in-name)))
(in-value (code)
(acase code
(:lf (mark) #'in-new-line)
(:cr (mark) #'after-cr)
(t #'in-value))))
(let ((state #'in-new-line))
(loop
(incf pos)
(when (<= (length vector) pos)
(error "No header found in response"))
(setf state (funcall state (aref vector pos))))))))
;;; HTTP URL parsing
(defclass url ()
((hostname
:initarg :hostname
:accessor hostname
:initform nil)
(port
:initarg :port
:accessor port
:initform 80)
(path
:initarg :path
:accessor path
:initform "/")))
(defun parse-urlstring (urlstring)
(setf urlstring (string-trim " " urlstring))
(let* ((pos (mismatch urlstring "http://" :test 'char-equal))
(mark pos)
(url (make-instance 'url)))
(labels ((save ()
(subseq urlstring mark pos))
(mark ()
(setf mark pos))
(finish ()
(return-from parse-urlstring url))
(hostname-char-p (char)
(position char "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."
:test 'char-equal))
(at-start (char)
(case char
(#\/
(setf (port url) nil)
(mark)
#'in-path)
(t
#'in-host)))
(in-host (char)
(case char
((#\/ :end)
(setf (hostname url) (save))
(mark)
#'in-path)
(#\:
(setf (hostname url) (save))
(mark)
#'in-port)
(t
(unless (hostname-char-p char)
(error "~S is not a valid URL" urlstring))
#'in-host)))
(in-port (char)
(case char
((#\/ :end)
(setf (port url)
(parse-integer urlstring
:start (1+ mark)
:end pos))
(mark)
#'in-path)
(t
(unless (digit-char-p char)
(error "Bad port in URL ~S" urlstring))
#'in-port)))
(in-path (char)
(case char
((#\# :end)
(setf (path url) (save))
(finish)))
#'in-path))
(let ((state #'at-start))
(loop
(when (<= (length urlstring) pos)
(funcall state :end)
(finish))
(setf state (funcall state (aref urlstring pos)))
(incf pos))))))
(defun url (thing)
(if (stringp thing)
(parse-urlstring thing)
thing))
(defgeneric request-buffer (method url)
(:method (method url)
(setf url (url url))
(make-request-buffer (hostname url) (port url) (path url)
:method method)))
(defun urlstring (url)
(format nil "~@[http://~A~]~@[:~D~]~A"
(hostname url)
(and (/= 80 (port url)) (port url))
(path url)))
(defmethod print-object ((url url) stream)
(print-unreadable-object (url stream :type t)
(prin1 (urlstring url) stream)))
(defun merge-urls (url1 url2)
(setf url1 (url url1))
(setf url2 (url url2))
(make-instance 'url
:hostname (or (hostname url1)
(hostname url2))
:port (or (port url1)
(port url2))
:path (or (path url1)
(path url2))))
;;; Requesting an URL and saving it to a file
(defparameter *maximum-redirects* 10)
(defvar *default-url-defaults* (url "/"))
(defun read-http-header (cbuf)
(let ((header-data (sink-until-matching (list (acode-matcher :lf :lf)
(acode-matcher :cr :cr)
(acode-matcher :cr :lf :cr :lf))
cbuf)))
(process-header header-data)))
(defun read-chunk-header (cbuf)
(let* ((header-data (sink-until-matching (acode-matcher :cr :lf) cbuf))
(end (or (position (acode :cr) header-data)
(position (acode #\;) header-data))))
(values (parse-integer (ascii-subseq header-data 0 end) :radix 16))))
(defun save-chunk-response (stream cbuf)
"For a chunked response, read all chunks and write them to STREAM."
(let ((fun (make-stream-writer stream))
(matcher (acode-matcher :cr :lf)))
(loop
(let ((chunk-size (read-chunk-header cbuf)))
(when (zerop chunk-size)
(return))
(call-for-n-octets chunk-size fun cbuf)
(skip-until-matching matcher cbuf)))))
(defun save-response (file header cbuf)
(with-open-file (stream file
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((content-length (content-length header)))
(cond ((chunkedp header)
(save-chunk-response stream cbuf))
(content-length
(call-for-n-octets content-length
(make-stream-writer stream)
cbuf))
(t
(call-until-end (make-stream-writer stream) cbuf))))))
(defun call-with-progress-bar (size fun)
(let ((progress-bar (make-progress-bar size)))
(start-display progress-bar)
(flet ((update (condition)
(update-progress progress-bar
(cbuf-progress-size condition))))
(handler-bind ((cbuf-progress #'update))
(funcall fun)))
(finish-display progress-bar)))
(defun fetch (url file &key (follow-redirects t) quietly
(maximum-redirects *maximum-redirects*))
"Request URL and write the body of the response to FILE."
(setf url (merge-urls url *default-url-defaults*))
(setf file (merge-pathnames file))
(let ((redirect-count 0)
(original-url url)
(connect-url (or (url *proxy-url*) url))
(stream (if quietly
(make-broadcast-stream)
*trace-output*)))
(loop
(when (<= maximum-redirects redirect-count)
(error "Too many redirects for ~A" original-url))
(with-connection (connection (hostname connect-url) (port connect-url))
(let ((cbuf (make-instance 'cbuf :connection connection))
(request (request-buffer "GET" url)))
(write-octets request connection)
(let ((header (read-http-header cbuf)))
(loop while (= (status header) 100)
do (setf header (read-http-header cbuf)))
(cond ((= (status header) 200)
(let ((size (content-length header)))
(format stream "~&; Fetching ~A~%" url)
(if (and (numberp size)
(plusp size))
(format stream "; ~$KB~%" (/ size 1024))
(format stream "; Unknown size~%"))
(if quietly
(save-response file header cbuf)
(call-with-progress-bar (content-length header)
(lambda ()
(save-response file header cbuf))))))
((not (<= 300 (status header) 399))
(error "Unexpected status for ~A: ~A"
url (status header))))
(if (and follow-redirects (<= 300 (status header) 399))
(let ((new-urlstring (ascii-header-value "location" header)))
(when (not new-urlstring)
(error "Redirect code ~D received, but no Location: header"
(status header)))
(incf redirect-count)
(setf url (merge-urls new-urlstring
url))
(format stream "~&; Redirecting to ~A~%" url))
(return (values header (and file (probe-file file)))))))))))
;;; A primitive tar unpacker
(in-package #:qlqs-minitar)
(defun make-block-buffer ()
(make-array 512 :element-type '(unsigned-byte 8) :initial-element 0))
(defun skip-n-blocks (n stream)
(let ((block (make-block-buffer)))
(dotimes (i n)
(read-sequence block stream))))
(defun ascii-subseq (vector start end)
(let ((string (make-string (- end start))))
(loop for i from 0
for j from start below end
do (setf (char string i) (code-char (aref vector j))))
string))
(defun block-asciiz-string (block start length)
(let* ((end (+ start length))
(eos (or (position 0 block :start start :end end)
end)))
(ascii-subseq block start eos)))
(defun prefix (header)
(when (plusp (aref header 345))
(block-asciiz-string header 345 155)))
(defun name (header)
(block-asciiz-string header 0 100))
(defun payload-size (header)
(values (parse-integer (block-asciiz-string header 124 12) :radix 8)))
(defun nth-block (n file)
(with-open-file (stream file :element-type '(unsigned-byte 8))
(let ((block (make-block-buffer)))
(skip-n-blocks (1- n) stream)
(read-sequence block stream)
block)))
(defun payload-type (code)
(case code
(0 :file)
(48 :file)
(53 :directory)
(t :unsupported)))
(defun full-path (header)
(let ((prefix (prefix header))
(name (name header)))
(if prefix
(format nil "~A/~A" prefix name)
name)))
(defun save-file (file size stream)
(multiple-value-bind (full-blocks partial)
(truncate size 512)
(ensure-directories-exist file)
(with-open-file (outstream file
:direction :output
:if-exists :supersede
:element-type '(unsigned-byte 8))
(let ((block (make-block-buffer)))
(dotimes (i full-blocks)
(read-sequence block stream)
(write-sequence block outstream))
(when (plusp partial)
(read-sequence block stream)
(write-sequence block outstream :end partial))))))
(defun unpack-tarball (tarfile &key (directory *default-pathname-defaults*))
(let ((block (make-block-buffer)))
(with-open-file (stream tarfile :element-type '(unsigned-byte 8))
(loop
(let ((size (read-sequence block stream)))
(when (zerop size)
(return))
(unless (= size 512)
(error "Bad size on tarfile"))
(when (every #'zerop block)
(return))
(let* ((payload-code (aref block 156))
(payload-type (payload-type payload-code))
(tar-path (full-path block))
(full-path (merge-pathnames tar-path directory))
(payload-size (payload-size block)))
(case payload-type
(:file
(save-file full-path payload-size stream))
(:directory
(ensure-directories-exist full-path))
(t
(warn "Unknown tar block payload code -- ~D" payload-code)
(skip-n-blocks (ceiling (payload-size block) 512) stream)))))))))
(defun contents (tarfile)
(let ((block (make-block-buffer))
(result '()))
(with-open-file (stream tarfile :element-type '(unsigned-byte 8))
(loop
(let ((size (read-sequence block stream)))
(when (zerop size)
(return (nreverse result)))
(unless (= size 512)
(error "Bad size on tarfile"))
(when (every #'zerop block)
(return (nreverse result)))
(let* ((payload-type (payload-type (aref block 156)))
(tar-path (full-path block))
(payload-size (payload-size block)))
(skip-n-blocks (ceiling payload-size 512) stream)
(case payload-type
(:file
(push tar-path result))
(:directory
(push tar-path result)))))))))
;;;
;;; The actual bootstrapping work
;;;
(in-package #:quicklisp-quickstart)
(defvar *home*
(merge-pathnames (make-pathname :directory '(:relative "quicklisp"))
(user-homedir-pathname)))
(defun qmerge (pathname)
(merge-pathnames pathname *home*))
(defun renaming-fetch (url file)
(let ((tmpfile (qmerge "tmp/fetch.dat")))
(fetch url tmpfile)
(rename-file tmpfile file)))
(defvar *asdf-url* "")
(defvar *quicklisp-tar-url* "")
(defvar *setup-url* "")
(defvar *after-load-message*
(format nil "~&~% ==== quicklisp quickstart loaded ====~%~% ~
To continue, evaluate: (quicklisp-quickstart:install)~%~%"))
(defvar *after-initial-setup-message*
(with-output-to-string (*standard-output*)
(format t "~&~% ==== quicklisp installed ====~%~%")
(format t " To load a system, use: (ql:quickload \"system-name\")~%~%")
(format t " To find systems, use: (ql:system-apropos \"term\")~%~%")
(format t " To load Quicklisp every time you start Lisp, use: (ql:add-to-init-file)~%~%")
(format t " For more information, see /~%~%")))
(defun initial-install ()
(ensure-directories-exist (qmerge "tmp/"))
(ensure-directories-exist (qmerge "quicklisp/"))
(renaming-fetch *asdf-url* (qmerge "asdf.lisp"))
(let ((tmptar (qmerge "tmp/quicklisp.tar")))
(renaming-fetch *quicklisp-tar-url* tmptar)
(unpack-tarball tmptar :directory (qmerge "./")))
(renaming-fetch *setup-url* (qmerge "setup.lisp"))
(load (qmerge "setup.lisp"))
(write-string *after-initial-setup-message*)
(finish-output))
(defun install (&key ((:path *home*) *home*)
((:proxy *proxy-url*) *proxy-url*))
(setf *home* (merge-pathnames *home*))
(let ((setup-file (qmerge "setup.lisp")))
(when (probe-file setup-file)
(multiple-value-bind (result proceed)
(with-simple-restart (load-setup "Load ~S" setup-file)
(error "Quicklisp has already been installed. Load ~S instead."
setup-file))
(declare (ignore result))
(when proceed
(return-from install (load setup-file))))))
(if (find-package '#:ql)
(progn
(write-line "!!! Quicklisp has already been set up. !!!")
(write-string *after-initial-setup-message*)
t)
(call-with-quiet-compilation #'initial-install)))
Try to canonicalize to an absolute pathname ; helps on where
;;; *default-pathname-defaults* isn't an absolute pathname at startup
( e.g. CCL , CMUCL )
(setf *default-pathname-defaults* (truename *default-pathname-defaults*))
(write-string *after-load-message*)
;;; End of quicklisp.lisp
| null | https://raw.githubusercontent.com/melhadad/fuf/57bd0e31afc6aaa03b85f45f4c7195af701508b8/quicklisp.lisp | lisp |
it, start Lisp, then (load "quicklisp.lisp")
contact:
Defining implementation-specific packages and functionality
Clozure CL
Utility function
Low-level networking implementations
A text progress bar
A simple HTTP client
Octet data
ASCII characters as integers
Pattern matching (for finding headers)
pattern-matching chunky stream. Callbacks can be called for a
connection as needed.
Creating HTTP requests as octet buffers
FIXME: get this version string from somewhere else.
HTTP headers
adjust
HTTP URL parsing
Requesting an URL and saving it to a file
) header-data))))
A primitive tar unpacker
The actual bootstrapping work
helps on where
*default-pathname-defaults* isn't an absolute pathname at startup
End of quicklisp.lisp | This is quicklisp.lisp , the quickstart file for Quicklisp . To use
Quicklisp is beta software and comes with no warranty of any kind .
For more information about the Quicklisp beta , see :
/
If you have any questions or comments about Quicklisp , please
< >
(cl:in-package #:cl-user)
(cl:defpackage #:qlqs-user
(:use #:cl))
(cl:in-package #:qlqs-user)
(defpackage #:qlqs-impl
(:use #:cl)
(:export #:*implementation*)
(:export #:definterface
#:defimplementation)
(:export #:lisp
#:abcl
#:allegro
#:ccl
#:clisp
#:cmucl
#:cormanlisp
#:ecl
#:gcl
#:lispworks
#:scl
#:sbcl))
(defpackage #:qlqs-impl-util
(:use #:cl #:qlqs-impl)
(:export #:call-with-quiet-compilation))
(defpackage #:qlqs-network
(:use #:cl #:qlqs-impl)
(:export #:open-connection
#:write-octets
#:read-octets
#:close-connection
#:with-connection))
(defpackage #:qlqs-progress
(:use #:cl)
(:export #:make-progress-bar
#:start-display
#:update-progress
#:finish-display))
(defpackage #:qlqs-http
(:use #:cl #:qlqs-network #:qlqs-progress)
(:export #:fetch
#:*proxy-url*
#:*maximum-redirects*
#:*default-url-defaults*))
(defpackage #:qlqs-minitar
(:use #:cl)
(:export #:tarball-contents
#:unpack-tarball))
(defpackage #:quicklisp-quickstart
(:use #:cl #:qlqs-impl #:qlqs-impl-util #:qlqs-http #:qlqs-minitar)
(:export #:install
#:*proxy-url*
#:*asdf-url*
#:*quicklisp-tar-url*
#:*setup-url*
#:*after-load-message*
#:*after-initial-setup-message*))
(in-package #:qlqs-impl)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun error-unimplemented (&rest args)
(declare (ignore args))
(error "Not implemented")))
(defmacro neuter-package (name)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(let ((definition (fdefinition 'error-unimplemented)))
(do-external-symbols (symbol ,(string name))
(unless (fboundp symbol)
(setf (fdefinition symbol) definition))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun feature-expression-passes-p (expression)
(cond ((keywordp expression)
(member expression *features*))
((consp expression)
(case (first expression)
(or
(some 'feature-expression-passes-p (rest expression)))
(and
(every 'feature-expression-passes-p (rest expression)))))
(t (error "Unrecognized feature expression -- ~S" expression)))))
(defmacro define-implementation-package (feature package-name &rest options)
(let* ((output-options '((:use)
(:export #:lisp)))
(prep (cdr (assoc :prep options)))
(class-option (cdr (assoc :class options)))
(class (first class-option))
(superclasses (rest class-option))
(import-options '())
(effectivep (feature-expression-passes-p feature)))
(dolist (option options)
(ecase (first option)
((:prep :class))
((:import-from
:import)
(push option import-options))
((:export
:shadow
:intern
:documentation)
(push option output-options))
((:reexport-from)
(push (cons :export (cddr option)) output-options)
(push (cons :import-from (cdr option)) import-options))))
`(eval-when (:compile-toplevel :load-toplevel :execute)
,@(when effectivep
prep)
(defclass ,class ,superclasses ())
(defpackage ,package-name ,@output-options
,@(when effectivep
import-options))
,@(when effectivep
`((setf *implementation* (make-instance ',class))))
,@(unless effectivep
`((neuter-package ,package-name))))))
(defmacro definterface (name lambda-list &body options)
(let* ((forbidden (intersection lambda-list lambda-list-keywords))
(gf-options (remove :implementation options :key #'first))
(implementations (set-difference options gf-options)))
(when forbidden
(error "~S not allowed in definterface lambda list" forbidden))
(flet ((method-option (class body)
`(:method ((*implementation* ,class) ,@lambda-list)
,@body)))
(let ((generic-name (intern (format nil "%~A" name))))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defgeneric ,generic-name (lisp ,@lambda-list)
,@gf-options
,@(mapcar (lambda (implementation)
(destructuring-bind (class &rest body)
(rest implementation)
(method-option class body)))
implementations))
(defun ,name ,lambda-list
(,generic-name *implementation* ,@lambda-list)))))))
(defmacro defimplementation (name-and-options
lambda-list &body body)
(destructuring-bind (name &key (for t) qualifier)
(if (consp name-and-options)
name-and-options
(list name-and-options))
(unless for
(error "You must specify an implementation name."))
(let ((generic-name (find-symbol (format nil "%~A" name))))
(unless (and generic-name
(fboundp generic-name))
(error "~S does not name an implementation function" name))
`(defmethod ,generic-name
,@(when qualifier (list qualifier))
,(list* `(*implementation* ,for) lambda-list) ,@body))))
Bootstrap implementations
(defvar *implementation* nil)
(defclass lisp () ())
Allegro Common Lisp
(define-implementation-package :allegro #:qlqs-allegro
(:documentation
"Allegro Common Lisp - /")
(:class allegro)
(:reexport-from #:socket
#:make-socket)
(:reexport-from #:excl
#:read-vector))
Armed Bear Common Lisp
(define-implementation-package :abcl #:qlqs-abcl
(:documentation
"Armed Bear Common Lisp - -lisp.net/project/armedbear/")
(:class abcl)
(:reexport-from #:system
#:make-socket
#:get-socket-stream))
(define-implementation-package :ccl #:qlqs-ccl
(:documentation
"Clozure Common Lisp - ")
(:class ccl)
(:reexport-from #:ccl
#:make-socket))
GNU CLISP
(define-implementation-package :clisp #:qlqs-clisp
(:documentation "GNU CLISP - /")
(:class clisp)
(:reexport-from #:socket
#:socket-connect)
(:reexport-from #:ext
#:read-byte-sequence))
CMUCL
(define-implementation-package :cmu #:qlqs-cmucl
(:documentation "CMU Common Lisp - /")
(:class cmucl)
(:reexport-from #:ext
#:*gc-verbose*)
(:reexport-from #:system
#:make-fd-stream)
(:reexport-from #:extensions
#:connect-to-inet-socket))
(defvar qlqs-cmucl:*gc-verbose* nil)
ECL
(define-implementation-package :ecl #:qlqs-ecl
(:documentation "ECL - /")
(:class ecl)
(:prep
(require 'sockets))
(:intern #:host-network-address)
(:reexport-from #:sb-bsd-sockets
#:get-host-by-name
#:host-ent-address
#:socket-connect
#:socket-make-stream
#:inet-socket))
LispWorks
(define-implementation-package :lispworks #:qlqs-lispworks
(:documentation "LispWorks - /")
(:class lispworks)
(:prep
(require "comm"))
(:reexport-from #:comm
#:open-tcp-stream
#:get-host-entry))
SBCL
(define-implementation-package :sbcl #:qlqs-sbcl
(:class sbcl)
(:documentation
"Steel Bank Common Lisp - /")
(:prep
(require 'sb-bsd-sockets))
(:intern #:host-network-address)
(:reexport-from #:sb-ext
#:compiler-note)
(:reexport-from #:sb-bsd-sockets
#:get-host-by-name
#:inet-socket
#:host-ent-address
#:socket-connect
#:socket-make-stream))
(in-package #:qlqs-impl-util)
(definterface call-with-quiet-compilation (fun)
(:implementation t
(let ((*load-verbose* nil)
(*compile-verbose* nil)
(*load-print* nil)
(*compile-print* nil))
(handler-bind ((warning #'muffle-warning))
(funcall fun)))))
(defimplementation (call-with-quiet-compilation :for sbcl :qualifier :around)
(fun)
(declare (ignorable fun))
(handler-bind ((qlqs-sbcl:compiler-note #'muffle-warning))
(call-next-method)))
(defimplementation (call-with-quiet-compilation :for cmucl :qualifier :around)
(fun)
(declare (ignorable fun))
(let ((qlqs-cmucl:*gc-verbose* nil))
(call-next-method)))
(in-package #:qlqs-network)
(definterface host-address (host)
(:implementation t
host)
(:implementation sbcl
(qlqs-sbcl:host-ent-address (qlqs-sbcl:get-host-by-name host))))
(definterface open-connection (host port)
(:implementation t
(declare (ignorable host port))
(error "Sorry, quicklisp in implementation ~S is not supported yet."
(lisp-implementation-type)))
(:implementation allegro
(qlqs-allegro:make-socket :remote-host host
:remote-port port))
(:implementation abcl
(let ((socket (qlqs-abcl:make-socket host port)))
(qlqs-abcl:get-socket-stream socket :element-type '(unsigned-byte 8))))
(:implementation ccl
(qlqs-ccl:make-socket :remote-host host
:remote-port port))
(:implementation clisp
(qlqs-clisp:socket-connect port host :element-type '(unsigned-byte 8)))
(:implementation cmucl
(let ((fd (qlqs-cmucl:connect-to-inet-socket host port)))
(qlqs-cmucl:make-fd-stream fd
:element-type '(unsigned-byte 8)
:binary-stream-p t
:input t
:output t)))
(:implementation ecl
(let* ((endpoint (qlqs-ecl:host-ent-address
(qlqs-ecl:get-host-by-name host)))
(socket (make-instance 'qlqs-ecl:inet-socket
:protocol :tcp
:type :stream)))
(qlqs-ecl:socket-connect socket endpoint port)
(qlqs-ecl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full)))
(:implementation lispworks
(qlqs-lispworks:open-tcp-stream host port
:direction :io
:read-timeout nil
:element-type '(unsigned-byte 8)
:timeout 5))
(:implementation sbcl
(let* ((endpoint (qlqs-sbcl:host-ent-address
(qlqs-sbcl:get-host-by-name host)))
(socket (make-instance 'qlqs-sbcl:inet-socket
:protocol :tcp
:type :stream)))
(qlqs-sbcl:socket-connect socket endpoint port)
(qlqs-sbcl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full))))
(definterface read-octets (buffer connection)
(:implementation t
(read-sequence buffer connection))
(:implementation allegro
(qlqs-allegro:read-vector buffer connection))
(:implementation clisp
(qlqs-clisp:read-byte-sequence buffer connection
:no-hang nil
:interactive t)))
(definterface write-octets (buffer connection)
(:implementation t
(write-sequence buffer connection)
(finish-output connection)))
(definterface close-connection (connection)
(:implementation t
(ignore-errors (close connection))))
(definterface call-with-connection (host port fun)
(:implementation t
(let (connection)
(unwind-protect
(progn
(setf connection (open-connection host port))
(funcall fun connection))
(when connection
(close connection))))))
(defmacro with-connection ((connection host port) &body body)
`(call-with-connection ,host ,port (lambda (,connection) ,@body)))
(in-package #:qlqs-progress)
(defclass progress-bar ()
((start-time
:initarg :start-time
:accessor start-time)
(end-time
:initarg :end-time
:accessor end-time)
(progress-character
:initarg :progress-character
:accessor progress-character)
(character-count
:initarg :character-count
:accessor character-count
:documentation "How many characters wide is the progress bar?")
(characters-so-far
:initarg :characters-so-far
:accessor characters-so-far)
(update-interval
:initarg :update-interval
:accessor update-interval
:documentation "Update the progress bar display after this many
internal-time units.")
(last-update-time
:initarg :last-update-time
:accessor last-update-time
:documentation "The display was last updated at this time.")
(total
:initarg :total
:accessor total
:documentation "The total number of units tracked by this progress bar.")
(progress
:initarg :progress
:accessor progress
:documentation "How far in the progress are we?")
(pending
:initarg :pending
:accessor pending
:documentation "How many raw units should be tracked in the next
display update?"))
(:default-initargs
:progress-character #\=
:character-count 50
:characters-so-far 0
:update-interval (floor internal-time-units-per-second 4)
:last-update-time 0
:total 0
:progress 0
:pending 0))
(defgeneric start-display (progress-bar))
(defgeneric update-progress (progress-bar unit-count))
(defgeneric update-display (progress-bar))
(defgeneric finish-display (progress-bar))
(defgeneric elapsed-time (progress-bar))
(defgeneric units-per-second (progress-bar))
(defmethod start-display (progress-bar)
(setf (last-update-time progress-bar) (get-internal-real-time))
(setf (start-time progress-bar) (get-internal-real-time))
(fresh-line)
(finish-output))
(defmethod update-display (progress-bar)
(incf (progress progress-bar) (pending progress-bar))
(setf (pending progress-bar) 0)
(setf (last-update-time progress-bar) (get-internal-real-time))
(let* ((showable (floor (character-count progress-bar)
(/ (total progress-bar) (progress progress-bar))))
(needed (- showable (characters-so-far progress-bar))))
(setf (characters-so-far progress-bar) showable)
(dotimes (i needed)
(write-char (progress-character progress-bar)))
(finish-output)))
(defmethod update-progress (progress-bar unit-count)
(incf (pending progress-bar) unit-count)
(let ((now (get-internal-real-time)))
(when (< (update-interval progress-bar)
(- now (last-update-time progress-bar)))
(update-display progress-bar))))
(defmethod finish-display (progress-bar)
(update-display progress-bar)
(setf (end-time progress-bar) (get-internal-real-time))
(terpri)
(format t "~:D bytes in ~$ seconds (~$KB/sec)"
(total progress-bar)
(elapsed-time progress-bar)
(/ (units-per-second progress-bar) 1024))
(finish-output))
(defmethod elapsed-time (progress-bar)
(/ (- (end-time progress-bar) (start-time progress-bar))
internal-time-units-per-second))
(defmethod units-per-second (progress-bar)
(if (plusp (elapsed-time progress-bar))
(/ (total progress-bar) (elapsed-time progress-bar))
0))
(defun kb/sec (progress-bar)
(/ (units-per-second progress-bar) 1024))
(defparameter *uncertain-progress-chars* "?")
(defclass uncertain-size-progress-bar (progress-bar)
((progress-char-index
:initarg :progress-char-index
:accessor progress-char-index)
(units-per-char
:initarg :units-per-char
:accessor units-per-char))
(:default-initargs
:total 0
:progress-char-index 0
:units-per-char (floor (expt 1024 2) 50)))
(defmethod update-progress :after ((progress-bar uncertain-size-progress-bar)
unit-count)
(incf (total progress-bar) unit-count))
(defmethod progress-character ((progress-bar uncertain-size-progress-bar))
(let ((index (progress-char-index progress-bar)))
(prog1
(char *uncertain-progress-chars* index)
(setf (progress-char-index progress-bar)
(mod (1+ index) (length *uncertain-progress-chars*))))))
(defmethod update-display ((progress-bar uncertain-size-progress-bar))
(setf (last-update-time progress-bar) (get-internal-real-time))
(multiple-value-bind (chars pend)
(floor (pending progress-bar) (units-per-char progress-bar))
(setf (pending progress-bar) pend)
(dotimes (i chars)
(write-char (progress-character progress-bar))
(incf (characters-so-far progress-bar))
(when (<= (character-count progress-bar)
(characters-so-far progress-bar))
(terpri)
(setf (characters-so-far progress-bar) 0)
(finish-output)))
(finish-output)))
(defun make-progress-bar (total)
(if (or (not total) (zerop total))
(make-instance 'uncertain-size-progress-bar)
(make-instance 'progress-bar :total total)))
(in-package #:qlqs-http)
(deftype octet ()
'(unsigned-byte 8))
(defun make-octet-vector (size)
(make-array size :element-type 'octet
:initial-element 0))
(defun octet-vector (&rest octets)
(make-array (length octets) :element-type 'octet
:initial-contents octets))
(defun acode (char)
(cond ((eql char :cr)
13)
((eql char :lf)
10)
(t
(let ((code (char-code char)))
(if (<= 0 code 127)
code
(error "Character ~S is not in the ASCII character set"
char))))))
(defvar *whitespace*
(list (acode #\Space) (acode #\Tab) (acode :cr) (acode :lf)))
(defun whitep (code)
(member code *whitespace*))
(defun ascii-vector (string)
(let ((vector (make-octet-vector (length string))))
(loop for char across string
for code = (char-code char)
for i from 0
if (< 127 code) do
(error "Invalid character for ASCII -- ~A" char)
else
do (setf (aref vector i) code))
vector))
(defun ascii-subseq (vector start end)
"Return a subseq of octet-specialized VECTOR as a string."
(let ((string (make-string (- end start))))
(loop for i from 0
for j from start below end
do (setf (char string i) (code-char (aref vector j))))
string))
(defun ascii-downcase (code)
(if (<= 65 code 90)
(+ code 32)
code))
(defun ascii-equal (a b)
(eql (ascii-downcase a) (ascii-downcase b)))
(defmacro acase (value &body cases)
(flet ((convert-case-keys (keys)
(mapcar (lambda (key)
(etypecase key
(integer key)
(character (char-code key))
(symbol
(ecase key
(:cr 13)
(:lf 10)
((t) t)))))
(if (consp keys) keys (list keys)))))
`(case ,value
,@(mapcar (lambda (case)
(destructuring-bind (keys &rest body)
case
`(,(if (eql keys t)
t
(convert-case-keys keys))
,@body)))
cases))))
(defclass matcher ()
((pattern
:initarg :pattern
:reader pattern)
(pos
:initform 0
:accessor match-pos)
(matchedp
:initform nil
:accessor matchedp)))
(defun reset-match (matcher)
(setf (match-pos matcher) 0
(matchedp matcher) nil))
(define-condition match-failure (error) ())
(defun match (matcher input &key (start 0) end error)
(let ((i start)
(end (or end (length input)))
(match-end (length (pattern matcher))))
(with-slots (pattern pos)
matcher
(loop
(cond ((= pos match-end)
(let ((match-start (- i pos)))
(setf pos 0)
(setf (matchedp matcher) t)
(return (values match-start (+ match-start match-end)))))
((= i end)
(return nil))
((= (aref pattern pos)
(aref input i))
(incf i)
(incf pos))
(t
(if error
(error 'match-failure)
(if (zerop pos)
(incf i)
(setf pos 0)))))))))
(defun ascii-matcher (string)
(make-instance 'matcher
:pattern (ascii-vector string)))
(defun octet-matcher (&rest octets)
(make-instance 'matcher
:pattern (apply 'octet-vector octets)))
(defun acode-matcher (&rest codes)
(make-instance 'matcher
:pattern (make-array (length codes)
:element-type 'octet
:initial-contents
(mapcar 'acode codes))))
" Connection Buffers " are a kind of callback - driven ,
certain number of octets or until one or more patterns are seen in
the input . cbufs automatically refill themselves from a
(defvar *cbuf-buffer-size* 8192)
(define-condition end-of-data (error) ())
(defclass cbuf ()
((data
:initarg :data
:accessor data)
(connection
:initarg :connection
:accessor connection)
(start
:initarg :start
:accessor start)
(end
:initarg :end
:accessor end)
(eofp
:initarg :eofp
:accessor eofp))
(:default-initargs
:data (make-octet-vector *cbuf-buffer-size*)
:connection nil
:start 0
:end 0
:eofp nil)
(:documentation "A CBUF is a connection buffer that keeps track of
incoming data from a connection. Several functions make it easy to
treat a CBUF as a kind of chunky, callback-driven stream."))
(define-condition cbuf-progress ()
((size
:initarg :size
:accessor cbuf-progress-size
:initform 0)))
(defun call-processor (fun cbuf start end)
(signal 'cbuf-progress :size (- end start))
(funcall fun (data cbuf) start end))
(defun make-cbuf (connection)
(make-instance 'cbuf :connection connection))
(defun make-stream-writer (stream)
"Create a callback for writing data to STREAM."
(lambda (data start end)
(write-sequence data stream :start start :end end)))
(defgeneric size (cbuf)
(:method ((cbuf cbuf))
(- (end cbuf) (start cbuf))))
(defgeneric emptyp (cbuf)
(:method ((cbuf cbuf))
(zerop (size cbuf))))
(defgeneric refill (cbuf)
(:method ((cbuf cbuf))
(when (eofp cbuf)
(error 'end-of-data))
(setf (start cbuf) 0)
(setf (end cbuf)
(read-octets (data cbuf)
(connection cbuf)))
(cond ((emptyp cbuf)
(setf (eofp cbuf) t)
(error 'end-of-data))
(t (size cbuf)))))
(defun process-all (fun cbuf)
(unless (emptyp cbuf)
(call-processor fun cbuf (start cbuf) (end cbuf))))
(defun multi-cmatch (matchers cbuf)
(let (start end)
(dolist (matcher matchers (values start end))
(multiple-value-bind (s e)
(match matcher (data cbuf)
:start (start cbuf)
:end (end cbuf))
(when (and s (or (null start) (< s start)))
(setf start s
end e))))))
(defun cmatch (matcher cbuf)
(if (consp matcher)
(multi-cmatch matcher cbuf)
(match matcher (data cbuf) :start (start cbuf) :end (end cbuf))))
(defun call-until-end (fun cbuf)
(handler-case
(loop
(process-all fun cbuf)
(refill cbuf))
(end-of-data ()
(return-from call-until-end))))
(defun show-cbuf (context cbuf)
(format t "cbuf: ~A ~D - ~D~%" context (start cbuf) (end cbuf)))
(defun call-for-n-octets (n fun cbuf)
(let ((remaining n))
(loop
(when (<= remaining (size cbuf))
(let ((end (+ (start cbuf) remaining)))
(call-processor fun cbuf (start cbuf) end)
(setf (start cbuf) end)
(return)))
(process-all fun cbuf)
(decf remaining (size cbuf))
(refill cbuf))))
(defun call-until-matching (matcher fun cbuf)
(loop
(multiple-value-bind (start end)
(cmatch matcher cbuf)
(when start
(call-processor fun cbuf (start cbuf) end)
(setf (start cbuf) end)
(return)))
(process-all fun cbuf)
(refill cbuf)))
(defun ignore-data (data start end)
(declare (ignore data start end)))
(defun skip-until-matching (matcher cbuf)
(call-until-matching matcher 'ignore-data cbuf))
(defclass octet-sink ()
((storage
:initarg :storage
:accessor storage))
(:default-initargs
:storage (make-array 1024 :element-type 'octet
:fill-pointer 0
:adjustable t))
(:documentation "A simple stream-like target for collecting
octets."))
(defun add-octet (octet sink)
(vector-push-extend octet (storage sink)))
(defun add-octets (octets sink &key (start 0) end)
(setf end (or end (length octets)))
(loop for i from start below end
do (add-octet (aref octets i) sink)))
(defun add-string (string sink)
(loop for char across string
for code = (char-code char)
do (add-octet code sink)))
(defun add-strings (sink &rest strings)
(mapc (lambda (string) (add-string string sink)) strings))
(defun add-newline (sink)
(add-octet 13 sink)
(add-octet 10 sink))
(defun sink-buffer (sink)
(subseq (storage sink) 0))
(defvar *proxy-url* nil)
(defun full-proxy-path (host port path)
(format nil "~:[http~;https~]://~A~:[:~D~;~*~]~A"
(= port 443)
host
(or (= port 80)
(= port 443))
port
path))
(defun make-request-buffer (host port path &key (method "GET"))
(setf method (string method))
(when *proxy-url*
(setf path (full-proxy-path host port path)))
(let ((sink (make-instance 'octet-sink)))
(flet ((add-line (&rest strings)
(apply #'add-strings sink strings)
(add-newline sink)))
(add-line method " " path " HTTP/1.1")
(add-line "Host: " host (if (= port 80) ""
(format nil ":~D" port)))
(add-line "Connection: close")
(add-line "User-Agent: quicklisp-bootstrap/2011040600")
(add-newline sink)
(sink-buffer sink))))
(defun sink-until-matching (matcher cbuf)
(let ((sink (make-instance 'octet-sink)))
(call-until-matching
matcher
(lambda (buffer start end)
(add-octets buffer sink :start start :end end))
cbuf)
(sink-buffer sink)))
(defclass header ()
((data
:initarg :data
:accessor data)
(status
:initarg :status
:accessor status)
(name-starts
:initarg :name-starts
:accessor name-starts)
(name-ends
:initarg :name-ends
:accessor name-ends)
(value-starts
:initarg :value-starts
:accessor value-starts)
(value-ends
:initarg :value-ends
:accessor value-ends)))
(defmethod print-object ((header header) stream)
(print-unreadable-object (header stream :type t)
(prin1 (status header) stream)))
(defun matches-at (pattern target pos)
(= (mismatch pattern target :start2 pos) (length pattern)))
(defun header-value-indexes (field-name header)
(loop with data = (data header)
with pattern = (ascii-vector (string-downcase field-name))
for start across (name-starts header)
for i from 0
when (matches-at pattern data start)
return (values (aref (value-starts header) i)
(aref (value-ends header) i))))
(defun ascii-header-value (field-name header)
(multiple-value-bind (start end)
(header-value-indexes field-name header)
(when start
(ascii-subseq (data header) start end))))
(defun all-field-names (header)
(map 'list
(lambda (start end)
(ascii-subseq (data header) start end))
(name-starts header)
(name-ends header)))
(defun headers-alist (header)
(mapcar (lambda (name)
(cons name (ascii-header-value name header)))
(all-field-names header)))
(defmethod describe-object :after ((header header) stream)
(format stream "~&Decoded headers:~% ~S~%" (headers-alist header)))
(defun content-length (header)
(let ((field-value (ascii-header-value "content-length" header)))
(when field-value
(let ((value (ignore-errors (parse-integer field-value))))
(or value
(error "Content-Length header field value is not a number -- ~A"
field-value))))))
(defun chunkedp (header)
(string= (ascii-header-value "transfer-encoding" header) "chunked"))
(defun location (header)
(ascii-header-value "location" header))
(defun status-code (vector)
(let* ((space (position (acode #\Space) vector))
(c1 (- (aref vector (incf space)) 48))
(c2 (- (aref vector (incf space)) 48))
(c3 (- (aref vector (incf space)) 48)))
(+ (* c1 100)
(* c2 10)
(* c3 1))))
(defun force-downcase-field-names (header)
(loop with data = (data header)
for start across (name-starts header)
for end across (name-ends header)
do (loop for i from start below end
for code = (aref data i)
do (setf (aref data i) (ascii-downcase code)))))
(defun skip-white-forward (pos vector)
(position-if-not 'whitep vector :start pos))
(defun skip-white-backward (pos vector)
(let ((nonwhite (position-if-not 'whitep vector :end pos :from-end t)))
(if nonwhite
(1+ nonwhite)
pos)))
(defun contract-field-value-indexes (header)
the indexes in the header accordingly."
(loop with starts = (value-starts header)
with ends = (value-ends header)
with data = (data header)
for i from 0
for start across starts
for end across ends
do
(setf (aref starts i) (skip-white-forward start data))
(setf (aref ends i) (skip-white-backward end data))))
(defun next-line-pos (vector)
(let ((pos 0))
(labels ((finish (&optional (i pos))
(return-from next-line-pos i))
(after-cr (code)
(acase code
(:lf (finish pos))
(t (finish (1- pos)))))
(pending (code)
(acase code
(:cr #'after-cr)
(:lf (finish pos))
(t #'pending))))
(let ((state #'pending))
(loop
(setf state (funcall state (aref vector pos)))
(incf pos))))))
(defun make-hvector ()
(make-array 16 :fill-pointer 0 :adjustable t))
(defun process-header (vector)
"Create a HEADER instance from the octet data in VECTOR."
(let* ((name-starts (make-hvector))
(name-ends (make-hvector))
(value-starts (make-hvector))
(value-ends (make-hvector))
(header (make-instance 'header
:data vector
:status 999
:name-starts name-starts
:name-ends name-ends
:value-starts value-starts
:value-ends value-ends))
(mark nil)
(pos (next-line-pos vector)))
(unless pos
(error "Unable to process HTTP header"))
(setf (status header) (status-code vector))
(labels ((save (value vector)
(vector-push-extend value vector))
(mark ()
(setf mark pos))
(clear-mark ()
(setf mark nil))
(finish ()
(if mark
(save mark value-ends)
(save pos value-ends))
(force-downcase-field-names header)
(contract-field-value-indexes header)
(return-from process-header header))
(in-new-line (code)
(acase code
((#\Tab #\Space) (setf mark nil) #'in-value)
(t
(when mark
(save mark value-ends))
(clear-mark)
(save pos name-starts)
(in-name code))))
(after-cr (code)
(acase code
(:lf #'in-new-line)
(t (in-new-line code))))
(pending-value (code)
(acase code
((#\Tab #\Space) #'pending-value)
(:cr #'after-cr)
(:lf #'in-new-line)
(t (save pos value-starts) #'in-value)))
(in-name (code)
(acase code
(#\:
(save pos name-ends)
(save (1+ pos) value-starts)
#'in-value)
((:cr :lf)
(finish))
((#\Tab #\Space)
(error "Unexpected whitespace in header field name"))
(t
(unless (<= 0 code 127)
(error "Unexpected non-ASCII header field name"))
#'in-name)))
(in-value (code)
(acase code
(:lf (mark) #'in-new-line)
(:cr (mark) #'after-cr)
(t #'in-value))))
(let ((state #'in-new-line))
(loop
(incf pos)
(when (<= (length vector) pos)
(error "No header found in response"))
(setf state (funcall state (aref vector pos))))))))
(defclass url ()
((hostname
:initarg :hostname
:accessor hostname
:initform nil)
(port
:initarg :port
:accessor port
:initform 80)
(path
:initarg :path
:accessor path
:initform "/")))
(defun parse-urlstring (urlstring)
(setf urlstring (string-trim " " urlstring))
(let* ((pos (mismatch urlstring "http://" :test 'char-equal))
(mark pos)
(url (make-instance 'url)))
(labels ((save ()
(subseq urlstring mark pos))
(mark ()
(setf mark pos))
(finish ()
(return-from parse-urlstring url))
(hostname-char-p (char)
(position char "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."
:test 'char-equal))
(at-start (char)
(case char
(#\/
(setf (port url) nil)
(mark)
#'in-path)
(t
#'in-host)))
(in-host (char)
(case char
((#\/ :end)
(setf (hostname url) (save))
(mark)
#'in-path)
(#\:
(setf (hostname url) (save))
(mark)
#'in-port)
(t
(unless (hostname-char-p char)
(error "~S is not a valid URL" urlstring))
#'in-host)))
(in-port (char)
(case char
((#\/ :end)
(setf (port url)
(parse-integer urlstring
:start (1+ mark)
:end pos))
(mark)
#'in-path)
(t
(unless (digit-char-p char)
(error "Bad port in URL ~S" urlstring))
#'in-port)))
(in-path (char)
(case char
((#\# :end)
(setf (path url) (save))
(finish)))
#'in-path))
(let ((state #'at-start))
(loop
(when (<= (length urlstring) pos)
(funcall state :end)
(finish))
(setf state (funcall state (aref urlstring pos)))
(incf pos))))))
(defun url (thing)
(if (stringp thing)
(parse-urlstring thing)
thing))
(defgeneric request-buffer (method url)
(:method (method url)
(setf url (url url))
(make-request-buffer (hostname url) (port url) (path url)
:method method)))
(defun urlstring (url)
(format nil "~@[http://~A~]~@[:~D~]~A"
(hostname url)
(and (/= 80 (port url)) (port url))
(path url)))
(defmethod print-object ((url url) stream)
(print-unreadable-object (url stream :type t)
(prin1 (urlstring url) stream)))
(defun merge-urls (url1 url2)
(setf url1 (url url1))
(setf url2 (url url2))
(make-instance 'url
:hostname (or (hostname url1)
(hostname url2))
:port (or (port url1)
(port url2))
:path (or (path url1)
(path url2))))
(defparameter *maximum-redirects* 10)
(defvar *default-url-defaults* (url "/"))
(defun read-http-header (cbuf)
(let ((header-data (sink-until-matching (list (acode-matcher :lf :lf)
(acode-matcher :cr :cr)
(acode-matcher :cr :lf :cr :lf))
cbuf)))
(process-header header-data)))
(defun read-chunk-header (cbuf)
(let* ((header-data (sink-until-matching (acode-matcher :cr :lf) cbuf))
(end (or (position (acode :cr) header-data)
(values (parse-integer (ascii-subseq header-data 0 end) :radix 16))))
(defun save-chunk-response (stream cbuf)
"For a chunked response, read all chunks and write them to STREAM."
(let ((fun (make-stream-writer stream))
(matcher (acode-matcher :cr :lf)))
(loop
(let ((chunk-size (read-chunk-header cbuf)))
(when (zerop chunk-size)
(return))
(call-for-n-octets chunk-size fun cbuf)
(skip-until-matching matcher cbuf)))))
(defun save-response (file header cbuf)
(with-open-file (stream file
:direction :output
:if-exists :supersede
:element-type 'octet)
(let ((content-length (content-length header)))
(cond ((chunkedp header)
(save-chunk-response stream cbuf))
(content-length
(call-for-n-octets content-length
(make-stream-writer stream)
cbuf))
(t
(call-until-end (make-stream-writer stream) cbuf))))))
(defun call-with-progress-bar (size fun)
(let ((progress-bar (make-progress-bar size)))
(start-display progress-bar)
(flet ((update (condition)
(update-progress progress-bar
(cbuf-progress-size condition))))
(handler-bind ((cbuf-progress #'update))
(funcall fun)))
(finish-display progress-bar)))
(defun fetch (url file &key (follow-redirects t) quietly
(maximum-redirects *maximum-redirects*))
"Request URL and write the body of the response to FILE."
(setf url (merge-urls url *default-url-defaults*))
(setf file (merge-pathnames file))
(let ((redirect-count 0)
(original-url url)
(connect-url (or (url *proxy-url*) url))
(stream (if quietly
(make-broadcast-stream)
*trace-output*)))
(loop
(when (<= maximum-redirects redirect-count)
(error "Too many redirects for ~A" original-url))
(with-connection (connection (hostname connect-url) (port connect-url))
(let ((cbuf (make-instance 'cbuf :connection connection))
(request (request-buffer "GET" url)))
(write-octets request connection)
(let ((header (read-http-header cbuf)))
(loop while (= (status header) 100)
do (setf header (read-http-header cbuf)))
(cond ((= (status header) 200)
(let ((size (content-length header)))
(format stream "~&; Fetching ~A~%" url)
(if (and (numberp size)
(plusp size))
(format stream "; ~$KB~%" (/ size 1024))
(format stream "; Unknown size~%"))
(if quietly
(save-response file header cbuf)
(call-with-progress-bar (content-length header)
(lambda ()
(save-response file header cbuf))))))
((not (<= 300 (status header) 399))
(error "Unexpected status for ~A: ~A"
url (status header))))
(if (and follow-redirects (<= 300 (status header) 399))
(let ((new-urlstring (ascii-header-value "location" header)))
(when (not new-urlstring)
(error "Redirect code ~D received, but no Location: header"
(status header)))
(incf redirect-count)
(setf url (merge-urls new-urlstring
url))
(format stream "~&; Redirecting to ~A~%" url))
(return (values header (and file (probe-file file)))))))))))
(in-package #:qlqs-minitar)
(defun make-block-buffer ()
(make-array 512 :element-type '(unsigned-byte 8) :initial-element 0))
(defun skip-n-blocks (n stream)
(let ((block (make-block-buffer)))
(dotimes (i n)
(read-sequence block stream))))
(defun ascii-subseq (vector start end)
(let ((string (make-string (- end start))))
(loop for i from 0
for j from start below end
do (setf (char string i) (code-char (aref vector j))))
string))
(defun block-asciiz-string (block start length)
(let* ((end (+ start length))
(eos (or (position 0 block :start start :end end)
end)))
(ascii-subseq block start eos)))
(defun prefix (header)
(when (plusp (aref header 345))
(block-asciiz-string header 345 155)))
(defun name (header)
(block-asciiz-string header 0 100))
(defun payload-size (header)
(values (parse-integer (block-asciiz-string header 124 12) :radix 8)))
(defun nth-block (n file)
(with-open-file (stream file :element-type '(unsigned-byte 8))
(let ((block (make-block-buffer)))
(skip-n-blocks (1- n) stream)
(read-sequence block stream)
block)))
(defun payload-type (code)
(case code
(0 :file)
(48 :file)
(53 :directory)
(t :unsupported)))
(defun full-path (header)
(let ((prefix (prefix header))
(name (name header)))
(if prefix
(format nil "~A/~A" prefix name)
name)))
(defun save-file (file size stream)
(multiple-value-bind (full-blocks partial)
(truncate size 512)
(ensure-directories-exist file)
(with-open-file (outstream file
:direction :output
:if-exists :supersede
:element-type '(unsigned-byte 8))
(let ((block (make-block-buffer)))
(dotimes (i full-blocks)
(read-sequence block stream)
(write-sequence block outstream))
(when (plusp partial)
(read-sequence block stream)
(write-sequence block outstream :end partial))))))
(defun unpack-tarball (tarfile &key (directory *default-pathname-defaults*))
(let ((block (make-block-buffer)))
(with-open-file (stream tarfile :element-type '(unsigned-byte 8))
(loop
(let ((size (read-sequence block stream)))
(when (zerop size)
(return))
(unless (= size 512)
(error "Bad size on tarfile"))
(when (every #'zerop block)
(return))
(let* ((payload-code (aref block 156))
(payload-type (payload-type payload-code))
(tar-path (full-path block))
(full-path (merge-pathnames tar-path directory))
(payload-size (payload-size block)))
(case payload-type
(:file
(save-file full-path payload-size stream))
(:directory
(ensure-directories-exist full-path))
(t
(warn "Unknown tar block payload code -- ~D" payload-code)
(skip-n-blocks (ceiling (payload-size block) 512) stream)))))))))
(defun contents (tarfile)
(let ((block (make-block-buffer))
(result '()))
(with-open-file (stream tarfile :element-type '(unsigned-byte 8))
(loop
(let ((size (read-sequence block stream)))
(when (zerop size)
(return (nreverse result)))
(unless (= size 512)
(error "Bad size on tarfile"))
(when (every #'zerop block)
(return (nreverse result)))
(let* ((payload-type (payload-type (aref block 156)))
(tar-path (full-path block))
(payload-size (payload-size block)))
(skip-n-blocks (ceiling payload-size 512) stream)
(case payload-type
(:file
(push tar-path result))
(:directory
(push tar-path result)))))))))
(in-package #:quicklisp-quickstart)
(defvar *home*
(merge-pathnames (make-pathname :directory '(:relative "quicklisp"))
(user-homedir-pathname)))
(defun qmerge (pathname)
(merge-pathnames pathname *home*))
(defun renaming-fetch (url file)
(let ((tmpfile (qmerge "tmp/fetch.dat")))
(fetch url tmpfile)
(rename-file tmpfile file)))
(defvar *asdf-url* "")
(defvar *quicklisp-tar-url* "")
(defvar *setup-url* "")
(defvar *after-load-message*
(format nil "~&~% ==== quicklisp quickstart loaded ====~%~% ~
To continue, evaluate: (quicklisp-quickstart:install)~%~%"))
(defvar *after-initial-setup-message*
(with-output-to-string (*standard-output*)
(format t "~&~% ==== quicklisp installed ====~%~%")
(format t " To load a system, use: (ql:quickload \"system-name\")~%~%")
(format t " To find systems, use: (ql:system-apropos \"term\")~%~%")
(format t " To load Quicklisp every time you start Lisp, use: (ql:add-to-init-file)~%~%")
(format t " For more information, see /~%~%")))
(defun initial-install ()
(ensure-directories-exist (qmerge "tmp/"))
(ensure-directories-exist (qmerge "quicklisp/"))
(renaming-fetch *asdf-url* (qmerge "asdf.lisp"))
(let ((tmptar (qmerge "tmp/quicklisp.tar")))
(renaming-fetch *quicklisp-tar-url* tmptar)
(unpack-tarball tmptar :directory (qmerge "./")))
(renaming-fetch *setup-url* (qmerge "setup.lisp"))
(load (qmerge "setup.lisp"))
(write-string *after-initial-setup-message*)
(finish-output))
(defun install (&key ((:path *home*) *home*)
((:proxy *proxy-url*) *proxy-url*))
(setf *home* (merge-pathnames *home*))
(let ((setup-file (qmerge "setup.lisp")))
(when (probe-file setup-file)
(multiple-value-bind (result proceed)
(with-simple-restart (load-setup "Load ~S" setup-file)
(error "Quicklisp has already been installed. Load ~S instead."
setup-file))
(declare (ignore result))
(when proceed
(return-from install (load setup-file))))))
(if (find-package '#:ql)
(progn
(write-line "!!! Quicklisp has already been set up. !!!")
(write-string *after-initial-setup-message*)
t)
(call-with-quiet-compilation #'initial-install)))
( e.g. CCL , CMUCL )
(setf *default-pathname-defaults* (truename *default-pathname-defaults*))
(write-string *after-load-message*)
|
f5ef2b1c841548870cd9b9bd0dfdf48ed8db852d6593f0f18c5baf6edcf05fad | purescript/purescript | Comments.hs | # LANGUAGE TemplateHaskell #
-- |
-- Defines the types of source code comments
--
module Language.PureScript.Comments where
import Prelude
import Codec.Serialise (Serialise)
import Control.DeepSeq (NFData)
import Data.Text (Text)
import GHC.Generics (Generic)
import Data.Aeson.TH
data Comment
= LineComment Text
| BlockComment Text
deriving (Show, Eq, Ord, Generic)
instance NFData Comment
instance Serialise Comment
$(deriveJSON (defaultOptions { sumEncoding = ObjectWithSingleField }) ''Comment)
| null | https://raw.githubusercontent.com/purescript/purescript/02bd6ae60bcd18cbfa892f268ef6359d84ed7c9b/src/Language/PureScript/Comments.hs | haskell | |
Defines the types of source code comments
| # LANGUAGE TemplateHaskell #
module Language.PureScript.Comments where
import Prelude
import Codec.Serialise (Serialise)
import Control.DeepSeq (NFData)
import Data.Text (Text)
import GHC.Generics (Generic)
import Data.Aeson.TH
data Comment
= LineComment Text
| BlockComment Text
deriving (Show, Eq, Ord, Generic)
instance NFData Comment
instance Serialise Comment
$(deriveJSON (defaultOptions { sumEncoding = ObjectWithSingleField }) ''Comment)
|
67f6ffa8e934a05af352347ba12247b393b9a828f66147fcbd76e67fe042bddf | wilbowma/cur | totality.rkt | #lang s-exp "../main.rkt"
(provide (for-syntax (all-defined-out)))
(require "pattern-tree.rkt"
(for-syntax racket/base
racket/bool
racket/list
racket/pretty
cur/curnel/reflection))
TODO : Lower to relative phase 1 and change import
(begin-for-syntax
;; A pattern match is total if and only if each match variable in the tree contains a match case for each
;; of the corresponding type constructors
(define (total? in-pat #:aliases [aliases '()] #:env [env '()])
(let* ([pt (create-pattern-tree in-pat #:env env)]
[warnings (fold-pt
(lambda (d context init)
(let* ([patterns (map pt-match-pattern (pt-decl-matches d))]
[constructors-res (get-constructors-metadata (pt-decl-match-var d) #:env env)]
[constructors (if constructors-res
(car constructors-res)
(error
'total?
"Expected pattern match on an inductively defined type, but ~a is not inductive"
(pt-decl-match-var d)))]
; handle implicit constructors
[updated-constructors
(map (lambda (c)
(let* ([c-list (syntax->list c)]
[alias-match
(if c-list
(for/or ([a aliases])
(and (free-identifier=? (first c-list) (second a)) a))
(for/or ([a aliases])
(and (free-identifier=? c (second a)))))])
(if alias-match
(if c-list
#`#,(cons (first alias-match) (drop (rest (syntax->list c)) (third alias-match)))
(first alias-match))
c)))
constructors)]
; if the current match pattern is marked as a pattern variable, then
; we actually don't need to worry about failures at this level; subsequent
; nested ones we do
; note: context is currently a list alternating between a decl object and a match object
[warnings (if (and (> (length context) 0)
(syntax-property (pt-match-pattern (first context)) 'is-pattern-variable?)
(> (length (pt-decl-matches (second context))) 1))
empty
(match-var-total-check (pt-decl-match-var d)
patterns
updated-constructors
#:env env))]
[result (string-append "failed totality check\n"
(format "match path: ~a\n" (append (map pt-match-pattern (reverse (filter pt-match? context))) (list (pt-decl-match-var d))))
(foldr (lambda (w i) (string-append (format "missing: ~a\n" w) i)) "" warnings))])
(if (not (empty? warnings))
(cons (cons (cons (pt-decl-match-var d) patterns) result) init)
init)))
empty
pt)])
(or (empty? warnings)
(raise (exn:fail:syntax (string-append (foldr (lambda (w i) (string-append w i)) "" (map cdr warnings))
(pretty-format pt))
(current-continuation-marks)
(foldr append empty (map car warnings)))))))
;; Given a list of patterns associated with a pattern variable and a list of expected
;; type cases, returns true if all type cases can be matched
(define (match-var-total-check match-var patterns ty-pats #:warnings [warnings empty] #:env [env '()])
(cond [(empty? ty-pats) warnings]
[else (let* ([matched? (for/or ([pat patterns])
(or
(syntax-property pat 'is-pattern-variable)
(typecase-match pat
(first ty-pats)
match-var
#:env env)))]
[new-warnings (if matched?
warnings
(cons (first ty-pats) warnings))])
(match-var-total-check match-var patterns (rest ty-pats) #:warnings new-warnings #:env env))]))
;; checks to see if the identifiers match
(define (constructor-match in-id match-id)
(free-identifier=? in-id match-id))
;; checks if a pattern has the same constructor and number of arguments
(define (typecase-match pat ty-pat match-var #:env [env '()])
(let ([patlist (syntax->list pat)]
[ty-patlist (syntax->list ty-pat)])
(or (and (false? patlist)
(not (is-constructor? pat match-var #:env env)))
(and (equal? (false? patlist)
(false? ty-patlist))
(if (false? ty-patlist)
(constructor-match pat ty-pat)
(and (= (length ty-patlist) (length patlist))
(constructor-match (first patlist) (first ty-patlist)))))))))
| null | https://raw.githubusercontent.com/wilbowma/cur/e039c98941b3d272c6e462387df22846e10b0128/cur-lib/cur/stdlib/totality.rkt | racket | A pattern match is total if and only if each match variable in the tree contains a match case for each
of the corresponding type constructors
handle implicit constructors
if the current match pattern is marked as a pattern variable, then
we actually don't need to worry about failures at this level; subsequent
nested ones we do
note: context is currently a list alternating between a decl object and a match object
Given a list of patterns associated with a pattern variable and a list of expected
type cases, returns true if all type cases can be matched
checks to see if the identifiers match
checks if a pattern has the same constructor and number of arguments | #lang s-exp "../main.rkt"
(provide (for-syntax (all-defined-out)))
(require "pattern-tree.rkt"
(for-syntax racket/base
racket/bool
racket/list
racket/pretty
cur/curnel/reflection))
TODO : Lower to relative phase 1 and change import
(begin-for-syntax
(define (total? in-pat #:aliases [aliases '()] #:env [env '()])
(let* ([pt (create-pattern-tree in-pat #:env env)]
[warnings (fold-pt
(lambda (d context init)
(let* ([patterns (map pt-match-pattern (pt-decl-matches d))]
[constructors-res (get-constructors-metadata (pt-decl-match-var d) #:env env)]
[constructors (if constructors-res
(car constructors-res)
(error
'total?
"Expected pattern match on an inductively defined type, but ~a is not inductive"
(pt-decl-match-var d)))]
[updated-constructors
(map (lambda (c)
(let* ([c-list (syntax->list c)]
[alias-match
(if c-list
(for/or ([a aliases])
(and (free-identifier=? (first c-list) (second a)) a))
(for/or ([a aliases])
(and (free-identifier=? c (second a)))))])
(if alias-match
(if c-list
#`#,(cons (first alias-match) (drop (rest (syntax->list c)) (third alias-match)))
(first alias-match))
c)))
constructors)]
[warnings (if (and (> (length context) 0)
(syntax-property (pt-match-pattern (first context)) 'is-pattern-variable?)
(> (length (pt-decl-matches (second context))) 1))
empty
(match-var-total-check (pt-decl-match-var d)
patterns
updated-constructors
#:env env))]
[result (string-append "failed totality check\n"
(format "match path: ~a\n" (append (map pt-match-pattern (reverse (filter pt-match? context))) (list (pt-decl-match-var d))))
(foldr (lambda (w i) (string-append (format "missing: ~a\n" w) i)) "" warnings))])
(if (not (empty? warnings))
(cons (cons (cons (pt-decl-match-var d) patterns) result) init)
init)))
empty
pt)])
(or (empty? warnings)
(raise (exn:fail:syntax (string-append (foldr (lambda (w i) (string-append w i)) "" (map cdr warnings))
(pretty-format pt))
(current-continuation-marks)
(foldr append empty (map car warnings)))))))
(define (match-var-total-check match-var patterns ty-pats #:warnings [warnings empty] #:env [env '()])
(cond [(empty? ty-pats) warnings]
[else (let* ([matched? (for/or ([pat patterns])
(or
(syntax-property pat 'is-pattern-variable)
(typecase-match pat
(first ty-pats)
match-var
#:env env)))]
[new-warnings (if matched?
warnings
(cons (first ty-pats) warnings))])
(match-var-total-check match-var patterns (rest ty-pats) #:warnings new-warnings #:env env))]))
(define (constructor-match in-id match-id)
(free-identifier=? in-id match-id))
(define (typecase-match pat ty-pat match-var #:env [env '()])
(let ([patlist (syntax->list pat)]
[ty-patlist (syntax->list ty-pat)])
(or (and (false? patlist)
(not (is-constructor? pat match-var #:env env)))
(and (equal? (false? patlist)
(false? ty-patlist))
(if (false? ty-patlist)
(constructor-match pat ty-pat)
(and (= (length ty-patlist) (length patlist))
(constructor-match (first patlist) (first ty-patlist)))))))))
|
accfa99740c7e68b90e35e157313e799b521116789ebc059e03bb9ffb0803578 | fossas/fossa-cli | Poetry.hs | module Strategy.Python.Poetry (
discover,
-- * for testing only
graphFromLockFile,
setGraphDirectsFromPyproject,
PoetryProject (..),
) where
import App.Fossa.Analyze.Types (AnalyzeProject (analyzeProject'), analyzeProject)
import Control.Algebra (Has)
import Control.Applicative ((<|>))
import Control.Effect.Diagnostics (Diagnostics, context, errCtx, fatalText, recover, warnOnErr)
import Control.Effect.Reader (Reader)
import Control.Monad (void)
import Data.Aeson (ToJSON)
import Data.Map (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import DepTypes (DepType (..), Dependency (..))
import Diag.Common (
MissingDeepDeps (MissingDeepDeps),
MissingEdges (MissingEdges),
)
import Discovery.Filters (AllFilters)
import Discovery.Simple (simpleDiscover)
import Discovery.Walk (
WalkStep (WalkContinue, WalkSkipAll),
findFileNamed,
walkWithFilters',
)
import Effect.Logger (Logger, Pretty (pretty), logDebug)
import Effect.ReadFS (ReadFS, readContentsToml)
import GHC.Generics (Generic)
import Graphing (Graphing)
import Graphing qualified
import Path (Abs, Dir, File, Path)
import Strategy.Python.Errors (
MissingPoetryLockFile (MissingPoetryLockFile),
)
import Strategy.Python.Poetry.Common (getPoetryBuildBackend, logIgnoredDeps, pyProjectDeps, toCanonicalName, toMap)
import Strategy.Python.Poetry.PoetryLock (PackageName (..), PoetryLock (..), PoetryLockPackage (..), poetryLockCodec)
import Strategy.Python.Poetry.PyProject (PyProject (..), pyProjectCodec)
import Types (DependencyResults (..), DiscoveredProject (..), DiscoveredProjectType (PoetryProjectType), GraphBreadth (..))
newtype PyProjectTomlFile = PyProjectTomlFile {pyProjectTomlPath :: Path Abs File} deriving (Eq, Ord, Show, Generic)
newtype PoetryLockFile = PoetryLockFile {poetryLockPath :: Path Abs File} deriving (Eq, Ord, Show, Generic)
newtype ProjectDir = ProjectDir {pyProjectPath :: Path Abs Dir} deriving (Eq, Ord, Show, Generic)
instance ToJSON PyProjectTomlFile
instance ToJSON PoetryLockFile
instance ToJSON ProjectDir
data PoetryProject = PoetryProject
{ projectDir :: ProjectDir
, pyProjectToml :: PyProjectTomlFile
, poetryLock :: Maybe PoetryLockFile
}
deriving (Show, Eq, Ord, Generic)
instance ToJSON PoetryProject
instance AnalyzeProject PoetryProject where
analyzeProject _ = getDeps
analyzeProject' _ = getDeps
discover ::
( Has ReadFS sig m
, Has Diagnostics sig m
, Has Logger sig m
, Has (Reader AllFilters) sig m
) =>
Path Abs Dir ->
m [DiscoveredProject PoetryProject]
discover = simpleDiscover findProjects mkProject PoetryProjectType
-- | Poetry build backend identifier required in [pyproject.toml](-poetry.org/docs/pyproject/#poetry-and-pep-517).
usesPoetryBackend :: Text -> Bool
usesPoetryBackend backend =
For poetry versions > = 1.1.0a1 ( released 2020 )
|| backend == "poetry.masonry.api" -- Refer to -poetry/poetry/pull/2212
-- | Reference message text for poetry build backend setting value required in pyproject.toml.
-- Users should configure poetry build backend in pyproject.toml for poetry project discovery.
poetryBuildBackendIdentifierHelpText :: Text
poetryBuildBackendIdentifierHelpText = "Poetry project must use poetry build backend. Please refer to -poetry.org/docs/pyproject/#poetry-and-pep-517."
warnIncorrectBuildBackend :: Has Logger sig m => Text -> m ()
warnIncorrectBuildBackend currentBackend =
(logDebug . pretty) $
"pyproject.toml does not use poetry build backend. It uses: "
<> currentBackend
<> "\n"
<> poetryBuildBackendIdentifierHelpText
-- | Finds poetry project by searching for pyproject.toml.
-- If poetry.lock file is also discovered, it is used as a supplement.
findProjects ::
( Has ReadFS sig m
, Has Diagnostics sig m
, Has Logger sig m
, Has (Reader AllFilters) sig m
) =>
Path Abs Dir ->
m [PoetryProject]
findProjects = walkWithFilters' $ \dir _ files -> do
let poetryLockFile = findFileNamed "poetry.lock" files
let pyprojectFile = findFileNamed "pyproject.toml" files
case (poetryLockFile, pyprojectFile) of
(poetry, Just pyproject) -> do
poetryProject <- readContentsToml pyProjectCodec pyproject
let project = PoetryProject (ProjectDir dir) (PyProjectTomlFile pyproject) (PoetryLockFile <$> poetry)
let pyprojectBuildBackend = getPoetryBuildBackend poetryProject
case pyprojectBuildBackend of
Nothing -> pure ([], WalkContinue)
Just pbs ->
if usesPoetryBackend pbs
then pure ([project], WalkSkipAll)
else ([], WalkContinue) <$ warnIncorrectBuildBackend pbs
-- Without pyproject file, it is unlikely that project is a poetry project. Poetry itself does not work
-- without [pyproject.toml manifest](-poetry.org/docs/pyproject/).
(Just _, Nothing) -> context "poetry.lock file found without accompanying pyproject.toml!" $ pure ([], WalkContinue)
(Nothing, Nothing) -> pure ([], WalkContinue)
mkProject :: PoetryProject -> DiscoveredProject PoetryProject
mkProject project =
DiscoveredProject
{ projectType = PoetryProjectType
, projectBuildTargets = mempty
, projectPath = pyProjectPath $ projectDir project
, projectData = project
}
getDeps :: (Has ReadFS sig m, Has Diagnostics sig m, Has Logger sig m) => PoetryProject -> m DependencyResults
getDeps project = do
context "Poetry" $ context "Static analysis" $ analyze project
-- | Analyzes Poetry Project and creates dependency graph.
analyze ::
( Has ReadFS sig m
, Has Diagnostics sig m
, Has Logger sig m
) =>
PoetryProject ->
m DependencyResults
analyze PoetryProject{pyProjectToml, poetryLock} = do
pyproject <- readContentsToml pyProjectCodec (pyProjectTomlPath pyProjectToml)
case poetryLock of
Just lockPath -> do
poetryLockProject <- readContentsToml poetryLockCodec (poetryLockPath lockPath)
_ <- logIgnoredDeps pyproject (Just poetryLockProject)
graph <- context "Building dependency graph from pyproject.toml and poetry.lock" $ pure $ setGraphDirectsFromPyproject (graphFromLockFile poetryLockProject) pyproject
pure $
DependencyResults
{ dependencyGraph = graph
, dependencyGraphBreadth = Complete
, dependencyManifestFiles = [poetryLockPath lockPath]
}
Nothing -> do
void
. recover
. warnOnErr MissingDeepDeps
. warnOnErr MissingEdges
. errCtx (MissingPoetryLockFile (pyProjectTomlPath pyProjectToml))
$ fatalText "poetry.lock file was not discovered"
graph <- context "Building dependency graph from only pyproject.toml" $ pure $ Graphing.fromList $ pyProjectDeps pyproject
pure $
DependencyResults
{ dependencyGraph = graph
, dependencyGraphBreadth = Partial
, dependencyManifestFiles = [pyProjectTomlPath pyProjectToml]
}
-- | Use a `pyproject.toml` to set the direct dependencies of a graph created from `poetry.lock`.
setGraphDirectsFromPyproject :: Graphing Dependency -> PyProject -> Graphing Dependency
setGraphDirectsFromPyproject graph pyproject = Graphing.promoteToDirect isDirect graph
where
-- Dependencies in `poetry.lock` are direct if they're specified in `pyproject.toml`.
-- `pyproject.toml` may use non canonical naming, when naming dependencies.
isDirect :: Dependency -> Bool
isDirect dep = case pyprojectPoetry pyproject of
Nothing -> False
Just _ -> any (\n -> toCanonicalName (dependencyName n) == toCanonicalName (dependencyName dep)) $ pyProjectDeps pyproject
-- | Using a Poetry lockfile, build the graph of packages.
-- The resulting graph contains edges, but does not distinguish between direct and deep dependencies,
-- since `poetry.lock` does not indicate which dependencies are direct.
graphFromLockFile :: PoetryLock -> Graphing Dependency
graphFromLockFile poetryLock = Graphing.gmap pkgNameToDependency (edges <> Graphing.deeps pkgsNoDeps)
where
pkgs :: [PoetryLockPackage]
pkgs = poetryLockPackages poetryLock
pkgsNoDeps :: [PackageName]
pkgsNoDeps = poetryLockPackageName <$> filter (null . poetryLockPackageDependencies) pkgs
depsWithEdges :: [PoetryLockPackage]
depsWithEdges = filter (not . null . poetryLockPackageDependencies) pkgs
edgeOf :: PoetryLockPackage -> [(PackageName, PackageName)]
edgeOf p = map tuplify . Map.keys $ poetryLockPackageDependencies p
where
tuplify :: Text -> (PackageName, PackageName)
tuplify x = (poetryLockPackageName p, PackageName x)
edges :: Graphing PackageName
edges = Graphing.edges (concatMap edgeOf depsWithEdges)
canonicalPkgName :: PackageName -> PackageName
canonicalPkgName name = PackageName . toCanonicalName $ unPackageName name
mapOfDependency :: Map PackageName Dependency
mapOfDependency = toMap pkgs
-- Pip packages are [case insensitive](-0508/#id21), but poetry.lock may use
-- non-canonical name for reference. Try to lookup with provided name, otherwise fallback to canonical naming.
pkgNameToDependency :: PackageName -> Dependency
pkgNameToDependency name =
fromMaybe
( Dependency
{ dependencyType = PipType
, dependencyName = unPackageName name
, dependencyVersion = Nothing
, dependencyLocations = []
, dependencyEnvironments = mempty
, dependencyTags = Map.empty
}
)
$ Map.lookup name mapOfDependency
<|> Map.lookup (canonicalPkgName name) mapOfDependency
| null | https://raw.githubusercontent.com/fossas/fossa-cli/187f19afec2133466d1998c89fc7f1c77107c2b0/src/Strategy/Python/Poetry.hs | haskell | * for testing only
| Poetry build backend identifier required in [pyproject.toml](-poetry.org/docs/pyproject/#poetry-and-pep-517).
Refer to -poetry/poetry/pull/2212
| Reference message text for poetry build backend setting value required in pyproject.toml.
Users should configure poetry build backend in pyproject.toml for poetry project discovery.
| Finds poetry project by searching for pyproject.toml.
If poetry.lock file is also discovered, it is used as a supplement.
Without pyproject file, it is unlikely that project is a poetry project. Poetry itself does not work
without [pyproject.toml manifest](-poetry.org/docs/pyproject/).
| Analyzes Poetry Project and creates dependency graph.
| Use a `pyproject.toml` to set the direct dependencies of a graph created from `poetry.lock`.
Dependencies in `poetry.lock` are direct if they're specified in `pyproject.toml`.
`pyproject.toml` may use non canonical naming, when naming dependencies.
| Using a Poetry lockfile, build the graph of packages.
The resulting graph contains edges, but does not distinguish between direct and deep dependencies,
since `poetry.lock` does not indicate which dependencies are direct.
Pip packages are [case insensitive](-0508/#id21), but poetry.lock may use
non-canonical name for reference. Try to lookup with provided name, otherwise fallback to canonical naming. | module Strategy.Python.Poetry (
discover,
graphFromLockFile,
setGraphDirectsFromPyproject,
PoetryProject (..),
) where
import App.Fossa.Analyze.Types (AnalyzeProject (analyzeProject'), analyzeProject)
import Control.Algebra (Has)
import Control.Applicative ((<|>))
import Control.Effect.Diagnostics (Diagnostics, context, errCtx, fatalText, recover, warnOnErr)
import Control.Effect.Reader (Reader)
import Control.Monad (void)
import Data.Aeson (ToJSON)
import Data.Map (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import DepTypes (DepType (..), Dependency (..))
import Diag.Common (
MissingDeepDeps (MissingDeepDeps),
MissingEdges (MissingEdges),
)
import Discovery.Filters (AllFilters)
import Discovery.Simple (simpleDiscover)
import Discovery.Walk (
WalkStep (WalkContinue, WalkSkipAll),
findFileNamed,
walkWithFilters',
)
import Effect.Logger (Logger, Pretty (pretty), logDebug)
import Effect.ReadFS (ReadFS, readContentsToml)
import GHC.Generics (Generic)
import Graphing (Graphing)
import Graphing qualified
import Path (Abs, Dir, File, Path)
import Strategy.Python.Errors (
MissingPoetryLockFile (MissingPoetryLockFile),
)
import Strategy.Python.Poetry.Common (getPoetryBuildBackend, logIgnoredDeps, pyProjectDeps, toCanonicalName, toMap)
import Strategy.Python.Poetry.PoetryLock (PackageName (..), PoetryLock (..), PoetryLockPackage (..), poetryLockCodec)
import Strategy.Python.Poetry.PyProject (PyProject (..), pyProjectCodec)
import Types (DependencyResults (..), DiscoveredProject (..), DiscoveredProjectType (PoetryProjectType), GraphBreadth (..))
newtype PyProjectTomlFile = PyProjectTomlFile {pyProjectTomlPath :: Path Abs File} deriving (Eq, Ord, Show, Generic)
newtype PoetryLockFile = PoetryLockFile {poetryLockPath :: Path Abs File} deriving (Eq, Ord, Show, Generic)
newtype ProjectDir = ProjectDir {pyProjectPath :: Path Abs Dir} deriving (Eq, Ord, Show, Generic)
instance ToJSON PyProjectTomlFile
instance ToJSON PoetryLockFile
instance ToJSON ProjectDir
data PoetryProject = PoetryProject
{ projectDir :: ProjectDir
, pyProjectToml :: PyProjectTomlFile
, poetryLock :: Maybe PoetryLockFile
}
deriving (Show, Eq, Ord, Generic)
instance ToJSON PoetryProject
instance AnalyzeProject PoetryProject where
analyzeProject _ = getDeps
analyzeProject' _ = getDeps
discover ::
( Has ReadFS sig m
, Has Diagnostics sig m
, Has Logger sig m
, Has (Reader AllFilters) sig m
) =>
Path Abs Dir ->
m [DiscoveredProject PoetryProject]
discover = simpleDiscover findProjects mkProject PoetryProjectType
usesPoetryBackend :: Text -> Bool
usesPoetryBackend backend =
For poetry versions > = 1.1.0a1 ( released 2020 )
poetryBuildBackendIdentifierHelpText :: Text
poetryBuildBackendIdentifierHelpText = "Poetry project must use poetry build backend. Please refer to -poetry.org/docs/pyproject/#poetry-and-pep-517."
warnIncorrectBuildBackend :: Has Logger sig m => Text -> m ()
warnIncorrectBuildBackend currentBackend =
(logDebug . pretty) $
"pyproject.toml does not use poetry build backend. It uses: "
<> currentBackend
<> "\n"
<> poetryBuildBackendIdentifierHelpText
findProjects ::
( Has ReadFS sig m
, Has Diagnostics sig m
, Has Logger sig m
, Has (Reader AllFilters) sig m
) =>
Path Abs Dir ->
m [PoetryProject]
findProjects = walkWithFilters' $ \dir _ files -> do
let poetryLockFile = findFileNamed "poetry.lock" files
let pyprojectFile = findFileNamed "pyproject.toml" files
case (poetryLockFile, pyprojectFile) of
(poetry, Just pyproject) -> do
poetryProject <- readContentsToml pyProjectCodec pyproject
let project = PoetryProject (ProjectDir dir) (PyProjectTomlFile pyproject) (PoetryLockFile <$> poetry)
let pyprojectBuildBackend = getPoetryBuildBackend poetryProject
case pyprojectBuildBackend of
Nothing -> pure ([], WalkContinue)
Just pbs ->
if usesPoetryBackend pbs
then pure ([project], WalkSkipAll)
else ([], WalkContinue) <$ warnIncorrectBuildBackend pbs
(Just _, Nothing) -> context "poetry.lock file found without accompanying pyproject.toml!" $ pure ([], WalkContinue)
(Nothing, Nothing) -> pure ([], WalkContinue)
mkProject :: PoetryProject -> DiscoveredProject PoetryProject
mkProject project =
DiscoveredProject
{ projectType = PoetryProjectType
, projectBuildTargets = mempty
, projectPath = pyProjectPath $ projectDir project
, projectData = project
}
getDeps :: (Has ReadFS sig m, Has Diagnostics sig m, Has Logger sig m) => PoetryProject -> m DependencyResults
getDeps project = do
context "Poetry" $ context "Static analysis" $ analyze project
analyze ::
( Has ReadFS sig m
, Has Diagnostics sig m
, Has Logger sig m
) =>
PoetryProject ->
m DependencyResults
analyze PoetryProject{pyProjectToml, poetryLock} = do
pyproject <- readContentsToml pyProjectCodec (pyProjectTomlPath pyProjectToml)
case poetryLock of
Just lockPath -> do
poetryLockProject <- readContentsToml poetryLockCodec (poetryLockPath lockPath)
_ <- logIgnoredDeps pyproject (Just poetryLockProject)
graph <- context "Building dependency graph from pyproject.toml and poetry.lock" $ pure $ setGraphDirectsFromPyproject (graphFromLockFile poetryLockProject) pyproject
pure $
DependencyResults
{ dependencyGraph = graph
, dependencyGraphBreadth = Complete
, dependencyManifestFiles = [poetryLockPath lockPath]
}
Nothing -> do
void
. recover
. warnOnErr MissingDeepDeps
. warnOnErr MissingEdges
. errCtx (MissingPoetryLockFile (pyProjectTomlPath pyProjectToml))
$ fatalText "poetry.lock file was not discovered"
graph <- context "Building dependency graph from only pyproject.toml" $ pure $ Graphing.fromList $ pyProjectDeps pyproject
pure $
DependencyResults
{ dependencyGraph = graph
, dependencyGraphBreadth = Partial
, dependencyManifestFiles = [pyProjectTomlPath pyProjectToml]
}
setGraphDirectsFromPyproject :: Graphing Dependency -> PyProject -> Graphing Dependency
setGraphDirectsFromPyproject graph pyproject = Graphing.promoteToDirect isDirect graph
where
isDirect :: Dependency -> Bool
isDirect dep = case pyprojectPoetry pyproject of
Nothing -> False
Just _ -> any (\n -> toCanonicalName (dependencyName n) == toCanonicalName (dependencyName dep)) $ pyProjectDeps pyproject
graphFromLockFile :: PoetryLock -> Graphing Dependency
graphFromLockFile poetryLock = Graphing.gmap pkgNameToDependency (edges <> Graphing.deeps pkgsNoDeps)
where
pkgs :: [PoetryLockPackage]
pkgs = poetryLockPackages poetryLock
pkgsNoDeps :: [PackageName]
pkgsNoDeps = poetryLockPackageName <$> filter (null . poetryLockPackageDependencies) pkgs
depsWithEdges :: [PoetryLockPackage]
depsWithEdges = filter (not . null . poetryLockPackageDependencies) pkgs
edgeOf :: PoetryLockPackage -> [(PackageName, PackageName)]
edgeOf p = map tuplify . Map.keys $ poetryLockPackageDependencies p
where
tuplify :: Text -> (PackageName, PackageName)
tuplify x = (poetryLockPackageName p, PackageName x)
edges :: Graphing PackageName
edges = Graphing.edges (concatMap edgeOf depsWithEdges)
canonicalPkgName :: PackageName -> PackageName
canonicalPkgName name = PackageName . toCanonicalName $ unPackageName name
mapOfDependency :: Map PackageName Dependency
mapOfDependency = toMap pkgs
pkgNameToDependency :: PackageName -> Dependency
pkgNameToDependency name =
fromMaybe
( Dependency
{ dependencyType = PipType
, dependencyName = unPackageName name
, dependencyVersion = Nothing
, dependencyLocations = []
, dependencyEnvironments = mempty
, dependencyTags = Map.empty
}
)
$ Map.lookup name mapOfDependency
<|> Map.lookup (canonicalPkgName name) mapOfDependency
|
fa4fad440c7d308f65bf6cfc89f090dfaa2ec15cf87692b5daae877dec975650 | 2600hz/kazoo | knm_vitelity_cnam.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
%%% @doc
@author
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(knm_vitelity_cnam).
-behaviour(knm_gen_provider).
-export([save/1]).
-export([delete/1]).
-include("knm.hrl").
%%------------------------------------------------------------------------------
%% @doc This function is called each time a number is saved, and will
produce notifications if the cnam object changes
%% @end
%%------------------------------------------------------------------------------
-spec save(knm_phone_number:record()) -> knm_phone_number:record().
save(PN) ->
State = knm_phone_number:state(PN),
save(PN, State).
-spec save(knm_phone_number:record(), kz_term:ne_binary()) -> knm_phone_number:record().
save(PN, ?NUMBER_STATE_RESERVED) ->
handle_outbound_cnam(PN);
save(PN, ?NUMBER_STATE_IN_SERVICE) ->
handle_outbound_cnam(PN);
save(PN, ?NUMBER_STATE_PORT_IN) ->
handle_outbound_cnam(PN);
save(PN, _State) ->
PN.
%%------------------------------------------------------------------------------
%% @doc This function is called each time a number is deleted
%% @end
%%------------------------------------------------------------------------------
-spec delete(knm_phone_number:record()) -> knm_phone_number:record().
delete(PN) ->
_ = remove_inbound_cnam(PN),
knm_providers:deactivate_features(PN
,[?FEATURE_CNAM_INBOUND
,?FEATURE_CNAM_OUTBOUND
,?FEATURE_CNAM
]
).
%%%=============================================================================
Internal functions
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_outbound_cnam(knm_phone_number:record()) -> knm_phone_number:record().
handle_outbound_cnam(PN) ->
IsDryRun = knm_phone_number:dry_run(PN),
Feature = knm_phone_number:feature(PN, ?FEATURE_CNAM_OUTBOUND),
Doc = knm_phone_number:doc(PN),
CurrentCNAM = kz_json:get_ne_value(?CNAM_DISPLAY_NAME, Feature),
case kz_json:get_ne_value([?FEATURE_CNAM, ?CNAM_DISPLAY_NAME], Doc) of
'undefined' ->
PN1 = knm_providers:deactivate_feature(PN, ?FEATURE_CNAM_OUTBOUND),
handle_inbound_cnam(PN1);
CurrentCNAM ->
handle_inbound_cnam(PN);
NewCNAM when IsDryRun ->
lager:debug("dry run: cnam display name changed to ~s", [NewCNAM]),
PN1 = knm_providers:activate_feature(PN, {?FEATURE_CNAM_OUTBOUND, NewCNAM}),
handle_inbound_cnam(PN1);
NewCNAM ->
lager:debug("cnam display name changed to ~s, updating", [NewCNAM]),
PN1 = try_update_outbound_cnam(PN, NewCNAM),
handle_inbound_cnam(PN1)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec try_update_outbound_cnam(knm_phone_number:record(), kz_term:ne_binary()) ->
knm_phone_number:record().
try_update_outbound_cnam(PN, NewCNAM) ->
DID = knm_phone_number:number(PN),
case
knm_vitelity_util:query_vitelity(
knm_vitelity_util:build_uri(
outbound_cnam_options(DID, NewCNAM)
)
)
of
{'error', E} -> knm_errors:unspecified(E, PN);
{'ok', XML} -> process_outbound_xml_resp(PN, NewCNAM, XML)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec outbound_cnam_options(kz_term:ne_binary(), kz_term:ne_binary()) ->
knm_vitelity_util:query_options().
outbound_cnam_options(DID, NewCNAM) ->
[{'qs', [{'cmd', <<"lidb">>}
,{'did', knm_converters:to_npan(DID)}
,{'name', NewCNAM}
,{'xml', <<"yes">>}
| knm_vitelity_util:default_options()
]}
,{'uri', knm_vitelity_util:api_uri()}
].
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec process_outbound_xml_resp(knm_phone_number:record(), kz_term:ne_binary(), kz_term:text()) ->
knm_phone_number:record().
process_outbound_xml_resp(PN, FeatureData, XML_binary) ->
XML = unicode:characters_to_list(XML_binary),
try xmerl_scan:string(XML) of
{#xmlElement{name='content'
,content=Children
}
,_Left
} -> process_outbound_resp(PN, FeatureData, Children);
_ -> knm_errors:unspecified('unknown_resp_format', PN)
catch
_E:_R ->
knm_errors:unspecified('invalid_resp_format', PN)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec process_outbound_resp(knm_phone_number:record(), kz_term:ne_binary(), kz_types:xml_els()) ->
knm_phone_number:record().
process_outbound_resp(PN, FeatureData, Children) ->
case knm_vitelity_util:xml_resp_status_msg(Children) of
<<"ok">> -> check_outbound_response_tag(PN, FeatureData, Children);
<<"fail">> ->
Msg = knm_vitelity_util:xml_resp_error_msg(Children),
knm_errors:unspecified(Msg, PN)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec check_outbound_response_tag(knm_phone_number:record(), kz_term:ne_binary(), kz_types:xml_els()) ->
knm_phone_number:record().
check_outbound_response_tag(PN, NewCNAM, Children) ->
case knm_vitelity_util:xml_resp_response_msg(Children) of
'undefined' -> knm_errors:unspecified('resp_tag_not_found', PN);
<<"ok">> ->
FeatureData = kz_json:from_list([{?CNAM_DISPLAY_NAME, NewCNAM}]),
PN1 = knm_providers:activate_feature(PN, {?FEATURE_CNAM_OUTBOUND, FeatureData}),
publish_cnam_update(PN1),
PN1;
Msg ->
lager:debug("resp was not ok, was ~s", [Msg]),
knm_errors:unspecified(Msg, PN)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec handle_inbound_cnam(knm_phone_number:record()) -> knm_phone_number:record().
handle_inbound_cnam(PN) ->
IsDryRun = knm_phone_number:dry_run(PN),
handle_inbound_cnam(PN, IsDryRun).
-spec handle_inbound_cnam(knm_phone_number:record(), boolean()) -> knm_phone_number:record().
handle_inbound_cnam(PN, 'true') ->
Doc = knm_phone_number:doc(PN),
case kz_json:is_true([?FEATURE_CNAM, ?CNAM_INBOUND_LOOKUP], Doc) of
'false' ->
knm_providers:deactivate_features(PN, [?FEATURE_CNAM_INBOUND
,?CNAM_INBOUND_LOOKUP
]);
'true' ->
FeatureData = kz_json:from_list([{?CNAM_INBOUND_LOOKUP, true}]),
knm_providers:activate_feature(PN, {?FEATURE_CNAM_INBOUND, FeatureData})
end;
handle_inbound_cnam(PN, 'false') ->
Doc = knm_phone_number:doc(PN),
case kz_json:is_true([?FEATURE_CNAM, ?CNAM_INBOUND_LOOKUP], Doc) of
'false' -> remove_inbound_cnam(PN);
'true' -> add_inbound_cnam(PN)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec remove_inbound_cnam(knm_phone_number:record()) -> knm_phone_number:record().
remove_inbound_cnam(PN) ->
DID = knm_phone_number:number(PN),
_ = knm_vitelity_util:query_vitelity(
knm_vitelity_util:build_uri(
remove_inbound_options(DID)
)
),
knm_providers:deactivate_features(PN, [?FEATURE_CNAM_INBOUND
,?CNAM_INBOUND_LOOKUP
]).
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec remove_inbound_options(kz_term:ne_binary()) -> knm_vitelity_util:query_options().
remove_inbound_options(PN) ->
[{'qs', [{'did', knm_converters:to_npan(PN)}
,{'cmd', <<"cnamdisable">>}
,{'xml', <<"yes">>}
| knm_vitelity_util:default_options()
]}
,{'uri', knm_vitelity_util:api_uri()}
].
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec add_inbound_cnam(knm_phone_number:record()) ->
knm_phone_number:record().
add_inbound_cnam(PN) ->
DID = knm_phone_number:number(PN),
case
knm_vitelity_util:query_vitelity(
knm_vitelity_util:build_uri(
inbound_options(DID)
)
)
of
{'ok', XML} -> process_xml_resp(PN, XML);
{'error', _E} ->
knm_errors:unspecified('unknown_error', PN)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec inbound_options(kz_term:ne_binary()) -> knm_vitelity_util:query_options().
inbound_options(DID) ->
[{'qs', [{'did', knm_converters:to_npan(DID)}
,{'cmd', <<"cnamenable">>}
,{'xml', <<"yes">>}
| knm_vitelity_util:default_options()
]}
,{'uri', knm_vitelity_util:api_uri()}
].
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec process_xml_resp(knm_phone_number:record(), kz_term:text()) ->
knm_phone_number:record().
process_xml_resp(PN, XML) ->
try xmerl_scan:string(XML) of
{XmlEl, _} -> process_xml_content_tag(PN, XmlEl)
catch
_E:_R ->
lager:debug("failed to process XML: ~s: ~p", [_E, _R]),
knm_errors:unspecified('invalid_resp_server', PN)
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec process_xml_content_tag(knm_phone_number:record(), kz_types:xml_el()) ->
knm_phone_number:record().
process_xml_content_tag(PN, #xmlElement{name='content'
,content=Children
}) ->
Els = kz_xml:elements(Children),
case knm_vitelity_util:xml_resp_status_msg(Els) of
<<"fail">> ->
Msg = knm_vitelity_util:xml_resp_error_msg(Els),
knm_errors:unspecified(Msg, PN);
<<"ok">> ->
FeatureData = kz_json:from_list([{?CNAM_INBOUND_LOOKUP, true}]),
knm_providers:activate_feature(PN, {?FEATURE_CNAM_INBOUND, FeatureData})
end.
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec publish_cnam_update(knm_phone_number:record()) -> 'ok'.
publish_cnam_update(PN) ->
Feature = knm_phone_number:feature(PN, ?FEATURE_CNAM),
Notify = [{<<"Account-ID">>, knm_phone_number:assigned_to(PN)}
,{<<"Number-State">>, knm_phone_number:state(PN)}
,{<<"Local-Number">>, knm_phone_number:module_name(PN) =:= ?CARRIER_LOCAL}
,{<<"Number">>, knm_util:pretty_print(knm_phone_number:number(PN))}
,{<<"Acquired-For">>, knm_phone_number:auth_by(PN)}
,{<<"Cnam">>, case Feature of 'undefined' -> kz_json:new(); _ -> Feature end}
| kz_api:default_headers(?APP_VERSION, ?APP_NAME)
],
kapps_notify_publisher:cast(Notify, fun kapi_notifications:publish_cnam_request/1).
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_numbers/src/providers/knm_vitelity_cnam.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc This function is called each time a number is saved, and will
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc This function is called each time a number is deleted
@end
------------------------------------------------------------------------------
=============================================================================
=============================================================================
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------ | ( C ) 2010 - 2020 , 2600Hz
@author
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(knm_vitelity_cnam).
-behaviour(knm_gen_provider).
-export([save/1]).
-export([delete/1]).
-include("knm.hrl").
produce notifications if the cnam object changes
-spec save(knm_phone_number:record()) -> knm_phone_number:record().
save(PN) ->
State = knm_phone_number:state(PN),
save(PN, State).
-spec save(knm_phone_number:record(), kz_term:ne_binary()) -> knm_phone_number:record().
save(PN, ?NUMBER_STATE_RESERVED) ->
handle_outbound_cnam(PN);
save(PN, ?NUMBER_STATE_IN_SERVICE) ->
handle_outbound_cnam(PN);
save(PN, ?NUMBER_STATE_PORT_IN) ->
handle_outbound_cnam(PN);
save(PN, _State) ->
PN.
-spec delete(knm_phone_number:record()) -> knm_phone_number:record().
delete(PN) ->
_ = remove_inbound_cnam(PN),
knm_providers:deactivate_features(PN
,[?FEATURE_CNAM_INBOUND
,?FEATURE_CNAM_OUTBOUND
,?FEATURE_CNAM
]
).
Internal functions
-spec handle_outbound_cnam(knm_phone_number:record()) -> knm_phone_number:record().
handle_outbound_cnam(PN) ->
IsDryRun = knm_phone_number:dry_run(PN),
Feature = knm_phone_number:feature(PN, ?FEATURE_CNAM_OUTBOUND),
Doc = knm_phone_number:doc(PN),
CurrentCNAM = kz_json:get_ne_value(?CNAM_DISPLAY_NAME, Feature),
case kz_json:get_ne_value([?FEATURE_CNAM, ?CNAM_DISPLAY_NAME], Doc) of
'undefined' ->
PN1 = knm_providers:deactivate_feature(PN, ?FEATURE_CNAM_OUTBOUND),
handle_inbound_cnam(PN1);
CurrentCNAM ->
handle_inbound_cnam(PN);
NewCNAM when IsDryRun ->
lager:debug("dry run: cnam display name changed to ~s", [NewCNAM]),
PN1 = knm_providers:activate_feature(PN, {?FEATURE_CNAM_OUTBOUND, NewCNAM}),
handle_inbound_cnam(PN1);
NewCNAM ->
lager:debug("cnam display name changed to ~s, updating", [NewCNAM]),
PN1 = try_update_outbound_cnam(PN, NewCNAM),
handle_inbound_cnam(PN1)
end.
-spec try_update_outbound_cnam(knm_phone_number:record(), kz_term:ne_binary()) ->
knm_phone_number:record().
try_update_outbound_cnam(PN, NewCNAM) ->
DID = knm_phone_number:number(PN),
case
knm_vitelity_util:query_vitelity(
knm_vitelity_util:build_uri(
outbound_cnam_options(DID, NewCNAM)
)
)
of
{'error', E} -> knm_errors:unspecified(E, PN);
{'ok', XML} -> process_outbound_xml_resp(PN, NewCNAM, XML)
end.
-spec outbound_cnam_options(kz_term:ne_binary(), kz_term:ne_binary()) ->
knm_vitelity_util:query_options().
outbound_cnam_options(DID, NewCNAM) ->
[{'qs', [{'cmd', <<"lidb">>}
,{'did', knm_converters:to_npan(DID)}
,{'name', NewCNAM}
,{'xml', <<"yes">>}
| knm_vitelity_util:default_options()
]}
,{'uri', knm_vitelity_util:api_uri()}
].
-spec process_outbound_xml_resp(knm_phone_number:record(), kz_term:ne_binary(), kz_term:text()) ->
knm_phone_number:record().
process_outbound_xml_resp(PN, FeatureData, XML_binary) ->
XML = unicode:characters_to_list(XML_binary),
try xmerl_scan:string(XML) of
{#xmlElement{name='content'
,content=Children
}
,_Left
} -> process_outbound_resp(PN, FeatureData, Children);
_ -> knm_errors:unspecified('unknown_resp_format', PN)
catch
_E:_R ->
knm_errors:unspecified('invalid_resp_format', PN)
end.
-spec process_outbound_resp(knm_phone_number:record(), kz_term:ne_binary(), kz_types:xml_els()) ->
knm_phone_number:record().
process_outbound_resp(PN, FeatureData, Children) ->
case knm_vitelity_util:xml_resp_status_msg(Children) of
<<"ok">> -> check_outbound_response_tag(PN, FeatureData, Children);
<<"fail">> ->
Msg = knm_vitelity_util:xml_resp_error_msg(Children),
knm_errors:unspecified(Msg, PN)
end.
-spec check_outbound_response_tag(knm_phone_number:record(), kz_term:ne_binary(), kz_types:xml_els()) ->
knm_phone_number:record().
check_outbound_response_tag(PN, NewCNAM, Children) ->
case knm_vitelity_util:xml_resp_response_msg(Children) of
'undefined' -> knm_errors:unspecified('resp_tag_not_found', PN);
<<"ok">> ->
FeatureData = kz_json:from_list([{?CNAM_DISPLAY_NAME, NewCNAM}]),
PN1 = knm_providers:activate_feature(PN, {?FEATURE_CNAM_OUTBOUND, FeatureData}),
publish_cnam_update(PN1),
PN1;
Msg ->
lager:debug("resp was not ok, was ~s", [Msg]),
knm_errors:unspecified(Msg, PN)
end.
-spec handle_inbound_cnam(knm_phone_number:record()) -> knm_phone_number:record().
handle_inbound_cnam(PN) ->
IsDryRun = knm_phone_number:dry_run(PN),
handle_inbound_cnam(PN, IsDryRun).
-spec handle_inbound_cnam(knm_phone_number:record(), boolean()) -> knm_phone_number:record().
handle_inbound_cnam(PN, 'true') ->
Doc = knm_phone_number:doc(PN),
case kz_json:is_true([?FEATURE_CNAM, ?CNAM_INBOUND_LOOKUP], Doc) of
'false' ->
knm_providers:deactivate_features(PN, [?FEATURE_CNAM_INBOUND
,?CNAM_INBOUND_LOOKUP
]);
'true' ->
FeatureData = kz_json:from_list([{?CNAM_INBOUND_LOOKUP, true}]),
knm_providers:activate_feature(PN, {?FEATURE_CNAM_INBOUND, FeatureData})
end;
handle_inbound_cnam(PN, 'false') ->
Doc = knm_phone_number:doc(PN),
case kz_json:is_true([?FEATURE_CNAM, ?CNAM_INBOUND_LOOKUP], Doc) of
'false' -> remove_inbound_cnam(PN);
'true' -> add_inbound_cnam(PN)
end.
-spec remove_inbound_cnam(knm_phone_number:record()) -> knm_phone_number:record().
remove_inbound_cnam(PN) ->
DID = knm_phone_number:number(PN),
_ = knm_vitelity_util:query_vitelity(
knm_vitelity_util:build_uri(
remove_inbound_options(DID)
)
),
knm_providers:deactivate_features(PN, [?FEATURE_CNAM_INBOUND
,?CNAM_INBOUND_LOOKUP
]).
-spec remove_inbound_options(kz_term:ne_binary()) -> knm_vitelity_util:query_options().
remove_inbound_options(PN) ->
[{'qs', [{'did', knm_converters:to_npan(PN)}
,{'cmd', <<"cnamdisable">>}
,{'xml', <<"yes">>}
| knm_vitelity_util:default_options()
]}
,{'uri', knm_vitelity_util:api_uri()}
].
-spec add_inbound_cnam(knm_phone_number:record()) ->
knm_phone_number:record().
add_inbound_cnam(PN) ->
DID = knm_phone_number:number(PN),
case
knm_vitelity_util:query_vitelity(
knm_vitelity_util:build_uri(
inbound_options(DID)
)
)
of
{'ok', XML} -> process_xml_resp(PN, XML);
{'error', _E} ->
knm_errors:unspecified('unknown_error', PN)
end.
-spec inbound_options(kz_term:ne_binary()) -> knm_vitelity_util:query_options().
inbound_options(DID) ->
[{'qs', [{'did', knm_converters:to_npan(DID)}
,{'cmd', <<"cnamenable">>}
,{'xml', <<"yes">>}
| knm_vitelity_util:default_options()
]}
,{'uri', knm_vitelity_util:api_uri()}
].
-spec process_xml_resp(knm_phone_number:record(), kz_term:text()) ->
knm_phone_number:record().
process_xml_resp(PN, XML) ->
try xmerl_scan:string(XML) of
{XmlEl, _} -> process_xml_content_tag(PN, XmlEl)
catch
_E:_R ->
lager:debug("failed to process XML: ~s: ~p", [_E, _R]),
knm_errors:unspecified('invalid_resp_server', PN)
end.
-spec process_xml_content_tag(knm_phone_number:record(), kz_types:xml_el()) ->
knm_phone_number:record().
process_xml_content_tag(PN, #xmlElement{name='content'
,content=Children
}) ->
Els = kz_xml:elements(Children),
case knm_vitelity_util:xml_resp_status_msg(Els) of
<<"fail">> ->
Msg = knm_vitelity_util:xml_resp_error_msg(Els),
knm_errors:unspecified(Msg, PN);
<<"ok">> ->
FeatureData = kz_json:from_list([{?CNAM_INBOUND_LOOKUP, true}]),
knm_providers:activate_feature(PN, {?FEATURE_CNAM_INBOUND, FeatureData})
end.
-spec publish_cnam_update(knm_phone_number:record()) -> 'ok'.
publish_cnam_update(PN) ->
Feature = knm_phone_number:feature(PN, ?FEATURE_CNAM),
Notify = [{<<"Account-ID">>, knm_phone_number:assigned_to(PN)}
,{<<"Number-State">>, knm_phone_number:state(PN)}
,{<<"Local-Number">>, knm_phone_number:module_name(PN) =:= ?CARRIER_LOCAL}
,{<<"Number">>, knm_util:pretty_print(knm_phone_number:number(PN))}
,{<<"Acquired-For">>, knm_phone_number:auth_by(PN)}
,{<<"Cnam">>, case Feature of 'undefined' -> kz_json:new(); _ -> Feature end}
| kz_api:default_headers(?APP_VERSION, ?APP_NAME)
],
kapps_notify_publisher:cast(Notify, fun kapi_notifications:publish_cnam_request/1).
|
58158d2e89da4844bfe08035b1ef4127302a9c64f3f3399bbb15ab00ae6c7316 | creichert/bencode | Parser.hs | # LANGUAGE CPP #
-----------------------------------------------------------------------------
-- |
-- Module : BParser
Copyright : ( c ) 2005 Lemmih < >
-- License : BSD3
-- Maintainer :
-- Stability : stable
-- Portability : portable
--
A parsec style parser for BEncoded data
-----------------------------------------------------------------------------
#
DEPRECATED " Use \"Data . . Reader\ " instead " #
DEPRECATED "Use \"Data.BEncode.Reader\" instead" #-}
( BParser
, runParser
, token
, dict
, list
, optional
, bstring
, bbytestring
, bint
, setInput
, (<|>)
) where
import Control.Applicative hiding (optional)
import Control.Monad
import Data.BEncode
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.Map as Map
#if MIN_VERSION_base(4,13,0)
import qualified Control.Monad.Fail as Fail
#endif
data BParser a
= BParser (BEncode -> Reply a)
instance Alternative BParser where
(<|>) = mplus
empty = mzero
instance MonadPlus BParser where
mzero = BParser $ \_ -> Error "mzero"
mplus (BParser a) (BParser b) = BParser $ \st -> case a st of
Error _err -> b st
ok -> ok
runB :: BParser a -> BEncode -> Reply a
runB (BParser b) = b
data Reply a
= Ok a BEncode
| Error String
instance Applicative BParser where
pure = return
(<*>) = ap
instance Monad BParser where
(BParser p) >>= f = BParser $ \b -> case p b of
Ok a b' -> runB (f a) b'
Error str -> Error str
return val = BParser $ Ok val
#if MIN_VERSION_base(4,13,0)
instance Fail.MonadFail BParser where
#endif
fail str = BParser $ \_ -> Error str
instance Functor BParser where
fmap = liftM
runParser :: BParser a -> BEncode -> Either String a
runParser parser b = case runB parser b of
Ok a _ -> Right a
Error str -> Left str
token :: BParser BEncode
token = BParser $ \b -> Ok b b
dict :: String -> BParser BEncode
dict name = BParser $ \b -> case b of
BDict bmap | Just code <- Map.lookup name bmap
-> Ok code b
BDict _ -> Error $ "Name not found in dictionary: " ++ name
_ -> Error $ "Not a dictionary: " ++ name
list :: String -> BParser a -> BParser [a]
list name p
= dict name >>= \lst ->
BParser $ \b -> case lst of
BList bs -> foldr (cat . runB p) (Ok [] b) bs
_ -> Error $ "Not a list: " ++ name
where cat (Ok v _) (Ok vs b) = Ok (v:vs) b
cat (Ok _ _) (Error str) = Error str
cat (Error str) _ = Error str
optional :: BParser a -> BParser (Maybe a)
optional p = liftM Just p <|> return Nothing
bstring :: BParser BEncode -> BParser String
bstring p = do b <- p
case b of
BString str -> return (L.unpack str)
_ -> fail $ "Expected BString, found: " ++ show b
bbytestring :: BParser BEncode -> BParser L.ByteString
bbytestring p = do b <- p
case b of
BString str -> return str
_ -> fail $ "Expected BString, found: " ++ show b
bint :: BParser BEncode -> BParser Integer
bint p = do b <- p
case b of
BInt int -> return int
_ -> fail $ "Expected BInt, found: " ++ show b
setInput :: BEncode -> BParser ()
setInput b = BParser $ \_ -> Ok () b
| null | https://raw.githubusercontent.com/creichert/bencode/ee1606cec92d8c2e142c8673c8e176c2151f8a70/src/Data/BEncode/Parser.hs | haskell | ---------------------------------------------------------------------------
|
Module : BParser
License : BSD3
Maintainer :
Stability : stable
Portability : portable
--------------------------------------------------------------------------- | # LANGUAGE CPP #
Copyright : ( c ) 2005 Lemmih < >
A parsec style parser for BEncoded data
#
DEPRECATED " Use \"Data . . Reader\ " instead " #
DEPRECATED "Use \"Data.BEncode.Reader\" instead" #-}
( BParser
, runParser
, token
, dict
, list
, optional
, bstring
, bbytestring
, bint
, setInput
, (<|>)
) where
import Control.Applicative hiding (optional)
import Control.Monad
import Data.BEncode
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.Map as Map
#if MIN_VERSION_base(4,13,0)
import qualified Control.Monad.Fail as Fail
#endif
data BParser a
= BParser (BEncode -> Reply a)
instance Alternative BParser where
(<|>) = mplus
empty = mzero
instance MonadPlus BParser where
mzero = BParser $ \_ -> Error "mzero"
mplus (BParser a) (BParser b) = BParser $ \st -> case a st of
Error _err -> b st
ok -> ok
runB :: BParser a -> BEncode -> Reply a
runB (BParser b) = b
data Reply a
= Ok a BEncode
| Error String
instance Applicative BParser where
pure = return
(<*>) = ap
instance Monad BParser where
(BParser p) >>= f = BParser $ \b -> case p b of
Ok a b' -> runB (f a) b'
Error str -> Error str
return val = BParser $ Ok val
#if MIN_VERSION_base(4,13,0)
instance Fail.MonadFail BParser where
#endif
fail str = BParser $ \_ -> Error str
instance Functor BParser where
fmap = liftM
runParser :: BParser a -> BEncode -> Either String a
runParser parser b = case runB parser b of
Ok a _ -> Right a
Error str -> Left str
token :: BParser BEncode
token = BParser $ \b -> Ok b b
dict :: String -> BParser BEncode
dict name = BParser $ \b -> case b of
BDict bmap | Just code <- Map.lookup name bmap
-> Ok code b
BDict _ -> Error $ "Name not found in dictionary: " ++ name
_ -> Error $ "Not a dictionary: " ++ name
list :: String -> BParser a -> BParser [a]
list name p
= dict name >>= \lst ->
BParser $ \b -> case lst of
BList bs -> foldr (cat . runB p) (Ok [] b) bs
_ -> Error $ "Not a list: " ++ name
where cat (Ok v _) (Ok vs b) = Ok (v:vs) b
cat (Ok _ _) (Error str) = Error str
cat (Error str) _ = Error str
optional :: BParser a -> BParser (Maybe a)
optional p = liftM Just p <|> return Nothing
bstring :: BParser BEncode -> BParser String
bstring p = do b <- p
case b of
BString str -> return (L.unpack str)
_ -> fail $ "Expected BString, found: " ++ show b
bbytestring :: BParser BEncode -> BParser L.ByteString
bbytestring p = do b <- p
case b of
BString str -> return str
_ -> fail $ "Expected BString, found: " ++ show b
bint :: BParser BEncode -> BParser Integer
bint p = do b <- p
case b of
BInt int -> return int
_ -> fail $ "Expected BInt, found: " ++ show b
setInput :: BEncode -> BParser ()
setInput b = BParser $ \_ -> Ok () b
|
f62e5e2daa755189822589ec91d001e548e5d5537eec8a7e007162fcec63650d | threatgrid/clj-momo | query.clj | (ns clj-momo.lib.es.query
(:require [clojure.string :as str]
[schema.core :as s]
[clj-momo.lib.es.schemas :refer [IdsQuery BoolQuery BoolQueryParams]]))
(s/defn ids :- IdsQuery
"Ids Query"
[ids :- [s/Str]]
{:ids {:values ids}})
(s/defn bool :- BoolQuery
"Boolean Query"
[opts :- BoolQueryParams]
{:bool opts})
(defn filtered
"Filtered query"
[opts]
{:filtered opts})
(defn nested
"Nested document query"
[opts]
{:nested opts})
(defn term
"Term Query"
([key values] (term key values nil))
([key values opts]
(merge { (if (coll? values) :terms :term) (hash-map key values) }
opts)))
(defn terms
"Terms Query"
([key values] (terms key values nil))
([key values opts]
(term key values opts)))
(defn nested-terms [filters]
"make nested terms from a filter:
[[[:observable :type] ip] [[:observable :value] 42.42.42.1]]
->
[{:terms {observable.type [ip]}} {:terms {observable.value [42.42.42.1]}}]
we force all values to lowercase, since our indexing does the same for all terms."
(vec (map (fn [[k v]]
(terms (->> k
(map name)
(str/join "."))
(map #(if (string? %)
(str/lower-case %)
%)
(if (coll? v) v [v]))))
filters)))
(defn prepare-terms [filter-map]
(let [terms (map (fn [[k v]]
(let [t-key (if (sequential? k) k [k])]
[t-key v]))
filter-map)]
(nested-terms terms)))
(defn filter-map->terms-query
"transforms a filter map to en ES terms query"
([filter-map]
(filter-map->terms-query filter-map nil))
([filter-map query]
(let [filter-terms (prepare-terms filter-map)]
(bool {:filter
(cond
(every? empty? [query filter-map]) [{:match_all {}}]
(empty? query) filter-terms
:else (conj filter-terms query))}))))
| null | https://raw.githubusercontent.com/threatgrid/clj-momo/7bc0a411593eee4a939b6a3d0f628413518e09e2/src/clj_momo/lib/es/query.clj | clojure | (ns clj-momo.lib.es.query
(:require [clojure.string :as str]
[schema.core :as s]
[clj-momo.lib.es.schemas :refer [IdsQuery BoolQuery BoolQueryParams]]))
(s/defn ids :- IdsQuery
"Ids Query"
[ids :- [s/Str]]
{:ids {:values ids}})
(s/defn bool :- BoolQuery
"Boolean Query"
[opts :- BoolQueryParams]
{:bool opts})
(defn filtered
"Filtered query"
[opts]
{:filtered opts})
(defn nested
"Nested document query"
[opts]
{:nested opts})
(defn term
"Term Query"
([key values] (term key values nil))
([key values opts]
(merge { (if (coll? values) :terms :term) (hash-map key values) }
opts)))
(defn terms
"Terms Query"
([key values] (terms key values nil))
([key values opts]
(term key values opts)))
(defn nested-terms [filters]
"make nested terms from a filter:
[[[:observable :type] ip] [[:observable :value] 42.42.42.1]]
->
[{:terms {observable.type [ip]}} {:terms {observable.value [42.42.42.1]}}]
we force all values to lowercase, since our indexing does the same for all terms."
(vec (map (fn [[k v]]
(terms (->> k
(map name)
(str/join "."))
(map #(if (string? %)
(str/lower-case %)
%)
(if (coll? v) v [v]))))
filters)))
(defn prepare-terms [filter-map]
(let [terms (map (fn [[k v]]
(let [t-key (if (sequential? k) k [k])]
[t-key v]))
filter-map)]
(nested-terms terms)))
(defn filter-map->terms-query
"transforms a filter map to en ES terms query"
([filter-map]
(filter-map->terms-query filter-map nil))
([filter-map query]
(let [filter-terms (prepare-terms filter-map)]
(bool {:filter
(cond
(every? empty? [query filter-map]) [{:match_all {}}]
(empty? query) filter-terms
:else (conj filter-terms query))}))))
| |
c56f804ced13549ba4ae98c9d266b121543cd49f205944ea51b185f471cfb3c2 | pkel/cpr | QueueSim.ml | module OrderedQueue = Cpr_lib.OrderedQueue
type time = T of float
type timedelta = D of float
type 'outcome step_outcome =
| Stop of 'outcome
| Continue
type ('event, 'outcome) model =
{ handler : (timedelta -> 'event -> unit) -> time -> 'event -> 'outcome step_outcome
; init : (time * 'event) list
}
type 'event sim_state =
{ mutable queue : (float, 'event) OrderedQueue.t
; mutable time : float
}
let init events =
let open OrderedQueue in
let queue =
let empty = init Float.compare in
List.fold_left (fun acc (T time, event) -> queue time event acc) empty events
in
{ queue; time = 0. }
;;
let run model =
let state = init model.init in
let delay (D d) ev =
state.queue <- OrderedQueue.queue (state.time +. d) ev state.queue
in
let rec step () =
match OrderedQueue.dequeue state.queue with
| None -> Error `EmptyQueue
| Some (t, e, q) ->
state.time <- t;
state.queue <- q;
(match model.handler delay (T t) e with
| Continue -> step ()
| Stop outcome -> Ok outcome)
in
step ()
;;
| null | https://raw.githubusercontent.com/pkel/cpr/854db775bdeb2e95ec94dc9f815314157e74dd81/experiments/safety-bounds/ml/QueueSim.ml | ocaml | module OrderedQueue = Cpr_lib.OrderedQueue
type time = T of float
type timedelta = D of float
type 'outcome step_outcome =
| Stop of 'outcome
| Continue
type ('event, 'outcome) model =
{ handler : (timedelta -> 'event -> unit) -> time -> 'event -> 'outcome step_outcome
; init : (time * 'event) list
}
type 'event sim_state =
{ mutable queue : (float, 'event) OrderedQueue.t
; mutable time : float
}
let init events =
let open OrderedQueue in
let queue =
let empty = init Float.compare in
List.fold_left (fun acc (T time, event) -> queue time event acc) empty events
in
{ queue; time = 0. }
;;
let run model =
let state = init model.init in
let delay (D d) ev =
state.queue <- OrderedQueue.queue (state.time +. d) ev state.queue
in
let rec step () =
match OrderedQueue.dequeue state.queue with
| None -> Error `EmptyQueue
| Some (t, e, q) ->
state.time <- t;
state.queue <- q;
(match model.handler delay (T t) e with
| Continue -> step ()
| Stop outcome -> Ok outcome)
in
step ()
;;
| |
19b4cae1058338ec885de6922c7e14ed87bb49ce8cba9550011d0853002a24f1 | simplex-chat/simplexmq | M20230110_users.hs | # LANGUAGE QuasiQuotes #
module Simplex.Messaging.Agent.Store.SQLite.Migrations.M20230110_users where
import Database.SQLite.Simple (Query)
import Database.SQLite.Simple.QQ (sql)
m20230110_users :: Query
m20230110_users =
[sql|
PRAGMA ignore_check_constraints=ON;
CREATE TABLE users (
user_id INTEGER PRIMARY KEY AUTOINCREMENT
);
INSERT INTO users (user_id) VALUES (1);
ALTER TABLE connections ADD COLUMN user_id INTEGER CHECK (user_id NOT NULL)
REFERENCES users ON DELETE CASCADE;
CREATE INDEX idx_connections_user ON connections(user_id);
CREATE INDEX idx_commands_conn_id ON commands(conn_id);
UPDATE connections SET user_id = 1;
PRAGMA ignore_check_constraints=OFF;
|]
| null | https://raw.githubusercontent.com/simplex-chat/simplexmq/e4aad7583f425765c605cd8042e3136e048bdbec/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/M20230110_users.hs | haskell | # LANGUAGE QuasiQuotes #
module Simplex.Messaging.Agent.Store.SQLite.Migrations.M20230110_users where
import Database.SQLite.Simple (Query)
import Database.SQLite.Simple.QQ (sql)
m20230110_users :: Query
m20230110_users =
[sql|
PRAGMA ignore_check_constraints=ON;
CREATE TABLE users (
user_id INTEGER PRIMARY KEY AUTOINCREMENT
);
INSERT INTO users (user_id) VALUES (1);
ALTER TABLE connections ADD COLUMN user_id INTEGER CHECK (user_id NOT NULL)
REFERENCES users ON DELETE CASCADE;
CREATE INDEX idx_connections_user ON connections(user_id);
CREATE INDEX idx_commands_conn_id ON commands(conn_id);
UPDATE connections SET user_id = 1;
PRAGMA ignore_check_constraints=OFF;
|]
| |
ceba4caad42bf279c1ac009dec0cb0be3ad1ab8d36cefe1036648bc28b27846f | rudymatela/express | Canon.hs | -- |
-- Module : Data.Express.Canon
Copyright : ( c ) 2019 - 2021
License : 3 - Clause BSD ( see the file LICENSE )
Maintainer : < >
--
Utilities for canonicalizing ' 's with variables .
module Data.Express.Canon
( canonicalize
, canonicalizeWith
, canonicalization
, canonicalizationWith
, isCanonical
, isCanonicalWith
, canonicalVariations
, mostGeneralCanonicalVariation
, mostSpecificCanonicalVariation
, fastCanonicalVariations
, fastMostGeneralVariation
, fastMostSpecificVariation
)
where
import Data.Express.Basic
import Data.Express.Name
import Data.Express.Instances
import Data.List ((\\))
-- |
-- Like 'canonicalize' but allows customization
-- of the list of variable names.
-- (cf. 'lookupNames', 'variableNamesFromTemplate')
--
> > canonicalizeWith ( const [ " i","j","k","l " , ... ] ) ( )
-- > i + j :: Int
--
The argument ' ' of the argument function allows
-- to provide a different list of names for different types:
--
-- > > let namesFor e
> > | typ e = = ( undefined::Char ) = variableNamesFromTemplate " c1 "
-- > > | typ e == typeOf (undefined::Int) = variableNamesFromTemplate "i"
-- > > | otherwise = variableNamesFromTemplate "x"
--
-- > > canonicalizeWith namesFor ((xx -+- ord' dd) -+- (ord' cc -+- yy))
-- > (i + ord c1) + (ord c2 + j) :: Int
canonicalizeWith :: (Expr -> [String]) -> Expr -> Expr
canonicalizeWith namesFor e = e //- canonicalizationWith namesFor e
-- |
-- Like 'canonicalization' but allows customization
-- of the list of variable names.
-- (cf. 'lookupNames', 'variableNamesFromTemplate')
canonicalizationWith :: (Expr -> [String]) -> Expr -> [(Expr,Expr)]
canonicalizationWith namesFor e = cr (vars e) []
where
cr :: [Expr] -> [(Expr,Expr)] -> [(Expr,Expr)]
cr [] bs = bs
cr (e:es) bs = cr es
$ if e `elem` map fst bs
then bs
else (e, n `varAsTypeOf` e):bs
where
existingNames = [n | (_,Value ('_':n) _) <- bs]
freshNames = namesFor e \\ existingNames
n = head freshNames
-- |
-- Like 'isCanonical' but allows specifying
-- the list of variable names.
isCanonicalWith :: (Expr -> [String]) -> Expr -> Bool
isCanonicalWith ti e = canonicalizeWith ti e == e
-- |
-- Canonicalizes an 'Expr' so that variable names appear in order.
-- Variable names are taken from the 'preludeNameInstances'.
--
> > canonicalize ( )
-- > x + y :: Int
--
-- > > canonicalize (yy -+- xx)
-- > x + y :: Int
--
> > canonicalize ( )
-- > x + x :: Int
--
-- > > canonicalize (yy -+- yy)
-- > x + x :: Int
--
-- Constants are untouched:
--
> > canonicalize ( jj -+- ( zero -+- abs ' ii ) )
-- > x + (y + abs y) :: Int
--
-- This also works for variable functions:
--
> > canonicalize ( gg yy -+- ff xx )
-- > (f x + g y) + f y :: Int
canonicalize :: Expr -> Expr
canonicalize = canonicalizeWith names'
-- |
-- Return a canonicalization of an 'Expr'
-- that makes variable names appear in order
-- using 'names' as provided by 'preludeNameInstances'.
By using ' //- ' it can ' canonicalize ' ' 's .
--
> > canonicalization ( gg yy -+- ff xx )
-- > [ (x :: Int, y :: Int)
> , ( f : : Int - > Int , : : Int - > Int )
-- > , (y :: Int, x :: Int)
-- > , (g :: Int -> Int, f :: Int -> Int) ]
--
-- > > canonicalization (yy -+- xx -+- yy)
-- > [ (x :: Int, y :: Int)
-- > , (y :: Int, x :: Int) ]
canonicalization :: Expr -> [(Expr,Expr)]
canonicalization = canonicalizationWith names'
-- |
-- Returns whether an 'Expr' is canonical:
-- if applying 'canonicalize' is an identity
-- using 'names' as provided by 'preludeNameInstances'.
isCanonical :: Expr -> Bool
isCanonical = isCanonicalWith names'
' names ' lifted over the ' ' type for a handful of prelude Name instances .
names' :: Expr -> [String]
names' = lookupNames preludeNameInstances
-- |
-- Returns all canonical variations of an 'Expr'
-- by filling holes with variables.
-- Where possible, variations are listed
-- from most general to least general.
--
-- > > canonicalVariations $ i_
-- > [x :: Int]
--
-- > > canonicalVariations $ i_ -+- i_
-- > [ x + y :: Int
-- > , x + x :: Int ]
--
-- > > canonicalVariations $ i_ -+- i_ -+- i_
-- > [ (x + y) + z :: Int
-- > , (x + y) + x :: Int
-- > , (x + y) + y :: Int
-- > , (x + x) + y :: Int
-- > , (x + x) + x :: Int ]
--
-- > > canonicalVariations $ i_ -+- ord' c_
-- > [x + ord c :: Int]
--
-- > > canonicalVariations $ i_ -+- i_ -+- ord' c_
-- > [ (x + y) + ord c :: Int
-- > , (x + x) + ord c :: Int ]
--
-- > > canonicalVariations $ i_ -+- i_ -+- length' (c_ -:- unit c_)
-- > [ (x + y) + length (c:d:"") :: Int
-- > , (x + y) + length (c:c:"") :: Int
-- > , (x + x) + length (c:d:"") :: Int
-- > , (x + x) + length (c:c:"") :: Int ]
--
-- In an expression without holes this functions just returns a singleton list
-- with the expression itself:
--
-- > > canonicalVariations $ val (0 :: Int)
-- > [0 :: Int]
--
-- > > canonicalVariations $ ord' bee
-- > [ord 'b' :: Int]
--
-- When applying this to expressions already containing variables
-- clashes are avoided and these variables are not touched:
--
-- > > canonicalVariations $ i_ -+- ii -+- jj -+- i_
-- > [ x + i + j + y :: Int
-- > , x + i + j + y :: Int ]
--
-- > > canonicalVariations $ ii -+- jj
-- > [i + j :: Int]
--
-- > > canonicalVariations $ xx -+- i_ -+- i_ -+- length' (c_ -:- unit c_) -+- yy
-- > [ (((x + z) + x') + length (c:d:"")) + y :: Int
-- > , (((x + z) + x') + length (c:c:"")) + y :: Int
-- > , (((x + z) + z) + length (c:d:"")) + y :: Int
-- > , (((x + z) + z) + length (c:c:"")) + y :: Int
-- > ]
canonicalVariations :: Expr -> [Expr]
canonicalVariations e = map (canonicalizeKeeping (nonHoleVars e))
$ fastCanonicalVariations e
-- |
-- Returns the most general canonical variation of an 'Expr'
-- by filling holes with variables.
--
-- > > mostGeneralCanonicalVariation $ i_
-- > x :: Int
--
-- > > mostGeneralCanonicalVariation $ i_ -+- i_
-- > x + y :: Int
--
-- > > mostGeneralCanonicalVariation $ i_ -+- i_ -+- i_
-- > (x + y) + z :: Int
--
-- > > mostGeneralCanonicalVariation $ i_ -+- ord' c_
-- > x + ord c :: Int
--
-- > > mostGeneralCanonicalVariation $ i_ -+- i_ -+- ord' c_
-- > (x + y) + ord c :: Int
--
-- > > mostGeneralCanonicalVariation $ i_ -+- i_ -+- length' (c_ -:- unit c_)
-- > (x + y) + length (c:d:"") :: Int
--
-- In an expression without holes this functions just returns
-- the given expression itself:
--
-- > > mostGeneralCanonicalVariation $ val (0 :: Int)
-- > 0 :: Int
--
-- > > mostGeneralCanonicalVariation $ ord' bee
-- > ord 'b' :: Int
--
-- This function is the same as taking the 'head' of 'canonicalVariations'
-- but a bit faster.
mostGeneralCanonicalVariation :: Expr -> Expr
mostGeneralCanonicalVariation e = canonicalizeKeeping (nonHoleVars e)
$ fastMostGeneralVariation e
-- |
-- Returns the most specific canonical variation of an 'Expr'
-- by filling holes with variables.
--
-- > > mostSpecificCanonicalVariation $ i_
-- > x :: Int
--
-- > > mostSpecificCanonicalVariation $ i_ -+- i_
-- > x + x :: Int
--
-- > > mostSpecificCanonicalVariation $ i_ -+- i_ -+- i_
-- > (x + x) + x :: Int
--
-- > > mostSpecificCanonicalVariation $ i_ -+- ord' c_
-- > x + ord c :: Int
--
-- > > mostSpecificCanonicalVariation $ i_ -+- i_ -+- ord' c_
-- > (x + x) + ord c :: Int
--
-- > > mostSpecificCanonicalVariation $ i_ -+- i_ -+- length' (c_ -:- unit c_)
-- > (x + x) + length (c:c:"") :: Int
--
-- In an expression without holes this functions just returns
-- the given expression itself:
--
-- > > mostSpecificCanonicalVariation $ val (0 :: Int)
-- > 0 :: Int
--
-- > > mostSpecificCanonicalVariation $ ord' bee
-- > ord 'b' :: Int
--
-- This function is the same as taking the 'last' of 'canonicalVariations'
-- but a bit faster.
mostSpecificCanonicalVariation :: Expr -> Expr
mostSpecificCanonicalVariation e = canonicalizeKeeping (nonHoleVars e)
$ fastMostSpecificVariation e
-- |
-- A faster version of 'canonicalVariations' that
-- disregards name clashes across different types.
-- Results are confusing to the user
but fine for Express which differentiates
-- between variables with the same name but different types.
--
Without applying ' canonicalize ' , the following ' '
may seem to have only one variable :
--
-- > > fastCanonicalVariations $ i_ -+- ord' c_
-- > [x + ord x :: Int]
--
Where in fact it has two , as the second @ x @ has a different type .
-- Applying 'canonicalize' disambiguates:
--
-- > > map canonicalize . fastCanonicalVariations $ i_ -+- ord' c_
-- > [x + ord c :: Int]
--
This function is useful when resulting ' 's are
-- not intended to be presented to the user
-- but instead to be used by another function.
-- It is simply faster to skip the step where clashes are resolved.
fastCanonicalVariations :: Expr -> [Expr]
fastCanonicalVariations e
| null hs' = [e]
| otherwise = concatMap fastCanonicalVariations
. map (fill e) . fillings 0
$ [h | h <- hs', typ h == typ h']
where
hs' = holes e
h' = head hs'
names = variableNamesFromTemplate "x" \\ varnames e
fillings :: Int -> [Expr] -> [[Expr]]
fillings i [] = [[]] -- no holes, single empty filling
fillings i (h:hs) =
concat $ map (names !! i `varAsTypeOf` h:) (fillings (i+1) hs) -- new var
: [ map (n `varAsTypeOf` h:) (fillings i hs) -- no new variable
| n <- take i names ]
-- |
-- A faster version of 'mostGeneralCanonicalVariation'
-- that disregards name clashes across different types.
-- Consider using 'mostGeneralCanonicalVariation' instead.
--
-- The same caveats of 'fastCanonicalVariations' do apply here.
fastMostGeneralVariation :: Expr -> Expr
fastMostGeneralVariation e = fill e (zipWith varAsTypeOf names (holes e))
where
names = variableNamesFromTemplate "x" \\ varnames e
-- |
-- A faster version of 'mostSpecificCanonicalVariation'
-- that disregards name clashes across different types.
-- Consider using 'mostSpecificCanonicalVariation' instead.
--
-- The same caveats of 'fastCanonicalVariations' do apply here.
fastMostSpecificVariation :: Expr -> Expr
fastMostSpecificVariation e = fill e (map (name `varAsTypeOf`) (holes e))
where
name = head $ variableNamesFromTemplate "x" \\ varnames e
-- |
Variable names existing in a given .
--
-- This function is not exported.
varnames :: Expr -> [String]
varnames e = [n | Value ('_':n) _ <- vars e]
-- |
-- Variables that are not holes.
--
-- This function is not exported.
nonHoleVars :: Expr -> [Expr]
nonHoleVars = filter (not . isHole) . nubVars
| Canonicalizes an ' ' while keeping the given variables untouched .
--
-- > > canonicalizeKeeping [zz] (zz -+- ii -+- jj)
-- > z + x + y :: Int
--
-- > > canonicalizeKeeping [ii,jj] (zz -+- ii -+- jj)
-- > x + i + j :: Int
--
-- This function is not exported.
canonicalizeKeeping :: [Expr] -> Expr -> Expr
canonicalizeKeeping vs e = canonicalizeWith namesFor e
where
nm (Value ('_':n) _) = n
namesFor v | v `elem` vs = nm v : err
| otherwise = names' v \\ map nm vs
err = error "Data.Express.canonicalizeKeeping: the impossible happened. This is definitely a bug."
| null | https://raw.githubusercontent.com/rudymatela/express/ac28404b82a3b282f538279c0e8796491122dd7b/src/Data/Express/Canon.hs | haskell | |
Module : Data.Express.Canon
|
Like 'canonicalize' but allows customization
of the list of variable names.
(cf. 'lookupNames', 'variableNamesFromTemplate')
> i + j :: Int
to provide a different list of names for different types:
> > let namesFor e
> > | typ e == typeOf (undefined::Int) = variableNamesFromTemplate "i"
> > | otherwise = variableNamesFromTemplate "x"
> > canonicalizeWith namesFor ((xx -+- ord' dd) -+- (ord' cc -+- yy))
> (i + ord c1) + (ord c2 + j) :: Int
|
Like 'canonicalization' but allows customization
of the list of variable names.
(cf. 'lookupNames', 'variableNamesFromTemplate')
|
Like 'isCanonical' but allows specifying
the list of variable names.
|
Canonicalizes an 'Expr' so that variable names appear in order.
Variable names are taken from the 'preludeNameInstances'.
> x + y :: Int
> > canonicalize (yy -+- xx)
> x + y :: Int
> x + x :: Int
> > canonicalize (yy -+- yy)
> x + x :: Int
Constants are untouched:
> x + (y + abs y) :: Int
This also works for variable functions:
> (f x + g y) + f y :: Int
|
Return a canonicalization of an 'Expr'
that makes variable names appear in order
using 'names' as provided by 'preludeNameInstances'.
> [ (x :: Int, y :: Int)
> , (y :: Int, x :: Int)
> , (g :: Int -> Int, f :: Int -> Int) ]
> > canonicalization (yy -+- xx -+- yy)
> [ (x :: Int, y :: Int)
> , (y :: Int, x :: Int) ]
|
Returns whether an 'Expr' is canonical:
if applying 'canonicalize' is an identity
using 'names' as provided by 'preludeNameInstances'.
|
Returns all canonical variations of an 'Expr'
by filling holes with variables.
Where possible, variations are listed
from most general to least general.
> > canonicalVariations $ i_
> [x :: Int]
> > canonicalVariations $ i_ -+- i_
> [ x + y :: Int
> , x + x :: Int ]
> > canonicalVariations $ i_ -+- i_ -+- i_
> [ (x + y) + z :: Int
> , (x + y) + x :: Int
> , (x + y) + y :: Int
> , (x + x) + y :: Int
> , (x + x) + x :: Int ]
> > canonicalVariations $ i_ -+- ord' c_
> [x + ord c :: Int]
> > canonicalVariations $ i_ -+- i_ -+- ord' c_
> [ (x + y) + ord c :: Int
> , (x + x) + ord c :: Int ]
> > canonicalVariations $ i_ -+- i_ -+- length' (c_ -:- unit c_)
> [ (x + y) + length (c:d:"") :: Int
> , (x + y) + length (c:c:"") :: Int
> , (x + x) + length (c:d:"") :: Int
> , (x + x) + length (c:c:"") :: Int ]
In an expression without holes this functions just returns a singleton list
with the expression itself:
> > canonicalVariations $ val (0 :: Int)
> [0 :: Int]
> > canonicalVariations $ ord' bee
> [ord 'b' :: Int]
When applying this to expressions already containing variables
clashes are avoided and these variables are not touched:
> > canonicalVariations $ i_ -+- ii -+- jj -+- i_
> [ x + i + j + y :: Int
> , x + i + j + y :: Int ]
> > canonicalVariations $ ii -+- jj
> [i + j :: Int]
> > canonicalVariations $ xx -+- i_ -+- i_ -+- length' (c_ -:- unit c_) -+- yy
> [ (((x + z) + x') + length (c:d:"")) + y :: Int
> , (((x + z) + x') + length (c:c:"")) + y :: Int
> , (((x + z) + z) + length (c:d:"")) + y :: Int
> , (((x + z) + z) + length (c:c:"")) + y :: Int
> ]
|
Returns the most general canonical variation of an 'Expr'
by filling holes with variables.
> > mostGeneralCanonicalVariation $ i_
> x :: Int
> > mostGeneralCanonicalVariation $ i_ -+- i_
> x + y :: Int
> > mostGeneralCanonicalVariation $ i_ -+- i_ -+- i_
> (x + y) + z :: Int
> > mostGeneralCanonicalVariation $ i_ -+- ord' c_
> x + ord c :: Int
> > mostGeneralCanonicalVariation $ i_ -+- i_ -+- ord' c_
> (x + y) + ord c :: Int
> > mostGeneralCanonicalVariation $ i_ -+- i_ -+- length' (c_ -:- unit c_)
> (x + y) + length (c:d:"") :: Int
In an expression without holes this functions just returns
the given expression itself:
> > mostGeneralCanonicalVariation $ val (0 :: Int)
> 0 :: Int
> > mostGeneralCanonicalVariation $ ord' bee
> ord 'b' :: Int
This function is the same as taking the 'head' of 'canonicalVariations'
but a bit faster.
|
Returns the most specific canonical variation of an 'Expr'
by filling holes with variables.
> > mostSpecificCanonicalVariation $ i_
> x :: Int
> > mostSpecificCanonicalVariation $ i_ -+- i_
> x + x :: Int
> > mostSpecificCanonicalVariation $ i_ -+- i_ -+- i_
> (x + x) + x :: Int
> > mostSpecificCanonicalVariation $ i_ -+- ord' c_
> x + ord c :: Int
> > mostSpecificCanonicalVariation $ i_ -+- i_ -+- ord' c_
> (x + x) + ord c :: Int
> > mostSpecificCanonicalVariation $ i_ -+- i_ -+- length' (c_ -:- unit c_)
> (x + x) + length (c:c:"") :: Int
In an expression without holes this functions just returns
the given expression itself:
> > mostSpecificCanonicalVariation $ val (0 :: Int)
> 0 :: Int
> > mostSpecificCanonicalVariation $ ord' bee
> ord 'b' :: Int
This function is the same as taking the 'last' of 'canonicalVariations'
but a bit faster.
|
A faster version of 'canonicalVariations' that
disregards name clashes across different types.
Results are confusing to the user
between variables with the same name but different types.
> > fastCanonicalVariations $ i_ -+- ord' c_
> [x + ord x :: Int]
Applying 'canonicalize' disambiguates:
> > map canonicalize . fastCanonicalVariations $ i_ -+- ord' c_
> [x + ord c :: Int]
not intended to be presented to the user
but instead to be used by another function.
It is simply faster to skip the step where clashes are resolved.
no holes, single empty filling
new var
no new variable
|
A faster version of 'mostGeneralCanonicalVariation'
that disregards name clashes across different types.
Consider using 'mostGeneralCanonicalVariation' instead.
The same caveats of 'fastCanonicalVariations' do apply here.
|
A faster version of 'mostSpecificCanonicalVariation'
that disregards name clashes across different types.
Consider using 'mostSpecificCanonicalVariation' instead.
The same caveats of 'fastCanonicalVariations' do apply here.
|
This function is not exported.
|
Variables that are not holes.
This function is not exported.
> > canonicalizeKeeping [zz] (zz -+- ii -+- jj)
> z + x + y :: Int
> > canonicalizeKeeping [ii,jj] (zz -+- ii -+- jj)
> x + i + j :: Int
This function is not exported. | Copyright : ( c ) 2019 - 2021
License : 3 - Clause BSD ( see the file LICENSE )
Maintainer : < >
Utilities for canonicalizing ' 's with variables .
module Data.Express.Canon
( canonicalize
, canonicalizeWith
, canonicalization
, canonicalizationWith
, isCanonical
, isCanonicalWith
, canonicalVariations
, mostGeneralCanonicalVariation
, mostSpecificCanonicalVariation
, fastCanonicalVariations
, fastMostGeneralVariation
, fastMostSpecificVariation
)
where
import Data.Express.Basic
import Data.Express.Name
import Data.Express.Instances
import Data.List ((\\))
> > canonicalizeWith ( const [ " i","j","k","l " , ... ] ) ( )
The argument ' ' of the argument function allows
> > | typ e = = ( undefined::Char ) = variableNamesFromTemplate " c1 "
canonicalizeWith :: (Expr -> [String]) -> Expr -> Expr
canonicalizeWith namesFor e = e //- canonicalizationWith namesFor e
canonicalizationWith :: (Expr -> [String]) -> Expr -> [(Expr,Expr)]
canonicalizationWith namesFor e = cr (vars e) []
where
cr :: [Expr] -> [(Expr,Expr)] -> [(Expr,Expr)]
cr [] bs = bs
cr (e:es) bs = cr es
$ if e `elem` map fst bs
then bs
else (e, n `varAsTypeOf` e):bs
where
existingNames = [n | (_,Value ('_':n) _) <- bs]
freshNames = namesFor e \\ existingNames
n = head freshNames
isCanonicalWith :: (Expr -> [String]) -> Expr -> Bool
isCanonicalWith ti e = canonicalizeWith ti e == e
> > canonicalize ( )
> > canonicalize ( )
> > canonicalize ( jj -+- ( zero -+- abs ' ii ) )
> > canonicalize ( gg yy -+- ff xx )
canonicalize :: Expr -> Expr
canonicalize = canonicalizeWith names'
By using ' //- ' it can ' canonicalize ' ' 's .
> > canonicalization ( gg yy -+- ff xx )
> , ( f : : Int - > Int , : : Int - > Int )
canonicalization :: Expr -> [(Expr,Expr)]
canonicalization = canonicalizationWith names'
isCanonical :: Expr -> Bool
isCanonical = isCanonicalWith names'
' names ' lifted over the ' ' type for a handful of prelude Name instances .
names' :: Expr -> [String]
names' = lookupNames preludeNameInstances
canonicalVariations :: Expr -> [Expr]
canonicalVariations e = map (canonicalizeKeeping (nonHoleVars e))
$ fastCanonicalVariations e
mostGeneralCanonicalVariation :: Expr -> Expr
mostGeneralCanonicalVariation e = canonicalizeKeeping (nonHoleVars e)
$ fastMostGeneralVariation e
mostSpecificCanonicalVariation :: Expr -> Expr
mostSpecificCanonicalVariation e = canonicalizeKeeping (nonHoleVars e)
$ fastMostSpecificVariation e
but fine for Express which differentiates
Without applying ' canonicalize ' , the following ' '
may seem to have only one variable :
Where in fact it has two , as the second @ x @ has a different type .
This function is useful when resulting ' 's are
fastCanonicalVariations :: Expr -> [Expr]
fastCanonicalVariations e
| null hs' = [e]
| otherwise = concatMap fastCanonicalVariations
. map (fill e) . fillings 0
$ [h | h <- hs', typ h == typ h']
where
hs' = holes e
h' = head hs'
names = variableNamesFromTemplate "x" \\ varnames e
fillings :: Int -> [Expr] -> [[Expr]]
fillings i (h:hs) =
| n <- take i names ]
fastMostGeneralVariation :: Expr -> Expr
fastMostGeneralVariation e = fill e (zipWith varAsTypeOf names (holes e))
where
names = variableNamesFromTemplate "x" \\ varnames e
fastMostSpecificVariation :: Expr -> Expr
fastMostSpecificVariation e = fill e (map (name `varAsTypeOf`) (holes e))
where
name = head $ variableNamesFromTemplate "x" \\ varnames e
Variable names existing in a given .
varnames :: Expr -> [String]
varnames e = [n | Value ('_':n) _ <- vars e]
nonHoleVars :: Expr -> [Expr]
nonHoleVars = filter (not . isHole) . nubVars
| Canonicalizes an ' ' while keeping the given variables untouched .
canonicalizeKeeping :: [Expr] -> Expr -> Expr
canonicalizeKeeping vs e = canonicalizeWith namesFor e
where
nm (Value ('_':n) _) = n
namesFor v | v `elem` vs = nm v : err
| otherwise = names' v \\ map nm vs
err = error "Data.Express.canonicalizeKeeping: the impossible happened. This is definitely a bug."
|
5d6df9ab81faa907da4b3416ea007f33f5029ade8750794775719053be1fbbd7 | erlang/otp | ct_test_support.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2022 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%% Test support functions
%%%
This is a support module for testing the Common Test Framework .
%%%
-module(ct_test_support).
-include_lib("common_test/include/ct_event.hrl").
-include_lib("common_test/include/ct.hrl").
-export([init_per_suite/1, init_per_suite/2, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2,
write_testspec/2, write_testspec/3,
run/2, run/3, run/4, run_ct_run_test/2, run_ct_script_start/2,
get_opts/1, wait_for_ct_stop/1]).
-export([handle_event/2, start_event_receiver/1, get_events/2,
verify_events/3, verify_events/4, reformat/2, log_events/4,
join_abs_dirs/2]).
-export([start_slave/3, slave_stop/1]).
-export([ct_test_halt/1, ct_rpc/2]).
-export([random_error/1]).
-export([unique_timestamp/0]).
-export([rm_dir/1]).
-include_lib("kernel/include/file.hrl").
%%%-----------------------------------------------------------------
%%% init_per_suite/1
init_per_suite(Config) ->
init_per_suite(Config, 50).
init_per_suite(Config, Level) ->
ScaleFactor = test_server:timetrap_scale_factor(),
case os:type() of
{win32, _} ->
Extend timeout to 1 hour for windows as starting node
%% can take a long time there
test_server:timetrap( 60*60*1000 * ScaleFactor );
_ ->
ok
end,
case delete_old_logs(os:type(), Config) of
{'EXIT',DelLogsReason} ->
test_server:format(0, "Failed to delete old log directories: ~tp~n",
[DelLogsReason]);
_ ->
ok
end,
{Mult,Scale} = test_server_ctrl:get_timetrap_parameters(),
test_server:format(Level, "Timetrap multiplier: ~w~n", [Mult]),
if Scale == true ->
test_server:format(Level, "Timetrap scale factor: ~w~n",
[ScaleFactor]);
true ->
ok
end,
start_slave(Config, Level).
start_slave(Config, Level) ->
start_slave(ct, Config, Level).
start_slave(NodeName, Config, Level) ->
[_,Host] = string:lexemes(atom_to_list(node()), "@"),
test_server:format(0, "Trying to start ~s~n",
[atom_to_list(NodeName)++"@"++Host]),
PR = proplists:get_value(printable_range,Config,io:printable_range()),
case slave:start(Host, NodeName, "+pc " ++ atom_to_list(PR)) of
{error,Reason} ->
ct:fail(Reason);
{ok,CTNode} ->
test_server:format(0, "Node ~p started~n", [CTNode]),
IsCover = test_server:is_cover(),
if IsCover ->
cover:start(CTNode);
true ->
ok
end,
DataDir = proplists:get_value(data_dir, Config),
PrivDir = proplists:get_value(priv_dir, Config),
PrivDir as well as directory of Test Server suites
%% have to be in code path on Common Test node.
[_ | Parts] = lists:reverse(filename:split(DataDir)),
TSDir = filename:join(lists:reverse(Parts)),
AddPathDirs = case proplists:get_value(path_dirs, Config) of
undefined -> [];
Ds -> Ds
end,
TestSupDir = filename:dirname(code:which(?MODULE)),
PathDirs = [PrivDir,TSDir,TestSupDir | AddPathDirs],
[true = rpc:call(CTNode, code, add_patha, [D]) || D <- PathDirs],
test_server:format(Level, "Dirs added to code path (on ~w):~n",
[CTNode]),
[io:format("~ts~n", [D]) || D <- PathDirs],
case proplists:get_value(start_sasl, Config) of
true ->
rpc:call(CTNode, application, start, [sasl]),
test_server:format(Level, "SASL started on ~w~n", [CTNode]);
_ ->
ok
end,
TraceFile = filename:join(DataDir, "ct.trace"),
case file:read_file_info(TraceFile) of
{ok,_} ->
[{trace_level,0},
{ct_opts,[{ct_trace,TraceFile}]},
{ct_node,CTNode} | Config];
_ ->
[{trace_level,Level},
{ct_opts,[]},
{ct_node,CTNode} | Config]
end
end.
%%%-----------------------------------------------------------------
%%% end_per_suite/1
end_per_suite(Config) ->
CTNode = proplists:get_value(ct_node, Config),
PrivDir = proplists:get_value(priv_dir, Config),
true = rpc:call(CTNode, code, del_path, [filename:join(PrivDir,"")]),
slave_stop(CTNode),
ok.
%%%-----------------------------------------------------------------
%%% init_per_testcase/2
init_per_testcase(_TestCase, Config) ->
Opts = get_opts(Config),
NetDir = proplists:get_value(net_dir, Opts),
LogDir = join_abs_dirs(NetDir, proplists:get_value(logdir, Opts)),
case lists:keysearch(master, 1, Config) of
false->
test_server:format("See Common Test logs here:\n\n"
"<a href=\"file://~ts/all_runs.html\">~ts/all_runs.html</a>\n"
"<a href=\"file://~ts/index.html\">~ts/index.html</a>",
[LogDir,LogDir,LogDir,LogDir]);
{value, _}->
test_server:format("See CT Master Test logs here:\n\n"
"<a href=\"file://~ts/master_runs.html\">~ts/master_runs.html</a>",
[LogDir,LogDir])
end,
Config.
%%%-----------------------------------------------------------------
%%% end_per_testcase/2
end_per_testcase(_TestCase, Config) ->
CTNode = proplists:get_value(ct_node, Config),
case wait_for_ct_stop(CTNode) of
%% Common test was not stopped to we restart node.
false ->
slave_stop(CTNode),
start_slave(Config,proplists:get_value(trace_level,Config)),
{fail, "Could not stop common_test"};
true ->
ok
end.
%%%-----------------------------------------------------------------
%%%
write_testspec(TestSpec, Dir, Name) ->
write_testspec(TestSpec, filename:join(Dir, Name)).
write_testspec(TestSpec, TSFile) ->
{ok,Dev} = file:open(TSFile, [write,{encoding,utf8}]),
[io:format(Dev, "~tp.~n", [Entry]) || Entry <- TestSpec],
file:close(Dev),
io:format("Test specification written to: ~tp~n", [TSFile]),
io:format(user, "Test specification written to: ~tp~n", [TSFile]),
TSFile.
%%%-----------------------------------------------------------------
%%%
get_opts(Config) ->
PrivDir = proplists:get_value(priv_dir, Config),
TempDir = case os:getenv("TMP") of
false ->
case os:getenv("TEMP") of
false ->
undefined;
Tmp ->
create_tmp_logdir(Tmp)
end;
Tmp ->
create_tmp_logdir(Tmp)
end,
LogDir =
case os:getenv("CT_USE_TMP_DIR") of
false -> PrivDir;
_ -> TempDir
end,
%% Copy test variables to app environment on new node
CtTestVars =
case init:get_argument(ct_test_vars) of
{ok,[Vars]} ->
[begin {ok,Ts,_} = erl_scan:string(Str++"."),
{ok,Expr} = erl_parse:parse_term(Ts),
Expr
end || Str <- Vars];
_ ->
[]
end,
test_server : format("Test variables added to Config : ~p\n\n " ,
%% [CtTestVars]),
InitOpts =
case proplists:get_value(ct_opts, Config) of
undefined -> [];
CtOpts -> CtOpts
end,
[{logdir,LogDir} | InitOpts ++ CtTestVars].
%%%-----------------------------------------------------------------
%%%
run(Opts0, Config) when is_list(Opts0) ->
Opts =
%% read (and override) opts from env variable, the form expected:
%% "[{some_key1,SomeVal2}, {some_key2,SomeVal2}]"
case os:getenv("CT_TEST_OPTS") of
false -> Opts0;
"" -> Opts0;
Terms ->
case erl_scan:string(Terms++".", 0) of
{ok,Tokens,_} ->
case erl_parse:parse_term(Tokens) of
{ok,OROpts} ->
Override =
fun(O={Key,_}, Os) ->
io:format(user, "ADDING START "
"OPTION: ~tp~n", [O]),
[O | lists:keydelete(Key, 1, Os)]
end,
lists:foldl(Override, Opts0, OROpts);
_ ->
Opts0
end;
_ ->
Opts0
end
end,
%% use ct interface
CtRunTestResult=run_ct_run_test(Opts,Config),
%% use run_test interface (simulated)
ExitStatus=run_ct_script_start(Opts,Config),
check_result(CtRunTestResult,ExitStatus,Opts).
run_ct_run_test(Opts,Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
test_server:format(Level, "~n[RUN #1] Calling ct:run_test(~tp) on ~p~n",
[Opts, CTNode]),
T0 = erlang:monotonic_time(),
CtRunTestResult = rpc:call(CTNode, ct, run_test, [Opts]),
T1 = erlang:monotonic_time(),
Elapsed = erlang:convert_time_unit(T1-T0, native, milli_seconds),
test_server:format(Level, "~n[RUN #1] Got return value ~tp after ~p ms~n",
[CtRunTestResult,Elapsed]),
case rpc:call(CTNode, erlang, whereis, [ct_util_server]) of
undefined ->
ok;
_ ->
test_server:format(Level,
"ct_util_server not stopped on ~p yet, waiting 5 s...~n",
[CTNode]),
timer:sleep(5000),
undefined = rpc:call(CTNode, erlang, whereis, [ct_util_server])
end,
CtRunTestResult.
run_ct_script_start(Opts, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
Opts1 = [{halt_with,{?MODULE,ct_test_halt}} | Opts],
test_server:format(Level, "Saving start opts on ~p: ~tp~n",
[CTNode, Opts1]),
rpc:call(CTNode, application, set_env,
[common_test, run_test_start_opts, Opts1]),
test_server:format(Level, "[RUN #2] Calling ct_run:script_start() on ~p~n",
[CTNode]),
T0 = erlang:monotonic_time(),
ExitStatus = rpc:call(CTNode, ct_run, script_start, []),
T1 = erlang:monotonic_time(),
Elapsed = erlang:convert_time_unit(T1-T0, native, milli_seconds),
test_server:format(Level, "[RUN #2] Got exit status value ~tp after ~p ms~n",
[ExitStatus,Elapsed]),
ExitStatus.
check_result({_Ok,Failed,{_UserSkipped,_AutoSkipped}},1,_Opts)
when Failed > 0 ->
ok;
check_result({_Ok,0,{_UserSkipped,AutoSkipped}},ExitStatus,Opts)
when AutoSkipped > 0 ->
case proplists:get_value(exit_status, Opts) of
ignore_config when ExitStatus == 1 ->
{error,{wrong_exit_status,ExitStatus}};
_ ->
ok
end;
check_result({error,_}=Error,2,_Opts) ->
Error;
check_result({error,_},ExitStatus,_Opts) ->
{error,{wrong_exit_status,ExitStatus}};
check_result({_Ok,0,{_UserSkipped,_AutoSkipped}},0,_Opts) ->
ok;
check_result(CtRunTestResult,ExitStatus,Opts)
when is_list(CtRunTestResult) -> % repeated testruns
try check_result(sum_testruns(CtRunTestResult,0,0,0,0),ExitStatus,Opts)
catch _:_ ->
{error,{unexpected_return_value,{CtRunTestResult,ExitStatus}}}
end;
check_result(done,0,_Opts) ->
%% refresh_logs return
ok;
check_result(CtRunTestResult,ExitStatus,_Opts) ->
{error,{unexpected_return_value,{CtRunTestResult,ExitStatus}}}.
sum_testruns([{O,F,{US,AS}}|T],Ok,Failed,UserSkipped,AutoSkipped) ->
sum_testruns(T,Ok+O,Failed+F,UserSkipped+US,AutoSkipped+AS);
sum_testruns([],Ok,Failed,UserSkipped,AutoSkipped) ->
{Ok,Failed,{UserSkipped,AutoSkipped}}.
run(M, F, A, Config) ->
run({M,F,A}, [], Config).
run({M,F,A}, InitCalls, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
lists:foreach(
fun({IM,IF,IA}) ->
test_server:format(Level, "~nInit call ~w:~tw(~tp) on ~p...~n",
[IM, IF, IA, CTNode]),
Result = rpc:call(CTNode, IM, IF, IA),
test_server:format(Level, "~n...with result: ~tp~n", [Result])
end, InitCalls),
test_server:format(Level, "~nStarting test with ~w:~tw(~tp) on ~p~n",
[M, F, A, CTNode]),
rpc:call(CTNode, M, F, A).
%% this is the last function that ct_run:script_start() calls, so the
%% return value here is what rpc:call/4 above returns
ct_test_halt(ExitStatus) ->
ExitStatus.
%%%-----------------------------------------------------------------
wait_for_ct_stop/1
wait_for_ct_stop(CTNode) ->
Give CT at least 15 sec to stop ( in case of bad make ) .
wait_for_ct_stop(5, CTNode).
wait_for_ct_stop(0, CTNode) ->
test_server:format(0, "Giving up! Stopping ~p.", [CTNode]),
false;
wait_for_ct_stop(Retries, CTNode) ->
case rpc:call(CTNode, erlang, whereis, [ct_util_server]) of
undefined ->
true;
Pid ->
Info = (catch process_info(Pid)),
test_server:format(0, "Waiting for CT (~p) to finish (~p)...",
[Pid,Retries]),
test_server:format(0, "Process info for ~p:~n~tp", [Pid,Info]),
timer:sleep(5000),
wait_for_ct_stop(Retries-1, CTNode)
end.
%%%-----------------------------------------------------------------
%%% ct_rpc/1
ct_rpc({M,F,A}, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
test_server:format(Level, "~nCalling ~w:~tw(~tp) on ~p...",
[M,F,A, CTNode]),
rpc:call(CTNode, M, F, A).
%%%-----------------------------------------------------------------
%%% random_error/1
random_error(Config) when is_list(Config) ->
rand:seed(exsplus),
Gen = fun(0,_) -> ok; (N,Fun) -> Fun(N-1, Fun) end,
Gen(rand:uniform(100), Gen),
ErrorTypes = ['BADMATCH','BADARG','CASE_CLAUSE','FUNCTION_CLAUSE',
'EXIT','THROW','UNDEF'],
Type = lists:nth(rand:uniform(length(ErrorTypes)), ErrorTypes),
Where = case rand:uniform(2) of
1 ->
io:format("ct_test_support *returning* error of type ~w",
[Type]),
tc;
2 ->
io:format("ct_test_support *generating* error of type ~w",
[Type]),
lib
end,
ErrorFun =
fun() ->
case Type of
'BADMATCH' ->
ok = proplists:get_value(undefined, Config);
'BADARG' ->
size(proplists:get_value(priv_dir, Config));
'FUNCTION_CLAUSE' ->
random_error(x);
'EXIT' ->
spawn_link(fun() ->
undef_proc ! hello,
ok
end);
'THROW' ->
PrivDir = proplists:get_value(priv_dir, Config),
if is_list(PrivDir) -> throw(generated_throw) end;
'UNDEF' ->
apply(?MODULE, random_error, [])
end
end,
%% either call the fun here or return it to the caller (to be
%% executed in a test case instead)
case Where of
tc -> ErrorFun;
lib -> ErrorFun()
end.
%%%-----------------------------------------------------------------
%%% EVENT HANDLING
handle_event(EH, Event) ->
event_receiver ! {self(),{event,EH,Event}},
receive {event_receiver,ok} -> ok end,
ok.
start_event_receiver(Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
ER = spawn_link(CTNode, fun() -> er() end),
test_server:format(Level, "~nEvent receiver ~w started!~n", [ER]),
ER.
get_events(_, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
{event_receiver,CTNode} ! {self(),get_events},
Events = receive {event_receiver,Evs} -> Evs end,
test_server:format(Level, "Stopping event receiver!~n", []),
{event_receiver,CTNode} ! {self(),stop},
receive {event_receiver,stopped} -> ok end,
Events.
er() ->
register(event_receiver, self()),
er_loop([]).
er_loop(Evs) ->
receive
{From,{event,EH,Ev}} ->
From ! {event_receiver,ok},
er_loop([{EH,Ev} | Evs]);
{From,get_events} ->
From ! {event_receiver,lists:reverse(Evs)},
er_loop(Evs);
{From,stop} ->
unregister(event_receiver),
From ! {event_receiver,stopped},
ok
end.
verify_events(TEvs, Evs, Config) ->
Node = proplists:get_value(ct_node, Config),
case catch verify_events1(TEvs, Evs, Node, Config) of
{'EXIT',Reason} ->
Reason;
_ ->
ok
end.
verify_events(TEvs, Evs, Node, Config) ->
case catch verify_events1(TEvs, Evs, Node, Config) of
{'EXIT',Reason} ->
Reason;
_ ->
ok
end.
verify_events1([TestEv|_], [{TEH,#event{name=stop_logging,node=Node,data=_}}|_], Node, _)
when element(1,TestEv) == TEH, element(2,TestEv) =/= stop_logging ->
test_server:format("Failed to find ~tp in the list of events!~n", [TestEv]),
exit({event_not_found,TestEv});
verify_events1(TEvs = [TestEv | TestEvs], Evs = [_|Events], Node, Config) ->
case catch locate(TestEv, Node, Evs, Config) of
nomatch ->
verify_events1(TEvs, Events, Node, Config);
{'EXIT',Reason} ->
test_server:format("Failed to find ~tp in ~tp~n"
"Reason: ~tp~n", [TestEv,Evs,Reason]),
exit(Reason);
{Config1,Events1} ->
if is_list(TestEv) ->
ok;
element(1,TestEv) == parallel ; element(1,TestEv) == shuffle ->
ok;
true ->
test_server:format("Found ~tp!", [TestEv])
end,
verify_events1(TestEvs, Events1, Node, Config1)
end;
verify_events1([TestEv|_], [], _, _) ->
test_server:format("Failed to find ~tp in the list of events!~n", [TestEv]),
exit({event_not_found,TestEv});
verify_events1([], Evs, _, Config) ->
{Config,Evs}.
%%%----------------------------------------------------------------------------
locate({TEHandler , TEName , TEData } , TENode , Events , Config ) - > { Config1,Evs1 }
%%%
%%% A group is represented as either:
%%% {parallel,ListOfCasesAndGroups},
%%% {shuffle,ListOfCasesAndGroups}, or
%%% ListOfCasesAndGroups.
%%%
The two first and two last events in a group * may * be tc_start and tc_done
%%% for init_per_group and end_per_group.
%% group (not parallel or shuffle)
locate(TEvs, Node, Evs, Config) when is_list(TEvs) ->
case TEvs of
[InitStart = {TEH,tc_start,{M,{init_per_group,GroupName,Props}}},
InitDone = {TEH,tc_done,{M,{init_per_group,GroupName,Props},R}} | TEvs1] ->
case Evs of
[{TEH,#event{name=tc_start,
node=Node,
data={M,{init_per_group,GroupName,Props}}}},
{TEH,#event{name=tc_done,
node=Node,
data={M,{init_per_group,GroupName,Props},Res}}} | Evs1] ->
case result_match(R, Res) of
false ->
nomatch;
true ->
test_server:format("Found ~tp!", [InitStart]),
test_server:format("Found ~tp!", [InitDone]),
verify_events1(TEvs1, Evs1, Node, Config)
end;
_ ->
nomatch
end;
_ ->
verify_events1(TEvs, Evs, Node, Config)
end;
Parallel events : Each test case in the group should be specified in a list
%% with the tc_start, followed by the tc_done event. The order of the cases
%% is irrelevant, but it must be checked that every test case exists and
%% that tc_done comes after tc_start.
locate({parallel,TEvs}, Node, Evs, Config) ->
Start =
case TEvs of
[InitStart = {TEH,tc_start,{M,{init_per_group,GroupName,Props}}},
InitDone = {TEH,tc_done,{M,{init_per_group,GroupName,Props},R}} | TEs] ->
case Evs of
[{TEH,#event{name=tc_start,
node=Node,
data={M,{init_per_group,
GroupName,Props}}}}|Es] ->
%% Use dropwhile here as a tc_done from a
%% previous testcase might sneak in here
EvsG = lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={EvM,{init_per_group,
EvGroupName,
EvProps},EvR}}})
when TEH == EH, EvNode == Node, EvM == M,
EvGroupName == GroupName,
EvProps == Props ->
case result_match(R, EvR) of
true -> false;
false -> true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}})
when EH == TEH, EvNode == Node ->
exit({group_init_done_not_found,
GroupName,Props});
(_) ->
true
end, Es),
test_server:format("Found ~tp!", [InitStart]),
test_server:format("Found ~tp!", [InitDone]),
{TEs,EvsG};
_ ->
nomatch
end;
_ ->
{TEvs,Evs}
end,
case Start of
nomatch ->
nomatch;
{TEvs1,Evs1} ->
{TcDoneEvs,RemainEvs,_} =
lists:foldl(
%% tc_start event for a parallel test case
fun(TEv={TEH,tc_start,{M,F}}, {Done,RemEvs,RemSize}) ->
%% drop events until TEv is found
Evs2 = lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,Func}}}) when
EH == TEH, EvNode == Node,
Mod == M, Func == F ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, Evs1),
%% split the list at the tc_done event and record the smallest
%% list of remaining events (Evs) as possible
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={Mod,Func,_}}}) when
EH == TEH, EvNode == Node,
Mod == M, Func == F ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_done_not_found,TEv});
(_) ->
true
end, Evs2),
case RemEvs1 of
[] when Evs2 == [] ->
exit({unmatched,TEv});
[] ->
test_server:format("Found ~tp!", [TEv]),
exit({tc_done_not_found,TEv});
[TcDone|Evs3] ->
test_server:format("Found ~tp!", [TEv]),
RemSize1 = length(Evs3),
if RemSize1 < RemSize ->
{[TcDone|Done],Evs3,RemSize1};
true ->
{[TcDone|Done],RemEvs,RemSize}
end
end;
%% tc_done event for a parallel test case
(TEv={TEH,tc_done,{M,F,R}}, {Done,RemEvs,RemSize}) ->
case [E || E={EH,#event{name=tc_done,
node=EvNode,
data={Mod,Func,Result}}} <- Done,
EH == TEH, EvNode == Node, Mod == M,
Func == F, result_match(R, Result)] of
[TcDone|_] ->
test_server:format("Found ~tp!", [TEv]),
{lists:delete(TcDone, Done),RemEvs,RemSize};
[] ->
exit({unmatched,TEv})
end;
%% tc_start event for end_per_group
(TEv={TEH,tc_start,{M,{end_per_group,GroupName,Props}}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,{end_per_group,
EvGName,EvProps}}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName, EvProps == Props ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_ | RemEvs2] ->
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
%% tc_done event for end_per_group
(TEv={TEH,tc_done,{M,{end_per_group,GroupName,Props},R}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={Mod,{end_per_group,
EvGName,EvProps},Res}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName, EvProps == Props ->
case result_match(R, Res) of
true ->
false;
false ->
true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_done_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_ | RemEvs2] ->
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
%% end_per_group auto- or user skipped
(TEv={TEH,AutoOrUserSkip,{M,{end_per_group,G},R}}, {Done,RemEvs,_RemSize})
when AutoOrUserSkip == tc_auto_skip;
AutoOrUserSkip == tc_user_skip ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_auto_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G ->
case match_data(R, Reason) of
match -> false;
_ -> true
end;
({EH,#event{name=tc_user_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G ->
case match_data(R, Reason) of
match -> false;
_ -> true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_auto_or_user_skip_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_AutoSkip | RemEvs2] ->
{Done,RemEvs2,length(RemEvs2)}
end;
(TEv={TEH,N,D}, Acc) ->
case [E || E={EH,#event{name=Name,
node=EvNode,
data=Data}} <- Evs1,
EH == TEH, EvNode == Node, Name == N,
match == match_data(D,Data)] of
[] ->
exit({unmatched,TEv});
_ ->
test_server:format("Found ~tp!", [TEv]),
Acc
end;
%% start of a sub-group
(SubGroupTEvs, Acc) when is_list(SubGroupTEvs) ->
verify_events1(SubGroupTEvs, Evs1, Node, Config),
Acc;
(TEv={Prop,_SubGroupTEvs}, Acc) when
Prop == shuffle ; Prop == parallel ->
verify_events1([TEv], Evs1, Node, Config),
Acc
end, {[],Evs1,length(Evs1)}, TEvs1),
case TcDoneEvs of
[] ->
test_server:format("Found all parallel events!", []),
{Config,RemainEvs};
_ ->
exit({unexpected_events,TcDoneEvs})
end
end;
%% Shuffled events: Each test case in the group should be specified in a list
%% with the tc_start, followed by the tc_done event. The order of the cases
%% is irrelevant, but it must be checked that every test case exists and
%% that the tc_done event follows the tc_start.
locate({shuffle,TEvs}, Node, Evs, Config) ->
Start =
case TEvs of
[InitStart = {TEH,tc_start,{M,{init_per_group,GroupName,Props}}},
InitDone = {TEH,tc_done,{M,{init_per_group,GroupName,Props},R}} | TEs] ->
case Evs of
[{TEH,#event{name=tc_start,
node=Node,
data={M,{init_per_group,GroupName,EvProps}}}},
{TEH,#event{name=tc_done,
node=Node,
data={M,{init_per_group,GroupName,EvProps},Res}}} | Es] ->
case result_match(R, Res) of
true ->
case proplists:get_value(shuffle, Props) of
'_' ->
case proplists:get_value(shuffle, EvProps) of
false ->
exit({no_shuffle_prop_found,
{M,init_per_group,
GroupName,EvProps}});
_ ->
PropsCmp = proplists:delete(shuffle, EvProps),
PropsCmp = proplists:delete(shuffle, Props)
end;
_ ->
Props = EvProps
end,
test_server:format("Found ~tp!", [InitStart]),
test_server:format("Found ~tp!", [InitDone]),
{TEs,Es};
false ->
nomatch
end;
_ ->
nomatch
end;
_ ->
{TEvs,Evs}
end,
case Start of
nomatch ->
nomatch;
{TEvs1,Evs1} ->
{TcDoneEvs,RemainEvs,_} =
lists:foldl(
%% tc_start event for a test case
fun(TEv={TEH,tc_start,{M,F}}, {Done,RemEvs,RemSize}) ->
%% drop events until TEv is found
Evs2 = lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,Func}}}) when
EH == TEH, EvNode == Node,
Mod == M, Func == F ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, Evs1),
%% verify the tc_done event comes next in Evs
case Evs2 of
[] ->
exit({unmatched,TEv});
[_TcStart, TcDone={TEH,#event{name=tc_done,
node=Node,
data={M,F,_}}} | Evs3] ->
test_server:format("Found ~tp!", [TEv]),
RemSize1 = length(Evs3),
if RemSize1 < RemSize ->
{[TcDone|Done],Evs3,RemSize1};
true ->
{[TcDone|Done],RemEvs,RemSize}
end
end;
%% tc_done event for a test case
(TEv={TEH,tc_done,{M,F,R}}, {Done,RemEvs,RemSize}) ->
case [E || E={EH,#event{name=tc_done,
node=EvNode,
data={Mod,Func,Result}}} <- Done,
EH == TEH, EvNode == Node, Mod == M,
Func == F, result_match(R, Result)] of
[TcDone|_] ->
test_server:format("Found ~tp!", [TEv]),
{lists:delete(TcDone, Done),RemEvs,RemSize};
[] ->
exit({unmatched,TEv})
end;
%% tc_start event for end_per_group
(TEv={TEH,tc_start,{M,{end_per_group,GroupName,Props}}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,{end_per_group,
EvGName,_}}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[{_,#event{data={_,{_,_,EvProps1}}}} | RemEvs2] ->
case proplists:get_value(shuffle, Props) of
'_' ->
case proplists:get_value(shuffle, EvProps1) of
false ->
exit({no_shuffle_prop_found,
{M,end_per_group,GroupName,EvProps1}});
_ ->
PropsCmp1 = proplists:delete(shuffle, EvProps1),
PropsCmp1 = proplists:delete(shuffle, Props)
end;
_ ->
Props = EvProps1
end,
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
%% tc_done event for end_per_group
(TEv={TEH,tc_done,{M,{end_per_group,GroupName,Props},R}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={Mod,{end_per_group,
EvGName,_},Res}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName ->
case result_match(R, Res) of
true ->
false;
false ->
true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_done_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[{_,#event{data={_,{_,_,EvProps1},_}}} | RemEvs2] ->
case proplists:get_value(shuffle, Props) of
'_' ->
case proplists:get_value(shuffle, EvProps1) of
false ->
exit({no_shuffle_prop_found,
{M,end_per_group,GroupName,EvProps1}});
_ ->
PropsCmp1 = proplists:delete(shuffle, EvProps1),
PropsCmp1 = proplists:delete(shuffle, Props)
end;
_ ->
Props = EvProps1
end,
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
%% end_per_group auto-or user skipped
(TEv={TEH,AutoOrUserSkip,{M,{end_per_group,G},R}}, {Done,RemEvs,_RemSize})
when AutoOrUserSkip == tc_auto_skip;
AutoOrUserSkip == tc_user_skip ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_auto_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G, Reason == R ->
false;
({EH,#event{name=tc_user_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G, Reason == R ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_auto_skip_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_AutoSkip | RemEvs2] ->
{Done,RemEvs2,length(RemEvs2)}
end;
%% match other event than test case
(TEv={TEH,N,D}, Acc) when D == '_' ->
case [E || E={EH,#event{name=Name,
node=EvNode,
data=_}} <- Evs1,
EH == TEH, EvNode == Node, Name == N] of
[] ->
exit({unmatched,TEv});
_ ->
test_server:format("Found ~tp!", [TEv]),
Acc
end;
(TEv={TEH,N,D}, Acc) ->
case [E || E={EH,#event{name=Name,
node=EvNode,
data=Data}} <- Evs1,
EH == TEH, EvNode == Node, Name == N, Data == D] of
[] ->
exit({unmatched,TEv});
_ ->
test_server:format("Found ~tp!", [TEv]),
Acc
end;
%% start of a sub-group
(SubGroupTEvs, Acc) when is_list(SubGroupTEvs) ->
verify_events1(SubGroupTEvs, Evs1, Node, Config),
Acc;
(TEv={Prop,_SubGroupTEvs}, Acc) when
Prop == shuffle ; Prop == parallel ->
verify_events1([TEv], Evs1, Node, Config),
Acc
end, {[],Evs1,length(Evs1)}, TEvs1),
case TcDoneEvs of
[] ->
test_server:format("Found all shuffled events!", []),
{Config,RemainEvs};
_ ->
exit({unexpected_events,TcDoneEvs})
end
end;
locate({TEH,Name,{'DEF','RUNDIR'}}, Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=Name, node=Node, data=EvData}} ->
{_,{_,LogDir}} = lists:keysearch(logdir, 1, get_opts(Config)),
D = filename:join(LogDir, "ct_run." ++ atom_to_list(Node)),
case string:find(EvData, D) of
nomatch -> exit({badmatch,EvData});
_ -> ok
end,
{Config,Evs};
_ ->
nomatch
end;
locate({TEH,Name,{'DEF',{'START_TIME','LOGDIR'}}}, Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=Name, node=Node, data=EvData}} ->
case EvData of
{DT={{_,_,_},{_,_,_}},Dir} when is_list(Dir) ->
{_,{_,LogDir}} = lists:keysearch(logdir, 1, get_opts(Config)),
D = filename:join(LogDir, "ct_run." ++ atom_to_list(Node)),
case string:find(Dir, D) of
nomatch -> exit({badmatch,Dir});
_ -> ok
end,
{[{start_time,DT}|Config],Evs};
Data ->
exit({badmatch,Data})
end;
_ ->
nomatch
end;
locate({TEH,Name,{'DEF','STOP_TIME'}}, Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=Name, node=Node, data=EvData}} ->
case EvData of
DT={{_,_,_},{_,_,_}} ->
{[{stop_time,DT}|Config],Evs};
Data ->
exit({badmatch,Data})
end;
_ ->
nomatch
end;
%% to match variable data as a result of an aborted test case
locate({TEH,tc_done,{undefined,undefined,{testcase_aborted,
{abort_current_testcase,Func},'_'}}},
Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=tc_done, node=Node,
data={undefined,undefined,
{testcase_aborted,{abort_current_testcase,Func},_}}}} ->
{Config,Evs};
_ ->
nomatch
end;
%% to match variable data as a result of a failed test case
locate({TEH,tc_done,{Mod,Func,R={SkipOrFail,{_ErrInd,ErrInfo}}}},
Node, [Ev|Evs], Config) when ((SkipOrFail == skipped) or
(SkipOrFail == failed)) and
((size(ErrInfo) == 2) or
(size(ErrInfo) == 3)) ->
case Ev of
{TEH,#event{name=tc_done, node=Node,
data={Mod,Func,Result}}} ->
case result_match(R, Result) of
true ->
{Config,Evs};
false ->
nomatch
end;
_ ->
nomatch
end;
Negative matching : Given two events , the first should not be present before
%% the other is matched.
locate({negative,NotMatch, Match} = Neg, Node, Evs, Config) ->
case locate(NotMatch, Node, Evs, Config) of
nomatch ->
locate(Match, Node, Evs, Config);
_ ->
exit({found_negative_event,Neg})
end;
%% matches any event of type Name
locate({TEH,Name,Data}, Node, [{TEH,#event{name=Name,
data = EvData,
node = Node}}|Evs],
Config) ->
case match_data(Data, EvData) of
match ->
{Config,Evs};
_ ->
nomatch
end;
locate({_TEH,_Name,_Data}, _Node, [_|_Evs], _Config) ->
nomatch.
match_data(Data, EvData) ->
try do_match_data(Data, EvData)
catch _:_ ->
nomatch
end.
do_match_data(D,D) ->
match;
do_match_data('_',_) ->
match;
do_match_data(Fun,Data) when is_function(Fun) ->
Fun(Data);
do_match_data('$proplist',Proplist) ->
do_match_data(
fun(List) ->
lists:foreach(fun({_,_}) -> ok end,List)
end,Proplist);
do_match_data([H1|MatchT],[H2|ValT]) ->
do_match_data(H1,H2),
do_match_data(MatchT,ValT);
do_match_data(Tuple1,Tuple2) when is_tuple(Tuple1),is_tuple(Tuple2) ->
do_match_data(tuple_to_list(Tuple1),tuple_to_list(Tuple2));
do_match_data([],[]) ->
match.
result_match({SkipOrFail,{ErrorInd,{Why,'_'}}},
{SkipOrFail,{ErrorInd,{Why,_Stack}}}) ->
true;
result_match({SkipOrFail,{ErrorInd,{EMod,EFunc,{Why,'_'}}}},
{SkipOrFail,{ErrorInd,{EMod,EFunc,{Why,_Stack}}}}) ->
true;
result_match({failed,{timetrap_timeout,{'$approx',Num}}},
{failed,{timetrap_timeout,Value}}) ->
if Value >= trunc(Num-0.05*Num),
Value =< trunc(Num+0.05*Num) -> true;
true -> false
end;
result_match({user_timetrap_error,{Why,'_'}},
{user_timetrap_error,{Why,_Stack}}) ->
true;
result_match({SkipOrFail,{ErrorInd,{thrown,{Why,'_'}}}},
{SkipOrFail,{ErrorInd,{thrown,{Why,_Stack}}}}) ->
true;
result_match(Result, Result) ->
true;
result_match(_, _) ->
false.
log_events(TC, Events, EvLogDir, Opts) ->
LogFile = filename:join(EvLogDir, atom_to_list(TC)++".events"),
{ok,Dev} = file:open(LogFile, [write,{encoding,utf8}]),
io:format(Dev, "[~n", []),
log_events1(Events, Dev, " "),
file:close(Dev),
FullLogFile = join_abs_dirs(proplists:get_value(net_dir, Opts),
LogFile),
ct:log("Events written to logfile: <a href=\"file://~ts\">~ts</a>~n",
[FullLogFile,FullLogFile],[no_css]),
io:format(user, "Events written to logfile: ~tp~n", [LogFile]).
log_events1(Evs, Dev, "") ->
log_events1(Evs, Dev, " ");
log_events1([E={_EH,tc_start,{_M,{init_per_group,_GrName,Props}}} | Evs], Dev, Ind) ->
case get_prop(Props) of
undefined ->
io:format(Dev, "~s[~tp,~n", [Ind,E]),
log_events1(Evs, Dev, Ind++" ");
Prop ->
io:format(Dev, "~s{~w,~n~s[~tp,~n", [Ind,Prop,Ind++" ",E]),
log_events1(Evs, Dev, Ind++" ")
end;
log_events1([E={_EH,tc_done,{_M,{init_per_group,_GrName,_Props},_R}} | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp,~n", [Ind,E]),
log_events1(Evs, Dev, Ind++" ");
log_events1([E={_EH,tc_start,{_M,{end_per_group,_GrName,_Props}}} | Evs], Dev, Ind) ->
Ind1 = Ind -- " ",
io:format(Dev, "~s~tp,~n", [Ind1,E]),
log_events1(Evs, Dev, Ind1);
log_events1([E={_EH,tc_done,{_M,{end_per_group,_GrName,Props},_R}} | Evs], Dev, Ind) ->
case get_prop(Props) of
undefined ->
io:format(Dev, "~s~tp],~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ");
_Prop ->
io:format(Dev, "~s~tp]},~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ")
end;
log_events1([E={_EH,tc_auto_skip,{_M,{end_per_group,_GrName},_Reason}} | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp],~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ");
log_events1([E={_EH,tc_user_skip,{_M,{end_per_group,_GrName},_Reason}} | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp],~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ");
log_events1([E], Dev, Ind) ->
io:format(Dev, "~s~tp~n].~n", [Ind,E]),
ok;
log_events1([E | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp,~n", [Ind,E]),
log_events1(Evs, Dev, Ind);
log_events1([], _Dev, _Ind) ->
ok.
get_prop(Props) ->
case lists:member(parallel, Props) of
true -> parallel;
false -> case lists:member(shuffle, Props) of
true -> shuffle;
false -> case lists:keysearch(shuffle, 1, Props) of
{value,_} -> shuffle;
_ -> undefined
end
end
end.
reformat([{_EH,#event{name=start_write_file,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=finished_write_file,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=start_make,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=finished_make,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=start_logging,data=_}} | Events], EH) ->
[{EH,start_logging,{'DEF','RUNDIR'}} | reformat(Events, EH)];
reformat([{_EH,#event{name=test_start,data=_}} | Events], EH) ->
[{EH,test_start,{'DEF',{'START_TIME','LOGDIR'}}} | reformat(Events, EH)];
reformat([{_EH,#event{name=test_done,data=_}} | Events], EH) ->
[{EH,test_done,{'DEF','STOP_TIME'}} | reformat(Events, EH)];
reformat([{_EH,#event{name=tc_logfile,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=test_stats,data=Data}} | Events], EH) ->
[{EH,test_stats,Data} | reformat(Events, EH)];
%% use this to only print the last test_stats event:
%% case [N || {_,#event{name=N}} <- Events, N == test_stats] of
%% [] -> % last stats event
[ { EH , test_stats , Data } | reformat(Events , ) ] ;
%% _ ->
%% reformat(Events, EH)
%% end;
reformat([{_EH,#event{name=Name,data=Data}} | Events], EH) ->
[{EH,Name,Data} | reformat(Events, EH)];
reformat([], _EH) ->
[].
%%%-----------------------------------------------------------------
%%% MISC HELP FUNCTIONS
join_abs_dirs(undefined, Dir2) ->
Dir2;
join_abs_dirs(Dir1, Dir2) ->
case filename:pathtype(Dir2) of
relative ->
filename:join(Dir1, Dir2);
_ ->
[_Abs|Parts] = filename:split(Dir2),
filename:join(Dir1, filename:join(Parts))
end.
create_tmp_logdir(Tmp) ->
LogDir = filename:join(Tmp,"ct"),
file:make_dir(LogDir),
LogDir.
delete_old_logs({win32,_}, Config) ->
case {proplists:get_value(priv_dir, Config),
proplists:get_value(logdir, get_opts(Config))} of
{LogDir,LogDir} ->
ignore;
{_,LogDir} -> % using tmp for logs
catch delete_dirs(LogDir)
end;
delete_old_logs(_, Config) ->
case os:getenv("CT_USE_TMP_DIR") of
false ->
ignore;
_ ->
catch delete_dirs(proplists:get_value(logdir,
get_opts(Config)))
end.
delete_dirs(LogDir) ->
Now = calendar:datetime_to_gregorian_seconds(calendar:local_time()),
SaveTime = list_to_integer(os:getenv("CT_SAVE_OLD_LOGS", "28800")),
Deadline = Now - SaveTime,
Dirs = filelib:wildcard(filename:join(LogDir,"ct_run*")),
Dirs2Del =
lists:foldl(fun(Dir, Del) ->
[S,Mi,H,D,Mo,Y|_] =
lists:reverse(string:lexemes(Dir, [$.,$-,$_])),
S2I = fun(Str) -> list_to_integer(Str) end,
DT = {{S2I(Y),S2I(Mo),S2I(D)}, {S2I(H),S2I(Mi),S2I(S)}},
Then = calendar:datetime_to_gregorian_seconds(DT),
if Then > Deadline ->
Del;
true ->
[Dir | Del]
end
end, [], Dirs),
case length(Dirs2Del) of
0 ->
test_server:format(0, "No log directories older than ~w secs.", [SaveTime]);
N ->
test_server:format(0, "Deleting ~w directories older than ~w secs.", [N,SaveTime])
end,
delete_dirs(LogDir, Dirs2Del).
delete_dirs(_, []) ->
ok;
delete_dirs(LogDir, [Dir | Dirs]) ->
test_server:format(0, "Removing old log directory: ~ts", [Dir]),
case catch rm_rec(Dir) of
{_,Reason} ->
test_server:format(0, "Delete failed! (~tp)", [Reason]);
ok ->
ok
end,
delete_dirs(LogDir, Dirs).
rm_rec(Dir) ->
%% ensure we're removing the ct_run directory
case lists:reverse(filename:split(Dir)) of
[[$c,$t,$_,$r,$u,$n,$.|_]|_] ->
rm_dir(filename:absname(Dir));
_ ->
{error,{invalid_logdir,Dir}}
end.
rm_dir(Dir) ->
case file:list_dir(Dir) of
{error,Errno} ->
exit({ls_failed,Dir,Errno});
{ok,Files} ->
rm_files([filename:join(Dir, F) || F <- Files]),
file:del_dir(Dir)
end.
rm_files([F | Fs]) ->
Base = filename:basename(F),
if Base == "." ; Base == ".." ->
rm_files(Fs);
true ->
case file:read_file_info(F) of
{ok,#file_info{type=directory}} ->
rm_dir(F),
rm_files(Fs);
{ok,_Regular} ->
case file:delete(F) of
ok ->
rm_files(Fs);
{error,Errno} ->
exit({del_failed,F,Errno})
end
end
end;
rm_files([]) ->
ok.
unique_timestamp() ->
unique_timestamp(os:timestamp(), 100000).
unique_timestamp(TS, 0) ->
TS;
unique_timestamp(TS0, N) ->
case os:timestamp() of
TS0 ->
timer:sleep(1),
unique_timestamp(TS0, N-1);
TS1 ->
TS1
end.
%%%-----------------------------------------------------------------
%%%
slave_stop(Node) ->
Cover = test_server:is_cover(),
if Cover-> cover:flush(Node);
true -> ok
end,
erlang:monitor_node(Node, true),
slave:stop(Node),
receive
{nodedown, Node} ->
if Cover -> cover:stop(Node);
true -> ok
end
after 5000 ->
erlang:monitor_node(Node, false),
receive {nodedown, Node} -> ok after 0 -> ok end %flush
end,
ok.
| null | https://raw.githubusercontent.com/erlang/otp/82d134f1b4132209337a5c58d3b8115816b725d0/lib/common_test/test/ct_test_support.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
Test support functions
-----------------------------------------------------------------
init_per_suite/1
can take a long time there
have to be in code path on Common Test node.
-----------------------------------------------------------------
end_per_suite/1
-----------------------------------------------------------------
init_per_testcase/2
-----------------------------------------------------------------
end_per_testcase/2
Common test was not stopped to we restart node.
-----------------------------------------------------------------
-----------------------------------------------------------------
Copy test variables to app environment on new node
[CtTestVars]),
-----------------------------------------------------------------
read (and override) opts from env variable, the form expected:
"[{some_key1,SomeVal2}, {some_key2,SomeVal2}]"
use ct interface
use run_test interface (simulated)
repeated testruns
refresh_logs return
this is the last function that ct_run:script_start() calls, so the
return value here is what rpc:call/4 above returns
-----------------------------------------------------------------
-----------------------------------------------------------------
ct_rpc/1
-----------------------------------------------------------------
random_error/1
either call the fun here or return it to the caller (to be
executed in a test case instead)
-----------------------------------------------------------------
EVENT HANDLING
----------------------------------------------------------------------------
A group is represented as either:
{parallel,ListOfCasesAndGroups},
{shuffle,ListOfCasesAndGroups}, or
ListOfCasesAndGroups.
for init_per_group and end_per_group.
group (not parallel or shuffle)
with the tc_start, followed by the tc_done event. The order of the cases
is irrelevant, but it must be checked that every test case exists and
that tc_done comes after tc_start.
Use dropwhile here as a tc_done from a
previous testcase might sneak in here
tc_start event for a parallel test case
drop events until TEv is found
split the list at the tc_done event and record the smallest
list of remaining events (Evs) as possible
tc_done event for a parallel test case
tc_start event for end_per_group
tc_done event for end_per_group
end_per_group auto- or user skipped
start of a sub-group
Shuffled events: Each test case in the group should be specified in a list
with the tc_start, followed by the tc_done event. The order of the cases
is irrelevant, but it must be checked that every test case exists and
that the tc_done event follows the tc_start.
tc_start event for a test case
drop events until TEv is found
verify the tc_done event comes next in Evs
tc_done event for a test case
tc_start event for end_per_group
tc_done event for end_per_group
end_per_group auto-or user skipped
match other event than test case
start of a sub-group
to match variable data as a result of an aborted test case
to match variable data as a result of a failed test case
the other is matched.
matches any event of type Name
use this to only print the last test_stats event:
case [N || {_,#event{name=N}} <- Events, N == test_stats] of
[] -> % last stats event
_ ->
reformat(Events, EH)
end;
-----------------------------------------------------------------
MISC HELP FUNCTIONS
using tmp for logs
ensure we're removing the ct_run directory
-----------------------------------------------------------------
flush | Copyright Ericsson AB 2008 - 2022 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
This is a support module for testing the Common Test Framework .
-module(ct_test_support).
-include_lib("common_test/include/ct_event.hrl").
-include_lib("common_test/include/ct.hrl").
-export([init_per_suite/1, init_per_suite/2, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2,
write_testspec/2, write_testspec/3,
run/2, run/3, run/4, run_ct_run_test/2, run_ct_script_start/2,
get_opts/1, wait_for_ct_stop/1]).
-export([handle_event/2, start_event_receiver/1, get_events/2,
verify_events/3, verify_events/4, reformat/2, log_events/4,
join_abs_dirs/2]).
-export([start_slave/3, slave_stop/1]).
-export([ct_test_halt/1, ct_rpc/2]).
-export([random_error/1]).
-export([unique_timestamp/0]).
-export([rm_dir/1]).
-include_lib("kernel/include/file.hrl").
init_per_suite(Config) ->
init_per_suite(Config, 50).
init_per_suite(Config, Level) ->
ScaleFactor = test_server:timetrap_scale_factor(),
case os:type() of
{win32, _} ->
Extend timeout to 1 hour for windows as starting node
test_server:timetrap( 60*60*1000 * ScaleFactor );
_ ->
ok
end,
case delete_old_logs(os:type(), Config) of
{'EXIT',DelLogsReason} ->
test_server:format(0, "Failed to delete old log directories: ~tp~n",
[DelLogsReason]);
_ ->
ok
end,
{Mult,Scale} = test_server_ctrl:get_timetrap_parameters(),
test_server:format(Level, "Timetrap multiplier: ~w~n", [Mult]),
if Scale == true ->
test_server:format(Level, "Timetrap scale factor: ~w~n",
[ScaleFactor]);
true ->
ok
end,
start_slave(Config, Level).
start_slave(Config, Level) ->
start_slave(ct, Config, Level).
start_slave(NodeName, Config, Level) ->
[_,Host] = string:lexemes(atom_to_list(node()), "@"),
test_server:format(0, "Trying to start ~s~n",
[atom_to_list(NodeName)++"@"++Host]),
PR = proplists:get_value(printable_range,Config,io:printable_range()),
case slave:start(Host, NodeName, "+pc " ++ atom_to_list(PR)) of
{error,Reason} ->
ct:fail(Reason);
{ok,CTNode} ->
test_server:format(0, "Node ~p started~n", [CTNode]),
IsCover = test_server:is_cover(),
if IsCover ->
cover:start(CTNode);
true ->
ok
end,
DataDir = proplists:get_value(data_dir, Config),
PrivDir = proplists:get_value(priv_dir, Config),
PrivDir as well as directory of Test Server suites
[_ | Parts] = lists:reverse(filename:split(DataDir)),
TSDir = filename:join(lists:reverse(Parts)),
AddPathDirs = case proplists:get_value(path_dirs, Config) of
undefined -> [];
Ds -> Ds
end,
TestSupDir = filename:dirname(code:which(?MODULE)),
PathDirs = [PrivDir,TSDir,TestSupDir | AddPathDirs],
[true = rpc:call(CTNode, code, add_patha, [D]) || D <- PathDirs],
test_server:format(Level, "Dirs added to code path (on ~w):~n",
[CTNode]),
[io:format("~ts~n", [D]) || D <- PathDirs],
case proplists:get_value(start_sasl, Config) of
true ->
rpc:call(CTNode, application, start, [sasl]),
test_server:format(Level, "SASL started on ~w~n", [CTNode]);
_ ->
ok
end,
TraceFile = filename:join(DataDir, "ct.trace"),
case file:read_file_info(TraceFile) of
{ok,_} ->
[{trace_level,0},
{ct_opts,[{ct_trace,TraceFile}]},
{ct_node,CTNode} | Config];
_ ->
[{trace_level,Level},
{ct_opts,[]},
{ct_node,CTNode} | Config]
end
end.
end_per_suite(Config) ->
CTNode = proplists:get_value(ct_node, Config),
PrivDir = proplists:get_value(priv_dir, Config),
true = rpc:call(CTNode, code, del_path, [filename:join(PrivDir,"")]),
slave_stop(CTNode),
ok.
init_per_testcase(_TestCase, Config) ->
Opts = get_opts(Config),
NetDir = proplists:get_value(net_dir, Opts),
LogDir = join_abs_dirs(NetDir, proplists:get_value(logdir, Opts)),
case lists:keysearch(master, 1, Config) of
false->
test_server:format("See Common Test logs here:\n\n"
"<a href=\"file://~ts/all_runs.html\">~ts/all_runs.html</a>\n"
"<a href=\"file://~ts/index.html\">~ts/index.html</a>",
[LogDir,LogDir,LogDir,LogDir]);
{value, _}->
test_server:format("See CT Master Test logs here:\n\n"
"<a href=\"file://~ts/master_runs.html\">~ts/master_runs.html</a>",
[LogDir,LogDir])
end,
Config.
end_per_testcase(_TestCase, Config) ->
CTNode = proplists:get_value(ct_node, Config),
case wait_for_ct_stop(CTNode) of
false ->
slave_stop(CTNode),
start_slave(Config,proplists:get_value(trace_level,Config)),
{fail, "Could not stop common_test"};
true ->
ok
end.
write_testspec(TestSpec, Dir, Name) ->
write_testspec(TestSpec, filename:join(Dir, Name)).
write_testspec(TestSpec, TSFile) ->
{ok,Dev} = file:open(TSFile, [write,{encoding,utf8}]),
[io:format(Dev, "~tp.~n", [Entry]) || Entry <- TestSpec],
file:close(Dev),
io:format("Test specification written to: ~tp~n", [TSFile]),
io:format(user, "Test specification written to: ~tp~n", [TSFile]),
TSFile.
get_opts(Config) ->
PrivDir = proplists:get_value(priv_dir, Config),
TempDir = case os:getenv("TMP") of
false ->
case os:getenv("TEMP") of
false ->
undefined;
Tmp ->
create_tmp_logdir(Tmp)
end;
Tmp ->
create_tmp_logdir(Tmp)
end,
LogDir =
case os:getenv("CT_USE_TMP_DIR") of
false -> PrivDir;
_ -> TempDir
end,
CtTestVars =
case init:get_argument(ct_test_vars) of
{ok,[Vars]} ->
[begin {ok,Ts,_} = erl_scan:string(Str++"."),
{ok,Expr} = erl_parse:parse_term(Ts),
Expr
end || Str <- Vars];
_ ->
[]
end,
test_server : format("Test variables added to Config : ~p\n\n " ,
InitOpts =
case proplists:get_value(ct_opts, Config) of
undefined -> [];
CtOpts -> CtOpts
end,
[{logdir,LogDir} | InitOpts ++ CtTestVars].
run(Opts0, Config) when is_list(Opts0) ->
Opts =
case os:getenv("CT_TEST_OPTS") of
false -> Opts0;
"" -> Opts0;
Terms ->
case erl_scan:string(Terms++".", 0) of
{ok,Tokens,_} ->
case erl_parse:parse_term(Tokens) of
{ok,OROpts} ->
Override =
fun(O={Key,_}, Os) ->
io:format(user, "ADDING START "
"OPTION: ~tp~n", [O]),
[O | lists:keydelete(Key, 1, Os)]
end,
lists:foldl(Override, Opts0, OROpts);
_ ->
Opts0
end;
_ ->
Opts0
end
end,
CtRunTestResult=run_ct_run_test(Opts,Config),
ExitStatus=run_ct_script_start(Opts,Config),
check_result(CtRunTestResult,ExitStatus,Opts).
run_ct_run_test(Opts,Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
test_server:format(Level, "~n[RUN #1] Calling ct:run_test(~tp) on ~p~n",
[Opts, CTNode]),
T0 = erlang:monotonic_time(),
CtRunTestResult = rpc:call(CTNode, ct, run_test, [Opts]),
T1 = erlang:monotonic_time(),
Elapsed = erlang:convert_time_unit(T1-T0, native, milli_seconds),
test_server:format(Level, "~n[RUN #1] Got return value ~tp after ~p ms~n",
[CtRunTestResult,Elapsed]),
case rpc:call(CTNode, erlang, whereis, [ct_util_server]) of
undefined ->
ok;
_ ->
test_server:format(Level,
"ct_util_server not stopped on ~p yet, waiting 5 s...~n",
[CTNode]),
timer:sleep(5000),
undefined = rpc:call(CTNode, erlang, whereis, [ct_util_server])
end,
CtRunTestResult.
run_ct_script_start(Opts, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
Opts1 = [{halt_with,{?MODULE,ct_test_halt}} | Opts],
test_server:format(Level, "Saving start opts on ~p: ~tp~n",
[CTNode, Opts1]),
rpc:call(CTNode, application, set_env,
[common_test, run_test_start_opts, Opts1]),
test_server:format(Level, "[RUN #2] Calling ct_run:script_start() on ~p~n",
[CTNode]),
T0 = erlang:monotonic_time(),
ExitStatus = rpc:call(CTNode, ct_run, script_start, []),
T1 = erlang:monotonic_time(),
Elapsed = erlang:convert_time_unit(T1-T0, native, milli_seconds),
test_server:format(Level, "[RUN #2] Got exit status value ~tp after ~p ms~n",
[ExitStatus,Elapsed]),
ExitStatus.
check_result({_Ok,Failed,{_UserSkipped,_AutoSkipped}},1,_Opts)
when Failed > 0 ->
ok;
check_result({_Ok,0,{_UserSkipped,AutoSkipped}},ExitStatus,Opts)
when AutoSkipped > 0 ->
case proplists:get_value(exit_status, Opts) of
ignore_config when ExitStatus == 1 ->
{error,{wrong_exit_status,ExitStatus}};
_ ->
ok
end;
check_result({error,_}=Error,2,_Opts) ->
Error;
check_result({error,_},ExitStatus,_Opts) ->
{error,{wrong_exit_status,ExitStatus}};
check_result({_Ok,0,{_UserSkipped,_AutoSkipped}},0,_Opts) ->
ok;
check_result(CtRunTestResult,ExitStatus,Opts)
try check_result(sum_testruns(CtRunTestResult,0,0,0,0),ExitStatus,Opts)
catch _:_ ->
{error,{unexpected_return_value,{CtRunTestResult,ExitStatus}}}
end;
check_result(done,0,_Opts) ->
ok;
check_result(CtRunTestResult,ExitStatus,_Opts) ->
{error,{unexpected_return_value,{CtRunTestResult,ExitStatus}}}.
sum_testruns([{O,F,{US,AS}}|T],Ok,Failed,UserSkipped,AutoSkipped) ->
sum_testruns(T,Ok+O,Failed+F,UserSkipped+US,AutoSkipped+AS);
sum_testruns([],Ok,Failed,UserSkipped,AutoSkipped) ->
{Ok,Failed,{UserSkipped,AutoSkipped}}.
run(M, F, A, Config) ->
run({M,F,A}, [], Config).
run({M,F,A}, InitCalls, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
lists:foreach(
fun({IM,IF,IA}) ->
test_server:format(Level, "~nInit call ~w:~tw(~tp) on ~p...~n",
[IM, IF, IA, CTNode]),
Result = rpc:call(CTNode, IM, IF, IA),
test_server:format(Level, "~n...with result: ~tp~n", [Result])
end, InitCalls),
test_server:format(Level, "~nStarting test with ~w:~tw(~tp) on ~p~n",
[M, F, A, CTNode]),
rpc:call(CTNode, M, F, A).
ct_test_halt(ExitStatus) ->
ExitStatus.
wait_for_ct_stop/1
wait_for_ct_stop(CTNode) ->
Give CT at least 15 sec to stop ( in case of bad make ) .
wait_for_ct_stop(5, CTNode).
wait_for_ct_stop(0, CTNode) ->
test_server:format(0, "Giving up! Stopping ~p.", [CTNode]),
false;
wait_for_ct_stop(Retries, CTNode) ->
case rpc:call(CTNode, erlang, whereis, [ct_util_server]) of
undefined ->
true;
Pid ->
Info = (catch process_info(Pid)),
test_server:format(0, "Waiting for CT (~p) to finish (~p)...",
[Pid,Retries]),
test_server:format(0, "Process info for ~p:~n~tp", [Pid,Info]),
timer:sleep(5000),
wait_for_ct_stop(Retries-1, CTNode)
end.
ct_rpc({M,F,A}, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
test_server:format(Level, "~nCalling ~w:~tw(~tp) on ~p...",
[M,F,A, CTNode]),
rpc:call(CTNode, M, F, A).
random_error(Config) when is_list(Config) ->
rand:seed(exsplus),
Gen = fun(0,_) -> ok; (N,Fun) -> Fun(N-1, Fun) end,
Gen(rand:uniform(100), Gen),
ErrorTypes = ['BADMATCH','BADARG','CASE_CLAUSE','FUNCTION_CLAUSE',
'EXIT','THROW','UNDEF'],
Type = lists:nth(rand:uniform(length(ErrorTypes)), ErrorTypes),
Where = case rand:uniform(2) of
1 ->
io:format("ct_test_support *returning* error of type ~w",
[Type]),
tc;
2 ->
io:format("ct_test_support *generating* error of type ~w",
[Type]),
lib
end,
ErrorFun =
fun() ->
case Type of
'BADMATCH' ->
ok = proplists:get_value(undefined, Config);
'BADARG' ->
size(proplists:get_value(priv_dir, Config));
'FUNCTION_CLAUSE' ->
random_error(x);
'EXIT' ->
spawn_link(fun() ->
undef_proc ! hello,
ok
end);
'THROW' ->
PrivDir = proplists:get_value(priv_dir, Config),
if is_list(PrivDir) -> throw(generated_throw) end;
'UNDEF' ->
apply(?MODULE, random_error, [])
end
end,
case Where of
tc -> ErrorFun;
lib -> ErrorFun()
end.
handle_event(EH, Event) ->
event_receiver ! {self(),{event,EH,Event}},
receive {event_receiver,ok} -> ok end,
ok.
start_event_receiver(Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
ER = spawn_link(CTNode, fun() -> er() end),
test_server:format(Level, "~nEvent receiver ~w started!~n", [ER]),
ER.
get_events(_, Config) ->
CTNode = proplists:get_value(ct_node, Config),
Level = proplists:get_value(trace_level, Config),
{event_receiver,CTNode} ! {self(),get_events},
Events = receive {event_receiver,Evs} -> Evs end,
test_server:format(Level, "Stopping event receiver!~n", []),
{event_receiver,CTNode} ! {self(),stop},
receive {event_receiver,stopped} -> ok end,
Events.
er() ->
register(event_receiver, self()),
er_loop([]).
er_loop(Evs) ->
receive
{From,{event,EH,Ev}} ->
From ! {event_receiver,ok},
er_loop([{EH,Ev} | Evs]);
{From,get_events} ->
From ! {event_receiver,lists:reverse(Evs)},
er_loop(Evs);
{From,stop} ->
unregister(event_receiver),
From ! {event_receiver,stopped},
ok
end.
verify_events(TEvs, Evs, Config) ->
Node = proplists:get_value(ct_node, Config),
case catch verify_events1(TEvs, Evs, Node, Config) of
{'EXIT',Reason} ->
Reason;
_ ->
ok
end.
verify_events(TEvs, Evs, Node, Config) ->
case catch verify_events1(TEvs, Evs, Node, Config) of
{'EXIT',Reason} ->
Reason;
_ ->
ok
end.
verify_events1([TestEv|_], [{TEH,#event{name=stop_logging,node=Node,data=_}}|_], Node, _)
when element(1,TestEv) == TEH, element(2,TestEv) =/= stop_logging ->
test_server:format("Failed to find ~tp in the list of events!~n", [TestEv]),
exit({event_not_found,TestEv});
verify_events1(TEvs = [TestEv | TestEvs], Evs = [_|Events], Node, Config) ->
case catch locate(TestEv, Node, Evs, Config) of
nomatch ->
verify_events1(TEvs, Events, Node, Config);
{'EXIT',Reason} ->
test_server:format("Failed to find ~tp in ~tp~n"
"Reason: ~tp~n", [TestEv,Evs,Reason]),
exit(Reason);
{Config1,Events1} ->
if is_list(TestEv) ->
ok;
element(1,TestEv) == parallel ; element(1,TestEv) == shuffle ->
ok;
true ->
test_server:format("Found ~tp!", [TestEv])
end,
verify_events1(TestEvs, Events1, Node, Config1)
end;
verify_events1([TestEv|_], [], _, _) ->
test_server:format("Failed to find ~tp in the list of events!~n", [TestEv]),
exit({event_not_found,TestEv});
verify_events1([], Evs, _, Config) ->
{Config,Evs}.
locate({TEHandler , TEName , TEData } , TENode , Events , Config ) - > { Config1,Evs1 }
The two first and two last events in a group * may * be tc_start and tc_done
locate(TEvs, Node, Evs, Config) when is_list(TEvs) ->
case TEvs of
[InitStart = {TEH,tc_start,{M,{init_per_group,GroupName,Props}}},
InitDone = {TEH,tc_done,{M,{init_per_group,GroupName,Props},R}} | TEvs1] ->
case Evs of
[{TEH,#event{name=tc_start,
node=Node,
data={M,{init_per_group,GroupName,Props}}}},
{TEH,#event{name=tc_done,
node=Node,
data={M,{init_per_group,GroupName,Props},Res}}} | Evs1] ->
case result_match(R, Res) of
false ->
nomatch;
true ->
test_server:format("Found ~tp!", [InitStart]),
test_server:format("Found ~tp!", [InitDone]),
verify_events1(TEvs1, Evs1, Node, Config)
end;
_ ->
nomatch
end;
_ ->
verify_events1(TEvs, Evs, Node, Config)
end;
Parallel events : Each test case in the group should be specified in a list
locate({parallel,TEvs}, Node, Evs, Config) ->
Start =
case TEvs of
[InitStart = {TEH,tc_start,{M,{init_per_group,GroupName,Props}}},
InitDone = {TEH,tc_done,{M,{init_per_group,GroupName,Props},R}} | TEs] ->
case Evs of
[{TEH,#event{name=tc_start,
node=Node,
data={M,{init_per_group,
GroupName,Props}}}}|Es] ->
EvsG = lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={EvM,{init_per_group,
EvGroupName,
EvProps},EvR}}})
when TEH == EH, EvNode == Node, EvM == M,
EvGroupName == GroupName,
EvProps == Props ->
case result_match(R, EvR) of
true -> false;
false -> true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}})
when EH == TEH, EvNode == Node ->
exit({group_init_done_not_found,
GroupName,Props});
(_) ->
true
end, Es),
test_server:format("Found ~tp!", [InitStart]),
test_server:format("Found ~tp!", [InitDone]),
{TEs,EvsG};
_ ->
nomatch
end;
_ ->
{TEvs,Evs}
end,
case Start of
nomatch ->
nomatch;
{TEvs1,Evs1} ->
{TcDoneEvs,RemainEvs,_} =
lists:foldl(
fun(TEv={TEH,tc_start,{M,F}}, {Done,RemEvs,RemSize}) ->
Evs2 = lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,Func}}}) when
EH == TEH, EvNode == Node,
Mod == M, Func == F ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, Evs1),
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={Mod,Func,_}}}) when
EH == TEH, EvNode == Node,
Mod == M, Func == F ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_done_not_found,TEv});
(_) ->
true
end, Evs2),
case RemEvs1 of
[] when Evs2 == [] ->
exit({unmatched,TEv});
[] ->
test_server:format("Found ~tp!", [TEv]),
exit({tc_done_not_found,TEv});
[TcDone|Evs3] ->
test_server:format("Found ~tp!", [TEv]),
RemSize1 = length(Evs3),
if RemSize1 < RemSize ->
{[TcDone|Done],Evs3,RemSize1};
true ->
{[TcDone|Done],RemEvs,RemSize}
end
end;
(TEv={TEH,tc_done,{M,F,R}}, {Done,RemEvs,RemSize}) ->
case [E || E={EH,#event{name=tc_done,
node=EvNode,
data={Mod,Func,Result}}} <- Done,
EH == TEH, EvNode == Node, Mod == M,
Func == F, result_match(R, Result)] of
[TcDone|_] ->
test_server:format("Found ~tp!", [TEv]),
{lists:delete(TcDone, Done),RemEvs,RemSize};
[] ->
exit({unmatched,TEv})
end;
(TEv={TEH,tc_start,{M,{end_per_group,GroupName,Props}}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,{end_per_group,
EvGName,EvProps}}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName, EvProps == Props ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_ | RemEvs2] ->
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
(TEv={TEH,tc_done,{M,{end_per_group,GroupName,Props},R}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={Mod,{end_per_group,
EvGName,EvProps},Res}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName, EvProps == Props ->
case result_match(R, Res) of
true ->
false;
false ->
true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_done_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_ | RemEvs2] ->
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
(TEv={TEH,AutoOrUserSkip,{M,{end_per_group,G},R}}, {Done,RemEvs,_RemSize})
when AutoOrUserSkip == tc_auto_skip;
AutoOrUserSkip == tc_user_skip ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_auto_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G ->
case match_data(R, Reason) of
match -> false;
_ -> true
end;
({EH,#event{name=tc_user_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G ->
case match_data(R, Reason) of
match -> false;
_ -> true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_auto_or_user_skip_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_AutoSkip | RemEvs2] ->
{Done,RemEvs2,length(RemEvs2)}
end;
(TEv={TEH,N,D}, Acc) ->
case [E || E={EH,#event{name=Name,
node=EvNode,
data=Data}} <- Evs1,
EH == TEH, EvNode == Node, Name == N,
match == match_data(D,Data)] of
[] ->
exit({unmatched,TEv});
_ ->
test_server:format("Found ~tp!", [TEv]),
Acc
end;
(SubGroupTEvs, Acc) when is_list(SubGroupTEvs) ->
verify_events1(SubGroupTEvs, Evs1, Node, Config),
Acc;
(TEv={Prop,_SubGroupTEvs}, Acc) when
Prop == shuffle ; Prop == parallel ->
verify_events1([TEv], Evs1, Node, Config),
Acc
end, {[],Evs1,length(Evs1)}, TEvs1),
case TcDoneEvs of
[] ->
test_server:format("Found all parallel events!", []),
{Config,RemainEvs};
_ ->
exit({unexpected_events,TcDoneEvs})
end
end;
locate({shuffle,TEvs}, Node, Evs, Config) ->
Start =
case TEvs of
[InitStart = {TEH,tc_start,{M,{init_per_group,GroupName,Props}}},
InitDone = {TEH,tc_done,{M,{init_per_group,GroupName,Props},R}} | TEs] ->
case Evs of
[{TEH,#event{name=tc_start,
node=Node,
data={M,{init_per_group,GroupName,EvProps}}}},
{TEH,#event{name=tc_done,
node=Node,
data={M,{init_per_group,GroupName,EvProps},Res}}} | Es] ->
case result_match(R, Res) of
true ->
case proplists:get_value(shuffle, Props) of
'_' ->
case proplists:get_value(shuffle, EvProps) of
false ->
exit({no_shuffle_prop_found,
{M,init_per_group,
GroupName,EvProps}});
_ ->
PropsCmp = proplists:delete(shuffle, EvProps),
PropsCmp = proplists:delete(shuffle, Props)
end;
_ ->
Props = EvProps
end,
test_server:format("Found ~tp!", [InitStart]),
test_server:format("Found ~tp!", [InitDone]),
{TEs,Es};
false ->
nomatch
end;
_ ->
nomatch
end;
_ ->
{TEvs,Evs}
end,
case Start of
nomatch ->
nomatch;
{TEvs1,Evs1} ->
{TcDoneEvs,RemainEvs,_} =
lists:foldl(
fun(TEv={TEH,tc_start,{M,F}}, {Done,RemEvs,RemSize}) ->
Evs2 = lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,Func}}}) when
EH == TEH, EvNode == Node,
Mod == M, Func == F ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, Evs1),
case Evs2 of
[] ->
exit({unmatched,TEv});
[_TcStart, TcDone={TEH,#event{name=tc_done,
node=Node,
data={M,F,_}}} | Evs3] ->
test_server:format("Found ~tp!", [TEv]),
RemSize1 = length(Evs3),
if RemSize1 < RemSize ->
{[TcDone|Done],Evs3,RemSize1};
true ->
{[TcDone|Done],RemEvs,RemSize}
end
end;
(TEv={TEH,tc_done,{M,F,R}}, {Done,RemEvs,RemSize}) ->
case [E || E={EH,#event{name=tc_done,
node=EvNode,
data={Mod,Func,Result}}} <- Done,
EH == TEH, EvNode == Node, Mod == M,
Func == F, result_match(R, Result)] of
[TcDone|_] ->
test_server:format("Found ~tp!", [TEv]),
{lists:delete(TcDone, Done),RemEvs,RemSize};
[] ->
exit({unmatched,TEv})
end;
(TEv={TEH,tc_start,{M,{end_per_group,GroupName,Props}}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_start,
node=EvNode,
data={Mod,{end_per_group,
EvGName,_}}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_start_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[{_,#event{data={_,{_,_,EvProps1}}}} | RemEvs2] ->
case proplists:get_value(shuffle, Props) of
'_' ->
case proplists:get_value(shuffle, EvProps1) of
false ->
exit({no_shuffle_prop_found,
{M,end_per_group,GroupName,EvProps1}});
_ ->
PropsCmp1 = proplists:delete(shuffle, EvProps1),
PropsCmp1 = proplists:delete(shuffle, Props)
end;
_ ->
Props = EvProps1
end,
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
(TEv={TEH,tc_done,{M,{end_per_group,GroupName,Props},R}},
{Done,RemEvs,_RemSize}) ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_done,
node=EvNode,
data={Mod,{end_per_group,
EvGName,_},Res}}}) when
EH == TEH, EvNode == Node, Mod == M,
EvGName == GroupName ->
case result_match(R, Res) of
true ->
false;
false ->
true
end;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_done_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[{_,#event{data={_,{_,_,EvProps1},_}}} | RemEvs2] ->
case proplists:get_value(shuffle, Props) of
'_' ->
case proplists:get_value(shuffle, EvProps1) of
false ->
exit({no_shuffle_prop_found,
{M,end_per_group,GroupName,EvProps1}});
_ ->
PropsCmp1 = proplists:delete(shuffle, EvProps1),
PropsCmp1 = proplists:delete(shuffle, Props)
end;
_ ->
Props = EvProps1
end,
test_server:format("Found ~tp!", [TEv]),
{Done,RemEvs2,length(RemEvs2)}
end;
(TEv={TEH,AutoOrUserSkip,{M,{end_per_group,G},R}}, {Done,RemEvs,_RemSize})
when AutoOrUserSkip == tc_auto_skip;
AutoOrUserSkip == tc_user_skip ->
RemEvs1 =
lists:dropwhile(
fun({EH,#event{name=tc_auto_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G, Reason == R ->
false;
({EH,#event{name=tc_user_skip,
node=EvNode,
data={Mod,{end_per_group,EvGroupName},Reason}}}) when
EH == TEH, EvNode == Node, Mod == M, EvGroupName == G, Reason == R ->
false;
({EH,#event{name=stop_logging,
node=EvNode,data=_}}) when
EH == TEH, EvNode == Node ->
exit({tc_auto_skip_not_found,TEv});
(_) ->
true
end, RemEvs),
case RemEvs1 of
[] ->
exit({end_per_group_not_found,TEv});
[_AutoSkip | RemEvs2] ->
{Done,RemEvs2,length(RemEvs2)}
end;
(TEv={TEH,N,D}, Acc) when D == '_' ->
case [E || E={EH,#event{name=Name,
node=EvNode,
data=_}} <- Evs1,
EH == TEH, EvNode == Node, Name == N] of
[] ->
exit({unmatched,TEv});
_ ->
test_server:format("Found ~tp!", [TEv]),
Acc
end;
(TEv={TEH,N,D}, Acc) ->
case [E || E={EH,#event{name=Name,
node=EvNode,
data=Data}} <- Evs1,
EH == TEH, EvNode == Node, Name == N, Data == D] of
[] ->
exit({unmatched,TEv});
_ ->
test_server:format("Found ~tp!", [TEv]),
Acc
end;
(SubGroupTEvs, Acc) when is_list(SubGroupTEvs) ->
verify_events1(SubGroupTEvs, Evs1, Node, Config),
Acc;
(TEv={Prop,_SubGroupTEvs}, Acc) when
Prop == shuffle ; Prop == parallel ->
verify_events1([TEv], Evs1, Node, Config),
Acc
end, {[],Evs1,length(Evs1)}, TEvs1),
case TcDoneEvs of
[] ->
test_server:format("Found all shuffled events!", []),
{Config,RemainEvs};
_ ->
exit({unexpected_events,TcDoneEvs})
end
end;
locate({TEH,Name,{'DEF','RUNDIR'}}, Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=Name, node=Node, data=EvData}} ->
{_,{_,LogDir}} = lists:keysearch(logdir, 1, get_opts(Config)),
D = filename:join(LogDir, "ct_run." ++ atom_to_list(Node)),
case string:find(EvData, D) of
nomatch -> exit({badmatch,EvData});
_ -> ok
end,
{Config,Evs};
_ ->
nomatch
end;
locate({TEH,Name,{'DEF',{'START_TIME','LOGDIR'}}}, Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=Name, node=Node, data=EvData}} ->
case EvData of
{DT={{_,_,_},{_,_,_}},Dir} when is_list(Dir) ->
{_,{_,LogDir}} = lists:keysearch(logdir, 1, get_opts(Config)),
D = filename:join(LogDir, "ct_run." ++ atom_to_list(Node)),
case string:find(Dir, D) of
nomatch -> exit({badmatch,Dir});
_ -> ok
end,
{[{start_time,DT}|Config],Evs};
Data ->
exit({badmatch,Data})
end;
_ ->
nomatch
end;
locate({TEH,Name,{'DEF','STOP_TIME'}}, Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=Name, node=Node, data=EvData}} ->
case EvData of
DT={{_,_,_},{_,_,_}} ->
{[{stop_time,DT}|Config],Evs};
Data ->
exit({badmatch,Data})
end;
_ ->
nomatch
end;
locate({TEH,tc_done,{undefined,undefined,{testcase_aborted,
{abort_current_testcase,Func},'_'}}},
Node, [Ev|Evs], Config) ->
case Ev of
{TEH,#event{name=tc_done, node=Node,
data={undefined,undefined,
{testcase_aborted,{abort_current_testcase,Func},_}}}} ->
{Config,Evs};
_ ->
nomatch
end;
locate({TEH,tc_done,{Mod,Func,R={SkipOrFail,{_ErrInd,ErrInfo}}}},
Node, [Ev|Evs], Config) when ((SkipOrFail == skipped) or
(SkipOrFail == failed)) and
((size(ErrInfo) == 2) or
(size(ErrInfo) == 3)) ->
case Ev of
{TEH,#event{name=tc_done, node=Node,
data={Mod,Func,Result}}} ->
case result_match(R, Result) of
true ->
{Config,Evs};
false ->
nomatch
end;
_ ->
nomatch
end;
Negative matching : Given two events , the first should not be present before
locate({negative,NotMatch, Match} = Neg, Node, Evs, Config) ->
case locate(NotMatch, Node, Evs, Config) of
nomatch ->
locate(Match, Node, Evs, Config);
_ ->
exit({found_negative_event,Neg})
end;
locate({TEH,Name,Data}, Node, [{TEH,#event{name=Name,
data = EvData,
node = Node}}|Evs],
Config) ->
case match_data(Data, EvData) of
match ->
{Config,Evs};
_ ->
nomatch
end;
locate({_TEH,_Name,_Data}, _Node, [_|_Evs], _Config) ->
nomatch.
match_data(Data, EvData) ->
try do_match_data(Data, EvData)
catch _:_ ->
nomatch
end.
do_match_data(D,D) ->
match;
do_match_data('_',_) ->
match;
do_match_data(Fun,Data) when is_function(Fun) ->
Fun(Data);
do_match_data('$proplist',Proplist) ->
do_match_data(
fun(List) ->
lists:foreach(fun({_,_}) -> ok end,List)
end,Proplist);
do_match_data([H1|MatchT],[H2|ValT]) ->
do_match_data(H1,H2),
do_match_data(MatchT,ValT);
do_match_data(Tuple1,Tuple2) when is_tuple(Tuple1),is_tuple(Tuple2) ->
do_match_data(tuple_to_list(Tuple1),tuple_to_list(Tuple2));
do_match_data([],[]) ->
match.
result_match({SkipOrFail,{ErrorInd,{Why,'_'}}},
{SkipOrFail,{ErrorInd,{Why,_Stack}}}) ->
true;
result_match({SkipOrFail,{ErrorInd,{EMod,EFunc,{Why,'_'}}}},
{SkipOrFail,{ErrorInd,{EMod,EFunc,{Why,_Stack}}}}) ->
true;
result_match({failed,{timetrap_timeout,{'$approx',Num}}},
{failed,{timetrap_timeout,Value}}) ->
if Value >= trunc(Num-0.05*Num),
Value =< trunc(Num+0.05*Num) -> true;
true -> false
end;
result_match({user_timetrap_error,{Why,'_'}},
{user_timetrap_error,{Why,_Stack}}) ->
true;
result_match({SkipOrFail,{ErrorInd,{thrown,{Why,'_'}}}},
{SkipOrFail,{ErrorInd,{thrown,{Why,_Stack}}}}) ->
true;
result_match(Result, Result) ->
true;
result_match(_, _) ->
false.
log_events(TC, Events, EvLogDir, Opts) ->
LogFile = filename:join(EvLogDir, atom_to_list(TC)++".events"),
{ok,Dev} = file:open(LogFile, [write,{encoding,utf8}]),
io:format(Dev, "[~n", []),
log_events1(Events, Dev, " "),
file:close(Dev),
FullLogFile = join_abs_dirs(proplists:get_value(net_dir, Opts),
LogFile),
ct:log("Events written to logfile: <a href=\"file://~ts\">~ts</a>~n",
[FullLogFile,FullLogFile],[no_css]),
io:format(user, "Events written to logfile: ~tp~n", [LogFile]).
log_events1(Evs, Dev, "") ->
log_events1(Evs, Dev, " ");
log_events1([E={_EH,tc_start,{_M,{init_per_group,_GrName,Props}}} | Evs], Dev, Ind) ->
case get_prop(Props) of
undefined ->
io:format(Dev, "~s[~tp,~n", [Ind,E]),
log_events1(Evs, Dev, Ind++" ");
Prop ->
io:format(Dev, "~s{~w,~n~s[~tp,~n", [Ind,Prop,Ind++" ",E]),
log_events1(Evs, Dev, Ind++" ")
end;
log_events1([E={_EH,tc_done,{_M,{init_per_group,_GrName,_Props},_R}} | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp,~n", [Ind,E]),
log_events1(Evs, Dev, Ind++" ");
log_events1([E={_EH,tc_start,{_M,{end_per_group,_GrName,_Props}}} | Evs], Dev, Ind) ->
Ind1 = Ind -- " ",
io:format(Dev, "~s~tp,~n", [Ind1,E]),
log_events1(Evs, Dev, Ind1);
log_events1([E={_EH,tc_done,{_M,{end_per_group,_GrName,Props},_R}} | Evs], Dev, Ind) ->
case get_prop(Props) of
undefined ->
io:format(Dev, "~s~tp],~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ");
_Prop ->
io:format(Dev, "~s~tp]},~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ")
end;
log_events1([E={_EH,tc_auto_skip,{_M,{end_per_group,_GrName},_Reason}} | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp],~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ");
log_events1([E={_EH,tc_user_skip,{_M,{end_per_group,_GrName},_Reason}} | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp],~n", [Ind,E]),
log_events1(Evs, Dev, Ind--" ");
log_events1([E], Dev, Ind) ->
io:format(Dev, "~s~tp~n].~n", [Ind,E]),
ok;
log_events1([E | Evs], Dev, Ind) ->
io:format(Dev, "~s~tp,~n", [Ind,E]),
log_events1(Evs, Dev, Ind);
log_events1([], _Dev, _Ind) ->
ok.
get_prop(Props) ->
case lists:member(parallel, Props) of
true -> parallel;
false -> case lists:member(shuffle, Props) of
true -> shuffle;
false -> case lists:keysearch(shuffle, 1, Props) of
{value,_} -> shuffle;
_ -> undefined
end
end
end.
reformat([{_EH,#event{name=start_write_file,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=finished_write_file,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=start_make,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=finished_make,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=start_logging,data=_}} | Events], EH) ->
[{EH,start_logging,{'DEF','RUNDIR'}} | reformat(Events, EH)];
reformat([{_EH,#event{name=test_start,data=_}} | Events], EH) ->
[{EH,test_start,{'DEF',{'START_TIME','LOGDIR'}}} | reformat(Events, EH)];
reformat([{_EH,#event{name=test_done,data=_}} | Events], EH) ->
[{EH,test_done,{'DEF','STOP_TIME'}} | reformat(Events, EH)];
reformat([{_EH,#event{name=tc_logfile,data=_}} | Events], EH) ->
reformat(Events, EH);
reformat([{_EH,#event{name=test_stats,data=Data}} | Events], EH) ->
[{EH,test_stats,Data} | reformat(Events, EH)];
[ { EH , test_stats , Data } | reformat(Events , ) ] ;
reformat([{_EH,#event{name=Name,data=Data}} | Events], EH) ->
[{EH,Name,Data} | reformat(Events, EH)];
reformat([], _EH) ->
[].
join_abs_dirs(undefined, Dir2) ->
Dir2;
join_abs_dirs(Dir1, Dir2) ->
case filename:pathtype(Dir2) of
relative ->
filename:join(Dir1, Dir2);
_ ->
[_Abs|Parts] = filename:split(Dir2),
filename:join(Dir1, filename:join(Parts))
end.
create_tmp_logdir(Tmp) ->
LogDir = filename:join(Tmp,"ct"),
file:make_dir(LogDir),
LogDir.
delete_old_logs({win32,_}, Config) ->
case {proplists:get_value(priv_dir, Config),
proplists:get_value(logdir, get_opts(Config))} of
{LogDir,LogDir} ->
ignore;
catch delete_dirs(LogDir)
end;
delete_old_logs(_, Config) ->
case os:getenv("CT_USE_TMP_DIR") of
false ->
ignore;
_ ->
catch delete_dirs(proplists:get_value(logdir,
get_opts(Config)))
end.
delete_dirs(LogDir) ->
Now = calendar:datetime_to_gregorian_seconds(calendar:local_time()),
SaveTime = list_to_integer(os:getenv("CT_SAVE_OLD_LOGS", "28800")),
Deadline = Now - SaveTime,
Dirs = filelib:wildcard(filename:join(LogDir,"ct_run*")),
Dirs2Del =
lists:foldl(fun(Dir, Del) ->
[S,Mi,H,D,Mo,Y|_] =
lists:reverse(string:lexemes(Dir, [$.,$-,$_])),
S2I = fun(Str) -> list_to_integer(Str) end,
DT = {{S2I(Y),S2I(Mo),S2I(D)}, {S2I(H),S2I(Mi),S2I(S)}},
Then = calendar:datetime_to_gregorian_seconds(DT),
if Then > Deadline ->
Del;
true ->
[Dir | Del]
end
end, [], Dirs),
case length(Dirs2Del) of
0 ->
test_server:format(0, "No log directories older than ~w secs.", [SaveTime]);
N ->
test_server:format(0, "Deleting ~w directories older than ~w secs.", [N,SaveTime])
end,
delete_dirs(LogDir, Dirs2Del).
delete_dirs(_, []) ->
ok;
delete_dirs(LogDir, [Dir | Dirs]) ->
test_server:format(0, "Removing old log directory: ~ts", [Dir]),
case catch rm_rec(Dir) of
{_,Reason} ->
test_server:format(0, "Delete failed! (~tp)", [Reason]);
ok ->
ok
end,
delete_dirs(LogDir, Dirs).
rm_rec(Dir) ->
case lists:reverse(filename:split(Dir)) of
[[$c,$t,$_,$r,$u,$n,$.|_]|_] ->
rm_dir(filename:absname(Dir));
_ ->
{error,{invalid_logdir,Dir}}
end.
rm_dir(Dir) ->
case file:list_dir(Dir) of
{error,Errno} ->
exit({ls_failed,Dir,Errno});
{ok,Files} ->
rm_files([filename:join(Dir, F) || F <- Files]),
file:del_dir(Dir)
end.
rm_files([F | Fs]) ->
Base = filename:basename(F),
if Base == "." ; Base == ".." ->
rm_files(Fs);
true ->
case file:read_file_info(F) of
{ok,#file_info{type=directory}} ->
rm_dir(F),
rm_files(Fs);
{ok,_Regular} ->
case file:delete(F) of
ok ->
rm_files(Fs);
{error,Errno} ->
exit({del_failed,F,Errno})
end
end
end;
rm_files([]) ->
ok.
unique_timestamp() ->
unique_timestamp(os:timestamp(), 100000).
unique_timestamp(TS, 0) ->
TS;
unique_timestamp(TS0, N) ->
case os:timestamp() of
TS0 ->
timer:sleep(1),
unique_timestamp(TS0, N-1);
TS1 ->
TS1
end.
slave_stop(Node) ->
Cover = test_server:is_cover(),
if Cover-> cover:flush(Node);
true -> ok
end,
erlang:monitor_node(Node, true),
slave:stop(Node),
receive
{nodedown, Node} ->
if Cover -> cover:stop(Node);
true -> ok
end
after 5000 ->
erlang:monitor_node(Node, false),
end,
ok.
|
1d98849e69966ada6f5512a9248d8a392d0597d217d0989b9a882b1fe9caa67b | fpco/wai-middleware-auth | Internal.hs | {-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - orphans #
module Spec.Network.Wai.Auth.Internal (tests) where
import Data.Binary (encode, decodeOrFail)
import qualified Data.ByteString.Lazy.Char8 as BSL8
import qualified Data.Text as T
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.Hedgehog (testProperty)
import Hedgehog
import Hedgehog.Gen as Gen
import Hedgehog.Range as Range
import Network.Wai.Auth.Internal
import qualified Network.OAuth.OAuth2.Internal as OA2
tests :: TestTree
tests = testGroup "Network.Wai.Auth.Internal"
[ testProperty "oAuth2TokenBinaryDuality" oAuth2TokenBinaryDuality
]
oAuth2TokenBinaryDuality :: Property
oAuth2TokenBinaryDuality = property $ do
token <- forAll oauth2TokenBinary
let checkUnconsumed ("", _, roundTripToken) = roundTripToken
checkUnconsumed (unconsumed, _, _) =
error $ "Unexpected unconsumed in bytes: " <> BSL8.unpack unconsumed
tripping token encode (fmap checkUnconsumed . decodeOrFail)
tripping token (encodeToken . unOAuth2TokenBinary) (fmap OAuth2TokenBinary . decodeToken)
oauth2TokenBinary :: Gen OAuth2TokenBinary
oauth2TokenBinary = do
accessToken <- OA2.AccessToken <$> anyText
refreshToken <- Gen.maybe $ OA2.RefreshToken <$> anyText
expiresIn <- Gen.maybe $ Gen.int (Range.linear 0 1000)
tokenType <- Gen.maybe anyText
idToken <- Gen.maybe $ OA2.IdToken <$> anyText
pure $
OAuth2TokenBinary $
OA2.OAuth2Token accessToken refreshToken expiresIn tokenType idToken
anyText :: Gen T.Text
anyText = Gen.text (Range.linear 0 100) Gen.unicodeAll
The ` OAuth2Token ` type from the ` hoauth2 ` library does not have a ` Eq `
-- instance, and it's constituent parts don't have a `Generic` instance. Hence
-- this orphan instance here.
instance Eq OAuth2TokenBinary where
(OAuth2TokenBinary t1) == (OAuth2TokenBinary t2) =
and
[ OA2.atoken (OA2.accessToken t1) == OA2.atoken (OA2.accessToken t2)
, (OA2.rtoken <$> OA2.refreshToken t1) == (OA2.rtoken <$> OA2.refreshToken t2)
, OA2.expiresIn t1 == OA2.expiresIn t2
, OA2.tokenType t1 == OA2.tokenType t2
, (OA2.idtoken <$> OA2.idToken t1) == (OA2.idtoken <$> OA2.idToken t2)
]
| null | https://raw.githubusercontent.com/fpco/wai-middleware-auth/77b83b91240916e74a8a61c74cd63aa3905c6a9f/test/Spec/Network/Wai/Auth/Internal.hs | haskell | # LANGUAGE OverloadedStrings #
instance, and it's constituent parts don't have a `Generic` instance. Hence
this orphan instance here. | # OPTIONS_GHC -fno - warn - orphans #
module Spec.Network.Wai.Auth.Internal (tests) where
import Data.Binary (encode, decodeOrFail)
import qualified Data.ByteString.Lazy.Char8 as BSL8
import qualified Data.Text as T
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.Hedgehog (testProperty)
import Hedgehog
import Hedgehog.Gen as Gen
import Hedgehog.Range as Range
import Network.Wai.Auth.Internal
import qualified Network.OAuth.OAuth2.Internal as OA2
tests :: TestTree
tests = testGroup "Network.Wai.Auth.Internal"
[ testProperty "oAuth2TokenBinaryDuality" oAuth2TokenBinaryDuality
]
oAuth2TokenBinaryDuality :: Property
oAuth2TokenBinaryDuality = property $ do
token <- forAll oauth2TokenBinary
let checkUnconsumed ("", _, roundTripToken) = roundTripToken
checkUnconsumed (unconsumed, _, _) =
error $ "Unexpected unconsumed in bytes: " <> BSL8.unpack unconsumed
tripping token encode (fmap checkUnconsumed . decodeOrFail)
tripping token (encodeToken . unOAuth2TokenBinary) (fmap OAuth2TokenBinary . decodeToken)
oauth2TokenBinary :: Gen OAuth2TokenBinary
oauth2TokenBinary = do
accessToken <- OA2.AccessToken <$> anyText
refreshToken <- Gen.maybe $ OA2.RefreshToken <$> anyText
expiresIn <- Gen.maybe $ Gen.int (Range.linear 0 1000)
tokenType <- Gen.maybe anyText
idToken <- Gen.maybe $ OA2.IdToken <$> anyText
pure $
OAuth2TokenBinary $
OA2.OAuth2Token accessToken refreshToken expiresIn tokenType idToken
anyText :: Gen T.Text
anyText = Gen.text (Range.linear 0 100) Gen.unicodeAll
The ` OAuth2Token ` type from the ` hoauth2 ` library does not have a ` Eq `
instance Eq OAuth2TokenBinary where
(OAuth2TokenBinary t1) == (OAuth2TokenBinary t2) =
and
[ OA2.atoken (OA2.accessToken t1) == OA2.atoken (OA2.accessToken t2)
, (OA2.rtoken <$> OA2.refreshToken t1) == (OA2.rtoken <$> OA2.refreshToken t2)
, OA2.expiresIn t1 == OA2.expiresIn t2
, OA2.tokenType t1 == OA2.tokenType t2
, (OA2.idtoken <$> OA2.idToken t1) == (OA2.idtoken <$> OA2.idToken t2)
]
|
59f1e0bbe9c7b650ee053ad7736b151aad2f7953bb8a5eb2f1b4c55c0389fd91 | spacegangster/space-ui | btn.cljc | (ns space-ui.tiny.btn
(:require [space-ui.bem :as bem]
[space-ui.style.main-mixins :as mm]
[space-ui.style.constants :as sc]
[space-ui.primitives :as prim]
[space-ui.svgs :as svgs]))
(def on-click-prop #?(:cljs :on-click :clj :onclick))
(def color:border-blue-skeuo "hsl(203, 59%, 52%)")
(def grad:blue-flat1
(prim/linear-gradient
:gradient/to-bottom
(prim/hsl 213 98 64)
(prim/hsl 213 98 63)))
(def grad:blue-flat1:active
(prim/linear-gradient
:gradient/to-bottom
(prim/hsl 213 98 62)
(prim/hsl 213 98 60)))
(def style-rules
[:.btn
mm/pane-frame
{:display :inline-flex
:align-items :center
:justify-content :center
:font-size :14px
:line-height 1.2
:color sc/color-text
:cursor :pointer
:border "1px solid"
:padding (sc/d-step-x-px 1 1.5)}
[:&__icon
{:color :inherit
:margin-right sc/dim-step-px}]
[:&--textual
:&--icon
{:padding 0
:border :none
:color sc/color-control--textual-default}
[:&:hover
{:color sc/color-control--textual-hovered}]]
[:&:active
:&--active
{:background (prim/hsla 0 0 0 0.07)}]
[:&--round
mm/button--round]
[:&--textual
{:font-size :inherit
:color :inherit}]
[:&--cta-blue
:&--cta-blue:visited
{:background grad:blue-flat1
:color :white
:border-color color:border-blue-skeuo}
[:&:active
{:background grad:blue-flat1:active}]]
[:&--inherit-color
{:color :inherit}]
[:&--bigger
{:font-size :18px
:letter-spacing :.09em}]
[:&--danger
mm/icon--danger]])
(defn btn
[{:btn/keys
[icon css-class mods label on-click goal-id
tooltip title tabindex type attrs]
:as params}]
[:button.btn
(cond-> {:class (str (bem/bem-str :btn mods) " " css-class)
:title (or title tooltip)
on-click-prop on-click
:data-goal-id goal-id
:tabIndex tabindex
:type type}
attrs (merge attrs))
(if icon
[:div.btn__icon
[svgs/icon icon]])
(if (string? label)
[:div.btn__label label])])
(defn cta
[{:btn/keys
[icon css-class mods label on-click
tooltip title tabindex type attrs]
:as params}]
(btn (update params :btn/mods conj ::cta)))
(defn cta-blue
[{:btn/keys
[icon css-class mods label on-click
tooltip title tabindex type attrs]
:as params}]
(btn (update params :btn/mods conj ::cta-blue)))
(comment
(cta {:label "hey"}))
(defn icon [icon & [{:btn/keys [title managed-colors? danger? active? on-click round?] :as opts}]]
[:button
{:title (or title (name icon))
:class (bem/bem-str :button :icon
(if round? :round)
(if danger? :danger)
(if active? :active))
on-click-prop on-click}
[svgs/icon icon {:active? active? :danger? danger?
:managed-colors managed-colors?}]])
| null | https://raw.githubusercontent.com/spacegangster/space-ui/a83fa857ec60daa59572eb9313244f189cc0798c/src/space_ui/tiny/btn.cljc | clojure | (ns space-ui.tiny.btn
(:require [space-ui.bem :as bem]
[space-ui.style.main-mixins :as mm]
[space-ui.style.constants :as sc]
[space-ui.primitives :as prim]
[space-ui.svgs :as svgs]))
(def on-click-prop #?(:cljs :on-click :clj :onclick))
(def color:border-blue-skeuo "hsl(203, 59%, 52%)")
(def grad:blue-flat1
(prim/linear-gradient
:gradient/to-bottom
(prim/hsl 213 98 64)
(prim/hsl 213 98 63)))
(def grad:blue-flat1:active
(prim/linear-gradient
:gradient/to-bottom
(prim/hsl 213 98 62)
(prim/hsl 213 98 60)))
(def style-rules
[:.btn
mm/pane-frame
{:display :inline-flex
:align-items :center
:justify-content :center
:font-size :14px
:line-height 1.2
:color sc/color-text
:cursor :pointer
:border "1px solid"
:padding (sc/d-step-x-px 1 1.5)}
[:&__icon
{:color :inherit
:margin-right sc/dim-step-px}]
[:&--textual
:&--icon
{:padding 0
:border :none
:color sc/color-control--textual-default}
[:&:hover
{:color sc/color-control--textual-hovered}]]
[:&:active
:&--active
{:background (prim/hsla 0 0 0 0.07)}]
[:&--round
mm/button--round]
[:&--textual
{:font-size :inherit
:color :inherit}]
[:&--cta-blue
:&--cta-blue:visited
{:background grad:blue-flat1
:color :white
:border-color color:border-blue-skeuo}
[:&:active
{:background grad:blue-flat1:active}]]
[:&--inherit-color
{:color :inherit}]
[:&--bigger
{:font-size :18px
:letter-spacing :.09em}]
[:&--danger
mm/icon--danger]])
(defn btn
[{:btn/keys
[icon css-class mods label on-click goal-id
tooltip title tabindex type attrs]
:as params}]
[:button.btn
(cond-> {:class (str (bem/bem-str :btn mods) " " css-class)
:title (or title tooltip)
on-click-prop on-click
:data-goal-id goal-id
:tabIndex tabindex
:type type}
attrs (merge attrs))
(if icon
[:div.btn__icon
[svgs/icon icon]])
(if (string? label)
[:div.btn__label label])])
(defn cta
[{:btn/keys
[icon css-class mods label on-click
tooltip title tabindex type attrs]
:as params}]
(btn (update params :btn/mods conj ::cta)))
(defn cta-blue
[{:btn/keys
[icon css-class mods label on-click
tooltip title tabindex type attrs]
:as params}]
(btn (update params :btn/mods conj ::cta-blue)))
(comment
(cta {:label "hey"}))
(defn icon [icon & [{:btn/keys [title managed-colors? danger? active? on-click round?] :as opts}]]
[:button
{:title (or title (name icon))
:class (bem/bem-str :button :icon
(if round? :round)
(if danger? :danger)
(if active? :active))
on-click-prop on-click}
[svgs/icon icon {:active? active? :danger? danger?
:managed-colors managed-colors?}]])
| |
6ec9cf5762806925badb5c77e69c97fc3357dec5da5e8ae0fb40581e9a17305a | 8c6794b6/haskell-sc-scratch | HelloAcid.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
|
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : portable
Example acid - state with HelloIxSet .
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : portable
Example acid-state with HelloIxSet.
-}
module HelloAcid where
import Data.Data
import Control.Monad.State
import Control.Monad.Reader
import Data.Acid
import Data.IxSet
import Data.SafeCopy
import HelloIxSet
data EntryIxSet = EntryIxSet (IxSet Entry)
deriving (Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''Id)
$(deriveSafeCopy 0 'base ''Author)
$(deriveSafeCopy 0 'base ''Updated)
$(deriveSafeCopy 0 'base ''Content)
$(deriveSafeCopy 0 'base ''Entry)
$(deriveSafeCopy 0 'base ''EntryIxSet)
saveEntries :: IxSet Entry -> Update EntryIxSet ()
saveEntries ixs = put (EntryIxSet ixs)
loadEntries :: Query EntryIxSet EntryIxSet
loadEntries = ask
$(makeAcidic ''EntryIxSet ['saveEntries, 'loadEntries]) | null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/DB/HelloAcid.hs | haskell | # LANGUAGE DeriveDataTypeable # | # LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
|
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : portable
Example acid - state with HelloIxSet .
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : portable
Example acid-state with HelloIxSet.
-}
module HelloAcid where
import Data.Data
import Control.Monad.State
import Control.Monad.Reader
import Data.Acid
import Data.IxSet
import Data.SafeCopy
import HelloIxSet
data EntryIxSet = EntryIxSet (IxSet Entry)
deriving (Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''Id)
$(deriveSafeCopy 0 'base ''Author)
$(deriveSafeCopy 0 'base ''Updated)
$(deriveSafeCopy 0 'base ''Content)
$(deriveSafeCopy 0 'base ''Entry)
$(deriveSafeCopy 0 'base ''EntryIxSet)
saveEntries :: IxSet Entry -> Update EntryIxSet ()
saveEntries ixs = put (EntryIxSet ixs)
loadEntries :: Query EntryIxSet EntryIxSet
loadEntries = ask
$(makeAcidic ''EntryIxSet ['saveEntries, 'loadEntries]) |
49084aafad151643d8eeff0e13c94174418ddcf2395503ba27a94037e455859d | yaxu/remake | Types.hs | module Sound.Tidal2.Types where
import Data.List (intersectBy, nub, (\\), intercalate)
import Data.Maybe (isJust)
import Sound.Tidal2.Pattern
-- ************************************************************ --
-- Types of types
data Type =
T_F Type Type
| T_String
| T_Float
| T_Int
| T_Rational
| T_Bool
| T_Map
| T_Pattern Type
| T_Constraint Int
| T_List Type
| T_SimpleList Type
deriving Eq
data Constraint =
C_OneOf [Type]
| C_WildCard
deriving Eq
instance Show Type where
show (T_F a b) = "(" ++ show a ++ " -> " ++ show b ++ ")"
show T_String = "s"
show T_Float = "f"
show T_Int = "i"
show T_Rational = "r"
show T_Bool = "#"
show T_Map = "map"
show (T_Pattern t) = "p [" ++ (show t) ++ "]"
show (T_Constraint n) = "constraint#" ++ (show n)
show (T_List t) = "list [" ++ (show t) ++ "]"
show (T_SimpleList t) = "simplelist [" ++ (show t) ++ "]"
instance Show Constraint where
show (C_OneOf ts) = "?" ++ show ts
show C_WildCard = "*"
-- Type signature
data Sig = Sig {constraints :: [Constraint],
is :: Type
}
deriving Eq
instance Show Sig where
show s = ps ++ (show $ is s)
where ps | constraints s == [] = ""
| otherwise = show (constraints s) ++ " => "
data Code =
Cd_Int Int | Cd_Rational Rational | Cd_String String | Cd_Float Float | Cd_Bool Bool |
Cd_App Code Code |
Cd_Op (Maybe Code) Code (Maybe Code) |
Cd_R R |
Cd_every | Cd_fast |
Cd_plus |
Cd_multiply |
Cd_divide |
Cd_subtract |
Cd_rev |
Cd_hash |
Cd_dollar |
Cd_pure |
Cd_name String
deriving (Show, Eq)
data R = R_Atom String
| R_Silence
| R_Subsequence [R]
| R_StackCycles [R]
| R_StackStep [R]
| R_StackSteps [R]
| R_Duration Code R
| R_Patterning Code R
deriving (Show, Eq)
data Fix = Prefix | Infix
functions : : [ ( String , ( Code , Fix , Sig ) ) ]
functions =
[ ( " + " , ( Tk_plus , Infix , numOp ) ) ,
( " * " , ( Tk_multiply , Infix , numOp ) ) ,
( " / " , ( Tk_divide , Infix , numOp ) ) ,
( " - " , ( Tk_subtract , Infix , numOp ) ) ,
( " # " , ( Tk_hash , Infix , ppOp ) ) ,
( " $ " , ( Tk_dollar , Infix , Sig [ C_WildCard , C_WildCard ] $ T_F ( T_F ( T_Constraint 0 ) ( T_Constraint 1 ) ) ( T_F ( T_Constraint 0 ) ( T_Constraint 1 ) ) ) ) ,
( " every " , ( Tk_every , Prefix , i_pf_p ) ) ,
( " rev " , ( Tk_rev , Prefix , pOp ) ) ,
( " pure " , ( Tk_pure , Prefix , Sig [ C_WildCard ] $ T_F ( T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) ) )
]
where pi_pf_p = Sig [ C_WildCard ] $ T_F ( T_Pattern T_Int )
( T_F ( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
)
i_pf_p = Sig [ C_WildCard ] $ T_F T_Int
( T_F ( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
)
numOp = Sig [ C_OneOf[T_Float , T_Int , T_Rational ] ]
$ T_F ( T_Constraint 0 ) $ T_F ( T_Constraint 0 ) ( T_Constraint 0 )
-- $ T_F ( T_Pattern $ T_Constraint 0 ) $ T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 )
sOp = Sig [ ] $ T_F ( T_Pattern $ T_String ) ( T_Pattern $ T_String )
pOp = Sig [ C_WildCard ] $ T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 )
[ C_WildCard ] $ T_F ( T_Pattern $ T_Constraint 0 ) $ T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 )
{ -
floatOp = Sig [ ] $ T_F ( T_Pattern T_Float ) ( T_F ( T_Pattern T_Float ) ( T_Pattern T_Float ) )
floatPat = Sig [ ] $ T_Pattern T_Float
mapper = Sig [ T_WildCard , T_WildCard ] $ T_F ( T_F ( T_Constraint 0 ) ( T_Constraint 1 ) ) $ T_F ( T_Pattern ( T_Constraint 0 ) ) ( T_Pattern ( T_Constraint 1 ) )
= Sig [ ] $ T_F ( T_Pattern T_String ) ( T_Pattern T_Map )
= Sig [ ] $ T_F ( T_Pattern T_Float ) ( T_Pattern T_Map )
number = OneOf [ Pattern Float , Pattern Int ]
number = T_Pattern ( T_OneOf[T_Float , T_Int ] )
functions =
[("+", (Tk_plus, Infix, numOp)),
("*", (Tk_multiply, Infix, numOp)),
("/", (Tk_divide, Infix, numOp)),
("-", (Tk_subtract, Infix, numOp)),
("#", (Tk_hash, Infix, ppOp)),
("$", (Tk_dollar, Infix, Sig [C_WildCard, C_WildCard] $ T_F (T_F (T_Constraint 0) (T_Constraint 1)) (T_F (T_Constraint 0) (T_Constraint 1)))),
("every", (Tk_every, Prefix, i_pf_p)),
("rev", (Tk_rev, Prefix, pOp)),
("pure", (Tk_pure, Prefix, Sig [C_WildCard] $ T_F (T_Constraint 0) (T_Pattern $ T_Constraint 0)))
]
where pi_pf_p = Sig [C_WildCard] $ T_F (T_Pattern T_Int)
(T_F (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
(T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
)
i_pf_p = Sig [C_WildCard] $ T_F T_Int
(T_F (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
(T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
)
numOp = Sig [C_OneOf[T_Float,T_Int,T_Rational]]
$ T_F (T_Constraint 0) $ T_F (T_Constraint 0) (T_Constraint 0)
-- $ T_F (T_Pattern $ T_Constraint 0) $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)
sOp = Sig [] $ T_F (T_Pattern $ T_String) (T_Pattern $ T_String)
pOp = Sig [C_WildCard] $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)
ppOp = Sig [C_WildCard] $ T_F (T_Pattern $ T_Constraint 0) $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)
{-
floatOp = Sig [] $ T_F (T_Pattern T_Float) (T_F (T_Pattern T_Float) (T_Pattern T_Float))
floatPat = Sig [] $ T_Pattern T_Float
mapper = Sig [T_WildCard, T_WildCard] $ T_F (T_F (T_Constraint 0) (T_Constraint 1)) $ T_F (T_Pattern (T_Constraint 0)) (T_Pattern (T_Constraint 1))
stringToPatMap = Sig [] $ T_F (T_Pattern T_String) (T_Pattern T_Map)
floatToPatMap = Sig [] $ T_F (T_Pattern T_Float) (T_Pattern T_Map)
number = OneOf [Pattern Float, Pattern Int]
number = T_Pattern (T_OneOf[T_Float,T_Int])
-}
-}
arity :: Type -> Int
arity (T_F _ b) = (arity b) + 1
arity _ = 0
isFn :: Type -> Bool
isFn (T_F _ _) = True
isFn _ = False
setAt :: [a] -> Int -> a -> [a]
setAt xs i x = take i xs ++ [x] ++ drop (i + 1) xs
fitsConstraint :: Type -> [Constraint]-> Int -> Bool
fitsConstraint t cs i | i >= length cs = error "Internal error - no such constraint"
| c == C_WildCard = True
| otherwise = or $ map (\t' -> fits' t $ Sig cs t') $ options c
where c = cs !! i
options (C_OneOf cs) = cs
options _ = [] -- can't happen..
fits' :: Type -> Sig -> Bool
fits' t s = isJust $ fits t s
fits :: Type -> Sig -> Maybe ([(Int, Type)])
fits t (Sig cs (T_Constraint i)) = if (fitsConstraint t cs i)
then Just [(i, t)]
else Nothing
fits (T_F arg result) (Sig c (T_F arg' result')) = do as <- fits arg (Sig c arg')
bs <- fits result (Sig c result')
return $ as ++ bs
fits (T_Pattern a) (Sig c (T_Pattern b)) = fits a (Sig c b)
fits (T_List a) (Sig c (T_List b)) = fits a (Sig c b)
fits a (Sig _ b) = if a == b
then Just []
else Nothing
-- How can b produce target a?
-- Will either return the target need, or a function that can
-- return it, or nothing.
fulfill :: Type -> Sig -> Maybe Type
fulfill n c = do (cs, t) <- fulfill' n c
resolveConstraint cs t
fulfill' :: Type -> Sig -> Maybe ([(Int, Type)], Type)
fulfill' need contender@(Sig c (T_F arg result))
| arityD == 0 = do cs <- fits need contender
return (cs, need)
| arityD > 0 = (T_F arg <$>) <$> fulfill' need (Sig c result)
| otherwise = Nothing
where arityD = arity (is contender) - arity need
fulfill' need contender = do cs <- fits need contender
return (cs, need)
resolveConstraint :: [(Int, Type)] -> Type -> Maybe Type
resolveConstraint cs (T_Constraint n) = lookup n cs
resolveConstraint cs (T_F a b)
= T_F <$> resolveConstraint cs a <*> resolveConstraint cs b
resolveConstraint cs (T_Pattern t) = T_Pattern <$> resolveConstraint cs t
resolveConstraint cs (T_List t) = T_List <$> resolveConstraint cs t
resolveConstraint _ t = Just t
| null | https://raw.githubusercontent.com/yaxu/remake/bc158cafcb2af3d0e639f25443e7b8ef4b98dbdc/src/Sound/Tidal2/Types.hs | haskell | ************************************************************ --
Types of types
Type signature
$ T_F ( T_Pattern $ T_Constraint 0 ) $ T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 )
$ T_F (T_Pattern $ T_Constraint 0) $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)
floatOp = Sig [] $ T_F (T_Pattern T_Float) (T_F (T_Pattern T_Float) (T_Pattern T_Float))
floatPat = Sig [] $ T_Pattern T_Float
mapper = Sig [T_WildCard, T_WildCard] $ T_F (T_F (T_Constraint 0) (T_Constraint 1)) $ T_F (T_Pattern (T_Constraint 0)) (T_Pattern (T_Constraint 1))
stringToPatMap = Sig [] $ T_F (T_Pattern T_String) (T_Pattern T_Map)
floatToPatMap = Sig [] $ T_F (T_Pattern T_Float) (T_Pattern T_Map)
number = OneOf [Pattern Float, Pattern Int]
number = T_Pattern (T_OneOf[T_Float,T_Int])
can't happen..
How can b produce target a?
Will either return the target need, or a function that can
return it, or nothing. | module Sound.Tidal2.Types where
import Data.List (intersectBy, nub, (\\), intercalate)
import Data.Maybe (isJust)
import Sound.Tidal2.Pattern
data Type =
T_F Type Type
| T_String
| T_Float
| T_Int
| T_Rational
| T_Bool
| T_Map
| T_Pattern Type
| T_Constraint Int
| T_List Type
| T_SimpleList Type
deriving Eq
data Constraint =
C_OneOf [Type]
| C_WildCard
deriving Eq
instance Show Type where
show (T_F a b) = "(" ++ show a ++ " -> " ++ show b ++ ")"
show T_String = "s"
show T_Float = "f"
show T_Int = "i"
show T_Rational = "r"
show T_Bool = "#"
show T_Map = "map"
show (T_Pattern t) = "p [" ++ (show t) ++ "]"
show (T_Constraint n) = "constraint#" ++ (show n)
show (T_List t) = "list [" ++ (show t) ++ "]"
show (T_SimpleList t) = "simplelist [" ++ (show t) ++ "]"
instance Show Constraint where
show (C_OneOf ts) = "?" ++ show ts
show C_WildCard = "*"
data Sig = Sig {constraints :: [Constraint],
is :: Type
}
deriving Eq
instance Show Sig where
show s = ps ++ (show $ is s)
where ps | constraints s == [] = ""
| otherwise = show (constraints s) ++ " => "
data Code =
Cd_Int Int | Cd_Rational Rational | Cd_String String | Cd_Float Float | Cd_Bool Bool |
Cd_App Code Code |
Cd_Op (Maybe Code) Code (Maybe Code) |
Cd_R R |
Cd_every | Cd_fast |
Cd_plus |
Cd_multiply |
Cd_divide |
Cd_subtract |
Cd_rev |
Cd_hash |
Cd_dollar |
Cd_pure |
Cd_name String
deriving (Show, Eq)
data R = R_Atom String
| R_Silence
| R_Subsequence [R]
| R_StackCycles [R]
| R_StackStep [R]
| R_StackSteps [R]
| R_Duration Code R
| R_Patterning Code R
deriving (Show, Eq)
data Fix = Prefix | Infix
functions : : [ ( String , ( Code , Fix , Sig ) ) ]
functions =
[ ( " + " , ( Tk_plus , Infix , numOp ) ) ,
( " * " , ( Tk_multiply , Infix , numOp ) ) ,
( " / " , ( Tk_divide , Infix , numOp ) ) ,
( " - " , ( Tk_subtract , Infix , numOp ) ) ,
( " # " , ( Tk_hash , Infix , ppOp ) ) ,
( " $ " , ( Tk_dollar , Infix , Sig [ C_WildCard , C_WildCard ] $ T_F ( T_F ( T_Constraint 0 ) ( T_Constraint 1 ) ) ( T_F ( T_Constraint 0 ) ( T_Constraint 1 ) ) ) ) ,
( " every " , ( Tk_every , Prefix , i_pf_p ) ) ,
( " rev " , ( Tk_rev , Prefix , pOp ) ) ,
( " pure " , ( Tk_pure , Prefix , Sig [ C_WildCard ] $ T_F ( T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) ) )
]
where pi_pf_p = Sig [ C_WildCard ] $ T_F ( T_Pattern T_Int )
( T_F ( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
)
i_pf_p = Sig [ C_WildCard ] $ T_F T_Int
( T_F ( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
( T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 ) )
)
numOp = Sig [ C_OneOf[T_Float , T_Int , T_Rational ] ]
$ T_F ( T_Constraint 0 ) $ T_F ( T_Constraint 0 ) ( T_Constraint 0 )
sOp = Sig [ ] $ T_F ( T_Pattern $ T_String ) ( T_Pattern $ T_String )
pOp = Sig [ C_WildCard ] $ T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 )
[ C_WildCard ] $ T_F ( T_Pattern $ T_Constraint 0 ) $ T_F ( T_Pattern $ T_Constraint 0 ) ( T_Pattern $ T_Constraint 0 )
{ -
floatOp = Sig [ ] $ T_F ( T_Pattern T_Float ) ( T_F ( T_Pattern T_Float ) ( T_Pattern T_Float ) )
floatPat = Sig [ ] $ T_Pattern T_Float
mapper = Sig [ T_WildCard , T_WildCard ] $ T_F ( T_F ( T_Constraint 0 ) ( T_Constraint 1 ) ) $ T_F ( T_Pattern ( T_Constraint 0 ) ) ( T_Pattern ( T_Constraint 1 ) )
= Sig [ ] $ T_F ( T_Pattern T_String ) ( T_Pattern T_Map )
= Sig [ ] $ T_F ( T_Pattern T_Float ) ( T_Pattern T_Map )
number = OneOf [ Pattern Float , Pattern Int ]
number = T_Pattern ( T_OneOf[T_Float , T_Int ] )
functions =
[("+", (Tk_plus, Infix, numOp)),
("*", (Tk_multiply, Infix, numOp)),
("/", (Tk_divide, Infix, numOp)),
("-", (Tk_subtract, Infix, numOp)),
("#", (Tk_hash, Infix, ppOp)),
("$", (Tk_dollar, Infix, Sig [C_WildCard, C_WildCard] $ T_F (T_F (T_Constraint 0) (T_Constraint 1)) (T_F (T_Constraint 0) (T_Constraint 1)))),
("every", (Tk_every, Prefix, i_pf_p)),
("rev", (Tk_rev, Prefix, pOp)),
("pure", (Tk_pure, Prefix, Sig [C_WildCard] $ T_F (T_Constraint 0) (T_Pattern $ T_Constraint 0)))
]
where pi_pf_p = Sig [C_WildCard] $ T_F (T_Pattern T_Int)
(T_F (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
(T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
)
i_pf_p = Sig [C_WildCard] $ T_F T_Int
(T_F (T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
(T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0))
)
numOp = Sig [C_OneOf[T_Float,T_Int,T_Rational]]
$ T_F (T_Constraint 0) $ T_F (T_Constraint 0) (T_Constraint 0)
sOp = Sig [] $ T_F (T_Pattern $ T_String) (T_Pattern $ T_String)
pOp = Sig [C_WildCard] $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)
ppOp = Sig [C_WildCard] $ T_F (T_Pattern $ T_Constraint 0) $ T_F (T_Pattern $ T_Constraint 0) (T_Pattern $ T_Constraint 0)
-}
arity :: Type -> Int
arity (T_F _ b) = (arity b) + 1
arity _ = 0
isFn :: Type -> Bool
isFn (T_F _ _) = True
isFn _ = False
setAt :: [a] -> Int -> a -> [a]
setAt xs i x = take i xs ++ [x] ++ drop (i + 1) xs
fitsConstraint :: Type -> [Constraint]-> Int -> Bool
fitsConstraint t cs i | i >= length cs = error "Internal error - no such constraint"
| c == C_WildCard = True
| otherwise = or $ map (\t' -> fits' t $ Sig cs t') $ options c
where c = cs !! i
options (C_OneOf cs) = cs
fits' :: Type -> Sig -> Bool
fits' t s = isJust $ fits t s
fits :: Type -> Sig -> Maybe ([(Int, Type)])
fits t (Sig cs (T_Constraint i)) = if (fitsConstraint t cs i)
then Just [(i, t)]
else Nothing
fits (T_F arg result) (Sig c (T_F arg' result')) = do as <- fits arg (Sig c arg')
bs <- fits result (Sig c result')
return $ as ++ bs
fits (T_Pattern a) (Sig c (T_Pattern b)) = fits a (Sig c b)
fits (T_List a) (Sig c (T_List b)) = fits a (Sig c b)
fits a (Sig _ b) = if a == b
then Just []
else Nothing
fulfill :: Type -> Sig -> Maybe Type
fulfill n c = do (cs, t) <- fulfill' n c
resolveConstraint cs t
fulfill' :: Type -> Sig -> Maybe ([(Int, Type)], Type)
fulfill' need contender@(Sig c (T_F arg result))
| arityD == 0 = do cs <- fits need contender
return (cs, need)
| arityD > 0 = (T_F arg <$>) <$> fulfill' need (Sig c result)
| otherwise = Nothing
where arityD = arity (is contender) - arity need
fulfill' need contender = do cs <- fits need contender
return (cs, need)
resolveConstraint :: [(Int, Type)] -> Type -> Maybe Type
resolveConstraint cs (T_Constraint n) = lookup n cs
resolveConstraint cs (T_F a b)
= T_F <$> resolveConstraint cs a <*> resolveConstraint cs b
resolveConstraint cs (T_Pattern t) = T_Pattern <$> resolveConstraint cs t
resolveConstraint cs (T_List t) = T_List <$> resolveConstraint cs t
resolveConstraint _ t = Just t
|
9e3fbf198ca646fe6f0f017c78087428a49dbb2ddf7cfa8ee7fb1f35f2a10d52 | jberryman/directory-tree | Test.hs | module Main
where
do a quick test for :
import System.Directory.Tree
import Control.Applicative
import qualified Data.Foldable as F
import System.Directory
import System.Process
import System.IO.Error(ioeGetErrorType,isPermissionErrorType)
import Control.Monad(void)
testDir :: FilePath
testDir = "/tmp/TESTDIR-LKJHBAE"
main :: IO ()
main = do
putStrLn "-- The following tests will either fail with an error "
putStrLn "-- message or with an 'undefined' error"
-- write our testing directory structure to disk. We include Failed
-- constructors which should be discarded:
_:/written <- writeDirectory testTree
putStrLn "OK"
if (fmap (const ()) (filterDir (not . failed) $dirTree testTree)) ==
filterDir (not . failed) written
then return ()
else error "writeDirectory returned a tree that didn't match"
putStrLn "OK"
-- make file farthest to the right unreadable:
(Dir _ [_,_,Dir "C" [_,_,File "G" p_unreadable]]) <- sortDir . dirTree <$> build testDir
setPermissions p_unreadable emptyPermissions{readable = False,
writable = True,
executable = True,
searchable = True}
putStrLn "OK"
-- read with lazy and standard functions, compare for equality. Also test that our crazy
-- operator works correctly inline with <$>:
tL <- readDirectoryWithL readFile testDir
t@(_:/Dir _ [_,_,Dir "C" [unreadable_constr,_,_]]) <- sortDir </$> id <$> readDirectory testDir
if t == tL then return () else error "lazy read /= standard read"
putStrLn "OK"
-- make sure the unreadable file left the correct error type in a Failed:
if isPermissionErrorType $ ioeGetErrorType $ err unreadable_constr
then return ()
else error "wrong error type for Failed file read"
putStrLn "OK"
-- run lazy fold, concating file contents. compare for equality:
tL_again <- sortDir </$> readDirectoryWithL readFile testDir
let tL_concated = F.concat $ dirTree tL_again
if tL_concated == "abcdef" then return () else error "foldable broke"
putStrLn "OK"
-- get a lazy DirTree at root directory with lazy Directory traversal:
putStrLn "-- If lazy IO is not working, we should be stalled right now "
putStrLn "-- as we try to read in the whole root directory tree."
putStrLn "-- Go ahead and press CTRL-C if you've read this far"
mapM_ putStr =<< (map name . contents . dirTree) <$> readDirectoryWithL readFile "/"
putStrLn "\nOK"
let undefinedOrdFailed = Failed undefined undefined :: DirTree Char
undefinedOrdDir = Dir undefined undefined :: DirTree Char
undefinedOrdFile = File undefined undefined :: DirTree Char
-- simple equality and sorting
if Dir "d" [File "b" "b",File "a" "a"] == Dir "d" [File "a" "a", File "b" "b"] &&
recursive sort order , enforces non - recursive sorting of Dirs
Dir "d" [Dir "b" undefined,File "a" "a"] /= Dir "d" [File "a" "a", Dir "c" undefined] &&
-- check ordering of constructors:
undefinedOrdFailed < undefinedOrdDir &&
undefinedOrdDir < undefinedOrdFile &&
-- check ordering by dir contents list length:
Dir "d" [File "b" "b",File "a" "a"] > Dir "d" [File "a" "a"] &&
-- recursive ordering on contents:
Dir "d" [File "b" "b", Dir "c" [File "a" "b"]] > Dir "d" [File "b" "b", Dir "c" [File "a" "a"]]
then putStrLn "OK"
else error "Ord/Eq instance is messed up"
if Dir "d" [File "b" "b",File "a" "a"] `equalShape` Dir "d" [File "a" undefined, File "b" undefined]
then putStrLn "OK"
else error "equalShape or comparinghape functions broken"
-- clean up by removing the directory:
void $ system $ "rm -r " ++ testDir
putStrLn "SUCCESS"
testTree :: AnchoredDirTree String
testTree = "" :/ Dir testDir [dA , dB , dC , Failed "FAAAIIILL" undefined]
where dA = Dir "A" [dA1 , dA2 , Failed "FAIL" undefined]
dA1 = Dir "A1" [File "A" "a", File "B" "b"]
dA2 = Dir "A2" [File "C" "c"]
dB = Dir "B" [File "D" "d"]
dC = Dir "C" [File "E" "e", File "F" "f", File "G" "g"]
| null | https://raw.githubusercontent.com/jberryman/directory-tree/bfd31a37ba4af34ed25b2e55865db8c30b175510/Test.hs | haskell | write our testing directory structure to disk. We include Failed
constructors which should be discarded:
make file farthest to the right unreadable:
read with lazy and standard functions, compare for equality. Also test that our crazy
operator works correctly inline with <$>:
make sure the unreadable file left the correct error type in a Failed:
run lazy fold, concating file contents. compare for equality:
get a lazy DirTree at root directory with lazy Directory traversal:
simple equality and sorting
check ordering of constructors:
check ordering by dir contents list length:
recursive ordering on contents:
clean up by removing the directory: | module Main
where
do a quick test for :
import System.Directory.Tree
import Control.Applicative
import qualified Data.Foldable as F
import System.Directory
import System.Process
import System.IO.Error(ioeGetErrorType,isPermissionErrorType)
import Control.Monad(void)
testDir :: FilePath
testDir = "/tmp/TESTDIR-LKJHBAE"
main :: IO ()
main = do
putStrLn "-- The following tests will either fail with an error "
putStrLn "-- message or with an 'undefined' error"
_:/written <- writeDirectory testTree
putStrLn "OK"
if (fmap (const ()) (filterDir (not . failed) $dirTree testTree)) ==
filterDir (not . failed) written
then return ()
else error "writeDirectory returned a tree that didn't match"
putStrLn "OK"
(Dir _ [_,_,Dir "C" [_,_,File "G" p_unreadable]]) <- sortDir . dirTree <$> build testDir
setPermissions p_unreadable emptyPermissions{readable = False,
writable = True,
executable = True,
searchable = True}
putStrLn "OK"
tL <- readDirectoryWithL readFile testDir
t@(_:/Dir _ [_,_,Dir "C" [unreadable_constr,_,_]]) <- sortDir </$> id <$> readDirectory testDir
if t == tL then return () else error "lazy read /= standard read"
putStrLn "OK"
if isPermissionErrorType $ ioeGetErrorType $ err unreadable_constr
then return ()
else error "wrong error type for Failed file read"
putStrLn "OK"
tL_again <- sortDir </$> readDirectoryWithL readFile testDir
let tL_concated = F.concat $ dirTree tL_again
if tL_concated == "abcdef" then return () else error "foldable broke"
putStrLn "OK"
putStrLn "-- If lazy IO is not working, we should be stalled right now "
putStrLn "-- as we try to read in the whole root directory tree."
putStrLn "-- Go ahead and press CTRL-C if you've read this far"
mapM_ putStr =<< (map name . contents . dirTree) <$> readDirectoryWithL readFile "/"
putStrLn "\nOK"
let undefinedOrdFailed = Failed undefined undefined :: DirTree Char
undefinedOrdDir = Dir undefined undefined :: DirTree Char
undefinedOrdFile = File undefined undefined :: DirTree Char
if Dir "d" [File "b" "b",File "a" "a"] == Dir "d" [File "a" "a", File "b" "b"] &&
recursive sort order , enforces non - recursive sorting of Dirs
Dir "d" [Dir "b" undefined,File "a" "a"] /= Dir "d" [File "a" "a", Dir "c" undefined] &&
undefinedOrdFailed < undefinedOrdDir &&
undefinedOrdDir < undefinedOrdFile &&
Dir "d" [File "b" "b",File "a" "a"] > Dir "d" [File "a" "a"] &&
Dir "d" [File "b" "b", Dir "c" [File "a" "b"]] > Dir "d" [File "b" "b", Dir "c" [File "a" "a"]]
then putStrLn "OK"
else error "Ord/Eq instance is messed up"
if Dir "d" [File "b" "b",File "a" "a"] `equalShape` Dir "d" [File "a" undefined, File "b" undefined]
then putStrLn "OK"
else error "equalShape or comparinghape functions broken"
void $ system $ "rm -r " ++ testDir
putStrLn "SUCCESS"
testTree :: AnchoredDirTree String
testTree = "" :/ Dir testDir [dA , dB , dC , Failed "FAAAIIILL" undefined]
where dA = Dir "A" [dA1 , dA2 , Failed "FAIL" undefined]
dA1 = Dir "A1" [File "A" "a", File "B" "b"]
dA2 = Dir "A2" [File "C" "c"]
dB = Dir "B" [File "D" "d"]
dC = Dir "C" [File "E" "e", File "F" "f", File "G" "g"]
|
1cb8246d0314764827b2c6ce11f7c1cc2b77194591111303bb987cf18133e436 | brendanzab/language-garden | Cpu.mli | (** {0 CPU based shader language} *)
* This implements a shader language natively in OCaml . This is useful for
testing the shader language and SDFs without needing to interface with
graphics APIs . It could also be useful for implementing constant folding
optimisations in the future .
testing the shader language and SDFs without needing to interface with
graphics APIs. It could also be useful for implementing constant folding
optimisations in the future. *)
open ShaderTypes
include Shader.S with type 'a repr = 'a
(** An image shader to be run on the CPU. The function takes a pixel (fragment)
coordinate as an argument and returns the color that should be rendered at
that pixel. *)
type image_shader = vec2f repr -> vec3f repr
* Render the shader sequentially on the CPU to a PPM image file , using a
coordinate system that starts from the bottom - left corner of the screen
for compatibility with OpenGL and Vulkan style shaders .
coordinate system that starts from the bottom-left corner of the screen
for compatibility with OpenGL and Vulkan style shaders. *)
val render_ppm : width:int -> height:int -> image_shader -> unit
| null | https://raw.githubusercontent.com/brendanzab/language-garden/d73b3e95dc7206f02c2a8ecc96c7aac10db4cc9e/lang-shader-graphics/lib/Cpu.mli | ocaml | * {0 CPU based shader language}
* An image shader to be run on the CPU. The function takes a pixel (fragment)
coordinate as an argument and returns the color that should be rendered at
that pixel. |
* This implements a shader language natively in OCaml . This is useful for
testing the shader language and SDFs without needing to interface with
graphics APIs . It could also be useful for implementing constant folding
optimisations in the future .
testing the shader language and SDFs without needing to interface with
graphics APIs. It could also be useful for implementing constant folding
optimisations in the future. *)
open ShaderTypes
include Shader.S with type 'a repr = 'a
type image_shader = vec2f repr -> vec3f repr
* Render the shader sequentially on the CPU to a PPM image file , using a
coordinate system that starts from the bottom - left corner of the screen
for compatibility with OpenGL and Vulkan style shaders .
coordinate system that starts from the bottom-left corner of the screen
for compatibility with OpenGL and Vulkan style shaders. *)
val render_ppm : width:int -> height:int -> image_shader -> unit
|
721ff6a78f217a5a8d939a4868b274f0ef5655df3320826bfcd1428e82a0f128 | brendanhay/amazonka | CreateAssistant.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
-- Module : Amazonka.Wisdom.CreateAssistant
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
Creates an Amazon Connect Wisdom assistant .
module Amazonka.Wisdom.CreateAssistant
( -- * Creating a Request
CreateAssistant (..),
newCreateAssistant,
-- * Request Lenses
createAssistant_clientToken,
createAssistant_description,
createAssistant_serverSideEncryptionConfiguration,
createAssistant_tags,
createAssistant_name,
createAssistant_type,
-- * Destructuring the Response
CreateAssistantResponse (..),
newCreateAssistantResponse,
-- * Response Lenses
createAssistantResponse_assistant,
createAssistantResponse_httpStatus,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.Wisdom.Types
-- | /See:/ 'newCreateAssistant' smart constructor.
data CreateAssistant = CreateAssistant'
{ -- | A unique, case-sensitive identifier that you provide to ensure the
-- idempotency of the request.
clientToken :: Prelude.Maybe Prelude.Text,
-- | The description of the assistant.
description :: Prelude.Maybe Prelude.Text,
| The KMS key used for encryption .
serverSideEncryptionConfiguration :: Prelude.Maybe ServerSideEncryptionConfiguration,
-- | The tags used to organize, track, or control access for this resource.
tags :: Prelude.Maybe (Prelude.HashMap Prelude.Text Prelude.Text),
-- | The name of the assistant.
name :: Prelude.Text,
-- | The type of assistant.
type' :: AssistantType
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'CreateAssistant' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
' clientToken ' , ' createAssistant_clientToken ' - A unique , case - sensitive identifier that you provide to ensure the
-- idempotency of the request.
--
-- 'description', 'createAssistant_description' - The description of the assistant.
--
' serverSideEncryptionConfiguration ' , ' createAssistant_serverSideEncryptionConfiguration ' - The KMS key used for encryption .
--
-- 'tags', 'createAssistant_tags' - The tags used to organize, track, or control access for this resource.
--
-- 'name', 'createAssistant_name' - The name of the assistant.
--
-- 'type'', 'createAssistant_type' - The type of assistant.
newCreateAssistant ::
-- | 'name'
Prelude.Text ->
-- | 'type''
AssistantType ->
CreateAssistant
newCreateAssistant pName_ pType_ =
CreateAssistant'
{ clientToken = Prelude.Nothing,
description = Prelude.Nothing,
serverSideEncryptionConfiguration = Prelude.Nothing,
tags = Prelude.Nothing,
name = pName_,
type' = pType_
}
-- | A unique, case-sensitive identifier that you provide to ensure the
-- idempotency of the request.
createAssistant_clientToken :: Lens.Lens' CreateAssistant (Prelude.Maybe Prelude.Text)
createAssistant_clientToken = Lens.lens (\CreateAssistant' {clientToken} -> clientToken) (\s@CreateAssistant' {} a -> s {clientToken = a} :: CreateAssistant)
-- | The description of the assistant.
createAssistant_description :: Lens.Lens' CreateAssistant (Prelude.Maybe Prelude.Text)
createAssistant_description = Lens.lens (\CreateAssistant' {description} -> description) (\s@CreateAssistant' {} a -> s {description = a} :: CreateAssistant)
| The KMS key used for encryption .
createAssistant_serverSideEncryptionConfiguration :: Lens.Lens' CreateAssistant (Prelude.Maybe ServerSideEncryptionConfiguration)
createAssistant_serverSideEncryptionConfiguration = Lens.lens (\CreateAssistant' {serverSideEncryptionConfiguration} -> serverSideEncryptionConfiguration) (\s@CreateAssistant' {} a -> s {serverSideEncryptionConfiguration = a} :: CreateAssistant)
-- | The tags used to organize, track, or control access for this resource.
createAssistant_tags :: Lens.Lens' CreateAssistant (Prelude.Maybe (Prelude.HashMap Prelude.Text Prelude.Text))
createAssistant_tags = Lens.lens (\CreateAssistant' {tags} -> tags) (\s@CreateAssistant' {} a -> s {tags = a} :: CreateAssistant) Prelude.. Lens.mapping Lens.coerced
-- | The name of the assistant.
createAssistant_name :: Lens.Lens' CreateAssistant Prelude.Text
createAssistant_name = Lens.lens (\CreateAssistant' {name} -> name) (\s@CreateAssistant' {} a -> s {name = a} :: CreateAssistant)
-- | The type of assistant.
createAssistant_type :: Lens.Lens' CreateAssistant AssistantType
createAssistant_type = Lens.lens (\CreateAssistant' {type'} -> type') (\s@CreateAssistant' {} a -> s {type' = a} :: CreateAssistant)
instance Core.AWSRequest CreateAssistant where
type
AWSResponse CreateAssistant =
CreateAssistantResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
CreateAssistantResponse'
Prelude.<$> (x Data..?> "assistant")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
)
instance Prelude.Hashable CreateAssistant where
hashWithSalt _salt CreateAssistant' {..} =
_salt `Prelude.hashWithSalt` clientToken
`Prelude.hashWithSalt` description
`Prelude.hashWithSalt` serverSideEncryptionConfiguration
`Prelude.hashWithSalt` tags
`Prelude.hashWithSalt` name
`Prelude.hashWithSalt` type'
instance Prelude.NFData CreateAssistant where
rnf CreateAssistant' {..} =
Prelude.rnf clientToken
`Prelude.seq` Prelude.rnf description
`Prelude.seq` Prelude.rnf serverSideEncryptionConfiguration
`Prelude.seq` Prelude.rnf tags
`Prelude.seq` Prelude.rnf name
`Prelude.seq` Prelude.rnf type'
instance Data.ToHeaders CreateAssistant where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToJSON CreateAssistant where
toJSON CreateAssistant' {..} =
Data.object
( Prelude.catMaybes
[ ("clientToken" Data..=) Prelude.<$> clientToken,
("description" Data..=) Prelude.<$> description,
("serverSideEncryptionConfiguration" Data..=)
Prelude.<$> serverSideEncryptionConfiguration,
("tags" Data..=) Prelude.<$> tags,
Prelude.Just ("name" Data..= name),
Prelude.Just ("type" Data..= type')
]
)
instance Data.ToPath CreateAssistant where
toPath = Prelude.const "/assistants"
instance Data.ToQuery CreateAssistant where
toQuery = Prelude.const Prelude.mempty
-- | /See:/ 'newCreateAssistantResponse' smart constructor.
data CreateAssistantResponse = CreateAssistantResponse'
{ -- | Information about the assistant.
assistant :: Prelude.Maybe AssistantData,
-- | The response's http status code.
httpStatus :: Prelude.Int
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'CreateAssistantResponse' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
-- 'assistant', 'createAssistantResponse_assistant' - Information about the assistant.
--
-- 'httpStatus', 'createAssistantResponse_httpStatus' - The response's http status code.
newCreateAssistantResponse ::
-- | 'httpStatus'
Prelude.Int ->
CreateAssistantResponse
newCreateAssistantResponse pHttpStatus_ =
CreateAssistantResponse'
{ assistant =
Prelude.Nothing,
httpStatus = pHttpStatus_
}
-- | Information about the assistant.
createAssistantResponse_assistant :: Lens.Lens' CreateAssistantResponse (Prelude.Maybe AssistantData)
createAssistantResponse_assistant = Lens.lens (\CreateAssistantResponse' {assistant} -> assistant) (\s@CreateAssistantResponse' {} a -> s {assistant = a} :: CreateAssistantResponse)
-- | The response's http status code.
createAssistantResponse_httpStatus :: Lens.Lens' CreateAssistantResponse Prelude.Int
createAssistantResponse_httpStatus = Lens.lens (\CreateAssistantResponse' {httpStatus} -> httpStatus) (\s@CreateAssistantResponse' {} a -> s {httpStatus = a} :: CreateAssistantResponse)
instance Prelude.NFData CreateAssistantResponse where
rnf CreateAssistantResponse' {..} =
Prelude.rnf assistant
`Prelude.seq` Prelude.rnf httpStatus
| null | https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-wisdom/gen/Amazonka/Wisdom/CreateAssistant.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Module : Amazonka.Wisdom.CreateAssistant
Stability : auto-generated
* Creating a Request
* Request Lenses
* Destructuring the Response
* Response Lenses
| /See:/ 'newCreateAssistant' smart constructor.
| A unique, case-sensitive identifier that you provide to ensure the
idempotency of the request.
| The description of the assistant.
| The tags used to organize, track, or control access for this resource.
| The name of the assistant.
| The type of assistant.
|
Create a value of 'CreateAssistant' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
idempotency of the request.
'description', 'createAssistant_description' - The description of the assistant.
'tags', 'createAssistant_tags' - The tags used to organize, track, or control access for this resource.
'name', 'createAssistant_name' - The name of the assistant.
'type'', 'createAssistant_type' - The type of assistant.
| 'name'
| 'type''
| A unique, case-sensitive identifier that you provide to ensure the
idempotency of the request.
| The description of the assistant.
| The tags used to organize, track, or control access for this resource.
| The name of the assistant.
| The type of assistant.
| /See:/ 'newCreateAssistantResponse' smart constructor.
| Information about the assistant.
| The response's http status code.
|
Create a value of 'CreateAssistantResponse' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'assistant', 'createAssistantResponse_assistant' - Information about the assistant.
'httpStatus', 'createAssistantResponse_httpStatus' - The response's http status code.
| 'httpStatus'
| Information about the assistant.
| The response's http status code. | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
Creates an Amazon Connect Wisdom assistant .
module Amazonka.Wisdom.CreateAssistant
CreateAssistant (..),
newCreateAssistant,
createAssistant_clientToken,
createAssistant_description,
createAssistant_serverSideEncryptionConfiguration,
createAssistant_tags,
createAssistant_name,
createAssistant_type,
CreateAssistantResponse (..),
newCreateAssistantResponse,
createAssistantResponse_assistant,
createAssistantResponse_httpStatus,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.Wisdom.Types
data CreateAssistant = CreateAssistant'
clientToken :: Prelude.Maybe Prelude.Text,
description :: Prelude.Maybe Prelude.Text,
| The KMS key used for encryption .
serverSideEncryptionConfiguration :: Prelude.Maybe ServerSideEncryptionConfiguration,
tags :: Prelude.Maybe (Prelude.HashMap Prelude.Text Prelude.Text),
name :: Prelude.Text,
type' :: AssistantType
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' clientToken ' , ' createAssistant_clientToken ' - A unique , case - sensitive identifier that you provide to ensure the
' serverSideEncryptionConfiguration ' , ' createAssistant_serverSideEncryptionConfiguration ' - The KMS key used for encryption .
newCreateAssistant ::
Prelude.Text ->
AssistantType ->
CreateAssistant
newCreateAssistant pName_ pType_ =
CreateAssistant'
{ clientToken = Prelude.Nothing,
description = Prelude.Nothing,
serverSideEncryptionConfiguration = Prelude.Nothing,
tags = Prelude.Nothing,
name = pName_,
type' = pType_
}
createAssistant_clientToken :: Lens.Lens' CreateAssistant (Prelude.Maybe Prelude.Text)
createAssistant_clientToken = Lens.lens (\CreateAssistant' {clientToken} -> clientToken) (\s@CreateAssistant' {} a -> s {clientToken = a} :: CreateAssistant)
createAssistant_description :: Lens.Lens' CreateAssistant (Prelude.Maybe Prelude.Text)
createAssistant_description = Lens.lens (\CreateAssistant' {description} -> description) (\s@CreateAssistant' {} a -> s {description = a} :: CreateAssistant)
| The KMS key used for encryption .
createAssistant_serverSideEncryptionConfiguration :: Lens.Lens' CreateAssistant (Prelude.Maybe ServerSideEncryptionConfiguration)
createAssistant_serverSideEncryptionConfiguration = Lens.lens (\CreateAssistant' {serverSideEncryptionConfiguration} -> serverSideEncryptionConfiguration) (\s@CreateAssistant' {} a -> s {serverSideEncryptionConfiguration = a} :: CreateAssistant)
createAssistant_tags :: Lens.Lens' CreateAssistant (Prelude.Maybe (Prelude.HashMap Prelude.Text Prelude.Text))
createAssistant_tags = Lens.lens (\CreateAssistant' {tags} -> tags) (\s@CreateAssistant' {} a -> s {tags = a} :: CreateAssistant) Prelude.. Lens.mapping Lens.coerced
createAssistant_name :: Lens.Lens' CreateAssistant Prelude.Text
createAssistant_name = Lens.lens (\CreateAssistant' {name} -> name) (\s@CreateAssistant' {} a -> s {name = a} :: CreateAssistant)
createAssistant_type :: Lens.Lens' CreateAssistant AssistantType
createAssistant_type = Lens.lens (\CreateAssistant' {type'} -> type') (\s@CreateAssistant' {} a -> s {type' = a} :: CreateAssistant)
instance Core.AWSRequest CreateAssistant where
type
AWSResponse CreateAssistant =
CreateAssistantResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
CreateAssistantResponse'
Prelude.<$> (x Data..?> "assistant")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
)
instance Prelude.Hashable CreateAssistant where
hashWithSalt _salt CreateAssistant' {..} =
_salt `Prelude.hashWithSalt` clientToken
`Prelude.hashWithSalt` description
`Prelude.hashWithSalt` serverSideEncryptionConfiguration
`Prelude.hashWithSalt` tags
`Prelude.hashWithSalt` name
`Prelude.hashWithSalt` type'
instance Prelude.NFData CreateAssistant where
rnf CreateAssistant' {..} =
Prelude.rnf clientToken
`Prelude.seq` Prelude.rnf description
`Prelude.seq` Prelude.rnf serverSideEncryptionConfiguration
`Prelude.seq` Prelude.rnf tags
`Prelude.seq` Prelude.rnf name
`Prelude.seq` Prelude.rnf type'
instance Data.ToHeaders CreateAssistant where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToJSON CreateAssistant where
toJSON CreateAssistant' {..} =
Data.object
( Prelude.catMaybes
[ ("clientToken" Data..=) Prelude.<$> clientToken,
("description" Data..=) Prelude.<$> description,
("serverSideEncryptionConfiguration" Data..=)
Prelude.<$> serverSideEncryptionConfiguration,
("tags" Data..=) Prelude.<$> tags,
Prelude.Just ("name" Data..= name),
Prelude.Just ("type" Data..= type')
]
)
instance Data.ToPath CreateAssistant where
toPath = Prelude.const "/assistants"
instance Data.ToQuery CreateAssistant where
toQuery = Prelude.const Prelude.mempty
data CreateAssistantResponse = CreateAssistantResponse'
assistant :: Prelude.Maybe AssistantData,
httpStatus :: Prelude.Int
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
newCreateAssistantResponse ::
Prelude.Int ->
CreateAssistantResponse
newCreateAssistantResponse pHttpStatus_ =
CreateAssistantResponse'
{ assistant =
Prelude.Nothing,
httpStatus = pHttpStatus_
}
createAssistantResponse_assistant :: Lens.Lens' CreateAssistantResponse (Prelude.Maybe AssistantData)
createAssistantResponse_assistant = Lens.lens (\CreateAssistantResponse' {assistant} -> assistant) (\s@CreateAssistantResponse' {} a -> s {assistant = a} :: CreateAssistantResponse)
createAssistantResponse_httpStatus :: Lens.Lens' CreateAssistantResponse Prelude.Int
createAssistantResponse_httpStatus = Lens.lens (\CreateAssistantResponse' {httpStatus} -> httpStatus) (\s@CreateAssistantResponse' {} a -> s {httpStatus = a} :: CreateAssistantResponse)
instance Prelude.NFData CreateAssistantResponse where
rnf CreateAssistantResponse' {..} =
Prelude.rnf assistant
`Prelude.seq` Prelude.rnf httpStatus
|
d007d4629e91bfaa543cab8e0b36c20dadd8321e56aed1bad3bd90c7c7050586 | HunterYIboHu/htdp2-solution | ex454-create-matrix.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex454-create-matrix) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; constants
(define lon-1 '(1 2 3 4))
(define lon-2 '(1 2 3 4 5 6 7 8 9))
(define matrix-1 '((1 2)
(3 4)))
(define matrix-2 '((1 2 3)
(4 5 6)
(7 8 9)))
;; functions
; N [List-of Number] -> [List-of [List-of Number]]
; prodcues a n x n matrix which is represented as list of list.
assume ( 1 ) the given lon 's length is ( sqr n )
( 2 ) the result consists of n list whose length is n.
(check-expect (create-matrix 2 lon-1) matrix-1)
(check-expect (create-matrix 3 lon-2) matrix-2)
(define (create-matrix num l)
(local (; N [List-of Number] -> [List-of [List-of Number]]
; help create matrix by unregularly create lol.
(define (create-matrix/auxi n lon)
(cond [(empty? lon) '()]
[else (cons (first-line n lon)
(create-matrix/auxi
n
(remove-first-line n lon)))])))
(create-matrix/auxi num l)))
;; auxiliary functions
; N [List-of Number] -> [List-of Number]
produces the first n items of the given list .
(check-expect (first-line 2 lon-1) '(1 2))
(check-expect (first-line 3 lon-2) '(1 2 3))
(define (first-line n lon)
(cond [(or (zero? n)
(empty? lon)) '()]
[else (cons (first lon)
(first-line (sub1 n) (rest lon)))]))
; N [List-of Number] -> [List-of Number]
produces the list which is removed the first n items .
(check-expect (remove-first-line 2 lon-1) '(3 4))
(check-expect (remove-first-line 3 lon-2) '(4 5 6 7 8 9))
(check-expect (remove-first-line 2 '(3 4)) '())
(define (remove-first-line n lon)
(cond [(or (zero? n)
(empty? lon)) lon]
[else (remove-first-line (sub1 n) (rest lon))]))
| null | https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter5/Section27-variations-on-the-theme/ex454-create-matrix.rkt | racket | about the language level of this file in a form that our tools can easily process.
constants
functions
N [List-of Number] -> [List-of [List-of Number]]
prodcues a n x n matrix which is represented as list of list.
N [List-of Number] -> [List-of [List-of Number]]
help create matrix by unregularly create lol.
auxiliary functions
N [List-of Number] -> [List-of Number]
N [List-of Number] -> [List-of Number] | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex454-create-matrix) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define lon-1 '(1 2 3 4))
(define lon-2 '(1 2 3 4 5 6 7 8 9))
(define matrix-1 '((1 2)
(3 4)))
(define matrix-2 '((1 2 3)
(4 5 6)
(7 8 9)))
assume ( 1 ) the given lon 's length is ( sqr n )
( 2 ) the result consists of n list whose length is n.
(check-expect (create-matrix 2 lon-1) matrix-1)
(check-expect (create-matrix 3 lon-2) matrix-2)
(define (create-matrix num l)
(define (create-matrix/auxi n lon)
(cond [(empty? lon) '()]
[else (cons (first-line n lon)
(create-matrix/auxi
n
(remove-first-line n lon)))])))
(create-matrix/auxi num l)))
produces the first n items of the given list .
(check-expect (first-line 2 lon-1) '(1 2))
(check-expect (first-line 3 lon-2) '(1 2 3))
(define (first-line n lon)
(cond [(or (zero? n)
(empty? lon)) '()]
[else (cons (first lon)
(first-line (sub1 n) (rest lon)))]))
produces the list which is removed the first n items .
(check-expect (remove-first-line 2 lon-1) '(3 4))
(check-expect (remove-first-line 3 lon-2) '(4 5 6 7 8 9))
(check-expect (remove-first-line 2 '(3 4)) '())
(define (remove-first-line n lon)
(cond [(or (zero? n)
(empty? lon)) lon]
[else (remove-first-line (sub1 n) (rest lon))]))
|
8ca23cc40b7cb1c0a6b022be5b784798f4a0f737e53e8a77fba65830bc824213 | tip-org/tools | Translate.hs | # LANGUAGE DeriveFunctor , , DeriveTraversable #
# LANGUAGE RecordWildCards #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE GADTs #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE CPP #
# LANGUAGE PatternGuards #
module Tip.Haskell.Translate where
#include "errors.h"
import Tip.Haskell.Repr as H
import Tip.Core as T hiding (Formula(..),globals,Type(..),Decl(..))
import Tip.Core (Type((:=>:),BuiltinType))
import qualified Tip.Core as T
import Tip.Pretty
import Tip.Utils
import Tip.Scope
import Data.Maybe (isNothing, catMaybes, listToMaybe)
import Tip.CallGraph
import qualified Data.Foldable as F
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import qualified Data.Map as M
import Data.Generics.Geniplate
import Data.List (nub,partition,find)
import qualified GHC.Generics as G
import Tip.Haskell.GenericArbitrary
prelude :: String -> HsId a
prelude = Qualified "Prelude" (Just "P")
ratio :: String -> HsId a
ratio = Qualified "Data.Ratio" (Just "R")
tipDSL :: String -> HsId a
tipDSL = Qualified "Tip" Nothing
quickCheck :: String -> HsId a
quickCheck = Qualified "Test.QuickCheck" (Just "QC")
quickCheckUnsafe :: String -> HsId a
quickCheckUnsafe = Qualified "Test.QuickCheck.Gen.Unsafe" (Just "QU")
quickCheckAll :: String -> HsId a
quickCheckAll = Qualified "Test.QuickCheck.All" (Just "QC")
quickSpec :: String -> HsId a
quickSpec = Qualified "QuickSpec" (Just "QS")
constraints :: String -> HsId a
constraints = Qualified "Data.Constraint" (Just "QS")
sysEnv :: String -> HsId a
sysEnv = Qualified "System.Environment" (Just "Env")
smtenSym :: String -> HsId a
smtenSym = Qualified "Smten.Symbolic" (Just "S")
smtenEnv :: String -> HsId a
smtenEnv = Qualified "Smten.System.Environment" (Just "Env")
smtenMinisat :: String -> HsId a
smtenMinisat = Qualified "Smten.Symbolic.Solver.MiniSat" (Just "S")
smtenMonad :: String -> HsId a
smtenMonad = Qualified "Smten.Control.Monad" (Just "S")
smten also needs Prelude to be replaced with Smten . Prelude
feat :: String -> HsId a
feat = Qualified "Test.Feat" (Just "F")
lsc :: String -> HsId a
lsc = Qualified "Test.LazySmallCheck" (Just "L")
typeable :: String -> HsId a
typeable = Qualified "Data.Typeable" (Just "T")
generic :: String -> HsId a
generic = Qualified "GHC.Generics" (Just "G")
data HsId a
= Qualified
{ qual_module :: String
, qual_module_short :: Maybe String
, qual_func :: String
}
-- ^ A qualified import
| Exact String
-- ^ The current module defines something with this very important name
| Other a
-- ^ From the theory
| Derived (HsId a) String
-- ^ For various purposes...
deriving (Eq,Ord,Show,Functor,Traversable,Foldable)
instance PrettyVar a => PrettyVar (HsId a) where
varStr (Qualified _ (Just m) s) = m ++ "." ++ s
varStr (Qualified m Nothing s) = m ++ "." ++ s
varStr (Exact s) = s
varStr (Other x) = varStr x
varStr (Derived o s) = s ++ varStr o
addHeader :: String -> Decls a -> Decls a
addHeader mod_name (Decls ds) =
Decls (map LANGUAGE ["TemplateHaskell","DeriveDataTypeable","TypeOperators",
"ImplicitParams","RankNTypes","DeriveGeneric", "MultiParamTypeClasses"]
++ Module mod_name : ds)
addImports :: Ord a => Decls (HsId a) -> Decls (HsId a)
addImports d@(Decls ds) = Decls (QualImport "Text.Show.Functions" Nothing : imps ++ ds)
where
imps = usort [ QualImport m short | Qualified m short _ <- F.toList d ]
trTheory :: (Ord a,PrettyVar a) => Mode -> Theory a -> Decls (HsId a)
trTheory mode = fixup_prel . trTheory' mode . fmap Other
where
fixup_prel =
case mode of
Smten -> fmap fx
_ -> id
where
fx (Qualified "Prelude" u v) = Qualified "Smten.Prelude" (Just "S") v
fx (Qualified "Data.Ratio" u v) = Qualified "Smten.Data.Ratio" (Just "S") v
fx u = u
data Kind = Expr | Formula deriving Eq
theorySigs :: Theory (HsId a) -> [HsId a]
theorySigs Theory{..} = map sig_name thy_sigs
ufInfo :: Theory (HsId a) -> [H.Type (HsId a)]
ufInfo Theory{thy_sigs} = imps
where
imps = [TyImp (Derived f "imp") (H.TyCon (Derived f "") []) | Signature f _ _ <- thy_sigs]
data Mode = Feat | QuickCheck
| LazySmallCheck
{ with_depth_as_argument :: Bool
, with_parallel_functions :: Bool
}
| Smten | QuickSpec QuickSpecParams | Plain
deriving (Eq,Ord,Show)
isLazySmallCheck LazySmallCheck{} = True
isLazySmallCheck _ = False
isSmten Smten{} = True
isSmten _ = False
trTheory' :: forall a b . (a ~ HsId b,Ord b,PrettyVar b) => Mode -> Theory a -> Decls a
trTheory' mode thy@Theory{..} =
Decls $
concat [space_decl | isSmten mode ] ++
map tr_sort thy_sorts ++
concatMap tr_datatype thy_datatypes ++
concatMap tr_sig thy_sigs ++
concatMap tr_func thy_funcs ++
tr_asserts thy_asserts ++
case mode of
QuickSpec bg -> [makeSig bg thy]
_ -> []
where
imps = ufInfo thy
space_decl :: [Decl a]
space_decl =
[ ClassDecl [] (TyCon (Exact "Space") [TyVar (Exact "stv")])
[TySig (Exact "space") []
(TyArr (TyCon (prelude "Int") [])
(TyCon (smtenSym "Symbolic") [TyVar (Exact "stv")]))
]
, InstDecl [] (TyCon (Exact "Space") [TyCon (prelude "Bool") []])
[funDecl
(Exact "space")
[d]
(H.Case (Apply (prelude "<") [var d,H.Int 0])
[(H.ConPat (prelude "True") [], Apply (smtenMonad "mzero") [])
,(H.WildPat,
Apply (smtenMonad "msum")
[List
[ Apply (smtenMonad "return") [Apply (prelude "False") []]
, Apply (smtenMonad "return") [Apply (prelude "True") []]
]])
])
]
]
where d = Exact "d"
tr_datatype :: Datatype a -> [Decl a]
tr_datatype dt@(Datatype tc _ tvs cons) =
[ DataDecl tc tvs
[ (c,map (trType . snd) args) | Constructor c _ _ args <- cons ]
(map prelude ["Eq","Ord","Show"]
++ [generic "Generic"]
++ [typeable "Typeable" | not (isSmten mode) ])
]
++
[ TH (Apply (feat "deriveEnumerable") [QuoteTyCon tc])
| case mode of { Feat -> True; QuickCheck -> True; QuickSpec _ -> True; _ -> False } ]
++
[ InstDecl [H.TyCon (feat "Enumerable") [H.TyVar a] | a <- tvs]
(H.TyCon (quickCheck "Arbitrary") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(quickCheck "arbitrary") []
(Do [Bind (Exact "k") (Apply (quickCheck "sized")
[Apply (prelude "return") []]),
Bind (Exact "n") (Apply (quickCheck "choose")
[Tup [H.Int 0, Apply (prelude "+") [Apply (prelude "*") [Apply (Exact "k") [], H.Int 2], H.Int 2]]])]
(Apply (feat "uniform") [Apply (Exact "n") []]))]
| case mode of { QuickCheck -> True; QuickSpec QuickSpecParams{..} -> not use_observers;
_ -> False } ]
++
[ InstDecl [H.TyTup ([H.TyCon (typeable "Typeable") [H.TyVar a] | a <- tvs]
++ [H.TyCon (quickCheck "Arbitrary") [H.TyVar a] | a <- tvs])]
(H.TyCon (quickCheck "Arbitrary") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(quickCheck "arbitrary") []
(Apply (Qualified "Tip.Haskell.GenericArbitrary" Nothing "genericArbitrary") [])]
| case mode of { QuickSpec QuickSpecParams{..} -> use_observers; _ -> False } ]
++
[ InstDecl [H.TyCon (quickCheck cls) [H.TyVar a] | a <- tvs, cls <- ["Arbitrary", "CoArbitrary"]]
(H.TyCon (quickCheck "CoArbitrary") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(quickCheck "coarbitrary") []
(Apply (quickCheck "genericCoarbitrary") [])]]
++
[ InstDecl
[H.TyCon (lsc "Serial") [H.TyVar a] | a <- tvs]
(H.TyCon (lsc "Serial") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(lsc "series")
[]
(foldr1
(\ e1 e2 -> Apply (lsc "\\/") [e1,e2])
[ foldl
(\ e _ -> Apply (lsc "><") [e,Apply (lsc "series") []])
(Apply (lsc "cons") [Apply c []])
as
| Constructor c _ _ as <- cons
])]
| isLazySmallCheck mode ]
++
[ InstDecl
[H.TyCon (Exact "Space") [H.TyVar a] | a <- tvs]
(H.TyCon (Exact "Space") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(Exact "space")
[d]
(H.Case (Apply (prelude "<") [var d,H.Int 0])
[(H.ConPat (prelude "True") [], Apply (smtenMonad "mzero") [])
,(H.WildPat,
Apply (smtenMonad "msum")
[List
[ foldl (\ e1 _ ->
Apply (smtenMonad "ap")
[e1,Apply (Exact "space")
[Apply (prelude "-") [var d,H.Int 1]]])
(Apply (smtenMonad "return") [Apply c []])
args
| Constructor c _ _ args <- cons
]])
])
]
| let d = Exact "d"
, isSmten mode
]
++ (obsType dt)
where
obsType :: Datatype a -> [Decl a]
obsType dt@(Datatype tc _ tvs cons) =
case mode of QuickSpec QuickSpecParams{..} ->
if use_observers then
[DataDecl (obsName tc) tvs
([ (obsName c, map (trObsType . snd) args)
| Constructor c _ _ args <- cons ]
++
[(nullConsName tc,[])]
)
(map prelude ["Eq","Ord","Show"]
++ [typeable "Typeable"])
]
++ (obsFun dt [] (obFuName (data_name dt))
(obFuType (data_name dt) (data_tvs dt)) False)
++ (nestedObsFuns thy dt)
++ [InstDecl [H.TyCon (prelude "Ord") [H.TyVar a] | a <- tvs]
(H.TyCon (quickSpec "Observe") $
[H.TyCon (prelude "Int") []]
++ [H.TyCon (obsName tc) (map H.TyVar tvs)]
++ [H.TyCon tc (map H.TyVar tvs)]
)
[funDecl (quickSpec "observe") []
(Apply (obFuName tc) [])
]
]
else []
_ -> []
tr_sort :: Sort a -> Decl a
tr_sort (Sort s _ i) | null i = TypeDef (TyCon s []) (TyCon (prelude "Int") [])
tr_sort (Sort _ _ _) = error "Haskell.Translate: Poly-kinded abstract sort"
tr_sig :: Signature a -> [Decl a]
tr_sig (Signature f _ pt) =
newtype f_NT = f_Mk ( forall tvs . ( Arbitrary a , CoArbitrary a ) = > T )
[ DataDecl (Derived f "") [] [ (Derived f "Mk",[tr_polyTypeArbitrary pt]) ] []
, FunDecl (Derived f "get")
[( [H.ConPat (Derived f "Mk") [VarPat (Derived f "x")]]
, var (Derived f "x")
)]
-- f :: (?f_imp :: f_NT) => T
-- f = f_get ?f_imp
, TySig f [] (tr_polyType pt)
, funDecl f [] (Apply (Derived f "get") [ImpVar (Derived f "imp")])
instance Arbitrary f_NT where
-- arbitrary = do
-- Capture x <- capture
-- return (f_Mk (x arbitrary))
, InstDecl [] (TyCon (quickCheck "Arbitrary") [TyCon (Derived f "") []])
[ funDecl (quickCheck "arbitrary") []
(mkDo [Bind (Derived f "x") (Apply (quickCheckUnsafe "capture") [])]
(H.Case (var (Derived f "x"))
[(H.ConPat (quickCheckUnsafe "Capture") [VarPat (Derived f "y")]
,Apply (prelude "return")
[Apply (Derived f "Mk")
[Apply (Derived f "y")
[Apply (quickCheck "arbitrary") []]]]
)]
)
)
]
-- gen :: Gen (Dict (?f_imp :: f_NT))
-- gen = do
-- x <- arbitrary
-- let ?f_imp = x
-- return Dict
, TySig (Derived f "gen") []
(TyCon (quickCheck "Gen")
[TyCon (constraints "Dict")
[TyImp (Derived f "imp") (TyCon (Derived f "") [])]])
, funDecl (Derived f "gen") []
(mkDo [Bind (Derived f "x") (Apply (quickCheck "arbitrary") [])]
(ImpLet (Derived f "imp") (var (Derived f "x"))
(Apply (prelude "return") [Apply (constraints "Dict") []])))
]
tr_func :: Function a -> [Decl a]
tr_func fn@Function{..} =
[ TySig func_name [] (tr_polyType (funcType fn))
, FunDecl
func_name
[ (map tr_deepPattern dps,tr_expr Expr rhs)
| (dps,rhs) <- patternMatchingView func_args func_body
]
] ++
[ FunDecl
(prop_version func_name)
[ (map tr_deepPattern dps,tr_expr Formula rhs)
| (dps,rhs) <- patternMatchingView func_args func_body
]
| isLazySmallCheck mode
&& with_parallel_functions mode
&& func_res == boolType
]
prop_version f = Derived f "property"
tr_asserts :: [T.Formula a] -> [Decl a]
tr_asserts fms =
let (info,decls) = unzip (zipWith tr_assert [1..] fms)
in concat decls ++
case mode of
QuickCheck ->
[ TH (Apply (prelude "return") [List []])
, funDecl (Exact "main") []
(mkDo [ Stmt (THSplice (Apply (quickCheckAll "polyQuickCheck")
[QuoteName name]))
| (name,_) <- info ]
Noop)
]
LazySmallCheck{..} ->
[ funDecl (Exact "main") []
((`mkDo` Noop)
$ [Bind (Exact "args") (Apply (sysEnv "getArgs") [])]
++ [Stmt (fn name) | (name,_) <- info])
]
where
fn name = case with_depth_as_argument of
False -> Apply (lsc "test") [var name]
True -> Apply (lsc "depthCheck")
[read_head (var (Exact "args"))
,var name]
Feat ->
[ funDecl (Exact "main") []
(mkDo [Stmt (Apply (feat "featCheckStop")
[ H.Lam [TupPat (map VarPat vs)] (Apply name (map var vs))
])
| (name,vs) <- info ] Noop)
]
Smten | let [(name,vs)] = info ->
[ funDecl (Exact "main") []
$ mkDo [Bind (Exact "args") (Apply (smtenEnv "getArgs") [])
,Bind (Exact "r")
(Apply (smtenSym "run_symbolic")
[Apply (smtenMinisat "minisat") []
,mkDo (
[ Bind v (Apply (Exact "space") [read_head (var (Exact "args"))])
| v <- vs ]
++
[ Stmt $ Apply (smtenMonad "guard") [Apply (prelude "not") [Apply name (map var vs)]] ])
(Apply (smtenMonad "return") [nestedTup (map var vs)])
])
]
(Apply (prelude "print") [var (Exact "r")])
]
_ -> []
where
read_head e = Apply (prelude "read") [Apply (prelude "head") [e]]
tr_assert :: Int -> T.Formula a -> ((a,[a]),[Decl a])
tr_assert i T.Formula{..} =
((prop_name,args),
[ TySig prop_name []
(foldr TyArr
(case mode of LazySmallCheck{} -> H.TyCon (lsc "Property") []
_ -> H.TyCon (prelude "Bool") [])
[ trType (applyType fm_tvs (replicate (length fm_tvs) (intType)) t)
| Local _ t <- typed_args ])
| mode == Feat || isLazySmallCheck mode || mode == Smten ]
++
[ funDecl prop_name args (assume (tr_expr (if mode == Feat || isSmten mode then Expr else Formula) body)) ]
)
where
prop_name | i == 1 = Exact "prop"
| otherwise = Exact ("prop" ++ show i)
(typed_args,body) =
case fm_body of
Quant _ Forall lcls term -> (lcls,term)
_ -> ([],fm_body)
args = map lcl_name typed_args
assume e =
case fm_role of
Prove -> e
Assert -> e -- Apply (tipDSL "assume") [e]
tr_deepPattern :: DeepPattern a -> H.Pat a
tr_deepPattern (DeepConPat Global{..} dps) = H.ConPat gbl_name (map tr_deepPattern dps)
tr_deepPattern (DeepVarPat Local{..}) = VarPat lcl_name
tr_deepPattern (DeepLitPat (T.Int i)) = IntPat i
tr_deepPattern (DeepLitPat (Bool b)) = withBool H.ConPat b
tr_pattern :: T.Pattern a -> H.Pat a
tr_pattern Default = WildPat
tr_pattern (T.ConPat Global{..} xs) = H.ConPat gbl_name (map (VarPat . lcl_name) xs)
tr_pattern (T.LitPat (T.Int i)) = H.IntPat i
tr_pattern (T.LitPat (Bool b)) = withBool H.ConPat b
tr_expr :: Kind -> T.Expr a -> H.Expr a
tr_expr k e0 =
case e0 of
Builtin (Lit (T.Int i)) :@: [] -> H.Int i
Builtin (Lit (Bool b)) :@: [] -> lsc_lift (withBool Apply b)
Builtin Implies :@: [u,v] | mode == Smten -> tr_expr k (Builtin Or :@: [Builtin Not :@: [u],v])
hd :@: es -> let ((f,k'),lft) = tr_head (map exprType es) k hd
in lift_if lft (maybe_ty_sig e0 (Apply f (map (tr_expr k') es)))
Lcl x -> lsc_lift (var (lcl_name x))
T.Lam xs b -> H.Lam (map (VarPat . lcl_name) xs) (tr_expr Expr b)
Match e alts -> H.Case (tr_expr Expr e) [ (tr_pattern p,tr_expr brs_k rhs) | T.Case p rhs <- default_last alts ]
where
brs_k
| isLazySmallCheck mode = k
| otherwise = Expr
T.Let x e b -> H.Let (lcl_name x) (tr_expr Expr e) (tr_expr k b)
T.Quant _ q xs b ->
foldr
(\ x e ->
Apply (tipDSL (case q of Forall -> "forAll"; Exists -> "exists"))
[H.Lam [VarPat (lcl_name x)] e])
(tr_expr Formula b)
xs
T.LetRec{} -> ERROR("letrec not supported")
where
maybe_ty_sig e@(hd@(Gbl Global{..}) :@: es) he
| isNothing (makeGlobal gbl_name gbl_type (map exprType es) Nothing)
= he ::: trType (exprType e)
maybe_ty_sig _ he = he
lift_if b e
| b && isLazySmallCheck mode = Apply (lsc "lift") [e]
| otherwise = e
lsc_lift = lift_if (k == Formula)
default_last (def@(T.Case Default _):alts) = alts ++ [def]
default_last alts = alts
tr_head :: [T.Type a] -> Kind -> T.Head a -> ((a,Kind),Bool)
tr_head ts k (Builtin b) = tr_builtin ts k b
tr_head ts k (Gbl Global{..})
| stay_prop = ((prop_version gbl_name,Expr),False)
| otherwise = ((gbl_name ,Expr),k == Formula)
where
stay_prop = k == Formula
&& isLazySmallCheck mode
&& with_parallel_functions mode
&& polytype_res gbl_type == boolType
tr_builtin :: [T.Type a] -> Kind -> T.Builtin -> ((a,Kind),Bool)
tr_builtin ts k b =
case b of
At -> ((prelude "id",Expr),False)
Lit{} -> error "tr_builtin"
And -> case_kind (tipDSL ".&&.") (Just (lsc "*&*"))
Or -> case_kind (tipDSL ".||.") (Just (lsc "*|*"))
Not -> case_kind (tipDSL "neg") (Just (lsc "neg"))
Implies -> case_kind (tipDSL "==>") (Just (lsc "*=>*"))
Equal -> case_kind (tipDSL "===") $ case ts of
BuiltinType Boolean:_ -> Just (lsc "*=*")
_ -> Nothing
Distinct -> case_kind (tipDSL "=/=") Nothing
_ -> (prelude_fn,False)
where
Just prelude_str_ = lookup b hsBuiltins
prelude_fn = (prelude prelude_str_,Expr)
case_kind tip_version lsc_version =
case k of
Expr -> (prelude_fn,False)
Formula ->
case mode of
LazySmallCheck{} ->
case lsc_version of
Just v -> ((v,Formula),False)
Nothing -> (prelude_fn,True)
_ -> ((tip_version,Formula),False)
-- ignores the type variables
tr_polyType_inner :: T.PolyType a -> H.Type a
tr_polyType_inner (PolyType _ ts t) = trType (ts :=>: t)
tr_polyType :: T.PolyType a -> H.Type a
tr_polyType pt@(PolyType tvs _ _) =
TyForall tvs (TyCtx (arb tvs ++ imps) (tr_polyType_inner pt))
translate type and add Arbitrary a , CoArbitrary a in the context for
-- all type variables a
tr_polyTypeArbitrary :: T.PolyType a -> H.Type a
tr_polyTypeArbitrary pt@(PolyType tvs _ _) = TyForall tvs (TyCtx (arb tvs) (tr_polyType_inner pt))
arb = (arbitrary ob) . map H.TyVar
ob = case mode of
QuickSpec QuickSpecParams{..} -> use_observers
_ -> False
arbitrary :: Bool -> [H.Type (HsId a)] -> [H.Type (HsId a)]
arbitrary obs ts =
[ TyCon tc [t]
| t <- ts
, tc <- tcs]
where tcs = case obs of
quickCheck " Arbitrary " , quickCheck " " , typeable " " ]
False -> [quickCheck "Arbitrary", feat "Enumerable", prelude "Ord"]
trType :: (a ~ HsId b) => T.Type a -> H.Type a
trType (T.TyVar x) = H.TyVar x
trType (T.TyCon tc ts) = H.TyCon tc (map trType ts)
trType (ts :=>: t) = foldr TyArr (trType t) (map trType ts)
trType (BuiltinType b) = trBuiltinType b
trObsType :: (a ~ HsId b) => T.Type a -> H.Type a
trObsType (T.TyCon tc ts) = H.TyCon (obsName tc) (map trObsType ts)
trObsType t = trType t
-- Name of generated observer type
-- obsName T_name = ObsT_name
obsName :: HsId a -> HsId a
obsName c = Derived c "Obs"
-- Name of nullary constructor for generated observer type
-- nullConsName T_name = NullConsT_name
nullConsName :: HsId a -> HsId a
nullConsName c = Derived c "NullCons"
-- Name of generated observer function
obFuName T_name = obsFunT_name
obFuName :: PrettyVar a => HsId a -> HsId a
obFuName c = Exact $ "obsFun" ++ varStr c
-- Type of generated observer function
obFuType :: (a ~ HsId b) => a -> [a] -> H.Type a
obFuType c vs =
-- Int -> dt -> obs_dt
TyArr (TyVar $ prelude "Int") (TyArr (TyCon c (map (\x -> TyVar x) vs))
(TyCon (obsName c) (map (\x -> TyVar x) vs)))
-- Name of recursive observer for nested type
nestObsName :: (a ~ HsId b, PrettyVar b) => T.Type a -> HsId b
nestObsName (T.TyCon tc ts) = Exact $ foldl (++) ("obsFun" ++ varStr tc) (map nestName ts)
where nestName (T.TyCon c s) = (foldr (++) (varStr c) (map nestName s))
nestName _ = ""
nestObsName _ = Exact ""
-- Type of recursive observer for nested type
nestObsType :: (a ~ HsId b) => T.Type a -> H.Type a
nestObsType t = TyArr (TyVar $ prelude "Int") (TyArr (trType t) (trObsType t))
-- observer functions for nested constructors
nestedObsFuns :: (a ~ HsId b, Eq b, PrettyVar b) => Theory a -> Datatype a -> [Decl a]
nestedObsFuns thy dt@(Datatype tc _ tvs cons) = concat $ catMaybes $ concatMap (nestedObs thy) cons
-- generate observers if constructor is nested
nestedObs :: (a ~ HsId b, Eq b, PrettyVar b) => Theory a -> Constructor a -> [Maybe [Decl a]]
nestedObs thy (Constructor _ _ _ as) = map ((nestObs thy) . snd) as
-- generate observer if constructor is found nested inside another constructor
nestObs :: (a ~ HsId b, Eq b, PrettyVar b) => Theory a -> T.Type a -> Maybe [Decl a]
nestObs Theory{..} t@(T.TyCon tc ts) = case find (\x -> (data_name x == tc)) thy_datatypes of
Just dt ->
if nestObsName t == obFuName tc
then Nothing
else Just $ obsFun dt ts (nestObsName t) (nestObsType t) True
_ -> Nothing
nestObs _ _ = Nothing
-- Generate observer function for the given type
obsFun :: (a ~ HsId b, Eq b, PrettyVar b) => Datatype a -> [T.Type a] -> a -> H.Type a -> Bool -> [Decl a]
obsFun (Datatype tname _ _ cons) targs fuName fuType recu =
[TySig fuName [] fuType, FunDecl fuName cases]
where
cases = [
-- if counter is down to 0 call nullary constructor on rhs
([H.VarPat (Exact "0"),
H.VarPat (Exact "_")], Apply (nullConsName tname) [])
,([H.VarPat n, H.VarPat x],
H.Case (Apply (prelude "<") [var n, H.Int 0])
-- if n is negative use -n instead
[(H.ConPat (prelude "True") [],
Apply fuName [Apply (prelude "negate") [var n], var x])
-- if n is positive call approx
,(H.ConPat (prelude "False") [],
H.Case (var x) $
[(H.ConPat cname $ varNames cargs,
approx recu cname (map snd cargs) (listToMaybe targs) fuName tname)
| Constructor cname _ _ cargs <- cons]
)
])]
n = Exact "n"
x = Exact "x"
varNames as = map (\((c,a),b) -> mkVar b a) (zip as [0..])
mkVar n (T.TyVar _) = H.VarPat (Exact $ "x" ++ (show n))
mkVar n (T.TyCon tc ts) = H.ConPat (Exact $ "x" ++ (show n)) []
mkVar n (BuiltinType b)
| Just ty <- lookup b hsBuiltinTys = H.ConPat (Exact $ "x" ++ (show n)) []
| otherwise = __
mkVar _ _ = WildPat
approx :: (a ~ HsId b, Eq b, PrettyVar b) => Bool -> a -> [T.Type a] -> Maybe (T.Type a) -> a -> a -> H.Expr a
approx recu c as ta fn nm | recu = Apply (obsName c) $ map (recappstep as ta fn nm) (zip as [0..])
| otherwise = Apply (obsName c) $ map (appstep as nm) (zip as [0..])
where
-- regular case
appstep as nm (t@(T.TyCon _ _), k) =
-- call the appropriate observer function with decremented counter
Apply (nestObsName t) [decrement $ countBranches as nm
, varName k]
appstep _ _ (_, k) = varName k
-- recursive approximation for nested constructors
recappstep as _ fn nm (t@(T.TyCon _ _), k) =
-- call the current observer function with decremented counter
Apply fn $ [decrement $ countBranches as nm
, varName k]
recappstep as (Just ta) fn nm (t@(T.TyVar x), k) =
-- call recursive observer for nested constructor
Apply (nestObsName ta) $ [decrement $ countBranches as nm
,varName k]
recappstep _ _ _ _ (_,k) = varName k
varName k = var (Exact $ "x" ++ (show k))
-- decrement fuel counter based on branching factor
decrement :: (a ~ HsId b) => Int -> H.Expr a
decrement k =
if k <= 1
then
Apply (prelude "-") [var n, H.Int 1]
else
Apply (prelude "quot") [var n, H.Int $ toInteger k]
where
n = Exact "n"
-- calculate branching factor
countBranches :: [T.Type a] -> a -> Int
countBranches as n =
foldr (+) 0 (map bcount as)
where
bcount (T.TyCon tc ts) = foldr (+) (isBranch tc) (map bcount ts)
bcount _ = 0
isBranch n = 1
isBranch _ = 0
trBuiltinType :: BuiltinType -> H.Type (HsId a)
trBuiltinType t
| Just ty <- lookup t hsBuiltinTys = H.TyCon ty []
| otherwise = __
withBool :: (a ~ HsId b) => (a -> [c] -> d) -> Bool -> d
withBool k b = k (prelude (show b)) []
-- * Builtins
hsBuiltinTys :: [(T.BuiltinType, HsId a)]
hsBuiltinTys =
[ (Integer, prelude "Int")
, (Real, ratio "Rational")
, (Boolean, prelude "Bool")
]
hsBuiltins :: [(T.Builtin,String)]
hsBuiltins =
[ (Equal , "==" )
, (Distinct , "/=" )
, (NumAdd , "+" )
, (NumSub , "-" )
, (NumMul , "*" )
, (NumDiv , "/" )
, (IntDiv , "div")
, (IntMod , "mod")
, (NumGt , ">" )
, (NumGe , ">=" )
, (NumLt , "<" )
, (NumLe , "<=" )
, (NumWiden , "fromIntegral")
, (And , "&&" )
, (Or , "||" )
, (Not , "not")
, (Implies , "<=" )
]
typesOfBuiltin :: Builtin -> [T.Type a]
typesOfBuiltin b = case b of
And -> [bbb]
Or -> [bbb]
Not -> [bb]
Implies -> [bbb]
Equal -> [iib] -- TODO: equality could be used on other types than int
Distinct -> [iib] -- ditto
NumAdd -> [iii, rrr]
NumSub -> [iii, rrr]
NumMul -> [iii, rrr]
NumDiv -> [rrr]
IntDiv -> [iii]
IntMod -> [iii, rrr]
NumGt -> [iib, rrb]
NumGe -> [iib, rrb]
NumLt -> [iib, rrb]
NumLe -> [iib, rrb]
NumWiden -> [ir]
Lit (T.Int _) -> [intType]
Lit (Bool _) -> [boolType]
_ -> error ("can't translate built-in: " ++ show b)
where
bb = [boolType] :=>: boolType
bbb = [boolType,boolType] :=>: boolType
iii = [intType,intType] :=>: intType
iib = [intType,intType] :=>: boolType
rrr = [realType,realType] :=>: realType
rrb = [realType,realType] :=>: boolType
ir = [intType] :=>: realType
* signatures
data QuickSpecParams =
QuickSpecParams {
foreground_functions :: Maybe [String],
predicates :: Maybe [String],
use_observers :: Bool,
use_completion :: Bool,
max_size :: Int,
max_test_size :: Int
}
deriving (Eq, Ord, Show)
makeSig :: forall a . (PrettyVar a, Ord a) => QuickSpecParams -> Theory (HsId a) -> Decl (HsId a)
makeSig qspms@QuickSpecParams{..} thy@Theory{..} =
funDecl (Exact "sig") [] $ List $
[constant_decl ft
| ft@(f,_) <- func_constants, inForeground f] ++
bg
++
[ mk_inst [] (mk_class (feat "Enumerable") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (feat "Enumerable") (H.TyCon (prelude "Rational") [])) ] ++
[ mk_inst [] (mk_class (feat "Enumerable") (H.TyCon (prelude "Bool") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "Arbitrary") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "Arbitrary") (H.TyCon (prelude "Rational") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "Arbitrary") (H.TyCon (prelude "Bool") [])) ] ++
[ mk_inst [] (mk_class (typeable "Typeable") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "CoArbitrary") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "CoArbitrary") (H.TyCon (prelude "Rational") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "CoArbitrary") (H.TyCon (prelude "Bool") [])) ] ++
[ mk_inst (map (mk_class c1) tys) (mk_class c2 (H.TyCon t tys))
| (t,n) <- type_univ
, (c1, c2) <- [(prelude "Ord", prelude "Ord"),
(feat "Enumerable", feat "Enumerable")]
, let tys = map trType (qsTvs n)
] ++
[ mk_inst [mk_class c ty | c <- cs, ty <- tys] (mk_class c2 (H.TyCon t tys))
| (t,n) <- type_univ
, (cs,c2) <- [([quickCheck "Arbitrary", quickCheck "CoArbitrary"],quickCheck "CoArbitrary"),
([typeable "Typeable"], typeable "Typeable")]
, let tys = map trType (qsTvs n)
] ++
[ mk_inst (map (mk_class (feat "Enumerable")) tys)
(mk_class (quickCheck "Arbitrary") (H.TyCon t tys))
| (t,n) <- type_univ, t `notElem` (map (\(a,b,c) -> a) obsTriples)
, let tys = map trType (qsTvs n)
] ++
[ mk_inst ((map (mk_class (typeable "Typeable")) tys)
++ (map (mk_class (quickCheck "Arbitrary")) tys)
) (mk_class (quickCheck "Arbitrary") (H.TyCon t tys))
| (t,n) <- type_univ, t `elem` (map (\(a,b,c) -> a) obsTriples)
, let tys = map trType (qsTvs n)
] ++
[ mk_inst ((map (mk_class (prelude "Ord")) tys)
++ (map (mk_class (quickCheck "Arbitrary")) tys)
) (H.TyCon (quickSpec "Observe") $
[H.TyCon (prelude "Int") []]
++ [H.TyCon (obsName t) tys]
++ [H.TyCon t tys])
| (t,n) <- type_univ, t `elem` (map (\(a,b,c) -> a) obsTriples)
, let tys = map trType (qsTvs n)
] ++
[ Apply (quickSpec "inst") [H.Lam [TupPat []] (Apply (Derived f "gen") [])]
| Signature f _ _ <- thy_sigs
] ++
[Apply (quickSpec "withMaxTermSize") [H.Int (fromIntegral max_size)]] ++
[Apply (quickSpec "withMaxTestSize") [H.Int (fromIntegral max_test_size)]] ++
[Apply (quickSpec "withPruningDepth") [H.Int 0] | not use_completion]
--TODO: What is reasonable size? Make size tweakable?
--TODO: Set more parameters?
where
inForeground f =
case foreground_functions of
Nothing -> True
Just fs -> varStr f `elem` fs
inPredicates p =
case predicates of
Nothing -> True
Just ps -> varStr p `elem` ps
bg = case bgs of
[] -> []
_ -> [Apply (quickSpec "background") [List bgs]]
bgs = [constant_decl ft
| ft@(f,_) <- func_constants,
not (inForeground f) ]
++ builtin_decls
++ map constant_decl (ctor_constants ++ builtin_constants)
imps = ufInfo thy
int_lit x = H.Int x ::: H.TyCon (prelude "Int") []
mk_inst ctx res =
Apply (quickSpec "inst")
[ Apply (constraints "Sub") [Apply (constraints "Dict") []] :::
H.TyCon (constraints ":-") [TyTup ctx,res] ]
mk_class c x = H.TyCon c [x]
scp = scope thy
poly_type (PolyType _ args res) = args :=>: res
constant_decl (f,t) =
FIXME : If there are more than 6 constraints quickspec wo n't find properties
-- for this function, can we get around that by changing the representation here?
Apply (quickSpec conOrPred) [H.String f,lam (Apply f []) ::: qs_type]
where
(_pre,qs_type) = qsType t
lam = H.Lam [H.ConPat (constraints "Dict") []]
conOrPred =
case t of
_ :=>: BuiltinType Boolean | inPredicates f -> "predicate"
_ -> "con"
int_lit_decl x =
Apply (quickSpec "con") [H.String (Exact (show x)),int_lit x]
bool_lit_decl b =
Apply (quickSpec "con") [H.String (prelude (show b)),withBool Apply b]
ctor_constants =
[ (f,poly_type (globalType g))
| (f,g@ConstructorInfo{}) <- M.toList (globals scp)
]
func_constants =
[ (f,poly_type (globalType g))
| (f,g@FunctionInfo{}) <- M.toList (globals scp)
]
type_univ =
[ (data_name, length data_tvs)
| (_,DatatypeInfo Datatype{..}) <- M.toList (types scp)
]
-- Types that require observers along with corresponding observer types
-- and functions
obsTriples =
[(data_name, obsName data_name, obFuName data_name)
| (_,DatatypeInfo dt@Datatype{..}) <- M.toList (types scp),
use_observers
]
-- builtins
(builtin_lits,builtin_funs) =
partition (litBuiltin . fst) $
usort
[ (b, map exprType args :=>: exprType e)
| e@(Builtin b :@: args) <- universeBi thy ]
used_builtin_types :: [BuiltinType]
used_builtin_types =
usort [ t | BuiltinType t :: T.Type (HsId a) <- universeBi thy ]
bool_used = Boolean `elem` used_builtin_types
num_used = -- Integer `elem` used_builtin_types
or [ op `elem` map fst builtin_funs | op <- [NumAdd,NumSub,NumMul,NumDiv,IntDiv,IntMod] ]
builtin_decls
= [ bool_lit_decl b | bool_used, b <- [False,True] ]
++ [ int_lit_decl x | num_used, x <- nub $
[0,1] ++
[ x
| Lit (T.Int x) <- map fst builtin_lits ]]
builtin_constants
= [ (prelude s, ty)
| (b, ty) <- nub $
-- [ b | bool_used, b <- [And,Or,Not] ]
-- [ IntAdd | int_used ]
-- [ Equal | bool_used && int_used ]
[ (b, ty) | (b, ty) <- builtin_funs, numBuiltin b ]
, Just s <- [lookup b hsBuiltins]
]
qsType :: Ord a => T.Type (HsId a) -> ([H.Type (HsId a)],H.Type (HsId a))
qsType t = (pre, TyArr (TyCon (constraints "Dict") [tyTup pre]) inner)
FIXME : can we curry the constraints so we do n't get tuples of more than 6 ?
where
pre = arbitrary use_observers (map trType qtvs) ++ imps
put each of qtvs in separate ?
inner = trType (applyType tvs qtvs t)
qtvs = qsTvs (length tvs)
tvs = tyVars t
Transform big tuples of constraints into nested tuples
( because QuickSpec does n't understand arbitrary tuples of constraints )
tyTup [] = TyTup []
tyTup [ty] = ty
tyTup (ty:tys) = TyTup [ty, tyTup tys]
qsTvs :: Int -> [T.Type (HsId a)]
qsTvs n = take n (cycle [ T.TyCon (quickSpec qs_tv) [] | qs_tv <- ["A","B","C","D","E"] ])
theoryBuiltins :: Ord a => Theory a -> [T.Builtin]
theoryBuiltins = usort . universeBi
| null | https://raw.githubusercontent.com/tip-org/tools/34350072587bd29157d18331eb895a1b2819555f/tip-lib/src/Tip/Haskell/Translate.hs | haskell | # LANGUAGE GADTs #
^ A qualified import
^ The current module defines something with this very important name
^ From the theory
^ For various purposes...
f :: (?f_imp :: f_NT) => T
f = f_get ?f_imp
arbitrary = do
Capture x <- capture
return (f_Mk (x arbitrary))
gen :: Gen (Dict (?f_imp :: f_NT))
gen = do
x <- arbitrary
let ?f_imp = x
return Dict
Apply (tipDSL "assume") [e]
ignores the type variables
all type variables a
Name of generated observer type
obsName T_name = ObsT_name
Name of nullary constructor for generated observer type
nullConsName T_name = NullConsT_name
Name of generated observer function
Type of generated observer function
Int -> dt -> obs_dt
Name of recursive observer for nested type
Type of recursive observer for nested type
observer functions for nested constructors
generate observers if constructor is nested
generate observer if constructor is found nested inside another constructor
Generate observer function for the given type
if counter is down to 0 call nullary constructor on rhs
if n is negative use -n instead
if n is positive call approx
regular case
call the appropriate observer function with decremented counter
recursive approximation for nested constructors
call the current observer function with decremented counter
call recursive observer for nested constructor
decrement fuel counter based on branching factor
calculate branching factor
* Builtins
TODO: equality could be used on other types than int
ditto
TODO: What is reasonable size? Make size tweakable?
TODO: Set more parameters?
for this function, can we get around that by changing the representation here?
Types that require observers along with corresponding observer types
and functions
builtins
Integer `elem` used_builtin_types
[ b | bool_used, b <- [And,Or,Not] ]
[ IntAdd | int_used ]
[ Equal | bool_used && int_used ] | # LANGUAGE DeriveFunctor , , DeriveTraversable #
# LANGUAGE RecordWildCards #
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE CPP #
# LANGUAGE PatternGuards #
module Tip.Haskell.Translate where
#include "errors.h"
import Tip.Haskell.Repr as H
import Tip.Core as T hiding (Formula(..),globals,Type(..),Decl(..))
import Tip.Core (Type((:=>:),BuiltinType))
import qualified Tip.Core as T
import Tip.Pretty
import Tip.Utils
import Tip.Scope
import Data.Maybe (isNothing, catMaybes, listToMaybe)
import Tip.CallGraph
import qualified Data.Foldable as F
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import qualified Data.Map as M
import Data.Generics.Geniplate
import Data.List (nub,partition,find)
import qualified GHC.Generics as G
import Tip.Haskell.GenericArbitrary
prelude :: String -> HsId a
prelude = Qualified "Prelude" (Just "P")
ratio :: String -> HsId a
ratio = Qualified "Data.Ratio" (Just "R")
tipDSL :: String -> HsId a
tipDSL = Qualified "Tip" Nothing
quickCheck :: String -> HsId a
quickCheck = Qualified "Test.QuickCheck" (Just "QC")
quickCheckUnsafe :: String -> HsId a
quickCheckUnsafe = Qualified "Test.QuickCheck.Gen.Unsafe" (Just "QU")
quickCheckAll :: String -> HsId a
quickCheckAll = Qualified "Test.QuickCheck.All" (Just "QC")
quickSpec :: String -> HsId a
quickSpec = Qualified "QuickSpec" (Just "QS")
constraints :: String -> HsId a
constraints = Qualified "Data.Constraint" (Just "QS")
sysEnv :: String -> HsId a
sysEnv = Qualified "System.Environment" (Just "Env")
smtenSym :: String -> HsId a
smtenSym = Qualified "Smten.Symbolic" (Just "S")
smtenEnv :: String -> HsId a
smtenEnv = Qualified "Smten.System.Environment" (Just "Env")
smtenMinisat :: String -> HsId a
smtenMinisat = Qualified "Smten.Symbolic.Solver.MiniSat" (Just "S")
smtenMonad :: String -> HsId a
smtenMonad = Qualified "Smten.Control.Monad" (Just "S")
smten also needs Prelude to be replaced with Smten . Prelude
feat :: String -> HsId a
feat = Qualified "Test.Feat" (Just "F")
lsc :: String -> HsId a
lsc = Qualified "Test.LazySmallCheck" (Just "L")
typeable :: String -> HsId a
typeable = Qualified "Data.Typeable" (Just "T")
generic :: String -> HsId a
generic = Qualified "GHC.Generics" (Just "G")
data HsId a
= Qualified
{ qual_module :: String
, qual_module_short :: Maybe String
, qual_func :: String
}
| Exact String
| Other a
| Derived (HsId a) String
deriving (Eq,Ord,Show,Functor,Traversable,Foldable)
instance PrettyVar a => PrettyVar (HsId a) where
varStr (Qualified _ (Just m) s) = m ++ "." ++ s
varStr (Qualified m Nothing s) = m ++ "." ++ s
varStr (Exact s) = s
varStr (Other x) = varStr x
varStr (Derived o s) = s ++ varStr o
addHeader :: String -> Decls a -> Decls a
addHeader mod_name (Decls ds) =
Decls (map LANGUAGE ["TemplateHaskell","DeriveDataTypeable","TypeOperators",
"ImplicitParams","RankNTypes","DeriveGeneric", "MultiParamTypeClasses"]
++ Module mod_name : ds)
addImports :: Ord a => Decls (HsId a) -> Decls (HsId a)
addImports d@(Decls ds) = Decls (QualImport "Text.Show.Functions" Nothing : imps ++ ds)
where
imps = usort [ QualImport m short | Qualified m short _ <- F.toList d ]
trTheory :: (Ord a,PrettyVar a) => Mode -> Theory a -> Decls (HsId a)
trTheory mode = fixup_prel . trTheory' mode . fmap Other
where
fixup_prel =
case mode of
Smten -> fmap fx
_ -> id
where
fx (Qualified "Prelude" u v) = Qualified "Smten.Prelude" (Just "S") v
fx (Qualified "Data.Ratio" u v) = Qualified "Smten.Data.Ratio" (Just "S") v
fx u = u
data Kind = Expr | Formula deriving Eq
theorySigs :: Theory (HsId a) -> [HsId a]
theorySigs Theory{..} = map sig_name thy_sigs
ufInfo :: Theory (HsId a) -> [H.Type (HsId a)]
ufInfo Theory{thy_sigs} = imps
where
imps = [TyImp (Derived f "imp") (H.TyCon (Derived f "") []) | Signature f _ _ <- thy_sigs]
data Mode = Feat | QuickCheck
| LazySmallCheck
{ with_depth_as_argument :: Bool
, with_parallel_functions :: Bool
}
| Smten | QuickSpec QuickSpecParams | Plain
deriving (Eq,Ord,Show)
isLazySmallCheck LazySmallCheck{} = True
isLazySmallCheck _ = False
isSmten Smten{} = True
isSmten _ = False
trTheory' :: forall a b . (a ~ HsId b,Ord b,PrettyVar b) => Mode -> Theory a -> Decls a
trTheory' mode thy@Theory{..} =
Decls $
concat [space_decl | isSmten mode ] ++
map tr_sort thy_sorts ++
concatMap tr_datatype thy_datatypes ++
concatMap tr_sig thy_sigs ++
concatMap tr_func thy_funcs ++
tr_asserts thy_asserts ++
case mode of
QuickSpec bg -> [makeSig bg thy]
_ -> []
where
imps = ufInfo thy
space_decl :: [Decl a]
space_decl =
[ ClassDecl [] (TyCon (Exact "Space") [TyVar (Exact "stv")])
[TySig (Exact "space") []
(TyArr (TyCon (prelude "Int") [])
(TyCon (smtenSym "Symbolic") [TyVar (Exact "stv")]))
]
, InstDecl [] (TyCon (Exact "Space") [TyCon (prelude "Bool") []])
[funDecl
(Exact "space")
[d]
(H.Case (Apply (prelude "<") [var d,H.Int 0])
[(H.ConPat (prelude "True") [], Apply (smtenMonad "mzero") [])
,(H.WildPat,
Apply (smtenMonad "msum")
[List
[ Apply (smtenMonad "return") [Apply (prelude "False") []]
, Apply (smtenMonad "return") [Apply (prelude "True") []]
]])
])
]
]
where d = Exact "d"
tr_datatype :: Datatype a -> [Decl a]
tr_datatype dt@(Datatype tc _ tvs cons) =
[ DataDecl tc tvs
[ (c,map (trType . snd) args) | Constructor c _ _ args <- cons ]
(map prelude ["Eq","Ord","Show"]
++ [generic "Generic"]
++ [typeable "Typeable" | not (isSmten mode) ])
]
++
[ TH (Apply (feat "deriveEnumerable") [QuoteTyCon tc])
| case mode of { Feat -> True; QuickCheck -> True; QuickSpec _ -> True; _ -> False } ]
++
[ InstDecl [H.TyCon (feat "Enumerable") [H.TyVar a] | a <- tvs]
(H.TyCon (quickCheck "Arbitrary") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(quickCheck "arbitrary") []
(Do [Bind (Exact "k") (Apply (quickCheck "sized")
[Apply (prelude "return") []]),
Bind (Exact "n") (Apply (quickCheck "choose")
[Tup [H.Int 0, Apply (prelude "+") [Apply (prelude "*") [Apply (Exact "k") [], H.Int 2], H.Int 2]]])]
(Apply (feat "uniform") [Apply (Exact "n") []]))]
| case mode of { QuickCheck -> True; QuickSpec QuickSpecParams{..} -> not use_observers;
_ -> False } ]
++
[ InstDecl [H.TyTup ([H.TyCon (typeable "Typeable") [H.TyVar a] | a <- tvs]
++ [H.TyCon (quickCheck "Arbitrary") [H.TyVar a] | a <- tvs])]
(H.TyCon (quickCheck "Arbitrary") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(quickCheck "arbitrary") []
(Apply (Qualified "Tip.Haskell.GenericArbitrary" Nothing "genericArbitrary") [])]
| case mode of { QuickSpec QuickSpecParams{..} -> use_observers; _ -> False } ]
++
[ InstDecl [H.TyCon (quickCheck cls) [H.TyVar a] | a <- tvs, cls <- ["Arbitrary", "CoArbitrary"]]
(H.TyCon (quickCheck "CoArbitrary") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(quickCheck "coarbitrary") []
(Apply (quickCheck "genericCoarbitrary") [])]]
++
[ InstDecl
[H.TyCon (lsc "Serial") [H.TyVar a] | a <- tvs]
(H.TyCon (lsc "Serial") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(lsc "series")
[]
(foldr1
(\ e1 e2 -> Apply (lsc "\\/") [e1,e2])
[ foldl
(\ e _ -> Apply (lsc "><") [e,Apply (lsc "series") []])
(Apply (lsc "cons") [Apply c []])
as
| Constructor c _ _ as <- cons
])]
| isLazySmallCheck mode ]
++
[ InstDecl
[H.TyCon (Exact "Space") [H.TyVar a] | a <- tvs]
(H.TyCon (Exact "Space") [H.TyCon tc (map H.TyVar tvs)])
[funDecl
(Exact "space")
[d]
(H.Case (Apply (prelude "<") [var d,H.Int 0])
[(H.ConPat (prelude "True") [], Apply (smtenMonad "mzero") [])
,(H.WildPat,
Apply (smtenMonad "msum")
[List
[ foldl (\ e1 _ ->
Apply (smtenMonad "ap")
[e1,Apply (Exact "space")
[Apply (prelude "-") [var d,H.Int 1]]])
(Apply (smtenMonad "return") [Apply c []])
args
| Constructor c _ _ args <- cons
]])
])
]
| let d = Exact "d"
, isSmten mode
]
++ (obsType dt)
where
obsType :: Datatype a -> [Decl a]
obsType dt@(Datatype tc _ tvs cons) =
case mode of QuickSpec QuickSpecParams{..} ->
if use_observers then
[DataDecl (obsName tc) tvs
([ (obsName c, map (trObsType . snd) args)
| Constructor c _ _ args <- cons ]
++
[(nullConsName tc,[])]
)
(map prelude ["Eq","Ord","Show"]
++ [typeable "Typeable"])
]
++ (obsFun dt [] (obFuName (data_name dt))
(obFuType (data_name dt) (data_tvs dt)) False)
++ (nestedObsFuns thy dt)
++ [InstDecl [H.TyCon (prelude "Ord") [H.TyVar a] | a <- tvs]
(H.TyCon (quickSpec "Observe") $
[H.TyCon (prelude "Int") []]
++ [H.TyCon (obsName tc) (map H.TyVar tvs)]
++ [H.TyCon tc (map H.TyVar tvs)]
)
[funDecl (quickSpec "observe") []
(Apply (obFuName tc) [])
]
]
else []
_ -> []
tr_sort :: Sort a -> Decl a
tr_sort (Sort s _ i) | null i = TypeDef (TyCon s []) (TyCon (prelude "Int") [])
tr_sort (Sort _ _ _) = error "Haskell.Translate: Poly-kinded abstract sort"
tr_sig :: Signature a -> [Decl a]
tr_sig (Signature f _ pt) =
newtype f_NT = f_Mk ( forall tvs . ( Arbitrary a , CoArbitrary a ) = > T )
[ DataDecl (Derived f "") [] [ (Derived f "Mk",[tr_polyTypeArbitrary pt]) ] []
, FunDecl (Derived f "get")
[( [H.ConPat (Derived f "Mk") [VarPat (Derived f "x")]]
, var (Derived f "x")
)]
, TySig f [] (tr_polyType pt)
, funDecl f [] (Apply (Derived f "get") [ImpVar (Derived f "imp")])
instance Arbitrary f_NT where
, InstDecl [] (TyCon (quickCheck "Arbitrary") [TyCon (Derived f "") []])
[ funDecl (quickCheck "arbitrary") []
(mkDo [Bind (Derived f "x") (Apply (quickCheckUnsafe "capture") [])]
(H.Case (var (Derived f "x"))
[(H.ConPat (quickCheckUnsafe "Capture") [VarPat (Derived f "y")]
,Apply (prelude "return")
[Apply (Derived f "Mk")
[Apply (Derived f "y")
[Apply (quickCheck "arbitrary") []]]]
)]
)
)
]
, TySig (Derived f "gen") []
(TyCon (quickCheck "Gen")
[TyCon (constraints "Dict")
[TyImp (Derived f "imp") (TyCon (Derived f "") [])]])
, funDecl (Derived f "gen") []
(mkDo [Bind (Derived f "x") (Apply (quickCheck "arbitrary") [])]
(ImpLet (Derived f "imp") (var (Derived f "x"))
(Apply (prelude "return") [Apply (constraints "Dict") []])))
]
tr_func :: Function a -> [Decl a]
tr_func fn@Function{..} =
[ TySig func_name [] (tr_polyType (funcType fn))
, FunDecl
func_name
[ (map tr_deepPattern dps,tr_expr Expr rhs)
| (dps,rhs) <- patternMatchingView func_args func_body
]
] ++
[ FunDecl
(prop_version func_name)
[ (map tr_deepPattern dps,tr_expr Formula rhs)
| (dps,rhs) <- patternMatchingView func_args func_body
]
| isLazySmallCheck mode
&& with_parallel_functions mode
&& func_res == boolType
]
prop_version f = Derived f "property"
tr_asserts :: [T.Formula a] -> [Decl a]
tr_asserts fms =
let (info,decls) = unzip (zipWith tr_assert [1..] fms)
in concat decls ++
case mode of
QuickCheck ->
[ TH (Apply (prelude "return") [List []])
, funDecl (Exact "main") []
(mkDo [ Stmt (THSplice (Apply (quickCheckAll "polyQuickCheck")
[QuoteName name]))
| (name,_) <- info ]
Noop)
]
LazySmallCheck{..} ->
[ funDecl (Exact "main") []
((`mkDo` Noop)
$ [Bind (Exact "args") (Apply (sysEnv "getArgs") [])]
++ [Stmt (fn name) | (name,_) <- info])
]
where
fn name = case with_depth_as_argument of
False -> Apply (lsc "test") [var name]
True -> Apply (lsc "depthCheck")
[read_head (var (Exact "args"))
,var name]
Feat ->
[ funDecl (Exact "main") []
(mkDo [Stmt (Apply (feat "featCheckStop")
[ H.Lam [TupPat (map VarPat vs)] (Apply name (map var vs))
])
| (name,vs) <- info ] Noop)
]
Smten | let [(name,vs)] = info ->
[ funDecl (Exact "main") []
$ mkDo [Bind (Exact "args") (Apply (smtenEnv "getArgs") [])
,Bind (Exact "r")
(Apply (smtenSym "run_symbolic")
[Apply (smtenMinisat "minisat") []
,mkDo (
[ Bind v (Apply (Exact "space") [read_head (var (Exact "args"))])
| v <- vs ]
++
[ Stmt $ Apply (smtenMonad "guard") [Apply (prelude "not") [Apply name (map var vs)]] ])
(Apply (smtenMonad "return") [nestedTup (map var vs)])
])
]
(Apply (prelude "print") [var (Exact "r")])
]
_ -> []
where
read_head e = Apply (prelude "read") [Apply (prelude "head") [e]]
tr_assert :: Int -> T.Formula a -> ((a,[a]),[Decl a])
tr_assert i T.Formula{..} =
((prop_name,args),
[ TySig prop_name []
(foldr TyArr
(case mode of LazySmallCheck{} -> H.TyCon (lsc "Property") []
_ -> H.TyCon (prelude "Bool") [])
[ trType (applyType fm_tvs (replicate (length fm_tvs) (intType)) t)
| Local _ t <- typed_args ])
| mode == Feat || isLazySmallCheck mode || mode == Smten ]
++
[ funDecl prop_name args (assume (tr_expr (if mode == Feat || isSmten mode then Expr else Formula) body)) ]
)
where
prop_name | i == 1 = Exact "prop"
| otherwise = Exact ("prop" ++ show i)
(typed_args,body) =
case fm_body of
Quant _ Forall lcls term -> (lcls,term)
_ -> ([],fm_body)
args = map lcl_name typed_args
assume e =
case fm_role of
Prove -> e
tr_deepPattern :: DeepPattern a -> H.Pat a
tr_deepPattern (DeepConPat Global{..} dps) = H.ConPat gbl_name (map tr_deepPattern dps)
tr_deepPattern (DeepVarPat Local{..}) = VarPat lcl_name
tr_deepPattern (DeepLitPat (T.Int i)) = IntPat i
tr_deepPattern (DeepLitPat (Bool b)) = withBool H.ConPat b
tr_pattern :: T.Pattern a -> H.Pat a
tr_pattern Default = WildPat
tr_pattern (T.ConPat Global{..} xs) = H.ConPat gbl_name (map (VarPat . lcl_name) xs)
tr_pattern (T.LitPat (T.Int i)) = H.IntPat i
tr_pattern (T.LitPat (Bool b)) = withBool H.ConPat b
tr_expr :: Kind -> T.Expr a -> H.Expr a
tr_expr k e0 =
case e0 of
Builtin (Lit (T.Int i)) :@: [] -> H.Int i
Builtin (Lit (Bool b)) :@: [] -> lsc_lift (withBool Apply b)
Builtin Implies :@: [u,v] | mode == Smten -> tr_expr k (Builtin Or :@: [Builtin Not :@: [u],v])
hd :@: es -> let ((f,k'),lft) = tr_head (map exprType es) k hd
in lift_if lft (maybe_ty_sig e0 (Apply f (map (tr_expr k') es)))
Lcl x -> lsc_lift (var (lcl_name x))
T.Lam xs b -> H.Lam (map (VarPat . lcl_name) xs) (tr_expr Expr b)
Match e alts -> H.Case (tr_expr Expr e) [ (tr_pattern p,tr_expr brs_k rhs) | T.Case p rhs <- default_last alts ]
where
brs_k
| isLazySmallCheck mode = k
| otherwise = Expr
T.Let x e b -> H.Let (lcl_name x) (tr_expr Expr e) (tr_expr k b)
T.Quant _ q xs b ->
foldr
(\ x e ->
Apply (tipDSL (case q of Forall -> "forAll"; Exists -> "exists"))
[H.Lam [VarPat (lcl_name x)] e])
(tr_expr Formula b)
xs
T.LetRec{} -> ERROR("letrec not supported")
where
maybe_ty_sig e@(hd@(Gbl Global{..}) :@: es) he
| isNothing (makeGlobal gbl_name gbl_type (map exprType es) Nothing)
= he ::: trType (exprType e)
maybe_ty_sig _ he = he
lift_if b e
| b && isLazySmallCheck mode = Apply (lsc "lift") [e]
| otherwise = e
lsc_lift = lift_if (k == Formula)
default_last (def@(T.Case Default _):alts) = alts ++ [def]
default_last alts = alts
tr_head :: [T.Type a] -> Kind -> T.Head a -> ((a,Kind),Bool)
tr_head ts k (Builtin b) = tr_builtin ts k b
tr_head ts k (Gbl Global{..})
| stay_prop = ((prop_version gbl_name,Expr),False)
| otherwise = ((gbl_name ,Expr),k == Formula)
where
stay_prop = k == Formula
&& isLazySmallCheck mode
&& with_parallel_functions mode
&& polytype_res gbl_type == boolType
tr_builtin :: [T.Type a] -> Kind -> T.Builtin -> ((a,Kind),Bool)
tr_builtin ts k b =
case b of
At -> ((prelude "id",Expr),False)
Lit{} -> error "tr_builtin"
And -> case_kind (tipDSL ".&&.") (Just (lsc "*&*"))
Or -> case_kind (tipDSL ".||.") (Just (lsc "*|*"))
Not -> case_kind (tipDSL "neg") (Just (lsc "neg"))
Implies -> case_kind (tipDSL "==>") (Just (lsc "*=>*"))
Equal -> case_kind (tipDSL "===") $ case ts of
BuiltinType Boolean:_ -> Just (lsc "*=*")
_ -> Nothing
Distinct -> case_kind (tipDSL "=/=") Nothing
_ -> (prelude_fn,False)
where
Just prelude_str_ = lookup b hsBuiltins
prelude_fn = (prelude prelude_str_,Expr)
case_kind tip_version lsc_version =
case k of
Expr -> (prelude_fn,False)
Formula ->
case mode of
LazySmallCheck{} ->
case lsc_version of
Just v -> ((v,Formula),False)
Nothing -> (prelude_fn,True)
_ -> ((tip_version,Formula),False)
tr_polyType_inner :: T.PolyType a -> H.Type a
tr_polyType_inner (PolyType _ ts t) = trType (ts :=>: t)
tr_polyType :: T.PolyType a -> H.Type a
tr_polyType pt@(PolyType tvs _ _) =
TyForall tvs (TyCtx (arb tvs ++ imps) (tr_polyType_inner pt))
translate type and add Arbitrary a , CoArbitrary a in the context for
tr_polyTypeArbitrary :: T.PolyType a -> H.Type a
tr_polyTypeArbitrary pt@(PolyType tvs _ _) = TyForall tvs (TyCtx (arb tvs) (tr_polyType_inner pt))
arb = (arbitrary ob) . map H.TyVar
ob = case mode of
QuickSpec QuickSpecParams{..} -> use_observers
_ -> False
arbitrary :: Bool -> [H.Type (HsId a)] -> [H.Type (HsId a)]
arbitrary obs ts =
[ TyCon tc [t]
| t <- ts
, tc <- tcs]
where tcs = case obs of
quickCheck " Arbitrary " , quickCheck " " , typeable " " ]
False -> [quickCheck "Arbitrary", feat "Enumerable", prelude "Ord"]
trType :: (a ~ HsId b) => T.Type a -> H.Type a
trType (T.TyVar x) = H.TyVar x
trType (T.TyCon tc ts) = H.TyCon tc (map trType ts)
trType (ts :=>: t) = foldr TyArr (trType t) (map trType ts)
trType (BuiltinType b) = trBuiltinType b
trObsType :: (a ~ HsId b) => T.Type a -> H.Type a
trObsType (T.TyCon tc ts) = H.TyCon (obsName tc) (map trObsType ts)
trObsType t = trType t
obsName :: HsId a -> HsId a
obsName c = Derived c "Obs"
nullConsName :: HsId a -> HsId a
nullConsName c = Derived c "NullCons"
obFuName T_name = obsFunT_name
obFuName :: PrettyVar a => HsId a -> HsId a
obFuName c = Exact $ "obsFun" ++ varStr c
obFuType :: (a ~ HsId b) => a -> [a] -> H.Type a
obFuType c vs =
TyArr (TyVar $ prelude "Int") (TyArr (TyCon c (map (\x -> TyVar x) vs))
(TyCon (obsName c) (map (\x -> TyVar x) vs)))
nestObsName :: (a ~ HsId b, PrettyVar b) => T.Type a -> HsId b
nestObsName (T.TyCon tc ts) = Exact $ foldl (++) ("obsFun" ++ varStr tc) (map nestName ts)
where nestName (T.TyCon c s) = (foldr (++) (varStr c) (map nestName s))
nestName _ = ""
nestObsName _ = Exact ""
nestObsType :: (a ~ HsId b) => T.Type a -> H.Type a
nestObsType t = TyArr (TyVar $ prelude "Int") (TyArr (trType t) (trObsType t))
nestedObsFuns :: (a ~ HsId b, Eq b, PrettyVar b) => Theory a -> Datatype a -> [Decl a]
nestedObsFuns thy dt@(Datatype tc _ tvs cons) = concat $ catMaybes $ concatMap (nestedObs thy) cons
nestedObs :: (a ~ HsId b, Eq b, PrettyVar b) => Theory a -> Constructor a -> [Maybe [Decl a]]
nestedObs thy (Constructor _ _ _ as) = map ((nestObs thy) . snd) as
nestObs :: (a ~ HsId b, Eq b, PrettyVar b) => Theory a -> T.Type a -> Maybe [Decl a]
nestObs Theory{..} t@(T.TyCon tc ts) = case find (\x -> (data_name x == tc)) thy_datatypes of
Just dt ->
if nestObsName t == obFuName tc
then Nothing
else Just $ obsFun dt ts (nestObsName t) (nestObsType t) True
_ -> Nothing
nestObs _ _ = Nothing
obsFun :: (a ~ HsId b, Eq b, PrettyVar b) => Datatype a -> [T.Type a] -> a -> H.Type a -> Bool -> [Decl a]
obsFun (Datatype tname _ _ cons) targs fuName fuType recu =
[TySig fuName [] fuType, FunDecl fuName cases]
where
cases = [
([H.VarPat (Exact "0"),
H.VarPat (Exact "_")], Apply (nullConsName tname) [])
,([H.VarPat n, H.VarPat x],
H.Case (Apply (prelude "<") [var n, H.Int 0])
[(H.ConPat (prelude "True") [],
Apply fuName [Apply (prelude "negate") [var n], var x])
,(H.ConPat (prelude "False") [],
H.Case (var x) $
[(H.ConPat cname $ varNames cargs,
approx recu cname (map snd cargs) (listToMaybe targs) fuName tname)
| Constructor cname _ _ cargs <- cons]
)
])]
n = Exact "n"
x = Exact "x"
varNames as = map (\((c,a),b) -> mkVar b a) (zip as [0..])
mkVar n (T.TyVar _) = H.VarPat (Exact $ "x" ++ (show n))
mkVar n (T.TyCon tc ts) = H.ConPat (Exact $ "x" ++ (show n)) []
mkVar n (BuiltinType b)
| Just ty <- lookup b hsBuiltinTys = H.ConPat (Exact $ "x" ++ (show n)) []
| otherwise = __
mkVar _ _ = WildPat
approx :: (a ~ HsId b, Eq b, PrettyVar b) => Bool -> a -> [T.Type a] -> Maybe (T.Type a) -> a -> a -> H.Expr a
approx recu c as ta fn nm | recu = Apply (obsName c) $ map (recappstep as ta fn nm) (zip as [0..])
| otherwise = Apply (obsName c) $ map (appstep as nm) (zip as [0..])
where
appstep as nm (t@(T.TyCon _ _), k) =
Apply (nestObsName t) [decrement $ countBranches as nm
, varName k]
appstep _ _ (_, k) = varName k
recappstep as _ fn nm (t@(T.TyCon _ _), k) =
Apply fn $ [decrement $ countBranches as nm
, varName k]
recappstep as (Just ta) fn nm (t@(T.TyVar x), k) =
Apply (nestObsName ta) $ [decrement $ countBranches as nm
,varName k]
recappstep _ _ _ _ (_,k) = varName k
varName k = var (Exact $ "x" ++ (show k))
decrement :: (a ~ HsId b) => Int -> H.Expr a
decrement k =
if k <= 1
then
Apply (prelude "-") [var n, H.Int 1]
else
Apply (prelude "quot") [var n, H.Int $ toInteger k]
where
n = Exact "n"
countBranches :: [T.Type a] -> a -> Int
countBranches as n =
foldr (+) 0 (map bcount as)
where
bcount (T.TyCon tc ts) = foldr (+) (isBranch tc) (map bcount ts)
bcount _ = 0
isBranch n = 1
isBranch _ = 0
trBuiltinType :: BuiltinType -> H.Type (HsId a)
trBuiltinType t
| Just ty <- lookup t hsBuiltinTys = H.TyCon ty []
| otherwise = __
withBool :: (a ~ HsId b) => (a -> [c] -> d) -> Bool -> d
withBool k b = k (prelude (show b)) []
hsBuiltinTys :: [(T.BuiltinType, HsId a)]
hsBuiltinTys =
[ (Integer, prelude "Int")
, (Real, ratio "Rational")
, (Boolean, prelude "Bool")
]
hsBuiltins :: [(T.Builtin,String)]
hsBuiltins =
[ (Equal , "==" )
, (Distinct , "/=" )
, (NumAdd , "+" )
, (NumSub , "-" )
, (NumMul , "*" )
, (NumDiv , "/" )
, (IntDiv , "div")
, (IntMod , "mod")
, (NumGt , ">" )
, (NumGe , ">=" )
, (NumLt , "<" )
, (NumLe , "<=" )
, (NumWiden , "fromIntegral")
, (And , "&&" )
, (Or , "||" )
, (Not , "not")
, (Implies , "<=" )
]
typesOfBuiltin :: Builtin -> [T.Type a]
typesOfBuiltin b = case b of
And -> [bbb]
Or -> [bbb]
Not -> [bb]
Implies -> [bbb]
NumAdd -> [iii, rrr]
NumSub -> [iii, rrr]
NumMul -> [iii, rrr]
NumDiv -> [rrr]
IntDiv -> [iii]
IntMod -> [iii, rrr]
NumGt -> [iib, rrb]
NumGe -> [iib, rrb]
NumLt -> [iib, rrb]
NumLe -> [iib, rrb]
NumWiden -> [ir]
Lit (T.Int _) -> [intType]
Lit (Bool _) -> [boolType]
_ -> error ("can't translate built-in: " ++ show b)
where
bb = [boolType] :=>: boolType
bbb = [boolType,boolType] :=>: boolType
iii = [intType,intType] :=>: intType
iib = [intType,intType] :=>: boolType
rrr = [realType,realType] :=>: realType
rrb = [realType,realType] :=>: boolType
ir = [intType] :=>: realType
* signatures
data QuickSpecParams =
QuickSpecParams {
foreground_functions :: Maybe [String],
predicates :: Maybe [String],
use_observers :: Bool,
use_completion :: Bool,
max_size :: Int,
max_test_size :: Int
}
deriving (Eq, Ord, Show)
makeSig :: forall a . (PrettyVar a, Ord a) => QuickSpecParams -> Theory (HsId a) -> Decl (HsId a)
makeSig qspms@QuickSpecParams{..} thy@Theory{..} =
funDecl (Exact "sig") [] $ List $
[constant_decl ft
| ft@(f,_) <- func_constants, inForeground f] ++
bg
++
[ mk_inst [] (mk_class (feat "Enumerable") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (feat "Enumerable") (H.TyCon (prelude "Rational") [])) ] ++
[ mk_inst [] (mk_class (feat "Enumerable") (H.TyCon (prelude "Bool") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "Arbitrary") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "Arbitrary") (H.TyCon (prelude "Rational") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "Arbitrary") (H.TyCon (prelude "Bool") [])) ] ++
[ mk_inst [] (mk_class (typeable "Typeable") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "CoArbitrary") (H.TyCon (prelude "Int") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "CoArbitrary") (H.TyCon (prelude "Rational") [])) ] ++
[ mk_inst [] (mk_class (quickCheck "CoArbitrary") (H.TyCon (prelude "Bool") [])) ] ++
[ mk_inst (map (mk_class c1) tys) (mk_class c2 (H.TyCon t tys))
| (t,n) <- type_univ
, (c1, c2) <- [(prelude "Ord", prelude "Ord"),
(feat "Enumerable", feat "Enumerable")]
, let tys = map trType (qsTvs n)
] ++
[ mk_inst [mk_class c ty | c <- cs, ty <- tys] (mk_class c2 (H.TyCon t tys))
| (t,n) <- type_univ
, (cs,c2) <- [([quickCheck "Arbitrary", quickCheck "CoArbitrary"],quickCheck "CoArbitrary"),
([typeable "Typeable"], typeable "Typeable")]
, let tys = map trType (qsTvs n)
] ++
[ mk_inst (map (mk_class (feat "Enumerable")) tys)
(mk_class (quickCheck "Arbitrary") (H.TyCon t tys))
| (t,n) <- type_univ, t `notElem` (map (\(a,b,c) -> a) obsTriples)
, let tys = map trType (qsTvs n)
] ++
[ mk_inst ((map (mk_class (typeable "Typeable")) tys)
++ (map (mk_class (quickCheck "Arbitrary")) tys)
) (mk_class (quickCheck "Arbitrary") (H.TyCon t tys))
| (t,n) <- type_univ, t `elem` (map (\(a,b,c) -> a) obsTriples)
, let tys = map trType (qsTvs n)
] ++
[ mk_inst ((map (mk_class (prelude "Ord")) tys)
++ (map (mk_class (quickCheck "Arbitrary")) tys)
) (H.TyCon (quickSpec "Observe") $
[H.TyCon (prelude "Int") []]
++ [H.TyCon (obsName t) tys]
++ [H.TyCon t tys])
| (t,n) <- type_univ, t `elem` (map (\(a,b,c) -> a) obsTriples)
, let tys = map trType (qsTvs n)
] ++
[ Apply (quickSpec "inst") [H.Lam [TupPat []] (Apply (Derived f "gen") [])]
| Signature f _ _ <- thy_sigs
] ++
[Apply (quickSpec "withMaxTermSize") [H.Int (fromIntegral max_size)]] ++
[Apply (quickSpec "withMaxTestSize") [H.Int (fromIntegral max_test_size)]] ++
[Apply (quickSpec "withPruningDepth") [H.Int 0] | not use_completion]
where
inForeground f =
case foreground_functions of
Nothing -> True
Just fs -> varStr f `elem` fs
inPredicates p =
case predicates of
Nothing -> True
Just ps -> varStr p `elem` ps
bg = case bgs of
[] -> []
_ -> [Apply (quickSpec "background") [List bgs]]
bgs = [constant_decl ft
| ft@(f,_) <- func_constants,
not (inForeground f) ]
++ builtin_decls
++ map constant_decl (ctor_constants ++ builtin_constants)
imps = ufInfo thy
int_lit x = H.Int x ::: H.TyCon (prelude "Int") []
mk_inst ctx res =
Apply (quickSpec "inst")
[ Apply (constraints "Sub") [Apply (constraints "Dict") []] :::
H.TyCon (constraints ":-") [TyTup ctx,res] ]
mk_class c x = H.TyCon c [x]
scp = scope thy
poly_type (PolyType _ args res) = args :=>: res
constant_decl (f,t) =
FIXME : If there are more than 6 constraints quickspec wo n't find properties
Apply (quickSpec conOrPred) [H.String f,lam (Apply f []) ::: qs_type]
where
(_pre,qs_type) = qsType t
lam = H.Lam [H.ConPat (constraints "Dict") []]
conOrPred =
case t of
_ :=>: BuiltinType Boolean | inPredicates f -> "predicate"
_ -> "con"
int_lit_decl x =
Apply (quickSpec "con") [H.String (Exact (show x)),int_lit x]
bool_lit_decl b =
Apply (quickSpec "con") [H.String (prelude (show b)),withBool Apply b]
ctor_constants =
[ (f,poly_type (globalType g))
| (f,g@ConstructorInfo{}) <- M.toList (globals scp)
]
func_constants =
[ (f,poly_type (globalType g))
| (f,g@FunctionInfo{}) <- M.toList (globals scp)
]
type_univ =
[ (data_name, length data_tvs)
| (_,DatatypeInfo Datatype{..}) <- M.toList (types scp)
]
obsTriples =
[(data_name, obsName data_name, obFuName data_name)
| (_,DatatypeInfo dt@Datatype{..}) <- M.toList (types scp),
use_observers
]
(builtin_lits,builtin_funs) =
partition (litBuiltin . fst) $
usort
[ (b, map exprType args :=>: exprType e)
| e@(Builtin b :@: args) <- universeBi thy ]
used_builtin_types :: [BuiltinType]
used_builtin_types =
usort [ t | BuiltinType t :: T.Type (HsId a) <- universeBi thy ]
bool_used = Boolean `elem` used_builtin_types
or [ op `elem` map fst builtin_funs | op <- [NumAdd,NumSub,NumMul,NumDiv,IntDiv,IntMod] ]
builtin_decls
= [ bool_lit_decl b | bool_used, b <- [False,True] ]
++ [ int_lit_decl x | num_used, x <- nub $
[0,1] ++
[ x
| Lit (T.Int x) <- map fst builtin_lits ]]
builtin_constants
= [ (prelude s, ty)
| (b, ty) <- nub $
[ (b, ty) | (b, ty) <- builtin_funs, numBuiltin b ]
, Just s <- [lookup b hsBuiltins]
]
qsType :: Ord a => T.Type (HsId a) -> ([H.Type (HsId a)],H.Type (HsId a))
qsType t = (pre, TyArr (TyCon (constraints "Dict") [tyTup pre]) inner)
FIXME : can we curry the constraints so we do n't get tuples of more than 6 ?
where
pre = arbitrary use_observers (map trType qtvs) ++ imps
put each of qtvs in separate ?
inner = trType (applyType tvs qtvs t)
qtvs = qsTvs (length tvs)
tvs = tyVars t
Transform big tuples of constraints into nested tuples
( because QuickSpec does n't understand arbitrary tuples of constraints )
tyTup [] = TyTup []
tyTup [ty] = ty
tyTup (ty:tys) = TyTup [ty, tyTup tys]
qsTvs :: Int -> [T.Type (HsId a)]
qsTvs n = take n (cycle [ T.TyCon (quickSpec qs_tv) [] | qs_tv <- ["A","B","C","D","E"] ])
theoryBuiltins :: Ord a => Theory a -> [T.Builtin]
theoryBuiltins = usort . universeBi
|
3ed8ac00eebbb8872e87030ec0227246d44f81d64fbc0fdc041ba00dab10c822 | stassats/lisp-bots | misc.lisp | (defpackage :webutils.misc (:use :cl :araneida :webutils.application)
(:export :with-body-params :define-configuration-variable :reload-configuration-variables
:with-query-params
:expire-authorization-tokens :make-authorization-token :is-authorized
:expire-request-authorization :handler-url :define-handler-hierarchy))
(in-package :webutils.misc)
(webutils::export-all :webutils.misc)
(defun conanicalize-body-param (param)
(when param
(map 'string
#'(lambda (char)
(if (typep char 'base-char)
char
#\?)) param)))
(defmacro with-body-params (param-pairs request &body body)
(when (null body)
(error "I think you forgot the request argument to with-body-params."))
(let ((request-name (gensym)))
`(let* ((,request-name ,request)
,@(mapcar #'(lambda (param-pair)
(let ((bind-to (if (listp param-pair)
(first param-pair)
param-pair))
(param-name (if (listp param-pair)
(second param-pair)
(string-downcase (symbol-name param-pair)))))
`(,bind-to
(conanicalize-body-param
(body-param ,param-name
(request-body ,request-name))))))
param-pairs))
,@body)))
(defmacro with-query-params (param-pairs request &body body)
(when (null body)
(error "I think you forgot the request argument to with-query-params."))
(let ((url-name (gensym)))
`(let* ((,url-name (request-url ,request))
,@(mapcar #'(lambda (param-pair)
(let ((bind-to (if (listp param-pair)
(first param-pair)
param-pair))
(param-name (if (listp param-pair)
(second param-pair)
(string-downcase (symbol-name param-pair)))))
`(,bind-to
(first (url-query-param ,url-name ,param-name)))))
param-pairs))
,@body)))
(defparameter *configuration-variable-reload-hooks* nil)
(defmacro define-configuration-variable (variable value-load-form)
`(progn
(defparameter ,variable ,value-load-form)
(setf (cdr (or (assoc ',variable *configuration-variable-reload-hooks*)
(first (push (cons ',variable nil) *configuration-variable-reload-hooks*))))
(lambda ()
(declare (special ,variable))
(setf ,variable ,value-load-form)))))
(defun reload-configuration-variables ()
(loop for hook in (reverse *configuration-variable-reload-hooks*)
do (funcall (cdr hook))))
(defparameter *authorization-tokens* nil)
(defun expire-authorization-tokens (&key (timeout (* 60 60)) (filter (constantly nil)))
(let ((now (get-universal-time)))
(setf *authorization-tokens*
(remove-if #'(lambda (token)
(or (< (+ (first token) timeout) now)
(funcall filter (third token))))
*authorization-tokens*))))
(defun expire-request-authorization (request)
(let ((token (is-authorized request)))
(if token
(setf *authorization-tokens*
(remove token *authorization-tokens* :key #'second)))))
(defun make-authorization-token (&key extra (path "/"))
(let ((token (random 10000000)))
(push (list (get-universal-time) token extra)
*authorization-tokens*)
(format nil "AUTHTOKEN=~A; path=~A" token path)))
(defun is-authorized (request &key (update t) (extra nil extra-supplied-p) (test 'eql))
(let* ((token (parse-integer (or (request-cookie request "AUTHTOKEN") "-1") :junk-allowed t))
(found (find token *authorization-tokens* :key #'second)))
(when found
(when update (setf (first found) (get-universal-time)))
(if extra-supplied-p
(values (funcall test extra (third found)) token)
(values token (third found))))))
(defgeneric handler-url (handler-class-name))
(defmacro define-handler-hierarchy (listener-or-application &rest hierarchy)
(let (handler-class-definitions)
(multiple-value-bind (listener extra-superclasses)
(if (listp listener-or-application)
(ecase (first listener-or-application)
(:listener (values (second listener-or-application) nil))
(:application (values `(application-listener (find-application ',(second listener-or-application)))
(list (second listener-or-application))))))
a four of three elements - class name , superclasses , URL root , and inexact - p
(labels ((parse-root-group (root-group existing-root)
(let ((new-url (if existing-root
`(merge-url ,existing-root ,(first root-group))
(first root-group))))
(if (and (or (eql (length root-group) 2)
(eql (length root-group) 4))
(or (symbolp (second root-group))
(every #'symbolp (second root-group)))
(or (eql (length root-group) 2)
(and (eq (third root-group) :inexact))))
;; it's actually a single handler definition
(push (list (if (symbolp (second root-group))
(second root-group)
(first (second root-group)))
(if (symbolp (second root-group))
nil
(cdr (second root-group)))
new-url
(if (eq (length root-group) 4)
(fourth root-group)))
handler-class-definitions)
(loop for sub-root-group in (cdr root-group)
do (parse-root-group sub-root-group new-url))))))
(loop for group in hierarchy
do (parse-root-group group nil)))
`(progn
,@(loop for (class-name superclasses root-url inexact) in handler-class-definitions
with g = (gensym)
collect `(defclass ,class-name (handler ,@superclasses ,@extra-superclasses) ())
collect `(defmethod handler-url ((,g (eql ',class-name)))
,root-url)
collect `(install-handler (http-listener-handler ,listener)
(make-instance ',class-name)
(urlstring (handler-url ',class-name))
(not ,inexact))))))) | null | https://raw.githubusercontent.com/stassats/lisp-bots/09bfce724afd20c91a08acde8816be6faf5f54b2/webutils/misc.lisp | lisp | it's actually a single handler definition | (defpackage :webutils.misc (:use :cl :araneida :webutils.application)
(:export :with-body-params :define-configuration-variable :reload-configuration-variables
:with-query-params
:expire-authorization-tokens :make-authorization-token :is-authorized
:expire-request-authorization :handler-url :define-handler-hierarchy))
(in-package :webutils.misc)
(webutils::export-all :webutils.misc)
(defun conanicalize-body-param (param)
(when param
(map 'string
#'(lambda (char)
(if (typep char 'base-char)
char
#\?)) param)))
(defmacro with-body-params (param-pairs request &body body)
(when (null body)
(error "I think you forgot the request argument to with-body-params."))
(let ((request-name (gensym)))
`(let* ((,request-name ,request)
,@(mapcar #'(lambda (param-pair)
(let ((bind-to (if (listp param-pair)
(first param-pair)
param-pair))
(param-name (if (listp param-pair)
(second param-pair)
(string-downcase (symbol-name param-pair)))))
`(,bind-to
(conanicalize-body-param
(body-param ,param-name
(request-body ,request-name))))))
param-pairs))
,@body)))
(defmacro with-query-params (param-pairs request &body body)
(when (null body)
(error "I think you forgot the request argument to with-query-params."))
(let ((url-name (gensym)))
`(let* ((,url-name (request-url ,request))
,@(mapcar #'(lambda (param-pair)
(let ((bind-to (if (listp param-pair)
(first param-pair)
param-pair))
(param-name (if (listp param-pair)
(second param-pair)
(string-downcase (symbol-name param-pair)))))
`(,bind-to
(first (url-query-param ,url-name ,param-name)))))
param-pairs))
,@body)))
(defparameter *configuration-variable-reload-hooks* nil)
(defmacro define-configuration-variable (variable value-load-form)
`(progn
(defparameter ,variable ,value-load-form)
(setf (cdr (or (assoc ',variable *configuration-variable-reload-hooks*)
(first (push (cons ',variable nil) *configuration-variable-reload-hooks*))))
(lambda ()
(declare (special ,variable))
(setf ,variable ,value-load-form)))))
(defun reload-configuration-variables ()
(loop for hook in (reverse *configuration-variable-reload-hooks*)
do (funcall (cdr hook))))
(defparameter *authorization-tokens* nil)
(defun expire-authorization-tokens (&key (timeout (* 60 60)) (filter (constantly nil)))
(let ((now (get-universal-time)))
(setf *authorization-tokens*
(remove-if #'(lambda (token)
(or (< (+ (first token) timeout) now)
(funcall filter (third token))))
*authorization-tokens*))))
(defun expire-request-authorization (request)
(let ((token (is-authorized request)))
(if token
(setf *authorization-tokens*
(remove token *authorization-tokens* :key #'second)))))
(defun make-authorization-token (&key extra (path "/"))
(let ((token (random 10000000)))
(push (list (get-universal-time) token extra)
*authorization-tokens*)
(format nil "AUTHTOKEN=~A; path=~A" token path)))
(defun is-authorized (request &key (update t) (extra nil extra-supplied-p) (test 'eql))
(let* ((token (parse-integer (or (request-cookie request "AUTHTOKEN") "-1") :junk-allowed t))
(found (find token *authorization-tokens* :key #'second)))
(when found
(when update (setf (first found) (get-universal-time)))
(if extra-supplied-p
(values (funcall test extra (third found)) token)
(values token (third found))))))
(defgeneric handler-url (handler-class-name))
(defmacro define-handler-hierarchy (listener-or-application &rest hierarchy)
(let (handler-class-definitions)
(multiple-value-bind (listener extra-superclasses)
(if (listp listener-or-application)
(ecase (first listener-or-application)
(:listener (values (second listener-or-application) nil))
(:application (values `(application-listener (find-application ',(second listener-or-application)))
(list (second listener-or-application))))))
a four of three elements - class name , superclasses , URL root , and inexact - p
(labels ((parse-root-group (root-group existing-root)
(let ((new-url (if existing-root
`(merge-url ,existing-root ,(first root-group))
(first root-group))))
(if (and (or (eql (length root-group) 2)
(eql (length root-group) 4))
(or (symbolp (second root-group))
(every #'symbolp (second root-group)))
(or (eql (length root-group) 2)
(and (eq (third root-group) :inexact))))
(push (list (if (symbolp (second root-group))
(second root-group)
(first (second root-group)))
(if (symbolp (second root-group))
nil
(cdr (second root-group)))
new-url
(if (eq (length root-group) 4)
(fourth root-group)))
handler-class-definitions)
(loop for sub-root-group in (cdr root-group)
do (parse-root-group sub-root-group new-url))))))
(loop for group in hierarchy
do (parse-root-group group nil)))
`(progn
,@(loop for (class-name superclasses root-url inexact) in handler-class-definitions
with g = (gensym)
collect `(defclass ,class-name (handler ,@superclasses ,@extra-superclasses) ())
collect `(defmethod handler-url ((,g (eql ',class-name)))
,root-url)
collect `(install-handler (http-listener-handler ,listener)
(make-instance ',class-name)
(urlstring (handler-url ',class-name))
(not ,inexact))))))) |
68d789a5fa2c236c2527ec39df591c3984b9bb1cfd7a9e67a6deaf115aca1c2c | bract/bract.core | dev.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns bract.core.dev
"Development and test support."
(:require
[clojure.java.javadoc :refer [javadoc]]
[clojure.pprint :refer [pprint]]
[clojure.repl :refer :all]
[clojure.string :as string]
[bract.core.keydef :as kdef]
[bract.core.echo :as echo]
[bract.core.inducer :as inducer]
[bract.core.main :as main]
[bract.core.util :as util])
(:import
[bract.core Echo]))
;; ----- overrides -----
(defn context-file
"Set context file to specified argument (unless environment variable `APP_CONTEXT` is set):
| Value | Effect |
|-------|------------------------------|
|string | set context file as override |
|`nil` | clear context file override |"
([]
(when-let [context-file (System/getenv "APP_CONTEXT")]
(util/err-println (format "Environment variable APP_CONTEXT='%s' overrides context file" context-file)))
(System/getProperty "app.context"))
([context-filename]
(if-let [env-context-file (System/getenv "APP_CONTEXT")]
(util/err-println (format "Override failed due to environment variable APP_CONTEXT='%s'" env-context-file))
(cond
(nil? context-filename) (do
(System/clearProperty "app.context")
nil)
(string? context-filename) (do
(System/setProperty "app.context" context-filename)
context-filename)
:otherwise (-> "Expected argument to be string or nil but found "
(str (pr-str context-filename))
(ex-info {:context-filename context-filename})
throw)))))
(defn verbose
"Set verbose mode to specified status (unless environment variable `APP_VERBOSE` is set):
| Value | Effect |
|-------|-----------------------------|
|`true` | enable verbose mode |
|`false`| disable verbose mode |
|`nil` | clear verbose mode override |"
([]
(when-let [verbose (System/getenv "APP_VERBOSE")]
(util/err-println (format "Environment variable APP_VERBOSE='%s' overrides verbosity" verbose)))
(System/getProperty "app.verbose"))
([status?]
(if-let [verbose (System/getenv "APP_VERBOSE")]
(util/err-println (format "Override failed due to environment variable APP_VERBOSE='%s'" verbose))
(case status?
nil (System/clearProperty "app.verbose")
true (do (System/setProperty "app.verbose" "true") (Echo/setVerbose true))
false (do (System/setProperty "app.verbose" "false") (Echo/setVerbose false))
(throw (ex-info (str "Expected argument to be true, false or nil but found " (pr-str status?)) {}))))))
(defn config-files
"Set config files to specified argument (unless environment variable `APP_CONFIG` is set):
| Value | Effect |
|----------|------------------------------|
|collection| set config files as override |
|string | set config files as override |
|`nil` | clear config file override |"
([]
(when-let [config-filenames (System/getenv "APP_CONFIG")]
(util/err-println (format "Environment variable APP_CONFIG='%s' overrides config file" config-filenames)))
(System/getProperty "app.config"))
([config-filenames]
(if-let [env-config-filenames (System/getenv "APP_CONFIG")]
(util/err-println (format "Override failed due to environment variable APP_CONFIG='%s'" env-config-filenames))
(cond
(nil? config-filenames) (do
(System/clearProperty "app.config")
nil)
(and (coll? config-filenames)
(every? string?
config-filenames)) (let [filenames (string/join ", " config-filenames)]
(System/setProperty "app.config" filenames)
filenames)
(string? config-filenames) (do
(System/setProperty "app.config" config-filenames)
config-filenames)
:otherwise (-> "Expected argument to be collection of string, string or nil but found "
(str (pr-str config-filenames))
(ex-info {:config-filenames config-filenames})
throw)))))
;; ----- initial context -----
(def root-context {(key kdef/ctx-context-file) "bract-context.dev.edn"
(key kdef/ctx-config-files) ["config/config.dev.edn"]
(key kdef/ctx-dev-mode?) true
(key kdef/ctx-launch?) false})
(defonce ^:redef seed-context {})
(defn initial-context
"Resolve and return the initial context to trigger the application in DEV mode."
[]
(merge root-context seed-context))
;; ----- REPL helpers -----
(defn init
"Initialize app in DEV mode."
[]
(try
(let [init-context (initial-context)]
(inducer/set-verbosity init-context)
(echo/with-latency-capture "Initializing app in DEV mode"
(inducer/induce inducer/apply-inducer init-context main/root-inducers)))
(catch Throwable e
(util/pst-when-uncaught-handler e)
(throw e))))
(defonce ^:redef init-gate nil)
(defn init-once!
"Given a var e.g. (defonce a-var nil) having logical false value, set it to `true` and initialize app in DEV mode."
([]
(init-once! #'init-gate))
([a-var]
(util/exec-once! a-var
(init))))
(defonce ^:redef app-context (format "Var %s/app-context not initialized" *ns*))
(defn ensure-init
"Ensure that [[app-context]] is initialized."
[]
(when (string? app-context)
(init))
(when (string? app-context)
(throw (ex-info "Failed to ensure initialization. Add `bract.core.dev/record-context!` to your inducer list."
{}))))
(defn record-context!
"Rebind var [[app-context]] to the given context."
[context]
(alter-var-root #'app-context (constantly context))
context)
(defn deinit
"De-initialize application. Throw error if [[app-context]] is not initialized."
[]
(ensure-init)
(util/expected map? "app-context to be initialized as map using inducer bract.core.dev/record-context!" app-context)
(echo/with-latency-capture "De-initializing application"
(-> app-context
inducer/invoke-deinit
record-context!))
nil)
(defn start
"Launch application. Throw error if [[app-context]]` is not initialized."
[]
(ensure-init)
(util/expected map? "app-context to be initialized as map using inducer bract.core.dev/record-context!" app-context)
(echo/with-latency-capture "Launching application"
(-> app-context
(assoc (key kdef/ctx-launch?) true)
inducer/invoke-launchers
record-context!))
nil)
(defn stop
"Stop the started application."
[]
(ensure-init)
(util/expected map? "app-context to be initialized as map using inducer bract.core.dev/record-context!" app-context)
(echo/with-latency-capture "Stopping the started application"
(inducer/invoke-stopper app-context))
nil)
(defn -main
"Java main() method entry point for DEV mode."
[& args]
(let [init-context (-> (initial-context)
inducer/set-verbosity
(merge {(key kdef/ctx-cli-args) (vec args)})
(assoc (key kdef/ctx-launch?) true))]
(echo/with-latency-capture "Initializing app in DEV mode"
(main/delegate-main init-context main/root-inducers))))
(defn help
"Print help text for this namespace"
[]
(println "
REPL helpers available in bract.core.dev:
See this help: (help)
Start app: (start)
Stop app: (stop)
Set verbosity mode: (verbose true-or-false)
Set context-file: (context-file \"context-filename\")
See initialized context: app-context
Set config files: (config-files [\"file1\" \"file2\"])
Initialize app (no launch): (init)
Deinitialize app (no stop): (deinit)
"))
| null | https://raw.githubusercontent.com/bract/bract.core/625b8738554b1e1b61bd8522397fb698fb12d3d3/src/bract/core/dev.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file LICENSE at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
----- overrides -----
----- initial context -----
----- REPL helpers ----- | Copyright ( c ) . All rights reserved .
(ns bract.core.dev
"Development and test support."
(:require
[clojure.java.javadoc :refer [javadoc]]
[clojure.pprint :refer [pprint]]
[clojure.repl :refer :all]
[clojure.string :as string]
[bract.core.keydef :as kdef]
[bract.core.echo :as echo]
[bract.core.inducer :as inducer]
[bract.core.main :as main]
[bract.core.util :as util])
(:import
[bract.core Echo]))
(defn context-file
"Set context file to specified argument (unless environment variable `APP_CONTEXT` is set):
| Value | Effect |
|-------|------------------------------|
|string | set context file as override |
|`nil` | clear context file override |"
([]
(when-let [context-file (System/getenv "APP_CONTEXT")]
(util/err-println (format "Environment variable APP_CONTEXT='%s' overrides context file" context-file)))
(System/getProperty "app.context"))
([context-filename]
(if-let [env-context-file (System/getenv "APP_CONTEXT")]
(util/err-println (format "Override failed due to environment variable APP_CONTEXT='%s'" env-context-file))
(cond
(nil? context-filename) (do
(System/clearProperty "app.context")
nil)
(string? context-filename) (do
(System/setProperty "app.context" context-filename)
context-filename)
:otherwise (-> "Expected argument to be string or nil but found "
(str (pr-str context-filename))
(ex-info {:context-filename context-filename})
throw)))))
(defn verbose
"Set verbose mode to specified status (unless environment variable `APP_VERBOSE` is set):
| Value | Effect |
|-------|-----------------------------|
|`true` | enable verbose mode |
|`false`| disable verbose mode |
|`nil` | clear verbose mode override |"
([]
(when-let [verbose (System/getenv "APP_VERBOSE")]
(util/err-println (format "Environment variable APP_VERBOSE='%s' overrides verbosity" verbose)))
(System/getProperty "app.verbose"))
([status?]
(if-let [verbose (System/getenv "APP_VERBOSE")]
(util/err-println (format "Override failed due to environment variable APP_VERBOSE='%s'" verbose))
(case status?
nil (System/clearProperty "app.verbose")
true (do (System/setProperty "app.verbose" "true") (Echo/setVerbose true))
false (do (System/setProperty "app.verbose" "false") (Echo/setVerbose false))
(throw (ex-info (str "Expected argument to be true, false or nil but found " (pr-str status?)) {}))))))
(defn config-files
"Set config files to specified argument (unless environment variable `APP_CONFIG` is set):
| Value | Effect |
|----------|------------------------------|
|collection| set config files as override |
|string | set config files as override |
|`nil` | clear config file override |"
([]
(when-let [config-filenames (System/getenv "APP_CONFIG")]
(util/err-println (format "Environment variable APP_CONFIG='%s' overrides config file" config-filenames)))
(System/getProperty "app.config"))
([config-filenames]
(if-let [env-config-filenames (System/getenv "APP_CONFIG")]
(util/err-println (format "Override failed due to environment variable APP_CONFIG='%s'" env-config-filenames))
(cond
(nil? config-filenames) (do
(System/clearProperty "app.config")
nil)
(and (coll? config-filenames)
(every? string?
config-filenames)) (let [filenames (string/join ", " config-filenames)]
(System/setProperty "app.config" filenames)
filenames)
(string? config-filenames) (do
(System/setProperty "app.config" config-filenames)
config-filenames)
:otherwise (-> "Expected argument to be collection of string, string or nil but found "
(str (pr-str config-filenames))
(ex-info {:config-filenames config-filenames})
throw)))))
(def root-context {(key kdef/ctx-context-file) "bract-context.dev.edn"
(key kdef/ctx-config-files) ["config/config.dev.edn"]
(key kdef/ctx-dev-mode?) true
(key kdef/ctx-launch?) false})
(defonce ^:redef seed-context {})
(defn initial-context
"Resolve and return the initial context to trigger the application in DEV mode."
[]
(merge root-context seed-context))
(defn init
"Initialize app in DEV mode."
[]
(try
(let [init-context (initial-context)]
(inducer/set-verbosity init-context)
(echo/with-latency-capture "Initializing app in DEV mode"
(inducer/induce inducer/apply-inducer init-context main/root-inducers)))
(catch Throwable e
(util/pst-when-uncaught-handler e)
(throw e))))
(defonce ^:redef init-gate nil)
(defn init-once!
"Given a var e.g. (defonce a-var nil) having logical false value, set it to `true` and initialize app in DEV mode."
([]
(init-once! #'init-gate))
([a-var]
(util/exec-once! a-var
(init))))
(defonce ^:redef app-context (format "Var %s/app-context not initialized" *ns*))
(defn ensure-init
"Ensure that [[app-context]] is initialized."
[]
(when (string? app-context)
(init))
(when (string? app-context)
(throw (ex-info "Failed to ensure initialization. Add `bract.core.dev/record-context!` to your inducer list."
{}))))
(defn record-context!
"Rebind var [[app-context]] to the given context."
[context]
(alter-var-root #'app-context (constantly context))
context)
(defn deinit
"De-initialize application. Throw error if [[app-context]] is not initialized."
[]
(ensure-init)
(util/expected map? "app-context to be initialized as map using inducer bract.core.dev/record-context!" app-context)
(echo/with-latency-capture "De-initializing application"
(-> app-context
inducer/invoke-deinit
record-context!))
nil)
(defn start
"Launch application. Throw error if [[app-context]]` is not initialized."
[]
(ensure-init)
(util/expected map? "app-context to be initialized as map using inducer bract.core.dev/record-context!" app-context)
(echo/with-latency-capture "Launching application"
(-> app-context
(assoc (key kdef/ctx-launch?) true)
inducer/invoke-launchers
record-context!))
nil)
(defn stop
"Stop the started application."
[]
(ensure-init)
(util/expected map? "app-context to be initialized as map using inducer bract.core.dev/record-context!" app-context)
(echo/with-latency-capture "Stopping the started application"
(inducer/invoke-stopper app-context))
nil)
(defn -main
"Java main() method entry point for DEV mode."
[& args]
(let [init-context (-> (initial-context)
inducer/set-verbosity
(merge {(key kdef/ctx-cli-args) (vec args)})
(assoc (key kdef/ctx-launch?) true))]
(echo/with-latency-capture "Initializing app in DEV mode"
(main/delegate-main init-context main/root-inducers))))
(defn help
"Print help text for this namespace"
[]
(println "
REPL helpers available in bract.core.dev:
See this help: (help)
Start app: (start)
Stop app: (stop)
Set verbosity mode: (verbose true-or-false)
Set context-file: (context-file \"context-filename\")
See initialized context: app-context
Set config files: (config-files [\"file1\" \"file2\"])
Initialize app (no launch): (init)
Deinitialize app (no stop): (deinit)
"))
|
6e991f2e0118db5d9724474d72a0f9a61d64ce19bbe4eaf4540aa9d74f5999c5 | cloudkj/lambda-ml | neural_network.clj | (ns lambda-ml.neural-network
"Multilayer perceptron neural network learning using backpropagation.
Example usage:
```
(def data [[0 0 [0]] [0 1 [1]] [1 0 [1]] [1 1 [0]]])
(def fit
(let [alpha 0.5
lambda 0.001
model (-> (make-neural-network alpha lambda)
(add-neural-network-layer 2 sigmoid) ;; input layer
(add-neural-network-layer 3 sigmoid) ;; hidden layer
(add-neural-network-layer 1 sigmoid))] ;; output layer
(-> (iterate #(neural-network-fit % data) model)
(nth 5000))))
(neural-network-predict fit (map butlast data))
= > [ [ 0.04262340225834812 ] [ 0.9582632706756758 ] [ 0.9581124103456861 ] [ 0.04103544440312673 ] ]
```"
(:require [lambda-ml.core :as c]
[clojure.core.matrix :as m]))
(m/set-current-implementation :vectorz)
(def bias (m/matrix [1.0]))
(def epsilon 0.0001)
(defn drop-bias
[m]
(m/submatrix m 1 [1 (dec (m/column-count m))]))
(defn feed-forward
"Returns the activation values for nodes in a neural network after forward
propagating the values of a single input example x through the network."
[x theta fns]
(reduce (fn [activations [weights f]]
(let [inputs (if (empty? activations) (m/matrix x) (last activations))
inputs+bias (m/join bias inputs)
outputs (m/emap f (m/mmul weights inputs+bias))]
(conj activations outputs)))
[]
(map vector theta fns)))
(defn feed-forward-batch
"Returns the activation values for nodes in a neural network after forward
propagating a collection of input examples x through the network."
[x theta fns]
(-> (reduce (fn [inputs [weights f]]
(let [bias (m/broadcast 1.0 [1 (m/column-count inputs)])
inputs+bias (m/join bias inputs)
outputs (m/emap f (m/mmul weights inputs+bias))]
outputs))
(m/transpose (m/matrix x))
(map vector theta fns))
(m/transpose)))
(defn back-propagate
"Returns the errors of each node in a neural network after propagating the
the errors at the output nodes, computed against a single target value y,
backwards through the network."
[y theta fns' activations output-error]
(->> (map vector
(reverse (rest theta))
(reverse (butlast activations))
(reverse (butlast fns')))
(reduce (fn [errors [w a f]]
(cons (m/mul (m/emap f a) (m/mmul (first errors) (drop-bias w)))
errors))
(list (output-error y (last activations) (last fns'))))
(vec)))
(defn compute-gradients
"Returns the gradients for each weight given activation values and errors on
a input values of a single example x."
[x activations errors]
(->> (map vector errors (cons (m/matrix x) (butlast activations)))
(reduce (fn [gradients [e a]]
(let [a (m/join bias a)]
(conj gradients (m/outer-product e a))))
[])))
(defn numeric-gradients
"Returns the numeric approximations of the gradients for each weight given the
input values of a single example x and label y. Used for debugging by checking
against the computed gradients during backpropagation."
[x y theta fns cost]
(mapv (fn [k weights]
(m/matrix (for [i (range (m/row-count weights))]
(for [j (range (m/column-count weights))]
(let [w (m/select weights i j)
theta+ (assoc theta k (m/set-selection weights i j (+ w epsilon)))
theta- (assoc theta k (m/set-selection weights i j (- w epsilon)))]
(/ (- (cost (list x) (list y) theta+ fns)
(cost (list x) (list y) theta- fns))
(* 2 epsilon)))))))
(range)
theta))
(defn regularize
"Returns regularized weights."
[theta alpha lambda]
(map (fn [w]
(-> (m/mul alpha lambda w)
(m/set-column 0 (m/matrix (repeat (m/row-count w) 0)))))
theta))
(defn gradient-descent-step
"Performs a single gradient step on the input and target values of a single
example x and label y, and returns the updated weights."
[model x y theta]
(let [{fns :activation-fns alpha :alpha lambda :lambda
cost :cost output-error :output-error} model
activations (feed-forward x theta fns)
errors (back-propagate y theta (map c/derivative fns) activations output-error)
gradients (compute-gradients x activations errors)
regularization (regularize theta alpha lambda)]
;; Numeric gradient checking
( println ( map ( comp # ( / ( m / esum % ) ( m / ecount % ) ) m / abs m / sub ) gradients ( numeric - gradients x y theta fns cost ) ) )
(mapv m/sub theta (map #(m/mul % alpha) gradients) regularization)))
(defn gradient-descent
"Performs gradient descent on input and target values of all examples x and
y, and returns the updated weights."
[model x y]
(reduce (fn [weights [xi yi]] (gradient-descent-step model xi yi weights))
(:parameters model)
(map vector x y)))
(defn init-parameters
[model]
(let [{layers :layers seed :seed} model
r (if seed (java.util.Random. seed) (java.util.Random.))
rand (fn [] (.nextGaussian r))]
(->> (for [i (range (dec (count layers)))]
(let [ni (inc (nth layers i)) ;; number of nodes at layer i (+ bias node)
ni+1 (nth layers (inc i))] ;; number of nodes at layer i+1
;; initialize random values as parameters
(vec (repeatedly ni+1 #(vec (repeatedly ni rand))))))
(mapv m/matrix))))
;; Cost functions
(defn cross-entropy-cost
[x y theta fns]
(let [a (feed-forward-batch x theta fns)]
(/ (m/esum (m/add (m/mul y (m/log a))
(m/mul (m/sub 1 y) (m/log (m/sub 1 a)))))
(- (count x)))))
(defn cross-entropy-output-error
[y activations f']
;; Cross entropy error is independent of the derivative of output activation
(m/sub activations y))
(defn quadratic-cost
[x y theta fns]
(/ (m/esum (m/square (m/sub (feed-forward-batch x theta fns) y)))
2))
(defn quadratic-output-error
[y activations f']
(m/mul (m/sub activations y) (m/emap f' activations)))
;; API
(defn neural-network-fit
"Trains a neural network model for the given training data. For new models,
parameters are initialized as random values from a normal distribution."
([model data]
(neural-network-fit model (map (comp vec butlast) data) (map (comp vec last) data)))
([model x y]
(let [{theta :parameters} model
model (-> model
(assoc :parameters (or theta (init-parameters model))))]
(assoc model :parameters (gradient-descent model x y)))))
(defn neural-network-predict
"Predicts the values of example data using a neural network model."
[model x]
(let [{theta :parameters fns :activation-fns} model]
(when (not (nil? theta))
(mapv vec (feed-forward-batch x theta fns)))))
(defn neural-network-cost
([model data]
(neural-network-cost model (map (comp vec butlast) data) (map (comp vec last) data)))
([model x y]
(let [{theta :parameters fns :activation-fns cost :cost} model]
(when (not (nil? theta))
(cost x y theta fns)))))
(defn print-neural-network
"Prints information about a given neural network."
[model]
(println
(cond-> model
(contains? model :parameters)
(assoc :parameters (clojure.string/join " -> "
(for [thetai (:parameters model)]
(str (dec (count (first thetai))) " x " (count thetai))))))))
(defn make-neural-network
"Returns a neural network model where alpha is the learning rate."
([alpha lambda]
(make-neural-network alpha lambda cross-entropy-cost))
([alpha lambda cost]
(make-neural-network alpha lambda cost nil))
([alpha lambda cost seed]
{:alpha alpha
:lambda lambda
:layers []
:activation-fns []
:cost cost
:seed seed
:output-error (cond
(= cost cross-entropy-cost) cross-entropy-output-error
(= cost quadratic-cost) quadratic-output-error)}))
(defn add-neural-network-layer
"Adds a layer to a neural network model with n nodes and an activation
function f."
[model n f]
(-> model
(update :layers #(conj % n))
(update :activation-fns #(conj % f))))
| null | https://raw.githubusercontent.com/cloudkj/lambda-ml/a470a375d2b94f5e5e623a5e198ac312b018ffb3/src/lambda_ml/neural_network.clj | clojure | input layer
hidden layer
output layer
Numeric gradient checking
number of nodes at layer i (+ bias node)
number of nodes at layer i+1
initialize random values as parameters
Cost functions
Cross entropy error is independent of the derivative of output activation
API | (ns lambda-ml.neural-network
"Multilayer perceptron neural network learning using backpropagation.
Example usage:
```
(def data [[0 0 [0]] [0 1 [1]] [1 0 [1]] [1 1 [0]]])
(def fit
(let [alpha 0.5
lambda 0.001
model (-> (make-neural-network alpha lambda)
(-> (iterate #(neural-network-fit % data) model)
(nth 5000))))
(neural-network-predict fit (map butlast data))
= > [ [ 0.04262340225834812 ] [ 0.9582632706756758 ] [ 0.9581124103456861 ] [ 0.04103544440312673 ] ]
```"
(:require [lambda-ml.core :as c]
[clojure.core.matrix :as m]))
(m/set-current-implementation :vectorz)
(def bias (m/matrix [1.0]))
(def epsilon 0.0001)
(defn drop-bias
[m]
(m/submatrix m 1 [1 (dec (m/column-count m))]))
(defn feed-forward
"Returns the activation values for nodes in a neural network after forward
propagating the values of a single input example x through the network."
[x theta fns]
(reduce (fn [activations [weights f]]
(let [inputs (if (empty? activations) (m/matrix x) (last activations))
inputs+bias (m/join bias inputs)
outputs (m/emap f (m/mmul weights inputs+bias))]
(conj activations outputs)))
[]
(map vector theta fns)))
(defn feed-forward-batch
"Returns the activation values for nodes in a neural network after forward
propagating a collection of input examples x through the network."
[x theta fns]
(-> (reduce (fn [inputs [weights f]]
(let [bias (m/broadcast 1.0 [1 (m/column-count inputs)])
inputs+bias (m/join bias inputs)
outputs (m/emap f (m/mmul weights inputs+bias))]
outputs))
(m/transpose (m/matrix x))
(map vector theta fns))
(m/transpose)))
(defn back-propagate
"Returns the errors of each node in a neural network after propagating the
the errors at the output nodes, computed against a single target value y,
backwards through the network."
[y theta fns' activations output-error]
(->> (map vector
(reverse (rest theta))
(reverse (butlast activations))
(reverse (butlast fns')))
(reduce (fn [errors [w a f]]
(cons (m/mul (m/emap f a) (m/mmul (first errors) (drop-bias w)))
errors))
(list (output-error y (last activations) (last fns'))))
(vec)))
(defn compute-gradients
"Returns the gradients for each weight given activation values and errors on
a input values of a single example x."
[x activations errors]
(->> (map vector errors (cons (m/matrix x) (butlast activations)))
(reduce (fn [gradients [e a]]
(let [a (m/join bias a)]
(conj gradients (m/outer-product e a))))
[])))
(defn numeric-gradients
"Returns the numeric approximations of the gradients for each weight given the
input values of a single example x and label y. Used for debugging by checking
against the computed gradients during backpropagation."
[x y theta fns cost]
(mapv (fn [k weights]
(m/matrix (for [i (range (m/row-count weights))]
(for [j (range (m/column-count weights))]
(let [w (m/select weights i j)
theta+ (assoc theta k (m/set-selection weights i j (+ w epsilon)))
theta- (assoc theta k (m/set-selection weights i j (- w epsilon)))]
(/ (- (cost (list x) (list y) theta+ fns)
(cost (list x) (list y) theta- fns))
(* 2 epsilon)))))))
(range)
theta))
(defn regularize
"Returns regularized weights."
[theta alpha lambda]
(map (fn [w]
(-> (m/mul alpha lambda w)
(m/set-column 0 (m/matrix (repeat (m/row-count w) 0)))))
theta))
(defn gradient-descent-step
"Performs a single gradient step on the input and target values of a single
example x and label y, and returns the updated weights."
[model x y theta]
(let [{fns :activation-fns alpha :alpha lambda :lambda
cost :cost output-error :output-error} model
activations (feed-forward x theta fns)
errors (back-propagate y theta (map c/derivative fns) activations output-error)
gradients (compute-gradients x activations errors)
regularization (regularize theta alpha lambda)]
( println ( map ( comp # ( / ( m / esum % ) ( m / ecount % ) ) m / abs m / sub ) gradients ( numeric - gradients x y theta fns cost ) ) )
(mapv m/sub theta (map #(m/mul % alpha) gradients) regularization)))
(defn gradient-descent
"Performs gradient descent on input and target values of all examples x and
y, and returns the updated weights."
[model x y]
(reduce (fn [weights [xi yi]] (gradient-descent-step model xi yi weights))
(:parameters model)
(map vector x y)))
(defn init-parameters
[model]
(let [{layers :layers seed :seed} model
r (if seed (java.util.Random. seed) (java.util.Random.))
rand (fn [] (.nextGaussian r))]
(->> (for [i (range (dec (count layers)))]
(vec (repeatedly ni+1 #(vec (repeatedly ni rand))))))
(mapv m/matrix))))
(defn cross-entropy-cost
[x y theta fns]
(let [a (feed-forward-batch x theta fns)]
(/ (m/esum (m/add (m/mul y (m/log a))
(m/mul (m/sub 1 y) (m/log (m/sub 1 a)))))
(- (count x)))))
(defn cross-entropy-output-error
[y activations f']
(m/sub activations y))
(defn quadratic-cost
[x y theta fns]
(/ (m/esum (m/square (m/sub (feed-forward-batch x theta fns) y)))
2))
(defn quadratic-output-error
[y activations f']
(m/mul (m/sub activations y) (m/emap f' activations)))
(defn neural-network-fit
"Trains a neural network model for the given training data. For new models,
parameters are initialized as random values from a normal distribution."
([model data]
(neural-network-fit model (map (comp vec butlast) data) (map (comp vec last) data)))
([model x y]
(let [{theta :parameters} model
model (-> model
(assoc :parameters (or theta (init-parameters model))))]
(assoc model :parameters (gradient-descent model x y)))))
(defn neural-network-predict
"Predicts the values of example data using a neural network model."
[model x]
(let [{theta :parameters fns :activation-fns} model]
(when (not (nil? theta))
(mapv vec (feed-forward-batch x theta fns)))))
(defn neural-network-cost
([model data]
(neural-network-cost model (map (comp vec butlast) data) (map (comp vec last) data)))
([model x y]
(let [{theta :parameters fns :activation-fns cost :cost} model]
(when (not (nil? theta))
(cost x y theta fns)))))
(defn print-neural-network
"Prints information about a given neural network."
[model]
(println
(cond-> model
(contains? model :parameters)
(assoc :parameters (clojure.string/join " -> "
(for [thetai (:parameters model)]
(str (dec (count (first thetai))) " x " (count thetai))))))))
(defn make-neural-network
"Returns a neural network model where alpha is the learning rate."
([alpha lambda]
(make-neural-network alpha lambda cross-entropy-cost))
([alpha lambda cost]
(make-neural-network alpha lambda cost nil))
([alpha lambda cost seed]
{:alpha alpha
:lambda lambda
:layers []
:activation-fns []
:cost cost
:seed seed
:output-error (cond
(= cost cross-entropy-cost) cross-entropy-output-error
(= cost quadratic-cost) quadratic-output-error)}))
(defn add-neural-network-layer
"Adds a layer to a neural network model with n nodes and an activation
function f."
[model n f]
(-> model
(update :layers #(conj % n))
(update :activation-fns #(conj % f))))
|
6bd518095fc2252cf0cd59c9a732b7fdc44a94e9aeb4ecc14766eafcc0ef2568 | c4-project/c4f | table.mli | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
(** The fuzzer action tables. *)
open Base
val actions : C4f_fuzz.Action.With_default_weight.t list Lazy.t
(** [actions] is a listing of all actions with their default weights. *)
val action_map :
C4f_fuzz.Action.With_default_weight.t Map.M(C4f_common.Id).t Lazy.t
(** [action_map] lazily evaluates to a map from action IDs to their actions.
It is, effectively, a rearrangement of the data available in [actions]. *)
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/fuzz_actions/src/table.mli | ocaml | * The fuzzer action tables.
* [actions] is a listing of all actions with their default weights.
* [action_map] lazily evaluates to a map from action IDs to their actions.
It is, effectively, a rearrangement of the data available in [actions]. | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
val actions : C4f_fuzz.Action.With_default_weight.t list Lazy.t
val action_map :
C4f_fuzz.Action.With_default_weight.t Map.M(C4f_common.Id).t Lazy.t
|
156cbb76f8636e74a68fa50c915062d332cbfec553b86a63ca955695ae3749b1 | Opetushallitus/aipal | opintoala.clj | Copyright ( c ) 2014 The Finnish National Board of Education - Opetushallitus
;;
This program is free software : Licensed under the EUPL , Version 1.1 or - as
soon as they will be approved by the European Commission - subsequent versions
of the EUPL ( the " Licence " ) ;
;;
;; You may not use this work except in compliance with the Licence.
;; You may obtain a copy of the Licence at: /
;;
;; 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
European Union Public Licence for more details .
(ns aipal.arkisto.opintoala
(:require [korma.core :as sql]
[aipal.integraatio.sql.korma :as taulut]))
(defn ^:integration-api lisaa!
[tiedot]
(sql/insert taulut/opintoala
(sql/values tiedot)))
(defn ^:integration-api paivita!
[opintoalatunnus tiedot]
(sql/update taulut/opintoala
(sql/set-fields tiedot)
(sql/where {:opintoalatunnus opintoalatunnus})))
(defn hae-kaikki
[]
(sql/select taulut/opintoala
(sql/order :opintoalatunnus)))
(defn hae
[opintoalatunnus]
(first
(sql/select taulut/opintoala
(sql/where {:opintoalatunnus opintoalatunnus}))))
| null | https://raw.githubusercontent.com/Opetushallitus/aipal/767bd14ec7153dc97fdf688443b9687cdb70082f/aipal/src/clj/aipal/arkisto/opintoala.clj | clojure |
You may not use this work except in compliance with the Licence.
You may obtain a copy of the Licence at: /
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 | Copyright ( c ) 2014 The Finnish National Board of Education - Opetushallitus
This program is free software : Licensed under the EUPL , Version 1.1 or - as
soon as they will be approved by the European Commission - subsequent versions
European Union Public Licence for more details .
(ns aipal.arkisto.opintoala
(:require [korma.core :as sql]
[aipal.integraatio.sql.korma :as taulut]))
(defn ^:integration-api lisaa!
[tiedot]
(sql/insert taulut/opintoala
(sql/values tiedot)))
(defn ^:integration-api paivita!
[opintoalatunnus tiedot]
(sql/update taulut/opintoala
(sql/set-fields tiedot)
(sql/where {:opintoalatunnus opintoalatunnus})))
(defn hae-kaikki
[]
(sql/select taulut/opintoala
(sql/order :opintoalatunnus)))
(defn hae
[opintoalatunnus]
(first
(sql/select taulut/opintoala
(sql/where {:opintoalatunnus opintoalatunnus}))))
|
fb183a989888bc3586fbaa1a6e2def3b3966fe9bd29e18a6a1827698c75d55ac | Flamefork/fleet | runtime.clj | (ns fleet.runtime
(:import
[clojure.lang Sequential IObj]
fleet.util.CljString))
(defn- escaped-with
[s]
(:escaped-with (meta s) {}))
(defn raw
"Prevent escaping of string by escaping-fn."
[escaping-fn s]
(let [obj (-> s .toString CljString.)
new-escw (assoc (escaped-with s) escaping-fn true)
new-meta (assoc (meta obj) :escaped-with new-escw)]
(with-meta obj new-meta)))
(defn raw?
"Check if string is already escaped by escaping-fn."
[escaping-fn s]
(get (escaped-with s) escaping-fn))
(defprotocol Screenable
(screen [s escaping-fn] "Process and collect template string(s)."))
(extend-protocol Screenable
CharSequence
(screen [s f] (raw f (if (raw? f s) s (f s))))
Sequential
(screen [s f] (raw f (apply str (map #(screen %1 f) s))))
Object
(screen [s f] (raw f (str s)))
nil
(screen [_ _] nil))
(defn make-runtime
"Create runtime functions applied to specified escaping-fn."
[escaping-fn]
{:raw (partial raw escaping-fn)
:raw? (partial raw? escaping-fn)
:screen #(screen %1 escaping-fn)})
| null | https://raw.githubusercontent.com/Flamefork/fleet/dc4adcd84b2f92d40797789c98e71746181f1a04/src/fleet/runtime.clj | clojure | (ns fleet.runtime
(:import
[clojure.lang Sequential IObj]
fleet.util.CljString))
(defn- escaped-with
[s]
(:escaped-with (meta s) {}))
(defn raw
"Prevent escaping of string by escaping-fn."
[escaping-fn s]
(let [obj (-> s .toString CljString.)
new-escw (assoc (escaped-with s) escaping-fn true)
new-meta (assoc (meta obj) :escaped-with new-escw)]
(with-meta obj new-meta)))
(defn raw?
"Check if string is already escaped by escaping-fn."
[escaping-fn s]
(get (escaped-with s) escaping-fn))
(defprotocol Screenable
(screen [s escaping-fn] "Process and collect template string(s)."))
(extend-protocol Screenable
CharSequence
(screen [s f] (raw f (if (raw? f s) s (f s))))
Sequential
(screen [s f] (raw f (apply str (map #(screen %1 f) s))))
Object
(screen [s f] (raw f (str s)))
nil
(screen [_ _] nil))
(defn make-runtime
"Create runtime functions applied to specified escaping-fn."
[escaping-fn]
{:raw (partial raw escaping-fn)
:raw? (partial raw? escaping-fn)
:screen #(screen %1 escaping-fn)})
| |
3ed7ae33b9aa588dc005c88ca4f470e131b6e9a6d620071eed7efd443cd44ac6 | rtoy/cmucl | gray-compat.lisp | ;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: STREAM -*-
;;;
;;; **********************************************************************
This code was written by and has been placed in the public
;;; domain.
;;;
(ext:file-comment
"$Header: src/pcl/gray-compat.lisp $")
;;;
;;; **********************************************************************
;;;
;;; Gray streams compatibility functions for simple-streams
(in-package "STREAM")
(intl:textdomain "cmucl")
(defvar *enable-gray-compat-warnings* nil)
(defmacro define-gray-stream-method (name lambda-list &body body)
`(defmethod ,name ,lambda-list
(when *enable-gray-compat-warnings*
(warn _"Called ~S on a simple-stream" ',name))
,@body))
(define-gray-stream-method ext:stream-advance-to-column ((stream
simple-stream)
column)
(let ((current (charpos stream)))
(when current
(dotimes (i (- column current))
(write-char #\Space stream)))))
(define-gray-stream-method ext:stream-line-length ((stream simple-stream))
nil)
(define-gray-stream-method ext:stream-file-position ((stream simple-stream)
&optional position)
(if position
(file-position stream position)
(file-position stream)))
(define-gray-stream-method ext:stream-clear-output ((stream simple-stream))
(clear-output stream))
(define-gray-stream-method ext:stream-write-byte ((stream simple-stream)
integer)
(write-byte integer stream))
(define-gray-stream-method ext:stream-finish-output ((stream simple-stream))
(finish-output stream))
(define-gray-stream-method ext:stream-listen ((stream simple-stream))
(listen stream))
(define-gray-stream-method ext:stream-write-string ((stream simple-stream)
string
&optional (start 0) end)
(write-string string stream
:start start :end (or end (length string))))
(define-gray-stream-method ext:stream-write-char ((stream simple-stream)
character)
(write-char character stream))
(define-gray-stream-method ext:stream-line-column ((stream simple-stream))
(charpos stream))
(define-gray-stream-method ext:stream-file-length ((stream simple-stream))
(file-length stream))
(define-gray-stream-method ext:stream-unread-char ((stream simple-stream)
character)
(unread-char character stream))
(define-gray-stream-method ext:stream-read-sequence ((stream simple-stream)
seq
&optional (start 0) end)
(read-sequence seq stream :start start :end end))
(define-gray-stream-method ext:stream-read-line ((stream simple-stream))
(read-line stream nil :eof))
(define-gray-stream-method ext:stream-peek-char ((stream simple-stream))
(peek-char nil stream nil :eof))
(define-gray-stream-method ext:stream-read-char-no-hang ((stream
simple-stream))
(read-char-no-hang stream nil :eof))
(define-gray-stream-method ext:stream-read-char ((stream simple-stream))
(read-char stream nil :eof))
(define-gray-stream-method ext:stream-clear-input ((stream simple-stream))
(clear-input stream))
(define-gray-stream-method ext:stream-start-line-p ((stream simple-stream))
(= (charpos stream) 0))
(define-gray-stream-method ext:stream-terpri ((stream simple-stream))
(write-char #\Newline stream))
(define-gray-stream-method ext:stream-write-sequence ((stream simple-stream)
seq
&optional (start 0)
end)
(write-sequence seq stream :start start :end end))
(define-gray-stream-method ext:stream-fresh-line ((stream simple-stream))
(fresh-line stream))
(define-gray-stream-method ext:stream-read-byte ((stream simple-stream))
(read-byte stream nil :eof))
(define-gray-stream-method ext:stream-force-output ((stream simple-stream))
(force-output stream))
(provide :gray-compat)
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/pcl/gray-compat.lisp | lisp | -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: STREAM -*-
**********************************************************************
domain.
**********************************************************************
Gray streams compatibility functions for simple-streams | This code was written by and has been placed in the public
(ext:file-comment
"$Header: src/pcl/gray-compat.lisp $")
(in-package "STREAM")
(intl:textdomain "cmucl")
(defvar *enable-gray-compat-warnings* nil)
(defmacro define-gray-stream-method (name lambda-list &body body)
`(defmethod ,name ,lambda-list
(when *enable-gray-compat-warnings*
(warn _"Called ~S on a simple-stream" ',name))
,@body))
(define-gray-stream-method ext:stream-advance-to-column ((stream
simple-stream)
column)
(let ((current (charpos stream)))
(when current
(dotimes (i (- column current))
(write-char #\Space stream)))))
(define-gray-stream-method ext:stream-line-length ((stream simple-stream))
nil)
(define-gray-stream-method ext:stream-file-position ((stream simple-stream)
&optional position)
(if position
(file-position stream position)
(file-position stream)))
(define-gray-stream-method ext:stream-clear-output ((stream simple-stream))
(clear-output stream))
(define-gray-stream-method ext:stream-write-byte ((stream simple-stream)
integer)
(write-byte integer stream))
(define-gray-stream-method ext:stream-finish-output ((stream simple-stream))
(finish-output stream))
(define-gray-stream-method ext:stream-listen ((stream simple-stream))
(listen stream))
(define-gray-stream-method ext:stream-write-string ((stream simple-stream)
string
&optional (start 0) end)
(write-string string stream
:start start :end (or end (length string))))
(define-gray-stream-method ext:stream-write-char ((stream simple-stream)
character)
(write-char character stream))
(define-gray-stream-method ext:stream-line-column ((stream simple-stream))
(charpos stream))
(define-gray-stream-method ext:stream-file-length ((stream simple-stream))
(file-length stream))
(define-gray-stream-method ext:stream-unread-char ((stream simple-stream)
character)
(unread-char character stream))
(define-gray-stream-method ext:stream-read-sequence ((stream simple-stream)
seq
&optional (start 0) end)
(read-sequence seq stream :start start :end end))
(define-gray-stream-method ext:stream-read-line ((stream simple-stream))
(read-line stream nil :eof))
(define-gray-stream-method ext:stream-peek-char ((stream simple-stream))
(peek-char nil stream nil :eof))
(define-gray-stream-method ext:stream-read-char-no-hang ((stream
simple-stream))
(read-char-no-hang stream nil :eof))
(define-gray-stream-method ext:stream-read-char ((stream simple-stream))
(read-char stream nil :eof))
(define-gray-stream-method ext:stream-clear-input ((stream simple-stream))
(clear-input stream))
(define-gray-stream-method ext:stream-start-line-p ((stream simple-stream))
(= (charpos stream) 0))
(define-gray-stream-method ext:stream-terpri ((stream simple-stream))
(write-char #\Newline stream))
(define-gray-stream-method ext:stream-write-sequence ((stream simple-stream)
seq
&optional (start 0)
end)
(write-sequence seq stream :start start :end end))
(define-gray-stream-method ext:stream-fresh-line ((stream simple-stream))
(fresh-line stream))
(define-gray-stream-method ext:stream-read-byte ((stream simple-stream))
(read-byte stream nil :eof))
(define-gray-stream-method ext:stream-force-output ((stream simple-stream))
(force-output stream))
(provide :gray-compat)
|
7c68b433598e6d0caea265294b3f1a5cc33d78c7b1a0dfd2007fbb5ee247db1d | haskell-lisp/blaise | StandardFunctions.hs |
module StandardFunctions where
import Expression
import Eval
import qualified Data.Map as Map
import Control.Monad.State
-- Standard functions we expose
blaiseArithmetic f = do (BlaiseList args) <- getSymbol "..."
blaiseBinary f args
blaiseBinary :: (Integer->Integer->Integer) -> [Expr] -> BlaiseResult
blaiseBinary op args = do return $ foldl1 (blaiseBinaryAux op) args
where blaiseBinaryAux op (BlaiseInt i) (BlaiseInt j) = BlaiseInt (i `op` j)
-- Equality
blaiseEq = do (BlaiseList args) <- getSymbol "..."
return $ foldl1 (\(BlaiseInt a) (BlaiseInt b) -> BlaiseInt(if a == b then 1 else 0)) args
-- A function to modify the context
blaiseSetArgs = ["symbol", "value"]
blaiseSet = do [(BlaiseSymbol s), e] <- getSymbols blaiseSetArgs
eval_e <- eval e
updateSymbolInParent s eval_e
return eval_e
-- Conditionals
blaiseIfArgs = ["condition", "expr1", "expr2"]
blaiseIf = do [condExpr, expr1, expr2] <- getSymbols blaiseIfArgs
eval_cond <- eval condExpr
if (0 `notEqual` eval_cond) then eval expr1
else eval expr2
where notEqual val1 (BlaiseInt val2) = val1 /= val2
-- Functions
blaiseFnArgs = ["args", "..."]
blaiseFn = do [(BlaiseList args), (BlaiseList body)] <- getSymbols blaiseFnArgs
let newFn = do evalBody <- mapM eval body
return $ last evalBody
return $ BlaiseFn newFn (map (\(BlaiseSymbol arg)->arg) args)
-- Our symbol table
initialCtx = Ctx (Map.fromList [("+", BlaiseFn (blaiseArithmetic (+)) ["..."]),
("-", BlaiseFn (blaiseArithmetic (-)) ["..."]),
("*", BlaiseFn (blaiseArithmetic (*)) ["..."]),
("/", BlaiseFn (blaiseArithmetic div) ["..."]),
("eq", BlaiseFn blaiseEq ["..."]),
("set", BlaiseSpecial blaiseSet blaiseSetArgs),
("if", BlaiseSpecial blaiseIf blaiseIfArgs),
("fn", BlaiseSpecial blaiseFn blaiseFnArgs )
]) Nothing
-- Helper
getSymbol sym = eval $ (BlaiseSymbol sym)
getSymbols syms = mapM getSymbol syms | null | https://raw.githubusercontent.com/haskell-lisp/blaise/17c75be05b6f6d2b2fff4774229ca733b2c5f0e3/src/StandardFunctions.hs | haskell | Standard functions we expose
Equality
A function to modify the context
Conditionals
Functions
Our symbol table
Helper
|
module StandardFunctions where
import Expression
import Eval
import qualified Data.Map as Map
import Control.Monad.State
blaiseArithmetic f = do (BlaiseList args) <- getSymbol "..."
blaiseBinary f args
blaiseBinary :: (Integer->Integer->Integer) -> [Expr] -> BlaiseResult
blaiseBinary op args = do return $ foldl1 (blaiseBinaryAux op) args
where blaiseBinaryAux op (BlaiseInt i) (BlaiseInt j) = BlaiseInt (i `op` j)
blaiseEq = do (BlaiseList args) <- getSymbol "..."
return $ foldl1 (\(BlaiseInt a) (BlaiseInt b) -> BlaiseInt(if a == b then 1 else 0)) args
blaiseSetArgs = ["symbol", "value"]
blaiseSet = do [(BlaiseSymbol s), e] <- getSymbols blaiseSetArgs
eval_e <- eval e
updateSymbolInParent s eval_e
return eval_e
blaiseIfArgs = ["condition", "expr1", "expr2"]
blaiseIf = do [condExpr, expr1, expr2] <- getSymbols blaiseIfArgs
eval_cond <- eval condExpr
if (0 `notEqual` eval_cond) then eval expr1
else eval expr2
where notEqual val1 (BlaiseInt val2) = val1 /= val2
blaiseFnArgs = ["args", "..."]
blaiseFn = do [(BlaiseList args), (BlaiseList body)] <- getSymbols blaiseFnArgs
let newFn = do evalBody <- mapM eval body
return $ last evalBody
return $ BlaiseFn newFn (map (\(BlaiseSymbol arg)->arg) args)
initialCtx = Ctx (Map.fromList [("+", BlaiseFn (blaiseArithmetic (+)) ["..."]),
("-", BlaiseFn (blaiseArithmetic (-)) ["..."]),
("*", BlaiseFn (blaiseArithmetic (*)) ["..."]),
("/", BlaiseFn (blaiseArithmetic div) ["..."]),
("eq", BlaiseFn blaiseEq ["..."]),
("set", BlaiseSpecial blaiseSet blaiseSetArgs),
("if", BlaiseSpecial blaiseIf blaiseIfArgs),
("fn", BlaiseSpecial blaiseFn blaiseFnArgs )
]) Nothing
getSymbol sym = eval $ (BlaiseSymbol sym)
getSymbols syms = mapM getSymbol syms |
f338f041d273bc86429c07de1d3eeecc9af985640b58aa657b330ac8c131c5f6 | green-coder/diffuse | helper_test.cljc | (ns diffuse.helper-test
(:require #?(:clj [clojure.test :refer [deftest testing is are]]
:cljs [cljs.test :refer [deftest testing is are] :include-macros true])
[diffuse.core :as d]
[diffuse.helper :as h]))
(deftest no-op-test
(is (= (h/value :foo) (d/comp (h/value :foo) h/no-op)))
(is (= (h/value :foo) (d/comp h/no-op (h/value :foo)))))
(deftest value-test
(is (= #{:foo} (d/apply (h/value #{:foo}) [:bar])))
(is (= #{:foo} (-> (d/comp (h/value #{:foo}) (h/value {:foo :bar}))
(d/apply [:bar])))))
(deftest set-test
(is (= #{:pim :poum} (-> (d/comp (h/set-conj :pim) (h/set-disj :pam))
(d/apply #{:pam :poum})))))
(deftest map-test
(is (= {:a 1, :b 2}
(-> (d/comp (h/map-assoc :a 1, :b 2)
(h/map-dissoc :d))
(d/apply {:a 2, :d 4}))))
(is (= {:a [1 2 3]}
(-> (d/comp (h/map-update :a (h/vec-remsert 1 0 [2 3]))
(h/map-dissoc :z))
(d/apply {:a [1], :z 7})))))
(deftest vector-test
(is (= [0 :x :y :z 3 4]
(-> (h/vec-remsert 1 2 [:x :y :z])
(d/apply [0 1 2 3 4]))))
(is (= [0 1 2]
(-> (h/vec-remsert 0 0 [0 1 2])
(d/apply []))))
(is (thrown? #?(:clj Exception :cljs js/Object)
(-> (h/vec-remsert 0 1 nil)
(d/apply []))))
(is (= [#{:a :b :c} [1 2 3] #{:x}]
(-> (h/vec-update 0
(h/set-conj :b :c)
(h/vec-remsert 0 0 [1 2])
(h/set-disj :y :z))
(d/apply [#{:a} [3] #{:x :y :z}]))))
(is (= [0 10 20 3 40]
(-> (d/comp (h/vec-assoc 2 20)
(h/vec-assoc 1 10)
(h/vec-assoc 4 40))
(d/apply [0 1 2 3 4]))))
(is (= ['zero 10 20 3 {:a 1, :b 2}]
(-> (d/comp (h/vec-assoc 0 'zero)
(h/vec-update 4 (h/map-assoc :b 2))
(h/vec-remsert 1 2 [10 20]))
(d/apply [0 1 2 3 {:a 1}])))))
(deftest assoc-test
(is (= (h/vec-assoc 2 :a)
(h/assoc [0 1 2 3 4] 2 :a)))
(is (= (d/comp (h/vec-assoc 2 :a)
(h/vec-assoc 4 :b))
(h/assoc [0 1 2 3 4] 2 :a 4 :b)))
(is (= (h/map-assoc 2 :a)
(h/assoc {0 :zero, 2 :x, 4 :y} 2 :a)))
(is (= (d/comp (h/map-assoc 2 :a)
(h/map-assoc 4 :b))
(h/assoc {2 :x, 4 :y} 2 :a 4 :b))))
(deftest update-test
(is (= (h/vec-update 2 (h/vec-insert 1 [:a :b]))
(h/update [0 1 [2] 3] 2 (h/vec-insert 1 [:a :b]))))
(is (= (h/map-update 2 (h/vec-assoc 1 [:a :b]))
(h/update {2 [0 1]} 2 (h/vec-assoc 1 [:a :b])))))
(deftest update-in-test
(is (= (h/map-update :a (h/map-update :b (h/map-assoc :c 2)))
(h/update-in {:a {:b {:c 1}}} [:a :b] h/assoc :c 2)))
(is (= (h/map-update :a (h/vec-update 1 (h/map-assoc :c 2)))
(h/update-in {:a [:b {:c 1}]} [:a 1] h/assoc :c 2)))
(is (= (h/map-assoc :a 2)
(h/update-in {:a 1} [] h/assoc :a 2)))
(is (= (h/set-conj 1 2 3)
(h/update-in nil [] (fn [data] (h/set-conj 1 2 3))))))
(deftest assoc-in-test
(is (= (h/map-update :a (h/map-update :b (h/map-assoc :c 2)))
(h/assoc-in {:a {:b {:c 1}}} [:a :b :c] 2)))
(is (= (h/map-update :a (h/vec-update 1 (h/map-assoc :c 2)))
(h/assoc-in {:a [:b {:c 1}]} [:a 1 :c] 2)))
(is (= (h/map-assoc :a 2)
(h/assoc-in {:a 1} [:a] 2)))
(is (= (h/vec-assoc 0 2)
(h/assoc-in [1] [0] 2)))
(is (= (h/value 2)
(h/assoc-in "whatever" [] 2))))
(deftest let-test
( is (= ' ( clojure.core/let [ a 101
b 102
c 103 ]
; {:type :map
; :key-op {:a [:assoc a]
; :b [:assoc b]
; :c [:update {:type :set
; :conj #{c}}]
; :d [:dissoc]}})
( macroexpand-1 ' ( h / let [ a 101
b 102
; c 103]
; (d/comp (h/map-assoc :a a, :b b)
; (h/map-update :c (h/set-conj c))
; (h/map-dissoc :d))))))
(is (= (d/comp (h/map-assoc :a 101, :b 102)
(h/map-update :c (h/set-conj 103))
(h/map-dissoc :d))
(h/let [a 101
b 102
c 103]
(d/comp (h/map-assoc :a a, :b b)
(h/map-update :c (h/set-conj c))
(h/map-dissoc :d))))))
| null | https://raw.githubusercontent.com/green-coder/diffuse/22675d1c586dcb6204f01836ce6fe63b1db2a5aa/test/diffuse/helper_test.cljc | clojure | {:type :map
:key-op {:a [:assoc a]
:b [:assoc b]
:c [:update {:type :set
:conj #{c}}]
:d [:dissoc]}})
c 103]
(d/comp (h/map-assoc :a a, :b b)
(h/map-update :c (h/set-conj c))
(h/map-dissoc :d)))))) | (ns diffuse.helper-test
(:require #?(:clj [clojure.test :refer [deftest testing is are]]
:cljs [cljs.test :refer [deftest testing is are] :include-macros true])
[diffuse.core :as d]
[diffuse.helper :as h]))
(deftest no-op-test
(is (= (h/value :foo) (d/comp (h/value :foo) h/no-op)))
(is (= (h/value :foo) (d/comp h/no-op (h/value :foo)))))
(deftest value-test
(is (= #{:foo} (d/apply (h/value #{:foo}) [:bar])))
(is (= #{:foo} (-> (d/comp (h/value #{:foo}) (h/value {:foo :bar}))
(d/apply [:bar])))))
(deftest set-test
(is (= #{:pim :poum} (-> (d/comp (h/set-conj :pim) (h/set-disj :pam))
(d/apply #{:pam :poum})))))
(deftest map-test
(is (= {:a 1, :b 2}
(-> (d/comp (h/map-assoc :a 1, :b 2)
(h/map-dissoc :d))
(d/apply {:a 2, :d 4}))))
(is (= {:a [1 2 3]}
(-> (d/comp (h/map-update :a (h/vec-remsert 1 0 [2 3]))
(h/map-dissoc :z))
(d/apply {:a [1], :z 7})))))
(deftest vector-test
(is (= [0 :x :y :z 3 4]
(-> (h/vec-remsert 1 2 [:x :y :z])
(d/apply [0 1 2 3 4]))))
(is (= [0 1 2]
(-> (h/vec-remsert 0 0 [0 1 2])
(d/apply []))))
(is (thrown? #?(:clj Exception :cljs js/Object)
(-> (h/vec-remsert 0 1 nil)
(d/apply []))))
(is (= [#{:a :b :c} [1 2 3] #{:x}]
(-> (h/vec-update 0
(h/set-conj :b :c)
(h/vec-remsert 0 0 [1 2])
(h/set-disj :y :z))
(d/apply [#{:a} [3] #{:x :y :z}]))))
(is (= [0 10 20 3 40]
(-> (d/comp (h/vec-assoc 2 20)
(h/vec-assoc 1 10)
(h/vec-assoc 4 40))
(d/apply [0 1 2 3 4]))))
(is (= ['zero 10 20 3 {:a 1, :b 2}]
(-> (d/comp (h/vec-assoc 0 'zero)
(h/vec-update 4 (h/map-assoc :b 2))
(h/vec-remsert 1 2 [10 20]))
(d/apply [0 1 2 3 {:a 1}])))))
(deftest assoc-test
(is (= (h/vec-assoc 2 :a)
(h/assoc [0 1 2 3 4] 2 :a)))
(is (= (d/comp (h/vec-assoc 2 :a)
(h/vec-assoc 4 :b))
(h/assoc [0 1 2 3 4] 2 :a 4 :b)))
(is (= (h/map-assoc 2 :a)
(h/assoc {0 :zero, 2 :x, 4 :y} 2 :a)))
(is (= (d/comp (h/map-assoc 2 :a)
(h/map-assoc 4 :b))
(h/assoc {2 :x, 4 :y} 2 :a 4 :b))))
(deftest update-test
(is (= (h/vec-update 2 (h/vec-insert 1 [:a :b]))
(h/update [0 1 [2] 3] 2 (h/vec-insert 1 [:a :b]))))
(is (= (h/map-update 2 (h/vec-assoc 1 [:a :b]))
(h/update {2 [0 1]} 2 (h/vec-assoc 1 [:a :b])))))
(deftest update-in-test
(is (= (h/map-update :a (h/map-update :b (h/map-assoc :c 2)))
(h/update-in {:a {:b {:c 1}}} [:a :b] h/assoc :c 2)))
(is (= (h/map-update :a (h/vec-update 1 (h/map-assoc :c 2)))
(h/update-in {:a [:b {:c 1}]} [:a 1] h/assoc :c 2)))
(is (= (h/map-assoc :a 2)
(h/update-in {:a 1} [] h/assoc :a 2)))
(is (= (h/set-conj 1 2 3)
(h/update-in nil [] (fn [data] (h/set-conj 1 2 3))))))
(deftest assoc-in-test
(is (= (h/map-update :a (h/map-update :b (h/map-assoc :c 2)))
(h/assoc-in {:a {:b {:c 1}}} [:a :b :c] 2)))
(is (= (h/map-update :a (h/vec-update 1 (h/map-assoc :c 2)))
(h/assoc-in {:a [:b {:c 1}]} [:a 1 :c] 2)))
(is (= (h/map-assoc :a 2)
(h/assoc-in {:a 1} [:a] 2)))
(is (= (h/vec-assoc 0 2)
(h/assoc-in [1] [0] 2)))
(is (= (h/value 2)
(h/assoc-in "whatever" [] 2))))
(deftest let-test
( is (= ' ( clojure.core/let [ a 101
b 102
c 103 ]
( macroexpand-1 ' ( h / let [ a 101
b 102
(is (= (d/comp (h/map-assoc :a 101, :b 102)
(h/map-update :c (h/set-conj 103))
(h/map-dissoc :d))
(h/let [a 101
b 102
c 103]
(d/comp (h/map-assoc :a a, :b b)
(h/map-update :c (h/set-conj c))
(h/map-dissoc :d))))))
|
b44bf03e5fd37e4ccb67666e3129e66355bb8a85dfc1cb149638a5807644b15f | Kalimehtar/gtk-cffi | drag-drop.lisp | (in-package :gdk-cffi)
(defbitfield drag-action :default :copy :move :link :private :ask) | null | https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/gdk/drag-drop.lisp | lisp | (in-package :gdk-cffi)
(defbitfield drag-action :default :copy :move :link :private :ask) | |
8636e298332bc26a46d310e70b931b5f5b854009fa1baec57b5992dc75e9c8c6 | fyquah/hardcaml_zprize | multiplier.mli | open! Base
open Hardcaml
val latency : int
val create : clock:Signal.t -> Signal.t -> Signal.t -> Signal.t
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/hardcaml_ntt/src/multiplier.mli | ocaml | open! Base
open Hardcaml
val latency : int
val create : clock:Signal.t -> Signal.t -> Signal.t -> Signal.t
| |
90d18e824995960d9bc5b3ab567df557c64ef906d5b0c590b0939b3404f5b7f0 | LdBeth/star-lisp | type-system-basics.lisp | (in-package :*sim-i)
;;;> *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+
;;;>
;;;> The Thinking Machines *Lisp Simulator is in the public domain.
;;;> You are free to do whatever you like with it, including but
;;;> not limited to distributing, modifying, and copying.
;;;>
;;;> *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+
;;; Author: JP Massar.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant short-float-mantissa 15)
(defconstant short-float-exponent 8)
(defconstant single-float-mantissa 23)
(defconstant single-float-exponent 8)
(defconstant double-float-mantissa 52)
(defconstant double-float-exponent 11)
(defconstant long-float-mantissa 74)
(defconstant long-float-exponent 21)
(defconstant extended-float-mantissa 96)
(defconstant extended-float-exponent 31)
(defconstant nbits-per-lisp 4)
)
(defun error-not-cpt (type)
(error "~S is not a canonical pvar type." type))
(defun error-if-not-cpt (type)
(unless (and (consp type) (eq (car type) 'pvar))
(error-not-cpt type)
))
This will return one of boolean , unsigned - byte , signed - byte , defined - float ,
;; complex, string-char, character, array, structure, t, front-end, or *.
(defun canonical-pvar-element-type (type)
(error-if-not-cpt type)
(if (consp (cadr type)) (caadr type) (cadr type))
)
(defun array-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'array)))
(defun structure-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'structure)))
(defun array-pvar-type-dimensions (type)
(unless (array-pvar-type-p type) (error-not-cpt type))
(caddr (cadr type)))
(defun array-pvar-type-element-type (type)
(unless (array-pvar-type-p type) (error-not-cpt type))
(cadr (cadr type)))
(defun structure-pvar-type-name (type)
(unless (structure-pvar-type-p type) (error-not-cpt type))
(cadr (cadr type)))
(defun float-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'defined-float)))
(defun complex-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'complex)))
(defun boolean-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'boolean))
(defun front-end-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'front-end))
(defun general-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 't))
(defun string-char-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'string-char))
(defun character-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'character))
(defun signed-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'signed-byte)))
(defun unsigned-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'unsigned-byte)))
(defun float-pvar-type-mantissa (type)
(unless (float-pvar-type-p type)
(error "~S is not a canonical pvar float type." type))
(cadr (cadr type)))
(defun float-pvar-type-exponent (type)
(unless (float-pvar-type-p type)
(error "~S is not a canonical pvar float type." type))
(caddr (cadr type)))
(defun complex-pvar-type-mantissa (type)
(unless (complex-pvar-type-p type)
(error "~S is not a canonical pvar complex type." type))
(cadr (cadadr type)))
(defun complex-pvar-type-exponent (type)
(unless (complex-pvar-type-p type)
(error "~S is not a canonical pvar complex type." type))
(caddr (cadadr type)))
| null | https://raw.githubusercontent.com/LdBeth/star-lisp/034fb97fe8780d6e9fbff7c1d8c4a6b8c331797b/source/type-system-basics.lisp | lisp | > *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+
>
> The Thinking Machines *Lisp Simulator is in the public domain.
> You are free to do whatever you like with it, including but
> not limited to distributing, modifying, and copying.
>
> *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+
Author: JP Massar.
complex, string-char, character, array, structure, t, front-end, or *. | (in-package :*sim-i)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant short-float-mantissa 15)
(defconstant short-float-exponent 8)
(defconstant single-float-mantissa 23)
(defconstant single-float-exponent 8)
(defconstant double-float-mantissa 52)
(defconstant double-float-exponent 11)
(defconstant long-float-mantissa 74)
(defconstant long-float-exponent 21)
(defconstant extended-float-mantissa 96)
(defconstant extended-float-exponent 31)
(defconstant nbits-per-lisp 4)
)
(defun error-not-cpt (type)
(error "~S is not a canonical pvar type." type))
(defun error-if-not-cpt (type)
(unless (and (consp type) (eq (car type) 'pvar))
(error-not-cpt type)
))
This will return one of boolean , unsigned - byte , signed - byte , defined - float ,
(defun canonical-pvar-element-type (type)
(error-if-not-cpt type)
(if (consp (cadr type)) (caadr type) (cadr type))
)
(defun array-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'array)))
(defun structure-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'structure)))
(defun array-pvar-type-dimensions (type)
(unless (array-pvar-type-p type) (error-not-cpt type))
(caddr (cadr type)))
(defun array-pvar-type-element-type (type)
(unless (array-pvar-type-p type) (error-not-cpt type))
(cadr (cadr type)))
(defun structure-pvar-type-name (type)
(unless (structure-pvar-type-p type) (error-not-cpt type))
(cadr (cadr type)))
(defun float-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'defined-float)))
(defun complex-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'complex)))
(defun boolean-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'boolean))
(defun front-end-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'front-end))
(defun general-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 't))
(defun string-char-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'string-char))
(defun character-pvar-type-p (type)
(error-if-not-cpt type)
(eq (cadr type) 'character))
(defun signed-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'signed-byte)))
(defun unsigned-pvar-type-p (type)
(error-if-not-cpt type)
(and (consp (cadr type)) (eq (caadr type) 'unsigned-byte)))
(defun float-pvar-type-mantissa (type)
(unless (float-pvar-type-p type)
(error "~S is not a canonical pvar float type." type))
(cadr (cadr type)))
(defun float-pvar-type-exponent (type)
(unless (float-pvar-type-p type)
(error "~S is not a canonical pvar float type." type))
(caddr (cadr type)))
(defun complex-pvar-type-mantissa (type)
(unless (complex-pvar-type-p type)
(error "~S is not a canonical pvar complex type." type))
(cadr (cadadr type)))
(defun complex-pvar-type-exponent (type)
(unless (complex-pvar-type-p type)
(error "~S is not a canonical pvar complex type." type))
(caddr (cadadr type)))
|
2ff43e604a7747f594b18f6bdb692721a46299556590d4882a2dc945618688b7 | Frechmatz/cl-threadpool | example-1.lisp | (defpackage :cl-threadpool-example-1
(:documentation "Synchronously execute a batch of jobs")
(:use :cl))
(in-package :cl-threadpool-example-1)
(defun example()
(let ((threadpool (cl-threadpool:make-threadpool 5 :name "Example thread pool")))
(let ((results
(cl-threadpool:run-jobs
threadpool
(list
(lambda() (sleep 5) "Batch-Job 1")
(lambda() (sleep 2) "Batch-Job 2")
(lambda() (sleep 1) "Batch-Job 3")))))
(format t "~%~a" (first results)) ;; => "Batch-Job 1"
(format t "~%~a" (second results)) ;; => "Batch-Job 2"
(format t "~%~a" (third results))) ;; => "Batch-Job 3"
(cl-threadpool:stop threadpool)))
;; (example)
| null | https://raw.githubusercontent.com/Frechmatz/cl-threadpool/86ef8a6b3d6a28ce41f25362c1c2db804d3ca605/examples/example-1.lisp | lisp | => "Batch-Job 1"
=> "Batch-Job 2"
=> "Batch-Job 3"
(example) | (defpackage :cl-threadpool-example-1
(:documentation "Synchronously execute a batch of jobs")
(:use :cl))
(in-package :cl-threadpool-example-1)
(defun example()
(let ((threadpool (cl-threadpool:make-threadpool 5 :name "Example thread pool")))
(let ((results
(cl-threadpool:run-jobs
threadpool
(list
(lambda() (sleep 5) "Batch-Job 1")
(lambda() (sleep 2) "Batch-Job 2")
(lambda() (sleep 1) "Batch-Job 3")))))
(cl-threadpool:stop threadpool)))
|
d2b8eaf8afbfe7e4d5179cd265129f6bf9e8ecdd9d4d414b57f1270c321a26b3 | isovector/cccc | Utils.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
{-# OPTIONS_GHC -Wall #-}
module Utils where
import Control.Lens ((<&>), makeLenses)
import Control.Monad.State
import Control.Monad.Trans.Except
import Data.Bifunctor (first, second)
import Data.List (nub)
import qualified Data.Map as M
import Data.Monoid ((<>))
import qualified Data.Set as S
import Debug.Trace (trace)
import Types
showTrace :: Show b => b -> b
showTrace = trace =<< show
data TIState = TIState
{ _tiVNames :: Int
, _tiTNames :: Int
, _tiSubst :: Subst
}
makeLenses ''TIState
type TI = ExceptT String (State TIState)
unravel :: Exp a -> Maybe (VName, [Exp a])
unravel = go []
where
go acc (LCon a) = pure (a, acc)
go acc (a :@ b) = go (b : acc) a
go _ _ = Nothing
unravelNative :: Exp a -> Maybe (String, [Exp a])
unravelNative = go []
where
go acc (Lit (LitNative a _)) = pure (a, acc)
go acc (a :@ b) = go (b : acc) a
go _ _ = Nothing
letters :: [String]
letters = do
b <- "":letters
a <- ['a'..'z']
pure $ a : b
runTI :: TI a -> Either String a
runTI = flip evalState (TIState 0 0 mempty) . runExceptT
kind :: Type -> TI Kind
kind (TVar x) = pure $ tKind x
kind (TCon x) = pure $ tKind x
kind (a :@@ b) = do
ka <- kind a
kb <- kind b
let kerr kk = throwE $ mconcat
[ "kind mismatch: '"
, show b
, " :: "
, show kb
, "' vs '"
, show kk
, "'\nwhen trying to apply '"
, show a
, " :: "
, show ka
, "'\n"
]
case ka of
kal :>> kar -> do
when (kal /= kb) $ kerr kal
pure kar
KStar -> kerr KStar
KConstraint -> kerr KConstraint
buildDataCon
:: VName
-> [Type]
-> Maybe Type
-> GenDataCon
buildDataCon n@(VName s) ts t' =
let ks = fmap (either error id . runTI . kind) ts
k = foldr (:>>) KStar ks
tr = maybe (foldl (:@@) (TCon $ TName s k)
. fmap TVar
$ S.toList $ free ts) id t'
t = foldr (:->) tr ts
ls = fmap fst $ zip (fmap VName letters) ts
in GenDataCon n ([] :=> t) ([] :=> tr)
. foldr lam
(foldl (:@) (LCon n) $ fmap V ls)
$ ls
buildRecord
:: VName
-> [(VName, Type)]
-> Maybe Type
-> (GenDataCon, [(VName, (Qual Type, Exp VName))])
buildRecord n fs t =
let gen@(GenDataCon _ _ t' _) = buildDataCon n (fmap snd fs) t
in (gen, )
$ zip [0..] fs <&> \(fn, (f, ft)) ->
let p = take (length fs) $ putBack $ splitAt fn $ repeat PWildcard
putBack (as, bs) = as <> [PVar "p"] <> bs
in (f,)
$ ([] :=> unqualType t' :-> ft,)
$ lam "z"
$ case_ "z"
$ [(PCon n p, "p")]
getDictName :: TName -> Type
getDictName n = TCon . TName (getDictName2 n) $ tKind n
getDictName2 :: TName -> String
getDictName2 n = "@" <> unTName n
getDictTypeForPred :: Pred -> Type
getDictTypeForPred (IsInst c t) = getDictName c :@@ t
getDict :: Pred -> String
getDict (IsInst c t) = "@" <> show c <> "@" <> show (normalizeType2 t)
buildDictType
:: Class
-> (GenDataCon, [(VName, (Qual Type, Exp VName))])
buildDictType c@(Class v n ms) =
second (fmap (second $ first $ dictToConstraint c))
$
buildRecord
(VName name)
-- TODO(sandy): there is a bug here if there is a constraint on the method
(fmap (second unqualType) $ M.assocs ms)
$ Just ((TVar $ TName name $ tKind n) :@@ TVar v)
( Just $ TCon ( TName name KStar ) )
where
name = getDictName2 n
buildDict :: GenDataCon -> InstRep Pred -> (VName, (Qual Type, Exp VName))
buildDict gdc (InstRep (_ :=> i@(IsInst c t)) impls) =
(VName dict,)
TODO(sandy ): buggy ; does n't do nested dicts
-- TODO(sandy): also buggy. we should just run the type checker on this
$ (sub (Subst $ M.fromList [("a", t)] ) $ gdcFinalType gdc,)
$ foldl (:@) (LCon (VName dname)) $ M.elems impls
where
dict = getDict i
dname = getDictName2 c
dictToConstraint :: Class -> Qual Type -> Qual Type
dictToConstraint (Class v n _) (qs :=> (_ :-> t)) =
(IsInst n $ TVar v) : qs :=> t
normalizeType :: Qual Type -> Qual Type
normalizeType = schemeType . normalize . Scheme mempty
normalizeType2 :: Type -> Type
normalizeType2 = unqualType . normalizeType . ([] :=>)
normalize :: Scheme -> Scheme
normalize (Scheme _ body) =
Scheme (fmap snd ord) $ normqual body
where
ord = zip (nub . S.toList $ free body) letters <&> \(old, l) ->
(old, TName l $ tKind old)
normqual (xs :=> zs) =
fmap (\(IsInst c t) -> IsInst c $ normtype t) xs :=> normtype zs
normtype (TCon a) = TCon a
normtype (a :@@ b) = normtype a :@@ normtype b
normtype (TVar a) =
case lookup a ord of
Just x -> TVar $ TName (unTName x) (tKind x)
Nothing -> error "type variable not in signature"
| null | https://raw.githubusercontent.com/isovector/cccc/57497046e7bf6170dfdb4964da6840001d46c91f/src/Utils.hs | haskell | # LANGUAGE OverloadedStrings #
# OPTIONS_GHC -Wall #
TODO(sandy): there is a bug here if there is a constraint on the method
TODO(sandy): also buggy. we should just run the type checker on this | # LANGUAGE FlexibleContexts #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
module Utils where
import Control.Lens ((<&>), makeLenses)
import Control.Monad.State
import Control.Monad.Trans.Except
import Data.Bifunctor (first, second)
import Data.List (nub)
import qualified Data.Map as M
import Data.Monoid ((<>))
import qualified Data.Set as S
import Debug.Trace (trace)
import Types
showTrace :: Show b => b -> b
showTrace = trace =<< show
data TIState = TIState
{ _tiVNames :: Int
, _tiTNames :: Int
, _tiSubst :: Subst
}
makeLenses ''TIState
type TI = ExceptT String (State TIState)
unravel :: Exp a -> Maybe (VName, [Exp a])
unravel = go []
where
go acc (LCon a) = pure (a, acc)
go acc (a :@ b) = go (b : acc) a
go _ _ = Nothing
unravelNative :: Exp a -> Maybe (String, [Exp a])
unravelNative = go []
where
go acc (Lit (LitNative a _)) = pure (a, acc)
go acc (a :@ b) = go (b : acc) a
go _ _ = Nothing
letters :: [String]
letters = do
b <- "":letters
a <- ['a'..'z']
pure $ a : b
runTI :: TI a -> Either String a
runTI = flip evalState (TIState 0 0 mempty) . runExceptT
kind :: Type -> TI Kind
kind (TVar x) = pure $ tKind x
kind (TCon x) = pure $ tKind x
kind (a :@@ b) = do
ka <- kind a
kb <- kind b
let kerr kk = throwE $ mconcat
[ "kind mismatch: '"
, show b
, " :: "
, show kb
, "' vs '"
, show kk
, "'\nwhen trying to apply '"
, show a
, " :: "
, show ka
, "'\n"
]
case ka of
kal :>> kar -> do
when (kal /= kb) $ kerr kal
pure kar
KStar -> kerr KStar
KConstraint -> kerr KConstraint
buildDataCon
:: VName
-> [Type]
-> Maybe Type
-> GenDataCon
buildDataCon n@(VName s) ts t' =
let ks = fmap (either error id . runTI . kind) ts
k = foldr (:>>) KStar ks
tr = maybe (foldl (:@@) (TCon $ TName s k)
. fmap TVar
$ S.toList $ free ts) id t'
t = foldr (:->) tr ts
ls = fmap fst $ zip (fmap VName letters) ts
in GenDataCon n ([] :=> t) ([] :=> tr)
. foldr lam
(foldl (:@) (LCon n) $ fmap V ls)
$ ls
buildRecord
:: VName
-> [(VName, Type)]
-> Maybe Type
-> (GenDataCon, [(VName, (Qual Type, Exp VName))])
buildRecord n fs t =
let gen@(GenDataCon _ _ t' _) = buildDataCon n (fmap snd fs) t
in (gen, )
$ zip [0..] fs <&> \(fn, (f, ft)) ->
let p = take (length fs) $ putBack $ splitAt fn $ repeat PWildcard
putBack (as, bs) = as <> [PVar "p"] <> bs
in (f,)
$ ([] :=> unqualType t' :-> ft,)
$ lam "z"
$ case_ "z"
$ [(PCon n p, "p")]
getDictName :: TName -> Type
getDictName n = TCon . TName (getDictName2 n) $ tKind n
getDictName2 :: TName -> String
getDictName2 n = "@" <> unTName n
getDictTypeForPred :: Pred -> Type
getDictTypeForPred (IsInst c t) = getDictName c :@@ t
getDict :: Pred -> String
getDict (IsInst c t) = "@" <> show c <> "@" <> show (normalizeType2 t)
buildDictType
:: Class
-> (GenDataCon, [(VName, (Qual Type, Exp VName))])
buildDictType c@(Class v n ms) =
second (fmap (second $ first $ dictToConstraint c))
$
buildRecord
(VName name)
(fmap (second unqualType) $ M.assocs ms)
$ Just ((TVar $ TName name $ tKind n) :@@ TVar v)
( Just $ TCon ( TName name KStar ) )
where
name = getDictName2 n
buildDict :: GenDataCon -> InstRep Pred -> (VName, (Qual Type, Exp VName))
buildDict gdc (InstRep (_ :=> i@(IsInst c t)) impls) =
(VName dict,)
TODO(sandy ): buggy ; does n't do nested dicts
$ (sub (Subst $ M.fromList [("a", t)] ) $ gdcFinalType gdc,)
$ foldl (:@) (LCon (VName dname)) $ M.elems impls
where
dict = getDict i
dname = getDictName2 c
dictToConstraint :: Class -> Qual Type -> Qual Type
dictToConstraint (Class v n _) (qs :=> (_ :-> t)) =
(IsInst n $ TVar v) : qs :=> t
normalizeType :: Qual Type -> Qual Type
normalizeType = schemeType . normalize . Scheme mempty
normalizeType2 :: Type -> Type
normalizeType2 = unqualType . normalizeType . ([] :=>)
normalize :: Scheme -> Scheme
normalize (Scheme _ body) =
Scheme (fmap snd ord) $ normqual body
where
ord = zip (nub . S.toList $ free body) letters <&> \(old, l) ->
(old, TName l $ tKind old)
normqual (xs :=> zs) =
fmap (\(IsInst c t) -> IsInst c $ normtype t) xs :=> normtype zs
normtype (TCon a) = TCon a
normtype (a :@@ b) = normtype a :@@ normtype b
normtype (TVar a) =
case lookup a ord of
Just x -> TVar $ TName (unTName x) (tKind x)
Nothing -> error "type variable not in signature"
|
97b3279bb1330537549a560498f5fef55ce5c6da5ba2b60245d867a86d36b655 | lehins/RockAnts | Common.hs | module Common
( module X
) where
import Test.Hspec as X
import Test.QuickCheck as X
| null | https://raw.githubusercontent.com/lehins/RockAnts/6b8cfcc476bb1230396ac18359cee578e5012154/tests/Common.hs | haskell | module Common
( module X
) where
import Test.Hspec as X
import Test.QuickCheck as X
| |
6e7d3fd342eb1aaae56850acb869d2b3f7dfc7a6a4c53e0468a661b8eaeb38e1 | ktakashi/sagittarius-scheme | keystores.scm | -*- mode : scheme ; coding : utf-8 ; -*-
;;;
sagittarius / crypto / keystores.scm - Keystores
;;;
Copyright ( c ) 2022 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. 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.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
#!nounbound
(library (sagittarius crypto keystores)
(export :all)
(import (sagittarius crypto keystores pkcs12)))
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/4581c9f88c1ca7044cca987a973d5b76b7258189/ext/crypto/sagittarius/crypto/keystores.scm | scheme | coding : utf-8 ; -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| sagittarius / crypto / keystores.scm - Keystores
Copyright ( c ) 2022 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
#!nounbound
(library (sagittarius crypto keystores)
(export :all)
(import (sagittarius crypto keystores pkcs12)))
|
01c23ad057770ed2a67693a2ea797443c6b5febda863d80f4282ffcd0b34ee8c | archaelus/erlirc | tcp_server.erl | %%%-------------------------------------------------------------------
Geoff Ca nt
@author nt < >
%% @version {@vsn}, {@date} {@time}
@doc A wrapper library to give gen_tcp a more Erlangy interface for
%% listen/accept.
%% @end
%%%-------------------------------------------------------------------
-module(tcp_server).
-behaviour(gen_server).
-include_lib("logging.hrl").
-include_lib("eunit/include/eunit.hrl").
%% API
-export([listen/2
,listen/3
,controlling_process/2
,close/1
,close/2]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3
,acceptor/2
]).
-record(state, {listen_socket,
acceptor,
controlling_process,
cp_monitor,
host,
port,
options}).
-define(SERVER, ?MODULE).
-define(LOCALHOST, {127,0,0,1}).
-define(ALLINTERFACES, {0,0,0,0}).
%%====================================================================
%% API
%%====================================================================
, OptionsProplist::list ( ) ) - > { ok , Pid } | ignore | { error , Error }
%% @see listen/3
listen(Port, Options) ->
listen(?ALLINTERFACES, Port, Options).
@spec listen(Host , Port::integer , OptionsProplist ) - > { ok , Pid } | ignore | { error , Error }
%% Host = {int(),int(),int(),int()} | string()
%% OptionsProplist = [Option]
Option = { client_handler , HandlerFn } | GenTcpOption
= term ( )
( ) , ClientSocket::port ( ) )
@doc Starts processes listening for connections on Port with
%% Options. The controlling process for the gen_tcp_server will be set
%% to the calling process.
%%
%% Host becomes the gen_tcp {ip, Host} option.
%%
%% @see gen_tcp:listen/2
%% @end
listen(Host, Port, Options) ->
gen_server:start_link(?MODULE, [self(), Host, Port, Options], []).
my_option({client_handler, _Fn}) -> true;
my_option(_) -> false.
( ) , NewControllingProcess::pid ( ) ) - > ok | { error , Error }
%% @doc Causes all new client notifications to be sent to
%% NewControllingProcess. The gen_tcp_server lifetime will track
%% NewControllingProcess too - when NewControllingProcess exits, the
%% gen_tcp_server will too.
%% @end
controlling_process(Server, Pid) ->
gen_server:call(Server, {controlling_process, Pid}).
close(Server::pid ( ) ) - > ok | { error , Error }
%% @see close/2
close(Server) ->
close(Server, timer:seconds(5)).
close(Server::pid ( ) , Timeout::integer ( ) ) - > ok | { error , Error }
@doc Cleanly shuts down the gen_tcp_server with a Timeout in milliseconds .
%% @end
close(Server, Timeout) ->
gen_server:call(Server, close, Timeout).
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
@private
) - > { ok , State } |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% @doc gen_server callback.
%% @end
%% Initiates the server
%%--------------------------------------------------------------------
init([Parent, Host, Port, Options]) ->
GenTcpOptions = gen_tcp_options([{ip, Host}, {active, false} | Options]),
? INFO("GenTCP Options : ~p " , [ GenTcpOptions ] ) ,
init(gen_tcp:listen(Port, GenTcpOptions), [Parent, Host, Port, Options]).
init({ok, Socket}, [Parent, Host, Port, Options]) ->
%?INFO("Got Socket ~p", [Socket]),
{ok, Acceptor} = proc_lib:start_link(?MODULE, acceptor, [self(), Socket]),
{ok, #state{listen_socket=Socket,
acceptor=Acceptor,
controlling_process=Parent,
cp_monitor=erlang:monitor(process, Parent),
host=Host,
port=Port,
options=Options}};
init({error, Reason}, _) ->
{stop, {gen_tcp, Reason}}.
%%--------------------------------------------------------------------
@private
handle_call(Request , From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% @doc gen_server callback.
%% @end
%% @see gen_server.
%%--------------------------------------------------------------------
handle_call(close, _From, S) ->
{stop, normal, ok, S};
handle_call({controlling_process, Pid}, _From, S = #state{controlling_process=P,
cp_monitor=Ref}) when P =/= Pid ->
erlang:demonitor(Ref),
{reply, ok, S#state{controlling_process=Pid,
cp_monitor=erlang:monitor(process, Pid)}};
handle_call({new_client, _CliSock}, _From, S = #state{controlling_process=P,
listen_socket=Socket,
options=O}) ->
ClientHandler = proplists:get_value(client_handler, O,
fun default_client_handler/2),
{ok, Acceptor} = proc_lib:start_link(?MODULE, acceptor, [self(), Socket]),
{reply, {ok, ClientHandler, P}, S#state{acceptor=Acceptor}};
handle_call(Call, _From, State) ->
?WARN("Unexpected call ~p.", [Call]),
{noreply, State}.
%%--------------------------------------------------------------------
@private
handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% @doc gen_server callback.
%% @end
%% Handling cast messages
%%--------------------------------------------------------------------
handle_cast(Msg, State) ->
?WARN("Unexpected cast ~p", [Msg]),
{noreply, State}.
%%--------------------------------------------------------------------
@private
handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% @doc gen_server callback.
%% @end
%% Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info({'DOWN', MonitorRef, process, ContollingProcess, Ok},
S = #state{controlling_process=ContollingProcess,
cp_monitor=MonitorRef}) when Ok =:= normal; Ok =:= shutdown ->
{stop, Ok, S};
handle_info({'DOWN', MonitorRef, process, ContollingProcess, Error},
S = #state{controlling_process=ContollingProcess,
cp_monitor=MonitorRef}) ->
{stop, {controlling_process, Error}, S};
handle_info(Info, State) ->
?WARN("Unexpected info ~p", [Info]),
{noreply, State}.
%%--------------------------------------------------------------------
@private
, State ) - > void ( )
%% @doc gen_server callback.
%% @end
%% This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(Reason, S = #state{listen_socket=Sck}) when Sck =/= undefined ->
gen_tcp:close(Sck),
terminate(Reason, S#state{listen_socket=undefined});
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
@private
, State , Extra ) - > { ok , NewState }
%% @doc gen_server callback.
%% @end
%% Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
@private
@spec acceptor(Parent::pid ( ) , Socket::port ( ) ) - > ok | closed | { error , term ( ) }
@doc Proc lib wrapper process for gen_tcp : accept/1 .
@see gen_tcp : accept/1
%% @see proc_lib:init_ack/2
acceptor(Parent, Socket) ->
proc_lib:init_ack(Parent, {ok, self()}),
case gen_tcp:accept(Socket) of
{ok, ClientSock} ->
new_client(Parent, Socket, ClientSock);
{error, closed} ->
closed;
{error, Reason} ->
exit(Reason)
end.
new_client(Parent, _ListenSock, ClientSock) ->
case gen_server:call(Parent, {new_client, ClientSock}) of
{ok, ClientHandlerFn, ClientParent} when is_function(ClientHandlerFn) ->
ClientHandlerFn(ClientParent, ClientSock);
Else ->
?WARN("Couldn't handle new client, ~p", [Else]),
gen_tcp:close(ClientSock),
exit(Else)
end.
handle_new_client(ok) -> ok;
handle_new_client(Error) -> {error, {client_handler, Error}}.
gen_tcp_options(Options) ->
lists:filter(fun (O) -> my_option(O) =:= false end,
proplists:unfold(proplists:normalize(Options, []))).
default_client_handler(Parent, ClientSocket) ->
gen_tcp:controlling_process(ClientSocket, Parent),
Parent ! {?MODULE, new_client, ClientSocket},
ok.
gtcps_test() ->
TestPort = 56432,
TestValue = "TestValue",
{ok, Pid} = listen(TestPort, [{packet, 4}]),
{ok, Socket} = gen_tcp:connect(?LOCALHOST, TestPort, [{packet, 4}]),
receive
{?MODULE, new_client, CliSock} ->
?assertMatch(ok, gen_tcp:controlling_process(CliSock, self())),
?assertMatch(ok, gen_tcp:send(Socket, TestValue)),
?assertMatch({ok, TestValue}, gen_tcp:recv(CliSock, 0)),
?assertMatch(ok, gen_tcp:close(Socket))
after timer:seconds(5) ->
?assertMatch(no_timeout, timeout)
end,
{ok, Socket2} = gen_tcp:connect(?LOCALHOST, TestPort, [{packet, 4}]),
receive
{?MODULE, new_client, CliSock2} ->
?assertMatch(ok, gen_tcp:controlling_process(CliSock2, self())),
?assertMatch(ok, gen_tcp:send(Socket2, TestValue)),
?assertMatch({ok, TestValue}, gen_tcp:recv(CliSock2, 0)),
?assertMatch(ok, gen_tcp:close(Socket2))
after timer:seconds(5) ->
?assertMatch(no_timeout, timeout)
end,
ok = close(Pid).
| null | https://raw.githubusercontent.com/archaelus/erlirc/b922b2004f0f9f58a6ccf8fe71313190dee081c6/src/tcp_server.erl | erlang | -------------------------------------------------------------------
@version {@vsn}, {@date} {@time}
listen/accept.
@end
-------------------------------------------------------------------
API
gen_server callbacks
====================================================================
API
====================================================================
@see listen/3
Host = {int(),int(),int(),int()} | string()
OptionsProplist = [Option]
Options. The controlling process for the gen_tcp_server will be set
to the calling process.
Host becomes the gen_tcp {ip, Host} option.
@see gen_tcp:listen/2
@end
@doc Causes all new client notifications to be sent to
NewControllingProcess. The gen_tcp_server lifetime will track
NewControllingProcess too - when NewControllingProcess exits, the
gen_tcp_server will too.
@end
@see close/2
@end
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
ignore |
{stop, Reason}
@doc gen_server callback.
@end
Initiates the server
--------------------------------------------------------------------
?INFO("Got Socket ~p", [Socket]),
--------------------------------------------------------------------
{stop, Reason, Reply, State} |
{stop, Reason, State}
@doc gen_server callback.
@end
@see gen_server.
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
@doc gen_server callback.
@end
Handling cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
@doc gen_server callback.
@end
Handling all non call/cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc gen_server callback.
@end
This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any necessary
cleaning up. When it returns, the gen_server terminates with Reason.
The return value is ignored.
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc gen_server callback.
@end
Convert process state when code is changed
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
@see proc_lib:init_ack/2 | Geoff Ca nt
@author nt < >
@doc A wrapper library to give gen_tcp a more Erlangy interface for
-module(tcp_server).
-behaviour(gen_server).
-include_lib("logging.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([listen/2
,listen/3
,controlling_process/2
,close/1
,close/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3
,acceptor/2
]).
-record(state, {listen_socket,
acceptor,
controlling_process,
cp_monitor,
host,
port,
options}).
-define(SERVER, ?MODULE).
-define(LOCALHOST, {127,0,0,1}).
-define(ALLINTERFACES, {0,0,0,0}).
, OptionsProplist::list ( ) ) - > { ok , Pid } | ignore | { error , Error }
listen(Port, Options) ->
listen(?ALLINTERFACES, Port, Options).
@spec listen(Host , Port::integer , OptionsProplist ) - > { ok , Pid } | ignore | { error , Error }
Option = { client_handler , HandlerFn } | GenTcpOption
= term ( )
( ) , ClientSocket::port ( ) )
@doc Starts processes listening for connections on Port with
listen(Host, Port, Options) ->
gen_server:start_link(?MODULE, [self(), Host, Port, Options], []).
my_option({client_handler, _Fn}) -> true;
my_option(_) -> false.
( ) , NewControllingProcess::pid ( ) ) - > ok | { error , Error }
controlling_process(Server, Pid) ->
gen_server:call(Server, {controlling_process, Pid}).
close(Server::pid ( ) ) - > ok | { error , Error }
close(Server) ->
close(Server, timer:seconds(5)).
close(Server::pid ( ) , Timeout::integer ( ) ) - > ok | { error , Error }
@doc Cleanly shuts down the gen_tcp_server with a Timeout in milliseconds .
close(Server, Timeout) ->
gen_server:call(Server, close, Timeout).
@private
) - > { ok , State } |
{ ok , State , Timeout } |
init([Parent, Host, Port, Options]) ->
GenTcpOptions = gen_tcp_options([{ip, Host}, {active, false} | Options]),
? INFO("GenTCP Options : ~p " , [ GenTcpOptions ] ) ,
init(gen_tcp:listen(Port, GenTcpOptions), [Parent, Host, Port, Options]).
init({ok, Socket}, [Parent, Host, Port, Options]) ->
{ok, Acceptor} = proc_lib:start_link(?MODULE, acceptor, [self(), Socket]),
{ok, #state{listen_socket=Socket,
acceptor=Acceptor,
controlling_process=Parent,
cp_monitor=erlang:monitor(process, Parent),
host=Host,
port=Port,
options=Options}};
init({error, Reason}, _) ->
{stop, {gen_tcp, Reason}}.
@private
handle_call(Request , From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call(close, _From, S) ->
{stop, normal, ok, S};
handle_call({controlling_process, Pid}, _From, S = #state{controlling_process=P,
cp_monitor=Ref}) when P =/= Pid ->
erlang:demonitor(Ref),
{reply, ok, S#state{controlling_process=Pid,
cp_monitor=erlang:monitor(process, Pid)}};
handle_call({new_client, _CliSock}, _From, S = #state{controlling_process=P,
listen_socket=Socket,
options=O}) ->
ClientHandler = proplists:get_value(client_handler, O,
fun default_client_handler/2),
{ok, Acceptor} = proc_lib:start_link(?MODULE, acceptor, [self(), Socket]),
{reply, {ok, ClientHandler, P}, S#state{acceptor=Acceptor}};
handle_call(Call, _From, State) ->
?WARN("Unexpected call ~p.", [Call]),
{noreply, State}.
@private
handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(Msg, State) ->
?WARN("Unexpected cast ~p", [Msg]),
{noreply, State}.
@private
handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info({'DOWN', MonitorRef, process, ContollingProcess, Ok},
S = #state{controlling_process=ContollingProcess,
cp_monitor=MonitorRef}) when Ok =:= normal; Ok =:= shutdown ->
{stop, Ok, S};
handle_info({'DOWN', MonitorRef, process, ContollingProcess, Error},
S = #state{controlling_process=ContollingProcess,
cp_monitor=MonitorRef}) ->
{stop, {controlling_process, Error}, S};
handle_info(Info, State) ->
?WARN("Unexpected info ~p", [Info]),
{noreply, State}.
@private
, State ) - > void ( )
terminate(Reason, S = #state{listen_socket=Sck}) when Sck =/= undefined ->
gen_tcp:close(Sck),
terminate(Reason, S#state{listen_socket=undefined});
terminate(_Reason, _State) ->
ok.
@private
, State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
@private
@spec acceptor(Parent::pid ( ) , Socket::port ( ) ) - > ok | closed | { error , term ( ) }
@doc Proc lib wrapper process for gen_tcp : accept/1 .
@see gen_tcp : accept/1
acceptor(Parent, Socket) ->
proc_lib:init_ack(Parent, {ok, self()}),
case gen_tcp:accept(Socket) of
{ok, ClientSock} ->
new_client(Parent, Socket, ClientSock);
{error, closed} ->
closed;
{error, Reason} ->
exit(Reason)
end.
new_client(Parent, _ListenSock, ClientSock) ->
case gen_server:call(Parent, {new_client, ClientSock}) of
{ok, ClientHandlerFn, ClientParent} when is_function(ClientHandlerFn) ->
ClientHandlerFn(ClientParent, ClientSock);
Else ->
?WARN("Couldn't handle new client, ~p", [Else]),
gen_tcp:close(ClientSock),
exit(Else)
end.
handle_new_client(ok) -> ok;
handle_new_client(Error) -> {error, {client_handler, Error}}.
gen_tcp_options(Options) ->
lists:filter(fun (O) -> my_option(O) =:= false end,
proplists:unfold(proplists:normalize(Options, []))).
default_client_handler(Parent, ClientSocket) ->
gen_tcp:controlling_process(ClientSocket, Parent),
Parent ! {?MODULE, new_client, ClientSocket},
ok.
gtcps_test() ->
TestPort = 56432,
TestValue = "TestValue",
{ok, Pid} = listen(TestPort, [{packet, 4}]),
{ok, Socket} = gen_tcp:connect(?LOCALHOST, TestPort, [{packet, 4}]),
receive
{?MODULE, new_client, CliSock} ->
?assertMatch(ok, gen_tcp:controlling_process(CliSock, self())),
?assertMatch(ok, gen_tcp:send(Socket, TestValue)),
?assertMatch({ok, TestValue}, gen_tcp:recv(CliSock, 0)),
?assertMatch(ok, gen_tcp:close(Socket))
after timer:seconds(5) ->
?assertMatch(no_timeout, timeout)
end,
{ok, Socket2} = gen_tcp:connect(?LOCALHOST, TestPort, [{packet, 4}]),
receive
{?MODULE, new_client, CliSock2} ->
?assertMatch(ok, gen_tcp:controlling_process(CliSock2, self())),
?assertMatch(ok, gen_tcp:send(Socket2, TestValue)),
?assertMatch({ok, TestValue}, gen_tcp:recv(CliSock2, 0)),
?assertMatch(ok, gen_tcp:close(Socket2))
after timer:seconds(5) ->
?assertMatch(no_timeout, timeout)
end,
ok = close(Pid).
|
41b81ac60d3081447dc34390de69c6cf0b011ca68b3d5f73255179ea38f9104c | wireapp/wire-server | LoginCode_user.hs | -- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Test.Wire.API.Golden.Generated.LoginCode_user where
import Wire.API.User.Auth (LoginCode (..))
testObject_LoginCode_user_1 :: LoginCode
testObject_LoginCode_user_1 = LoginCode {fromLoginCode = "\DLE~0j"}
testObject_LoginCode_user_2 :: LoginCode
testObject_LoginCode_user_2 = LoginCode {fromLoginCode = "A[jh<o\1044837?^s\14833u9\DC3\SIOUC2?X\160613\15473 \SOH`\r"}
testObject_LoginCode_user_3 :: LoginCode
testObject_LoginCode_user_3 = LoginCode {fromLoginCode = "=ul^\37571b\164879\1068736h6"}
testObject_LoginCode_user_4 :: LoginCode
testObject_LoginCode_user_4 = LoginCode {fromLoginCode = "."}
testObject_LoginCode_user_5 :: LoginCode
testObject_LoginCode_user_5 = LoginCode {fromLoginCode = "\DEL\172890U8\\\SYNg\DC4\1058657\1013344\EOT:\USq\RSV~_\NULx"}
testObject_LoginCode_user_6 :: LoginCode
testObject_LoginCode_user_6 = LoginCode {fromLoginCode = "M@\DEL\DLE*"}
testObject_LoginCode_user_7 :: LoginCode
testObject_LoginCode_user_7 = LoginCode {fromLoginCode = "\t\1013514B\EOT\1006353\EOT\1113695\r\1025460"}
testObject_LoginCode_user_8 :: LoginCode
testObject_LoginCode_user_8 = LoginCode {fromLoginCode = "\10686fd_]\1089889>\SO\22981\ENQla\1096933\CAN-\FS\DC3}e"}
testObject_LoginCode_user_9 :: LoginCode
testObject_LoginCode_user_9 = LoginCode {fromLoginCode = "f`j\1002620K\USm\1108775\46341>\ETB%O"}
testObject_LoginCode_user_10 :: LoginCode
testObject_LoginCode_user_10 = LoginCode {fromLoginCode = "W\ESC\DC4u"}
testObject_LoginCode_user_11 :: LoginCode
testObject_LoginCode_user_11 =
LoginCode {fromLoginCode = ".Z\f\1038820Ux\145788\STX\16118\NUL\SYNS\1092765\DC3\DELP\1003786\ETX|h\987631"}
testObject_LoginCode_user_12 :: LoginCode
testObject_LoginCode_user_12 = LoginCode {fromLoginCode = "S!i5\SUB{\1042102!]\CAN\41836\1079056l"}
testObject_LoginCode_user_13 :: LoginCode
testObject_LoginCode_user_13 = LoginCode {fromLoginCode = "}\SIQ:\38444\12018H\1111816\DC2T"}
testObject_LoginCode_user_14 :: LoginCode
testObject_LoginCode_user_14 = LoginCode {fromLoginCode = "7V\119013\74081/?O\1085005D\DC1"}
testObject_LoginCode_user_15 :: LoginCode
testObject_LoginCode_user_15 = LoginCode {fromLoginCode = "r\11162L[\45618c3e]\1072799N\SUB"}
testObject_LoginCode_user_16 :: LoginCode
testObject_LoginCode_user_16 = LoginCode {fromLoginCode = "s\1102063"}
testObject_LoginCode_user_17 :: LoginCode
testObject_LoginCode_user_17 = LoginCode {fromLoginCode = "A,gVB.Nf\8255\&5\999384[\1042634@\1100583="}
testObject_LoginCode_user_18 :: LoginCode
testObject_LoginCode_user_18 = LoginCode {fromLoginCode = "E\1049604_b^V\EOT\SUB>%\33456B/g"}
testObject_LoginCode_user_19 :: LoginCode
testObject_LoginCode_user_19 = LoginCode {fromLoginCode = "z!@hZF\FSj\v\137098\10010"}
testObject_LoginCode_user_20 :: LoginCode
testObject_LoginCode_user_20 = LoginCode {fromLoginCode = "\n&%3s:q\1026580\1015041cu\RS\DC4p4.N\1053981T"}
| null | https://raw.githubusercontent.com/wireapp/wire-server/c428355b7683b7b7722ea544eba314fc843ad8fa/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/LoginCode_user.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>. | Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Test.Wire.API.Golden.Generated.LoginCode_user where
import Wire.API.User.Auth (LoginCode (..))
testObject_LoginCode_user_1 :: LoginCode
testObject_LoginCode_user_1 = LoginCode {fromLoginCode = "\DLE~0j"}
testObject_LoginCode_user_2 :: LoginCode
testObject_LoginCode_user_2 = LoginCode {fromLoginCode = "A[jh<o\1044837?^s\14833u9\DC3\SIOUC2?X\160613\15473 \SOH`\r"}
testObject_LoginCode_user_3 :: LoginCode
testObject_LoginCode_user_3 = LoginCode {fromLoginCode = "=ul^\37571b\164879\1068736h6"}
testObject_LoginCode_user_4 :: LoginCode
testObject_LoginCode_user_4 = LoginCode {fromLoginCode = "."}
testObject_LoginCode_user_5 :: LoginCode
testObject_LoginCode_user_5 = LoginCode {fromLoginCode = "\DEL\172890U8\\\SYNg\DC4\1058657\1013344\EOT:\USq\RSV~_\NULx"}
testObject_LoginCode_user_6 :: LoginCode
testObject_LoginCode_user_6 = LoginCode {fromLoginCode = "M@\DEL\DLE*"}
testObject_LoginCode_user_7 :: LoginCode
testObject_LoginCode_user_7 = LoginCode {fromLoginCode = "\t\1013514B\EOT\1006353\EOT\1113695\r\1025460"}
testObject_LoginCode_user_8 :: LoginCode
testObject_LoginCode_user_8 = LoginCode {fromLoginCode = "\10686fd_]\1089889>\SO\22981\ENQla\1096933\CAN-\FS\DC3}e"}
testObject_LoginCode_user_9 :: LoginCode
testObject_LoginCode_user_9 = LoginCode {fromLoginCode = "f`j\1002620K\USm\1108775\46341>\ETB%O"}
testObject_LoginCode_user_10 :: LoginCode
testObject_LoginCode_user_10 = LoginCode {fromLoginCode = "W\ESC\DC4u"}
testObject_LoginCode_user_11 :: LoginCode
testObject_LoginCode_user_11 =
LoginCode {fromLoginCode = ".Z\f\1038820Ux\145788\STX\16118\NUL\SYNS\1092765\DC3\DELP\1003786\ETX|h\987631"}
testObject_LoginCode_user_12 :: LoginCode
testObject_LoginCode_user_12 = LoginCode {fromLoginCode = "S!i5\SUB{\1042102!]\CAN\41836\1079056l"}
testObject_LoginCode_user_13 :: LoginCode
testObject_LoginCode_user_13 = LoginCode {fromLoginCode = "}\SIQ:\38444\12018H\1111816\DC2T"}
testObject_LoginCode_user_14 :: LoginCode
testObject_LoginCode_user_14 = LoginCode {fromLoginCode = "7V\119013\74081/?O\1085005D\DC1"}
testObject_LoginCode_user_15 :: LoginCode
testObject_LoginCode_user_15 = LoginCode {fromLoginCode = "r\11162L[\45618c3e]\1072799N\SUB"}
testObject_LoginCode_user_16 :: LoginCode
testObject_LoginCode_user_16 = LoginCode {fromLoginCode = "s\1102063"}
testObject_LoginCode_user_17 :: LoginCode
testObject_LoginCode_user_17 = LoginCode {fromLoginCode = "A,gVB.Nf\8255\&5\999384[\1042634@\1100583="}
testObject_LoginCode_user_18 :: LoginCode
testObject_LoginCode_user_18 = LoginCode {fromLoginCode = "E\1049604_b^V\EOT\SUB>%\33456B/g"}
testObject_LoginCode_user_19 :: LoginCode
testObject_LoginCode_user_19 = LoginCode {fromLoginCode = "z!@hZF\FSj\v\137098\10010"}
testObject_LoginCode_user_20 :: LoginCode
testObject_LoginCode_user_20 = LoginCode {fromLoginCode = "\n&%3s:q\1026580\1015041cu\RS\DC4p4.N\1053981T"}
|
1ef4aa20daa108dc8e9a2eab06e15f85d42ecbb4f105fd94295ab85591ba2e57 | BinaryAnalysisPlatform/bap | dwarf_types.ml | (** Basic type declarations for DWARF format. *)
open Core_kernel[@@warning "-D"]
open Bap.Std
type leb128 = Dwarf_leb128.t [@@deriving bin_io, compare, sexp]
(** File sections *)
module Section = struct
type t =
| Info
| Abbrev
| Str
[@@deriving sexp, bin_io, compare, variants]
end
(** Debug Entry Tag *)
module Tag = struct
type t =
| Compile_unit
| Partial_unit
| Subprogram
| Entry_point
| Inlined_subroutine
| Unknown of int
[@@deriving sexp, bin_io, compare, variants]
end
(** Attribute *)
module Attr = struct
type t =
| Name
| Low_pc
| High_pc
| Entry_pc
| Unknown of int
[@@deriving sexp, bin_io, compare, variants]
end
type lenspec =
| Leb128
| One
| Two
| Four
| Eight
[@@deriving sexp, bin_io, compare]
(** Attribute form *)
module Form = struct
type t =
| Addr
| String
| Block of lenspec
| Const of lenspec
| Flag_present
| Strp
| Ref of lenspec
| Indirect
| Offset
| Expr
| Sig
[@@deriving sexp, bin_io, compare, variants]
end
type tag = Tag.t [@@deriving sexp, bin_io, compare]
type attr = Attr.t [@@deriving sexp, bin_io, compare]
type form = Form.t [@@deriving sexp, bin_io, compare]
type section = Section.t [@@deriving sexp, bin_io, compare]
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/bap_dwarf/dwarf_types.ml | ocaml | * Basic type declarations for DWARF format.
* File sections
* Debug Entry Tag
* Attribute
* Attribute form | open Core_kernel[@@warning "-D"]
open Bap.Std
type leb128 = Dwarf_leb128.t [@@deriving bin_io, compare, sexp]
module Section = struct
type t =
| Info
| Abbrev
| Str
[@@deriving sexp, bin_io, compare, variants]
end
module Tag = struct
type t =
| Compile_unit
| Partial_unit
| Subprogram
| Entry_point
| Inlined_subroutine
| Unknown of int
[@@deriving sexp, bin_io, compare, variants]
end
module Attr = struct
type t =
| Name
| Low_pc
| High_pc
| Entry_pc
| Unknown of int
[@@deriving sexp, bin_io, compare, variants]
end
type lenspec =
| Leb128
| One
| Two
| Four
| Eight
[@@deriving sexp, bin_io, compare]
module Form = struct
type t =
| Addr
| String
| Block of lenspec
| Const of lenspec
| Flag_present
| Strp
| Ref of lenspec
| Indirect
| Offset
| Expr
| Sig
[@@deriving sexp, bin_io, compare, variants]
end
type tag = Tag.t [@@deriving sexp, bin_io, compare]
type attr = Attr.t [@@deriving sexp, bin_io, compare]
type form = Form.t [@@deriving sexp, bin_io, compare]
type section = Section.t [@@deriving sexp, bin_io, compare]
|
571bbc8a6b30ae881d0e059393cb3e0fbad105d08d5d913e816503e21f7403f8 | Motiva-AI/stepwise | client.clj | (ns stepwise.client
(:require [stepwise.model :as mdl]
[clojure.core.async :as async])
(:import (com.amazonaws.services.stepfunctions AWSStepFunctionsClient
AWSStepFunctionsClientBuilder)
(com.amazonaws ClientConfiguration)
(com.amazonaws.services.stepfunctions.builder StateMachine)))
(set! *warn-on-reflection* true)
(def default-client
(atom nil))
(def client-config
(doto (ClientConfiguration.)
(.setSocketTimeout 70000)
(.setMaxConnections 75)))
(def stock-default-client
(delay (-> (AWSStepFunctionsClientBuilder/standard)
(.withClientConfiguration client-config)
(.build))))
(defn set-default-client! [^AWSStepFunctionsClient client]
(reset! default-client client))
(defn get-default-client []
(if-let [client @default-client]
client
@stock-default-client))
(defn get-client-max-connections
([^AWSStepFunctionsClient client]
(-> client
(.getClientConfiguration)
(.getMaxConnections)))
([]
(get-client-max-connections (get-default-client))))
(defn syms->pairs [syms]
(into []
(mapcat #(vector (keyword (name 'stepwise.model) (name %))
%))
syms))
(defmacro syms->map [& symbols]
`(hash-map ~@(syms->pairs symbols)))
(defn create-activity
([name]
(create-activity (get-default-client) name))
([^AWSStepFunctionsClient client name]
(->> (syms->map name)
mdl/map->CreateActivityRequest
(.createActivity client)
mdl/CreateActivityResult->map
::mdl/arn)))
(defn create-state-machine
([name definition role-arn]
(create-state-machine (get-default-client) name definition role-arn))
([^AWSStepFunctionsClient client name definition role-arn]
(->> (syms->map name
role-arn
definition)
mdl/map->CreateStateMachineRequest
(.createStateMachine client)
mdl/CreateStateMachineResult->map
::mdl/arn)))
(defn update-state-machine
([arn definition role-arn]
(update-state-machine (get-default-client) arn definition role-arn))
([^AWSStepFunctionsClient client arn definition role-arn]
(->> #::mdl {:arn arn
:definition-json (.toPrettyJson ^StateMachine
(mdl/map->StateMachine definition))
:role-arn role-arn}
mdl/map->UpdateStateMachineRequest
(.updateStateMachine client)
mdl/UpdateStateMachineResult->map)
arn))
(defn delete-activity
([arn] (delete-activity (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(.deleteActivity client (mdl/map->DeleteActivityRequest (syms->map arn)))
nil))
(defn delete-state-machine
([arn] (delete-state-machine (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(.deleteStateMachine client (mdl/map->DeleteStateMachineRequest (syms->map arn)))
nil))
(defn describe-activity
([arn] (describe-activity (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(->> (syms->map arn)
mdl/map->DescribeActivityRequest
(.describeActivity client)
mdl/DescribeActivityResult->map)))
(defn describe-execution
([arn] (describe-execution (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(->> (syms->map arn)
mdl/map->DescribeExecutionRequest
(.describeExecution client)
mdl/DescribeExecutionResult->map)))
(defn describe-state-machine
([arn] (describe-state-machine (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(->> (syms->map arn)
mdl/map->DescribeStateMachineRequest
(.describeStateMachine client)
mdl/DescribeStateMachineResult->map)))
(defn get-activity-task
([arn]
(get-activity-task arn nil))
([arn {:keys [worker-name] :as opts}]
(get-activity-task (get-default-client) arn opts))
([^AWSStepFunctionsClient client arn {:keys [worker-name]}]
(->> (syms->map arn worker-name)
mdl/map->GetActivityTaskRequest
(.getActivityTask client)
mdl/GetActivityTaskResult->map)))
(defn get-execution-history
([arn]
(get-execution-history arn nil))
([arn {:keys [max-results next-token reverse-order?] :as opts}]
(get-execution-history (get-default-client) arn opts))
([^AWSStepFunctionsClient client arn {:keys [max-results next-token reverse-order?]}]
(->> (syms->map arn max-results next-token reverse-order?)
mdl/map->GetExecutionHistoryRequest
(.getExecutionHistory client)
mdl/GetExecutionHistoryResult->map)))
(defn list-activities
([] (list-activities nil))
([{:keys [max-results next-token] :as opts}]
(list-activities (get-default-client) opts))
([^AWSStepFunctionsClient client {:keys [max-results next-token]}]
(->> (syms->map max-results next-token)
mdl/map->ListActivitiesRequest
(.listActivities client)
mdl/ListActivitiesResult->map)))
(defn list-executions
([state-machine-arn]
(list-executions state-machine-arn nil))
([state-machine-arn {:keys [status-filter next-token max-results] :as opts}]
(list-executions (get-default-client) state-machine-arn opts))
([^AWSStepFunctionsClient client state-machine-arn {:keys [status-filter next-token max-results]}]
(let [request-map (syms->map state-machine-arn status-filter next-token max-results)]
(->> (if (nil? (::mdl/status-filter request-map))
(dissoc request-map ::mdl/status-filter)
request-map)
mdl/map->ListExecutionsRequest
(.listExecutions client)
mdl/ListExecutionsResult->map))))
(defn list-state-machines
([] (list-state-machines nil))
([{:keys [max-results next-token] :as opts}]
(list-state-machines (get-default-client) opts))
([^AWSStepFunctionsClient client {:keys [max-results next-token]}]
(->> (syms->map max-results next-token)
mdl/map->ListStateMachinesRequest
(.listStateMachines client)
mdl/ListStateMachinesResult->map)))
(defn send-task-failure
([task-token]
(send-task-failure task-token nil))
([task-token {:keys [cause error] :as opts}]
(send-task-failure (get-default-client) task-token opts))
([^AWSStepFunctionsClient client task-token {:keys [cause error]}]
(->> (syms->map task-token cause error)
mdl/map->SendTaskFailureRequest
(.sendTaskFailure client))
nil))
(defn send-task-success
([task-token output]
(send-task-success (get-default-client) task-token output))
([^AWSStepFunctionsClient client task-token output]
(->> (syms->map task-token output)
mdl/map->SendTaskSuccessRequest
(.sendTaskSuccess client))
nil))
(defn send-task-heartbeat
([task-token]
(send-task-heartbeat (get-default-client) task-token))
([^AWSStepFunctionsClient client task-token]
(->> (syms->map task-token)
mdl/map->SendTaskHeartbeatRequest
(.sendTaskHeartbeat client))
nil))
(defn start-execution
([state-machine-arn]
(start-execution state-machine-arn nil))
([state-machine-arn {:keys [input name] :as opts}]
(start-execution (get-default-client) state-machine-arn opts))
([^AWSStepFunctionsClient client state-machine-arn {:keys [input name]}]
(->> (syms->map state-machine-arn input name)
mdl/map->StartExecutionRequest
(.startExecution client)
mdl/StartExecutionResult->map
::mdl/arn)))
(defn stop-execution
([arn]
(stop-execution arn nil))
([arn {:keys [cause error] :as opts}]
(stop-execution (get-default-client) arn opts))
([^AWSStepFunctionsClient client arn {:keys [cause error]}]
(->> (syms->map arn cause error)
mdl/map->StopExecutionRequest
(.stopExecution client))
nil))
(defn auto-page' [client-fn items-key base-args xform]
(let [items-chan (async/chan 1 xform)
[base-pos-args base-map-args] (if (map? (last base-args))
[(pop base-args) (last base-args)]
[base-args {}])
get-page (fn [token]
(let [map-args (assoc base-map-args :next-token token)
args (conj base-pos-args map-args)]
(apply client-fn args)))]
(async/go
(try (loop [page (get-page nil)]
(async/<! (async/onto-chan items-chan
(get page items-key)
false))
(when-let [next-token (::mdl/next-token page)]
(recur (get-page next-token))))
(catch Throwable e
(async/>! items-chan e)))
(async/close! items-chan))
items-chan))
(def request-fn->items-key
{#'get-execution-history ::mdl/events
#'list-activities ::mdl/activities
#'list-executions ::mdl/executions
#'list-state-machines ::mdl/state-machines})
(defmacro auto-page [request-form & [xform]]
(let [request-fn-sym (first request-form)
request-fn-var (resolve request-fn-sym)
items-key (request-fn->items-key request-fn-var)]
(when-not items-key
(throw (ex-info "Function called is not paginating"
{:request-fn request-fn-var})))
`(auto-page' ~request-fn-sym
~items-key
~(vec (rest request-form))
~xform)))
| null | https://raw.githubusercontent.com/Motiva-AI/stepwise/3986bc9e50e89390bb6459757901317ab505e756/src/stepwise/client.clj | clojure | (ns stepwise.client
(:require [stepwise.model :as mdl]
[clojure.core.async :as async])
(:import (com.amazonaws.services.stepfunctions AWSStepFunctionsClient
AWSStepFunctionsClientBuilder)
(com.amazonaws ClientConfiguration)
(com.amazonaws.services.stepfunctions.builder StateMachine)))
(set! *warn-on-reflection* true)
(def default-client
(atom nil))
(def client-config
(doto (ClientConfiguration.)
(.setSocketTimeout 70000)
(.setMaxConnections 75)))
(def stock-default-client
(delay (-> (AWSStepFunctionsClientBuilder/standard)
(.withClientConfiguration client-config)
(.build))))
(defn set-default-client! [^AWSStepFunctionsClient client]
(reset! default-client client))
(defn get-default-client []
(if-let [client @default-client]
client
@stock-default-client))
(defn get-client-max-connections
([^AWSStepFunctionsClient client]
(-> client
(.getClientConfiguration)
(.getMaxConnections)))
([]
(get-client-max-connections (get-default-client))))
(defn syms->pairs [syms]
(into []
(mapcat #(vector (keyword (name 'stepwise.model) (name %))
%))
syms))
(defmacro syms->map [& symbols]
`(hash-map ~@(syms->pairs symbols)))
(defn create-activity
([name]
(create-activity (get-default-client) name))
([^AWSStepFunctionsClient client name]
(->> (syms->map name)
mdl/map->CreateActivityRequest
(.createActivity client)
mdl/CreateActivityResult->map
::mdl/arn)))
(defn create-state-machine
([name definition role-arn]
(create-state-machine (get-default-client) name definition role-arn))
([^AWSStepFunctionsClient client name definition role-arn]
(->> (syms->map name
role-arn
definition)
mdl/map->CreateStateMachineRequest
(.createStateMachine client)
mdl/CreateStateMachineResult->map
::mdl/arn)))
(defn update-state-machine
([arn definition role-arn]
(update-state-machine (get-default-client) arn definition role-arn))
([^AWSStepFunctionsClient client arn definition role-arn]
(->> #::mdl {:arn arn
:definition-json (.toPrettyJson ^StateMachine
(mdl/map->StateMachine definition))
:role-arn role-arn}
mdl/map->UpdateStateMachineRequest
(.updateStateMachine client)
mdl/UpdateStateMachineResult->map)
arn))
(defn delete-activity
([arn] (delete-activity (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(.deleteActivity client (mdl/map->DeleteActivityRequest (syms->map arn)))
nil))
(defn delete-state-machine
([arn] (delete-state-machine (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(.deleteStateMachine client (mdl/map->DeleteStateMachineRequest (syms->map arn)))
nil))
(defn describe-activity
([arn] (describe-activity (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(->> (syms->map arn)
mdl/map->DescribeActivityRequest
(.describeActivity client)
mdl/DescribeActivityResult->map)))
(defn describe-execution
([arn] (describe-execution (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(->> (syms->map arn)
mdl/map->DescribeExecutionRequest
(.describeExecution client)
mdl/DescribeExecutionResult->map)))
(defn describe-state-machine
([arn] (describe-state-machine (get-default-client) arn))
([^AWSStepFunctionsClient client arn]
(->> (syms->map arn)
mdl/map->DescribeStateMachineRequest
(.describeStateMachine client)
mdl/DescribeStateMachineResult->map)))
(defn get-activity-task
([arn]
(get-activity-task arn nil))
([arn {:keys [worker-name] :as opts}]
(get-activity-task (get-default-client) arn opts))
([^AWSStepFunctionsClient client arn {:keys [worker-name]}]
(->> (syms->map arn worker-name)
mdl/map->GetActivityTaskRequest
(.getActivityTask client)
mdl/GetActivityTaskResult->map)))
(defn get-execution-history
([arn]
(get-execution-history arn nil))
([arn {:keys [max-results next-token reverse-order?] :as opts}]
(get-execution-history (get-default-client) arn opts))
([^AWSStepFunctionsClient client arn {:keys [max-results next-token reverse-order?]}]
(->> (syms->map arn max-results next-token reverse-order?)
mdl/map->GetExecutionHistoryRequest
(.getExecutionHistory client)
mdl/GetExecutionHistoryResult->map)))
(defn list-activities
([] (list-activities nil))
([{:keys [max-results next-token] :as opts}]
(list-activities (get-default-client) opts))
([^AWSStepFunctionsClient client {:keys [max-results next-token]}]
(->> (syms->map max-results next-token)
mdl/map->ListActivitiesRequest
(.listActivities client)
mdl/ListActivitiesResult->map)))
(defn list-executions
([state-machine-arn]
(list-executions state-machine-arn nil))
([state-machine-arn {:keys [status-filter next-token max-results] :as opts}]
(list-executions (get-default-client) state-machine-arn opts))
([^AWSStepFunctionsClient client state-machine-arn {:keys [status-filter next-token max-results]}]
(let [request-map (syms->map state-machine-arn status-filter next-token max-results)]
(->> (if (nil? (::mdl/status-filter request-map))
(dissoc request-map ::mdl/status-filter)
request-map)
mdl/map->ListExecutionsRequest
(.listExecutions client)
mdl/ListExecutionsResult->map))))
(defn list-state-machines
([] (list-state-machines nil))
([{:keys [max-results next-token] :as opts}]
(list-state-machines (get-default-client) opts))
([^AWSStepFunctionsClient client {:keys [max-results next-token]}]
(->> (syms->map max-results next-token)
mdl/map->ListStateMachinesRequest
(.listStateMachines client)
mdl/ListStateMachinesResult->map)))
(defn send-task-failure
([task-token]
(send-task-failure task-token nil))
([task-token {:keys [cause error] :as opts}]
(send-task-failure (get-default-client) task-token opts))
([^AWSStepFunctionsClient client task-token {:keys [cause error]}]
(->> (syms->map task-token cause error)
mdl/map->SendTaskFailureRequest
(.sendTaskFailure client))
nil))
(defn send-task-success
([task-token output]
(send-task-success (get-default-client) task-token output))
([^AWSStepFunctionsClient client task-token output]
(->> (syms->map task-token output)
mdl/map->SendTaskSuccessRequest
(.sendTaskSuccess client))
nil))
(defn send-task-heartbeat
([task-token]
(send-task-heartbeat (get-default-client) task-token))
([^AWSStepFunctionsClient client task-token]
(->> (syms->map task-token)
mdl/map->SendTaskHeartbeatRequest
(.sendTaskHeartbeat client))
nil))
(defn start-execution
([state-machine-arn]
(start-execution state-machine-arn nil))
([state-machine-arn {:keys [input name] :as opts}]
(start-execution (get-default-client) state-machine-arn opts))
([^AWSStepFunctionsClient client state-machine-arn {:keys [input name]}]
(->> (syms->map state-machine-arn input name)
mdl/map->StartExecutionRequest
(.startExecution client)
mdl/StartExecutionResult->map
::mdl/arn)))
(defn stop-execution
([arn]
(stop-execution arn nil))
([arn {:keys [cause error] :as opts}]
(stop-execution (get-default-client) arn opts))
([^AWSStepFunctionsClient client arn {:keys [cause error]}]
(->> (syms->map arn cause error)
mdl/map->StopExecutionRequest
(.stopExecution client))
nil))
(defn auto-page' [client-fn items-key base-args xform]
(let [items-chan (async/chan 1 xform)
[base-pos-args base-map-args] (if (map? (last base-args))
[(pop base-args) (last base-args)]
[base-args {}])
get-page (fn [token]
(let [map-args (assoc base-map-args :next-token token)
args (conj base-pos-args map-args)]
(apply client-fn args)))]
(async/go
(try (loop [page (get-page nil)]
(async/<! (async/onto-chan items-chan
(get page items-key)
false))
(when-let [next-token (::mdl/next-token page)]
(recur (get-page next-token))))
(catch Throwable e
(async/>! items-chan e)))
(async/close! items-chan))
items-chan))
(def request-fn->items-key
{#'get-execution-history ::mdl/events
#'list-activities ::mdl/activities
#'list-executions ::mdl/executions
#'list-state-machines ::mdl/state-machines})
(defmacro auto-page [request-form & [xform]]
(let [request-fn-sym (first request-form)
request-fn-var (resolve request-fn-sym)
items-key (request-fn->items-key request-fn-var)]
(when-not items-key
(throw (ex-info "Function called is not paginating"
{:request-fn request-fn-var})))
`(auto-page' ~request-fn-sym
~items-key
~(vec (rest request-form))
~xform)))
| |
28945efe74d14f2d541268b127e05219be68b501936f9cda2f98bfe930755d46 | mransan/ocaml-protoc | pb_codegen_ocaml_type.ml |
The MIT License ( MIT )
Copyright ( c ) 2016 < >
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
The MIT License (MIT)
Copyright (c) 2016 Maxime Ransan <>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*)
(** OCaml type representation *)
module Pt = Pb_parsing_parse_tree
type payload_kind =
| Pk_varint of bool (** zigzag *)
| Pk_bits32
| Pk_bits64
| Pk_bytes
type user_defined_type = {
since code generated is split in multiple file ( type , binary , json , .. )
this defines the prefix for the given type , the suffix will
be defined by each generator
this defines the prefix for the given type, the suffix will
be defined by each generator *)
udt_module_prefix: string option;
(* OCaml type name ie not the type name in proto file *)
udt_type_name: string;
(* Need to keep track of this since encoding logic in binary
format is quite different *)
udt_type: [ `Message | `Enum ];
}
type basic_type =
| Bt_string
| Bt_float
| Bt_int
| Bt_int32
| Bt_uint32
| Bt_int64
| Bt_uint64
| Bt_bytes
| Bt_bool
type wrapper_type = {
wt_type: basic_type; (* basic type being wrapped *)
wt_pk: payload_kind; (* encoding used for the basic type *)
}
type field_type =
| Ft_unit
| Ft_basic_type of basic_type
| Ft_user_defined_type of user_defined_type
(* New wrapper type which indicates that the corresponding ocaml
Type should be an `option` along with the fact that it is encoded with
special rules *)
| Ft_wrapper_type of wrapper_type
type default_value = Pb_option.constant option
type associative_type =
| At_list
| At_hashtable
(* Future work can include the following OCaml associative containers
| Al_map *)
type repeated_type =
| Rt_list
| Rt_repeated_field
type encoding_number = int
type is_packed = bool
type record_field_type =
| Rft_nolabel of (field_type * encoding_number * payload_kind)
no default values in no label fields
| Rft_required of
(field_type * encoding_number * payload_kind * default_value)
| Rft_optional of
(field_type * encoding_number * payload_kind * default_value)
| Rft_repeated of
(repeated_type * field_type * encoding_number * payload_kind * is_packed)
| Rft_associative of
(associative_type
* encoding_number
* (basic_type * payload_kind)
* (field_type * payload_kind))
| Rft_variant of variant
and variant_constructor = {
vc_constructor: string;
vc_field_type: variant_constructor_type;
vc_encoding_number: encoding_number;
vc_payload_kind: payload_kind;
}
and variant_constructor_type =
| Vct_nullary
| Vct_non_nullary_constructor of field_type
and variant = {
v_name: string;
v_constructors: variant_constructor list;
}
and record_field = {
rf_label: string;
rf_field_type: record_field_type;
rf_mutable: bool;
}
and record = {
r_name: string;
r_fields: record_field list;
}
and const_variant_constructor = {
cvc_name: string;
cvc_binary_value: int;
cvc_string_value: string;
}
and const_variant = {
cv_name: string;
cv_constructors: const_variant_constructor list;
}
and type_spec =
| Record of record
| Variant of variant
| Const_variant of const_variant
type type_ = {
module_prefix: string;
(** code generation leads to several file/module being generated for
a given [type_]. [module_prefix] is the common prefix for all those
generated module and it is based on the `.proto` filename. *)
spec: type_spec;
type_level_ppx_extension: string option;
}
| null | https://raw.githubusercontent.com/mransan/ocaml-protoc/e43b509b9c4a06e419edba92a0d3f8e26b0a89ba/src/compilerlib/pb_codegen_ocaml_type.ml | ocaml | * OCaml type representation
* zigzag
OCaml type name ie not the type name in proto file
Need to keep track of this since encoding logic in binary
format is quite different
basic type being wrapped
encoding used for the basic type
New wrapper type which indicates that the corresponding ocaml
Type should be an `option` along with the fact that it is encoded with
special rules
Future work can include the following OCaml associative containers
| Al_map
* code generation leads to several file/module being generated for
a given [type_]. [module_prefix] is the common prefix for all those
generated module and it is based on the `.proto` filename. |
The MIT License ( MIT )
Copyright ( c ) 2016 < >
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
The MIT License (MIT)
Copyright (c) 2016 Maxime Ransan <>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*)
module Pt = Pb_parsing_parse_tree
type payload_kind =
| Pk_bits32
| Pk_bits64
| Pk_bytes
type user_defined_type = {
since code generated is split in multiple file ( type , binary , json , .. )
this defines the prefix for the given type , the suffix will
be defined by each generator
this defines the prefix for the given type, the suffix will
be defined by each generator *)
udt_module_prefix: string option;
udt_type_name: string;
udt_type: [ `Message | `Enum ];
}
type basic_type =
| Bt_string
| Bt_float
| Bt_int
| Bt_int32
| Bt_uint32
| Bt_int64
| Bt_uint64
| Bt_bytes
| Bt_bool
type wrapper_type = {
}
type field_type =
| Ft_unit
| Ft_basic_type of basic_type
| Ft_user_defined_type of user_defined_type
| Ft_wrapper_type of wrapper_type
type default_value = Pb_option.constant option
type associative_type =
| At_list
| At_hashtable
type repeated_type =
| Rt_list
| Rt_repeated_field
type encoding_number = int
type is_packed = bool
type record_field_type =
| Rft_nolabel of (field_type * encoding_number * payload_kind)
no default values in no label fields
| Rft_required of
(field_type * encoding_number * payload_kind * default_value)
| Rft_optional of
(field_type * encoding_number * payload_kind * default_value)
| Rft_repeated of
(repeated_type * field_type * encoding_number * payload_kind * is_packed)
| Rft_associative of
(associative_type
* encoding_number
* (basic_type * payload_kind)
* (field_type * payload_kind))
| Rft_variant of variant
and variant_constructor = {
vc_constructor: string;
vc_field_type: variant_constructor_type;
vc_encoding_number: encoding_number;
vc_payload_kind: payload_kind;
}
and variant_constructor_type =
| Vct_nullary
| Vct_non_nullary_constructor of field_type
and variant = {
v_name: string;
v_constructors: variant_constructor list;
}
and record_field = {
rf_label: string;
rf_field_type: record_field_type;
rf_mutable: bool;
}
and record = {
r_name: string;
r_fields: record_field list;
}
and const_variant_constructor = {
cvc_name: string;
cvc_binary_value: int;
cvc_string_value: string;
}
and const_variant = {
cv_name: string;
cv_constructors: const_variant_constructor list;
}
and type_spec =
| Record of record
| Variant of variant
| Const_variant of const_variant
type type_ = {
module_prefix: string;
spec: type_spec;
type_level_ppx_extension: string option;
}
|
1ae0e3e07a872f0639b3a0fd5b2d3b4fe60e183eccb3bb85037f8fd85aa3d351 | input-output-hk/plutus-apps | DatumRedeemerGuess.hs | # LANGUAGE DataKinds #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
module PlutusExample.PlutusVersion1.DatumRedeemerGuess
( guessScript
, guessScriptStake
, datumRedeemerGuessScriptShortBs
) where
import Prelude hiding (($), (&&), (==))
import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1)
import Codec.Serialise
import Data.ByteString.Lazy qualified as LBS
import Data.ByteString.Short qualified as SBS
import Plutus.V1.Ledger.Api qualified as Plutus
import PlutusTx (toBuiltinData)
import PlutusTx qualified
import PlutusTx.Prelude hiding (Semigroup (..), unless, (.))
# INLINABLE mkValidator #
mkValidator :: BuiltinData -> BuiltinData -> BuiltinData -> ()
mkValidator datum redeemer _txContext
| datum == toBuiltinData (42 :: Integer)
&& redeemer == toBuiltinData (42 :: Integer) = ()
| otherwise = traceError "Incorrect datum. Expected 42."
validator :: Plutus.Validator
validator = Plutus.mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||])
script :: Plutus.Script
script = Plutus.unValidatorScript validator
datumRedeemerGuessScriptShortBs :: SBS.ShortByteString
datumRedeemerGuessScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script
guessScript :: PlutusScript PlutusScriptV1
guessScript = PlutusScriptSerialised datumRedeemerGuessScriptShortBs
{-# INLINEABLE mkValidatorStake #-}
mkValidatorStake :: BuiltinData -> BuiltinData -> ()
mkValidatorStake redeemer _txContext
| redeemer == toBuiltinData (42 :: Integer) = ()
| otherwise = traceError "Incorrect datum. Expected 42."
validatorStake :: Plutus.StakeValidator
validatorStake = Plutus.mkStakeValidatorScript $$(PlutusTx.compile [||mkValidatorStake||])
scriptStake :: Plutus.Script
scriptStake = Plutus.unStakeValidatorScript validatorStake
datumRedeemerGuessScriptStakeShortBs :: SBS.ShortByteString
datumRedeemerGuessScriptStakeShortBs = SBS.toShort . LBS.toStrict $ serialise scriptStake
guessScriptStake :: PlutusScript PlutusScriptV1
guessScriptStake = PlutusScriptSerialised datumRedeemerGuessScriptStakeShortBs
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/c1269a7ab8806957cda93448a4637c485352cda5/plutus-example/src/PlutusExample/PlutusVersion1/DatumRedeemerGuess.hs | haskell | # LANGUAGE TypeFamilies #
# INLINEABLE mkValidatorStake # | # LANGUAGE DataKinds #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module PlutusExample.PlutusVersion1.DatumRedeemerGuess
( guessScript
, guessScriptStake
, datumRedeemerGuessScriptShortBs
) where
import Prelude hiding (($), (&&), (==))
import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1)
import Codec.Serialise
import Data.ByteString.Lazy qualified as LBS
import Data.ByteString.Short qualified as SBS
import Plutus.V1.Ledger.Api qualified as Plutus
import PlutusTx (toBuiltinData)
import PlutusTx qualified
import PlutusTx.Prelude hiding (Semigroup (..), unless, (.))
# INLINABLE mkValidator #
mkValidator :: BuiltinData -> BuiltinData -> BuiltinData -> ()
mkValidator datum redeemer _txContext
| datum == toBuiltinData (42 :: Integer)
&& redeemer == toBuiltinData (42 :: Integer) = ()
| otherwise = traceError "Incorrect datum. Expected 42."
validator :: Plutus.Validator
validator = Plutus.mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||])
script :: Plutus.Script
script = Plutus.unValidatorScript validator
datumRedeemerGuessScriptShortBs :: SBS.ShortByteString
datumRedeemerGuessScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script
guessScript :: PlutusScript PlutusScriptV1
guessScript = PlutusScriptSerialised datumRedeemerGuessScriptShortBs
mkValidatorStake :: BuiltinData -> BuiltinData -> ()
mkValidatorStake redeemer _txContext
| redeemer == toBuiltinData (42 :: Integer) = ()
| otherwise = traceError "Incorrect datum. Expected 42."
validatorStake :: Plutus.StakeValidator
validatorStake = Plutus.mkStakeValidatorScript $$(PlutusTx.compile [||mkValidatorStake||])
scriptStake :: Plutus.Script
scriptStake = Plutus.unStakeValidatorScript validatorStake
datumRedeemerGuessScriptStakeShortBs :: SBS.ShortByteString
datumRedeemerGuessScriptStakeShortBs = SBS.toShort . LBS.toStrict $ serialise scriptStake
guessScriptStake :: PlutusScript PlutusScriptV1
guessScriptStake = PlutusScriptSerialised datumRedeemerGuessScriptStakeShortBs
|
d0be8693907f1d199fff695cf3f88d842620330e0dfab718cb818bf7e195dcae | thehandsomepanther/system-f | check.mli | (*
* Type checking
*)
open Syntax
(* Thrown on type errors. *)
exception Type_error of string
(* Returns the type of an expression or throws Type_error. *)
val tc_infer : int * typ Env.t -> exp -> typ
val tc_check : int * typ Env.t -> exp -> typ -> unit
| null | https://raw.githubusercontent.com/thehandsomepanther/system-f/90bb8ac121a7f731c198134b326cb1dd6a61b233/check.mli | ocaml |
* Type checking
Thrown on type errors.
Returns the type of an expression or throws Type_error. |
open Syntax
exception Type_error of string
val tc_infer : int * typ Env.t -> exp -> typ
val tc_check : int * typ Env.t -> exp -> typ -> unit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.