_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
|
---|---|---|---|---|---|---|---|---|
f8d42f303a1836a4a664c1d93a7a02f28d6daf577faab08a0b4dd17b90e02e83 | simplex-chat/simplex-chat | WebRTC.hs | # LANGUAGE FlexibleContexts #
module Simplex.Chat.Mobile.WebRTC (
cChatEncryptMedia,
cChatDecryptMedia,
chatEncryptMedia,
chatDecryptMedia,
reservedSize,
) where
import Control.Monad.Except
import qualified Crypto.Cipher.Types as AES
import Data.Bifunctor (bimap)
import qualified Data.ByteArray as BA
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64.URL as U
import Data.ByteString.Internal (ByteString (PS), memcpy)
import Data.Either (fromLeft)
import Data.Word (Word8)
import Foreign.C (CInt, CString, newCAString)
import Foreign.ForeignPtr (newForeignPtr_)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import Foreign.Ptr (Ptr, plusPtr)
import qualified Simplex.Messaging.Crypto as C
cChatEncryptMedia :: CString -> Ptr Word8 -> CInt -> IO CString
cChatEncryptMedia = cTransformMedia chatEncryptMedia
cChatDecryptMedia :: CString -> Ptr Word8 -> CInt -> IO CString
cChatDecryptMedia = cTransformMedia chatDecryptMedia
cTransformMedia :: (ByteString -> ByteString -> ExceptT String IO ByteString) -> CString -> Ptr Word8 -> CInt -> IO CString
cTransformMedia f cKey cFrame cFrameLen = do
key <- B.packCString cKey
frame <- getFrame
runExceptT (f key frame >>= liftIO . putFrame) >>= newCAString . fromLeft ""
where
getFrame = do
fp <- newForeignPtr_ cFrame
pure $ PS fp 0 $ fromIntegral cFrameLen
putFrame bs@(PS fp offset _) = do
let len = B.length bs
p = unsafeForeignPtrToPtr fp `plusPtr` offset
when (len <= fromIntegral cFrameLen) $ memcpy cFrame p len
# INLINE cTransformMedia #
chatEncryptMedia :: ByteString -> ByteString -> ExceptT String IO ByteString
chatEncryptMedia keyStr frame = do
len <- checkFrameLen frame
key <- decodeKey keyStr
iv <- liftIO C.randomGCMIV
(tag, frame') <- withExceptT show $ C.encryptAESNoPad key iv $ B.take len frame
pure $ frame' <> BA.convert (C.unAuthTag tag) <> C.unGCMIV iv
chatDecryptMedia :: ByteString -> ByteString -> ExceptT String IO ByteString
chatDecryptMedia keyStr frame = do
len <- checkFrameLen frame
key <- decodeKey keyStr
let (frame', rest) = B.splitAt len frame
(tag, iv) = B.splitAt C.authTagSize rest
authTag = C.AuthTag $ AES.AuthTag $ BA.convert tag
withExceptT show $ do
iv' <- liftEither $ C.gcmIV iv
frame'' <- C.decryptAESNoPad key iv' frame' authTag
pure $ frame'' <> framePad
checkFrameLen :: ByteString -> ExceptT String IO Int
checkFrameLen frame = do
let len = B.length frame - reservedSize
when (len < 0) $ throwError "frame has no [reserved space for] IV and/or auth tag"
pure len
# INLINE checkFrameLen #
decodeKey :: ByteString -> ExceptT String IO C.Key
decodeKey = liftEither . bimap ("invalid key: " <>) C.Key . U.decode
# INLINE decodeKey #
reservedSize :: Int
reservedSize = C.authTagSize + C.gcmIVSize
framePad :: ByteString
framePad = B.replicate reservedSize 0
| null | https://raw.githubusercontent.com/simplex-chat/simplex-chat/01acbb970ae7762e1551e352131453e77a601764/src/Simplex/Chat/Mobile/WebRTC.hs | haskell | # LANGUAGE FlexibleContexts #
module Simplex.Chat.Mobile.WebRTC (
cChatEncryptMedia,
cChatDecryptMedia,
chatEncryptMedia,
chatDecryptMedia,
reservedSize,
) where
import Control.Monad.Except
import qualified Crypto.Cipher.Types as AES
import Data.Bifunctor (bimap)
import qualified Data.ByteArray as BA
import qualified Data.ByteString as B
import qualified Data.ByteString.Base64.URL as U
import Data.ByteString.Internal (ByteString (PS), memcpy)
import Data.Either (fromLeft)
import Data.Word (Word8)
import Foreign.C (CInt, CString, newCAString)
import Foreign.ForeignPtr (newForeignPtr_)
import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)
import Foreign.Ptr (Ptr, plusPtr)
import qualified Simplex.Messaging.Crypto as C
cChatEncryptMedia :: CString -> Ptr Word8 -> CInt -> IO CString
cChatEncryptMedia = cTransformMedia chatEncryptMedia
cChatDecryptMedia :: CString -> Ptr Word8 -> CInt -> IO CString
cChatDecryptMedia = cTransformMedia chatDecryptMedia
cTransformMedia :: (ByteString -> ByteString -> ExceptT String IO ByteString) -> CString -> Ptr Word8 -> CInt -> IO CString
cTransformMedia f cKey cFrame cFrameLen = do
key <- B.packCString cKey
frame <- getFrame
runExceptT (f key frame >>= liftIO . putFrame) >>= newCAString . fromLeft ""
where
getFrame = do
fp <- newForeignPtr_ cFrame
pure $ PS fp 0 $ fromIntegral cFrameLen
putFrame bs@(PS fp offset _) = do
let len = B.length bs
p = unsafeForeignPtrToPtr fp `plusPtr` offset
when (len <= fromIntegral cFrameLen) $ memcpy cFrame p len
# INLINE cTransformMedia #
chatEncryptMedia :: ByteString -> ByteString -> ExceptT String IO ByteString
chatEncryptMedia keyStr frame = do
len <- checkFrameLen frame
key <- decodeKey keyStr
iv <- liftIO C.randomGCMIV
(tag, frame') <- withExceptT show $ C.encryptAESNoPad key iv $ B.take len frame
pure $ frame' <> BA.convert (C.unAuthTag tag) <> C.unGCMIV iv
chatDecryptMedia :: ByteString -> ByteString -> ExceptT String IO ByteString
chatDecryptMedia keyStr frame = do
len <- checkFrameLen frame
key <- decodeKey keyStr
let (frame', rest) = B.splitAt len frame
(tag, iv) = B.splitAt C.authTagSize rest
authTag = C.AuthTag $ AES.AuthTag $ BA.convert tag
withExceptT show $ do
iv' <- liftEither $ C.gcmIV iv
frame'' <- C.decryptAESNoPad key iv' frame' authTag
pure $ frame'' <> framePad
checkFrameLen :: ByteString -> ExceptT String IO Int
checkFrameLen frame = do
let len = B.length frame - reservedSize
when (len < 0) $ throwError "frame has no [reserved space for] IV and/or auth tag"
pure len
# INLINE checkFrameLen #
decodeKey :: ByteString -> ExceptT String IO C.Key
decodeKey = liftEither . bimap ("invalid key: " <>) C.Key . U.decode
# INLINE decodeKey #
reservedSize :: Int
reservedSize = C.authTagSize + C.gcmIVSize
framePad :: ByteString
framePad = B.replicate reservedSize 0
|
|
bd010b48a44f6b3803baeaa44787cd8c59585c439a5d3023599a9660a798e386 | danielecapo/sfont | math.rkt | #lang racket
(require "interpolables.rkt"
"info-kern-math.rkt"
"../../main.rkt"
"../../geometry.rkt"
"../../properties.rkt"
"../../utilities.rkt"
(for-syntax racket/syntax))
(provide (except-out (all-from-out racket) + - * /)
(contract-out
[fontmath-object/c (-> any/c boolean?)]
[font-intp-object/c (-> any/c boolean?)]
[get-interpolable-fonts (->* () () #:rest (listof font?) (listof font?))]
[rename prod * (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[rename add + (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[rename sub - (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[rename div / (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[x-> (-> geometric? geometric?)]
[y-> (-> geometric? geometric?)]
[fix-components (-> font? font? font?)])
define-interpolable-fonts
define-space
use-only-glyphs)
(define fontmath-object/c
(flat-named-contract
'fontmath-object/c
(or/c vec? real? font? glyph? bezier/c)))
(define font-intp-object/c
(flat-named-contract
'font-object/c
(or/c vec? font? glyph? layer? contour? anchor? component? fontinfo/c kerning/c)))
(define mathfilter
(make-parameter #f))
(define-syntax use-only-glyphs
(syntax-rules ()
[(_ gs . body)
(parameterize [(mathfilter gs)] . body)]))
Font ( Symbol ) - > Font
(define (only-glyphs-in gl f)
(struct-copy font f
[glyphs (filter-glyphs
(lambda (g)
(member (glyph-name g) gl))
f)]))
; [layers (map-layers
; (lambda (l)
; (struct-copy layer l
; [glyphs (filter-glyphs
; (lambda (g)
( member ( glyph - name ) gl ) )
; l)]))
; f)]))
; Symbol Font -> (listof Symbol)
(define (component-deps g f)
(let ([cs (map component-base (layer-components (get-layer (get-glyph f g) foreground)))])
(append* cs (map (lambda (g) (component-deps g f)) cs))))
; Font -> Font
(define (reduced-font f)
(let ([ls (if (mathfilter)
(remove-duplicates
(apply append (mathfilter)
(map (lambda (g) (component-deps g f)) (mathfilter))))
#f)])
(if ls (only-glyphs-in ls f) f)))
; Point ... -> Point
(define (point+ p1 . ps)
(letrec ([p+ (lambda (p1 p2)
(struct-copy point p1
[pos (vec+ (point-pos p1) (point-pos p2))]))])
(foldl p+ p1 ps)))
; Contour ... -> Contour
(define (contour+ c1 . cs)
(struct-copy contour c1
[points (apply map
(lambda (p1 . ps)
(foldl point+ p1 ps))
(contour-points c1)
(map contour-points cs))]))
; Component ... -> Component
(define (component+ c1 . cs)
(struct-copy component c1
[matrix (foldl (lambda (cc1 cc2)
(match cc1
[(trans-mat x xy yx y xo yo)
(match cc2
[(trans-mat x2 xy2 yx2 y2 xo2 yo2)
(trans-mat (+ x x2) (+ xy xy2) (+ yx yx2) (+ y y2) (+ xo xo2) (+ yo yo2))])]))
(get-matrix c1)
(map get-matrix cs))]))
; Anchor ... -> Anchor
(define (anchor+ a1 . as)
(struct-copy anchor a1
[pos (foldl vec+ (get-position a1)
(map get-position as))]))
; Advance ... -> Advance
(define (advance+ a1 . as)
(struct-copy advance a1
[width (foldl + (advance-width a1) (map advance-width as))]
[height (foldl + (advance-height a1) (map advance-height as))]))
; Layer ... -> Layer
(define (layer+ l1 . ls)
(let [(lss (cons l1 ls))]
(struct-copy layer l1
[contours
(apply map contour+ (map layer-contours lss))]
[components
(apply map component+ (map layer-components lss))]
[anchors
(apply map anchor+ (map layer-anchors lss))])))
; Glyph ... -> Glyph
(define (glyph+ g1 . gs)
(let [(gss (cons g1 gs))]
(struct-copy glyph g1
[advance (apply advance+ (map glyph-advance gss))]
[layers
(list (apply layer+ (map (curryr get-layer foreground) gss)))])))
; Font Real Real -> Any
(define (font-scale* o fx [fy fx])
(let ([o1 (scale o fx fy)])
(struct-copy font o1
[fontinfo (info-scale (font-fontinfo o1) fx fy)]
[kerning (kerning-scale (font-kerning o1) fx)])))
; Font ... -> Font
(define (font+ f1 . fs)
(if (null? fs)
f1
(let ([f+ (lambda (f1 f2)
(struct-copy font f1
[fontinfo (info+ (font-fontinfo f1) (font-fontinfo f2))]
[kerning (kerning+ (font-kerning f1) (font-kerning f2))]
[glyphs (map glyph+ (font-glyphs-list f1)
(font-glyphs-list f2))]))]
[fonts (map reduced-font (cons f1 fs))])
(foldl f+ (car fonts) (cdr fonts)))))
; Font Real ... -> Font
(define (font* f s1 . ss)
(let ([s (apply * (cons s1 ss))])
(if (= 1 s) f
(font-scale* (reduced-font f) s))))
FontObject Real ... - > FontObject
(define (font:* o s1 . ss)
((match o
[(? font? _) font*]
[(? glyph? _) scale]
[(? layer? _) scale]
[(? contour? _) scale]
[(? anchor? _ ) scale]
[(? component? _) scale]
[_ (error "Error: wrong type for font:*")])
o
(apply * (cons s1 ss))))
FontObject ... - > FontObject
(define (font:+ o1 . os)
(apply (match o1
[(? font? _) font+]
[(? glyph? _) glyph+]
[(? layer? _) layer+]
[(? contour? _) contour+]
[(? anchor? _ ) anchor+]
[(? component? _) component+]
[_ (error "Error: wrong type for font:+")])
(cons o1 os)))
FontObject ... - > FontObject
(define (font:- o1 . os)
(font:+ o1 (font:* (apply font:+ os) -1)))
FontObject Real ... - > FontObject
(define (font:/ o s1 . ss)
(font:* o (apply * (map (lambda (s)
(/ 1 s))
(cons s1 ss)))))
; FontMathObject ... -> FontMathObject
(define (add a . as)
(match (cons a as)
[(list (? font? _) ...)
(apply font:+ a as)]
[(list (? glyph? _) ...)
(apply font:+ a as)]
[(list (? layer? _) ...)
(apply font:+ a as)]
[(list (? real? _) ...)
(apply + a as)]
[(list (? vec? _) ...)
(foldl vec+ a as)]
[(list (? bezier/c _) ...)
(foldl (lambda (a b) (map vec+ a b)) a as)]
[_ (error "Invalid operands for product for addition")]))
; FontMathObject -> FontMathObject
(define (sub a . as)
(match (cons a as)
[(list (? font? _) ...)
(apply font:+ a (map (lambda (i) (prod i -1)) as))]
[(list (? glyph? _) ...)
(apply font:+ a (map (lambda (i) (prod i -1)) as))]
[(list (? layer? _) ...)
(apply font:+ a (map (lambda (i) (prod i -1)) as))]
[(list (? real? _) ...)
(apply - a as)]
[(list (? vec? _) ...)
(foldl vec- a as)]
[(list (? bezier/c _) ...)
(foldl (lambda (a b) (map vec- a b)) a as)]
[_ (error "Invalid operands for product for addition")]))
; FontMathObject ... -> FontMathObject
(define (prod a . as)
(match (cons a as)
[(list-no-order (? font? f) (? real? s) ...)
(apply font:* f s)]
[(list-no-order (? glyph? f) (? real? s) ...)
(apply font:* f s)]
[(list-no-order (? layer? f) (? real? s) ...)
(apply font:* f s)]
[(list-no-order (? vec? v) (? real? s) ...)
(vec* v (apply * s))]
[(list-no-order (? bezier/c b) (? real? s) ...)
(let ([f (apply * s)])
(map (lambda (v) (vec* v f)) b ))]
[(list (? real? x) ...)
(apply * x)]
[(list (? vec? v) ...)
(foldl (lambda (v1 v2)
(let* ([c1 (make-rectangular (vec-x v1) (vec-y v1))]
[c2 (make-rectangular (vec-x v2) (vec-y v2))]
[c (* c1 c2)])
(vec (real-part c) (imag-part c))))
a as)]
[(list (? bezier/c b) ...)
(foldl (lambda (b1 b2) (map prod b1 b2)) a as)]
[_ (error "Invalid operands for product")]))
; FontMathObject Real ... -> FontMathObject
(define (div a . as)
(match (cons a as)
[(list (? font? f) (? real? s) ...)
(apply font:* f (map (lambda (n) (/ 1.0 n)) s))]
[(list (? glyph? f) (? real? s) ...)
(apply font:* f (map (lambda (n) (/ 1.0 n)) s))]
[(list (? layer? f) (? real? s) ...)
(apply font:* f (map (lambda (n) (/ 1.0 n)) s))]
[(list (? vec? v) (? real? s) ...)
(vec* v (apply * (map (lambda (n) (/ 1.0 n)) s)))]
[(list (? bezier/c b) (? real? s) ...)
(let ([f (apply * (map (lambda (n) (/ 1.0 n)) s))])
(map (lambda (v) (vec* v f)) b ))]
[(list (? real? x) ...)
(apply / x)]
[_ (error "Invalid operands for product")]))
;; PROJECTIONS
; Geometric -> Geometric
project the object on the x axis ( set every y coord . to zero )
(define (x-> o)
((if (font? o) font-scale* scale) o 1 0))
; Geometric -> Geometric
project the object on the y axis ( set every x coord . to zero )
(define (y-> o)
((if (font? o) font-scale* scale) o 0 1))
Font ... - > ( )
(define (interpolables f . fs)
(let ([f0 (foldl (lambda (f acc)
(let-values ([(a b) (interpolable-fonts acc f #f #t)])
a))
f fs)])
(cons f0 (map (lambda (f)
(let-values ([(a b) (interpolable-fonts f f0 #f #t)])
(match-fonts-contours f0 a)))
fs))))
; Font ... -> Font ...
(define (get-interpolable-fonts . fs)
(apply interpolables
(map (lambda (f)
(prepare-font f #f #t))
fs)))
; Font, Font -> Font
; Produce a new font with components scale fields imported from f2
(define (fix-components f1 f2)
(struct-copy font f1
[glyphs
(map
(lambda (g1 g2)
(struct-copy glyph g1
[layers
(list
(struct-copy layer (get-layer g1 foreground)
[components (map import-component-scale
(layer-components (get-layer g1 foreground))
(layer-components (get-layer g2 foreground)))]))]))
(font-glyphs-list f1)
(font-glyphs-list f2))]))
(define-syntax-rule (define-interpolable-fonts (id f) ...)
(define-values (id ...)
(apply values (interpolables f ...))))
(define-syntax (define-space stx)
(syntax-case stx ()
[(define-space id (origin [font ...]))
(for-each (lambda (i)
(unless (identifier? i)
(raise-syntax-error #f "Not an identifier" stx i)))
(append (list #'id #'origin) (syntax->list #'(font ...))))
(with-syntax ([(fname ...)
(map (lambda (f)
(format-id stx "~a-~a" #'id f))
(syntax->list #'(font ...)))])
#'(begin
(define (id f . fs)
(apply values (map (lambda (f) (add origin f)) (cons f fs))))
(define fname (sub font origin)) ...))]))
| null | https://raw.githubusercontent.com/danielecapo/sfont/c854f9734f15f4c7cd4b98e041b8c961faa3eef2/sfont/private/fontmath/math.rkt | racket | [layers (map-layers
(lambda (l)
(struct-copy layer l
[glyphs (filter-glyphs
(lambda (g)
l)]))
f)]))
Symbol Font -> (listof Symbol)
Font -> Font
Point ... -> Point
Contour ... -> Contour
Component ... -> Component
Anchor ... -> Anchor
Advance ... -> Advance
Layer ... -> Layer
Glyph ... -> Glyph
Font Real Real -> Any
Font ... -> Font
Font Real ... -> Font
FontMathObject ... -> FontMathObject
FontMathObject -> FontMathObject
FontMathObject ... -> FontMathObject
FontMathObject Real ... -> FontMathObject
PROJECTIONS
Geometric -> Geometric
Geometric -> Geometric
Font ... -> Font ...
Font, Font -> Font
Produce a new font with components scale fields imported from f2 | #lang racket
(require "interpolables.rkt"
"info-kern-math.rkt"
"../../main.rkt"
"../../geometry.rkt"
"../../properties.rkt"
"../../utilities.rkt"
(for-syntax racket/syntax))
(provide (except-out (all-from-out racket) + - * /)
(contract-out
[fontmath-object/c (-> any/c boolean?)]
[font-intp-object/c (-> any/c boolean?)]
[get-interpolable-fonts (->* () () #:rest (listof font?) (listof font?))]
[rename prod * (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[rename add + (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[rename sub - (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[rename div / (->* (fontmath-object/c) () #:rest (listof fontmath-object/c) fontmath-object/c)]
[x-> (-> geometric? geometric?)]
[y-> (-> geometric? geometric?)]
[fix-components (-> font? font? font?)])
define-interpolable-fonts
define-space
use-only-glyphs)
(define fontmath-object/c
(flat-named-contract
'fontmath-object/c
(or/c vec? real? font? glyph? bezier/c)))
(define font-intp-object/c
(flat-named-contract
'font-object/c
(or/c vec? font? glyph? layer? contour? anchor? component? fontinfo/c kerning/c)))
(define mathfilter
(make-parameter #f))
(define-syntax use-only-glyphs
(syntax-rules ()
[(_ gs . body)
(parameterize [(mathfilter gs)] . body)]))
Font ( Symbol ) - > Font
(define (only-glyphs-in gl f)
(struct-copy font f
[glyphs (filter-glyphs
(lambda (g)
(member (glyph-name g) gl))
f)]))
( member ( glyph - name ) gl ) )
(define (component-deps g f)
(let ([cs (map component-base (layer-components (get-layer (get-glyph f g) foreground)))])
(append* cs (map (lambda (g) (component-deps g f)) cs))))
(define (reduced-font f)
(let ([ls (if (mathfilter)
(remove-duplicates
(apply append (mathfilter)
(map (lambda (g) (component-deps g f)) (mathfilter))))
#f)])
(if ls (only-glyphs-in ls f) f)))
(define (point+ p1 . ps)
(letrec ([p+ (lambda (p1 p2)
(struct-copy point p1
[pos (vec+ (point-pos p1) (point-pos p2))]))])
(foldl p+ p1 ps)))
(define (contour+ c1 . cs)
(struct-copy contour c1
[points (apply map
(lambda (p1 . ps)
(foldl point+ p1 ps))
(contour-points c1)
(map contour-points cs))]))
(define (component+ c1 . cs)
(struct-copy component c1
[matrix (foldl (lambda (cc1 cc2)
(match cc1
[(trans-mat x xy yx y xo yo)
(match cc2
[(trans-mat x2 xy2 yx2 y2 xo2 yo2)
(trans-mat (+ x x2) (+ xy xy2) (+ yx yx2) (+ y y2) (+ xo xo2) (+ yo yo2))])]))
(get-matrix c1)
(map get-matrix cs))]))
(define (anchor+ a1 . as)
(struct-copy anchor a1
[pos (foldl vec+ (get-position a1)
(map get-position as))]))
(define (advance+ a1 . as)
(struct-copy advance a1
[width (foldl + (advance-width a1) (map advance-width as))]
[height (foldl + (advance-height a1) (map advance-height as))]))
(define (layer+ l1 . ls)
(let [(lss (cons l1 ls))]
(struct-copy layer l1
[contours
(apply map contour+ (map layer-contours lss))]
[components
(apply map component+ (map layer-components lss))]
[anchors
(apply map anchor+ (map layer-anchors lss))])))
(define (glyph+ g1 . gs)
(let [(gss (cons g1 gs))]
(struct-copy glyph g1
[advance (apply advance+ (map glyph-advance gss))]
[layers
(list (apply layer+ (map (curryr get-layer foreground) gss)))])))
(define (font-scale* o fx [fy fx])
(let ([o1 (scale o fx fy)])
(struct-copy font o1
[fontinfo (info-scale (font-fontinfo o1) fx fy)]
[kerning (kerning-scale (font-kerning o1) fx)])))
(define (font+ f1 . fs)
(if (null? fs)
f1
(let ([f+ (lambda (f1 f2)
(struct-copy font f1
[fontinfo (info+ (font-fontinfo f1) (font-fontinfo f2))]
[kerning (kerning+ (font-kerning f1) (font-kerning f2))]
[glyphs (map glyph+ (font-glyphs-list f1)
(font-glyphs-list f2))]))]
[fonts (map reduced-font (cons f1 fs))])
(foldl f+ (car fonts) (cdr fonts)))))
(define (font* f s1 . ss)
(let ([s (apply * (cons s1 ss))])
(if (= 1 s) f
(font-scale* (reduced-font f) s))))
FontObject Real ... - > FontObject
(define (font:* o s1 . ss)
((match o
[(? font? _) font*]
[(? glyph? _) scale]
[(? layer? _) scale]
[(? contour? _) scale]
[(? anchor? _ ) scale]
[(? component? _) scale]
[_ (error "Error: wrong type for font:*")])
o
(apply * (cons s1 ss))))
FontObject ... - > FontObject
(define (font:+ o1 . os)
(apply (match o1
[(? font? _) font+]
[(? glyph? _) glyph+]
[(? layer? _) layer+]
[(? contour? _) contour+]
[(? anchor? _ ) anchor+]
[(? component? _) component+]
[_ (error "Error: wrong type for font:+")])
(cons o1 os)))
FontObject ... - > FontObject
(define (font:- o1 . os)
(font:+ o1 (font:* (apply font:+ os) -1)))
FontObject Real ... - > FontObject
(define (font:/ o s1 . ss)
(font:* o (apply * (map (lambda (s)
(/ 1 s))
(cons s1 ss)))))
(define (add a . as)
(match (cons a as)
[(list (? font? _) ...)
(apply font:+ a as)]
[(list (? glyph? _) ...)
(apply font:+ a as)]
[(list (? layer? _) ...)
(apply font:+ a as)]
[(list (? real? _) ...)
(apply + a as)]
[(list (? vec? _) ...)
(foldl vec+ a as)]
[(list (? bezier/c _) ...)
(foldl (lambda (a b) (map vec+ a b)) a as)]
[_ (error "Invalid operands for product for addition")]))
(define (sub a . as)
(match (cons a as)
[(list (? font? _) ...)
(apply font:+ a (map (lambda (i) (prod i -1)) as))]
[(list (? glyph? _) ...)
(apply font:+ a (map (lambda (i) (prod i -1)) as))]
[(list (? layer? _) ...)
(apply font:+ a (map (lambda (i) (prod i -1)) as))]
[(list (? real? _) ...)
(apply - a as)]
[(list (? vec? _) ...)
(foldl vec- a as)]
[(list (? bezier/c _) ...)
(foldl (lambda (a b) (map vec- a b)) a as)]
[_ (error "Invalid operands for product for addition")]))
(define (prod a . as)
(match (cons a as)
[(list-no-order (? font? f) (? real? s) ...)
(apply font:* f s)]
[(list-no-order (? glyph? f) (? real? s) ...)
(apply font:* f s)]
[(list-no-order (? layer? f) (? real? s) ...)
(apply font:* f s)]
[(list-no-order (? vec? v) (? real? s) ...)
(vec* v (apply * s))]
[(list-no-order (? bezier/c b) (? real? s) ...)
(let ([f (apply * s)])
(map (lambda (v) (vec* v f)) b ))]
[(list (? real? x) ...)
(apply * x)]
[(list (? vec? v) ...)
(foldl (lambda (v1 v2)
(let* ([c1 (make-rectangular (vec-x v1) (vec-y v1))]
[c2 (make-rectangular (vec-x v2) (vec-y v2))]
[c (* c1 c2)])
(vec (real-part c) (imag-part c))))
a as)]
[(list (? bezier/c b) ...)
(foldl (lambda (b1 b2) (map prod b1 b2)) a as)]
[_ (error "Invalid operands for product")]))
(define (div a . as)
(match (cons a as)
[(list (? font? f) (? real? s) ...)
(apply font:* f (map (lambda (n) (/ 1.0 n)) s))]
[(list (? glyph? f) (? real? s) ...)
(apply font:* f (map (lambda (n) (/ 1.0 n)) s))]
[(list (? layer? f) (? real? s) ...)
(apply font:* f (map (lambda (n) (/ 1.0 n)) s))]
[(list (? vec? v) (? real? s) ...)
(vec* v (apply * (map (lambda (n) (/ 1.0 n)) s)))]
[(list (? bezier/c b) (? real? s) ...)
(let ([f (apply * (map (lambda (n) (/ 1.0 n)) s))])
(map (lambda (v) (vec* v f)) b ))]
[(list (? real? x) ...)
(apply / x)]
[_ (error "Invalid operands for product")]))
project the object on the x axis ( set every y coord . to zero )
(define (x-> o)
((if (font? o) font-scale* scale) o 1 0))
project the object on the y axis ( set every x coord . to zero )
(define (y-> o)
((if (font? o) font-scale* scale) o 0 1))
Font ... - > ( )
(define (interpolables f . fs)
(let ([f0 (foldl (lambda (f acc)
(let-values ([(a b) (interpolable-fonts acc f #f #t)])
a))
f fs)])
(cons f0 (map (lambda (f)
(let-values ([(a b) (interpolable-fonts f f0 #f #t)])
(match-fonts-contours f0 a)))
fs))))
(define (get-interpolable-fonts . fs)
(apply interpolables
(map (lambda (f)
(prepare-font f #f #t))
fs)))
(define (fix-components f1 f2)
(struct-copy font f1
[glyphs
(map
(lambda (g1 g2)
(struct-copy glyph g1
[layers
(list
(struct-copy layer (get-layer g1 foreground)
[components (map import-component-scale
(layer-components (get-layer g1 foreground))
(layer-components (get-layer g2 foreground)))]))]))
(font-glyphs-list f1)
(font-glyphs-list f2))]))
(define-syntax-rule (define-interpolable-fonts (id f) ...)
(define-values (id ...)
(apply values (interpolables f ...))))
(define-syntax (define-space stx)
(syntax-case stx ()
[(define-space id (origin [font ...]))
(for-each (lambda (i)
(unless (identifier? i)
(raise-syntax-error #f "Not an identifier" stx i)))
(append (list #'id #'origin) (syntax->list #'(font ...))))
(with-syntax ([(fname ...)
(map (lambda (f)
(format-id stx "~a-~a" #'id f))
(syntax->list #'(font ...)))])
#'(begin
(define (id f . fs)
(apply values (map (lambda (f) (add origin f)) (cons f fs))))
(define fname (sub font origin)) ...))]))
|
d3319816731244083524bc9b4112be7edad368265aa9a038a0e07d19ffc6932b | MinaProtocol/mina | cache_handle.mli | Cache handle
type t = Dirty.t lazy_t
* [ generate_or_load hdl ] is an alias for [ Lazy.force ] .
val generate_or_load : t -> Dirty.t
* [ ( + ) ] is semantically equivalent to { ! ) } .
val ( + ) : t -> t -> t
| null | https://raw.githubusercontent.com/MinaProtocol/mina/b19a220d87caa129ed5dcffc94f89204ae874661/src/lib/pickles/cache_handle.mli | ocaml | Cache handle
type t = Dirty.t lazy_t
* [ generate_or_load hdl ] is an alias for [ Lazy.force ] .
val generate_or_load : t -> Dirty.t
* [ ( + ) ] is semantically equivalent to { ! ) } .
val ( + ) : t -> t -> t
|
|
896bfbd5e84b34f567fca309aec0bbe8735e8f33ac952138bb01d851e8b23824 | sebschrader/programmierung-ss2015 | A2.hs | module E02.A2
( pack
, pack'
, pack''
, encode
, encode'
, decode
, decode'
, rotate
, rotate'
, example1
, example2
, example3
) where
example1 :: [Char]
example1 = ['a','a','b','b','b','a']
example2 :: [(Int,Char)]
example2 = [(2, 'a'), (3, 'b'), (1, 'a')]
example3 :: [Int]
example3 = [1,2,3,4]
-- (a)
-- This problem is somewhat difficult to solve as we have to apply a concept
-- that we never used before: multiple result values and modifying result
-- values from a recursive function application.
-- We need a helper function takeEqual that splits the longest prefix of
-- recurring characters off of a list and gives us both the longest prefix and
-- the remaining list.
-- Using where we can assign through pattern matching both parts of the result
-- of the helper function to variables and use them for the actual result of
-- the result function.
pack :: [Char] -> [[Char]]
pack "" = []
pack xs'@(x:xs) = ys:pack zs
where (ys, zs) = takeEqual x xs'
takeEqual :: Char -> [Char] -> ([Char], [Char])
takeEqual _ "" = ("","")
takeEqual c xs'@(x:xs)
-- We can do something with let as we have done above with where.
-- See for a discussion of both of
-- these constructs.
| x == c = let (ys, zs) = takeEqual c xs
in (x:ys, zs)
| otherwise = ("", xs')
-- Advanced: Very elegant solution using takeWhile and dropWhile
-- takeWhile: take elements from a list as long as a predicate is satisfied
-- -4.8.0.0/docs/Prelude.html#v:takeWhile
-- dropWhile: drop elements from a list as long as a predicate is satisfied
-- -4.8.0.0/docs/Prelude.html#v:dropWhile
-- We partially apply the equality function (==)
pack' :: [Char] -> [[Char]]
pack' [] = []
pack' xs'@(x:xs) = takeWhile (==x) xs':pack' (dropWhile (== x) xs)
Advanced : span combines takeWhile and dropWhile
-- -4.8.0.0/docs/Prelude.html#v:span
-- See also break:
-4.8.0.0/docs/Prelude.html#v:break
pack'' :: [Char] -> [[Char]]
pack'' [] = []
pack'' xs'@(x:xs) = ys:pack'' zs
where (ys, zs) = span (==x) xs'
-- (b)
-- We reuse the pack function to get lists of characters. We can compress these
-- lists then using the length function.
encode :: [Char] -> [(Int, Char)]
encode xs = compress (pack xs)
where
compress :: [[Char]] -> [(Int, Char)]
compress [] = []
compress (l:ls) = (length l, head l):compress ls
-- Advanced: map, Anonymous function (lambda)
-- We've seen map before. It allows the transformation of a list using a helper
-- function. The function would be really small, so we can use an anonymous
-- function.
-- We can even omit the argument of encode' and use function composition. This is
-- called pointfree style:
--
encode' :: [Char] -> [(Int, Char)]
encode' = map (\l -> (length l, head l)) . pack
-- (c)
intuitive idea , to split the first element a tuple
-- into its pattern (num,lit) and to work than with then
-- with this elements.
decode :: [(Int, Char)] -> [Char]
decode [] = ""
decode ((n, c):xs) = rep n c ++ decode xs
where rep :: Int -> Char -> [Char]
rep 0 _ = []
rep n c = c : rep (n-1) c
-- Advanced: Use built-in functions
The prelude already includes the functions replicate , fst , snd
-- replicate: Repeat an element a given number of times
-4.8.0.0/docs/Prelude.html#v:replicate
fst , snd : Extract components out of pairs
-- -4.8.0.0/docs/Prelude.html#v:fst
decode' :: [(Int, Char)] -> [Char]
decode' [] = []
decode' (x:xs) = replicate (fst x) (snd x) ++ decode xs
-- (d)
-- additional built-in functions: head, tail, init, last
-- intuitive approach: Shift elements to the end of the list with ++ until
the count reaches zero .
-- Problem: ++ can be inefficient
rotate :: [Int] -> Int -> [Int]
rotate [] n = []
rotate xs'@(x:xs) n
| n == 0 = xs'
| n < 0 = rotate xs' (length xs' + n)
| otherwise = rotate (xs ++ [x]) (n-1)
Advanced : take , drop , cycle
-- Use the built-in functions take, drop and cycle
take : take the first n elements of a list
-- -4.8.0.0/docs/Prelude.html#v:take
drop : drop the first n elements of a list
-- -4.8.0.0/docs/Prelude.html#v:drop
-- repeat a list
-4.8.0.0/docs/Prelude.html#v:cycle
rotate' :: [Int] -> Int -> [Int]
rotate' xs n
| n < 0 = rotate' xs (l + n)
| otherwise = take l $ drop n $ cycle xs
where l = length xs
| null | https://raw.githubusercontent.com/sebschrader/programmierung-ss2015/88fc40107dc42f013d1a1374b2b44a481b4f1746/E02/A2.hs | haskell | (a)
This problem is somewhat difficult to solve as we have to apply a concept
that we never used before: multiple result values and modifying result
values from a recursive function application.
We need a helper function takeEqual that splits the longest prefix of
recurring characters off of a list and gives us both the longest prefix and
the remaining list.
Using where we can assign through pattern matching both parts of the result
of the helper function to variables and use them for the actual result of
the result function.
We can do something with let as we have done above with where.
See for a discussion of both of
these constructs.
Advanced: Very elegant solution using takeWhile and dropWhile
takeWhile: take elements from a list as long as a predicate is satisfied
-4.8.0.0/docs/Prelude.html#v:takeWhile
dropWhile: drop elements from a list as long as a predicate is satisfied
-4.8.0.0/docs/Prelude.html#v:dropWhile
We partially apply the equality function (==)
-4.8.0.0/docs/Prelude.html#v:span
See also break:
(b)
We reuse the pack function to get lists of characters. We can compress these
lists then using the length function.
Advanced: map, Anonymous function (lambda)
We've seen map before. It allows the transformation of a list using a helper
function. The function would be really small, so we can use an anonymous
function.
We can even omit the argument of encode' and use function composition. This is
called pointfree style:
(c)
into its pattern (num,lit) and to work than with then
with this elements.
Advanced: Use built-in functions
replicate: Repeat an element a given number of times
-4.8.0.0/docs/Prelude.html#v:fst
(d)
additional built-in functions: head, tail, init, last
intuitive approach: Shift elements to the end of the list with ++ until
Problem: ++ can be inefficient
Use the built-in functions take, drop and cycle
-4.8.0.0/docs/Prelude.html#v:take
-4.8.0.0/docs/Prelude.html#v:drop
repeat a list | module E02.A2
( pack
, pack'
, pack''
, encode
, encode'
, decode
, decode'
, rotate
, rotate'
, example1
, example2
, example3
) where
example1 :: [Char]
example1 = ['a','a','b','b','b','a']
example2 :: [(Int,Char)]
example2 = [(2, 'a'), (3, 'b'), (1, 'a')]
example3 :: [Int]
example3 = [1,2,3,4]
pack :: [Char] -> [[Char]]
pack "" = []
pack xs'@(x:xs) = ys:pack zs
where (ys, zs) = takeEqual x xs'
takeEqual :: Char -> [Char] -> ([Char], [Char])
takeEqual _ "" = ("","")
takeEqual c xs'@(x:xs)
| x == c = let (ys, zs) = takeEqual c xs
in (x:ys, zs)
| otherwise = ("", xs')
pack' :: [Char] -> [[Char]]
pack' [] = []
pack' xs'@(x:xs) = takeWhile (==x) xs':pack' (dropWhile (== x) xs)
Advanced : span combines takeWhile and dropWhile
-4.8.0.0/docs/Prelude.html#v:break
pack'' :: [Char] -> [[Char]]
pack'' [] = []
pack'' xs'@(x:xs) = ys:pack'' zs
where (ys, zs) = span (==x) xs'
encode :: [Char] -> [(Int, Char)]
encode xs = compress (pack xs)
where
compress :: [[Char]] -> [(Int, Char)]
compress [] = []
compress (l:ls) = (length l, head l):compress ls
encode' :: [Char] -> [(Int, Char)]
encode' = map (\l -> (length l, head l)) . pack
intuitive idea , to split the first element a tuple
decode :: [(Int, Char)] -> [Char]
decode [] = ""
decode ((n, c):xs) = rep n c ++ decode xs
where rep :: Int -> Char -> [Char]
rep 0 _ = []
rep n c = c : rep (n-1) c
The prelude already includes the functions replicate , fst , snd
-4.8.0.0/docs/Prelude.html#v:replicate
fst , snd : Extract components out of pairs
decode' :: [(Int, Char)] -> [Char]
decode' [] = []
decode' (x:xs) = replicate (fst x) (snd x) ++ decode xs
the count reaches zero .
rotate :: [Int] -> Int -> [Int]
rotate [] n = []
rotate xs'@(x:xs) n
| n == 0 = xs'
| n < 0 = rotate xs' (length xs' + n)
| otherwise = rotate (xs ++ [x]) (n-1)
Advanced : take , drop , cycle
take : take the first n elements of a list
drop : drop the first n elements of a list
-4.8.0.0/docs/Prelude.html#v:cycle
rotate' :: [Int] -> Int -> [Int]
rotate' xs n
| n < 0 = rotate' xs (l + n)
| otherwise = take l $ drop n $ cycle xs
where l = length xs
|
9750de7ede1a0a384dce617b5d7ffcc0471048f941c5327b09360fa4bd24353e | haskell/hackage-security | JSON.hs | # LANGUAGE CPP #
#if __GLASGOW_HASKELL__ < 710
# LANGUAGE OverlappingInstances #
#endif
-- |
module Hackage.Security.Util.JSON (
-- * Type classes
ToJSON(..)
, FromJSON(..)
, ToObjectKey(..)
, FromObjectKey(..)
, ReportSchemaErrors(..)
, Expected
, Got
, expected'
-- * Utility
, fromJSObject
, fromJSField
, fromJSOptField
, mkObject
-- * Re-exports
, JSValue(..)
, Int54
) where
import MyPrelude
import Control.Monad (liftM)
import Data.Maybe (catMaybes)
import Data.Map (Map)
import Data.Time
import Text.JSON.Canonical
import Network.URI
import qualified Data.Map as Map
#if !MIN_VERSION_time(1,5,0)
import System.Locale (defaultTimeLocale)
#endif
import Hackage.Security.Util.Path
------------------------------------------------------------------------------
ToJSON and FromJSON classes
We parameterize over the monad here to avoid mutual module dependencies .
------------------------------------------------------------------------------
ToJSON and FromJSON classes
We parameterize over the monad here to avoid mutual module dependencies.
-------------------------------------------------------------------------------}
class ToJSON m a where
toJSON :: a -> m JSValue
class FromJSON m a where
fromJSON :: JSValue -> m a
| Used in the ' ToJSON ' instance for ' Map '
class ToObjectKey m a where
toObjectKey :: a -> m String
-- | Used in the 'FromJSON' instance for 'Map'
class FromObjectKey m a where
fromObjectKey :: String -> m (Maybe a)
-- | Monads in which we can report schema errors
class (Applicative m, Monad m) => ReportSchemaErrors m where
expected :: Expected -> Maybe Got -> m a
type Expected = String
type Got = String
expected' :: ReportSchemaErrors m => Expected -> JSValue -> m a
expected' descr val = expected descr (Just (describeValue val))
where
describeValue :: JSValue -> String
describeValue (JSNull ) = "null"
describeValue (JSBool _) = "bool"
describeValue (JSNum _) = "num"
describeValue (JSString _) = "string"
describeValue (JSArray _) = "array"
describeValue (JSObject _) = "object"
unknownField :: ReportSchemaErrors m => String -> m a
unknownField field = expected ("field " ++ show field) Nothing
{-------------------------------------------------------------------------------
ToObjectKey and FromObjectKey instances
-------------------------------------------------------------------------------}
instance Monad m => ToObjectKey m String where
toObjectKey = return
instance Monad m => FromObjectKey m String where
fromObjectKey = return . Just
instance Monad m => ToObjectKey m (Path root) where
toObjectKey (Path fp) = return fp
instance Monad m => FromObjectKey m (Path root) where
fromObjectKey = liftM (fmap Path) . fromObjectKey
------------------------------------------------------------------------------
ToJSON and FromJSON instances
------------------------------------------------------------------------------
ToJSON and FromJSON instances
-------------------------------------------------------------------------------}
instance Monad m => ToJSON m JSValue where
toJSON = return
instance Monad m => FromJSON m JSValue where
fromJSON = return
instance Monad m => ToJSON m String where
toJSON = return . JSString
instance ReportSchemaErrors m => FromJSON m String where
fromJSON (JSString str) = return str
fromJSON val = expected' "string" val
instance Monad m => ToJSON m Int54 where
toJSON = return . JSNum
instance ReportSchemaErrors m => FromJSON m Int54 where
fromJSON (JSNum i) = return i
fromJSON val = expected' "int" val
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(Monad m, ToJSON m a) => ToJSON m [a] where
toJSON = liftM JSArray . mapM toJSON
instance
#if __GLASGOW_HASKELL__ >= 710
{-# OVERLAPPABLE #-}
#endif
(ReportSchemaErrors m, FromJSON m a) => FromJSON m [a] where
fromJSON (JSArray as) = mapM fromJSON as
fromJSON val = expected' "array" val
instance Monad m => ToJSON m UTCTime where
toJSON = return . JSString . formatTime defaultTimeLocale "%FT%TZ"
instance ReportSchemaErrors m => FromJSON m UTCTime where
fromJSON enc = do
str <- fromJSON enc
case parseTimeM False defaultTimeLocale "%FT%TZ" str of
Just time -> return time
Nothing -> expected "valid date-time string" (Just str)
#if !MIN_VERSION_time(1,5,0)
where
parseTimeM _trim = parseTime
#endif
instance ( Monad m
, ToObjectKey m k
, ToJSON m a
) => ToJSON m (Map k a) where
toJSON = liftM JSObject . mapM aux . Map.toList
where
aux :: (k, a) -> m (String, JSValue)
aux (k, a) = do k' <- toObjectKey k; a' <- toJSON a; return (k', a')
instance ( ReportSchemaErrors m
, Ord k
, FromObjectKey m k
, FromJSON m a
) => FromJSON m (Map k a) where
fromJSON enc = do
obj <- fromJSObject enc
Map.fromList . catMaybes <$> mapM aux obj
where
aux :: (String, JSValue) -> m (Maybe (k, a))
aux (k, a) = knownKeys <$> fromObjectKey k <*> fromJSON a
knownKeys :: Maybe k -> a -> Maybe (k, a)
knownKeys Nothing _ = Nothing
knownKeys (Just k) a = Just (k, a)
instance Monad m => ToJSON m URI where
toJSON = toJSON . show
instance ReportSchemaErrors m => FromJSON m URI where
fromJSON enc = do
str <- fromJSON enc
case parseURI str of
Nothing -> expected "valid URI" (Just str)
Just uri -> return uri
{-------------------------------------------------------------------------------
Utility
-------------------------------------------------------------------------------}
fromJSObject :: ReportSchemaErrors m => JSValue -> m [(String, JSValue)]
fromJSObject (JSObject obj) = return obj
fromJSObject val = expected' "object" val
-- | Extract a field from a JSON object
fromJSField :: (ReportSchemaErrors m, FromJSON m a)
=> JSValue -> String -> m a
fromJSField val nm = do
obj <- fromJSObject val
case lookup nm obj of
Just fld -> fromJSON fld
Nothing -> unknownField nm
fromJSOptField :: (ReportSchemaErrors m, FromJSON m a)
=> JSValue -> String -> m (Maybe a)
fromJSOptField val nm = do
obj <- fromJSObject val
case lookup nm obj of
Just fld -> Just <$> fromJSON fld
Nothing -> return Nothing
mkObject :: forall m. Monad m => [(String, m JSValue)] -> m JSValue
mkObject = liftM JSObject . sequenceFields
where
sequenceFields :: [(String, m JSValue)] -> m [(String, JSValue)]
sequenceFields [] = return []
sequenceFields ((fld,val):flds) = do val' <- val
flds' <- sequenceFields flds
return ((fld,val'):flds')
| null | https://raw.githubusercontent.com/haskell/hackage-security/745b294e8cda2b46a21a6d1766a87f699a0277a8/hackage-security/src/Hackage/Security/Util/JSON.hs | haskell | |
* Type classes
* Utility
* Re-exports
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Used in the 'FromJSON' instance for 'Map'
| Monads in which we can report schema errors
------------------------------------------------------------------------------
ToObjectKey and FromObjectKey instances
------------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
# OVERLAPPABLE #
# OVERLAPPABLE #
------------------------------------------------------------------------------
Utility
------------------------------------------------------------------------------
| Extract a field from a JSON object | # LANGUAGE CPP #
#if __GLASGOW_HASKELL__ < 710
# LANGUAGE OverlappingInstances #
#endif
module Hackage.Security.Util.JSON (
ToJSON(..)
, FromJSON(..)
, ToObjectKey(..)
, FromObjectKey(..)
, ReportSchemaErrors(..)
, Expected
, Got
, expected'
, fromJSObject
, fromJSField
, fromJSOptField
, mkObject
, JSValue(..)
, Int54
) where
import MyPrelude
import Control.Monad (liftM)
import Data.Maybe (catMaybes)
import Data.Map (Map)
import Data.Time
import Text.JSON.Canonical
import Network.URI
import qualified Data.Map as Map
#if !MIN_VERSION_time(1,5,0)
import System.Locale (defaultTimeLocale)
#endif
import Hackage.Security.Util.Path
ToJSON and FromJSON classes
We parameterize over the monad here to avoid mutual module dependencies .
ToJSON and FromJSON classes
We parameterize over the monad here to avoid mutual module dependencies.
class ToJSON m a where
toJSON :: a -> m JSValue
class FromJSON m a where
fromJSON :: JSValue -> m a
| Used in the ' ToJSON ' instance for ' Map '
class ToObjectKey m a where
toObjectKey :: a -> m String
class FromObjectKey m a where
fromObjectKey :: String -> m (Maybe a)
class (Applicative m, Monad m) => ReportSchemaErrors m where
expected :: Expected -> Maybe Got -> m a
type Expected = String
type Got = String
expected' :: ReportSchemaErrors m => Expected -> JSValue -> m a
expected' descr val = expected descr (Just (describeValue val))
where
describeValue :: JSValue -> String
describeValue (JSNull ) = "null"
describeValue (JSBool _) = "bool"
describeValue (JSNum _) = "num"
describeValue (JSString _) = "string"
describeValue (JSArray _) = "array"
describeValue (JSObject _) = "object"
unknownField :: ReportSchemaErrors m => String -> m a
unknownField field = expected ("field " ++ show field) Nothing
instance Monad m => ToObjectKey m String where
toObjectKey = return
instance Monad m => FromObjectKey m String where
fromObjectKey = return . Just
instance Monad m => ToObjectKey m (Path root) where
toObjectKey (Path fp) = return fp
instance Monad m => FromObjectKey m (Path root) where
fromObjectKey = liftM (fmap Path) . fromObjectKey
ToJSON and FromJSON instances
ToJSON and FromJSON instances
instance Monad m => ToJSON m JSValue where
toJSON = return
instance Monad m => FromJSON m JSValue where
fromJSON = return
instance Monad m => ToJSON m String where
toJSON = return . JSString
instance ReportSchemaErrors m => FromJSON m String where
fromJSON (JSString str) = return str
fromJSON val = expected' "string" val
instance Monad m => ToJSON m Int54 where
toJSON = return . JSNum
instance ReportSchemaErrors m => FromJSON m Int54 where
fromJSON (JSNum i) = return i
fromJSON val = expected' "int" val
instance
#if __GLASGOW_HASKELL__ >= 710
#endif
(Monad m, ToJSON m a) => ToJSON m [a] where
toJSON = liftM JSArray . mapM toJSON
instance
#if __GLASGOW_HASKELL__ >= 710
#endif
(ReportSchemaErrors m, FromJSON m a) => FromJSON m [a] where
fromJSON (JSArray as) = mapM fromJSON as
fromJSON val = expected' "array" val
instance Monad m => ToJSON m UTCTime where
toJSON = return . JSString . formatTime defaultTimeLocale "%FT%TZ"
instance ReportSchemaErrors m => FromJSON m UTCTime where
fromJSON enc = do
str <- fromJSON enc
case parseTimeM False defaultTimeLocale "%FT%TZ" str of
Just time -> return time
Nothing -> expected "valid date-time string" (Just str)
#if !MIN_VERSION_time(1,5,0)
where
parseTimeM _trim = parseTime
#endif
instance ( Monad m
, ToObjectKey m k
, ToJSON m a
) => ToJSON m (Map k a) where
toJSON = liftM JSObject . mapM aux . Map.toList
where
aux :: (k, a) -> m (String, JSValue)
aux (k, a) = do k' <- toObjectKey k; a' <- toJSON a; return (k', a')
instance ( ReportSchemaErrors m
, Ord k
, FromObjectKey m k
, FromJSON m a
) => FromJSON m (Map k a) where
fromJSON enc = do
obj <- fromJSObject enc
Map.fromList . catMaybes <$> mapM aux obj
where
aux :: (String, JSValue) -> m (Maybe (k, a))
aux (k, a) = knownKeys <$> fromObjectKey k <*> fromJSON a
knownKeys :: Maybe k -> a -> Maybe (k, a)
knownKeys Nothing _ = Nothing
knownKeys (Just k) a = Just (k, a)
instance Monad m => ToJSON m URI where
toJSON = toJSON . show
instance ReportSchemaErrors m => FromJSON m URI where
fromJSON enc = do
str <- fromJSON enc
case parseURI str of
Nothing -> expected "valid URI" (Just str)
Just uri -> return uri
fromJSObject :: ReportSchemaErrors m => JSValue -> m [(String, JSValue)]
fromJSObject (JSObject obj) = return obj
fromJSObject val = expected' "object" val
fromJSField :: (ReportSchemaErrors m, FromJSON m a)
=> JSValue -> String -> m a
fromJSField val nm = do
obj <- fromJSObject val
case lookup nm obj of
Just fld -> fromJSON fld
Nothing -> unknownField nm
fromJSOptField :: (ReportSchemaErrors m, FromJSON m a)
=> JSValue -> String -> m (Maybe a)
fromJSOptField val nm = do
obj <- fromJSObject val
case lookup nm obj of
Just fld -> Just <$> fromJSON fld
Nothing -> return Nothing
mkObject :: forall m. Monad m => [(String, m JSValue)] -> m JSValue
mkObject = liftM JSObject . sequenceFields
where
sequenceFields :: [(String, m JSValue)] -> m [(String, JSValue)]
sequenceFields [] = return []
sequenceFields ((fld,val):flds) = do val' <- val
flds' <- sequenceFields flds
return ((fld,val'):flds')
|
829ba08773185bc58d03e13d365677dd13bbb03e3b3c6924d7ffded58aa8860e | modular-macros/ocaml-macros | callback.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Registering OCaml values with the C runtime for later callbacks *)
external register_named_value : string -> Obj.t -> unit
= "caml_register_named_value"
let register name v =
register_named_value name (Obj.repr v)
let register_exception name (exn : exn) =
let exn = Obj.repr exn in
let slot = if Obj.tag exn = Obj.object_tag then exn else Obj.field exn 0 in
register_named_value name slot
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/stdlib/callback.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Registering OCaml values with the C runtime for later callbacks | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
external register_named_value : string -> Obj.t -> unit
= "caml_register_named_value"
let register name v =
register_named_value name (Obj.repr v)
let register_exception name (exn : exn) =
let exn = Obj.repr exn in
let slot = if Obj.tag exn = Obj.object_tag then exn else Obj.field exn 0 in
register_named_value name slot
|
cbc7a724157293eb6a545ed4e85bfead4a63c9a14eb366c6b7e8e58076fdb0bc | patricoferris/ni-forests | l.mli | open Brr
module G : sig
val l : Jv.t
end
module Layer : sig
type t
include Jv.CONV with type t := t
end
module LatLng : sig
type t = Jv.t
include Jv.CONV with type t := t
val create : lat:float -> lng:float -> t
end
module TileLayer : sig
type opts
val opts_to_jv : opts -> Jv.t
val opts :
?min_zoom:int ->
?max_zoom:int ->
?subdomains:string array ->
?error_title_url:string ->
?zoom_offset:int ->
?tms:bool ->
?zoom_reverse:bool ->
?detect_retina:bool ->
?cross_origin:bool ->
unit ->
opts
type t
include Jv.CONV with type t := t
val create : ?opts:opts -> string -> t
val set_url : ?no_redraw:bool -> t -> string -> unit
end
module Map : sig
type opts
val opts_to_jv : opts -> Jv.t
val opts :
?prefer_canvas:bool ->
?attribution_control:bool ->
?zoom_control:bool ->
?close_popup_on_click:bool ->
?zoom_snap:int ->
?zoom_delta:int ->
?track_resize:bool ->
?box_zoom:bool ->
?double_click_zoom:bool ->
?dragging:bool ->
?center:Jv.t ->
?zoom:int ->
?min_zoom:int ->
?max_zoom:int ->
unit ->
opts
type t
include Jv.CONV with type t := t
val create : ?opts:opts -> string -> t
val create_with_el : ?opts:opts -> El.t -> t
val set_view : latlng:LatLng.t -> zoom:int -> t -> t
val add_layer : t -> [ `Layer of Layer.t | `Tile of TileLayer.t ] -> t
end
module Control : sig
type t
type position = TopLeft | TopRight | BottomLeft | BottomRight
include Jv.CONV with type t := t
val create : ?position:position -> on_add:(Map.t -> El.t) -> update:(Jv.t -> unit) -> unit -> t
val add_to : map:Map.t -> t -> t
val remove : t -> unit
end | null | https://raw.githubusercontent.com/patricoferris/ni-forests/610a2bb3694faab7b688dda2381fbc24a313d2df/src/leaflet/l.mli | ocaml | open Brr
module G : sig
val l : Jv.t
end
module Layer : sig
type t
include Jv.CONV with type t := t
end
module LatLng : sig
type t = Jv.t
include Jv.CONV with type t := t
val create : lat:float -> lng:float -> t
end
module TileLayer : sig
type opts
val opts_to_jv : opts -> Jv.t
val opts :
?min_zoom:int ->
?max_zoom:int ->
?subdomains:string array ->
?error_title_url:string ->
?zoom_offset:int ->
?tms:bool ->
?zoom_reverse:bool ->
?detect_retina:bool ->
?cross_origin:bool ->
unit ->
opts
type t
include Jv.CONV with type t := t
val create : ?opts:opts -> string -> t
val set_url : ?no_redraw:bool -> t -> string -> unit
end
module Map : sig
type opts
val opts_to_jv : opts -> Jv.t
val opts :
?prefer_canvas:bool ->
?attribution_control:bool ->
?zoom_control:bool ->
?close_popup_on_click:bool ->
?zoom_snap:int ->
?zoom_delta:int ->
?track_resize:bool ->
?box_zoom:bool ->
?double_click_zoom:bool ->
?dragging:bool ->
?center:Jv.t ->
?zoom:int ->
?min_zoom:int ->
?max_zoom:int ->
unit ->
opts
type t
include Jv.CONV with type t := t
val create : ?opts:opts -> string -> t
val create_with_el : ?opts:opts -> El.t -> t
val set_view : latlng:LatLng.t -> zoom:int -> t -> t
val add_layer : t -> [ `Layer of Layer.t | `Tile of TileLayer.t ] -> t
end
module Control : sig
type t
type position = TopLeft | TopRight | BottomLeft | BottomRight
include Jv.CONV with type t := t
val create : ?position:position -> on_add:(Map.t -> El.t) -> update:(Jv.t -> unit) -> unit -> t
val add_to : map:Map.t -> t -> t
val remove : t -> unit
end |
|
39e24b52d7ef38c68adeddb8e80b960e6d971cf7f31745f12655669211890eab | lehins/massiv | Stream.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
-- |
-- Module : Data.Massiv.Array.Delayed.Stream
Copyright : ( c ) 2019 - 2022
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
module Data.Massiv.Array.Delayed.Stream (
DS (..),
Array (..),
toStreamArray,
toStreamM,
toStreamIxM,
toSteps,
fromSteps,
fromStepsM,
) where
import Control.Applicative
import Control.Monad.ST
import Data.Coerce
import Data.Foldable
import Data.Massiv.Array.Delayed.Pull
import Data.Massiv.Core.Common
import qualified Data.Massiv.Vector.Stream as S
import GHC.Exts
import Prelude hiding (drop, take)
-- | Delayed stream array that represents a sequence of values that can be loaded
-- sequentially. Important distinction from other arrays is that its size might no be
-- known until it is computed.
data DS = DS
newtype instance Array DS Ix1 e = DSArray
{ dsArray :: S.Steps S.Id e
}
-- | /O(1)/ - Convert delayed stream array into `Steps`.
--
-- @since 0.4.1
toSteps :: Vector DS e -> Steps Id e
toSteps = coerce
# INLINE toSteps #
-- | /O(1)/ - Convert `Steps` into delayed stream array
--
-- @since 0.4.1
fromSteps :: Steps Id e -> Vector DS e
fromSteps = coerce
# INLINE fromSteps #
-- | /O(1)/ - Convert monadic `Steps` into delayed stream array
--
-- @since 0.5.0
fromStepsM :: Monad m => Steps m e -> m (Vector DS e)
fromStepsM = fmap DSArray . S.transSteps
# INLINE fromStepsM #
instance Shape DS Ix1 where
linearSizeHint = stepsSize . dsArray
# INLINE linearSizeHint #
linearSize = SafeSz . unId . S.length . dsArray
# INLINE linearSize #
outerSize = linearSize
# INLINE outerSize #
isNull = S.unId . S.null . coerce
# INLINE isNull #
-- | For now only `Seq` strategy.
instance Strategy DS where
getComp _ = Seq
setComp _ = id
repr = DS
instance Functor (Array DS Ix1) where
fmap f = coerce . S.map f . dsArray
# INLINE fmap #
(<$) e = coerce . (e <$) . dsArray
{-# INLINE (<$) #-}
instance Applicative (Array DS Ix1) where
pure = fromSteps . S.singleton
# INLINE pure #
(<*>) a1 a2 = fromSteps (S.zipWith ($) (coerce a1) (coerce a2))
{-# INLINE (<*>) #-}
#if MIN_VERSION_base(4,10,0)
liftA2 f a1 a2 = fromSteps (S.zipWith f (coerce a1) (coerce a2))
# INLINE liftA2 #
#endif
instance Monad (Array DS Ix1) where
(>>=) arr f = coerce (S.concatMap (coerce . f) (dsArray arr))
{-# INLINE (>>=) #-}
instance Foldable (Array DS Ix1) where
foldr f acc = S.unId . S.foldrLazy f acc . toSteps
# INLINE foldr #
foldl f acc = S.unId . S.foldlLazy f acc . toSteps
{-# INLINE foldl #-}
foldl' f acc = S.unId . S.foldl f acc . toSteps
{-# INLINE foldl' #-}
foldr1 f = S.unId . S.foldr1Lazy f . toSteps
# INLINE foldr1 #
foldl1 f = S.unId . S.foldl1Lazy f . toSteps
# INLINE foldl1 #
toList = S.toList . coerce
# INLINE toList #
length = S.unId . S.length . coerce
# INLINE length #
null = S.unId . S.null . coerce
# INLINE null #
sum = S.unId . S.foldl (+) 0 . toSteps
# INLINE sum #
product = S.unId . S.foldl (*) 1 . toSteps
# INLINE product #
maximum = S.unId . S.foldl1 max . toSteps
# INLINE maximum #
minimum = S.unId . S.foldl1 min . toSteps
# INLINE minimum #
instance Semigroup (Array DS Ix1 e) where
(<>) a1 a2 = fromSteps (coerce a1 `S.append` coerce a2)
{-# INLINE (<>) #-}
instance Monoid (Array DS Ix1 e) where
mempty = DSArray S.empty
# INLINE mempty #
#if !MIN_VERSION_base(4,11,0)
mappend = (<>)
# INLINE mappend #
#endif
instance IsList (Array DS Ix1 e) where
type Item (Array DS Ix1 e) = e
fromList = fromSteps . fromList
# INLINE fromList #
fromListN n = fromSteps . fromListN n
# INLINE fromListN #
toList = S.toList . coerce
# INLINE toList #
instance S.Stream DS Ix1 e where
toStream = coerce
{-# INLINE toStream #-}
toStreamIx = S.indexed . coerce
# INLINE toStreamIx #
-- | Flatten an array into a stream of values.
--
-- @since 0.4.1
toStreamArray :: (Index ix, Source r e) => Array r ix e -> Vector DS e
toStreamArray = DSArray . S.steps
{-# INLINE [1] toStreamArray #-}
{-# RULES "toStreamArray/id" toStreamArray = id #-}
-- | /O(1)/ - Convert an array into monadic `Steps`
--
-- @since 0.5.0
toStreamM :: (Stream r ix e, Monad m) => Array r ix e -> Steps m e
toStreamM = S.transStepsId . toStream
# INLINE toStreamM #
-- | /O(1)/ - Convert an array into monadic `Steps`
--
-- @since 0.5.0
toStreamIxM :: (Stream r ix e, Monad m) => Array r ix e -> Steps m (ix, e)
toStreamIxM = S.transStepsId . toStreamIx
# INLINE toStreamIxM #
-- | /O(n)/ - `size` implementation.
instance Load DS Ix1 e where
makeArrayLinear _ k = fromSteps . S.generate k
# INLINE makeArrayLinear #
replicate _ k = fromSteps . S.replicate k
# INLINE replicate #
iterArrayLinearST_ _scheduler arr uWrite =
S.mapM_ (uncurry uWrite) $ S.indexed $ S.transStepsId (coerce arr)
{-# INLINE iterArrayLinearST_ #-}
unsafeLoadIntoST marr (DSArray sts) =
S.unstreamIntoM marr (stepsSize sts) (stepsStream sts)
# INLINE unsafeLoadIntoST #
unsafeLoadIntoIO marr arr = stToIO $ unsafeLoadIntoST marr arr
# INLINE unsafeLoadIntoIO #
-- cons :: e -> Array DS Ix1 e -> Array DS Ix1 e
cons e = coerce . S.cons e . dsArray
-- {-# INLINE cons #-}
-- uncons :: Array DS Ix1 e -> Maybe (e, Array DS Ix1 e)
uncons = coerce . S.uncons . dsArray
{ - # INLINE uncons # - }
-- snoc :: Array DS Ix1 e -> e -> Array DS Ix1 e
snoc ( DSArray sts ) e = DSArray ( S.snoc sts e )
{ - # INLINE snoc # - }
-- TODO: skip the stride while loading
instance StrideLoad DS Ix1 e where
iterArrayLinearWithStrideST _ scheduler stride resultSize arr uWrite =
-- let strideIx = unStride stride
-- DIArray (DArray _ _ f) = arr
-- in loopM_ 0 (< numWorkers scheduler) (+ 1) $ \ !start ->
-- scheduleWork scheduler $
iterLinearM _ resultSize start ( totalElem resultSize ) ( numWorkers scheduler ) ( < ) $
\ ! i ix - > uWrite i ( f ( liftIndex2 ( * ) strideIx ix ) )
-- {-# INLINE iterArrayLinearWithStrideST_ #-}
| null | https://raw.githubusercontent.com/lehins/massiv/67a920d4403f210d0bfdad1acc4bec208d80a588/massiv/src/Data/Massiv/Array/Delayed/Stream.hs | haskell | |
Module : Data.Massiv.Array.Delayed.Stream
License : BSD3
Stability : experimental
Portability : non-portable
| Delayed stream array that represents a sequence of values that can be loaded
sequentially. Important distinction from other arrays is that its size might no be
known until it is computed.
| /O(1)/ - Convert delayed stream array into `Steps`.
@since 0.4.1
| /O(1)/ - Convert `Steps` into delayed stream array
@since 0.4.1
| /O(1)/ - Convert monadic `Steps` into delayed stream array
@since 0.5.0
| For now only `Seq` strategy.
# INLINE (<$) #
# INLINE (<*>) #
# INLINE (>>=) #
# INLINE foldl #
# INLINE foldl' #
# INLINE (<>) #
# INLINE toStream #
| Flatten an array into a stream of values.
@since 0.4.1
# INLINE [1] toStreamArray #
# RULES "toStreamArray/id" toStreamArray = id #
| /O(1)/ - Convert an array into monadic `Steps`
@since 0.5.0
| /O(1)/ - Convert an array into monadic `Steps`
@since 0.5.0
| /O(n)/ - `size` implementation.
# INLINE iterArrayLinearST_ #
cons :: e -> Array DS Ix1 e -> Array DS Ix1 e
{-# INLINE cons #-}
uncons :: Array DS Ix1 e -> Maybe (e, Array DS Ix1 e)
snoc :: Array DS Ix1 e -> e -> Array DS Ix1 e
TODO: skip the stride while loading
let strideIx = unStride stride
DIArray (DArray _ _ f) = arr
in loopM_ 0 (< numWorkers scheduler) (+ 1) $ \ !start ->
scheduleWork scheduler $
{-# INLINE iterArrayLinearWithStrideST_ #-} | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
Copyright : ( c ) 2019 - 2022
Maintainer : < >
module Data.Massiv.Array.Delayed.Stream (
DS (..),
Array (..),
toStreamArray,
toStreamM,
toStreamIxM,
toSteps,
fromSteps,
fromStepsM,
) where
import Control.Applicative
import Control.Monad.ST
import Data.Coerce
import Data.Foldable
import Data.Massiv.Array.Delayed.Pull
import Data.Massiv.Core.Common
import qualified Data.Massiv.Vector.Stream as S
import GHC.Exts
import Prelude hiding (drop, take)
data DS = DS
newtype instance Array DS Ix1 e = DSArray
{ dsArray :: S.Steps S.Id e
}
toSteps :: Vector DS e -> Steps Id e
toSteps = coerce
# INLINE toSteps #
fromSteps :: Steps Id e -> Vector DS e
fromSteps = coerce
# INLINE fromSteps #
fromStepsM :: Monad m => Steps m e -> m (Vector DS e)
fromStepsM = fmap DSArray . S.transSteps
# INLINE fromStepsM #
instance Shape DS Ix1 where
linearSizeHint = stepsSize . dsArray
# INLINE linearSizeHint #
linearSize = SafeSz . unId . S.length . dsArray
# INLINE linearSize #
outerSize = linearSize
# INLINE outerSize #
isNull = S.unId . S.null . coerce
# INLINE isNull #
instance Strategy DS where
getComp _ = Seq
setComp _ = id
repr = DS
instance Functor (Array DS Ix1) where
fmap f = coerce . S.map f . dsArray
# INLINE fmap #
(<$) e = coerce . (e <$) . dsArray
instance Applicative (Array DS Ix1) where
pure = fromSteps . S.singleton
# INLINE pure #
(<*>) a1 a2 = fromSteps (S.zipWith ($) (coerce a1) (coerce a2))
#if MIN_VERSION_base(4,10,0)
liftA2 f a1 a2 = fromSteps (S.zipWith f (coerce a1) (coerce a2))
# INLINE liftA2 #
#endif
instance Monad (Array DS Ix1) where
(>>=) arr f = coerce (S.concatMap (coerce . f) (dsArray arr))
instance Foldable (Array DS Ix1) where
foldr f acc = S.unId . S.foldrLazy f acc . toSteps
# INLINE foldr #
foldl f acc = S.unId . S.foldlLazy f acc . toSteps
foldl' f acc = S.unId . S.foldl f acc . toSteps
foldr1 f = S.unId . S.foldr1Lazy f . toSteps
# INLINE foldr1 #
foldl1 f = S.unId . S.foldl1Lazy f . toSteps
# INLINE foldl1 #
toList = S.toList . coerce
# INLINE toList #
length = S.unId . S.length . coerce
# INLINE length #
null = S.unId . S.null . coerce
# INLINE null #
sum = S.unId . S.foldl (+) 0 . toSteps
# INLINE sum #
product = S.unId . S.foldl (*) 1 . toSteps
# INLINE product #
maximum = S.unId . S.foldl1 max . toSteps
# INLINE maximum #
minimum = S.unId . S.foldl1 min . toSteps
# INLINE minimum #
instance Semigroup (Array DS Ix1 e) where
(<>) a1 a2 = fromSteps (coerce a1 `S.append` coerce a2)
instance Monoid (Array DS Ix1 e) where
mempty = DSArray S.empty
# INLINE mempty #
#if !MIN_VERSION_base(4,11,0)
mappend = (<>)
# INLINE mappend #
#endif
instance IsList (Array DS Ix1 e) where
type Item (Array DS Ix1 e) = e
fromList = fromSteps . fromList
# INLINE fromList #
fromListN n = fromSteps . fromListN n
# INLINE fromListN #
toList = S.toList . coerce
# INLINE toList #
instance S.Stream DS Ix1 e where
toStream = coerce
toStreamIx = S.indexed . coerce
# INLINE toStreamIx #
toStreamArray :: (Index ix, Source r e) => Array r ix e -> Vector DS e
toStreamArray = DSArray . S.steps
toStreamM :: (Stream r ix e, Monad m) => Array r ix e -> Steps m e
toStreamM = S.transStepsId . toStream
# INLINE toStreamM #
toStreamIxM :: (Stream r ix e, Monad m) => Array r ix e -> Steps m (ix, e)
toStreamIxM = S.transStepsId . toStreamIx
# INLINE toStreamIxM #
instance Load DS Ix1 e where
makeArrayLinear _ k = fromSteps . S.generate k
# INLINE makeArrayLinear #
replicate _ k = fromSteps . S.replicate k
# INLINE replicate #
iterArrayLinearST_ _scheduler arr uWrite =
S.mapM_ (uncurry uWrite) $ S.indexed $ S.transStepsId (coerce arr)
unsafeLoadIntoST marr (DSArray sts) =
S.unstreamIntoM marr (stepsSize sts) (stepsStream sts)
# INLINE unsafeLoadIntoST #
unsafeLoadIntoIO marr arr = stToIO $ unsafeLoadIntoST marr arr
# INLINE unsafeLoadIntoIO #
cons e = coerce . S.cons e . dsArray
uncons = coerce . S.uncons . dsArray
{ - # INLINE uncons # - }
snoc ( DSArray sts ) e = DSArray ( S.snoc sts e )
{ - # INLINE snoc # - }
instance StrideLoad DS Ix1 e where
iterArrayLinearWithStrideST _ scheduler stride resultSize arr uWrite =
iterLinearM _ resultSize start ( totalElem resultSize ) ( numWorkers scheduler ) ( < ) $
\ ! i ix - > uWrite i ( f ( liftIndex2 ( * ) strideIx ix ) )
|
27fdd6226c79fe0390cdf9c20bd7da71db5d96ee7feea114898540b3f6e9227f | JeffreyBenjaminBrown/digraphs-with-text | Main.hs | # LANGUAGE FlexibleContexts #
module Main (main) where
import Test.HUnit
import TParse
import TAdd
import TGraph
import TShow
import TSearch
main = runTestTT $ TestList [
TestLabel "tParse" tParse
, TestLabel "tAdd" tAdd
, TestLabel "tGraph" tGraph
, TestLabel "tShow" tShow
, TestLabel "tSearch" tSearch
]
| null | https://raw.githubusercontent.com/JeffreyBenjaminBrown/digraphs-with-text/34e47a52aa9abb6fd42028deba1623a92e278aae/test/Main.hs | haskell | # LANGUAGE FlexibleContexts #
module Main (main) where
import Test.HUnit
import TParse
import TAdd
import TGraph
import TShow
import TSearch
main = runTestTT $ TestList [
TestLabel "tParse" tParse
, TestLabel "tAdd" tAdd
, TestLabel "tGraph" tGraph
, TestLabel "tShow" tShow
, TestLabel "tSearch" tSearch
]
|
|
16f02c5524c8a696790207809c0a3bd51c9046ddd2608af7d7c8a98e853cdfaf | cdepillabout/world-peace | TypeErrors.hs | # LANGUAGE DataKinds #
# LANGUAGE InstanceSigs #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
-- Deferring type errors is necessary for should-not-typecheck to work.
{-# OPTIONS_GHC -fdefer-type-errors #-}
{-# OPTIONS_GHC -Wno-deferred-type-errors #-}
module Test.TypeErrors where
import Data.Functor.Identity (Identity(Identity))
import Test.ShouldNotTypecheck (shouldNotTypecheck)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase)
import Data.WorldPeace (Union(..), unionRemove)
unionRemoveTypeErrors :: TestTree
unionRemoveTypeErrors =
testGroup
"unionRemove should not typecheck"
[ testCase "too few types in resulting union 1" $ do
let u = This (Identity "hello") :: Union Identity '[String]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[]) (Identity Double))
, testCase "too few types in resulting union 2" $ do
let u = This (Identity "hello") :: Union Identity '[String, Char, Double]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String]) (Identity Double))
, testCase "too many types in resulting union 1" $ do
let u = This (Identity "hello") :: Union Identity '[String]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String, String]) (Identity Double))
, testCase "too many types in resulting union 2" $ do
let u = This (Identity "hello") :: Union Identity '[String, Char, Double]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String, Char, Double]) (Identity Double))
, testCase "does not pull out multiple" $ do
let u = This (Identity "hello") :: Union Identity '[String, String, Double]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String, Double]) (Identity String))
]
| null | https://raw.githubusercontent.com/cdepillabout/world-peace/0596da67d792ccf9f0ddbe44b5ce71b38cbde020/test/Test/TypeErrors.hs | haskell | # LANGUAGE OverloadedStrings #
Deferring type errors is necessary for should-not-typecheck to work.
# OPTIONS_GHC -fdefer-type-errors #
# OPTIONS_GHC -Wno-deferred-type-errors # | # LANGUAGE DataKinds #
# LANGUAGE InstanceSigs #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
module Test.TypeErrors where
import Data.Functor.Identity (Identity(Identity))
import Test.ShouldNotTypecheck (shouldNotTypecheck)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase)
import Data.WorldPeace (Union(..), unionRemove)
unionRemoveTypeErrors :: TestTree
unionRemoveTypeErrors =
testGroup
"unionRemove should not typecheck"
[ testCase "too few types in resulting union 1" $ do
let u = This (Identity "hello") :: Union Identity '[String]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[]) (Identity Double))
, testCase "too few types in resulting union 2" $ do
let u = This (Identity "hello") :: Union Identity '[String, Char, Double]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String]) (Identity Double))
, testCase "too many types in resulting union 1" $ do
let u = This (Identity "hello") :: Union Identity '[String]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String, String]) (Identity Double))
, testCase "too many types in resulting union 2" $ do
let u = This (Identity "hello") :: Union Identity '[String, Char, Double]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String, Char, Double]) (Identity Double))
, testCase "does not pull out multiple" $ do
let u = This (Identity "hello") :: Union Identity '[String, String, Double]
shouldNotTypecheck
(unionRemove u :: Either (Union Identity '[String, Double]) (Identity String))
]
|
7dc4743de561dfb9d9e6951e8a57495105dca953ec139a8bdfc2c1776315892a | gvolpe/shopping-cart-haskell | Orphan.hs | # OPTIONS_GHC -fno - warn - orphans #
{-# LANGUAGE DataKinds, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings #-}
module Orphan where
import Control.Monad.Catch ( Exception )
import Data.Bifunctor ( first )
import Data.Text ( Text )
import qualified Data.Text as T
import Database.PostgreSQL.Simple.FromField
import qualified Database.Redis as R
import Domain.Cart ( CartItem )
import GHC.TypeNats ( KnownNat )
import Refined
import Servant
instance Exception R.Reply
instance KnownNat n => Predicate (SizeEqualTo n) Int where
validate p value = validate p (digits value) where
digits :: Integral x => x -> [x]
digits 0 = []
digits x = digits (x `div` 10) ++ [x `mod` 10]
instance FromHttpApiData (Refined NonEmpty Text) where
parseUrlPiece = first (T.pack . show) . refine
instance FromField [CartItem] where
fromField = fromJSONField
| null | https://raw.githubusercontent.com/gvolpe/shopping-cart-haskell/23c1303fb27a1b006fe88eb3beb67188a536475f/src/Orphan.hs | haskell | # LANGUAGE DataKinds, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings # | # OPTIONS_GHC -fno - warn - orphans #
module Orphan where
import Control.Monad.Catch ( Exception )
import Data.Bifunctor ( first )
import Data.Text ( Text )
import qualified Data.Text as T
import Database.PostgreSQL.Simple.FromField
import qualified Database.Redis as R
import Domain.Cart ( CartItem )
import GHC.TypeNats ( KnownNat )
import Refined
import Servant
instance Exception R.Reply
instance KnownNat n => Predicate (SizeEqualTo n) Int where
validate p value = validate p (digits value) where
digits :: Integral x => x -> [x]
digits 0 = []
digits x = digits (x `div` 10) ++ [x `mod` 10]
instance FromHttpApiData (Refined NonEmpty Text) where
parseUrlPiece = first (T.pack . show) . refine
instance FromField [CartItem] where
fromField = fromJSONField
|
caa8d57d0d5825c334053b5298c582ebd06df27e138c8c077470b987224c5109 | input-output-hk/hydra | ServerSpec.hs | # LANGUAGE TypeApplications #
module Hydra.API.ServerSpec where
import Hydra.Prelude hiding (seq)
import Test.Hydra.Prelude
import Control.Exception (IOException)
import Control.Monad.Class.MonadSTM (
check,
modifyTVar',
newTQueue,
newTVarIO,
readTQueue,
tryReadTQueue,
writeTQueue,
)
import qualified Data.Aeson as Aeson
import Hydra.API.Server (Server (Server, sendOutput), withAPIServer)
import Hydra.API.ServerOutput (ServerOutput (Greetings, InvalidInput), TimedServerOutput (..), input)
import Hydra.Ledger.Simple (SimpleTx)
import Hydra.Logging (nullTracer, showLogsOnFailure)
import Hydra.Persistence (PersistenceIncremental (..), createPersistenceIncremental)
import Network.WebSockets (Connection, receiveData, runClient, sendBinaryData)
import Test.Hydra.Fixture (alice)
import Test.Network.Ports (withFreePort)
import Test.QuickCheck (checkCoverage, cover, generate)
import Test.QuickCheck.Monadic (monadicIO, monitor, pick, run)
spec :: Spec
spec = parallel $ do
it "greets" $ do
failAfter 5 $
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \_ -> do
withClient port $ \conn -> do
received <- receiveData conn
case Aeson.eitherDecode received of
Left{} -> failure $ "Failed to decode greeting " <> show received
Right TimedServerOutput{output = msg} -> msg `shouldBe` greeting
it "sends sendOutput to all connected clients" $ do
queue <- atomically newTQueue
showLogsOnFailure $ \tracer -> failAfter 5 $
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence tracer noop $ \Server{sendOutput} -> do
semaphore <- newTVarIO 0
withAsync
( concurrently_
(withClient port $ testClient queue semaphore)
(withClient port $ testClient queue semaphore)
)
$ \_ -> do
waitForClients semaphore
failAfter 1 $ atomically (replicateM 2 (readTQueue queue)) `shouldReturn` [greeting, greeting]
arbitraryMsg <- generate arbitrary
sendOutput arbitraryMsg
failAfter 1 $ atomically (replicateM 2 (readTQueue queue)) `shouldReturn` [arbitraryMsg, arbitraryMsg]
failAfter 1 $ atomically (tryReadTQueue queue) `shouldReturn` Nothing
it "sends all sendOutput history to all connected clients after a restart" $ do
showLogsOnFailure $ \tracer -> failAfter 5 $
withTempDir "ServerSpec" $ \tmpDir -> do
let persistentFile = tmpDir <> "/history"
arbitraryMsg <- generate arbitrary
persistence <- createPersistenceIncremental persistentFile
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice persistence tracer noop $ \Server{sendOutput} -> do
sendOutput arbitraryMsg
queue1 <- atomically newTQueue
queue2 <- atomically newTQueue
persistence' <- createPersistenceIncremental persistentFile
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice persistence' tracer noop $ \Server{sendOutput} -> do
semaphore <- newTVarIO 0
withAsync
( concurrently_
(withClient port $ testClient queue1 semaphore)
(withClient port $ testClient queue2 semaphore)
)
$ \_ -> do
waitForClients semaphore
failAfter 1 $ atomically (replicateM 3 (readTQueue queue1)) `shouldReturn` [greeting, arbitraryMsg, greeting]
failAfter 1 $ atomically (replicateM 3 (readTQueue queue2)) `shouldReturn` [greeting, arbitraryMsg, greeting]
sendOutput arbitraryMsg
failAfter 1 $ atomically (replicateM 1 (readTQueue queue1)) `shouldReturn` [arbitraryMsg]
failAfter 1 $ atomically (replicateM 1 (readTQueue queue2)) `shouldReturn` [arbitraryMsg]
failAfter 1 $ atomically (tryReadTQueue queue1) `shouldReturn` Nothing
it "echoes history (past outputs) to client upon reconnection" $
checkCoverage . monadicIO $ do
outputs <- pick arbitrary
monitor $ cover 0.1 (null outputs) "no message when reconnecting"
monitor $ cover 0.1 (length outputs == 1) "only one message when reconnecting"
monitor $ cover 1 (length outputs > 1) "more than one message when reconnecting"
run . failAfter 5 $ do
withFreePort $ \port ->
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \Server{sendOutput} -> do
mapM_ sendOutput outputs
withClient port $ \conn -> do
received <- replicateM (length outputs + 1) (receiveData conn)
case traverse Aeson.eitherDecode received of
Left{} -> failure $ "Failed to decode messages:\n" <> show received
Right timedOutputs ->
(output <$> timedOutputs) `shouldBe` greeting : outputs
it "sequence numbers are continuous and strictly monotonically increasing" $
monadicIO $ do
outputs :: [ServerOutput SimpleTx] <- pick arbitrary
run . failAfter 5 $ do
withFreePort $ \port ->
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \Server{sendOutput} -> do
mapM_ sendOutput outputs
withClient port $ \conn -> do
received <- replicateM (length outputs + 1) (receiveData conn)
case traverse Aeson.eitherDecode received of
Left{} -> failure $ "Failed to decode messages:\n" <> show received
Right (timedOutputs :: [TimedServerOutput SimpleTx]) ->
seq <$> timedOutputs `shouldSatisfy` strictlyMonotonic
it "sends an error when input cannot be decoded" $
failAfter 5 $
withFreePort $ \port -> sendsAnErrorWhenInputCannotBeDecoded port
strictlyMonotonic :: [Natural] -> Bool
strictlyMonotonic = \case
[] -> True
[_] -> True
(a : b : as) -> a + 1 == b && strictlyMonotonic (b : as)
sendsAnErrorWhenInputCannotBeDecoded :: Int -> Expectation
sendsAnErrorWhenInputCannotBeDecoded port = do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \_server -> do
withClient port $ \con -> do
_greeting :: ByteString <- receiveData con
sendBinaryData con invalidInput
msg <- receiveData con
case Aeson.eitherDecode @(TimedServerOutput SimpleTx) msg of
Left{} -> failure $ "Failed to decode output " <> show msg
Right TimedServerOutput{output = resp} -> resp `shouldSatisfy` isInvalidInput
where
invalidInput = "not a valid message"
isInvalidInput = \case
InvalidInput{input} -> input == invalidInput
_ -> False
greeting :: ServerOutput SimpleTx
greeting = Greetings alice
waitForClients :: (MonadSTM m, Ord a, Num a) => TVar m a -> m ()
waitForClients semaphore = atomically $ readTVar semaphore >>= \n -> check (n >= 2)
-- NOTE: this client runs indefinitely so it should be run within a context that won't
-- leak runaway threads
testClient :: TQueue IO (ServerOutput SimpleTx) -> TVar IO Int -> Connection -> IO ()
testClient queue semaphore cnx = do
atomically $ modifyTVar' semaphore (+ 1)
msg <- receiveData cnx
case Aeson.eitherDecode msg of
Left{} -> failure $ "Failed to decode message " <> show msg
Right TimedServerOutput{output = resp} -> do
atomically (writeTQueue queue resp)
testClient queue semaphore cnx
noop :: Applicative m => a -> m ()
noop = const $ pure ()
withClient :: HasCallStack => Int -> (Connection -> IO ()) -> IO ()
withClient port action = do
failAfter 5 retry
where
retry = runClient "127.0.0.1" port "/" action `catch` \(_ :: IOException) -> retry
-- | Mocked persistence handle which just does nothing.
mockPersistence :: Applicative m => PersistenceIncremental a m
mockPersistence =
PersistenceIncremental
{ append = \_ -> pure ()
, loadAll = pure []
}
| null | https://raw.githubusercontent.com/input-output-hk/hydra/7f5e25cb4e9dd1b12a016a6bab8f0e275f59ff62/hydra-node/test/Hydra/API/ServerSpec.hs | haskell | NOTE: this client runs indefinitely so it should be run within a context that won't
leak runaway threads
| Mocked persistence handle which just does nothing. | # LANGUAGE TypeApplications #
module Hydra.API.ServerSpec where
import Hydra.Prelude hiding (seq)
import Test.Hydra.Prelude
import Control.Exception (IOException)
import Control.Monad.Class.MonadSTM (
check,
modifyTVar',
newTQueue,
newTVarIO,
readTQueue,
tryReadTQueue,
writeTQueue,
)
import qualified Data.Aeson as Aeson
import Hydra.API.Server (Server (Server, sendOutput), withAPIServer)
import Hydra.API.ServerOutput (ServerOutput (Greetings, InvalidInput), TimedServerOutput (..), input)
import Hydra.Ledger.Simple (SimpleTx)
import Hydra.Logging (nullTracer, showLogsOnFailure)
import Hydra.Persistence (PersistenceIncremental (..), createPersistenceIncremental)
import Network.WebSockets (Connection, receiveData, runClient, sendBinaryData)
import Test.Hydra.Fixture (alice)
import Test.Network.Ports (withFreePort)
import Test.QuickCheck (checkCoverage, cover, generate)
import Test.QuickCheck.Monadic (monadicIO, monitor, pick, run)
spec :: Spec
spec = parallel $ do
it "greets" $ do
failAfter 5 $
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \_ -> do
withClient port $ \conn -> do
received <- receiveData conn
case Aeson.eitherDecode received of
Left{} -> failure $ "Failed to decode greeting " <> show received
Right TimedServerOutput{output = msg} -> msg `shouldBe` greeting
it "sends sendOutput to all connected clients" $ do
queue <- atomically newTQueue
showLogsOnFailure $ \tracer -> failAfter 5 $
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence tracer noop $ \Server{sendOutput} -> do
semaphore <- newTVarIO 0
withAsync
( concurrently_
(withClient port $ testClient queue semaphore)
(withClient port $ testClient queue semaphore)
)
$ \_ -> do
waitForClients semaphore
failAfter 1 $ atomically (replicateM 2 (readTQueue queue)) `shouldReturn` [greeting, greeting]
arbitraryMsg <- generate arbitrary
sendOutput arbitraryMsg
failAfter 1 $ atomically (replicateM 2 (readTQueue queue)) `shouldReturn` [arbitraryMsg, arbitraryMsg]
failAfter 1 $ atomically (tryReadTQueue queue) `shouldReturn` Nothing
it "sends all sendOutput history to all connected clients after a restart" $ do
showLogsOnFailure $ \tracer -> failAfter 5 $
withTempDir "ServerSpec" $ \tmpDir -> do
let persistentFile = tmpDir <> "/history"
arbitraryMsg <- generate arbitrary
persistence <- createPersistenceIncremental persistentFile
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice persistence tracer noop $ \Server{sendOutput} -> do
sendOutput arbitraryMsg
queue1 <- atomically newTQueue
queue2 <- atomically newTQueue
persistence' <- createPersistenceIncremental persistentFile
withFreePort $ \port -> do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice persistence' tracer noop $ \Server{sendOutput} -> do
semaphore <- newTVarIO 0
withAsync
( concurrently_
(withClient port $ testClient queue1 semaphore)
(withClient port $ testClient queue2 semaphore)
)
$ \_ -> do
waitForClients semaphore
failAfter 1 $ atomically (replicateM 3 (readTQueue queue1)) `shouldReturn` [greeting, arbitraryMsg, greeting]
failAfter 1 $ atomically (replicateM 3 (readTQueue queue2)) `shouldReturn` [greeting, arbitraryMsg, greeting]
sendOutput arbitraryMsg
failAfter 1 $ atomically (replicateM 1 (readTQueue queue1)) `shouldReturn` [arbitraryMsg]
failAfter 1 $ atomically (replicateM 1 (readTQueue queue2)) `shouldReturn` [arbitraryMsg]
failAfter 1 $ atomically (tryReadTQueue queue1) `shouldReturn` Nothing
it "echoes history (past outputs) to client upon reconnection" $
checkCoverage . monadicIO $ do
outputs <- pick arbitrary
monitor $ cover 0.1 (null outputs) "no message when reconnecting"
monitor $ cover 0.1 (length outputs == 1) "only one message when reconnecting"
monitor $ cover 1 (length outputs > 1) "more than one message when reconnecting"
run . failAfter 5 $ do
withFreePort $ \port ->
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \Server{sendOutput} -> do
mapM_ sendOutput outputs
withClient port $ \conn -> do
received <- replicateM (length outputs + 1) (receiveData conn)
case traverse Aeson.eitherDecode received of
Left{} -> failure $ "Failed to decode messages:\n" <> show received
Right timedOutputs ->
(output <$> timedOutputs) `shouldBe` greeting : outputs
it "sequence numbers are continuous and strictly monotonically increasing" $
monadicIO $ do
outputs :: [ServerOutput SimpleTx] <- pick arbitrary
run . failAfter 5 $ do
withFreePort $ \port ->
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \Server{sendOutput} -> do
mapM_ sendOutput outputs
withClient port $ \conn -> do
received <- replicateM (length outputs + 1) (receiveData conn)
case traverse Aeson.eitherDecode received of
Left{} -> failure $ "Failed to decode messages:\n" <> show received
Right (timedOutputs :: [TimedServerOutput SimpleTx]) ->
seq <$> timedOutputs `shouldSatisfy` strictlyMonotonic
it "sends an error when input cannot be decoded" $
failAfter 5 $
withFreePort $ \port -> sendsAnErrorWhenInputCannotBeDecoded port
strictlyMonotonic :: [Natural] -> Bool
strictlyMonotonic = \case
[] -> True
[_] -> True
(a : b : as) -> a + 1 == b && strictlyMonotonic (b : as)
sendsAnErrorWhenInputCannotBeDecoded :: Int -> Expectation
sendsAnErrorWhenInputCannotBeDecoded port = do
withAPIServer @SimpleTx "127.0.0.1" (fromIntegral port) alice mockPersistence nullTracer noop $ \_server -> do
withClient port $ \con -> do
_greeting :: ByteString <- receiveData con
sendBinaryData con invalidInput
msg <- receiveData con
case Aeson.eitherDecode @(TimedServerOutput SimpleTx) msg of
Left{} -> failure $ "Failed to decode output " <> show msg
Right TimedServerOutput{output = resp} -> resp `shouldSatisfy` isInvalidInput
where
invalidInput = "not a valid message"
isInvalidInput = \case
InvalidInput{input} -> input == invalidInput
_ -> False
greeting :: ServerOutput SimpleTx
greeting = Greetings alice
waitForClients :: (MonadSTM m, Ord a, Num a) => TVar m a -> m ()
waitForClients semaphore = atomically $ readTVar semaphore >>= \n -> check (n >= 2)
testClient :: TQueue IO (ServerOutput SimpleTx) -> TVar IO Int -> Connection -> IO ()
testClient queue semaphore cnx = do
atomically $ modifyTVar' semaphore (+ 1)
msg <- receiveData cnx
case Aeson.eitherDecode msg of
Left{} -> failure $ "Failed to decode message " <> show msg
Right TimedServerOutput{output = resp} -> do
atomically (writeTQueue queue resp)
testClient queue semaphore cnx
noop :: Applicative m => a -> m ()
noop = const $ pure ()
withClient :: HasCallStack => Int -> (Connection -> IO ()) -> IO ()
withClient port action = do
failAfter 5 retry
where
retry = runClient "127.0.0.1" port "/" action `catch` \(_ :: IOException) -> retry
mockPersistence :: Applicative m => PersistenceIncremental a m
mockPersistence =
PersistenceIncremental
{ append = \_ -> pure ()
, loadAll = pure []
}
|
400b60954dc5175e12b61afd1a05ac1371a6c97844b095d4d0edc860a51032d3 | static-analysis-engineering/codehawk | bCHARMTestSupport.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2023 Aarno Labs , LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2023 Aarno Labs, LLC
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.
============================================================================= *)
chlib
open CHLanguage
(* chutil *)
open CHTraceResult
(* xprlib *)
open XprTypes
(* bchlib *)
open BCHLibTypes
(* bchlibarm32 *)
open BCHARMTypes
module H = Hashtbl
type testdatatype_t =
| Tst_instrx_data of variable_t list * xpr_t list
| Tst_chif_conditionxprs of
arm_assembly_instruction_int * arm_assembly_instruction_int * xpr_t list
class testsupport_t: testsupport_int =
object (self)
val testdata = H.create 3
method request_instrx_data = H.add testdata "instrx_data" (H.create 3)
method request_chif_conditionxprs =
H.add testdata "chif_conditionxprs" (H.create 3)
method requested_instrx_data = H.mem testdata "instrx_data"
method requested_chif_conditionxprs = H.mem testdata "chif_conditionxprs"
method submit_instrx_data
(iaddr: doubleword_int)
(vars: variable_t list)
(xprs: xpr_t list) =
if H.mem testdata "instrx_data" then
H.add
(H.find testdata "instrx_data")
iaddr#to_hex_string
(Tst_instrx_data (vars, xprs))
method retrieve_instrx_data (iaddr: string) =
if H.mem testdata "instrx_data" then
if H.mem (H.find testdata "instrx_data") iaddr then
match (H.find (H.find testdata "instrx_data") iaddr) with
| Tst_instrx_data (vars, xprs) -> Ok (vars, xprs)
| _ -> Error ["retrieve_instrx_data: internal error"]
else
Error ["no data submitted for instrx_data for iaddr: " ^ iaddr]
else
Error ["no request made for instrx_data "]
method submit_chif_conditionxprs
(consumer: arm_assembly_instruction_int)
(producer: arm_assembly_instruction_int)
(xprs: xpr_t list) =
if H.mem testdata "chif_conditionxprs" then
H.add
(H.find testdata "chif_conditionxprs")
consumer#get_address#to_hex_string
(Tst_chif_conditionxprs (consumer, producer, xprs))
method retrieve_chif_conditionxprs (iaddr: string) =
if H.mem testdata "chif_conditionxprs" then
if H.mem (H.find testdata "chif_conditionxprs") iaddr then
match (H.find (H.find testdata "chif_conditionxprs") iaddr) with
| Tst_chif_conditionxprs (consumer, producer, xprs) ->
Ok (consumer, producer, xprs)
| _ -> Error ["retrieve_chif_conditionxprs: internal error"]
else
let keys = H.fold (fun k _ v -> k::v) (H.find testdata "chif_conditionxprs") [] in
Error [
"no data submitted for chif_conditionxprs for iaddr: "
^ iaddr
^ " (values found: ["
^ (String.concat "," keys)
^ ")]"]
else
Error ["no request made for chif_conditionxprs"]
end
let testsupport = new testsupport_t
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/e8fed9f226abe38578768968279c8242eb21fea9/CodeHawk/CHB/bchlibarm32/bCHARMTestSupport.ml | ocaml | chutil
xprlib
bchlib
bchlibarm32 | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2023 Aarno Labs , LLC
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
, 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 .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Binary Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2023 Aarno Labs, LLC
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.
============================================================================= *)
chlib
open CHLanguage
open CHTraceResult
open XprTypes
open BCHLibTypes
open BCHARMTypes
module H = Hashtbl
type testdatatype_t =
| Tst_instrx_data of variable_t list * xpr_t list
| Tst_chif_conditionxprs of
arm_assembly_instruction_int * arm_assembly_instruction_int * xpr_t list
class testsupport_t: testsupport_int =
object (self)
val testdata = H.create 3
method request_instrx_data = H.add testdata "instrx_data" (H.create 3)
method request_chif_conditionxprs =
H.add testdata "chif_conditionxprs" (H.create 3)
method requested_instrx_data = H.mem testdata "instrx_data"
method requested_chif_conditionxprs = H.mem testdata "chif_conditionxprs"
method submit_instrx_data
(iaddr: doubleword_int)
(vars: variable_t list)
(xprs: xpr_t list) =
if H.mem testdata "instrx_data" then
H.add
(H.find testdata "instrx_data")
iaddr#to_hex_string
(Tst_instrx_data (vars, xprs))
method retrieve_instrx_data (iaddr: string) =
if H.mem testdata "instrx_data" then
if H.mem (H.find testdata "instrx_data") iaddr then
match (H.find (H.find testdata "instrx_data") iaddr) with
| Tst_instrx_data (vars, xprs) -> Ok (vars, xprs)
| _ -> Error ["retrieve_instrx_data: internal error"]
else
Error ["no data submitted for instrx_data for iaddr: " ^ iaddr]
else
Error ["no request made for instrx_data "]
method submit_chif_conditionxprs
(consumer: arm_assembly_instruction_int)
(producer: arm_assembly_instruction_int)
(xprs: xpr_t list) =
if H.mem testdata "chif_conditionxprs" then
H.add
(H.find testdata "chif_conditionxprs")
consumer#get_address#to_hex_string
(Tst_chif_conditionxprs (consumer, producer, xprs))
method retrieve_chif_conditionxprs (iaddr: string) =
if H.mem testdata "chif_conditionxprs" then
if H.mem (H.find testdata "chif_conditionxprs") iaddr then
match (H.find (H.find testdata "chif_conditionxprs") iaddr) with
| Tst_chif_conditionxprs (consumer, producer, xprs) ->
Ok (consumer, producer, xprs)
| _ -> Error ["retrieve_chif_conditionxprs: internal error"]
else
let keys = H.fold (fun k _ v -> k::v) (H.find testdata "chif_conditionxprs") [] in
Error [
"no data submitted for chif_conditionxprs for iaddr: "
^ iaddr
^ " (values found: ["
^ (String.concat "," keys)
^ ")]"]
else
Error ["no request made for chif_conditionxprs"]
end
let testsupport = new testsupport_t
|
5c4af69de35a5b30c23d37b52eae67993e2ff98c927b37ce88ae69065d52d190 | graninas/Hydra | Interpreters.hs | module Hydra.Interpreters
( module X
) where
import Hydra.Core.Interpreters as X
import Hydra.Framework.Interpreters as X
| null | https://raw.githubusercontent.com/graninas/Hydra/60d591b1300528f5ffd93efa205012eebdd0286c/lib/hydra-church-free/src/Hydra/Interpreters.hs | haskell | module Hydra.Interpreters
( module X
) where
import Hydra.Core.Interpreters as X
import Hydra.Framework.Interpreters as X
|
|
84cb5ba11e0f7e84ff5f46d3493d83814073c2b3313827b364615731499e3479 | system-f/fp-course | StateTest.hs | # OPTIONS_GHC -fno - warn - type - defaults #
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Test.StateTest (
-- * Tests
test_State
, getTest
, putTest
, functorTest
, applicativeTest
, monadTest
, findMTest
, firstRepeatTest
, distinctTest
, isHappyTest
, execTest
, evalTest
-- * Runner
, test
) where
import Data.List (nub)
import qualified Prelude as P ((++))
import Test.Framework (TestTree, testCase, testGroup,
testProperty, test, (@?=))
import Test.Framework.Property (Unshowable(..))
import Course.Applicative (pure, (<*>))
import Course.Core
import Course.Functor ((<$>))
import Course.List (List (..), filter, flatMap, hlist, length,
listh, span, (++))
import Course.Monad
import Course.Optional (Optional (Empty, Full))
import Course.State (State (State), distinct, eval, exec, findM,
firstRepeat, get, isHappy, put, runState)
test_State :: TestTree
test_State =
testGroup "State" [
execTest
, evalTest
, getTest
, putTest
, functorTest
, applicativeTest
, monadTest
, findMTest
, firstRepeatTest
, distinctTest
, isHappyTest
]
execTest :: TestTree
execTest = testProperty "exec" $ \(Unshowable f) s ->
exec (State f) s == snd (runState (State (f :: Int -> (Int, Int))) (s :: Int))
evalTest :: TestTree
evalTest = testProperty "eval" $ \(Unshowable f) s ->
eval (State f) s == fst (runState (State (f :: Int -> (Int, Int))) (s :: Int))
getTest :: TestTree
getTest =
testCase "get" $ runState get 0 @?= (0,0)
putTest :: TestTree
putTest =
testCase "put" $ runState (put 1) 0 @?= ((),1)
functorTest :: TestTree
functorTest =
testCase "(<$>)" $
runState ((+1) <$> State (\s -> (9, s * 2))) 3 @?= (10,6)
applicativeTest :: TestTree
applicativeTest =
testGroup "Applicative" [
testCase "pure" $ runState (pure 2) 0 @?= (2,0)
, testCase "<*>" $ runState (pure (+1) <*> pure 0) 0 @?= (1,0)
, testCase "complicated <*>" $
let state = State (\s -> ((+3), s P.++ ["apple"])) <*> State (\s -> (7, s P.++ ["banana"]))
in runState state [] @?= (10,["apple","banana"])
]
monadTest :: TestTree
monadTest =
testGroup "Monad" [
testCase "(=<<)" $
runState (const (put 2) =<< put 1) 0 @?= ((),2)
, testCase "correctly produces new state and value" $
runState ((\a -> State (\s -> (a + s, 10 + s))) =<< State (\s -> (s * 2, 4 + s))) 2 @?= (10, 16)
, testCase "(>>=)" $
let modify f = State (\s -> ((), f s))
in runState (modify (+1) >>= \() -> modify (*2)) 7 @?= ((),16)
]
findMTest :: TestTree
findMTest =
testGroup "findM" [
testCase "find 'c' in 'a'..'h'" $
let p x = (\s -> const (pure (x == 'c')) =<< put (1+s)) =<< get
in runState (findM p $ listh ['a'..'h']) 0 @?= (Full 'c',3)
, testCase "find 'i' in 'a'..'h'" $
let p x = (\s -> const (pure (x == 'i')) =<< put (1+s)) =<< get
in runState (findM p $ listh ['a'..'h']) 0 @?= (Empty,8)
]
firstRepeatTest :: TestTree
firstRepeatTest =
testGroup "firstRepeat" [
testCase "'x' is the only repeat" $
firstRepeat (listh "abxdexghi") @?= Full 'x'
, testCase "'x' is the first repeat" $
firstRepeat (listh "abxdexgg") @?= Full 'x'
, testCase "no repeats" $
firstRepeat (listh ['a'..'z']) @?= Empty
, testProperty "finds repeats" $ \xs ->
case firstRepeat (xs :: List Integer) of
Empty ->
let xs' = hlist xs
in nub xs' == xs'
Full x -> length (filter (== x) xs) > 1
, testProperty "removing repeats matches nub" $ \xs ->
case firstRepeat (xs :: List Integer) of
Empty -> True
Full x ->
let
(l, rx :. rs) = span (/= x) xs
(l2, _) = span (/= x) rs
l3 = hlist (l ++ rx :. l2)
in
nub l3 == l3
]
distinctTest :: TestTree
distinctTest =
testGroup "distinct" [
testCase "No repeats" $
let cs = listh ['a'..'z'] in distinct cs @?= cs
, testCase "Every element repeated" $
let cs = listh ['a'..'z'] in distinct (flatMap (\x -> x :. x :. Nil) cs) @?= cs
, testProperty "No repeats after distinct" $ \xs ->
firstRepeat (distinct (xs :: List Integer)) == Empty
, testProperty "Every element repeated" $ \xs ->
distinct (xs :: List Integer) == distinct (flatMap (\x -> x :. x :. Nil) xs)
]
isHappyTest :: TestTree
isHappyTest =
testGroup "isHappy" [
testCase "4" $ isHappy 4 @?= False
, testCase "7" $ isHappy 7 @?= True
, testCase "42" $ isHappy 42 @?= False
, testCase "44" $ isHappy 44 @?= True
]
| null | https://raw.githubusercontent.com/system-f/fp-course/e929bc909a1701f67d218ed7974e9732d1e8dd32/src/Test/StateTest.hs | haskell | # LANGUAGE OverloadedStrings #
* Tests
* Runner | # OPTIONS_GHC -fno - warn - type - defaults #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
module Test.StateTest (
test_State
, getTest
, putTest
, functorTest
, applicativeTest
, monadTest
, findMTest
, firstRepeatTest
, distinctTest
, isHappyTest
, execTest
, evalTest
, test
) where
import Data.List (nub)
import qualified Prelude as P ((++))
import Test.Framework (TestTree, testCase, testGroup,
testProperty, test, (@?=))
import Test.Framework.Property (Unshowable(..))
import Course.Applicative (pure, (<*>))
import Course.Core
import Course.Functor ((<$>))
import Course.List (List (..), filter, flatMap, hlist, length,
listh, span, (++))
import Course.Monad
import Course.Optional (Optional (Empty, Full))
import Course.State (State (State), distinct, eval, exec, findM,
firstRepeat, get, isHappy, put, runState)
test_State :: TestTree
test_State =
testGroup "State" [
execTest
, evalTest
, getTest
, putTest
, functorTest
, applicativeTest
, monadTest
, findMTest
, firstRepeatTest
, distinctTest
, isHappyTest
]
execTest :: TestTree
execTest = testProperty "exec" $ \(Unshowable f) s ->
exec (State f) s == snd (runState (State (f :: Int -> (Int, Int))) (s :: Int))
evalTest :: TestTree
evalTest = testProperty "eval" $ \(Unshowable f) s ->
eval (State f) s == fst (runState (State (f :: Int -> (Int, Int))) (s :: Int))
getTest :: TestTree
getTest =
testCase "get" $ runState get 0 @?= (0,0)
putTest :: TestTree
putTest =
testCase "put" $ runState (put 1) 0 @?= ((),1)
functorTest :: TestTree
functorTest =
testCase "(<$>)" $
runState ((+1) <$> State (\s -> (9, s * 2))) 3 @?= (10,6)
applicativeTest :: TestTree
applicativeTest =
testGroup "Applicative" [
testCase "pure" $ runState (pure 2) 0 @?= (2,0)
, testCase "<*>" $ runState (pure (+1) <*> pure 0) 0 @?= (1,0)
, testCase "complicated <*>" $
let state = State (\s -> ((+3), s P.++ ["apple"])) <*> State (\s -> (7, s P.++ ["banana"]))
in runState state [] @?= (10,["apple","banana"])
]
monadTest :: TestTree
monadTest =
testGroup "Monad" [
testCase "(=<<)" $
runState (const (put 2) =<< put 1) 0 @?= ((),2)
, testCase "correctly produces new state and value" $
runState ((\a -> State (\s -> (a + s, 10 + s))) =<< State (\s -> (s * 2, 4 + s))) 2 @?= (10, 16)
, testCase "(>>=)" $
let modify f = State (\s -> ((), f s))
in runState (modify (+1) >>= \() -> modify (*2)) 7 @?= ((),16)
]
findMTest :: TestTree
findMTest =
testGroup "findM" [
testCase "find 'c' in 'a'..'h'" $
let p x = (\s -> const (pure (x == 'c')) =<< put (1+s)) =<< get
in runState (findM p $ listh ['a'..'h']) 0 @?= (Full 'c',3)
, testCase "find 'i' in 'a'..'h'" $
let p x = (\s -> const (pure (x == 'i')) =<< put (1+s)) =<< get
in runState (findM p $ listh ['a'..'h']) 0 @?= (Empty,8)
]
firstRepeatTest :: TestTree
firstRepeatTest =
testGroup "firstRepeat" [
testCase "'x' is the only repeat" $
firstRepeat (listh "abxdexghi") @?= Full 'x'
, testCase "'x' is the first repeat" $
firstRepeat (listh "abxdexgg") @?= Full 'x'
, testCase "no repeats" $
firstRepeat (listh ['a'..'z']) @?= Empty
, testProperty "finds repeats" $ \xs ->
case firstRepeat (xs :: List Integer) of
Empty ->
let xs' = hlist xs
in nub xs' == xs'
Full x -> length (filter (== x) xs) > 1
, testProperty "removing repeats matches nub" $ \xs ->
case firstRepeat (xs :: List Integer) of
Empty -> True
Full x ->
let
(l, rx :. rs) = span (/= x) xs
(l2, _) = span (/= x) rs
l3 = hlist (l ++ rx :. l2)
in
nub l3 == l3
]
distinctTest :: TestTree
distinctTest =
testGroup "distinct" [
testCase "No repeats" $
let cs = listh ['a'..'z'] in distinct cs @?= cs
, testCase "Every element repeated" $
let cs = listh ['a'..'z'] in distinct (flatMap (\x -> x :. x :. Nil) cs) @?= cs
, testProperty "No repeats after distinct" $ \xs ->
firstRepeat (distinct (xs :: List Integer)) == Empty
, testProperty "Every element repeated" $ \xs ->
distinct (xs :: List Integer) == distinct (flatMap (\x -> x :. x :. Nil) xs)
]
isHappyTest :: TestTree
isHappyTest =
testGroup "isHappy" [
testCase "4" $ isHappy 4 @?= False
, testCase "7" $ isHappy 7 @?= True
, testCase "42" $ isHappy 42 @?= False
, testCase "44" $ isHappy 44 @?= True
]
|
8807381a961c0a85c3a684066627d75c69a4b726cbfd68d4c5ee279e19033527 | kwanghoon/polyrpc | NameGen.hs | -- | Name generation
module NameGen where
import Control.Monad.State
import Naming
import Location
import Type
import Expr
import Pretty
import Debug.Trace
data NameState = NameState
{ varNames :: [ExprVar]
, tvarNames :: [TypeVar]
, lvarNames :: [LocationVar]
, indent :: Int -- This has no place here, but useful for debugging
, debug :: Bool
}
data EVar = EVar ExprVar
data TVar = TVar TypeVar
data LVar = LVar LocationVar
initialNameState :: NameState
initialNameState = NameState
EVar .
TVar .
LVar .
, indent = 0
, debug = False
}
where
namelist = [1..] >>= flip replicateM ['a'..'z']
type NameGen a = State NameState a
evalNameGen :: NameGen a -> a
evalNameGen = flip evalState initialNameState
-- | Create a fresh variable
freshVar :: NameGen ExprVar
freshVar = do
vvs <- gets varNames
case vvs of
(v:vs) -> do
modify $ \s -> s {varNames = vs}
return v
[] -> error "No fresh variable can be created."
-- | Create a fresh type variable
freshTypeVar :: NameGen TypeVar
freshTypeVar = do
vvs <- gets tvarNames
case vvs of
(v:vs) -> do
modify $ \s -> s {tvarNames = vs}
return v
[] -> error "No fresh type variable can be created."
freshExistsTypeVar = do
alpha <- freshTypeVar
return $ mkExists alpha
-- | Create a fresh location variable
freshLocationVar :: NameGen LocationVar
freshLocationVar = do
vvs <- gets lvarNames
case vvs of
(v:vs) -> do
modify $ \s -> s {lvarNames = vs}
return v
[] -> error "No fresh location variable can be created."
freshExistsLocationVar = do
l <- freshLocationVar
return $ mkExists l
setDebug :: Bool -> NameGen ()
setDebug flag = do
modify $ \s -> s {debug = flag}
return ()
| null | https://raw.githubusercontent.com/kwanghoon/polyrpc/6b68d7fd7f0743be55d467d4b722763dd49da474/app/bidi/NameGen.hs | haskell | | Name generation
This has no place here, but useful for debugging
| Create a fresh variable
| Create a fresh type variable
| Create a fresh location variable | module NameGen where
import Control.Monad.State
import Naming
import Location
import Type
import Expr
import Pretty
import Debug.Trace
data NameState = NameState
{ varNames :: [ExprVar]
, tvarNames :: [TypeVar]
, lvarNames :: [LocationVar]
, debug :: Bool
}
data EVar = EVar ExprVar
data TVar = TVar TypeVar
data LVar = LVar LocationVar
initialNameState :: NameState
initialNameState = NameState
EVar .
TVar .
LVar .
, indent = 0
, debug = False
}
where
namelist = [1..] >>= flip replicateM ['a'..'z']
type NameGen a = State NameState a
evalNameGen :: NameGen a -> a
evalNameGen = flip evalState initialNameState
freshVar :: NameGen ExprVar
freshVar = do
vvs <- gets varNames
case vvs of
(v:vs) -> do
modify $ \s -> s {varNames = vs}
return v
[] -> error "No fresh variable can be created."
freshTypeVar :: NameGen TypeVar
freshTypeVar = do
vvs <- gets tvarNames
case vvs of
(v:vs) -> do
modify $ \s -> s {tvarNames = vs}
return v
[] -> error "No fresh type variable can be created."
freshExistsTypeVar = do
alpha <- freshTypeVar
return $ mkExists alpha
freshLocationVar :: NameGen LocationVar
freshLocationVar = do
vvs <- gets lvarNames
case vvs of
(v:vs) -> do
modify $ \s -> s {lvarNames = vs}
return v
[] -> error "No fresh location variable can be created."
freshExistsLocationVar = do
l <- freshLocationVar
return $ mkExists l
setDebug :: Bool -> NameGen ()
setDebug flag = do
modify $ \s -> s {debug = flag}
return ()
|
e3750381890f9b0282ccd3f6bbe53db7f56b93e8880d4709e47d5ae96b9e03f0 | coalton-lang/coalton | package.lisp | (in-package #:cl-user)
(defpackage #:coalton
(:documentation "Public interface to COALTON.")
(:use) ; Keep the package clean!
(:import-from
#:common-lisp
#:in-package)
(:export
#:in-package)
(:export #:call-coalton-function)
(:export
#:coalton-toplevel
#:coalton-codegen
#:coalton-codegen-types
#:coalton-codegen-ast
#:coalton
#:declare
#:define
#:define-type
#:define-class
#:define-instance
#:repr
#:monomorphize
#:specialize
#:unable-to-codegen)
;; Early Types
(:export
#:-> #:→
#:=> #:⇒
#:∀
#:Unit
#:Void
#:Boolean #:True #:False
#:Char
#:U8
#:U16
#:U32
#:U64
#:I8
#:I16
#:I32
#:I64
#:Integer
#:IFix
#:UFix
#:Single-Float
#:Double-Float
#:String
#:Fraction
#:Arrow
#:List #:Cons #:Nil)
;; Primitive Syntax
(:export
#:fn #:λ
#:match
#:let
#:= ; Syntax
#:lisp
#:<- ; Syntax
#:_
#:return
#:the)
Macros
(:export
#:if
#:when
#:unless
#:and
#:or
#:cond
#:nest
#:pipe
#:.<
#:.>
#:make-list
#:to-boolean
#:do
#:progn
#:assert)
(:export
#:print-value-db
#:print-type-db
#:print-class-db
#:print-instance-db
#:print-specializations
#:lookup-code
#:lookup-class
#:lookup-fundeps
#:type-of
#:kind-of)
(:intern
#:seq
#:bind
#:Boolean/True
#:Boolean/False))
| null | https://raw.githubusercontent.com/coalton-lang/coalton/f4b810e78501345ae82a74eb4de761bd4b6924f0/src/package.lisp | lisp | Keep the package clean!
Early Types
Primitive Syntax
Syntax
Syntax | (in-package #:cl-user)
(defpackage #:coalton
(:documentation "Public interface to COALTON.")
(:import-from
#:common-lisp
#:in-package)
(:export
#:in-package)
(:export #:call-coalton-function)
(:export
#:coalton-toplevel
#:coalton-codegen
#:coalton-codegen-types
#:coalton-codegen-ast
#:coalton
#:declare
#:define
#:define-type
#:define-class
#:define-instance
#:repr
#:monomorphize
#:specialize
#:unable-to-codegen)
(:export
#:-> #:→
#:=> #:⇒
#:∀
#:Unit
#:Void
#:Boolean #:True #:False
#:Char
#:U8
#:U16
#:U32
#:U64
#:I8
#:I16
#:I32
#:I64
#:Integer
#:IFix
#:UFix
#:Single-Float
#:Double-Float
#:String
#:Fraction
#:Arrow
#:List #:Cons #:Nil)
(:export
#:fn #:λ
#:match
#:let
#:lisp
#:_
#:return
#:the)
Macros
(:export
#:if
#:when
#:unless
#:and
#:or
#:cond
#:nest
#:pipe
#:.<
#:.>
#:make-list
#:to-boolean
#:do
#:progn
#:assert)
(:export
#:print-value-db
#:print-type-db
#:print-class-db
#:print-instance-db
#:print-specializations
#:lookup-code
#:lookup-class
#:lookup-fundeps
#:type-of
#:kind-of)
(:intern
#:seq
#:bind
#:Boolean/True
#:Boolean/False))
|
e6afdf734b6b6db13e9330862669d80b2e86ac660e6ba4b06be6513d46f9df99 | ghcjs/jsaddle-dom | DocumentFragment.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.DocumentFragment
(newDocumentFragment, DocumentFragment(..), gTypeDocumentFragment,
IsDocumentFragment, toDocumentFragment)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/DocumentFragment Mozilla DocumentFragment documentation >
newDocumentFragment :: (MonadDOM m) => m DocumentFragment
newDocumentFragment
= liftDOM (DocumentFragment <$> new (jsg "DocumentFragment") ())
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/DocumentFragment.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.DocumentFragment
(newDocumentFragment, DocumentFragment(..), gTypeDocumentFragment,
IsDocumentFragment, toDocumentFragment)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/DocumentFragment Mozilla DocumentFragment documentation >
newDocumentFragment :: (MonadDOM m) => m DocumentFragment
newDocumentFragment
= liftDOM (DocumentFragment <$> new (jsg "DocumentFragment") ())
|
fefbb7b5ce9fc9d2b68833baf71b6454f6925ca8a0c04fe14b5831ea5d16205e | rizo/snowflake-os | trie.ml |
module type Ordering =
sig
type t
type index
type key
val to_index : t -> index list
val from_index : index list -> t
end
module Make = functor(O : Ordering) ->
struct
type elt = O.t
type index = O.index
type key = O.key
type t = {
mutable children : (index, t) Hashtbl.t;
mutable key : key option
}
let
rec empty () = { children = Hashtbl.create 3; key = None }
and insert e = insert_direct (O.to_index e)
and delete e = delete_direct (O.to_index e)
and restrict e = restrict_direct (O.to_index e)
and find_empty trie = match trie.key with
Some k -> k
| None -> raise Not_found
and find e = find_direct (O.to_index e)
Find the trie at idx , and then read its empty string 's key .
and find_direct idx trie = find_empty (restrict_direct idx trie)
and insert_direct idx k = replace_direct idx (Some k)
(* This doesn't delete unneeded nodes, but never mind. *)
and delete_direct idx = replace_direct idx None
and replace_direct idx k trie =
let traverse t i = try
Hashtbl.find t.children i
with Not_found ->
let t' = empty () in
Hashtbl.add t.children i t';
t'
in let node = List.fold_left traverse trie idx in
node.key <- k
and restrict_direct idx trie =
let traverse t i = Hashtbl.find t.children i in
List.fold_left traverse trie idx
and iter f trie =
let recurse a b = iter f b in
Hashtbl.iter recurse trie.children;
match trie.key with
Some k -> f trie
| None -> ()
and iter_string f trie = iter_string_from [] f trie
and iter_string_from rev_prefix f trie =
let recurse a b = iter_string_from (a::rev_prefix) f b in
Hashtbl.iter recurse trie.children;
match trie.key with
Some k -> f (O.from_index (List.rev rev_prefix))
| None -> ()
and fold f trie =
let rec fold list trie =
Hashtbl.fold (fun index t accu -> let index = list @ [index] in (f (O.from_index index)) :: (fold index t) @ accu) trie.children []
in fold [] trie
end
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/kernel/trie.ml | ocaml | This doesn't delete unneeded nodes, but never mind. |
module type Ordering =
sig
type t
type index
type key
val to_index : t -> index list
val from_index : index list -> t
end
module Make = functor(O : Ordering) ->
struct
type elt = O.t
type index = O.index
type key = O.key
type t = {
mutable children : (index, t) Hashtbl.t;
mutable key : key option
}
let
rec empty () = { children = Hashtbl.create 3; key = None }
and insert e = insert_direct (O.to_index e)
and delete e = delete_direct (O.to_index e)
and restrict e = restrict_direct (O.to_index e)
and find_empty trie = match trie.key with
Some k -> k
| None -> raise Not_found
and find e = find_direct (O.to_index e)
Find the trie at idx , and then read its empty string 's key .
and find_direct idx trie = find_empty (restrict_direct idx trie)
and insert_direct idx k = replace_direct idx (Some k)
and delete_direct idx = replace_direct idx None
and replace_direct idx k trie =
let traverse t i = try
Hashtbl.find t.children i
with Not_found ->
let t' = empty () in
Hashtbl.add t.children i t';
t'
in let node = List.fold_left traverse trie idx in
node.key <- k
and restrict_direct idx trie =
let traverse t i = Hashtbl.find t.children i in
List.fold_left traverse trie idx
and iter f trie =
let recurse a b = iter f b in
Hashtbl.iter recurse trie.children;
match trie.key with
Some k -> f trie
| None -> ()
and iter_string f trie = iter_string_from [] f trie
and iter_string_from rev_prefix f trie =
let recurse a b = iter_string_from (a::rev_prefix) f b in
Hashtbl.iter recurse trie.children;
match trie.key with
Some k -> f (O.from_index (List.rev rev_prefix))
| None -> ()
and fold f trie =
let rec fold list trie =
Hashtbl.fold (fun index t accu -> let index = list @ [index] in (f (O.from_index index)) :: (fold index t) @ accu) trie.children []
in fold [] trie
end
|
a0dc99e911ebb1d9a2c4d1d876da2d841fe26930d8eef9ebd5320568cb1de9e4 | Capelare/ejercicios-haskell | examen-septiembre-2010.hs |
Problema 1
¿ Cuáles son siguientes funciones ?
a ) fun1 f g = map ( f . )
Problema 1
¿Cuáles son los tipos polimórficos de las siguientes funciones?
a) fun1 f g = map (f . g)
-}
fun1 :: (b -> c) -> (a -> b) -> [a] -> [c]
b ) fun2 f g = ( map f ) .
b) fun2 f g = (map f) . g
-}
fun2 :: (b -> c) -> (a -> [b]) -> a -> [c]
c ) fun3 f p q xs = [ p ( f x ) | x < - xs , q x ]
c) fun3 f p q xs = [p (f x) | x <- xs, q x]
-}
fun3 :: (a -> b) -> (b -> c) -> (a -> Bool) -> [a] -> [c]
Problema 2
Define una función cortesPropios que dada una lista xs devuelva todos los pares ( ys , zs )
de listas no vacías tales que ys++zs = = xs . :
[ 1 .. 4 ] = = > [ ( [ 1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4 ] ) ]
Problema 2
Define una función cortesPropios que dada una lista xs devuelva todos los pares (ys,zs)
de listas no vacías tales que ys++zs == xs. Por ejemplo:
cortesPropios [1..4] ==> [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]
-}
cortesPropios :: [a] -> [([a],[a])]
cortesPropios [] = []
cortesPropios [x] = []
cortesPropios | null | https://raw.githubusercontent.com/Capelare/ejercicios-haskell/84952b50797f8c1624f95877642c5c05593b2f88/miguel/examen-septiembre-2010.hs | haskell |
Problema 1
¿ Cuáles son siguientes funciones ?
a ) fun1 f g = map ( f . )
Problema 1
¿Cuáles son los tipos polimórficos de las siguientes funciones?
a) fun1 f g = map (f . g)
-}
fun1 :: (b -> c) -> (a -> b) -> [a] -> [c]
b ) fun2 f g = ( map f ) .
b) fun2 f g = (map f) . g
-}
fun2 :: (b -> c) -> (a -> [b]) -> a -> [c]
c ) fun3 f p q xs = [ p ( f x ) | x < - xs , q x ]
c) fun3 f p q xs = [p (f x) | x <- xs, q x]
-}
fun3 :: (a -> b) -> (b -> c) -> (a -> Bool) -> [a] -> [c]
Problema 2
Define una función cortesPropios que dada una lista xs devuelva todos los pares ( ys , zs )
de listas no vacías tales que ys++zs = = xs . :
[ 1 .. 4 ] = = > [ ( [ 1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4 ] ) ]
Problema 2
Define una función cortesPropios que dada una lista xs devuelva todos los pares (ys,zs)
de listas no vacías tales que ys++zs == xs. Por ejemplo:
cortesPropios [1..4] ==> [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]
-}
cortesPropios :: [a] -> [([a],[a])]
cortesPropios [] = []
cortesPropios [x] = []
cortesPropios |
|
dda08b908290a61883da6b3b1ca69998eb3a50e69cee599b92482e023f347123 | ijvcms/chuanqi_dev | scene_send_lib_copy.erl | %%%-------------------------------------------------------------------
@author zhengsiying
( C ) 2015 , < COMPANY >
%%% @doc
%%%
%%% @end
Created : 09 . 2015 下午4:46
%%%-------------------------------------------------------------------
-module(scene_send_lib_copy).
-include("common.hrl").
-include("record.hrl").
-include("proto.hrl").
-include("cache.hrl").
-include("config.hrl").
%% API
-export([
send_scene_info_data/3,
send_scene_info_data_all/1,
send_scene_move_info/2,
send_screen_player/2,
send_player_id/3,
send_lists_11020/1,
send_lists_12010/1,
get_single_boss_result/1,
add_single_boss_left_time/2,
stay_scene/1
]).
-export([
do_send_scene_info_data/3,
do_send_scene_info_data_all/4,
do_send_scene_move_info/2,
do_send_screen/6,
send_screen/3,
do_get_single_boss_result/2,
do_add_single_boss_left_time/3,
stay_scene_local/1,
get_scene_guise/3,
do_get_scene_guise/3
]).
%% 获取玩家所在场景的对象信息
send_scene_info_data(ScenePid, PlayerPid, SceneObj) ->
gen_server2:apply_async(ScenePid, {?MODULE, do_send_scene_info_data, [PlayerPid, SceneObj]}).
%% 获取玩家所在场景的对象信息
do_send_scene_info_data(SceneState, PlayerPid, SceneObj) ->
Data = scene_send_lib:make_rep_change_scene([SceneObj], #rep_change_scene{scene_id = SceneState#scene_state.scene_id}),
net_send:send_to_client(PlayerPid, 11101, #req_scene_pic{scene_pic = SceneState#scene_state.scene_pic}),
net_send:send_to_client(PlayerPid, 11001, Data).
%% 获取玩家所在场景的对象信息
get_scene_guise(ScenePid, PlayerPid, PlayerId) ->
try
gen_server2:apply_async(ScenePid, {?MODULE, do_get_scene_guise, [PlayerPid, PlayerId]})
catch
Err:Info ->
?ERR("Err ~p ~p", [{Err, Info}, {ScenePid, PlayerPid, PlayerId}]),
Data = #rep_guise_list{},
%% ?INFO("11053 ~p ~p", [Data, length(GuiseList)]),
net_send:send_to_client(PlayerPid, 11053, Data)
end.
%% 获取玩家所在场景的对象信息
do_get_scene_guise(SceneState, PlayerPid, PlayerId) ->
MyObj = scene_base_lib:get_scene_obj_state(SceneState, ?OBJ_TYPE_PLAYER, PlayerId),
case MyObj of
null ->
?ERR("sceneid: ~p", [{SceneState#scene_state.scene_id, PlayerId}]);
_ ->
#scene_obj_state{x = MX, y = MY} = MyObj,
ObjList = scene_base_lib:do_get_scene_obj_list(SceneState, [?OBJ_TYPE_PLAYER, ?OBJ_TYPE_MONSTER]),
F = fun(X, {TempGuiseList, TempMonsterList}) ->
#scene_obj_state{x = X1, y = Y1, guise = Guise, monster_res_id = MonsterResId, obj_type = ObjType} = X,
case ObjType of
?OBJ_TYPE_PLAYER ->
TempGuise = {util_math:get_distance_set({MX, MY}, {X1, Y1}), Guise},
{[TempGuise | TempGuiseList], TempMonsterList};
_ ->
{TempGuiseList, [MonsterResId | TempMonsterList]}
end
end,
{GuiseList, MonsterResList} = lists:foldl(F, {[], []}, ObjList),
GuiseList1 = lists:keysort(1, GuiseList),
{WeaponList, ClothesList, WingList} = get_guise_list(GuiseList1, [], [], []),
Data = #rep_guise_list{
weapon_list = WeaponList,
clothes_list = ClothesList,
wing_list = WingList,
monster_list = MonsterResList
},
?INFO("11053 ~p ~p", [Data, length(GuiseList)]),
net_send:send_to_client(PlayerPid, 11053, Data)
end.
%% 获取材质列表
get_guise_list([], WeaponList, ClothesList, WingList) ->
{WeaponList, ClothesList, WingList};
get_guise_list([{_, Guise} | GuiseList], WeaponList, ClothesList, WingList) ->
#guise_state{weapon = Weapon, clothes = Clothes, wing = Wing} = Guise,
WeaponList1 = case Weapon =:= 0 orelse lists:member(Weapon, WeaponList) of
true ->
WeaponList;
_ ->
[Weapon | WeaponList]
end,
ClothesList1 = case Clothes =:= 0 orelse lists:member(Clothes, ClothesList) of
true ->
ClothesList;
_ ->
[Clothes | ClothesList]
end,
WingList1 = case Wing =:= 0 orelse lists:member(Wing, WingList) of
true ->
WingList;
_ ->
[Wing | WingList]
end,
get_guise_list(GuiseList, WeaponList1, ClothesList1, WingList1).
%% 发送周围玩家给玩家自己, 把自己信息告诉周围的玩家
send_scene_info_data_all(PlayerState) ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_send_scene_info_data_all, [PlayerState#player_state.socket, PlayerState#player_state.scene_obj, PlayerState#player_state.player_id]}).
%% 发送周围玩家给玩家自己, 把自己信息告诉周围的玩家
do_send_scene_info_data_all(SceneState, Socket, SceneObj, PlayerId) ->
case scene_base_lib:do_get_screen_obj(SceneState, ?OBJ_TYPE_PLAYER, PlayerId, false) of
[] ->
skip;
ObjList ->
{Data, TempNum} = scene_send_lib:make_rep_obj_enter(ObjList, {#rep_obj_enter{}, 0}),
case TempNum > 0 of
true ->
net_send:send_to_client(Socket, 11005, Data);
_ ->
skip
end,
TempList = [X || X <- ObjList, X#scene_obj_state.obj_type =:= ?OBJ_TYPE_PLAYER],
scene_send_lib:send_enter_screen(TempList, SceneObj, false),
game_obj_lib:set_monster_targer(SceneState, ?OBJ_TYPE_PLAYER, PlayerId, ObjList)
end.
%%发送 11020列表
send_lists_11020([{PlayerId, Data} | H]) ->
Data1 = scene_send_lib:make_rep_obj_often_update(Data, #rep_obj_often_update{}),
send_player_id(PlayerId, 11020, Data1),
send_lists_11020(H);
send_lists_11020([]) ->
[].
%% 发送12010列表
send_lists_12010([{PlayerId, TargetList, BuffList, MoveList, KnockBackList} | H]) ->
Data = #rep_trigger_skill{
target_list = TargetList,
buff_list = BuffList,
move_list = MoveList,
knockback_list = KnockBackList
},
send_player_id(PlayerId, 12010, Data),
send_lists_12010(H);
send_lists_12010([]) ->
[].
get_single_boss_result(PlayerState) ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_get_single_boss_result, [PlayerState]}).
do_get_single_boss_result(SceneState, PlayerState) ->
case SceneState#scene_state.instance_state of
#instance_single_boss_state{
enter_time = EnterTime,
boss_count = BossCount,
kill_boss_count = KillBossCount
} ->
#player_state{db_player_base = #db_player_base{instance_left_time = LeftTimeOld}} = PlayerState,
CurTime = util_date:unixtime(),
LeftTime = erlang:max(LeftTimeOld - (CurTime - EnterTime), 0),
Rep = #rep_single_boss_result{left_time = LeftTime, left_boss = BossCount - KillBossCount},
? ~p " , [ Rep ] ) ,
scene_send_lib:do_send_scene(SceneState, 11045, Rep);
_ ->
skip
end.
%% 个人boss副本,增加副本时间
add_single_boss_left_time(PlayerState, Time) ->
case scene_config:get(PlayerState#player_state.scene_id) of
#scene_conf{type = ?SCENE_TYPE_INSTANCE} ->
InstanceConf = instance_config:get(PlayerState#player_state.scene_id),
case InstanceConf#instance_conf.type =:= 9 of
true ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_add_single_boss_left_time, [PlayerState, Time]});
false ->
skip
end;
_ ->
skip
end.
do_add_single_boss_left_time(SceneState, PlayerState, Time) ->
InstanceState = SceneState#scene_state.instance_state,
case InstanceState of
#instance_single_boss_state{} ->
#player_state{db_player_base = #db_player_base{instance_left_time = LeftTimeOld}} = PlayerState,
NewInstanceState = InstanceState#instance_single_boss_state{left_time = LeftTimeOld + Time},
NewSceneState = SceneState#scene_state{instance_state = NewInstanceState},
do_get_single_boss_result(NewSceneState, PlayerState),
{ok, NewSceneState};
_ ->
skip
end.
%% 副本通关后继续留在副本中
stay_scene(PlayerState) ->
SceneId = PlayerState#player_state.scene_id,
case scene_config:get(SceneId) of
#scene_conf{type = ?SCENE_TYPE_INSTANCE} ->
InstanceConf = instance_config : get(SceneId ) ,
case not instance_base_lib:is_multiple_instance(SceneId) of
true ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, stay_scene_local, []});
false ->
skip
end;
_ ->
skip
end.
stay_scene_local(SceneState) ->
CurTime = util_date:unixtime(),
{ok, SceneState#scene_state{close_time = CurTime + 300}}.
%% ====================================================================
Internal functions 发送给场景中的玩家
%% ====================================================================
send_screen_player(ObjList, Bin) ->
[begin
case Obj#scene_obj_state.obj_type of
?OBJ_TYPE_PLAYER ->
send_scene_move_info(Obj#scene_obj_state.obj_id, Bin);
_ ->
skip
end
end || Obj <- ObjList].
%% 全屏广播 包含自己
send_screen(PlayerState, Cmd, Data) ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_send_screen, [?OBJ_TYPE_PLAYER, PlayerState#player_state.player_id, true, Cmd, Data]}).
%% 全屏广播(不包括自己)
do_send_screen(SceneState, ObjType, ObjId, IncludeSelf, Cmd, Data) ->
case scene_base_lib:do_get_screen_biont(SceneState, ObjType, ObjId, IncludeSelf) of
[] ->
skip;
ObjList ->
{ok, Bin} = pt:write_cmd(Cmd, Data),
Bin1 = pt:pack(Cmd, Bin),
F = fun(ObjState) ->
case ObjState#scene_obj_state.obj_type of
?OBJ_TYPE_PLAYER ->
%% ?INFO("send player: ~p: ~p", [ObjState#scene_obj_state.obj_id, Data]),
send_scene_move_info(ObjState#scene_obj_state.obj_id, Bin1);
_ ->
skip
end
end,
[F(X) || X <- ObjList]
end.
send_player_id(PlayerId, Cmd, Data) ->
{ok, Bin} = pt:write_cmd(Cmd, Data),
Bin1 = pt:pack(Cmd, Bin),
send_scene_move_info(PlayerId, Bin1).
发送移动信息
send_scene_move_info(Playerid, Bin) ->
net_send:send_one(Playerid, Bin).
发送移动信息
do_send_scene_move_info(PlayerState, Bin) ->
case PlayerState#player_state.is_load_over of
false ->
skip;
_ ->
net_send:send_one(PlayerState#player_state.socket, Bin)
end.
| null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/business/scene/scene_send_lib_copy.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
获取玩家所在场景的对象信息
获取玩家所在场景的对象信息
获取玩家所在场景的对象信息
?INFO("11053 ~p ~p", [Data, length(GuiseList)]),
获取玩家所在场景的对象信息
获取材质列表
发送周围玩家给玩家自己, 把自己信息告诉周围的玩家
发送周围玩家给玩家自己, 把自己信息告诉周围的玩家
发送 11020列表
发送12010列表
个人boss副本,增加副本时间
副本通关后继续留在副本中
====================================================================
====================================================================
全屏广播 包含自己
全屏广播(不包括自己)
?INFO("send player: ~p: ~p", [ObjState#scene_obj_state.obj_id, Data]), | @author zhengsiying
( C ) 2015 , < COMPANY >
Created : 09 . 2015 下午4:46
-module(scene_send_lib_copy).
-include("common.hrl").
-include("record.hrl").
-include("proto.hrl").
-include("cache.hrl").
-include("config.hrl").
-export([
send_scene_info_data/3,
send_scene_info_data_all/1,
send_scene_move_info/2,
send_screen_player/2,
send_player_id/3,
send_lists_11020/1,
send_lists_12010/1,
get_single_boss_result/1,
add_single_boss_left_time/2,
stay_scene/1
]).
-export([
do_send_scene_info_data/3,
do_send_scene_info_data_all/4,
do_send_scene_move_info/2,
do_send_screen/6,
send_screen/3,
do_get_single_boss_result/2,
do_add_single_boss_left_time/3,
stay_scene_local/1,
get_scene_guise/3,
do_get_scene_guise/3
]).
send_scene_info_data(ScenePid, PlayerPid, SceneObj) ->
gen_server2:apply_async(ScenePid, {?MODULE, do_send_scene_info_data, [PlayerPid, SceneObj]}).
do_send_scene_info_data(SceneState, PlayerPid, SceneObj) ->
Data = scene_send_lib:make_rep_change_scene([SceneObj], #rep_change_scene{scene_id = SceneState#scene_state.scene_id}),
net_send:send_to_client(PlayerPid, 11101, #req_scene_pic{scene_pic = SceneState#scene_state.scene_pic}),
net_send:send_to_client(PlayerPid, 11001, Data).
get_scene_guise(ScenePid, PlayerPid, PlayerId) ->
try
gen_server2:apply_async(ScenePid, {?MODULE, do_get_scene_guise, [PlayerPid, PlayerId]})
catch
Err:Info ->
?ERR("Err ~p ~p", [{Err, Info}, {ScenePid, PlayerPid, PlayerId}]),
Data = #rep_guise_list{},
net_send:send_to_client(PlayerPid, 11053, Data)
end.
do_get_scene_guise(SceneState, PlayerPid, PlayerId) ->
MyObj = scene_base_lib:get_scene_obj_state(SceneState, ?OBJ_TYPE_PLAYER, PlayerId),
case MyObj of
null ->
?ERR("sceneid: ~p", [{SceneState#scene_state.scene_id, PlayerId}]);
_ ->
#scene_obj_state{x = MX, y = MY} = MyObj,
ObjList = scene_base_lib:do_get_scene_obj_list(SceneState, [?OBJ_TYPE_PLAYER, ?OBJ_TYPE_MONSTER]),
F = fun(X, {TempGuiseList, TempMonsterList}) ->
#scene_obj_state{x = X1, y = Y1, guise = Guise, monster_res_id = MonsterResId, obj_type = ObjType} = X,
case ObjType of
?OBJ_TYPE_PLAYER ->
TempGuise = {util_math:get_distance_set({MX, MY}, {X1, Y1}), Guise},
{[TempGuise | TempGuiseList], TempMonsterList};
_ ->
{TempGuiseList, [MonsterResId | TempMonsterList]}
end
end,
{GuiseList, MonsterResList} = lists:foldl(F, {[], []}, ObjList),
GuiseList1 = lists:keysort(1, GuiseList),
{WeaponList, ClothesList, WingList} = get_guise_list(GuiseList1, [], [], []),
Data = #rep_guise_list{
weapon_list = WeaponList,
clothes_list = ClothesList,
wing_list = WingList,
monster_list = MonsterResList
},
?INFO("11053 ~p ~p", [Data, length(GuiseList)]),
net_send:send_to_client(PlayerPid, 11053, Data)
end.
get_guise_list([], WeaponList, ClothesList, WingList) ->
{WeaponList, ClothesList, WingList};
get_guise_list([{_, Guise} | GuiseList], WeaponList, ClothesList, WingList) ->
#guise_state{weapon = Weapon, clothes = Clothes, wing = Wing} = Guise,
WeaponList1 = case Weapon =:= 0 orelse lists:member(Weapon, WeaponList) of
true ->
WeaponList;
_ ->
[Weapon | WeaponList]
end,
ClothesList1 = case Clothes =:= 0 orelse lists:member(Clothes, ClothesList) of
true ->
ClothesList;
_ ->
[Clothes | ClothesList]
end,
WingList1 = case Wing =:= 0 orelse lists:member(Wing, WingList) of
true ->
WingList;
_ ->
[Wing | WingList]
end,
get_guise_list(GuiseList, WeaponList1, ClothesList1, WingList1).
send_scene_info_data_all(PlayerState) ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_send_scene_info_data_all, [PlayerState#player_state.socket, PlayerState#player_state.scene_obj, PlayerState#player_state.player_id]}).
do_send_scene_info_data_all(SceneState, Socket, SceneObj, PlayerId) ->
case scene_base_lib:do_get_screen_obj(SceneState, ?OBJ_TYPE_PLAYER, PlayerId, false) of
[] ->
skip;
ObjList ->
{Data, TempNum} = scene_send_lib:make_rep_obj_enter(ObjList, {#rep_obj_enter{}, 0}),
case TempNum > 0 of
true ->
net_send:send_to_client(Socket, 11005, Data);
_ ->
skip
end,
TempList = [X || X <- ObjList, X#scene_obj_state.obj_type =:= ?OBJ_TYPE_PLAYER],
scene_send_lib:send_enter_screen(TempList, SceneObj, false),
game_obj_lib:set_monster_targer(SceneState, ?OBJ_TYPE_PLAYER, PlayerId, ObjList)
end.
send_lists_11020([{PlayerId, Data} | H]) ->
Data1 = scene_send_lib:make_rep_obj_often_update(Data, #rep_obj_often_update{}),
send_player_id(PlayerId, 11020, Data1),
send_lists_11020(H);
send_lists_11020([]) ->
[].
send_lists_12010([{PlayerId, TargetList, BuffList, MoveList, KnockBackList} | H]) ->
Data = #rep_trigger_skill{
target_list = TargetList,
buff_list = BuffList,
move_list = MoveList,
knockback_list = KnockBackList
},
send_player_id(PlayerId, 12010, Data),
send_lists_12010(H);
send_lists_12010([]) ->
[].
get_single_boss_result(PlayerState) ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_get_single_boss_result, [PlayerState]}).
do_get_single_boss_result(SceneState, PlayerState) ->
case SceneState#scene_state.instance_state of
#instance_single_boss_state{
enter_time = EnterTime,
boss_count = BossCount,
kill_boss_count = KillBossCount
} ->
#player_state{db_player_base = #db_player_base{instance_left_time = LeftTimeOld}} = PlayerState,
CurTime = util_date:unixtime(),
LeftTime = erlang:max(LeftTimeOld - (CurTime - EnterTime), 0),
Rep = #rep_single_boss_result{left_time = LeftTime, left_boss = BossCount - KillBossCount},
? ~p " , [ Rep ] ) ,
scene_send_lib:do_send_scene(SceneState, 11045, Rep);
_ ->
skip
end.
add_single_boss_left_time(PlayerState, Time) ->
case scene_config:get(PlayerState#player_state.scene_id) of
#scene_conf{type = ?SCENE_TYPE_INSTANCE} ->
InstanceConf = instance_config:get(PlayerState#player_state.scene_id),
case InstanceConf#instance_conf.type =:= 9 of
true ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_add_single_boss_left_time, [PlayerState, Time]});
false ->
skip
end;
_ ->
skip
end.
do_add_single_boss_left_time(SceneState, PlayerState, Time) ->
InstanceState = SceneState#scene_state.instance_state,
case InstanceState of
#instance_single_boss_state{} ->
#player_state{db_player_base = #db_player_base{instance_left_time = LeftTimeOld}} = PlayerState,
NewInstanceState = InstanceState#instance_single_boss_state{left_time = LeftTimeOld + Time},
NewSceneState = SceneState#scene_state{instance_state = NewInstanceState},
do_get_single_boss_result(NewSceneState, PlayerState),
{ok, NewSceneState};
_ ->
skip
end.
stay_scene(PlayerState) ->
SceneId = PlayerState#player_state.scene_id,
case scene_config:get(SceneId) of
#scene_conf{type = ?SCENE_TYPE_INSTANCE} ->
InstanceConf = instance_config : get(SceneId ) ,
case not instance_base_lib:is_multiple_instance(SceneId) of
true ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, stay_scene_local, []});
false ->
skip
end;
_ ->
skip
end.
stay_scene_local(SceneState) ->
CurTime = util_date:unixtime(),
{ok, SceneState#scene_state{close_time = CurTime + 300}}.
Internal functions 发送给场景中的玩家
send_screen_player(ObjList, Bin) ->
[begin
case Obj#scene_obj_state.obj_type of
?OBJ_TYPE_PLAYER ->
send_scene_move_info(Obj#scene_obj_state.obj_id, Bin);
_ ->
skip
end
end || Obj <- ObjList].
send_screen(PlayerState, Cmd, Data) ->
gen_server2:apply_async(PlayerState#player_state.scene_pid, {?MODULE, do_send_screen, [?OBJ_TYPE_PLAYER, PlayerState#player_state.player_id, true, Cmd, Data]}).
do_send_screen(SceneState, ObjType, ObjId, IncludeSelf, Cmd, Data) ->
case scene_base_lib:do_get_screen_biont(SceneState, ObjType, ObjId, IncludeSelf) of
[] ->
skip;
ObjList ->
{ok, Bin} = pt:write_cmd(Cmd, Data),
Bin1 = pt:pack(Cmd, Bin),
F = fun(ObjState) ->
case ObjState#scene_obj_state.obj_type of
?OBJ_TYPE_PLAYER ->
send_scene_move_info(ObjState#scene_obj_state.obj_id, Bin1);
_ ->
skip
end
end,
[F(X) || X <- ObjList]
end.
send_player_id(PlayerId, Cmd, Data) ->
{ok, Bin} = pt:write_cmd(Cmd, Data),
Bin1 = pt:pack(Cmd, Bin),
send_scene_move_info(PlayerId, Bin1).
发送移动信息
send_scene_move_info(Playerid, Bin) ->
net_send:send_one(Playerid, Bin).
发送移动信息
do_send_scene_move_info(PlayerState, Bin) ->
case PlayerState#player_state.is_load_over of
false ->
skip;
_ ->
net_send:send_one(PlayerState#player_state.socket, Bin)
end.
|
417c28be06acb476b0a8a060b35879bc0b43a41dfd7a36525718e7fdd9f3d55c | javalib-team/sawja | sawjap.ml | open! Javalib_pack
open Sawja_pack
module IR = JBir
let transform folding cm c =
IR.transform cm c ~folding
let print_class folding i_or_c =
Javalib.JPrint.print_class
(Javalib.map_interface_or_class_context
(transform folding)
i_or_c)
(IR.print ~show_type:false)
stdout
let () =
let input_files = ref [] in
let folding = ref JBir.FoldOrFail in
Arg.parse
[("--fold",
Arg.Symbol
(["yes"; "no"; "try"],
function
| "yes" -> folding := JBir.FoldOrFail
| "no" -> folding := JBir.DoNotFold
| "try" -> folding := JBir.FoldIfPossible
| _ -> assert false),
"Disable/enable constructor folding")]
(fun filename -> input_files := filename :: !input_files)
"sawjap [--do-not-fold] <file>";
List.iter (Javalib.iter (print_class !folding)) !input_files
| null | https://raw.githubusercontent.com/javalib-team/sawja/3c7dedd5819e482ad4cb92af0660d58279a89779/test/sawjap.ml | ocaml | open! Javalib_pack
open Sawja_pack
module IR = JBir
let transform folding cm c =
IR.transform cm c ~folding
let print_class folding i_or_c =
Javalib.JPrint.print_class
(Javalib.map_interface_or_class_context
(transform folding)
i_or_c)
(IR.print ~show_type:false)
stdout
let () =
let input_files = ref [] in
let folding = ref JBir.FoldOrFail in
Arg.parse
[("--fold",
Arg.Symbol
(["yes"; "no"; "try"],
function
| "yes" -> folding := JBir.FoldOrFail
| "no" -> folding := JBir.DoNotFold
| "try" -> folding := JBir.FoldIfPossible
| _ -> assert false),
"Disable/enable constructor folding")]
(fun filename -> input_files := filename :: !input_files)
"sawjap [--do-not-fold] <file>";
List.iter (Javalib.iter (print_class !folding)) !input_files
|
|
680bdc7c5a7c9e9e0ad98fd9fd16c3b087b2bf47d6f3be30a2f583cf9840f9ae | suhdonghwi/nuri | Util.hs | # OPTIONS_GHC -Wno - missing - signatures #
module Nuri.Spec.Util where
import Nuri.Expr
import Nuri.Literal
import Nuri.Stmt
import Text.Megaparsec.Pos
initPos :: SourcePos
initPos = initialPos "(test)"
litNone = Lit initPos LitNone
litInteger v = Lit initPos (LitInteger v)
litChar v = Lit initPos (LitChar v)
litReal v = Lit initPos (LitReal v)
litBool v = Lit initPos (LitBool v)
ifExpr = If initPos
binaryOp = BinaryOp initPos
unaryOp = UnaryOp initPos
var = Var initPos
funcCall = FuncCall initPos
lambda = Lambda initPos ""
struct = Struct initPos
decl = Decl initPos
funcDecl name args body = decl name $ FuncDecl args (Just body)
funcDeclStmt = ((DeclStmt .) .) . funcDecl
verbDecl name args body = decl name $ VerbDecl args (Just body)
verbDeclStmt = ((DeclStmt .) .) . verbDecl
adjectiveDecl name args vars body = decl name $ AdjectiveDecl args vars (Just body)
adjectiveDeclStmt = (((DeclStmt .) .) .) . adjectiveDecl
funcForward name args = decl name $ FuncDecl args Nothing
funcForwardStmt = (DeclStmt .) . funcForward
verbForward name args = decl name $ VerbDecl args Nothing
verbForwardStmt = (DeclStmt .) . verbForward
adjectiveForward name args vars = decl name $ AdjectiveDecl args vars Nothing
adjectiveForwardStmt = ((DeclStmt .) .) . adjectiveForward
constDecl name expr = decl name (ConstDecl expr)
constDeclStmt = (DeclStmt .) . constDecl
structDecl name fields = decl name (StructDecl fields)
structDeclStmt = (DeclStmt .) . structDecl
| null | https://raw.githubusercontent.com/suhdonghwi/nuri/337550e3d50c290144df905ea3f189e9af6123c2/test/Nuri/Spec/Util.hs | haskell | # OPTIONS_GHC -Wno - missing - signatures #
module Nuri.Spec.Util where
import Nuri.Expr
import Nuri.Literal
import Nuri.Stmt
import Text.Megaparsec.Pos
initPos :: SourcePos
initPos = initialPos "(test)"
litNone = Lit initPos LitNone
litInteger v = Lit initPos (LitInteger v)
litChar v = Lit initPos (LitChar v)
litReal v = Lit initPos (LitReal v)
litBool v = Lit initPos (LitBool v)
ifExpr = If initPos
binaryOp = BinaryOp initPos
unaryOp = UnaryOp initPos
var = Var initPos
funcCall = FuncCall initPos
lambda = Lambda initPos ""
struct = Struct initPos
decl = Decl initPos
funcDecl name args body = decl name $ FuncDecl args (Just body)
funcDeclStmt = ((DeclStmt .) .) . funcDecl
verbDecl name args body = decl name $ VerbDecl args (Just body)
verbDeclStmt = ((DeclStmt .) .) . verbDecl
adjectiveDecl name args vars body = decl name $ AdjectiveDecl args vars (Just body)
adjectiveDeclStmt = (((DeclStmt .) .) .) . adjectiveDecl
funcForward name args = decl name $ FuncDecl args Nothing
funcForwardStmt = (DeclStmt .) . funcForward
verbForward name args = decl name $ VerbDecl args Nothing
verbForwardStmt = (DeclStmt .) . verbForward
adjectiveForward name args vars = decl name $ AdjectiveDecl args vars Nothing
adjectiveForwardStmt = ((DeclStmt .) .) . adjectiveForward
constDecl name expr = decl name (ConstDecl expr)
constDeclStmt = (DeclStmt .) . constDecl
structDecl name fields = decl name (StructDecl fields)
structDeclStmt = (DeclStmt .) . structDecl
|
|
3839290e7e8b94f3b2ed695ee75dc4378d8b242e34c6177037e0b84ee1ebb7f4 | sklassen/erlang-linalg-native | linalg_det.erl | -module(linalg_det).
-export([det/1]).
-define(EPSILON, 1.0e-12).
% 1x1 ...
det([[X]]) ->
X;
.. well known 2x2 ...
det([[A, B], [C, D]]) ->
A * D - B * C;
... rule of sarrus 3x3 ...
det([[A, B, C], [D, E, F], [G, H, I]]) ->
A * E * I + B * F * G + C * D * H - C * E * G - B * D * I - A * F * H;
... and extention 4x4 ( speeds up processing for larger matrix by 2 - 3x )
det([[A, B, C, D], [E, F, G, H], [I, J, K, L], [M, N, O, P]]) ->
A * F * K * P - A * F * L * O - A * G * J * P + A * G * L * N + A * H * J * O - A * H * K * N -
B * E * K * P + B * E * L * O +
B * G * I * P - B * G * L * M - B * H * I * O + B * H * K * M + C * E * J * P -
C * E * L * N - C * F * I * P + C * F * L * M +
C * H * I * N - C * H * J * M - D * E * J * O + D * E * K * N + D * F * I * O -
D * F * K * M - D * G * I * N + D * G * J * M;
... Laplace for 5x5 ( is as fast as Gauss - Jordon ) ...
det([H | Tail]) when length(H) == 5 andalso length([H | Tail]) == 5 ->
linalg:sum([
math:pow(-1, J - 1) * X * det(linalg:col(-J, Tail))
|| {J, X} <- lists:zip(lists:seq(1, length(H)), H)
]);
% ... remaining check for square matrix
det([H | Tail] = RowWise) when length(H) == length([H | Tail]) ->
det(RowWise, 1);
det(_) ->
erlang:error({error, matrix_not_square}).
% Gauss-Jordan elimination
det(RowWise, N) when length(RowWise) == N ->
linalg:prod(linalg:diag(RowWise));
det(RowWise, N) ->
{Top, Bottom} = lists:split(N, RowWise),
Row = lists:last(Top),
case lists:nth(N, Row) of
Z when abs(Z) < ?EPSILON ->
case swap(RowWise, N, N + 1) of
na -> 0.0;
New -> -det(New, N)
end;
H ->
Col = linalg:divide(linalg:col(N, Bottom), H),
Sub = [linalg:mul(Row, X) || X <- Col],
det(lists:append(Top, linalg:sub(Bottom, Sub)), N + 1)
end.
swap(RowWise, _, J) when J > length(RowWise) ->
na;
swap(RowWise, I, J) ->
case linalg:cell(J, I, RowWise) of
Z when abs(Z) < ?EPSILON -> swap(RowWise, I, J + 1);
_ ->
{A, [C | Tail]} = lists:split(I - 1, RowWise),
{B, D} = lists:split(J - I, Tail),
lists:append([A, B, [C], D])
end.
| null | https://raw.githubusercontent.com/sklassen/erlang-linalg-native/b31eef532b9fe2be7ecbff52a060ccdc833b4dca/src/linalg_det.erl | erlang | 1x1 ...
... remaining check for square matrix
Gauss-Jordan elimination | -module(linalg_det).
-export([det/1]).
-define(EPSILON, 1.0e-12).
det([[X]]) ->
X;
.. well known 2x2 ...
det([[A, B], [C, D]]) ->
A * D - B * C;
... rule of sarrus 3x3 ...
det([[A, B, C], [D, E, F], [G, H, I]]) ->
A * E * I + B * F * G + C * D * H - C * E * G - B * D * I - A * F * H;
... and extention 4x4 ( speeds up processing for larger matrix by 2 - 3x )
det([[A, B, C, D], [E, F, G, H], [I, J, K, L], [M, N, O, P]]) ->
A * F * K * P - A * F * L * O - A * G * J * P + A * G * L * N + A * H * J * O - A * H * K * N -
B * E * K * P + B * E * L * O +
B * G * I * P - B * G * L * M - B * H * I * O + B * H * K * M + C * E * J * P -
C * E * L * N - C * F * I * P + C * F * L * M +
C * H * I * N - C * H * J * M - D * E * J * O + D * E * K * N + D * F * I * O -
D * F * K * M - D * G * I * N + D * G * J * M;
... Laplace for 5x5 ( is as fast as Gauss - Jordon ) ...
det([H | Tail]) when length(H) == 5 andalso length([H | Tail]) == 5 ->
linalg:sum([
math:pow(-1, J - 1) * X * det(linalg:col(-J, Tail))
|| {J, X} <- lists:zip(lists:seq(1, length(H)), H)
]);
det([H | Tail] = RowWise) when length(H) == length([H | Tail]) ->
det(RowWise, 1);
det(_) ->
erlang:error({error, matrix_not_square}).
det(RowWise, N) when length(RowWise) == N ->
linalg:prod(linalg:diag(RowWise));
det(RowWise, N) ->
{Top, Bottom} = lists:split(N, RowWise),
Row = lists:last(Top),
case lists:nth(N, Row) of
Z when abs(Z) < ?EPSILON ->
case swap(RowWise, N, N + 1) of
na -> 0.0;
New -> -det(New, N)
end;
H ->
Col = linalg:divide(linalg:col(N, Bottom), H),
Sub = [linalg:mul(Row, X) || X <- Col],
det(lists:append(Top, linalg:sub(Bottom, Sub)), N + 1)
end.
swap(RowWise, _, J) when J > length(RowWise) ->
na;
swap(RowWise, I, J) ->
case linalg:cell(J, I, RowWise) of
Z when abs(Z) < ?EPSILON -> swap(RowWise, I, J + 1);
_ ->
{A, [C | Tail]} = lists:split(I - 1, RowWise),
{B, D} = lists:split(J - I, Tail),
lists:append([A, B, [C], D])
end.
|
928b7302d887a6fda244acc73643ee91e759ba3a365fcc21d5cb653f4c17a01d | Quviq/quickcheck-contractmodel | ContractModel.hs | module Test.QuickCheck.ContractModel
( ContractModel(..)
, RunModel(..)
, IsRunnable(..)
, DefaultRealized
, RunMonad(..)
, Actions
, Act(..)
, pattern Actions
, pattern ContractAction
, pattern WaitUntil
, stateAfter
, runContractModel
, liftRunMonad
, contractState
, registerToken
-- * Chain index
, HasChainIndex(..)
, ChainIndex(..)
, ChainState(..)
, TxInState(..)
, Era
* The safe interface to ` SymToken `
--
-- NOTE: we don't export the internals here because
-- it's important that you can't tell the difference
between differnelty numbered SymTokens as these are
-- not guaranteed to be stable.
, SymToken
, SymValue
, symIsZero
, symLeq
, toValue
, toSymVal
, inv
, SymValueLike(..)
, TokenLike(..)
, HasSymTokens(..)
-- * Properties
, BalanceChangeOptions(..)
, assertBalanceChangesMatch
, signerPaysFees
, asserts
-- * Dynamic logic
, module DL
-- * The safe interface to `Spec`
--
-- NOTE: we don't export internals here because we
-- really don't want people seeing or changing the
-- sensitive parts of the model.
, ModelState
, Spec(..)
, GetModelState(..)
, runSpec
, currentSlot
, balanceChanges
, balanceChange
, minted
, lockedValue
, getContractState
, askModelState
, askContractState
, viewModelState
, viewContractState
, createToken
, mint
, burn
, deposit
, withdraw
, transfer
, waitUntil
, wait
, assertSpec
, coerceSpec
-- * Internals
, fromStateModelActions
) where
import Test.QuickCheck.ContractModel.Internal
import Test.QuickCheck.ContractModel.Internal.ChainIndex
import Test.QuickCheck.ContractModel.Internal.Common
import Test.QuickCheck.ContractModel.Internal.Model
import Test.QuickCheck.ContractModel.Internal.Spec
import Test.QuickCheck.ContractModel.Internal.Symbolics
import Test.QuickCheck.ContractModel.DL as DL
| null | https://raw.githubusercontent.com/Quviq/quickcheck-contractmodel/071628000ad391ba6849b4d8407b5375228d235d/quickcheck-contractmodel/src/Test/QuickCheck/ContractModel.hs | haskell | * Chain index
NOTE: we don't export the internals here because
it's important that you can't tell the difference
not guaranteed to be stable.
* Properties
* Dynamic logic
* The safe interface to `Spec`
NOTE: we don't export internals here because we
really don't want people seeing or changing the
sensitive parts of the model.
* Internals | module Test.QuickCheck.ContractModel
( ContractModel(..)
, RunModel(..)
, IsRunnable(..)
, DefaultRealized
, RunMonad(..)
, Actions
, Act(..)
, pattern Actions
, pattern ContractAction
, pattern WaitUntil
, stateAfter
, runContractModel
, liftRunMonad
, contractState
, registerToken
, HasChainIndex(..)
, ChainIndex(..)
, ChainState(..)
, TxInState(..)
, Era
* The safe interface to ` SymToken `
between differnelty numbered SymTokens as these are
, SymToken
, SymValue
, symIsZero
, symLeq
, toValue
, toSymVal
, inv
, SymValueLike(..)
, TokenLike(..)
, HasSymTokens(..)
, BalanceChangeOptions(..)
, assertBalanceChangesMatch
, signerPaysFees
, asserts
, module DL
, ModelState
, Spec(..)
, GetModelState(..)
, runSpec
, currentSlot
, balanceChanges
, balanceChange
, minted
, lockedValue
, getContractState
, askModelState
, askContractState
, viewModelState
, viewContractState
, createToken
, mint
, burn
, deposit
, withdraw
, transfer
, waitUntil
, wait
, assertSpec
, coerceSpec
, fromStateModelActions
) where
import Test.QuickCheck.ContractModel.Internal
import Test.QuickCheck.ContractModel.Internal.ChainIndex
import Test.QuickCheck.ContractModel.Internal.Common
import Test.QuickCheck.ContractModel.Internal.Model
import Test.QuickCheck.ContractModel.Internal.Spec
import Test.QuickCheck.ContractModel.Internal.Symbolics
import Test.QuickCheck.ContractModel.DL as DL
|
4aec757bf5ca85a294a46ccc2e34d5be8417edc1cb98967e79bdf4bb4fd9bd2e | hipsleek/hipsleek | mcpure_D.ml | #include "xdebug.cppo"
open VarGen
open Globals
open Cpure
(* Memoised structures *)
type memo_pure = memoised_group list
and memoised_group = {
memo_group_fv : spec_var list;
memo_group_linking_vars : spec_var list;
memo_group_changed : bool;
false if the slice has been checked UNSAT
memo_group_cons : memoised_constraint list; (*used for pruning*)
memo_group_slice : formula list; (*constraints that can not be used for pruning but belong to the current slice non-the less*)
memo_group_aset : var_aset; (* alias set *)
}
and memoised_constraint = {
memo_formula : b_formula;
memo_status : prune_status
}
and prune_status =
Redundant constraint - Need not be proven when present in conseq
Propagated constraint - Need not be proven when present in conseq
| Implied_N (* Original constraint *)
and var_aset = Gen.EqMap(SV).emap
let empty_var_aset = EMapSV.mkEmpty
let print_mg_f = ref (fun (c: memoised_group) -> "printing not initialized")
let print_mp_f = ref (fun (c: memo_pure) -> "printing not initialized")
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/src/mcpure_D.ml | ocaml | Memoised structures
used for pruning
constraints that can not be used for pruning but belong to the current slice non-the less
alias set
Original constraint | #include "xdebug.cppo"
open VarGen
open Globals
open Cpure
type memo_pure = memoised_group list
and memoised_group = {
memo_group_fv : spec_var list;
memo_group_linking_vars : spec_var list;
memo_group_changed : bool;
false if the slice has been checked UNSAT
}
and memoised_constraint = {
memo_formula : b_formula;
memo_status : prune_status
}
and prune_status =
Redundant constraint - Need not be proven when present in conseq
Propagated constraint - Need not be proven when present in conseq
and var_aset = Gen.EqMap(SV).emap
let empty_var_aset = EMapSV.mkEmpty
let print_mg_f = ref (fun (c: memoised_group) -> "printing not initialized")
let print_mp_f = ref (fun (c: memo_pure) -> "printing not initialized")
|
34c807f574c8cf831aa6158e33ab1414b42d6c74a4ed661fe1647b5e02c641e7 | ostera/serde.ml | data.ml | type t =
| Int of Int.t
| Bool of bool
| Float of float
| String of string
| Char of char
| Tuple of { tup_size : int; tup_elements : t list }
| Unit
| Variant_unit of { vu_type : string; vu_name : string; vu_idx : int }
| Variant_tuple of {
vt_type : string;
vt_name : string;
vt_idx : int;
vt_size : int;
vt_fields : t list;
}
| Variant_record of {
vr_type : string;
vr_name : string;
vr_idx : int;
vr_size : int;
vr_fields : (string * t) list;
}
| Record of {
rec_type : string;
rec_size : int;
rec_fields : (string * t) list;
}
| null | https://raw.githubusercontent.com/ostera/serde.ml/34adb836b3854e4469a757e32c18dbdbd9e79bf0/serde/data.ml | ocaml | type t =
| Int of Int.t
| Bool of bool
| Float of float
| String of string
| Char of char
| Tuple of { tup_size : int; tup_elements : t list }
| Unit
| Variant_unit of { vu_type : string; vu_name : string; vu_idx : int }
| Variant_tuple of {
vt_type : string;
vt_name : string;
vt_idx : int;
vt_size : int;
vt_fields : t list;
}
| Variant_record of {
vr_type : string;
vr_name : string;
vr_idx : int;
vr_size : int;
vr_fields : (string * t) list;
}
| Record of {
rec_type : string;
rec_size : int;
rec_fields : (string * t) list;
}
|
|
c9bea1d79e7fb0ef7d28538d28a43c064b2224a5da2c55c6e5d26b1a713e7b30 | exercism/racket | example.rkt | #lang racket
(provide add-gigasecond)
(require racket/date)
(define (add-gigasecond date)
(seconds->date (+ 1e9 (date->seconds date))))
| null | https://raw.githubusercontent.com/exercism/racket/d171a5fb3595cc09d171051a3f5ef45caedad020/exercises/practice/gigasecond/.meta/example.rkt | racket | #lang racket
(provide add-gigasecond)
(require racket/date)
(define (add-gigasecond date)
(seconds->date (+ 1e9 (date->seconds date))))
|
|
7d208ddf34c589b3b09d97dc4af3cdeefd4a2833253e94715e1e84bed400b2bc | cnuernber/dtype-next | nio_buf_mmodel.clj | (ns tech.v3.datatype.ffi.nio-buf-mmodel
(:require [tech.v3.datatype.protocols :as dtype-proto])
(:import [jdk.incubator.foreign MemoryAddress ResourceScope]
[java.nio ByteBuffer ByteOrder])
)
(set! *warn-on-reflection* true)
(defn direct-buffer-constructor
^ByteBuffer [nbuf ^long address ^long nbytes _options]
(let [retval (if-not (== 0 nbytes)
(-> (MemoryAddress/ofLong address)
(.asSegment nbytes (ResourceScope/globalScope))
(.asByteBuffer))
(ByteBuffer/allocateDirect 0))
endianness (dtype-proto/endianness nbuf)]
(case endianness
:little-endian (.order retval ByteOrder/LITTLE_ENDIAN)
:big-endian (.order retval ByteOrder/BIG_ENDIAN))
retval))
| null | https://raw.githubusercontent.com/cnuernber/dtype-next/71477752fc376fad4b678fa9607ef54a40b2b1ff/src/tech/v3/datatype/ffi/nio_buf_mmodel.clj | clojure | (ns tech.v3.datatype.ffi.nio-buf-mmodel
(:require [tech.v3.datatype.protocols :as dtype-proto])
(:import [jdk.incubator.foreign MemoryAddress ResourceScope]
[java.nio ByteBuffer ByteOrder])
)
(set! *warn-on-reflection* true)
(defn direct-buffer-constructor
^ByteBuffer [nbuf ^long address ^long nbytes _options]
(let [retval (if-not (== 0 nbytes)
(-> (MemoryAddress/ofLong address)
(.asSegment nbytes (ResourceScope/globalScope))
(.asByteBuffer))
(ByteBuffer/allocateDirect 0))
endianness (dtype-proto/endianness nbuf)]
(case endianness
:little-endian (.order retval ByteOrder/LITTLE_ENDIAN)
:big-endian (.order retval ByteOrder/BIG_ENDIAN))
retval))
|
|
5977ad0259895e29c8360b339d223105b3e6550809a6c87fbe55d6bfb64445d7 | andersfugmann/amqp-client | channel_test.ml | open Amqp
open Thread
let uniq s =
Printf.sprintf "%s_%d_%s" (Filename.basename Sys.argv.(0)) (Unix.getpid ()) s
let test =
let port = Sys.getenv_opt "AMQP_PORT" |> function Some port -> Some (int_of_string port) | None -> None in
Connection.connect ~id:(uniq "ocaml-amqp-tests") ?port "localhost" >>= fun connection ->
Log.info "Connection started";
Connection.open_channel ~id:(uniq "test") Channel.no_confirm connection >>= fun channel ->
Log.info "Channel opened";
Channel.close channel >>= fun () ->
Log.info "Channel closed";
Deferred.List.init 600 ~f:(fun _ -> Connection.open_channel ~id:(uniq "test") Channel.no_confirm connection) >>= fun channels ->
Log.info "Channels opened";
Deferred.List.iter channels ~f:Channel.close >>= fun () ->
Log.info "Channels closed";
Connection.close connection >>| fun () ->
Log.info "Connection closed";
Scheduler.shutdown 0
let _ =
Scheduler.go ()
let () = Printf.printf "Done\n"
| null | https://raw.githubusercontent.com/andersfugmann/amqp-client/2932a69510af550e9e156ed479f4fca7daee31cc/async/test/channel_test.ml | ocaml | open Amqp
open Thread
let uniq s =
Printf.sprintf "%s_%d_%s" (Filename.basename Sys.argv.(0)) (Unix.getpid ()) s
let test =
let port = Sys.getenv_opt "AMQP_PORT" |> function Some port -> Some (int_of_string port) | None -> None in
Connection.connect ~id:(uniq "ocaml-amqp-tests") ?port "localhost" >>= fun connection ->
Log.info "Connection started";
Connection.open_channel ~id:(uniq "test") Channel.no_confirm connection >>= fun channel ->
Log.info "Channel opened";
Channel.close channel >>= fun () ->
Log.info "Channel closed";
Deferred.List.init 600 ~f:(fun _ -> Connection.open_channel ~id:(uniq "test") Channel.no_confirm connection) >>= fun channels ->
Log.info "Channels opened";
Deferred.List.iter channels ~f:Channel.close >>= fun () ->
Log.info "Channels closed";
Connection.close connection >>| fun () ->
Log.info "Connection closed";
Scheduler.shutdown 0
let _ =
Scheduler.go ()
let () = Printf.printf "Done\n"
|
|
49fa62741337533afbc7ebbd1b2dcc854678ca52df1363617dd235614cbc9f0a | dundalek/closh | plain.clj | (ns closh.zero.frontend.plain
(:gen-class)
(:require [closh.zero.platform.eval :as eval]
[closh.zero.compiler]
[closh.zero.parser]
[closh.zero.pipeline]
[closh.zero.reader]))
(defn -main [& args]
(let [cmd (or (first args) "echo hello clojure")]
(eval/eval
`(-> ~(closh.zero.compiler/compile-interactive
(closh.zero.parser/parse (closh.zero.reader/read-string cmd)))
(closh.zero.pipeline/wait-for-pipeline)))))
| null | https://raw.githubusercontent.com/dundalek/closh/b1a7fd310b6511048fbacb8e496f574c8ccfa291/src/jvm/closh/zero/frontend/plain.clj | clojure | (ns closh.zero.frontend.plain
(:gen-class)
(:require [closh.zero.platform.eval :as eval]
[closh.zero.compiler]
[closh.zero.parser]
[closh.zero.pipeline]
[closh.zero.reader]))
(defn -main [& args]
(let [cmd (or (first args) "echo hello clojure")]
(eval/eval
`(-> ~(closh.zero.compiler/compile-interactive
(closh.zero.parser/parse (closh.zero.reader/read-string cmd)))
(closh.zero.pipeline/wait-for-pipeline)))))
|
|
f676369998665fac61ec5bbc3cac263450c337c572b40ace24fba8b329f5a526 | macourtney/Dark-Exchange | payment_sent.clj | (ns darkexchange.model.actions.payment-sent
(:require [darkexchange.interchange-map-util :as interchange-map-util]
[darkexchange.model.actions.action-keys :as action-keys]
[darkexchange.model.trade :as trade-model]))
(def action-key action-keys/payment-sent-action-key)
(defn payment-sent [foreign-trade-id trade-partner-identity]
(trade-model/foreign-payment-sent foreign-trade-id trade-partner-identity)
"Ok")
(defn action [request-map]
{ :data (payment-sent (:trade-id (:data request-map)) (interchange-map-util/from-identity request-map)) }) | null | https://raw.githubusercontent.com/macourtney/Dark-Exchange/1654d05cda0c81585da7b8e64f9ea3e2944b27f1/src/darkexchange/model/actions/payment_sent.clj | clojure | (ns darkexchange.model.actions.payment-sent
(:require [darkexchange.interchange-map-util :as interchange-map-util]
[darkexchange.model.actions.action-keys :as action-keys]
[darkexchange.model.trade :as trade-model]))
(def action-key action-keys/payment-sent-action-key)
(defn payment-sent [foreign-trade-id trade-partner-identity]
(trade-model/foreign-payment-sent foreign-trade-id trade-partner-identity)
"Ok")
(defn action [request-map]
{ :data (payment-sent (:trade-id (:data request-map)) (interchange-map-util/from-identity request-map)) }) |
|
b245ccbb50b98ef7d8e364f062c49c6f0543e90a65784934fd68c96391012a9b | yallop/ocaml-asp | asp_utilities.mli |
* Copyright ( c ) 2018 and
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2018 Neelakantan Krishnaswami and Jeremy Yallop
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
module Unstaged :
sig
val toString : char list -> string
val toInt : char list -> int
val peek_channel : in_channel -> char option
val junk_channel : in_channel -> unit
end
type _ chr = Chr : char -> char chr [@@unboxed]
module Char_tag : Asp.Types.TAG with type 'a t = 'a chr
module Char_element : Asp.Types.TOKEN with type 'a tag = 'a chr
and type t = char
| null | https://raw.githubusercontent.com/yallop/ocaml-asp/a092f17ea55d427c63414899e39a8fe80b30db14/lib/asp_utilities.mli | ocaml |
* Copyright ( c ) 2018 and
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2018 Neelakantan Krishnaswami and Jeremy Yallop
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
module Unstaged :
sig
val toString : char list -> string
val toInt : char list -> int
val peek_channel : in_channel -> char option
val junk_channel : in_channel -> unit
end
type _ chr = Chr : char -> char chr [@@unboxed]
module Char_tag : Asp.Types.TAG with type 'a t = 'a chr
module Char_element : Asp.Types.TOKEN with type 'a tag = 'a chr
and type t = char
|
|
2c9bbb7c14399f2acdd40804dceef3094a25265bf567cabd1b8ff8b0c888228f | ocaml-multicore/tezos | test_global_constants_storage.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Marigold < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Protocol
open Alpha_context
open Test_transfer
(** Testing
-------
Component: Protocol (global table of constants)
Invocation: dune exec src/proto_alpha/lib_protocol/test/main.exe \
-- test "^global table of constants$"
Subject: This module tests that the global table of constants
can be written to and read from across blocks.
*)
let get_next_context b =
Incremental.begin_construction b >>=? fun b ->
return (Incremental.alpha_ctxt b)
let assert_expr_equal loc =
Assert.equal
~loc
( = )
"Michelson Expressions Not Equal"
Michelson_v1_printer.print_expr
let assert_proto_error_id loc id result =
let test err =
(Error_monad.find_info_of_error err).id
= "proto." ^ Protocol.name ^ "." ^ id
in
Assert.error ~loc result test
let expr_to_hash expr =
let lexpr = Script_repr.lazy_expr @@ Expr.from_string expr in
Script_repr.force_bytes lexpr >|? fun b -> Script_expr_hash.hash_bytes [b]
(* This test has a long wind-up, but is very simple: it just asserts
that values written to the global table of constants persist across
blocks. *)
let get_happy_path () =
register_two_contracts () >>=? fun (b, alice, bob) ->
Incremental.begin_construction b >>=? fun b ->
let expr_str = "Pair 3 7" in
let expr = Expr.from_string expr_str in
Environment.wrap_tzresult @@ expr_to_hash expr_str >>?= fun hash ->
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op >>=? fun b ->
Incremental.finalize_block b >>=? fun b ->
let assert_unchanged b =
get_next_context b >>=? fun context ->
Global_constants_storage.get context hash >|= Environment.wrap_tzresult
>>=? fun (_, result_expr) ->
assert_expr_equal __LOC__ expr result_expr >|=? fun _ -> b
in
assert_unchanged b >>=? fun b ->
let do_many_transfers b =
Incremental.begin_construction b >>=? fun b ->
n_transactions 10 b alice bob (Tez.of_mutez_exn 1000L) >>=? fun b ->
Incremental.finalize_block b >>=? fun b -> assert_unchanged b
in
do_many_transfers b >>=? do_many_transfers >>=? do_many_transfers >>= fun _ ->
Lwt.return_ok ()
(* Blocks that include a registration of a bad expression should
fail. *)
let test_registration_of_bad_expr_fails () =
register_two_contracts () >>=? fun (b, alice, _) ->
Incremental.begin_construction b >>=? fun b ->
(* To produce the failure, we attempt to register an expression with
a malformed hash. *)
let expr = Expr.from_string "Pair 1 (constant \"foo\")" in
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op
>>= assert_proto_error_id __LOC__ "Badly_formed_constant_expression"
(* You cannot register the same expression twice. *)
let test_no_double_register () =
register_two_contracts () >>=? fun (b, alice, _) ->
Incremental.begin_construction b >>=? fun b ->
let expr = Expr.from_string "Pair 1 2" in
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op >>=? fun b ->
(* Register the same expression again *)
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op
>>= assert_proto_error_id __LOC__ "Expression_already_registered"
let tests =
[
Tztest.tztest "Multiple blocks happy path" `Quick get_happy_path;
Tztest.tztest
"Bad register global operations fail when added to the block"
`Quick
test_registration_of_bad_expr_fails;
Tztest.tztest
"You cannot register the same expression twice."
`Quick
test_no_double_register;
]
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_protocol/test/test_global_constants_storage.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Testing
-------
Component: Protocol (global table of constants)
Invocation: dune exec src/proto_alpha/lib_protocol/test/main.exe \
-- test "^global table of constants$"
Subject: This module tests that the global table of constants
can be written to and read from across blocks.
This test has a long wind-up, but is very simple: it just asserts
that values written to the global table of constants persist across
blocks.
Blocks that include a registration of a bad expression should
fail.
To produce the failure, we attempt to register an expression with
a malformed hash.
You cannot register the same expression twice.
Register the same expression again | Copyright ( c ) 2021 Marigold < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol
open Alpha_context
open Test_transfer
let get_next_context b =
Incremental.begin_construction b >>=? fun b ->
return (Incremental.alpha_ctxt b)
let assert_expr_equal loc =
Assert.equal
~loc
( = )
"Michelson Expressions Not Equal"
Michelson_v1_printer.print_expr
let assert_proto_error_id loc id result =
let test err =
(Error_monad.find_info_of_error err).id
= "proto." ^ Protocol.name ^ "." ^ id
in
Assert.error ~loc result test
let expr_to_hash expr =
let lexpr = Script_repr.lazy_expr @@ Expr.from_string expr in
Script_repr.force_bytes lexpr >|? fun b -> Script_expr_hash.hash_bytes [b]
let get_happy_path () =
register_two_contracts () >>=? fun (b, alice, bob) ->
Incremental.begin_construction b >>=? fun b ->
let expr_str = "Pair 3 7" in
let expr = Expr.from_string expr_str in
Environment.wrap_tzresult @@ expr_to_hash expr_str >>?= fun hash ->
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op >>=? fun b ->
Incremental.finalize_block b >>=? fun b ->
let assert_unchanged b =
get_next_context b >>=? fun context ->
Global_constants_storage.get context hash >|= Environment.wrap_tzresult
>>=? fun (_, result_expr) ->
assert_expr_equal __LOC__ expr result_expr >|=? fun _ -> b
in
assert_unchanged b >>=? fun b ->
let do_many_transfers b =
Incremental.begin_construction b >>=? fun b ->
n_transactions 10 b alice bob (Tez.of_mutez_exn 1000L) >>=? fun b ->
Incremental.finalize_block b >>=? fun b -> assert_unchanged b
in
do_many_transfers b >>=? do_many_transfers >>=? do_many_transfers >>= fun _ ->
Lwt.return_ok ()
let test_registration_of_bad_expr_fails () =
register_two_contracts () >>=? fun (b, alice, _) ->
Incremental.begin_construction b >>=? fun b ->
let expr = Expr.from_string "Pair 1 (constant \"foo\")" in
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op
>>= assert_proto_error_id __LOC__ "Badly_formed_constant_expression"
let test_no_double_register () =
register_two_contracts () >>=? fun (b, alice, _) ->
Incremental.begin_construction b >>=? fun b ->
let expr = Expr.from_string "Pair 1 2" in
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op >>=? fun b ->
Op.register_global_constant
(I b)
~source:alice
~value:(Script_repr.lazy_expr expr)
>>=? fun op ->
Incremental.add_operation b op
>>= assert_proto_error_id __LOC__ "Expression_already_registered"
let tests =
[
Tztest.tztest "Multiple blocks happy path" `Quick get_happy_path;
Tztest.tztest
"Bad register global operations fail when added to the block"
`Quick
test_registration_of_bad_expr_fails;
Tztest.tztest
"You cannot register the same expression twice."
`Quick
test_no_double_register;
]
|
446e014a434ea079743c3048510e9d1c64071822cbc3dd799d31f699ca06e5a0 | RolfRolles/PandemicML | X86SemanticsDivinator.ml | open X86Predicate
open DataStructures
(* This code creates the JIT scaffolding necessary for testing *)
let init_t,blit_t,retn_t,stack_t,c_stack32,mem_t,f_blit,f_execute = JITSampler.create_setup ()
(* This code applies all test functions against expressions that have been
turned into statements. *)
let apply_all l_evalstmt stmt =
if l_evalstmt = [] then invalid_arg "apply_all";
let rec aux = function
( Printf.printf " Eliminated % s\n " ( string_of_stmt stmt ) ;
| [] -> true
in
aux l_evalstmt
let expand_single_and_apply_all l_evalstmt l_f_stmt acc expr =
let stmts = List.rev_map (fun f -> f expr) l_f_stmt in
List.fold_left (fun acc stmt -> if apply_all l_evalstmt stmt then stmt::acc else acc) acc stmts
let expand_and_apply_all l_evalstmt l_expr l_f_stmt =
List.fold_left (expand_single_and_apply_all l_evalstmt l_f_stmt) [] l_expr
This code makes a function ( stmt - > bool ) given an input state
let make_fixed_test_statement_evaluator q_clobbered x86_cp instate =
let outstate = f_execute instate in
let f_stmt =
let open X86PredicateEvaluator in
eval_stmt (y_combinator (eval_expr instate outstate)) instate outstate
in
let q_clobbered = IOAnalysis.get_clobbered f_stmt q_clobbered in
let x86_cp = IOAnalysis.join_x86_cp x86_cp (IOAnalysis.x86_cp_of_x86_state outstate) in
(f_stmt,q_clobbered,x86_cp,instate,outstate)
Make an input state where all 32 and 1 - bit values respectively match
let instate_all_same val32 val1 =
let open JITRegion in
{ eax = val32; ebx = val32; ecx = val32; edx = val32; esp = c_stack32; ebp = val32; esi = val32; edi = val32;
eflags = Int32.of_int (X86Misc.fl2eflags val1 val1 val1 val1 val1 val1 val1); }
(* Make such a function from a random input state *)
let make_random_test_statement_evaluator q_clobbered x86_cp =
let instate = JITSampler.mk_random_state c_stack32 in
make_fixed_test_statement_evaluator q_clobbered x86_cp instate
let expand_state_by_flag state f =
let mask32 = X86Misc.mask32_of_x86_flags f in
let nmask32 = Int32.lognot mask32 in
let open JITRegion in
let flag_set = { state with eflags = Int32.logor state.eflags mask32; } in
let flag_nset = { state with eflags = Int32.logand state.eflags nmask32; } in
(flag_set,flag_nset)
let expand_state_by_flags state l_f =
let rec aux list = function
| f::fs ->
let rec aux2 outlist = function
| s::ss -> let s,n = expand_state_by_flag s f in aux2 (s::n::outlist) ss
| [] -> outlist
in aux (aux2 [] list) fs
| [] -> list
in aux [state] l_f
let expand_and_evaluate instate l_f list q cp =
let instates = expand_state_by_flags instate l_f in
List.fold_left
(fun (list,q,cp) instate ->
let f_stmt,q,cp,_,o = make_fixed_test_statement_evaluator q cp instate in
((f_stmt,instate,o)::list,q,cp))
(list,q,cp)
instates
(* Delete this when done testing *)
let exhaustive_al_cl l_f =
let rec aux eax ecx q cp list =
match eax,ecx with
| 0x100l,0x100l -> (list,q,cp)
| 0x100l,_ -> aux 0x0l (Int32.succ ecx) q cp list
| _,_ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; JITRegion.ecx = ecx; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) ecx q cp list
in
let list,q_clob,x86_cp = aux 0l 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
(* Delete this when done testing *)
let exhaustive_al l_f =
let rec aux eax q cp list =
match eax with
| 0x100l -> (list,q,cp)
| _ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) q cp list
in
let list,q_clob,x86_cp = aux 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
(* Delete this when done testing *)
let exhaustive_ax l_f =
let rec aux eax q cp list =
match eax with
| 0x10000l -> (list,q,cp)
| _ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) q cp list
in
let list,q_clob,x86_cp = aux 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
(* Delete this when done testing *)
let exhaustive_ax_cx4 l_f =
let rec aux eax ecx q cp list =
match eax,ecx with
| 0x10000l,0x10l -> (list,q,cp)
| 0x10000l,_ -> aux 0x0l (Int32.succ ecx) q cp list
| _,_ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; JITRegion.ecx = ecx; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) ecx q cp list
in
let list,q_clob,x86_cp = aux 0l 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
Generate N randomized statement evaluators , along with some fixed evaluators .
Throughout this process , discover which locations are outputs ( i.e. their
output value differs from their input value ) , and which registers and flags
are always set to a constant value .
Return the list of evaluators , a quadruple of lists of functions that make
statements from expressions ( i.e. , if eax is the only output location , then
the 32 - bit component of the quadruple will be
( fun x - > RegEquals(X86Reg(X86.Gd(X86.Eax)),x ) ) ) , and a quadruple containing
sets of those locations that are constant .
Throughout this process, discover which locations are outputs (i.e. their
output value differs from their input value), and which registers and flags
are always set to a constant value.
Return the list of evaluators, a quadruple of lists of functions that make
statements from expressions (i.e., if eax is the only output location, then
the 32-bit component of the quadruple will be
(fun x -> RegEquals(X86Reg(X86.Gd(X86.Eax)),x))), and a quadruple containing
sets of those locations that are constant. *)
let mk_random_test_statement_evaluators n =
let rec aux i list q_clob x86_cp =
if i = n
then list,q_clob,x86_cp
else
let f_stmt,q_clob,x86_cp,instate,outstate = make_random_test_statement_evaluator q_clob x86_cp in
aux (i+1) ((f_stmt,instate,outstate)::list) q_clob x86_cp
in
let list,q_clob,x86_cp = aux 0 [] IOAnalysis.empty_clob IOAnalysis.default_x86_cp in
let rec aux2 list q_clob x86_cp = function
| x::xs ->
let f_stmt,q_clob,x86_cp,instate,outstate = make_fixed_test_statement_evaluator q_clob x86_cp x in
aux2 ((f_stmt,instate,outstate)::list) q_clob x86_cp xs
| [] -> list,q_clob,x86_cp
in
let list,q_clob,x86_cp =
let open JITRegion in
aux2
list
q_clob
x86_cp
[instate_all_same 0l 0;
instate_all_same 0l 1;
instate_all_same 0x80000000l 0;
instate_all_same 0x80000000l 1;
instate_all_same 0xffffffffl 0;
instate_all_same 0xffffffffl 1;
{ (instate_all_same 0x80000000l 0) with eax = 0l; };
{ (instate_all_same 0x80000000l 1) with eax = 0l; };
]
in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
(* Some syntactic pruning to discard candidates with undesirable patterns
(constants-in-disguise, arithmetic identities). *)
let rec keep = function
| X86Flag(_) -> true
| X86Reg(_) -> true
| BitImm(_) -> true
| Imm(_) -> true
(* Don't do constant folding *)
| Binop(Imm(_),_,Imm(_)) -> false
| Binop(BitImm(_),_,BitImm(_)) -> false
(* Equivalent to smaller Sub *)
| Binop(Binop(l1,Or,r1),Add,Binop(l2,And,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
| Binop(Binop(l1,And,r1),Add,Binop(l2,Or,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
| Binop(Binop(l1,Add,r1),And,Binop(l2,Or,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
| Binop(Binop(l1,Or,r1),And,Binop(l2,Add,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
Sets to zero
| Binop(Unop(Not,l),And,r) when l = r -> false
| Binop(l,And,Unop(Not,r)) when l = r -> false
| Binop(l,Xor,r) when l = r -> false
| Binop(l,Sub,r) when l = r -> false
| Binop(Binop(l1,o1,r1),Xor,Binop(l2,o2,r2)) when o1 = o2 && is_commutative o1 && l1 = r2 && r1 = l2 -> false
(* Equivalent to smaller Add *)
| Binop(_,Sub,Unop(Neg,_)) -> false
(* Equivalent to smaller Sub *)
| Binop(Unop(Neg,_),Add,_) -> false
| Binop(_,Add,Unop(Neg,_)) -> false
(* Produces -1 *)
| Binop(Unop(Not,l),Add,r) when l = r -> false
| Binop(l,Add,Unop(Not,r)) when l = r -> false
| Binop(Unop(Not,l),Or,r) when l = r -> false
| Binop(l,Or,Unop(Not,r)) when l = r -> false
| Binop(Unop(Not,l),Xor,r) when l = r -> false
| Binop(l,Xor,Unop(Not,r)) when l = r -> false
| Binop(Unop(Dec,l),Sub,r) when l = r -> false
| Binop(l,Sub,Unop(Inc,r)) when l = r -> false
(* Equivalent to smaller term-in-itself*)
| Binop(l,Or, r) when l = r -> false
| Binop(l,And,r) when l = r -> false
| Binop(Binop(l1,o1,r1),Or, Binop(l2,o2,r2)) when o1 = o2 && is_commutative o1 && l1 = r2 && r1 = l2 -> false
| Binop(Binop(l1,o1,r1),And,Binop(l2,o2,r2)) when o1 = o2 && is_commutative o1 && l1 = r2 && r1 = l2 -> false
| Binop(l,o,r) -> keep l && keep r
(* Don't fold constants *)
| Unop(_,Imm(_)) -> false
| Unop(_,BitImm(_)) -> false
(* Equivalent to swapped Sub *)
| Unop(Neg,Binop(_,Sub,_)) -> false
| Unop(_,e) -> keep e
| Bitop(_,Imm(_)) -> false
| Bitop(_,e) -> keep e
| Extend(_,_,e) -> keep e
| ITE(b,t,f) -> keep b && keep t && keep f
(* If we end up with multiple equivalent candidates, we want to select the
"smallest" one according to some metric. This is that metric. *)
let rec score expr = let open X86Predicate in match expr with
| X86Flag(_) -> 1
| X86Reg(_) -> 1
| BitImm(_) -> 1
| Imm(X86.Id(i32)) -> if i32 = 0l then 1 else 3
| Imm(X86.Iw(i16)) -> if i16 = 0l then 1 else 3
| Imm(X86.Ib(i8 )) -> if i8 = 0l then 1 else 3
| Binop(l,(Eq|Ne),r) -> 1 + (score l) + (score r)
| Binop(l,(And|Or|Xor),r) -> 3 + (score l) + (score r)
| Binop(l,(Slt|Sle|Ult|Ule),r) -> 7 + (score l) + (score r)
| Binop(l,_,r) -> 15 + (score l) + (score r)
| Unop(_,e) -> 1 + (score e)
| Bitop(FifthBit,e) -> 1 + (score e)
| Bitop(Parity,e) -> 1 + (score e)
| Bitop(SignBit,e) -> 50 + (score e)
| Bitop(SecondBit,e) -> 50 + (score e)
| Extend(Low,_,e) -> 1000 + (score e)
| Extend(_,_,e) -> 20 + (score e)
| ITE(b,t,f) -> 1000 + (score b) + (score t) + (score f)
(* Given a quadruple of candidates, for each location, collect all expressions
and store them in a list. Return a quadruple of hash tables with this
information in them. *)
let refine_candidates q_cand =
let ht32 = Hashtbl.create 17 in
let ht16 = Hashtbl.create 17 in
let ht8 = Hashtbl.create 17 in
let ht1 = Hashtbl.create 17 in
let add h k v =
let res = try Hashtbl.find h k with Not_found -> [] in
Hashtbl.replace h k (v::res)
in
let aux = function
| FlagEquals(f,e) -> add ht1 f e
| RegEquals(X86.Gd(r32),e) -> add ht32 r32 e
| RegEquals(X86.Gw(r16),e) -> add ht16 r16 e
| RegEquals(X86.Gb(r8) ,e) -> add ht8 r8 e
| ImmEquals(_,e) -> Printf.printf "Skipping imm equals for now\n"
in
List.iter aux q_cand.val32;
List.iter aux q_cand.val16;
List.iter aux q_cand.val8;
List.iter aux q_cand.val1;
{
val32 = ht32;
val16 = ht16;
val8 = ht8;
val1 = ht1;
}
(* While distinguishing candidates, if the theorem prover returns a query, this
function is responsible for turning that query into an x86 state. *)
let reify_counterexample l =
let instate = JITSampler.mk_random_state c_stack32 in
let update f32 p b =
let i32 = Int32.shift_left 1l p in
if b
then Int32.logor f32 i32
else Int32.logand f32 (Int32.lognot i32)
in
let open JITRegion in
let aux s = function
| RegEquals(X86.Gd(X86.Eax),Imm(X86.Id(v32))) -> { s with eax = v32; }
| RegEquals(X86.Gd(X86.Ebx),Imm(X86.Id(v32))) -> { s with ebx = v32; }
| RegEquals(X86.Gd(X86.Ecx),Imm(X86.Id(v32))) -> { s with ecx = v32; }
| RegEquals(X86.Gd(X86.Edx),Imm(X86.Id(v32))) -> { s with edx = v32; }
| RegEquals(X86.Gd(X86.Esp),Imm(X86.Id(v32))) -> { s with esp = v32; }
| RegEquals(X86.Gd(X86.Ebp),Imm(X86.Id(v32))) -> { s with ebp = v32; }
| RegEquals(X86.Gd(X86.Esi),Imm(X86.Id(v32))) -> { s with esi = v32; }
| RegEquals(X86.Gd(X86.Edi),Imm(X86.Id(v32))) -> { s with edi = v32; }
| FlagEquals(X86.X86F_C,BitImm(b)) -> { s with eflags = update s.eflags 0 b }
| FlagEquals(X86.X86F_P,BitImm(b)) -> { s with eflags = update s.eflags 2 b }
| FlagEquals(X86.X86F_A,BitImm(b)) -> { s with eflags = update s.eflags 4 b }
| FlagEquals(X86.X86F_Z,BitImm(b)) -> { s with eflags = update s.eflags 6 b }
| FlagEquals(X86.X86F_S,BitImm(b)) -> { s with eflags = update s.eflags 7 b }
| FlagEquals(X86.X86F_D,BitImm(b)) -> { s with eflags = update s.eflags 10 b }
| FlagEquals(X86.X86F_O,BitImm(b)) -> { s with eflags = update s.eflags 11 b }
| _ -> invalid_arg "reify_counterxample"
in
List.fold_left aux instate l
Takes an ( expr * expr list ) option and an expr . Either :
1 ) Eliminate the first and return Some(second )
2 ) Eliminate the second and return o_current
3 ) Decide that they are indistinct and return Some(first , second::list )
1) Eliminate the first and return Some(second)
2) Eliminate the second and return o_current
3) Decide that they are indistinct and return Some(first,second::list) *)
let deathmatch f_stmt_maker f_dist f o_current e_challenger =
match o_current with
| None -> Some(e_challenger,[])
| Some(e_current,l_indistinct) ->
let x = f_dist f e_challenger e_current in
Printf.printf " Distinguishing % s from % s\n " ( string_of_expr e_current ) ( string_of_expr e_challenger ) ;
match x with
| [] ->
if score e_current <= score e_challenger
then Some(e_current,e_challenger::l_indistinct)
else Some(e_challenger,e_current::l_indistinct)
| l -> let c = reify_counterexample l in
let outstate = f_execute c in
let f_stmt =
let open X86PredicateEvaluator in
eval_stmt (y_combinator (eval_expr c outstate)) c outstate
in
let s_el = f_stmt_maker f e_challenger in
let b_el = f_stmt s_el in
let s_el2 = f_stmt_maker f e_current in
let b_el2 = f_stmt s_el2 in
Printf.printf " Distinguishing % s from % s using counterexample:\n " ( string_of_stmt s_el ) ( string_of_stmt s_el2 ) ;
List.iter ( fun s - > Printf.printf " % s\n " ( string_of_stmt s ) ) l ;
List.iter (fun s -> Printf.printf "%s\n" (string_of_stmt s)) l;*)
match b_el,b_el2 with
(* Indicates a bug *)
| true,true ->
Printf.printf
"Input did not distinguish?\nChal: %s\nCurr: %s\nState before:\n"
(string_of_stmt s_el)
(string_of_stmt s_el2);
JITSampler.print_x86ctx c;
Printf.printf "State after:\n";
JITSampler.print_x86ctx outstate;
List.iter (fun s -> Printf.printf "%s\n" (string_of_stmt s)) l;
None
| true,false ->
Printf.printf " Eliminated % s\n " ( string_of_stmt s_el2 ) ;
Some(e_challenger,[])
| false,true ->
Printf.printf " Eliminated % s\n " ( string_of_stmt s_el ) ;
Some(e_current,l_indistinct)
(* Possible for non-booleans *)
| false,false -> None
let deathmatch_single f_stmt_maker f_dist expr1 = deathmatch f_stmt_maker f_dist (Some(expr1,[]))
This is the SMT magic . Given a hash table location - > [ candidates ] , winnow
and merge the candidates based upon whether the theorem prover says that
they are identical . The output is one pruned list of candidates , sorted
by score , where the candidates passed all the checks and are assumed after
this point to represent the true behaviors of the instructions .
and merge the candidates based upon whether the theorem prover says that
they are identical. The output is one pruned list of candidates, sorted
by score, where the candidates passed all the checks and are assumed after
this point to represent the true behaviors of the instructions. *)
let minimize_candidates ht_cand f_stmt_maker f_dist =
let ht_new = Hashtbl.create 17 in
Hashtbl.iter (fun f l ->
let scres =
match (List.fold_left (deathmatch f_stmt_maker f_dist f) (None) l) with
| Some(x,y) -> x::y
| None -> []
in
let scres = List.map (fun x -> (score x,x)) scres in
let sorted = List.sort (fun (s1,_) (s2,_) -> Pervasives.compare s1 s2) scres in
(*List.iter (fun (s,e) -> Printf.printf "%d: %s\n" s (string_of_expr e)) sorted;*)
let res = List.map snd sorted in
Hashtbl.replace ht_new f res)
ht_cand;
ht_new
(* Applies minimization to candidate of a specified size *)
let minimize_candidates_by_size d q sz =
let open X86Predicate in
let open Z3Integration in
match sz with
| S32 -> { q with val32 = (minimize_candidates q.val32 (fun x e -> RegEquals(X86.Gd(x),e)) (distinguish_reg32 d)); }
| S16 -> { q with val16 = (minimize_candidates q.val16 (fun x e -> RegEquals(X86.Gw(x),e)) (distinguish_reg16 d)); }
| S8 -> { q with val8 = (minimize_candidates q.val8 (fun x e -> RegEquals(X86.Gb(x),e)) (distinguish_reg8 d)); }
| S1 -> { q with val1 = (minimize_candidates q.val1 (fun x e -> FlagEquals(x,e)) (distinguish_flag d)); }
(* This function takes as input a list of statement evaluators, a list of
statement-making functions as described previously, a sequential generator
object, and a size. It generates all candidate expressions, generates all
statements corresponding to those expressions being equal to some final
location, and then applies the statement evaluators to them. Those
statements that satisfy all evaluators are returned in a list. *)
let try_all l_evalstmt q_l_f_stmt seq_g esize =
let rec aux quad =
let _,e = seq_g#yield_current () in
(*Printf.printf "%s\n" (string_of_expr e);*)
let quad =
if keep e
then
update_quad
quad
(expand_single_and_apply_all l_evalstmt (select_quad q_l_f_stmt esize) (select_quad quad esize) e)
esize
else quad
in
let continue =
try (seq_g#increase_current (); true)
with X86PredicateGenerator.Lapsed -> false
in
if continue then aux quad else quad
in
aux { val32 = []; val16 = []; val8 = []; val1 = [] }
(* Print the verified behaviors for all locations. *)
let print_results q_res =
let print ht f_descr =
Hashtbl.iter (fun f l -> List.iter (fun x -> Printf.printf "%s: %s\n" (f_descr f) (string_of_expr x)) l)
let str = match l with x : : _ - > string_of_expr x | [ ] - > " NONE ! " in
Printf.printf " % s : % s\n " ( f_descr f ) )
Printf.printf "%s: %s\n" (f_descr f) str)*)
ht
in
print q_res.val32 X86Disasm.string_of_x86_reg32;
print q_res.val16 X86Disasm.string_of_x86_reg16;
print q_res.val8 X86Disasm.string_of_x86_reg8;
print q_res.val1 X86Disasm.string_of_x86_flags
The top - level function . Given a quadruple of templates , a quadruple of
registers and a quadruple of atoms for use in filling the templates , and
an x86 instruction , JIT the instruction , make N=5000 randomized evaluators
based upon it , generate all expressions as specified by the templates and
filling values , then apply the SMT - based minimization . Repeat for the
flags . Return a hash table containing the final candidates .
registers and a quadruple of atoms for use in filling the templates, and
an x86 instruction, JIT the instruction, make N=5000 randomized evaluators
based upon it, generate all expressions as specified by the templates and
filling values, then apply the SMT-based minimization. Repeat for the
flags. Return a hash table containing the final candidates. *)
let divine_semantics f_make bsmt q_templates q_reg_atoms q_imm_atoms instr size =
let _ = JITSampler.blit_instr f_blit instr in
let _ = Printf.printf "%s:\n%!" (X86Disasm.string_of_x86instr instr) in
let l_evalstmt,q_l_f_stmt,q_const = f_make () in
let blah2 = Z3Integration.mk_blah2 [("MODEL", "true");("SOFT_TIMEOUT", "10000")] in
let q =
let f size = function
| [] -> { val32 = []; val16 = []; val8 = []; val1 = []; }
| x -> try_all l_evalstmt q_l_f_stmt (X86PredicateGenerator.seq_generator x q_reg_atoms q_imm_atoms) size
in
match size with
| S32 -> f size q_templates.val32
| S16 -> f size q_templates.val16
| S8 -> f size q_templates.val8
| S1 -> f size q_templates.val1
in
let q_r_cand = refine_candidates q in
let q_r_cand = if bsmt then minimize_candidates_by_size blah2 q_r_cand size else q_r_cand in
let res =
match q_templates.val1 with
| [] -> q_r_cand
| _ ->
let el =
match size with
| S32 -> q_reg_atoms.val32
| S16 -> q_reg_atoms.val16
| S8 -> q_reg_atoms.val8
| S1 -> q_reg_atoms.val1
in
let el =
try
match size with
| S32 -> List.hd (Hashtbl.find q_r_cand.val32 X86.Eax)::el
| S16 -> List.hd (Hashtbl.find q_r_cand.val16 X86.Ax)::el
| S8 -> List.hd (Hashtbl.find q_r_cand.val8 X86.Al)::el
| S1 -> el
with _ -> el
in
let q_reg_atoms_extended = update_quad q_reg_atoms el size in
(* Printf.printf "Chose %s for the base component\n" (string_of_expr expr);*)
let seq_g = X86PredicateGenerator.seq_generator q_templates.val1 q_reg_atoms_extended q_imm_atoms in
let q = try_all l_evalstmt q_l_f_stmt seq_g S1 in
List.iter ( fun s - > Printf.printf " % s\n% ! " ( string_of_stmt s ) ) q.val1 ;
Printf.printf " Candidates\n " ;
List.iter ( fun s - > Printf.printf " % s\n " ( string_of_stmt s ) ) q.val1 ;
Printf.printf " \n " ;
Printf.printf "Candidates\n";
List.iter (fun s -> Printf.printf "%s\n" (string_of_stmt s)) q.val1;
Printf.printf "\n";*)
let q1 = { val32 = []; val16 = []; val8 = []; val1 = 1; } in
let q_r_cand1 = refine_candidates q1 in
let q_r_cand1 = if bsmt then minimize_candidates_by_size blah2 q_r_cand1 S1 else q_r_cand1 in
{ val32 = q_r_cand.val32; val16 = q_r_cand.val16; val8 = q_r_cand.val8; val1 = q_r_cand1.val1; }
in
print_results res;
res
let divine_semantics_exhaustive_8bit bcf = divine_semantics (fun _ -> exhaustive_al_cl bcf) false
let divine_semantics_random n = divine_semantics (fun _ -> mk_random_test_statement_evaluators n) true
let infinite_test l =
let rec aux i j =
if i = 1000000
then
let j = j + 1 in
Printf.printf "%dM tests done\n%!" j;
aux 0 j
else
let rec aux2 = function
| (i,l)::xs ->
let _ = JITSampler.blit_instr f_blit i in
let instate = JITSampler.mk_random_state c_stack32 in
let f_stmt,_,_,_,_ = make_fixed_test_statement_evaluator IOAnalysis.empty_clob IOAnalysis.default_x86_cp instate in
List.iter
(fun stmt ->
if not (f_stmt stmt)
then
let _ = Printf.printf "%s :: %s FAILED!\n" (X86Disasm.string_of_x86instr i) (string_of_stmt stmt) in
JITSampler.print_x86ctx instate)
l;
aux2 xs
| [] -> aux (i+1) j
in aux2 l
in
aux 0 0
| null | https://raw.githubusercontent.com/RolfRolles/PandemicML/9c31ecaf9c782dbbeb6cf502bc2a6730316d681e/Test/X86SemanticsDivinator.ml | ocaml | This code creates the JIT scaffolding necessary for testing
This code applies all test functions against expressions that have been
turned into statements.
Make such a function from a random input state
Delete this when done testing
Delete this when done testing
Delete this when done testing
Delete this when done testing
Some syntactic pruning to discard candidates with undesirable patterns
(constants-in-disguise, arithmetic identities).
Don't do constant folding
Equivalent to smaller Sub
Equivalent to smaller Add
Equivalent to smaller Sub
Produces -1
Equivalent to smaller term-in-itself
Don't fold constants
Equivalent to swapped Sub
If we end up with multiple equivalent candidates, we want to select the
"smallest" one according to some metric. This is that metric.
Given a quadruple of candidates, for each location, collect all expressions
and store them in a list. Return a quadruple of hash tables with this
information in them.
While distinguishing candidates, if the theorem prover returns a query, this
function is responsible for turning that query into an x86 state.
Indicates a bug
Possible for non-booleans
List.iter (fun (s,e) -> Printf.printf "%d: %s\n" s (string_of_expr e)) sorted;
Applies minimization to candidate of a specified size
This function takes as input a list of statement evaluators, a list of
statement-making functions as described previously, a sequential generator
object, and a size. It generates all candidate expressions, generates all
statements corresponding to those expressions being equal to some final
location, and then applies the statement evaluators to them. Those
statements that satisfy all evaluators are returned in a list.
Printf.printf "%s\n" (string_of_expr e);
Print the verified behaviors for all locations.
Printf.printf "Chose %s for the base component\n" (string_of_expr expr); | open X86Predicate
open DataStructures
let init_t,blit_t,retn_t,stack_t,c_stack32,mem_t,f_blit,f_execute = JITSampler.create_setup ()
let apply_all l_evalstmt stmt =
if l_evalstmt = [] then invalid_arg "apply_all";
let rec aux = function
( Printf.printf " Eliminated % s\n " ( string_of_stmt stmt ) ;
| [] -> true
in
aux l_evalstmt
let expand_single_and_apply_all l_evalstmt l_f_stmt acc expr =
let stmts = List.rev_map (fun f -> f expr) l_f_stmt in
List.fold_left (fun acc stmt -> if apply_all l_evalstmt stmt then stmt::acc else acc) acc stmts
let expand_and_apply_all l_evalstmt l_expr l_f_stmt =
List.fold_left (expand_single_and_apply_all l_evalstmt l_f_stmt) [] l_expr
This code makes a function ( stmt - > bool ) given an input state
let make_fixed_test_statement_evaluator q_clobbered x86_cp instate =
let outstate = f_execute instate in
let f_stmt =
let open X86PredicateEvaluator in
eval_stmt (y_combinator (eval_expr instate outstate)) instate outstate
in
let q_clobbered = IOAnalysis.get_clobbered f_stmt q_clobbered in
let x86_cp = IOAnalysis.join_x86_cp x86_cp (IOAnalysis.x86_cp_of_x86_state outstate) in
(f_stmt,q_clobbered,x86_cp,instate,outstate)
Make an input state where all 32 and 1 - bit values respectively match
let instate_all_same val32 val1 =
let open JITRegion in
{ eax = val32; ebx = val32; ecx = val32; edx = val32; esp = c_stack32; ebp = val32; esi = val32; edi = val32;
eflags = Int32.of_int (X86Misc.fl2eflags val1 val1 val1 val1 val1 val1 val1); }
let make_random_test_statement_evaluator q_clobbered x86_cp =
let instate = JITSampler.mk_random_state c_stack32 in
make_fixed_test_statement_evaluator q_clobbered x86_cp instate
let expand_state_by_flag state f =
let mask32 = X86Misc.mask32_of_x86_flags f in
let nmask32 = Int32.lognot mask32 in
let open JITRegion in
let flag_set = { state with eflags = Int32.logor state.eflags mask32; } in
let flag_nset = { state with eflags = Int32.logand state.eflags nmask32; } in
(flag_set,flag_nset)
let expand_state_by_flags state l_f =
let rec aux list = function
| f::fs ->
let rec aux2 outlist = function
| s::ss -> let s,n = expand_state_by_flag s f in aux2 (s::n::outlist) ss
| [] -> outlist
in aux (aux2 [] list) fs
| [] -> list
in aux [state] l_f
let expand_and_evaluate instate l_f list q cp =
let instates = expand_state_by_flags instate l_f in
List.fold_left
(fun (list,q,cp) instate ->
let f_stmt,q,cp,_,o = make_fixed_test_statement_evaluator q cp instate in
((f_stmt,instate,o)::list,q,cp))
(list,q,cp)
instates
let exhaustive_al_cl l_f =
let rec aux eax ecx q cp list =
match eax,ecx with
| 0x100l,0x100l -> (list,q,cp)
| 0x100l,_ -> aux 0x0l (Int32.succ ecx) q cp list
| _,_ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; JITRegion.ecx = ecx; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) ecx q cp list
in
let list,q_clob,x86_cp = aux 0l 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
let exhaustive_al l_f =
let rec aux eax q cp list =
match eax with
| 0x100l -> (list,q,cp)
| _ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) q cp list
in
let list,q_clob,x86_cp = aux 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
let exhaustive_ax l_f =
let rec aux eax q cp list =
match eax with
| 0x10000l -> (list,q,cp)
| _ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) q cp list
in
let list,q_clob,x86_cp = aux 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
let exhaustive_ax_cx4 l_f =
let rec aux eax ecx q cp list =
match eax,ecx with
| 0x10000l,0x10l -> (list,q,cp)
| 0x10000l,_ -> aux 0x0l (Int32.succ ecx) q cp list
| _,_ ->
let instate = JITSampler.mk_random_state c_stack32 in
let instate = { instate with JITRegion.eax = eax; JITRegion.ecx = ecx; } in
let list,q,cp = expand_and_evaluate instate l_f list q cp in
aux (Int32.succ eax) ecx q cp list
in
let list,q_clob,x86_cp = aux 0l 0l IOAnalysis.empty_clob IOAnalysis.default_x86_cp [] in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
Generate N randomized statement evaluators , along with some fixed evaluators .
Throughout this process , discover which locations are outputs ( i.e. their
output value differs from their input value ) , and which registers and flags
are always set to a constant value .
Return the list of evaluators , a quadruple of lists of functions that make
statements from expressions ( i.e. , if eax is the only output location , then
the 32 - bit component of the quadruple will be
( fun x - > RegEquals(X86Reg(X86.Gd(X86.Eax)),x ) ) ) , and a quadruple containing
sets of those locations that are constant .
Throughout this process, discover which locations are outputs (i.e. their
output value differs from their input value), and which registers and flags
are always set to a constant value.
Return the list of evaluators, a quadruple of lists of functions that make
statements from expressions (i.e., if eax is the only output location, then
the 32-bit component of the quadruple will be
(fun x -> RegEquals(X86Reg(X86.Gd(X86.Eax)),x))), and a quadruple containing
sets of those locations that are constant. *)
let mk_random_test_statement_evaluators n =
let rec aux i list q_clob x86_cp =
if i = n
then list,q_clob,x86_cp
else
let f_stmt,q_clob,x86_cp,instate,outstate = make_random_test_statement_evaluator q_clob x86_cp in
aux (i+1) ((f_stmt,instate,outstate)::list) q_clob x86_cp
in
let list,q_clob,x86_cp = aux 0 [] IOAnalysis.empty_clob IOAnalysis.default_x86_cp in
let rec aux2 list q_clob x86_cp = function
| x::xs ->
let f_stmt,q_clob,x86_cp,instate,outstate = make_fixed_test_statement_evaluator q_clob x86_cp x in
aux2 ((f_stmt,instate,outstate)::list) q_clob x86_cp xs
| [] -> list,q_clob,x86_cp
in
let list,q_clob,x86_cp =
let open JITRegion in
aux2
list
q_clob
x86_cp
[instate_all_same 0l 0;
instate_all_same 0l 1;
instate_all_same 0x80000000l 0;
instate_all_same 0x80000000l 1;
instate_all_same 0xffffffffl 0;
instate_all_same 0xffffffffl 1;
{ (instate_all_same 0x80000000l 0) with eax = 0l; };
{ (instate_all_same 0x80000000l 1) with eax = 0l; };
]
in
let q_l_f_stmt,q_const = IOAnalysis.finalize_analysis q_clob x86_cp in
(list,q_l_f_stmt,q_const)
let rec keep = function
| X86Flag(_) -> true
| X86Reg(_) -> true
| BitImm(_) -> true
| Imm(_) -> true
| Binop(Imm(_),_,Imm(_)) -> false
| Binop(BitImm(_),_,BitImm(_)) -> false
| Binop(Binop(l1,Or,r1),Add,Binop(l2,And,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
| Binop(Binop(l1,And,r1),Add,Binop(l2,Or,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
| Binop(Binop(l1,Add,r1),And,Binop(l2,Or,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
| Binop(Binop(l1,Or,r1),And,Binop(l2,Add,r2)) when (l1 = l2 && r1 = r2) || (l1 = r2 && r1 = l2) -> false
Sets to zero
| Binop(Unop(Not,l),And,r) when l = r -> false
| Binop(l,And,Unop(Not,r)) when l = r -> false
| Binop(l,Xor,r) when l = r -> false
| Binop(l,Sub,r) when l = r -> false
| Binop(Binop(l1,o1,r1),Xor,Binop(l2,o2,r2)) when o1 = o2 && is_commutative o1 && l1 = r2 && r1 = l2 -> false
| Binop(_,Sub,Unop(Neg,_)) -> false
| Binop(Unop(Neg,_),Add,_) -> false
| Binop(_,Add,Unop(Neg,_)) -> false
| Binop(Unop(Not,l),Add,r) when l = r -> false
| Binop(l,Add,Unop(Not,r)) when l = r -> false
| Binop(Unop(Not,l),Or,r) when l = r -> false
| Binop(l,Or,Unop(Not,r)) when l = r -> false
| Binop(Unop(Not,l),Xor,r) when l = r -> false
| Binop(l,Xor,Unop(Not,r)) when l = r -> false
| Binop(Unop(Dec,l),Sub,r) when l = r -> false
| Binop(l,Sub,Unop(Inc,r)) when l = r -> false
| Binop(l,Or, r) when l = r -> false
| Binop(l,And,r) when l = r -> false
| Binop(Binop(l1,o1,r1),Or, Binop(l2,o2,r2)) when o1 = o2 && is_commutative o1 && l1 = r2 && r1 = l2 -> false
| Binop(Binop(l1,o1,r1),And,Binop(l2,o2,r2)) when o1 = o2 && is_commutative o1 && l1 = r2 && r1 = l2 -> false
| Binop(l,o,r) -> keep l && keep r
| Unop(_,Imm(_)) -> false
| Unop(_,BitImm(_)) -> false
| Unop(Neg,Binop(_,Sub,_)) -> false
| Unop(_,e) -> keep e
| Bitop(_,Imm(_)) -> false
| Bitop(_,e) -> keep e
| Extend(_,_,e) -> keep e
| ITE(b,t,f) -> keep b && keep t && keep f
let rec score expr = let open X86Predicate in match expr with
| X86Flag(_) -> 1
| X86Reg(_) -> 1
| BitImm(_) -> 1
| Imm(X86.Id(i32)) -> if i32 = 0l then 1 else 3
| Imm(X86.Iw(i16)) -> if i16 = 0l then 1 else 3
| Imm(X86.Ib(i8 )) -> if i8 = 0l then 1 else 3
| Binop(l,(Eq|Ne),r) -> 1 + (score l) + (score r)
| Binop(l,(And|Or|Xor),r) -> 3 + (score l) + (score r)
| Binop(l,(Slt|Sle|Ult|Ule),r) -> 7 + (score l) + (score r)
| Binop(l,_,r) -> 15 + (score l) + (score r)
| Unop(_,e) -> 1 + (score e)
| Bitop(FifthBit,e) -> 1 + (score e)
| Bitop(Parity,e) -> 1 + (score e)
| Bitop(SignBit,e) -> 50 + (score e)
| Bitop(SecondBit,e) -> 50 + (score e)
| Extend(Low,_,e) -> 1000 + (score e)
| Extend(_,_,e) -> 20 + (score e)
| ITE(b,t,f) -> 1000 + (score b) + (score t) + (score f)
let refine_candidates q_cand =
let ht32 = Hashtbl.create 17 in
let ht16 = Hashtbl.create 17 in
let ht8 = Hashtbl.create 17 in
let ht1 = Hashtbl.create 17 in
let add h k v =
let res = try Hashtbl.find h k with Not_found -> [] in
Hashtbl.replace h k (v::res)
in
let aux = function
| FlagEquals(f,e) -> add ht1 f e
| RegEquals(X86.Gd(r32),e) -> add ht32 r32 e
| RegEquals(X86.Gw(r16),e) -> add ht16 r16 e
| RegEquals(X86.Gb(r8) ,e) -> add ht8 r8 e
| ImmEquals(_,e) -> Printf.printf "Skipping imm equals for now\n"
in
List.iter aux q_cand.val32;
List.iter aux q_cand.val16;
List.iter aux q_cand.val8;
List.iter aux q_cand.val1;
{
val32 = ht32;
val16 = ht16;
val8 = ht8;
val1 = ht1;
}
let reify_counterexample l =
let instate = JITSampler.mk_random_state c_stack32 in
let update f32 p b =
let i32 = Int32.shift_left 1l p in
if b
then Int32.logor f32 i32
else Int32.logand f32 (Int32.lognot i32)
in
let open JITRegion in
let aux s = function
| RegEquals(X86.Gd(X86.Eax),Imm(X86.Id(v32))) -> { s with eax = v32; }
| RegEquals(X86.Gd(X86.Ebx),Imm(X86.Id(v32))) -> { s with ebx = v32; }
| RegEquals(X86.Gd(X86.Ecx),Imm(X86.Id(v32))) -> { s with ecx = v32; }
| RegEquals(X86.Gd(X86.Edx),Imm(X86.Id(v32))) -> { s with edx = v32; }
| RegEquals(X86.Gd(X86.Esp),Imm(X86.Id(v32))) -> { s with esp = v32; }
| RegEquals(X86.Gd(X86.Ebp),Imm(X86.Id(v32))) -> { s with ebp = v32; }
| RegEquals(X86.Gd(X86.Esi),Imm(X86.Id(v32))) -> { s with esi = v32; }
| RegEquals(X86.Gd(X86.Edi),Imm(X86.Id(v32))) -> { s with edi = v32; }
| FlagEquals(X86.X86F_C,BitImm(b)) -> { s with eflags = update s.eflags 0 b }
| FlagEquals(X86.X86F_P,BitImm(b)) -> { s with eflags = update s.eflags 2 b }
| FlagEquals(X86.X86F_A,BitImm(b)) -> { s with eflags = update s.eflags 4 b }
| FlagEquals(X86.X86F_Z,BitImm(b)) -> { s with eflags = update s.eflags 6 b }
| FlagEquals(X86.X86F_S,BitImm(b)) -> { s with eflags = update s.eflags 7 b }
| FlagEquals(X86.X86F_D,BitImm(b)) -> { s with eflags = update s.eflags 10 b }
| FlagEquals(X86.X86F_O,BitImm(b)) -> { s with eflags = update s.eflags 11 b }
| _ -> invalid_arg "reify_counterxample"
in
List.fold_left aux instate l
Takes an ( expr * expr list ) option and an expr . Either :
1 ) Eliminate the first and return Some(second )
2 ) Eliminate the second and return o_current
3 ) Decide that they are indistinct and return Some(first , second::list )
1) Eliminate the first and return Some(second)
2) Eliminate the second and return o_current
3) Decide that they are indistinct and return Some(first,second::list) *)
let deathmatch f_stmt_maker f_dist f o_current e_challenger =
match o_current with
| None -> Some(e_challenger,[])
| Some(e_current,l_indistinct) ->
let x = f_dist f e_challenger e_current in
Printf.printf " Distinguishing % s from % s\n " ( string_of_expr e_current ) ( string_of_expr e_challenger ) ;
match x with
| [] ->
if score e_current <= score e_challenger
then Some(e_current,e_challenger::l_indistinct)
else Some(e_challenger,e_current::l_indistinct)
| l -> let c = reify_counterexample l in
let outstate = f_execute c in
let f_stmt =
let open X86PredicateEvaluator in
eval_stmt (y_combinator (eval_expr c outstate)) c outstate
in
let s_el = f_stmt_maker f e_challenger in
let b_el = f_stmt s_el in
let s_el2 = f_stmt_maker f e_current in
let b_el2 = f_stmt s_el2 in
Printf.printf " Distinguishing % s from % s using counterexample:\n " ( string_of_stmt s_el ) ( string_of_stmt s_el2 ) ;
List.iter ( fun s - > Printf.printf " % s\n " ( string_of_stmt s ) ) l ;
List.iter (fun s -> Printf.printf "%s\n" (string_of_stmt s)) l;*)
match b_el,b_el2 with
| true,true ->
Printf.printf
"Input did not distinguish?\nChal: %s\nCurr: %s\nState before:\n"
(string_of_stmt s_el)
(string_of_stmt s_el2);
JITSampler.print_x86ctx c;
Printf.printf "State after:\n";
JITSampler.print_x86ctx outstate;
List.iter (fun s -> Printf.printf "%s\n" (string_of_stmt s)) l;
None
| true,false ->
Printf.printf " Eliminated % s\n " ( string_of_stmt s_el2 ) ;
Some(e_challenger,[])
| false,true ->
Printf.printf " Eliminated % s\n " ( string_of_stmt s_el ) ;
Some(e_current,l_indistinct)
| false,false -> None
let deathmatch_single f_stmt_maker f_dist expr1 = deathmatch f_stmt_maker f_dist (Some(expr1,[]))
This is the SMT magic . Given a hash table location - > [ candidates ] , winnow
and merge the candidates based upon whether the theorem prover says that
they are identical . The output is one pruned list of candidates , sorted
by score , where the candidates passed all the checks and are assumed after
this point to represent the true behaviors of the instructions .
and merge the candidates based upon whether the theorem prover says that
they are identical. The output is one pruned list of candidates, sorted
by score, where the candidates passed all the checks and are assumed after
this point to represent the true behaviors of the instructions. *)
let minimize_candidates ht_cand f_stmt_maker f_dist =
let ht_new = Hashtbl.create 17 in
Hashtbl.iter (fun f l ->
let scres =
match (List.fold_left (deathmatch f_stmt_maker f_dist f) (None) l) with
| Some(x,y) -> x::y
| None -> []
in
let scres = List.map (fun x -> (score x,x)) scres in
let sorted = List.sort (fun (s1,_) (s2,_) -> Pervasives.compare s1 s2) scres in
let res = List.map snd sorted in
Hashtbl.replace ht_new f res)
ht_cand;
ht_new
let minimize_candidates_by_size d q sz =
let open X86Predicate in
let open Z3Integration in
match sz with
| S32 -> { q with val32 = (minimize_candidates q.val32 (fun x e -> RegEquals(X86.Gd(x),e)) (distinguish_reg32 d)); }
| S16 -> { q with val16 = (minimize_candidates q.val16 (fun x e -> RegEquals(X86.Gw(x),e)) (distinguish_reg16 d)); }
| S8 -> { q with val8 = (minimize_candidates q.val8 (fun x e -> RegEquals(X86.Gb(x),e)) (distinguish_reg8 d)); }
| S1 -> { q with val1 = (minimize_candidates q.val1 (fun x e -> FlagEquals(x,e)) (distinguish_flag d)); }
let try_all l_evalstmt q_l_f_stmt seq_g esize =
let rec aux quad =
let _,e = seq_g#yield_current () in
let quad =
if keep e
then
update_quad
quad
(expand_single_and_apply_all l_evalstmt (select_quad q_l_f_stmt esize) (select_quad quad esize) e)
esize
else quad
in
let continue =
try (seq_g#increase_current (); true)
with X86PredicateGenerator.Lapsed -> false
in
if continue then aux quad else quad
in
aux { val32 = []; val16 = []; val8 = []; val1 = [] }
let print_results q_res =
let print ht f_descr =
Hashtbl.iter (fun f l -> List.iter (fun x -> Printf.printf "%s: %s\n" (f_descr f) (string_of_expr x)) l)
let str = match l with x : : _ - > string_of_expr x | [ ] - > " NONE ! " in
Printf.printf " % s : % s\n " ( f_descr f ) )
Printf.printf "%s: %s\n" (f_descr f) str)*)
ht
in
print q_res.val32 X86Disasm.string_of_x86_reg32;
print q_res.val16 X86Disasm.string_of_x86_reg16;
print q_res.val8 X86Disasm.string_of_x86_reg8;
print q_res.val1 X86Disasm.string_of_x86_flags
The top - level function . Given a quadruple of templates , a quadruple of
registers and a quadruple of atoms for use in filling the templates , and
an x86 instruction , JIT the instruction , make N=5000 randomized evaluators
based upon it , generate all expressions as specified by the templates and
filling values , then apply the SMT - based minimization . Repeat for the
flags . Return a hash table containing the final candidates .
registers and a quadruple of atoms for use in filling the templates, and
an x86 instruction, JIT the instruction, make N=5000 randomized evaluators
based upon it, generate all expressions as specified by the templates and
filling values, then apply the SMT-based minimization. Repeat for the
flags. Return a hash table containing the final candidates. *)
let divine_semantics f_make bsmt q_templates q_reg_atoms q_imm_atoms instr size =
let _ = JITSampler.blit_instr f_blit instr in
let _ = Printf.printf "%s:\n%!" (X86Disasm.string_of_x86instr instr) in
let l_evalstmt,q_l_f_stmt,q_const = f_make () in
let blah2 = Z3Integration.mk_blah2 [("MODEL", "true");("SOFT_TIMEOUT", "10000")] in
let q =
let f size = function
| [] -> { val32 = []; val16 = []; val8 = []; val1 = []; }
| x -> try_all l_evalstmt q_l_f_stmt (X86PredicateGenerator.seq_generator x q_reg_atoms q_imm_atoms) size
in
match size with
| S32 -> f size q_templates.val32
| S16 -> f size q_templates.val16
| S8 -> f size q_templates.val8
| S1 -> f size q_templates.val1
in
let q_r_cand = refine_candidates q in
let q_r_cand = if bsmt then minimize_candidates_by_size blah2 q_r_cand size else q_r_cand in
let res =
match q_templates.val1 with
| [] -> q_r_cand
| _ ->
let el =
match size with
| S32 -> q_reg_atoms.val32
| S16 -> q_reg_atoms.val16
| S8 -> q_reg_atoms.val8
| S1 -> q_reg_atoms.val1
in
let el =
try
match size with
| S32 -> List.hd (Hashtbl.find q_r_cand.val32 X86.Eax)::el
| S16 -> List.hd (Hashtbl.find q_r_cand.val16 X86.Ax)::el
| S8 -> List.hd (Hashtbl.find q_r_cand.val8 X86.Al)::el
| S1 -> el
with _ -> el
in
let q_reg_atoms_extended = update_quad q_reg_atoms el size in
let seq_g = X86PredicateGenerator.seq_generator q_templates.val1 q_reg_atoms_extended q_imm_atoms in
let q = try_all l_evalstmt q_l_f_stmt seq_g S1 in
List.iter ( fun s - > Printf.printf " % s\n% ! " ( string_of_stmt s ) ) q.val1 ;
Printf.printf " Candidates\n " ;
List.iter ( fun s - > Printf.printf " % s\n " ( string_of_stmt s ) ) q.val1 ;
Printf.printf " \n " ;
Printf.printf "Candidates\n";
List.iter (fun s -> Printf.printf "%s\n" (string_of_stmt s)) q.val1;
Printf.printf "\n";*)
let q1 = { val32 = []; val16 = []; val8 = []; val1 = 1; } in
let q_r_cand1 = refine_candidates q1 in
let q_r_cand1 = if bsmt then minimize_candidates_by_size blah2 q_r_cand1 S1 else q_r_cand1 in
{ val32 = q_r_cand.val32; val16 = q_r_cand.val16; val8 = q_r_cand.val8; val1 = q_r_cand1.val1; }
in
print_results res;
res
let divine_semantics_exhaustive_8bit bcf = divine_semantics (fun _ -> exhaustive_al_cl bcf) false
let divine_semantics_random n = divine_semantics (fun _ -> mk_random_test_statement_evaluators n) true
let infinite_test l =
let rec aux i j =
if i = 1000000
then
let j = j + 1 in
Printf.printf "%dM tests done\n%!" j;
aux 0 j
else
let rec aux2 = function
| (i,l)::xs ->
let _ = JITSampler.blit_instr f_blit i in
let instate = JITSampler.mk_random_state c_stack32 in
let f_stmt,_,_,_,_ = make_fixed_test_statement_evaluator IOAnalysis.empty_clob IOAnalysis.default_x86_cp instate in
List.iter
(fun stmt ->
if not (f_stmt stmt)
then
let _ = Printf.printf "%s :: %s FAILED!\n" (X86Disasm.string_of_x86instr i) (string_of_stmt stmt) in
JITSampler.print_x86ctx instate)
l;
aux2 xs
| [] -> aux (i+1) j
in aux2 l
in
aux 0 0
|
c29def7e18d2757fa98187684c39b536fad34d7af9ca84e74608253dd6026dcd | w3ntao/programming-in-haskell | Exercise_12_5_1.hs | # OPTIONS_GHC -Wall #
module Exercise_12_5_1 where
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving Show
instance Functor Tree where
fmap _ Leaf = Leaf
fmap g (Node l x r) = Node (fmap g l) (g x) (fmap g r) | null | https://raw.githubusercontent.com/w3ntao/programming-in-haskell/c2769fa19d8507aad209818c83f67e82c3698f07/Chapter-12/Exercise_12_5_1.hs | haskell | # OPTIONS_GHC -Wall #
module Exercise_12_5_1 where
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving Show
instance Functor Tree where
fmap _ Leaf = Leaf
fmap g (Node l x r) = Node (fmap g l) (g x) (fmap g r) |
|
e540904903b57f727a1a48af8c9f3fc2a0b79e7dc350137dc6d3d75ba44efd42 | kelamg/HtDP2e-workthrough | ex347.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 ex347) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(require 2htdp/abstraction)
(define-struct add [left right])
(define-struct mul [left right])
A BSL - expr is one of :
;; - Number
- ( make - add BSL - expr BSL - expr )
- ( make - mul BSL - expr BSL - expr )
A NumRet is a Number
BSL - expr - > NumRet
computes the value of bexpr
(check-expect (eval-expression 3) 3)
(check-expect
(eval-expression (make-add 1 1)) 2)
(check-expect
(eval-expression (make-mul 3 10)) 30)
(check-expect
(eval-expression (make-add (make-mul 1 1) 10)) 11)
(define (eval-expression bexpr)
(match bexpr
[(? number?) bexpr]
[(add l r) (+ (eval-expression l) (eval-expression r))]
[(mul l r) (* (eval-expression l) (eval-expression r))])) | null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Intertwined-Data/ex347.rkt | racket | about the language level of this file in a form that our tools can easily process.
- Number | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex347) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(require 2htdp/abstraction)
(define-struct add [left right])
(define-struct mul [left right])
A BSL - expr is one of :
- ( make - add BSL - expr BSL - expr )
- ( make - mul BSL - expr BSL - expr )
A NumRet is a Number
BSL - expr - > NumRet
computes the value of bexpr
(check-expect (eval-expression 3) 3)
(check-expect
(eval-expression (make-add 1 1)) 2)
(check-expect
(eval-expression (make-mul 3 10)) 30)
(check-expect
(eval-expression (make-add (make-mul 1 1) 10)) 11)
(define (eval-expression bexpr)
(match bexpr
[(? number?) bexpr]
[(add l r) (+ (eval-expression l) (eval-expression r))]
[(mul l r) (* (eval-expression l) (eval-expression r))])) |
8c12bcdafdfcdb42bb19ec4fac88c187270a687ca319571bda8b8ab5dab00b16 | chaoxu/fancy-walks | 25.hs |
fib = 1 : 1 : zipWith (+) fib (tail fib)
problem_25 = (+1).length $ takeWhile ((<1000).length.show) fib
main = print problem_25
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/25.hs | haskell |
fib = 1 : 1 : zipWith (+) fib (tail fib)
problem_25 = (+1).length $ takeWhile ((<1000).length.show) fib
main = print problem_25
|
|
4986e8e1420d20a6d109b9a65f0f0431cacd8f9d89210cc711b8a9d9ee07c57e | racket/typed-racket | dead-code.rkt | #lang racket/base
(require syntax/parse syntax/stx racket/sequence
racket/syntax
(for-template racket/base)
"../utils/utils.rkt"
(only-in "../utils/tc-utils.rkt" current-type-enforcement-mode deep)
"../types/type-table.rkt"
"utils.rkt"
"logging.rkt")
(provide dead-code-opt-expr)
;; The type based 'dead code elimination' done by this file just makes the dead code obvious.
;; The actual elimination step is left to the compiler.
(define-syntax-class dead-code-opt-expr
#:commit
#:literal-sets (kernel-literals)
(pattern ((~and kw if) tst:opt-expr thn:opt-expr els:opt-expr)
#:do [(define takes-true (test-position-takes-true-branch #'tst))
(define takes-false (test-position-takes-false-branch #'tst))
(unless takes-true
(log-optimization "dead then branch" "Unreachable then branch elimination." #'thn))
(unless takes-false
(log-optimization "dead else branch" "Unreachable else branch elimination." #'els))]
#:with thn-opt (if takes-true #'thn.opt #'thn)
#:with els-opt (if takes-false #'els.opt #'els)
;; if the conditional has a known truth value, we can reveal this
;; we have to keep the test, in case it has side effects
#:with opt
(cond
[(and (not takes-true) (not takes-false))
(quasisyntax/loc/origin this-syntax #'kw
(if #t tst.opt (begin thn-opt els-opt)))]
[else
(define/with-syntax tst-opt
(cond
[(and takes-true takes-false) #'tst.opt]
[takes-true #'(begin tst.opt #t)]
[takes-false #'(begin tst.opt #f)]))
(quasisyntax/loc/origin this-syntax #'kw
(if tst-opt thn-opt els-opt))]))
(pattern ((~and kw lambda) formals . bodies)
#:when (eq? deep (current-type-enforcement-mode))
#:when (dead-lambda-branch? #'formals)
#:with opt this-syntax)
(pattern ((~and kw case-lambda) (formals . bodies) ...)
#:when (eq? deep (current-type-enforcement-mode))
#:when (for/or ((formals (in-syntax #'(formals ...))))
(dead-lambda-branch? formals))
#:with opt
(quasisyntax/loc/origin
this-syntax #'kw
(begin0
(case-lambda
#,@(for/list ((formals (in-syntax #'(formals ...)))
(bodies (in-syntax #'(bodies ...))))
(if (dead-lambda-branch? formals)
;; keep the clause (to have a case-lambda with the right arity)
;; but not the body (to make the function smaller for inlining)
TODO could do better , and keep a single clause per arity
(list formals #'(void)) ; return type doesn't matter, should never run
(cons formals (stx-map (optimize) bodies)))))
;; We need to keep the syntax objects around in the generated code with the correct bindings
so that CheckSyntax displays the arrows correctly
#,@(for/list ((formals (in-syntax #'(formals ...)))
(bodies (in-syntax #'(bodies ...)))
#:when (dead-lambda-branch? formals))
(log-optimization
"dead case-lambda branch"
"Unreachable case-lambda branch elimination."
formals)
#`(λ #,formals . #,bodies))))))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-lib/typed-racket/optimizer/dead-code.rkt | racket | The type based 'dead code elimination' done by this file just makes the dead code obvious.
The actual elimination step is left to the compiler.
if the conditional has a known truth value, we can reveal this
we have to keep the test, in case it has side effects
keep the clause (to have a case-lambda with the right arity)
but not the body (to make the function smaller for inlining)
return type doesn't matter, should never run
We need to keep the syntax objects around in the generated code with the correct bindings | #lang racket/base
(require syntax/parse syntax/stx racket/sequence
racket/syntax
(for-template racket/base)
"../utils/utils.rkt"
(only-in "../utils/tc-utils.rkt" current-type-enforcement-mode deep)
"../types/type-table.rkt"
"utils.rkt"
"logging.rkt")
(provide dead-code-opt-expr)
(define-syntax-class dead-code-opt-expr
#:commit
#:literal-sets (kernel-literals)
(pattern ((~and kw if) tst:opt-expr thn:opt-expr els:opt-expr)
#:do [(define takes-true (test-position-takes-true-branch #'tst))
(define takes-false (test-position-takes-false-branch #'tst))
(unless takes-true
(log-optimization "dead then branch" "Unreachable then branch elimination." #'thn))
(unless takes-false
(log-optimization "dead else branch" "Unreachable else branch elimination." #'els))]
#:with thn-opt (if takes-true #'thn.opt #'thn)
#:with els-opt (if takes-false #'els.opt #'els)
#:with opt
(cond
[(and (not takes-true) (not takes-false))
(quasisyntax/loc/origin this-syntax #'kw
(if #t tst.opt (begin thn-opt els-opt)))]
[else
(define/with-syntax tst-opt
(cond
[(and takes-true takes-false) #'tst.opt]
[takes-true #'(begin tst.opt #t)]
[takes-false #'(begin tst.opt #f)]))
(quasisyntax/loc/origin this-syntax #'kw
(if tst-opt thn-opt els-opt))]))
(pattern ((~and kw lambda) formals . bodies)
#:when (eq? deep (current-type-enforcement-mode))
#:when (dead-lambda-branch? #'formals)
#:with opt this-syntax)
(pattern ((~and kw case-lambda) (formals . bodies) ...)
#:when (eq? deep (current-type-enforcement-mode))
#:when (for/or ((formals (in-syntax #'(formals ...))))
(dead-lambda-branch? formals))
#:with opt
(quasisyntax/loc/origin
this-syntax #'kw
(begin0
(case-lambda
#,@(for/list ((formals (in-syntax #'(formals ...)))
(bodies (in-syntax #'(bodies ...))))
(if (dead-lambda-branch? formals)
TODO could do better , and keep a single clause per arity
(cons formals (stx-map (optimize) bodies)))))
so that CheckSyntax displays the arrows correctly
#,@(for/list ((formals (in-syntax #'(formals ...)))
(bodies (in-syntax #'(bodies ...)))
#:when (dead-lambda-branch? formals))
(log-optimization
"dead case-lambda branch"
"Unreachable case-lambda branch elimination."
formals)
#`(λ #,formals . #,bodies))))))
|
8f7bbb64b7e253c01829af7b666cfb6543b8852338e6c92d8700bd87a9f8bd24 | victornicolet/parsynt | Lib.ml | module Log = Utils.Log
module Config = Utils.Config
module Lang = struct
module AC = Lang.AcTerm
module A = Lang.Analyze
module E = Lang.SolutionDescriptors
module N = Lang.Normalize
module T = struct
include Lang.Typ
include Lang.Term
module Pp = Lang.TermPp
end
module U = Lang.Unfold
module R = Lang.ResourceModel
end
module Front = struct
module C = Front.MinicFront
end
module C = Commands
module D = Recursion.Discover
module St = Solve.STerm
module Sf = Solve.SolverForms
module Smt = Solve.SmtLib
module Scripting = Solve.Scripting
module Builders = Recursion.SketchBuilders
(* Modules exposed for testing purposes *)
module Testing_RD = Recursion.RecursionDiscovery
| null | https://raw.githubusercontent.com/victornicolet/parsynt/d3f530923c0c75537b92c2930eb882921f38268c/src/Lib.ml | ocaml | Modules exposed for testing purposes | module Log = Utils.Log
module Config = Utils.Config
module Lang = struct
module AC = Lang.AcTerm
module A = Lang.Analyze
module E = Lang.SolutionDescriptors
module N = Lang.Normalize
module T = struct
include Lang.Typ
include Lang.Term
module Pp = Lang.TermPp
end
module U = Lang.Unfold
module R = Lang.ResourceModel
end
module Front = struct
module C = Front.MinicFront
end
module C = Commands
module D = Recursion.Discover
module St = Solve.STerm
module Sf = Solve.SolverForms
module Smt = Solve.SmtLib
module Scripting = Solve.Scripting
module Builders = Recursion.SketchBuilders
module Testing_RD = Recursion.RecursionDiscovery
|
0f7962d185aee7e48940e61fb78053cfdd662b23bb13937920b52feb111ece55 | sionescu/iolib | types.lisp | ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
;;;
;;; --- Types.
;;;
(in-package :iolib/base)
(deftype function-designator ()
'(or symbol function))
(defun symbol-with-name-of-length-one (thing)
(if (and (symbolp thing)
(= 1 (length (symbol-name thing))))
(char (symbol-name thing) 0)
nil))
(deftype character-designator ()
'(or character (string 1) (satisfies symbol-with-name-of-length-one)))
;; Vector types
(deftype ub8 () '(unsigned-byte 8))
(deftype ub16 () '(unsigned-byte 16))
(deftype ub32 () '(unsigned-byte 32))
(deftype ub64 () '(unsigned-byte 64))
(deftype sb8 () '(signed-byte 8))
(deftype sb16 () '(signed-byte 16))
(deftype sb32 () '(signed-byte 32))
(deftype sb64 () '(signed-byte 64))
(deftype ub8-sarray (&optional (size '*))
`(simple-array ub8 (,size)))
(deftype ub8-vector (&optional (size '*))
`(vector ub8 ,size))
(deftype ub16-sarray (&optional (size '*))
`(simple-array ub16 (,size)))
(deftype ub16-vector (&optional (size '*))
`(vector ub16 ,size))
(deftype ub32-sarray (&optional (size '*))
`(simple-array ub32 (,size)))
(deftype ub32-vector (&optional (size '*))
`(vector ub32 ,size))
(deftype ub64-sarray (&optional (size '*))
`(simple-array ub64 (,size)))
(deftype ub64-vector (&optional (size '*))
`(vector ub64 ,size))
| null | https://raw.githubusercontent.com/sionescu/iolib/dac715c81db55704db623d8b2cfc399ebcf6175f/src/base/types.lisp | lisp | -*- Mode: Lisp; indent-tabs-mode: nil -*-
--- Types.
Vector types |
(in-package :iolib/base)
(deftype function-designator ()
'(or symbol function))
(defun symbol-with-name-of-length-one (thing)
(if (and (symbolp thing)
(= 1 (length (symbol-name thing))))
(char (symbol-name thing) 0)
nil))
(deftype character-designator ()
'(or character (string 1) (satisfies symbol-with-name-of-length-one)))
(deftype ub8 () '(unsigned-byte 8))
(deftype ub16 () '(unsigned-byte 16))
(deftype ub32 () '(unsigned-byte 32))
(deftype ub64 () '(unsigned-byte 64))
(deftype sb8 () '(signed-byte 8))
(deftype sb16 () '(signed-byte 16))
(deftype sb32 () '(signed-byte 32))
(deftype sb64 () '(signed-byte 64))
(deftype ub8-sarray (&optional (size '*))
`(simple-array ub8 (,size)))
(deftype ub8-vector (&optional (size '*))
`(vector ub8 ,size))
(deftype ub16-sarray (&optional (size '*))
`(simple-array ub16 (,size)))
(deftype ub16-vector (&optional (size '*))
`(vector ub16 ,size))
(deftype ub32-sarray (&optional (size '*))
`(simple-array ub32 (,size)))
(deftype ub32-vector (&optional (size '*))
`(vector ub32 ,size))
(deftype ub64-sarray (&optional (size '*))
`(simple-array ub64 (,size)))
(deftype ub64-vector (&optional (size '*))
`(vector ub64 ,size))
|
6fe6db536c621a56a9c1805e1332f1c69cf43302a273366abdca26605ca1077d | dmjio/graphql-meta | LexerUtils.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveDataTypeable #-}
--------------------------------------------------------------------------------
-- |
-- Module : GraphQL.LexerUtils
Description : / Tokenizer of GraphQL document per GraphQL specification
Maintainer : < > , < >
-- Maturity : Usable
--
--------------------------------------------------------------------------------
module GraphQL.LexerUtils where
import Control.DeepSeq
import Control.Monad.State
import Data.Data
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Word
import GHC.Generics
import Text.Read hiding (get)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Internal as B (w2c)
-- | A GraphQL 'Operation' type
data OperationType
= Query
| Subscription
| Mutation
deriving (Show, Eq, Data, Read, Generic, Typeable, Enum)
instance NFData OperationType
-- | /#ExecutableDirectiveLocation
data ExecutableDirectiveLocation
= QUERY
| MUTATION
| SUBSCRIPTION
| FIELD
| FRAGMENT_DEFINITION
| FRAGMENT_SPREAD
| INLINE_FRAGMENT
deriving (Show, Eq, Read, Data, Generic, Typeable, Enum)
instance NFData ExecutableDirectiveLocation
-- | /#TypeSystemDirectiveLocation
data TypeSystemDirectiveLocation
= SCHEMA
| SCALAR
| OBJECT
| FIELD_DEFINITION
| ARGUMENT_DEFINITION
| INTERFACE
| UNION
| ENUM
| ENUM_VALUE
| INPUT_OBJECT
| INPUT_FIELD_DEFINITION
deriving (Show, Eq, Read, Data, Generic, Typeable, Enum)
instance NFData TypeSystemDirectiveLocation
| Token unit for lexing the GraphQL specification
data Token
= TokenInt Int
| TokenFloat Double
| TokenName Text
| TokenString StringValue
| TokenReserved Text
| TokenPunctuator Char
| TokenMultiPunctuator Text
| TokenBool Bool
| TokenError Error
| TokenOperator OperationType
| TokenExecutableDirectiveLocation ExecutableDirectiveLocation
| TokenTypeSystemDirectiveLocation TypeSystemDirectiveLocation
| TokenNull
deriving (Show, Eq, Data, Read, Generic, Typeable)
data Error
= ConversionError Text Text
| LexerError Text
| NoMatch Text
| UntermBlockString
| UntermString
deriving (Show, Eq, Data, Read, Generic, Typeable)
instance NFData Error
data AlexInput = AlexInput
{ alexChar :: {-# UNPACK #-} !Char
, alexStr :: {-# UNPACK #-} !B.ByteString
, alexBytePos :: {-# UNPACK #-} !Int
} deriving (Show, Eq)
data LexerState
= LexerState
{ matchedInput :: !AlexInput
, lexerMode :: !LexerMode
, stringBuffer :: !ByteString
} deriving (Show, Eq)
type Action = Int -> AlexInput -> State LexerState (Maybe Token)
data StringValue
= StringValue StringType T.Text
deriving (Show, Eq, Data, Read, Generic, Typeable)
instance NFData StringValue
token :: (ByteString -> Token) -> Action
token f inputLength _ = do
LexerState {..} <- get
pure . pure $ f (B.take inputLength (alexStr matchedInput))
token_ :: Token -> Action
token_ = token . const
data StringType
= SingleLine
| BlockString
deriving (Show, Eq, Data, Read, Generic, Typeable, NFData)
data LexerMode
= InNormal
| InBlockString
| InString
deriving (Show, Eq)
processEscapedCharacter :: Action
processEscapedCharacter = appendMode
processEscapedUnicode :: Action
processEscapedUnicode = appendMode
appendMode :: Action
appendMode = action
action :: Action
action len bs = do
s@LexerState {..} <- get
put s { stringBuffer = stringBuffer `B.append` B.take len (alexStr bs) }
pure Nothing
appendModeBlock :: Action
appendModeBlock = action
endMode :: Action
endMode _ _ = do
mode <- gets lexerMode
case mode of
InNormal -> pure Nothing
InBlockString -> apply BlockString
InString -> apply SingleLine
where
apply stringType = do
buf <- gets stringBuffer
modify $ \s -> s { lexerMode = InNormal, stringBuffer = mempty }
pure $ Just $ TokenString $ StringValue stringType (T.decodeUtf8 buf)
eofAction :: State LexerState [Token]
eofAction = do
mode <- gets lexerMode
pure $ case mode of
InBlockString -> [TokenError UntermBlockString]
InString -> [TokenError UntermString]
InNormal -> []
errorAction :: AlexInput -> State LexerState [Token]
errorAction AlexInput {..} =
pure [TokenError (NoMatch (T.decodeUtf8 alexStr))]
startBlockString :: Action
startBlockString _ _ =
Nothing <$ do
modify $ \s -> s { lexerMode = InBlockString }
startString :: Action
startString _ _ =
Nothing <$ do
modify $ \s -> s { lexerMode = InString }
alexInputPrevChar :: AlexInput -> Char
alexInputPrevChar = alexChar
alexGetByte :: AlexInput -> Maybe (Word8, AlexInput)
alexGetByte AlexInput {..} =
case B.uncons alexStr of
Nothing -> Nothing
Just (c, rest) ->
Just (c, AlexInput {
alexChar = B.w2c c,
alexStr = rest,
alexBytePos = alexBytePos+1
})
parseIntToken :: ByteString -> Token
parseIntToken s =
maybe (TokenError $ ConversionError "Not a valid int" (T.decodeUtf8 s)) TokenInt (readMaybe (T.unpack $ T.decodeUtf8 s))
parseFloatToken :: ByteString -> Token
parseFloatToken s =
maybe (TokenError $ ConversionError "Not a valid float" (T.decodeUtf8 s)) TokenFloat (readMaybe (B8.unpack s))
parseExecutableDirectiveLocationToken :: ByteString -> Token
parseExecutableDirectiveLocationToken s =
case readMaybe (T.unpack $ T.decodeUtf8 s) :: Maybe ExecutableDirectiveLocation of
Just r -> TokenExecutableDirectiveLocation r
Nothing -> TokenError (ConversionError "Invalid ExecutableDirectiveLocation" (T.decodeUtf8 s))
parseTypeSystemDirectiveLocationToken :: ByteString -> Token
parseTypeSystemDirectiveLocationToken s =
case readMaybe (T.unpack $ T.decodeUtf8 s) :: Maybe TypeSystemDirectiveLocation of
Just r -> TokenTypeSystemDirectiveLocation r
Nothing -> TokenError (ConversionError "Invalid TypeSystemDirectiveLocation" (T.decodeUtf8 s))
| null | https://raw.githubusercontent.com/dmjio/graphql-meta/3fc759d6976a9ea1429e23fe1c6a9e6adb45e372/src/GraphQL/LexerUtils.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable #
------------------------------------------------------------------------------
|
Module : GraphQL.LexerUtils
Maturity : Usable
------------------------------------------------------------------------------
| A GraphQL 'Operation' type
| /#ExecutableDirectiveLocation
| /#TypeSystemDirectiveLocation
# UNPACK #
# UNPACK #
# UNPACK # | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE DeriveGeneric #
Description : / Tokenizer of GraphQL document per GraphQL specification
Maintainer : < > , < >
module GraphQL.LexerUtils where
import Control.DeepSeq
import Control.Monad.State
import Data.Data
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Word
import GHC.Generics
import Text.Read hiding (get)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Internal as B (w2c)
data OperationType
= Query
| Subscription
| Mutation
deriving (Show, Eq, Data, Read, Generic, Typeable, Enum)
instance NFData OperationType
data ExecutableDirectiveLocation
= QUERY
| MUTATION
| SUBSCRIPTION
| FIELD
| FRAGMENT_DEFINITION
| FRAGMENT_SPREAD
| INLINE_FRAGMENT
deriving (Show, Eq, Read, Data, Generic, Typeable, Enum)
instance NFData ExecutableDirectiveLocation
data TypeSystemDirectiveLocation
= SCHEMA
| SCALAR
| OBJECT
| FIELD_DEFINITION
| ARGUMENT_DEFINITION
| INTERFACE
| UNION
| ENUM
| ENUM_VALUE
| INPUT_OBJECT
| INPUT_FIELD_DEFINITION
deriving (Show, Eq, Read, Data, Generic, Typeable, Enum)
instance NFData TypeSystemDirectiveLocation
| Token unit for lexing the GraphQL specification
data Token
= TokenInt Int
| TokenFloat Double
| TokenName Text
| TokenString StringValue
| TokenReserved Text
| TokenPunctuator Char
| TokenMultiPunctuator Text
| TokenBool Bool
| TokenError Error
| TokenOperator OperationType
| TokenExecutableDirectiveLocation ExecutableDirectiveLocation
| TokenTypeSystemDirectiveLocation TypeSystemDirectiveLocation
| TokenNull
deriving (Show, Eq, Data, Read, Generic, Typeable)
data Error
= ConversionError Text Text
| LexerError Text
| NoMatch Text
| UntermBlockString
| UntermString
deriving (Show, Eq, Data, Read, Generic, Typeable)
instance NFData Error
data AlexInput = AlexInput
} deriving (Show, Eq)
data LexerState
= LexerState
{ matchedInput :: !AlexInput
, lexerMode :: !LexerMode
, stringBuffer :: !ByteString
} deriving (Show, Eq)
type Action = Int -> AlexInput -> State LexerState (Maybe Token)
data StringValue
= StringValue StringType T.Text
deriving (Show, Eq, Data, Read, Generic, Typeable)
instance NFData StringValue
token :: (ByteString -> Token) -> Action
token f inputLength _ = do
LexerState {..} <- get
pure . pure $ f (B.take inputLength (alexStr matchedInput))
token_ :: Token -> Action
token_ = token . const
data StringType
= SingleLine
| BlockString
deriving (Show, Eq, Data, Read, Generic, Typeable, NFData)
data LexerMode
= InNormal
| InBlockString
| InString
deriving (Show, Eq)
processEscapedCharacter :: Action
processEscapedCharacter = appendMode
processEscapedUnicode :: Action
processEscapedUnicode = appendMode
appendMode :: Action
appendMode = action
action :: Action
action len bs = do
s@LexerState {..} <- get
put s { stringBuffer = stringBuffer `B.append` B.take len (alexStr bs) }
pure Nothing
appendModeBlock :: Action
appendModeBlock = action
endMode :: Action
endMode _ _ = do
mode <- gets lexerMode
case mode of
InNormal -> pure Nothing
InBlockString -> apply BlockString
InString -> apply SingleLine
where
apply stringType = do
buf <- gets stringBuffer
modify $ \s -> s { lexerMode = InNormal, stringBuffer = mempty }
pure $ Just $ TokenString $ StringValue stringType (T.decodeUtf8 buf)
eofAction :: State LexerState [Token]
eofAction = do
mode <- gets lexerMode
pure $ case mode of
InBlockString -> [TokenError UntermBlockString]
InString -> [TokenError UntermString]
InNormal -> []
errorAction :: AlexInput -> State LexerState [Token]
errorAction AlexInput {..} =
pure [TokenError (NoMatch (T.decodeUtf8 alexStr))]
startBlockString :: Action
startBlockString _ _ =
Nothing <$ do
modify $ \s -> s { lexerMode = InBlockString }
startString :: Action
startString _ _ =
Nothing <$ do
modify $ \s -> s { lexerMode = InString }
alexInputPrevChar :: AlexInput -> Char
alexInputPrevChar = alexChar
alexGetByte :: AlexInput -> Maybe (Word8, AlexInput)
alexGetByte AlexInput {..} =
case B.uncons alexStr of
Nothing -> Nothing
Just (c, rest) ->
Just (c, AlexInput {
alexChar = B.w2c c,
alexStr = rest,
alexBytePos = alexBytePos+1
})
parseIntToken :: ByteString -> Token
parseIntToken s =
maybe (TokenError $ ConversionError "Not a valid int" (T.decodeUtf8 s)) TokenInt (readMaybe (T.unpack $ T.decodeUtf8 s))
parseFloatToken :: ByteString -> Token
parseFloatToken s =
maybe (TokenError $ ConversionError "Not a valid float" (T.decodeUtf8 s)) TokenFloat (readMaybe (B8.unpack s))
parseExecutableDirectiveLocationToken :: ByteString -> Token
parseExecutableDirectiveLocationToken s =
case readMaybe (T.unpack $ T.decodeUtf8 s) :: Maybe ExecutableDirectiveLocation of
Just r -> TokenExecutableDirectiveLocation r
Nothing -> TokenError (ConversionError "Invalid ExecutableDirectiveLocation" (T.decodeUtf8 s))
parseTypeSystemDirectiveLocationToken :: ByteString -> Token
parseTypeSystemDirectiveLocationToken s =
case readMaybe (T.unpack $ T.decodeUtf8 s) :: Maybe TypeSystemDirectiveLocation of
Just r -> TokenTypeSystemDirectiveLocation r
Nothing -> TokenError (ConversionError "Invalid TypeSystemDirectiveLocation" (T.decodeUtf8 s))
|
3a9ee605024a6305d00d1532a6af1eae6e6d44adcfb3a1da6d3d940cedc02c0d | igarnier/prbnmcn-dagger | resampling.ml | module type Particle = sig
type t
type field
val weight : t -> field
end
module type S = sig
type field
type particle
type 'a t := 'a Stateful_sampling_monad.t
val resampling_generic_iterative :
particle array -> (int -> field) -> int array
val resampling_generic : particle array -> (int -> field t) -> int array t
val resampling_generic_list :
(int -> field t) ->
(particle -> int -> 'a -> 'a) ->
particle list ->
'a ->
'a t
val stratified_resampling : target:int -> particle array -> int array t
val stratified_resampling_list :
target:int -> (particle -> int -> 'a -> 'a) -> particle list -> 'a -> 'a t
val systematic_resampling : target:int -> particle array -> int array t
val systematic_resampling_list :
target:int -> (particle -> int -> 'a -> 'a) -> particle list -> 'a -> 'a t
end
module Make
(F : Intf.Field)
(P : Particle with type field = F.t) (Sampler : sig
val uniform : F.t -> F.t Stateful_sampling_monad.t
end) =
struct
type field = F.t
type particle = P.t
type 'a t = 'a Stateful_sampling_monad.t
(* Both stratified and systematic resampling are implemented through the
same generic function. *)
(* The [f] function is supposed to return the next "noisy" quantile boundary. *)
let resampling_generic_iterative (dist : P.t array) f =
let particles = Array.length dist in
let replication_counts = Array.make particles 0 in
let cumulative = ref F.zero in
let particle_index = ref 0 in
let partition_index = ref 1 in
let last = ref (f !partition_index) in
while !particle_index < particles do
cumulative :=
F.add !cumulative (P.weight (Array.get dist !particle_index)) ;
while F.(!last < !cumulative) do
let c = replication_counts.(!particle_index) in
replication_counts.(!particle_index) <- c + 1 ;
last := f !partition_index ;
incr partition_index
done ;
incr particle_index
done ;
replication_counts
let resampling_generic_list (f : int -> F.t t) cons pop acc =
let open Stateful_sampling_monad.Infix in
let rec particle_loop particles partition_index cumulative last acc =
match particles with
| [] -> return acc
| particle :: rest ->
let w = P.weight particle in
if F.(w = zero) then
particle_loop rest partition_index cumulative last acc
else
let cumulative = F.add cumulative w in
counting_loop particle rest 0 partition_index cumulative last acc
and counting_loop particle rest replication_count partition_index cumulative
last acc =
if F.(last < cumulative) then
let replication_count = replication_count + 1 in
let* last = f partition_index in
let partition_index = partition_index + 1 in
counting_loop
particle
rest
replication_count
partition_index
cumulative
last
acc
else
particle_loop
rest
partition_index
cumulative
last
(cons particle replication_count acc)
in
let* last = f 1 in
particle_loop pop 1 F.zero last acc
let resampling_generic (dist : P.t array) (f : int -> F.t t) =
let open Stateful_sampling_monad.Infix in
let particles = Array.length dist in
let replication_counts = Array.make particles 0 in
let rec particle_loop particle_index partition_index cumulative last =
if particle_index < particles then
let cumulative =
F.add cumulative (P.weight (Array.get dist particle_index))
in
counting_loop particle_index partition_index cumulative last
else return replication_counts
and counting_loop particle_index partition_index cumulative last =
if F.(last < cumulative) then (
let c = replication_counts.(particle_index) in
replication_counts.(particle_index) <- c + 1 ;
let* last = f partition_index in
let partition_index = partition_index + 1 in
counting_loop particle_index partition_index cumulative last)
else
let particle_index = particle_index + 1 in
particle_loop particle_index partition_index cumulative last
in
let* last = f 1 in
particle_loop 0 1 F.zero last
let stratified_resampling ~target mu =
if target < 2 then invalid_arg "stratified_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = Array.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero mu in
let inv = F.div tot (F.of_int target) in
resampling_generic mu (fun i ->
let* rand = Sampler.uniform inv in
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
let systematic_resampling ~target mu =
if target < 2 then invalid_arg "systematic_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = Array.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero mu in
let inv = F.div tot (F.of_int target) in
let* rand = Sampler.uniform inv in
resampling_generic mu (fun i ->
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
let stratified_resampling_list ~target cons pop acc =
if target < 2 then invalid_arg "stratified_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = List.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero pop in
let inv = F.div tot (F.of_int target) in
resampling_generic_list
(fun i ->
let* rand = Sampler.uniform inv in
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
cons
pop
acc
let systematic_resampling_list ~target cons pop acc =
if target < 2 then invalid_arg "systematic_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = List.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero pop in
let inv = F.div tot (F.of_int target) in
let* rand = Sampler.uniform inv in
resampling_generic_list
(fun i ->
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
cons
pop
acc
end
[@@inline]
module Float_field : Intf.Field with type t = float = struct
type t = float
let add = ( +. )
let sub = ( -. )
let mul = ( *. )
let div = ( /. )
let zero = 0.0
let one = 1.0
let of_int = float_of_int
let ( = ) (x : float) (y : float) = x = y [@@inline]
let ( < ) (x : float) (y : float) = x < y [@@inline]
end
module Make_float (P : Particle with type field = float) =
Make (Float_field) (P)
(struct
let uniform x rng_state = RNG.float rng_state x
end)
| null | https://raw.githubusercontent.com/igarnier/prbnmcn-dagger/360e196be3e28cbcc67691a1fd68f1cd93743e35/src/resampling.ml | ocaml | Both stratified and systematic resampling are implemented through the
same generic function.
The [f] function is supposed to return the next "noisy" quantile boundary. | module type Particle = sig
type t
type field
val weight : t -> field
end
module type S = sig
type field
type particle
type 'a t := 'a Stateful_sampling_monad.t
val resampling_generic_iterative :
particle array -> (int -> field) -> int array
val resampling_generic : particle array -> (int -> field t) -> int array t
val resampling_generic_list :
(int -> field t) ->
(particle -> int -> 'a -> 'a) ->
particle list ->
'a ->
'a t
val stratified_resampling : target:int -> particle array -> int array t
val stratified_resampling_list :
target:int -> (particle -> int -> 'a -> 'a) -> particle list -> 'a -> 'a t
val systematic_resampling : target:int -> particle array -> int array t
val systematic_resampling_list :
target:int -> (particle -> int -> 'a -> 'a) -> particle list -> 'a -> 'a t
end
module Make
(F : Intf.Field)
(P : Particle with type field = F.t) (Sampler : sig
val uniform : F.t -> F.t Stateful_sampling_monad.t
end) =
struct
type field = F.t
type particle = P.t
type 'a t = 'a Stateful_sampling_monad.t
let resampling_generic_iterative (dist : P.t array) f =
let particles = Array.length dist in
let replication_counts = Array.make particles 0 in
let cumulative = ref F.zero in
let particle_index = ref 0 in
let partition_index = ref 1 in
let last = ref (f !partition_index) in
while !particle_index < particles do
cumulative :=
F.add !cumulative (P.weight (Array.get dist !particle_index)) ;
while F.(!last < !cumulative) do
let c = replication_counts.(!particle_index) in
replication_counts.(!particle_index) <- c + 1 ;
last := f !partition_index ;
incr partition_index
done ;
incr particle_index
done ;
replication_counts
let resampling_generic_list (f : int -> F.t t) cons pop acc =
let open Stateful_sampling_monad.Infix in
let rec particle_loop particles partition_index cumulative last acc =
match particles with
| [] -> return acc
| particle :: rest ->
let w = P.weight particle in
if F.(w = zero) then
particle_loop rest partition_index cumulative last acc
else
let cumulative = F.add cumulative w in
counting_loop particle rest 0 partition_index cumulative last acc
and counting_loop particle rest replication_count partition_index cumulative
last acc =
if F.(last < cumulative) then
let replication_count = replication_count + 1 in
let* last = f partition_index in
let partition_index = partition_index + 1 in
counting_loop
particle
rest
replication_count
partition_index
cumulative
last
acc
else
particle_loop
rest
partition_index
cumulative
last
(cons particle replication_count acc)
in
let* last = f 1 in
particle_loop pop 1 F.zero last acc
let resampling_generic (dist : P.t array) (f : int -> F.t t) =
let open Stateful_sampling_monad.Infix in
let particles = Array.length dist in
let replication_counts = Array.make particles 0 in
let rec particle_loop particle_index partition_index cumulative last =
if particle_index < particles then
let cumulative =
F.add cumulative (P.weight (Array.get dist particle_index))
in
counting_loop particle_index partition_index cumulative last
else return replication_counts
and counting_loop particle_index partition_index cumulative last =
if F.(last < cumulative) then (
let c = replication_counts.(particle_index) in
replication_counts.(particle_index) <- c + 1 ;
let* last = f partition_index in
let partition_index = partition_index + 1 in
counting_loop particle_index partition_index cumulative last)
else
let particle_index = particle_index + 1 in
particle_loop particle_index partition_index cumulative last
in
let* last = f 1 in
particle_loop 0 1 F.zero last
let stratified_resampling ~target mu =
if target < 2 then invalid_arg "stratified_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = Array.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero mu in
let inv = F.div tot (F.of_int target) in
resampling_generic mu (fun i ->
let* rand = Sampler.uniform inv in
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
let systematic_resampling ~target mu =
if target < 2 then invalid_arg "systematic_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = Array.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero mu in
let inv = F.div tot (F.of_int target) in
let* rand = Sampler.uniform inv in
resampling_generic mu (fun i ->
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
let stratified_resampling_list ~target cons pop acc =
if target < 2 then invalid_arg "stratified_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = List.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero pop in
let inv = F.div tot (F.of_int target) in
resampling_generic_list
(fun i ->
let* rand = Sampler.uniform inv in
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
cons
pop
acc
let systematic_resampling_list ~target cons pop acc =
if target < 2 then invalid_arg "systematic_resampling" ;
let open Stateful_sampling_monad.Infix in
let tot = List.fold_left (fun acc p -> F.add (P.weight p) acc) F.zero pop in
let inv = F.div tot (F.of_int target) in
let* rand = Sampler.uniform inv in
resampling_generic_list
(fun i ->
return (F.add F.(div (mul tot (of_int i)) (of_int target)) rand))
cons
pop
acc
end
[@@inline]
module Float_field : Intf.Field with type t = float = struct
type t = float
let add = ( +. )
let sub = ( -. )
let mul = ( *. )
let div = ( /. )
let zero = 0.0
let one = 1.0
let of_int = float_of_int
let ( = ) (x : float) (y : float) = x = y [@@inline]
let ( < ) (x : float) (y : float) = x < y [@@inline]
end
module Make_float (P : Particle with type field = float) =
Make (Float_field) (P)
(struct
let uniform x rng_state = RNG.float rng_state x
end)
|
ecc9f002d92e00bc04ca6d134be3e8be54c8793c657724a42e3dcff3bf42ea10 | GumTreeDiff/cgum | osetb.ml | open Ocollection
open Oset
let empty = Setb.empty
class ['a] osetb xs =
object(o)
inherit ['a] oset
val data = xs (* Setb.empty *)
method tosetb = data
if put [ ] then no segfault , if [ 11 ] then
method toset = Obj.magic data
method empty = {< data = Setb.empty >}
method add e = {< data = Setb.add e data >}
method iter f = Setb.iter f data
method view =
if Setb.is_empty data
then Empty
else let el = Setb.choose data in Cons (el, o#del el)
method del e = {< data = Setb.remove e data >}
method mem e = Setb.mem e data
method null = Setb.is_empty data
method tolist = Setb.elements data
method length = Setb.cardinal data
method union s = {< data = Setb.union data s#tosetb >}
method inter s = {< data = Setb.inter data s#tosetb >}
method minus s = {< data = Setb.diff data s#tosetb >}
(* todo: include, ... *)
end
| null | https://raw.githubusercontent.com/GumTreeDiff/cgum/8521aa80fcf4873a19e60ce8c846c886aaefb41b/commons/ocollection/osetb.ml | ocaml | Setb.empty
todo: include, ... | open Ocollection
open Oset
let empty = Setb.empty
class ['a] osetb xs =
object(o)
inherit ['a] oset
method tosetb = data
if put [ ] then no segfault , if [ 11 ] then
method toset = Obj.magic data
method empty = {< data = Setb.empty >}
method add e = {< data = Setb.add e data >}
method iter f = Setb.iter f data
method view =
if Setb.is_empty data
then Empty
else let el = Setb.choose data in Cons (el, o#del el)
method del e = {< data = Setb.remove e data >}
method mem e = Setb.mem e data
method null = Setb.is_empty data
method tolist = Setb.elements data
method length = Setb.cardinal data
method union s = {< data = Setb.union data s#tosetb >}
method inter s = {< data = Setb.inter data s#tosetb >}
method minus s = {< data = Setb.diff data s#tosetb >}
end
|
6ba7a1038f12815a4ce00831e107436ecef0851e45d7057f11f04863ae3c9409 | ultralisp/ultralisp | changelog.lisp | (defpackage #:ultralisp/widgets/changelog
(:use #:cl)
(:import-from #:str)
(:import-from #:reblocks/html
#:with-html)
(:import-from #:ultralisp/models/action
#:get-params
#:project-updated
#:project-removed
#:get-project
#:project-added)
(:import-from #:ultralisp/models/project
#:get-url
#:get-name)
(:import-from #:ultralisp/utils
#:format-timestamp)
(:import-from #:mito
#:object-updated-at
#:object-created-at)
(:import-from #:ultralisp/models/version
#:get-built-at
#:get-number
#:version)
(:import-from #:ultralisp/models/check
#:get-processed-at
#:any-check)
(:export
#:render
#:get-key-name
#:render-action
#:render-object))
(in-package #:ultralisp/widgets/changelog)
(defgeneric get-key-name (key)
(:method ((key (eql :last-seen-commit)))
"commit"))
(defgeneric prepare-value (key value)
(:method ((key (eql :last-seen-commit)) value)
(when value
(str:shorten 8 value :ellipsis "…"))))
;; TODO: remove this code after refactoring
(defgeneric render-object (action &key timestamp)
(:method ((obj t) &key timestamp)
(with-html
(:li ("~@[~A - ~]Unknown type of object ~A"
(when timestamp
(format-timestamp (object-updated-at obj)))
(type-of obj)))))
(:method ((version version) &key timestamp)
(let* ((number (get-number version))
(updated-at (object-updated-at version))
;; TODO: create a generic get-uri and define it for a version class
(url (format nil "/versions/~A" number))
(version-type (ultralisp/models/version:get-type version)))
(with-html
(if (eql version-type :ready)
(:li ("~@[~A - ~]Version [~A](~A)"
(when timestamp
(format-timestamp updated-at))
url number))
(:li ("~@[~A - ~]Pending version"
(when timestamp
(format-timestamp updated-at))))))))
(:method ((action project-added) &key timestamp)
(let* ((project (get-project action))
(name (get-name project))
(url (get-url project)))
(with-html
(:li ("~@[~A - ~]Project [~A](~A) was added"
(when timestamp
(format-timestamp (object-updated-at action)))
url name)))))
(:method ((action project-removed) &key timestamp)
(let* ((project (get-project action))
(name (get-name project))
(url (get-url project))
(params (get-params action))
(reason (getf params :reason))
(traceback (getf params :traceback)))
(with-html
(:li ("~@[~A - ~]Project [~A](~A) was removed."
(when timestamp
(format-timestamp (object-updated-at action)))
url name
reason)
(when reason
(:span "Reason is: ")
(if traceback
(:a :title traceback reason)
(:span reason)))))))
(:method ((action project-updated) &key timestamp)
(let* ((project (get-project action))
(name (get-name project))
(url (get-url project))
(params (get-params action))
(diff (getf params :diff)))
(with-html
(:li (:p ("~@[~A - ~]Project [~A](~A) was updated"
(when timestamp
(format-timestamp (object-updated-at action)))
url name))
(:dl :class "diff"
(loop for (key (before after)) on diff by #'cddr
do (:dt (get-key-name key))
when before
do (:dd ("~A -> ~A" (prepare-value key before)
(prepare-value key after)))
else
do (:dd ("set to ~A" (prepare-value key after)))))))))
(:method ((check any-check) &key timestamp)
(with-html
(:li (:p ("~@[~A - ~]~A"
(when timestamp
(format-timestamp (object-updated-at check)))
(if (get-processed-at check)
"Finished check"
"Pending check")))))))
(defun render (objects &key timestamps limit)
(check-type objects (or list null))
(with-html
(cond (objects
(:ul :class "changelog"
(loop with objects = (if limit
(subseq objects
0
(min limit
(length objects)))
objects)
for object in objects
do (render-object object
:timestamp timestamps)))
(when (and limit
(> (length objects)
limit))
(:p :class "and-more"
(format nil "And ~A more..."
(- (length objects)
limit)))))
(t
(:ul :class "changelog"
(:li "No changes"))))))
| null | https://raw.githubusercontent.com/ultralisp/ultralisp/37bd5d92b2cf751cd03ced69bac785bf4bcb6c15/src/widgets/changelog.lisp | lisp | TODO: remove this code after refactoring
TODO: create a generic get-uri and define it for a version class | (defpackage #:ultralisp/widgets/changelog
(:use #:cl)
(:import-from #:str)
(:import-from #:reblocks/html
#:with-html)
(:import-from #:ultralisp/models/action
#:get-params
#:project-updated
#:project-removed
#:get-project
#:project-added)
(:import-from #:ultralisp/models/project
#:get-url
#:get-name)
(:import-from #:ultralisp/utils
#:format-timestamp)
(:import-from #:mito
#:object-updated-at
#:object-created-at)
(:import-from #:ultralisp/models/version
#:get-built-at
#:get-number
#:version)
(:import-from #:ultralisp/models/check
#:get-processed-at
#:any-check)
(:export
#:render
#:get-key-name
#:render-action
#:render-object))
(in-package #:ultralisp/widgets/changelog)
(defgeneric get-key-name (key)
(:method ((key (eql :last-seen-commit)))
"commit"))
(defgeneric prepare-value (key value)
(:method ((key (eql :last-seen-commit)) value)
(when value
(str:shorten 8 value :ellipsis "…"))))
(defgeneric render-object (action &key timestamp)
(:method ((obj t) &key timestamp)
(with-html
(:li ("~@[~A - ~]Unknown type of object ~A"
(when timestamp
(format-timestamp (object-updated-at obj)))
(type-of obj)))))
(:method ((version version) &key timestamp)
(let* ((number (get-number version))
(updated-at (object-updated-at version))
(url (format nil "/versions/~A" number))
(version-type (ultralisp/models/version:get-type version)))
(with-html
(if (eql version-type :ready)
(:li ("~@[~A - ~]Version [~A](~A)"
(when timestamp
(format-timestamp updated-at))
url number))
(:li ("~@[~A - ~]Pending version"
(when timestamp
(format-timestamp updated-at))))))))
(:method ((action project-added) &key timestamp)
(let* ((project (get-project action))
(name (get-name project))
(url (get-url project)))
(with-html
(:li ("~@[~A - ~]Project [~A](~A) was added"
(when timestamp
(format-timestamp (object-updated-at action)))
url name)))))
(:method ((action project-removed) &key timestamp)
(let* ((project (get-project action))
(name (get-name project))
(url (get-url project))
(params (get-params action))
(reason (getf params :reason))
(traceback (getf params :traceback)))
(with-html
(:li ("~@[~A - ~]Project [~A](~A) was removed."
(when timestamp
(format-timestamp (object-updated-at action)))
url name
reason)
(when reason
(:span "Reason is: ")
(if traceback
(:a :title traceback reason)
(:span reason)))))))
(:method ((action project-updated) &key timestamp)
(let* ((project (get-project action))
(name (get-name project))
(url (get-url project))
(params (get-params action))
(diff (getf params :diff)))
(with-html
(:li (:p ("~@[~A - ~]Project [~A](~A) was updated"
(when timestamp
(format-timestamp (object-updated-at action)))
url name))
(:dl :class "diff"
(loop for (key (before after)) on diff by #'cddr
do (:dt (get-key-name key))
when before
do (:dd ("~A -> ~A" (prepare-value key before)
(prepare-value key after)))
else
do (:dd ("set to ~A" (prepare-value key after)))))))))
(:method ((check any-check) &key timestamp)
(with-html
(:li (:p ("~@[~A - ~]~A"
(when timestamp
(format-timestamp (object-updated-at check)))
(if (get-processed-at check)
"Finished check"
"Pending check")))))))
(defun render (objects &key timestamps limit)
(check-type objects (or list null))
(with-html
(cond (objects
(:ul :class "changelog"
(loop with objects = (if limit
(subseq objects
0
(min limit
(length objects)))
objects)
for object in objects
do (render-object object
:timestamp timestamps)))
(when (and limit
(> (length objects)
limit))
(:p :class "and-more"
(format nil "And ~A more..."
(- (length objects)
limit)))))
(t
(:ul :class "changelog"
(:li "No changes"))))))
|
b82250f7c7a77e013bb705e4c51f92556f92ce9b9c23c7917be93925d4fe1f56 | ont-app/rdf | core.cljc | (ns ont-app.rdf.core
{:doc "This is a backstop for shared logic between various RDF-based
implementations of IGraph.
It includes:
- support for LangStr using the #voc/lstr custom reader
- support for ^^transit:json datatype tags
- templating utilities for the standard IGraph member access methods.
- i/o methods `load-rdf` `read-rdf` and `write-rdf`.
"
:author "Eric D. Scott"
;; These errors were found to be spurious, related to cljs ...
:clj-kondo/config '{:linters {:unresolved-symbol {:level :off}
}}
} ;; meta
(:require
[clojure.string :as s]
[clojure.spec.alpha :as spec]
3rd party
[cljstache.core :as stache]
;; ont-app
[ont-app.igraph.core :as igraph :refer [unique]]
[ont-app.igraph.graph :as native-normal]
[ont-app.vocabulary.core :as voc]
[ont-app.rdf.ont :as ont]
;; reader conditionals
#?(:clj [clj-http.client :as http]) ;; todo add cljs-http.client?
#?(:clj [clojure.java.io :as io])
todo remove conditional after issue 4
#?(:clj [ont-app.graph-log.levels :as levels
:refer [warn debug trace value-trace value-debug]]
:cljs [ont-app.graph-log.levels :as levels
:refer-macros [warn debug value-trace value-debug]])
todo remove conditional after issue 4
) ;; require
#?(:clj
(:import
[java.io ByteArrayInputStream ByteArrayOutputStream]
[java.io File]
[ont_app.vocabulary.lstr LangStr]
)))
(voc/put-ns-meta!
'ont-app.rdf.core
{
:voc/mapsTo 'ont-app.rdf.ont
}
)
;; aliases
(def prefixed
"Returns `query`, with prefix declarations prepended
Where
- `query` is presumed to be a SPARQL query"
voc/prepend-prefix-declarations)
(def ontology
"The supporting vocabulary for the RDF module"
@ont/ontology-atom)
;; FUN WITH READER MACROS
#?(:cljs
(enable-console-print!)
)
#?(:cljs
(defn on-js-reload [] )
)
;; standard clojure containers are declared by default as descendents of
: rdf - app / TransitData , which keys to the render - literal method for rendering
;; transit data. renders as transit by default.
;; Note that you can undo this with 'underive', in which case
;; it will probably be rendered as a string, unless you want
;; to write your own method...
(derive #?(:clj clojure.lang.PersistentVector
:cljs cljs.core.PersistentVector)
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentHashSet
:cljs cljs.core.PersistentHashSet )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentArrayMap
:cljs cljs.core.PersistentArrayMap )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentList
:cljs cljs.core.PersistentList )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.Cons
:cljs cljs.core.Cons )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.LazySeq
:cljs cljs.core.LazySeq )
:rdf-app/TransitData)
#?(:clj (derive java.lang.Long ::number)
:cljs (derive cljs.core.Long ::number)
)
#?(:clj (derive java.lang.Double ::number)
:cljs (derive cljs.core..Double ::number)
)
(declare transit-read-handlers)
(defn read-transit-json
"Returns a value parsed from transit string `s`
Where
- `s` is a "-escaped string encoded as transit
Note: custom datatypes will be informed by @transit-read-handlers
"
[^String s]
#?(:clj
(transit/read
(transit/reader
(ByteArrayInputStream. (.getBytes (clojure.string/replace
s
""" "\"")
"UTF-8"))
:json
{:handlers @transit-read-handlers}))
:cljs
(throw (ex-info "read-transit-json not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'read-transit-json
::args [s]
}))
#_(transit/read
(transit/reader
:json
{:handlers @transit-read-handlers})
(clojure.string/replace
s
""" "\""))))
(declare transit-write-handlers)
(defn render-transit-json
"Returns a string of transit for `value`
Where
- `value` is any value that be handled by cognitict/transit
- Note: custom datatypes will be informed by @transit-write-handlers
"
[value]
#?(:clj
(let [output-stream (ByteArrayOutputStream.)
]
(transit/write
(transit/writer output-stream :json {:handlers @transit-write-handlers})
value)
(String. (.toByteArray output-stream)))
:cljs
(throw (ex-info "render-transit-json not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'render-transit-json
::args [value]
}))
#_(transit/write
(transit/writer :json {:handlers @transit-write-handlers})
value)))
(defn cljc-file-exists?
"True when `path` exists in the local file system"
[path]
#?(:clj
(.exists (io/file path))
:cljs
(let []
(warn ::FileExistsCheckInCljs
:glog/message "Checking for existence of local file {{path}} in clojurescript (returning false)"
::path path)
false
)))
(defn cljc-is-local-file?
"True when `f` is a file in the local file system"
[f]
#?(:clj
(instance? java.io.File f)
:cljs
(let []
(warn ::IsLocalFileCheckInCljs
:glog/message "Checking whether {{f}} is local file in clojurescript (returning false)"
::f f)
false)))
(defn cljc-make-file
"Returns new file object for `path`. Not supported under cljs."
[path]
#?(:clj
(io/file path)
:cljs
(throw (ex-info "Make-file not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-make-file
::args [path]
}))))
(defn cljc-file-length
"Returns length of file `f`. Not supported under cljs."
[f]
#?(:clj
(.length f)
:cljs
(throw (ex-info "File-length not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-file-length
::args [f]
}))))
(defn cljc-make-parents
"Ensures directory path for file `f`. Not supported under cljs."
[f]
#?(:clj
(io/make-parents f)
:cljs
(throw (ex-info "Make-parents not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-make-parents
::args [f]
}))))
(defn cljc-resource
"Returns the resource named by `r`. Not supported under cljs."
[r]
#?(:clj
(io/resource r)
:cljs
(throw (ex-info "Resource not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-resource
::args [r]
}))))
(defn cljc-create-temp-file
"Returns a temporary file named per `stem` and `ext`. Not supported under cljs.
- where
- `stem` is a general name for the file
- `ext` is a file extension typically starting with '.'
"
[stem ext]
#?(:clj
(File/createTempFile stem ext)
:cljs
(throw (ex-info "Create-temp-file not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-create-temp-file
::args [stem ext]
}))))
(defn cljc-http-get
"Makes a GET call to `url` with `req`. Not yet supported in cljs.
- Where
- `url` is a URL or a URL string
- `req` is an http request map
"
[url req]
#?(:clj
(http/get (str url) req)
:cljs
TODO : probably need to import cljs - http . Pending issue 4
(throw (ex-info "Http-get not yet supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-http-get
::args [url req]
}))))
;; NO READER MACROS BELOW THIS POINT
;; except in try/catch clauses
;; SPECS
(def transit-re
"Matches data tagged as transit:json"
(re-pattern (str "^\"" ;; start with quote
anything ( group 1 )
"\"" ;; terminal quote
"\\^\\^" ;; ^^
"transit:json$" ;; end with type tag
)))
(spec/def ::transit-tag (spec/and string? (fn [s] (re-matches transit-re s))))
(defn bnode-kwi?
"True when `kwi` matches the canonical bnode representation."
[kwi]
(and (keyword? kwi)
(some->> (namespace kwi)
(str)
(re-matches #"^_.*"))))
(spec/def ::bnode-kwi bnode-kwi?)
(spec/def ::file-resource (fn [url] (and (instance? java.net.URL url)
(-> (.getProtocol url)
#{"file" "jar"}))))
(spec/def ::web-resource (fn [url] (and (instance? java.net.URL url)
(-> (.getProtocol url)
#{"http" "https"}))))
;;;;;;;;;;;;;;;;;;
;; INPUT/OUTPUT
;;;;;;;;;;;;;;;;;;
;; KWI/URI conversion for catalog contents
(defn coerce-graph-element
"Returns `x`, possibly coerced to either a kwi or a java.net.URI per `policy`
- where
- `policy` := m s.t. (keys m) :- #{::kwi-if ::uri-if}
- `x` is any candidate as an element in an IGraph
- `kwi-if` := fn [x] -> truthy if `x` should be translated to a keyword id
- `uri-if` := fn [x] -> truthy if `x` should be translated to a java.net.URI
- NOTE: Some implementations of IGraph may be a lot more tolarant of datatypes
in s/p/o position than the URI/URI/URI-or-literal that RDF expects.
"
([x]
(coerce-graph-element {::kwi-if (fn [x] (re-matches (voc/namespace-re) (str x)))
::uri-if (fn [x] (or
(re-matches voc/ordinary-iri-str-re (str x))
(re-matches voc/exceptional-iri-str-re (str x))))
}
x))
([policy x]
(cond
((::kwi-if policy) x)
(if (keyword? x)
x
(voc/keyword-for (str x)))
((::uri-if policy) x)
(if (instance? java.net.URI x)
x
(java.net.URI. (str x)))
:else x
)))
(defn collect-ns-catalog-metadata
"Reducing function outputs `gacc'` given voc metadata assigned to namespace
- NOTE: typically used to initialize the resource catalog.
"
[gacc _prefix ns]
(let [m (voc/get-ns-meta ns)
uri (:vann/preferredNamespaceUri m)
prefix (:vann/preferredNamespacePrefix m)
download-url (:dcat/downloadURL m)
appendix (:voc/appendix m)
]
(if (and download-url appendix)
appendix is one or more triples expressed as vectors
(-> gacc
(igraph/add [(coerce-graph-element uri)
:dcat/downloadURL (coerce-graph-element download-url)
:vann/preferredNamespacePrefix prefix
])
(igraph/add (mapv (fn [v] (mapv coerce-graph-element v))
appendix)))
gacc)))
(def resource-catalog
"A native normal graph using this vocabulary:
- [`namespace-uri` :dcat/downloadURL `download-url`]
- [`namespace-uri` :vann/preferredNamespacePrefix `prefix`]
- [`download-url` :dcat/mediaType `media-type`]
- where
- `download-url` is a URL string
- `media-type` := :rdf/type :dct/MediaTypeOrExtent
"
(atom (->> (voc/prefix-to-ns)
(reduce-kv collect-ns-catalog-metadata
(native-normal/make-graph)))))
(defn add-catalog-entry!
"Adds an entry in @resource-catalog for `download-url` `namespace-uri` `prefix` `media-type`
- Where
- `download-url` is a URL (or string) naming a place on the web containing an RDF file
- `namespace-uri` is the primary URI, associated with `prefix`
- `prefix` is the preferred prefix for `namespace-uri`
- `media-type` is the MIME type, of `download-url` eg 'text/turtle'
"
[download-url namespace-uri prefix media-type]
(swap! resource-catalog
igraph/add
[[(coerce-graph-element namespace-uri)
:vann/preferredNamespacePrefix prefix
:dcat/downloadURL (coerce-graph-element download-url)]
[(coerce-graph-element download-url)
:dcat/mediaType media-type
]]))
(def default-context
"An atom containing a native-normal graph with default i/o context configurations.
- NOTE: This would typically be the starting point for the i/o context of individual
implementations.
- VOCABULARY
- [:rdf-app/UrlCache :rdf-app/directory `URL cache directory`]
"
(atom (-> (native-normal/make-graph)
(igraph/add [[:rdf-app/UrlCache
:rdf-app/directory "/tmp/rdf-app/UrlCache"]
]))))
(defn standard-data-transfer-dispatch
"Returns a standard `dispatch-key` for `to-transfer`, defaulting to (type to-transfer)
- Where
- `to-transfer` is typically an argument to the `load-rdf`, `read-rdf` or `write-rdf` methods.
- `dispatch-key` :~ #{:rdf-app/LocalFile, :rdf-app/FileResource :rdf/WebResource}
or the type of `to-transfer`.
- :rdf-app/LocalFile indicates that `to-transfer` is a local path string
- :rdf-app/FileResource indicates that `to-transfer` is a file resource (maybe from a jar)
- :rdf-app/WebResource indicates something accessible through a curl call.
"
[to-transfer]
(cond
(and (string? to-transfer)
(cljc-file-exists? to-transfer))
:rdf-app/LocalFile
(cljc-is-local-file? to-transfer)
:rdf-app/LocalFile
(spec/valid? ::file-resource to-transfer)
:rdf-app/FileResource
(spec/valid? ::web-resource to-transfer)
:rdf-app/WebResource
:else (type to-transfer))
)
(declare load-rdf-dispatch)
(defmulti load-rdf
"Returns a new IGraph with contents for `to-load`,
- args: [`context` `to-load`]
- dispatched on: [`graph-dispatch` `to-load-rdf-dispatch`]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-load` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`. We may need to derive `file-extension`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-load-rdf-dispatch` is the dispatch value derived for `to-load-rdf`
- `file-extension` may be implicit from a file name or derived per vocabulary below
It may be necesary to inform your RDF store about the expected format.
- VOCABULARY (in `context`)
- [`#'load-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'load-rdf` :rdf-app/toImportDispatchFn (fn [to-load] -> to-load-dispatch)]
... optional. Defaults to output of `standard-data-transfer-dispatch`
- [`#'load-rdf` :rdf-app/extensionFn (fn [to-load] -> file-extension)]
... optional. By default it parses the presumed path name described by `to-load`
- [rdf-app/UrlCache rdf-app/directory `cache-directory`]
- [rdf-app/UrlCache rdf-app/cacheMaintenance :rdf-app/DeleteOnRead]
... optional. specifies that a cached file should be deleted after a read.
- by default it will not be deleted.
"
;; There's a tricky circular dependency here in reference to #'load-rdf....
(fn [context to-load] (load-rdf-dispatch context to-load)))
(defn load-rdf-dispatch
"Returns [graph-dispatch to-load-dispatch]. See docstring for `rdf/load-rdf`"
[context to-load]
{:pre [(fn [context _] (context #'load-rdf :rdf-app/hasGraphDispatch))
]
}
(value-trace
::load-rdf-dispatch
[::context context
::to-load to-load
]
;; return [graph-dispatch, to-load-dispatch] ...
[(unique (context #'load-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-load-dispatch (unique (context #'load-rdf :rdf-app/toImportDispatchFn))]
(to-load-dispatch to-load)
;; else no despatch function was provided
(standard-data-transfer-dispatch to-load))
]))
;; URL caching
(defn cached-file-path
"Returns a canonical path for cached contents read from a URL."
[& {:keys [dir url stem ext]}]
(assert dir)
(str dir "/" stem "_hash=" (hash url) "." ext))
(defn catalog-lookup
"Returns `catalog-entry` for `url`
- Where
- `catalog-entry` := m s.t. (keys m) :~ #{?media-type :?prefix :?suffix :?media-url}
- `url` is a URL that may be in the resource catalog
- `:?prefix` is the preferred prefix associated with `url` (which informs the stem)
- `:?suffix` is the suffix associated with the `:?media-url` (informs the extension)
"
[url]
(let [g (igraph/union @resource-catalog
ontology)
url (coerce-graph-element url)
]
(-> (igraph/query g
[[url :dcat/mediaType :?media-type]
[:?media-url :formats/media_type :?media-type]
[:?media-url :formats/preferred_suffix :?suffix]
[:?namespace-uri :dcat/downloadURL url]
[:?namespace-uri :vann/preferredNamespacePrefix :?prefix]
])
(unique))))
(defn lookup-file-specs-in-catalog
"Returns `file-specs` for `url`
- Where
- `file-specs` := m s.t. (keys m) :~ #{:url :path :stem :ext}
- `url` (as arg) is a URL we may want to get from an http call
- `url` (as key) is the string version of `url`
- `path` is the file path of `url`
- `stem` is the preferred prefix for `url` in the catalog
- `ext` is the file suffix associated with the media type of `url` in the catalog
"
[url]
(when-let [lookup (catalog-lookup url)
]
{:url (str url)
:path (.getPath url)
:stem (:?prefix lookup)
:ext (clojure.string/replace (:?suffix lookup) #"\." "")
}))
(defn http-get-from-catalog
"returns an http response to a GET request for `url`
- Where
- `url` is a URL with an entry in the @`resource-catalog`
"
[url]
(let [lookup (catalog-lookup url)
]
(when lookup
(cljc-http-get (str url)
{:accept (:?media-type lookup)})
)))
(def parse-url-re
"A regex to parse a file URL string with a file name and an extension."
(re-pattern
(str "^.*/" ;; start with anything ending in slash
at least one non - slash ( group 1 )
"\\." ;; dot
any ending , ( group 2 )
)))
(defn parse-url
"Returns a file specification parsed directly from a URL (not in the catalog), or nil
- where
- `url` is a URL, probably a file resource"
[url]
(let [path (.getPath url)
matches (re-matches parse-url-re path)
]
(when-let [[_ stem ext] matches]
{:url (str url)
:path path
:stem stem
:ext ext
})))
(defn get-cached-file-path-spec
"Returns `m` s.t (keys m) :~ #{:url :path :stem :ext} for `url` informed by `context`
- Where
- `url` (as arg) is x s.t. (str x) -> a URL string
- `context` is an native-normal graph describing the I/O context
- `url` (as key) is a URL string
- `path` is the path component of `url`
- `stem` is the 'stem portion of /path/to/<stem>.<ext>
- `ext` is the 'ext' portion of /path/to/<stem>.<ext>
- `dir` is the directory containing cache files
- NOTE: this should be sufficient to create a unique temp file path for caching
contents of `url`.
- VOCABULARY
- [:rdf-app/UrlCache :rdf-app/pathFn `cached-file-path-fn`]
- optional. Default will try to infer `m` from `url` automatically
Either through `lookup-file-specs-in-catalog` or by parsing `url` itself.
- [:rdf-app/UrlCache :rdf-app/directory `dir`]
- `cached-file-path-fn` := fn (uri) -> `m`
"
[context url]
(value-trace
::get-cached-file-spec
[::context context
::url url
]
(if-let [cached-file-path-fn (unique (context :rdf-app/UrlCache :rdf-app/pathFn))
]
(cached-file-path-fn url)
;; else there is no pathFn, try to parse the URL...
(let [dir (unique (context :rdf-app/UrlCache :rdf-app/directory))
]
(assoc (or (lookup-file-specs-in-catalog url)
(parse-url url))
:dir dir)))))
(defn cache-url-as-local-file
"RETURNS `cached-file`, with contents of `url` loaded
SIDE-EFFECT: creates file named `cached-file` if it does not already exist.
- Where
- `context` is a native-normal graph informed by vocabulary below.
- `url` := a URL or string naming URL
- `cached-file-path` names a local file to contain contents from `url`
- VOCABULARY (for `context`)
- [:rdf-app/UrlCache :rdf-app/pathFn `cached-file-path-fn`]
- optional. Default will try to derive `parse-map` from `url` first by looking
it up in the @`resource-catalog` and then by parsing the `url` itself
- [:rdf-app/UrlCache :rdf-app/directory `cache-directory`]
- `cached-file-path-fn` := fn (uri) -> `parse-map`
- `parse-map` := m s.t (keys m) :~ #{:url :path :stem :ext} for `url` informed by `context`
"
[context url]
(value-trace
::cache-url-as-local-file
[::context context
::url url
]
(if-let [temp-file-path (some-> (get-cached-file-path-spec context url)
(cached-file-path))
]
(let [cached-file (cljc-make-file temp-file-path)
]
(when (not (and (cljc-file-exists? cached-file)
(> (cljc-file-length cached-file) 0)))
(cljc-make-parents cached-file)
(spit cached-file
(cond
(context url :rdf/type :rdf-app/FileResource)
(slurp url)
(context url :rdf/type :rdf-app/WebResource)
(-> (http-get-from-catalog url)
:body)
:else
(throw (ex-info "Resource type not sufficiently specified in context"
{:type ::ResourceNotSufficientlySpecifiedInContext
::context context
::url url
})))))
cached-file)
;; else no cached-file-path
(throw (ex-info (str "No caching path could be inferred for %s" url)
{:type ::NOCachingPathCouldBeInferredForURL
::context context
::url url
})))))
(defmethod load-rdf [:rdf-app/IGraph :rdf-app/FileResource]
;; default behavior to load URLs.
;; to enable (derive <my-Igraph> :rdf-app/IGraph)
[context url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/FileResource])
url)
(load-rdf context)))
(defmethod load-rdf [:rdf-app/IGraph :rdf-app/WebResource]
;; default behavior to load URLs.
;; to enable (derive <my-Igraph> :rdf-app/IGraph)
[context url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/WebResource])
url)
(load-rdf context)))
(defmethod load-rdf :default
[context file-id]
(throw (ex-info "No method for rdf/load-rdf"
{:type ::NoMethodForLoadRdf
::context context
::file file-id
::dispatch (load-rdf-dispatch context file-id)
})))
(declare read-rdf-dispatch)
(defmulti read-rdf
"Side-effect: updates `g` with added contents from `to-read`,
Returns: modified `g`
- args: [context g to-read]
- dispatched on: [graph-dispatch to-read-dispatch]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-read` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`. We may need to derive `file-extension`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-read-dispatch` is the dispatch value derived for `to-read`
- `file-extension` may be implicit from a file name or derived per vocabulary below
It may be necesary to inform your RDF store about the expected format.
- VOCABULARY (in `context`)
- [`#'read-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'read-rdf` :rdf-app/toImportDispatchFn (fn [to-read] -> `to-read-dispatch`)]
... optional. Defaults to output of `standard-data-transfer-dispatch`
- [`#'read-rdf` :rdf-app/extensionFn (fn [to-read] -> file-extension)]
... optional. By default it parses the presumed path name described by `to-read`
"
;; There's a tricky circular dependency here in reference to #'read-rdf....
(fn [context g to-read] (read-rdf-dispatch context g to-read)))
(defn read-rdf-dispatch
"Returns [graph-dispatch to-read-dispatch]. See docstring for `rdf/read-rdf`"
[context g to-read]
{:pre [(instance? ont_app.igraph.graph.Graph context)
(context #'read-rdf :rdf-app/hasGraphDispatch)
]
}
(trace
::starting-read-rdf-dispatch
::context context
::g g
::to-read to-read
)
(value-trace
::value-of-read-rdf-dispatch
[::context context
::g g
::to-read to-read
]
;; return vector...
[(unique (context #'read-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-read-dispatch (unique (context #'read-rdf :rdf-app/toImportDispatchFn))]
(to-read-dispatch to-read)
;; else no despatch function was provided
(standard-data-transfer-dispatch to-read))
]))
(defmethod read-rdf [:rdf-app/IGraph :rdf-app/FileResource]
[context g url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/FileResource])
url)
(read-rdf context g)))
(defmethod read-rdf [:rdf-app/IGraph :rdf-app/WebResource]
[context g url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/WebResource])
url)
(read-rdf context g)))
(defmethod read-rdf :default
[context g file-id]
(throw (ex-info "No method for rdf/read-rdf"
{:type ::NoMethodForReadRdf
::context context
::g g
::file file-id
::dispatch (read-rdf-dispatch context g file-id)
})))
;; write-rdf
(declare write-rdf-dispatch)
(defmulti write-rdf
"Side-effect: writes contents of `g` to `to-write` in `fmt`,
Returns: modified `g`
- args: [context g to-write fmt]
- dispatched on: [graph-dispatch to-write-dispatch fmt]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-write` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-write-dispatch` is the dispatch value derived for `to-write`
- `fmt` is typically a KWI derived from `:dct/MediaTypeOrExtent`
- VOCABULARY (in `context`)
- [`#'write-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'write-rdf` :rdf-app/toExportDispatchFn (fn [to-write] -> `to-write-dispatch`)]
... optional. Defaults to (type to-write)
"
;; There's a tricky circular dependency here in reference to #'write-rdf....
(fn [context g to-write fmt] (write-rdf-dispatch context g to-write fmt)))
(defn write-rdf-dispatch
"Returns [graph-dispatch to-write-dispatch fmt]. See docstring for `rdf/write-rdf`"
[context g to-write fmt]
{:pre [(instance? ont_app.igraph.graph.Graph context)
(context #'write-rdf :rdf-app/hasGraphDispatch)
]
}
(trace
::starting-write-rdf-dispatch
::context context
::g g
::to-write to-write
::fmt fmt
)
(value-trace
::value-of-write-rdf-dispatch
[::context context
::g g
::to-write to-write
::fmt fmt
]
;; return vector...
[(unique (context #'write-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-write-dispatch (unique (context #'write-rdf :rdf-app/toExportDispatchFn))]
(to-write-dispatch to-write)
;; else no despatch function was provided
(standard-data-transfer-dispatch to-write))
,
fmt
]))
(defmethod write-rdf :default
[context g file-id fmt]
(throw (ex-info "No method for rdf/write-rdf"
{:type ::NoMethodForWriteRdf
::context context
::g g
::file file-id
::fmt fmt
::dispatch (write-rdf-dispatch context g file-id fmt)
})))
;;;;;;;;;;;;;;;;;;;;
;; LITERAL SUPPORT
;;;;;;;;;;;;;;;;;;;;
(defn quote-str
"Returns `s`, in escaped quotation marks.
Where
- `s` is a string, typically to be rendered in a query or RDF source.
"
[s]
(value-trace
::QuoteString
(str "\"" s "\"")
))
(def transit-write-handlers
"Atom of the form {`Class` `write-handler`, ...}
Where
- `Class`, a symbol, is a direct reference to the class instance to be encoded
- `write-handler` := fn [s] -> {`field` `value`, ...}
"
(atom
#?(:clj
{LangStr
(cognitect.transit/write-handler
"ont-app.vocabulary.lstr.LangStr"
(fn [ls]
{:lang (.lang ls)
:s (.s ls)
}))
}
:cljs
{})))
(def transit-read-handlers
"Atom of the form {`className` `read-handler, ...}`
Where
- `className` is a fully qualified string naming a class to be encoded
- `read-handler` := fn [from-rep] -> `instance`
- `from-rep` := an Object s.t. (`field` from-rep), encoded in corresponding
write-handler in @`transit-write-handlers`.
"
(atom
#?(:clj
{"ont-app.vocabulary.lstr.LangStr"
(cognitect.transit/read-handler
(fn [from-rep]
(->LangStr (:s from-rep) (:lang from-rep))))
}
:cljs
{})
))
(defn render-literal-as-transit-json
"Returns 'x^^transit:json'
NOTE: this will be encoded on write and decoded on read by the
cognitect/transit library."
[x]
(stache/render "\"{{x}}\"^^transit:json" {:x (render-transit-json x)}))
;; RENDER LITERAL
(def special-literal-dispatch
"A function [x] -> `dispatch-value`
Where
- `x` is any value, probabaly an RDF literal
- `dispatch-value` is a value to be matched to a `render-literal-dispatch` method.
Default is to return nil, signalling no special dispatch."
(atom (fn [_] nil)))
(defn render-literal-dispatch
"Returns a key for the render-literal method to dispatch on given `literal`
Where
- `literal` is any non-keyword
- NOTE: LangStr and non-nil `special-dispatch` are special cases; otherwise
(type `literal`)
"
[literal]
(value-trace
::RenderLiteralDispatch
[:literal literal]
(if-let [special-dispatch (@special-literal-dispatch literal)]
special-dispatch
;; else no special dispatch...
(type literal))))
(defmulti render-literal
"Returns an RDF (Turtle) rendering of `literal`
for methods with signature (fn [literal] -> `rdf`)"
render-literal-dispatch)
(defmethod render-literal :rdf-app/TransitData
[v]
(render-literal-as-transit-json v))
(defmethod render-literal LangStr
[ls]
(str (quote-str (.s ls)) "@" (.lang ls)))
(defmethod render-literal ::number
;; ints and floats all derive from ::number
;; just insert the value directly
[n]
n)
(defmethod render-literal :default
[s]
(quote-str s))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
STANDARD TEMPLATES FOR IGRAPH MEMBER ACCESS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def query-template-defaults
"Default key/value pairs appicable to query templates for your platform.
Where
- `:from-clauses` one FROM clause for each graph informing the query
- `:rebind-_s` asserts new binding for ?_s in ?_s ?_p ?_o
- `:rebind-_p` asserts a new binding the value retrieved for ?_p in ?_s ?_p ?_o
- `:rebind-_o` aserts a new binding the value retrieved for ?_o in ?_s ?_p ?_o
- NOTE: For example we may assert :rebind-_s as `IRI(?_S)` in jena to set up bnode round-tripping for ?_s.
"
(atom
{:from-clauses ""
:rebind-_s "?_s"
:rebind-_p "?_p"
:rebind-_o "?_o"
}))
(defn from-clause-for
"
Returns FROM `graph-uri`'
Note: typically informs `query-template-map`
"
[graph-uri]
(stache/render "FROM <{{{graph-uri}}}>"
{:graph-uri graph-uri}))
(defn- query-template-map
"Returns {`k` `v`, ...} appropriate for `rdf-store` with `graph-uri`
Where
- `k` and `v` are cljstache template parameters which may appear in some query,
e.g. named graph open/close clauses
- `rdf-store` is an RDF store.
- `graph-uri` is either nil, a single graph-uri or a set of graph-uris
"
[graph-uri _rdf-store]
(let [as-set (fn [gu] (if (set? gu) gu (set gu)))
]
(merge @query-template-defaults
{:from-clauses (if graph-uri
(s/join "\n"
(map (comp from-clause-for voc/iri-for)
(as-set graph-uri)))
;; else no graph uri
"")
})))
(def subjects-query-template "A 'stache template for a query ref'd in `query-for-subjects`, informed by `query-template-map` "
note the use of 3 brackets to turn off escaping
"
Select Distinct ?s
{{{from-clauses}}}
Where
{
?_s ?_p ?_o.
Bind ({{{rebind-_s}}} as ?s)
Bind ({{{rebind-_p}}} as ?p)
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-subjects
"Returns [`subject` ...] at endpoint of `rdf-store` for `graph-uri`
Where
- `subject` is the uri of a subject from `rdf-store`,
rendered per the binding translator of `rdf-store`
- `rdf-store` conforms to ::sparql-client spec
- `query-fn` := fn [repo] -> bindings
- `graph-uri` is a URI or KWI naming the graph, or a set of them (or nil if DEFAULT
graph)
"
([query-fn rdf-store]
(query-for-subjects (fn [_] nil) query-fn rdf-store)
)
([graph-uri query-fn rdf-store]
(let [query (stache/render subjects-query-template
(query-template-map graph-uri rdf-store))
]
(map :s
(query-fn rdf-store query)))))
(def normal-form-query-template "A 'stache template for a query ref'd in `query-for-normal-form`, informed by `query-template-map` "
"
Select ?s ?p ?o
{{{from-clauses}}}
Where
{
?_s ?_p ?_o.
Bind ({{{rebind-_s}}} as ?s)
Bind ({{{rebind-_p}}} as ?p)
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-normal-form
"Returns IGraph normal form for `graph` named by `graph-uri` in `rdf-store`
Where
- `graph` is a named graph in `rdf-store`
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(default nil -> DEFAULT graph)
- `rdf-store` is an RDF store
- `query-fn` := fn [rdf-store sparql-query] -> #{`bmap`, ...}
- `bmap` := {:?s :?p :?o}
- `sparql-query` :- `normal-form-query-template`
"
([query-fn rdf-store]
(query-for-normal-form nil query-fn rdf-store))
([graph-uri query-fn rdf-store]
(letfn [
(add-o [o binding]
(conj o (:o binding)))
(add-po [po binding]
(assoc po (:p binding)
(add-o (get po (:p binding) #{})
binding)))
(collect-binding [spo binding]
(value-trace
::CollectNormalFormBinding
[:spo spo
:binding binding]
(assoc spo (:s binding)
(add-po (get spo (:s binding) {})
binding))))
]
(let [query (stache/render normal-form-query-template
(query-template-map graph-uri rdf-store))
]
(value-trace
::QueryForNormalForm
[:query query
:graph-uri graph-uri
:query-fn query-fn]
(reduce collect-binding
{}
(query-fn rdf-store query)))))))
(defn check-ns-metadata
"Logs a warning when `kwi` is in a namespace with no metadata."
[kwi]
(let [n (symbol (namespace kwi))]
(when-let [the-ns (find-ns n)]
(when (not (meta the-ns))
(warn ::NoMetaDataInNS
:glog/message "The namespace for {{kwi}} is in a namespace with no associated metadata."
:kwi kwi))))
kwi)
(defn check-qname
"Traps the keyword assertion error in voc and throws a more meaningful error
about blank nodes not being supported as first-class identifiers."
[uri-spec]
(if (bnode-kwi? uri-spec)
(name uri-spec)
;;else not a blank node
(try
(voc/qname-for (check-ns-metadata uri-spec))
(catch Throwable e
(throw (ex-info (str "The URI spec " uri-spec " is invalid.\nCould it be a blank node?")
(merge (ex-data e)
{:type ::Invalid-URI-spec
::uri-spec uri-spec
})))))))
(def query-for-p-o-template "A 'stache template for a query ref'd in `query-for-p-o`, informed by `query-template-map`"
"
Select ?p ?o
{{{from-clauses}}}
Where
{
{{{subject}}} ?_p ?_o.
Bind ({{{rebind-_p}}} as ?p)
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-p-o
"Returns {`p` #{`o`...}...} for `s` from query to `rdf-store`
Where
- `p` is a predicate URI rendered per binding translator of `rdf-store`
- `o` is an object value, rendered per the binding translator of `rdf-store`
- `s` is a subject uri keyword. ~ voc/voc-re
- `rdf-store` is and RDF store.
- `query-fn` := fn [repo] -> bindings
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(or nil if DEFAULT graph)
"
([query-fn rdf-store s]
(query-for-p-o nil query-fn rdf-store s)
)
([graph-uri query-fn rdf-store s]
{:pre [(not (nil? s))
]
}
(debug ::Starting_query-for-p-o
::graph-uri graph-uri
::query-fn query-fn
::rdf-store rdf-store
::s s)
(let [query (prefixed
(stache/render query-for-p-o-template
(merge (query-template-map graph-uri rdf-store)
{:subject (check-qname s)})))
collect-bindings (fn [acc b]
(update acc (:p b)
(fn[os] (set (conj os (:o b))))))
]
(value-debug
::query-for-po
[::query query ::subject s]
(reduce collect-bindings {}
(query-fn rdf-store query))))))
(def query-for-o-template "A 'stache template for a query ref'd in `query-for-o`, informed by `query-template-map`"
"
Select ?o
{{{from-clauses}}}
Where
{
{{{subject}}} {{{predicate}}} ?_o.
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-o
"Returns #{`o`...} for `s` and `p` at endpoint of `rdf-store`
Where:
- `o` is an object rendered per binding translator of `rdf-store`
- `s` is a subject URI rendered per binding translator of `rdf-store`
- `p` is a predicate URI rendered per binding translator of `rdf-store`
- `rdf-store` is an RDF store
- `query-fn` := fn [repo] -> bindings
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(or nil if DEFAULT graph)
"
([query-fn rdf-store s p]
(query-for-o nil query-fn rdf-store s p))
([graph-uri query-fn rdf-store s p]
(let [query (prefixed
(stache/render
query-for-o-template
(merge (query-template-map graph-uri rdf-store)
{:subject (check-qname s)
:predicate (check-qname p)})))
collect-bindings (fn [acc b]
(conj acc (:o b)))
]
(value-debug
::query-for-o-return
[::query query
::subject s
::predicate p]
(reduce collect-bindings #{}
(query-fn rdf-store query))))))
(def ask-s-p-o-template "A 'stache template for a query ref'd in `ask-s-p-o`, informed by `query-template-map`"
"ASK
{{{from-clauses}}}
where
{
{{{subject}}} {{{predicate}}} {{{object}}}.
}"
)
(defn ask-s-p-o
"Returns true if `s` `p` `o` is a triple at endpoint of `rdf-store`
Where:
- `s` `p` `o` are subject, predicate and object
- `rdf-store` is an RDF store
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(or nil if DEFAULT graph)
- `ask-fn` := fn [repo] -> bindings
"
([ask-fn rdf-store s p o]
(ask-s-p-o nil ask-fn rdf-store s p o)
)
([graph-uri ask-fn rdf-store s p o]
(let [query (prefixed
(stache/render
ask-s-p-o-template
(merge (query-template-map graph-uri rdf-store)
{:subject (check-qname s)
:predicate (check-qname p)
:object (if (keyword? o)
(voc/qname-for o)
(render-literal o))})))
starting (debug ::Starting_ask-s-p-o
:query query
:subject s
:predicate p
:object o)
]
(value-debug
::ask-s-p-o-return
[:resultOf starting]
(ask-fn rdf-store query)))))
;;;;;;;;;;;;;;;
;;; DEPRECATED
;;;;;;;;;;;;;;
^:deprecated
(defmethod render-literal :rdf-app/LangStr ;; using the type is fine
[ls]
(str (quote-str (.s ls)) "@" (.lang ls)))
| null | https://raw.githubusercontent.com/ont-app/rdf/60b7a7331db4d435d67d4baccf9b4756e3304c26/src/ont_app/rdf/core.cljc | clojure | These errors were found to be spurious, related to cljs ...
meta
ont-app
reader conditionals
todo add cljs-http.client?
require
aliases
FUN WITH READER MACROS
standard clojure containers are declared by default as descendents of
transit data. renders as transit by default.
Note that you can undo this with 'underive', in which case
it will probably be rendered as a string, unless you want
to write your own method...
-escaped string encoded as transit
NO READER MACROS BELOW THIS POINT
except in try/catch clauses
SPECS
start with quote
terminal quote
^^
end with type tag
INPUT/OUTPUT
KWI/URI conversion for catalog contents
There's a tricky circular dependency here in reference to #'load-rdf....
return [graph-dispatch, to-load-dispatch] ...
else no despatch function was provided
URL caching
start with anything ending in slash
dot
else there is no pathFn, try to parse the URL...
else no cached-file-path
default behavior to load URLs.
to enable (derive <my-Igraph> :rdf-app/IGraph)
default behavior to load URLs.
to enable (derive <my-Igraph> :rdf-app/IGraph)
There's a tricky circular dependency here in reference to #'read-rdf....
return vector...
else no despatch function was provided
write-rdf
There's a tricky circular dependency here in reference to #'write-rdf....
return vector...
else no despatch function was provided
LITERAL SUPPORT
RENDER LITERAL
otherwise
else no special dispatch...
ints and floats all derive from ::number
just insert the value directly
else no graph uri
else not a blank node
DEPRECATED
using the type is fine | (ns ont-app.rdf.core
{:doc "This is a backstop for shared logic between various RDF-based
implementations of IGraph.
It includes:
- support for LangStr using the #voc/lstr custom reader
- support for ^^transit:json datatype tags
- templating utilities for the standard IGraph member access methods.
- i/o methods `load-rdf` `read-rdf` and `write-rdf`.
"
:author "Eric D. Scott"
:clj-kondo/config '{:linters {:unresolved-symbol {:level :off}
}}
(:require
[clojure.string :as s]
[clojure.spec.alpha :as spec]
3rd party
[cljstache.core :as stache]
[ont-app.igraph.core :as igraph :refer [unique]]
[ont-app.igraph.graph :as native-normal]
[ont-app.vocabulary.core :as voc]
[ont-app.rdf.ont :as ont]
#?(:clj [clojure.java.io :as io])
todo remove conditional after issue 4
#?(:clj [ont-app.graph-log.levels :as levels
:refer [warn debug trace value-trace value-debug]]
:cljs [ont-app.graph-log.levels :as levels
:refer-macros [warn debug value-trace value-debug]])
todo remove conditional after issue 4
#?(:clj
(:import
[java.io ByteArrayInputStream ByteArrayOutputStream]
[java.io File]
[ont_app.vocabulary.lstr LangStr]
)))
(voc/put-ns-meta!
'ont-app.rdf.core
{
:voc/mapsTo 'ont-app.rdf.ont
}
)
(def prefixed
"Returns `query`, with prefix declarations prepended
Where
- `query` is presumed to be a SPARQL query"
voc/prepend-prefix-declarations)
(def ontology
"The supporting vocabulary for the RDF module"
@ont/ontology-atom)
#?(:cljs
(enable-console-print!)
)
#?(:cljs
(defn on-js-reload [] )
)
: rdf - app / TransitData , which keys to the render - literal method for rendering
(derive #?(:clj clojure.lang.PersistentVector
:cljs cljs.core.PersistentVector)
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentHashSet
:cljs cljs.core.PersistentHashSet )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentArrayMap
:cljs cljs.core.PersistentArrayMap )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.PersistentList
:cljs cljs.core.PersistentList )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.Cons
:cljs cljs.core.Cons )
:rdf-app/TransitData)
(derive #?(:clj clojure.lang.LazySeq
:cljs cljs.core.LazySeq )
:rdf-app/TransitData)
#?(:clj (derive java.lang.Long ::number)
:cljs (derive cljs.core.Long ::number)
)
#?(:clj (derive java.lang.Double ::number)
:cljs (derive cljs.core..Double ::number)
)
(declare transit-read-handlers)
(defn read-transit-json
"Returns a value parsed from transit string `s`
Where
Note: custom datatypes will be informed by @transit-read-handlers
"
[^String s]
#?(:clj
(transit/read
(transit/reader
(ByteArrayInputStream. (.getBytes (clojure.string/replace
s
""" "\"")
"UTF-8"))
:json
{:handlers @transit-read-handlers}))
:cljs
(throw (ex-info "read-transit-json not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'read-transit-json
::args [s]
}))
#_(transit/read
(transit/reader
:json
{:handlers @transit-read-handlers})
(clojure.string/replace
s
""" "\""))))
(declare transit-write-handlers)
(defn render-transit-json
"Returns a string of transit for `value`
Where
- `value` is any value that be handled by cognitict/transit
- Note: custom datatypes will be informed by @transit-write-handlers
"
[value]
#?(:clj
(let [output-stream (ByteArrayOutputStream.)
]
(transit/write
(transit/writer output-stream :json {:handlers @transit-write-handlers})
value)
(String. (.toByteArray output-stream)))
:cljs
(throw (ex-info "render-transit-json not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'render-transit-json
::args [value]
}))
#_(transit/write
(transit/writer :json {:handlers @transit-write-handlers})
value)))
(defn cljc-file-exists?
"True when `path` exists in the local file system"
[path]
#?(:clj
(.exists (io/file path))
:cljs
(let []
(warn ::FileExistsCheckInCljs
:glog/message "Checking for existence of local file {{path}} in clojurescript (returning false)"
::path path)
false
)))
(defn cljc-is-local-file?
"True when `f` is a file in the local file system"
[f]
#?(:clj
(instance? java.io.File f)
:cljs
(let []
(warn ::IsLocalFileCheckInCljs
:glog/message "Checking whether {{f}} is local file in clojurescript (returning false)"
::f f)
false)))
(defn cljc-make-file
"Returns new file object for `path`. Not supported under cljs."
[path]
#?(:clj
(io/file path)
:cljs
(throw (ex-info "Make-file not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-make-file
::args [path]
}))))
(defn cljc-file-length
"Returns length of file `f`. Not supported under cljs."
[f]
#?(:clj
(.length f)
:cljs
(throw (ex-info "File-length not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-file-length
::args [f]
}))))
(defn cljc-make-parents
"Ensures directory path for file `f`. Not supported under cljs."
[f]
#?(:clj
(io/make-parents f)
:cljs
(throw (ex-info "Make-parents not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-make-parents
::args [f]
}))))
(defn cljc-resource
"Returns the resource named by `r`. Not supported under cljs."
[r]
#?(:clj
(io/resource r)
:cljs
(throw (ex-info "Resource not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-resource
::args [r]
}))))
(defn cljc-create-temp-file
"Returns a temporary file named per `stem` and `ext`. Not supported under cljs.
- where
- `stem` is a general name for the file
- `ext` is a file extension typically starting with '.'
"
[stem ext]
#?(:clj
(File/createTempFile stem ext)
:cljs
(throw (ex-info "Create-temp-file not supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-create-temp-file
::args [stem ext]
}))))
(defn cljc-http-get
"Makes a GET call to `url` with `req`. Not yet supported in cljs.
- Where
- `url` is a URL or a URL string
- `req` is an http request map
"
[url req]
#?(:clj
(http/get (str url) req)
:cljs
TODO : probably need to import cljs - http . Pending issue 4
(throw (ex-info "Http-get not yet supported in cljs"
{:type ::NotSupportedInCljs
::fn #'cljc-http-get
::args [url req]
}))))
(def transit-re
"Matches data tagged as transit:json"
anything ( group 1 )
)))
(spec/def ::transit-tag (spec/and string? (fn [s] (re-matches transit-re s))))
(defn bnode-kwi?
"True when `kwi` matches the canonical bnode representation."
[kwi]
(and (keyword? kwi)
(some->> (namespace kwi)
(str)
(re-matches #"^_.*"))))
(spec/def ::bnode-kwi bnode-kwi?)
(spec/def ::file-resource (fn [url] (and (instance? java.net.URL url)
(-> (.getProtocol url)
#{"file" "jar"}))))
(spec/def ::web-resource (fn [url] (and (instance? java.net.URL url)
(-> (.getProtocol url)
#{"http" "https"}))))
(defn coerce-graph-element
"Returns `x`, possibly coerced to either a kwi or a java.net.URI per `policy`
- where
- `policy` := m s.t. (keys m) :- #{::kwi-if ::uri-if}
- `x` is any candidate as an element in an IGraph
- `kwi-if` := fn [x] -> truthy if `x` should be translated to a keyword id
- `uri-if` := fn [x] -> truthy if `x` should be translated to a java.net.URI
- NOTE: Some implementations of IGraph may be a lot more tolarant of datatypes
in s/p/o position than the URI/URI/URI-or-literal that RDF expects.
"
([x]
(coerce-graph-element {::kwi-if (fn [x] (re-matches (voc/namespace-re) (str x)))
::uri-if (fn [x] (or
(re-matches voc/ordinary-iri-str-re (str x))
(re-matches voc/exceptional-iri-str-re (str x))))
}
x))
([policy x]
(cond
((::kwi-if policy) x)
(if (keyword? x)
x
(voc/keyword-for (str x)))
((::uri-if policy) x)
(if (instance? java.net.URI x)
x
(java.net.URI. (str x)))
:else x
)))
(defn collect-ns-catalog-metadata
"Reducing function outputs `gacc'` given voc metadata assigned to namespace
- NOTE: typically used to initialize the resource catalog.
"
[gacc _prefix ns]
(let [m (voc/get-ns-meta ns)
uri (:vann/preferredNamespaceUri m)
prefix (:vann/preferredNamespacePrefix m)
download-url (:dcat/downloadURL m)
appendix (:voc/appendix m)
]
(if (and download-url appendix)
appendix is one or more triples expressed as vectors
(-> gacc
(igraph/add [(coerce-graph-element uri)
:dcat/downloadURL (coerce-graph-element download-url)
:vann/preferredNamespacePrefix prefix
])
(igraph/add (mapv (fn [v] (mapv coerce-graph-element v))
appendix)))
gacc)))
(def resource-catalog
"A native normal graph using this vocabulary:
- [`namespace-uri` :dcat/downloadURL `download-url`]
- [`namespace-uri` :vann/preferredNamespacePrefix `prefix`]
- [`download-url` :dcat/mediaType `media-type`]
- where
- `download-url` is a URL string
- `media-type` := :rdf/type :dct/MediaTypeOrExtent
"
(atom (->> (voc/prefix-to-ns)
(reduce-kv collect-ns-catalog-metadata
(native-normal/make-graph)))))
(defn add-catalog-entry!
"Adds an entry in @resource-catalog for `download-url` `namespace-uri` `prefix` `media-type`
- Where
- `download-url` is a URL (or string) naming a place on the web containing an RDF file
- `namespace-uri` is the primary URI, associated with `prefix`
- `prefix` is the preferred prefix for `namespace-uri`
- `media-type` is the MIME type, of `download-url` eg 'text/turtle'
"
[download-url namespace-uri prefix media-type]
(swap! resource-catalog
igraph/add
[[(coerce-graph-element namespace-uri)
:vann/preferredNamespacePrefix prefix
:dcat/downloadURL (coerce-graph-element download-url)]
[(coerce-graph-element download-url)
:dcat/mediaType media-type
]]))
(def default-context
"An atom containing a native-normal graph with default i/o context configurations.
- NOTE: This would typically be the starting point for the i/o context of individual
implementations.
- VOCABULARY
- [:rdf-app/UrlCache :rdf-app/directory `URL cache directory`]
"
(atom (-> (native-normal/make-graph)
(igraph/add [[:rdf-app/UrlCache
:rdf-app/directory "/tmp/rdf-app/UrlCache"]
]))))
(defn standard-data-transfer-dispatch
"Returns a standard `dispatch-key` for `to-transfer`, defaulting to (type to-transfer)
- Where
- `to-transfer` is typically an argument to the `load-rdf`, `read-rdf` or `write-rdf` methods.
- `dispatch-key` :~ #{:rdf-app/LocalFile, :rdf-app/FileResource :rdf/WebResource}
or the type of `to-transfer`.
- :rdf-app/LocalFile indicates that `to-transfer` is a local path string
- :rdf-app/FileResource indicates that `to-transfer` is a file resource (maybe from a jar)
- :rdf-app/WebResource indicates something accessible through a curl call.
"
[to-transfer]
(cond
(and (string? to-transfer)
(cljc-file-exists? to-transfer))
:rdf-app/LocalFile
(cljc-is-local-file? to-transfer)
:rdf-app/LocalFile
(spec/valid? ::file-resource to-transfer)
:rdf-app/FileResource
(spec/valid? ::web-resource to-transfer)
:rdf-app/WebResource
:else (type to-transfer))
)
(declare load-rdf-dispatch)
(defmulti load-rdf
"Returns a new IGraph with contents for `to-load`,
- args: [`context` `to-load`]
- dispatched on: [`graph-dispatch` `to-load-rdf-dispatch`]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-load` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`. We may need to derive `file-extension`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-load-rdf-dispatch` is the dispatch value derived for `to-load-rdf`
- `file-extension` may be implicit from a file name or derived per vocabulary below
It may be necesary to inform your RDF store about the expected format.
- VOCABULARY (in `context`)
- [`#'load-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'load-rdf` :rdf-app/toImportDispatchFn (fn [to-load] -> to-load-dispatch)]
... optional. Defaults to output of `standard-data-transfer-dispatch`
- [`#'load-rdf` :rdf-app/extensionFn (fn [to-load] -> file-extension)]
... optional. By default it parses the presumed path name described by `to-load`
- [rdf-app/UrlCache rdf-app/directory `cache-directory`]
- [rdf-app/UrlCache rdf-app/cacheMaintenance :rdf-app/DeleteOnRead]
... optional. specifies that a cached file should be deleted after a read.
- by default it will not be deleted.
"
(fn [context to-load] (load-rdf-dispatch context to-load)))
(defn load-rdf-dispatch
"Returns [graph-dispatch to-load-dispatch]. See docstring for `rdf/load-rdf`"
[context to-load]
{:pre [(fn [context _] (context #'load-rdf :rdf-app/hasGraphDispatch))
]
}
(value-trace
::load-rdf-dispatch
[::context context
::to-load to-load
]
[(unique (context #'load-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-load-dispatch (unique (context #'load-rdf :rdf-app/toImportDispatchFn))]
(to-load-dispatch to-load)
(standard-data-transfer-dispatch to-load))
]))
(defn cached-file-path
"Returns a canonical path for cached contents read from a URL."
[& {:keys [dir url stem ext]}]
(assert dir)
(str dir "/" stem "_hash=" (hash url) "." ext))
(defn catalog-lookup
"Returns `catalog-entry` for `url`
- Where
- `catalog-entry` := m s.t. (keys m) :~ #{?media-type :?prefix :?suffix :?media-url}
- `url` is a URL that may be in the resource catalog
- `:?prefix` is the preferred prefix associated with `url` (which informs the stem)
- `:?suffix` is the suffix associated with the `:?media-url` (informs the extension)
"
[url]
(let [g (igraph/union @resource-catalog
ontology)
url (coerce-graph-element url)
]
(-> (igraph/query g
[[url :dcat/mediaType :?media-type]
[:?media-url :formats/media_type :?media-type]
[:?media-url :formats/preferred_suffix :?suffix]
[:?namespace-uri :dcat/downloadURL url]
[:?namespace-uri :vann/preferredNamespacePrefix :?prefix]
])
(unique))))
(defn lookup-file-specs-in-catalog
"Returns `file-specs` for `url`
- Where
- `file-specs` := m s.t. (keys m) :~ #{:url :path :stem :ext}
- `url` (as arg) is a URL we may want to get from an http call
- `url` (as key) is the string version of `url`
- `path` is the file path of `url`
- `stem` is the preferred prefix for `url` in the catalog
- `ext` is the file suffix associated with the media type of `url` in the catalog
"
[url]
(when-let [lookup (catalog-lookup url)
]
{:url (str url)
:path (.getPath url)
:stem (:?prefix lookup)
:ext (clojure.string/replace (:?suffix lookup) #"\." "")
}))
(defn http-get-from-catalog
"returns an http response to a GET request for `url`
- Where
- `url` is a URL with an entry in the @`resource-catalog`
"
[url]
(let [lookup (catalog-lookup url)
]
(when lookup
(cljc-http-get (str url)
{:accept (:?media-type lookup)})
)))
(def parse-url-re
"A regex to parse a file URL string with a file name and an extension."
(re-pattern
at least one non - slash ( group 1 )
any ending , ( group 2 )
)))
(defn parse-url
"Returns a file specification parsed directly from a URL (not in the catalog), or nil
- where
- `url` is a URL, probably a file resource"
[url]
(let [path (.getPath url)
matches (re-matches parse-url-re path)
]
(when-let [[_ stem ext] matches]
{:url (str url)
:path path
:stem stem
:ext ext
})))
(defn get-cached-file-path-spec
"Returns `m` s.t (keys m) :~ #{:url :path :stem :ext} for `url` informed by `context`
- Where
- `url` (as arg) is x s.t. (str x) -> a URL string
- `context` is an native-normal graph describing the I/O context
- `url` (as key) is a URL string
- `path` is the path component of `url`
- `stem` is the 'stem portion of /path/to/<stem>.<ext>
- `ext` is the 'ext' portion of /path/to/<stem>.<ext>
- `dir` is the directory containing cache files
- NOTE: this should be sufficient to create a unique temp file path for caching
contents of `url`.
- VOCABULARY
- [:rdf-app/UrlCache :rdf-app/pathFn `cached-file-path-fn`]
- optional. Default will try to infer `m` from `url` automatically
Either through `lookup-file-specs-in-catalog` or by parsing `url` itself.
- [:rdf-app/UrlCache :rdf-app/directory `dir`]
- `cached-file-path-fn` := fn (uri) -> `m`
"
[context url]
(value-trace
::get-cached-file-spec
[::context context
::url url
]
(if-let [cached-file-path-fn (unique (context :rdf-app/UrlCache :rdf-app/pathFn))
]
(cached-file-path-fn url)
(let [dir (unique (context :rdf-app/UrlCache :rdf-app/directory))
]
(assoc (or (lookup-file-specs-in-catalog url)
(parse-url url))
:dir dir)))))
(defn cache-url-as-local-file
"RETURNS `cached-file`, with contents of `url` loaded
SIDE-EFFECT: creates file named `cached-file` if it does not already exist.
- Where
- `context` is a native-normal graph informed by vocabulary below.
- `url` := a URL or string naming URL
- `cached-file-path` names a local file to contain contents from `url`
- VOCABULARY (for `context`)
- [:rdf-app/UrlCache :rdf-app/pathFn `cached-file-path-fn`]
- optional. Default will try to derive `parse-map` from `url` first by looking
it up in the @`resource-catalog` and then by parsing the `url` itself
- [:rdf-app/UrlCache :rdf-app/directory `cache-directory`]
- `cached-file-path-fn` := fn (uri) -> `parse-map`
- `parse-map` := m s.t (keys m) :~ #{:url :path :stem :ext} for `url` informed by `context`
"
[context url]
(value-trace
::cache-url-as-local-file
[::context context
::url url
]
(if-let [temp-file-path (some-> (get-cached-file-path-spec context url)
(cached-file-path))
]
(let [cached-file (cljc-make-file temp-file-path)
]
(when (not (and (cljc-file-exists? cached-file)
(> (cljc-file-length cached-file) 0)))
(cljc-make-parents cached-file)
(spit cached-file
(cond
(context url :rdf/type :rdf-app/FileResource)
(slurp url)
(context url :rdf/type :rdf-app/WebResource)
(-> (http-get-from-catalog url)
:body)
:else
(throw (ex-info "Resource type not sufficiently specified in context"
{:type ::ResourceNotSufficientlySpecifiedInContext
::context context
::url url
})))))
cached-file)
(throw (ex-info (str "No caching path could be inferred for %s" url)
{:type ::NOCachingPathCouldBeInferredForURL
::context context
::url url
})))))
(defmethod load-rdf [:rdf-app/IGraph :rdf-app/FileResource]
[context url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/FileResource])
url)
(load-rdf context)))
(defmethod load-rdf [:rdf-app/IGraph :rdf-app/WebResource]
[context url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/WebResource])
url)
(load-rdf context)))
(defmethod load-rdf :default
[context file-id]
(throw (ex-info "No method for rdf/load-rdf"
{:type ::NoMethodForLoadRdf
::context context
::file file-id
::dispatch (load-rdf-dispatch context file-id)
})))
(declare read-rdf-dispatch)
(defmulti read-rdf
"Side-effect: updates `g` with added contents from `to-read`,
Returns: modified `g`
- args: [context g to-read]
- dispatched on: [graph-dispatch to-read-dispatch]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-read` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`. We may need to derive `file-extension`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-read-dispatch` is the dispatch value derived for `to-read`
- `file-extension` may be implicit from a file name or derived per vocabulary below
It may be necesary to inform your RDF store about the expected format.
- VOCABULARY (in `context`)
- [`#'read-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'read-rdf` :rdf-app/toImportDispatchFn (fn [to-read] -> `to-read-dispatch`)]
... optional. Defaults to output of `standard-data-transfer-dispatch`
- [`#'read-rdf` :rdf-app/extensionFn (fn [to-read] -> file-extension)]
... optional. By default it parses the presumed path name described by `to-read`
"
(fn [context g to-read] (read-rdf-dispatch context g to-read)))
(defn read-rdf-dispatch
"Returns [graph-dispatch to-read-dispatch]. See docstring for `rdf/read-rdf`"
[context g to-read]
{:pre [(instance? ont_app.igraph.graph.Graph context)
(context #'read-rdf :rdf-app/hasGraphDispatch)
]
}
(trace
::starting-read-rdf-dispatch
::context context
::g g
::to-read to-read
)
(value-trace
::value-of-read-rdf-dispatch
[::context context
::g g
::to-read to-read
]
[(unique (context #'read-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-read-dispatch (unique (context #'read-rdf :rdf-app/toImportDispatchFn))]
(to-read-dispatch to-read)
(standard-data-transfer-dispatch to-read))
]))
(defmethod read-rdf [:rdf-app/IGraph :rdf-app/FileResource]
[context g url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/FileResource])
url)
(read-rdf context g)))
(defmethod read-rdf [:rdf-app/IGraph :rdf-app/WebResource]
[context g url]
(->> (cache-url-as-local-file (igraph/add context
[url :rdf/type :rdf-app/WebResource])
url)
(read-rdf context g)))
(defmethod read-rdf :default
[context g file-id]
(throw (ex-info "No method for rdf/read-rdf"
{:type ::NoMethodForReadRdf
::context context
::g g
::file file-id
::dispatch (read-rdf-dispatch context g file-id)
})))
(declare write-rdf-dispatch)
(defmulti write-rdf
"Side-effect: writes contents of `g` to `to-write` in `fmt`,
Returns: modified `g`
- args: [context g to-write fmt]
- dispatched on: [graph-dispatch to-write-dispatch fmt]
- Where
- `context` is a native-normal graph with descriptions per the vocabulary below.
It may also provide platform-specific details that inform specific methods.
- `to-write` is typically a path or URL, but could be anything you write a method for
- if this is a file name that exists in the local file system this will be
dispatched as `:rdf-app/LocalFile`.
- `graph-dispatch` is the dispatch value identifying the IGraph implementation
- `to-write-dispatch` is the dispatch value derived for `to-write`
- `fmt` is typically a KWI derived from `:dct/MediaTypeOrExtent`
- VOCABULARY (in `context`)
- [`#'write-rdf` :rdf-app/hasGraphDispatch `graph-dispatch`]
- [`#'write-rdf` :rdf-app/toExportDispatchFn (fn [to-write] -> `to-write-dispatch`)]
... optional. Defaults to (type to-write)
"
(fn [context g to-write fmt] (write-rdf-dispatch context g to-write fmt)))
(defn write-rdf-dispatch
"Returns [graph-dispatch to-write-dispatch fmt]. See docstring for `rdf/write-rdf`"
[context g to-write fmt]
{:pre [(instance? ont_app.igraph.graph.Graph context)
(context #'write-rdf :rdf-app/hasGraphDispatch)
]
}
(trace
::starting-write-rdf-dispatch
::context context
::g g
::to-write to-write
::fmt fmt
)
(value-trace
::value-of-write-rdf-dispatch
[::context context
::g g
::to-write to-write
::fmt fmt
]
[(unique (context #'write-rdf :rdf-app/hasGraphDispatch))
,
(if-let [to-write-dispatch (unique (context #'write-rdf :rdf-app/toExportDispatchFn))]
(to-write-dispatch to-write)
(standard-data-transfer-dispatch to-write))
,
fmt
]))
(defmethod write-rdf :default
[context g file-id fmt]
(throw (ex-info "No method for rdf/write-rdf"
{:type ::NoMethodForWriteRdf
::context context
::g g
::file file-id
::fmt fmt
::dispatch (write-rdf-dispatch context g file-id fmt)
})))
(defn quote-str
"Returns `s`, in escaped quotation marks.
Where
- `s` is a string, typically to be rendered in a query or RDF source.
"
[s]
(value-trace
::QuoteString
(str "\"" s "\"")
))
(def transit-write-handlers
"Atom of the form {`Class` `write-handler`, ...}
Where
- `Class`, a symbol, is a direct reference to the class instance to be encoded
- `write-handler` := fn [s] -> {`field` `value`, ...}
"
(atom
#?(:clj
{LangStr
(cognitect.transit/write-handler
"ont-app.vocabulary.lstr.LangStr"
(fn [ls]
{:lang (.lang ls)
:s (.s ls)
}))
}
:cljs
{})))
(def transit-read-handlers
"Atom of the form {`className` `read-handler, ...}`
Where
- `className` is a fully qualified string naming a class to be encoded
- `read-handler` := fn [from-rep] -> `instance`
- `from-rep` := an Object s.t. (`field` from-rep), encoded in corresponding
write-handler in @`transit-write-handlers`.
"
(atom
#?(:clj
{"ont-app.vocabulary.lstr.LangStr"
(cognitect.transit/read-handler
(fn [from-rep]
(->LangStr (:s from-rep) (:lang from-rep))))
}
:cljs
{})
))
(defn render-literal-as-transit-json
"Returns 'x^^transit:json'
NOTE: this will be encoded on write and decoded on read by the
cognitect/transit library."
[x]
(stache/render "\"{{x}}\"^^transit:json" {:x (render-transit-json x)}))
(def special-literal-dispatch
"A function [x] -> `dispatch-value`
Where
- `x` is any value, probabaly an RDF literal
- `dispatch-value` is a value to be matched to a `render-literal-dispatch` method.
Default is to return nil, signalling no special dispatch."
(atom (fn [_] nil)))
(defn render-literal-dispatch
"Returns a key for the render-literal method to dispatch on given `literal`
Where
- `literal` is any non-keyword
(type `literal`)
"
[literal]
(value-trace
::RenderLiteralDispatch
[:literal literal]
(if-let [special-dispatch (@special-literal-dispatch literal)]
special-dispatch
(type literal))))
(defmulti render-literal
"Returns an RDF (Turtle) rendering of `literal`
for methods with signature (fn [literal] -> `rdf`)"
render-literal-dispatch)
(defmethod render-literal :rdf-app/TransitData
[v]
(render-literal-as-transit-json v))
(defmethod render-literal LangStr
[ls]
(str (quote-str (.s ls)) "@" (.lang ls)))
(defmethod render-literal ::number
[n]
n)
(defmethod render-literal :default
[s]
(quote-str s))
STANDARD TEMPLATES FOR IGRAPH MEMBER ACCESS
(def query-template-defaults
"Default key/value pairs appicable to query templates for your platform.
Where
- `:from-clauses` one FROM clause for each graph informing the query
- `:rebind-_s` asserts new binding for ?_s in ?_s ?_p ?_o
- `:rebind-_p` asserts a new binding the value retrieved for ?_p in ?_s ?_p ?_o
- `:rebind-_o` aserts a new binding the value retrieved for ?_o in ?_s ?_p ?_o
- NOTE: For example we may assert :rebind-_s as `IRI(?_S)` in jena to set up bnode round-tripping for ?_s.
"
(atom
{:from-clauses ""
:rebind-_s "?_s"
:rebind-_p "?_p"
:rebind-_o "?_o"
}))
(defn from-clause-for
"
Returns FROM `graph-uri`'
Note: typically informs `query-template-map`
"
[graph-uri]
(stache/render "FROM <{{{graph-uri}}}>"
{:graph-uri graph-uri}))
(defn- query-template-map
"Returns {`k` `v`, ...} appropriate for `rdf-store` with `graph-uri`
Where
- `k` and `v` are cljstache template parameters which may appear in some query,
e.g. named graph open/close clauses
- `rdf-store` is an RDF store.
- `graph-uri` is either nil, a single graph-uri or a set of graph-uris
"
[graph-uri _rdf-store]
(let [as-set (fn [gu] (if (set? gu) gu (set gu)))
]
(merge @query-template-defaults
{:from-clauses (if graph-uri
(s/join "\n"
(map (comp from-clause-for voc/iri-for)
(as-set graph-uri)))
"")
})))
(def subjects-query-template "A 'stache template for a query ref'd in `query-for-subjects`, informed by `query-template-map` "
note the use of 3 brackets to turn off escaping
"
Select Distinct ?s
{{{from-clauses}}}
Where
{
?_s ?_p ?_o.
Bind ({{{rebind-_s}}} as ?s)
Bind ({{{rebind-_p}}} as ?p)
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-subjects
"Returns [`subject` ...] at endpoint of `rdf-store` for `graph-uri`
Where
- `subject` is the uri of a subject from `rdf-store`,
rendered per the binding translator of `rdf-store`
- `rdf-store` conforms to ::sparql-client spec
- `query-fn` := fn [repo] -> bindings
- `graph-uri` is a URI or KWI naming the graph, or a set of them (or nil if DEFAULT
graph)
"
([query-fn rdf-store]
(query-for-subjects (fn [_] nil) query-fn rdf-store)
)
([graph-uri query-fn rdf-store]
(let [query (stache/render subjects-query-template
(query-template-map graph-uri rdf-store))
]
(map :s
(query-fn rdf-store query)))))
(def normal-form-query-template "A 'stache template for a query ref'd in `query-for-normal-form`, informed by `query-template-map` "
"
Select ?s ?p ?o
{{{from-clauses}}}
Where
{
?_s ?_p ?_o.
Bind ({{{rebind-_s}}} as ?s)
Bind ({{{rebind-_p}}} as ?p)
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-normal-form
"Returns IGraph normal form for `graph` named by `graph-uri` in `rdf-store`
Where
- `graph` is a named graph in `rdf-store`
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(default nil -> DEFAULT graph)
- `rdf-store` is an RDF store
- `query-fn` := fn [rdf-store sparql-query] -> #{`bmap`, ...}
- `bmap` := {:?s :?p :?o}
- `sparql-query` :- `normal-form-query-template`
"
([query-fn rdf-store]
(query-for-normal-form nil query-fn rdf-store))
([graph-uri query-fn rdf-store]
(letfn [
(add-o [o binding]
(conj o (:o binding)))
(add-po [po binding]
(assoc po (:p binding)
(add-o (get po (:p binding) #{})
binding)))
(collect-binding [spo binding]
(value-trace
::CollectNormalFormBinding
[:spo spo
:binding binding]
(assoc spo (:s binding)
(add-po (get spo (:s binding) {})
binding))))
]
(let [query (stache/render normal-form-query-template
(query-template-map graph-uri rdf-store))
]
(value-trace
::QueryForNormalForm
[:query query
:graph-uri graph-uri
:query-fn query-fn]
(reduce collect-binding
{}
(query-fn rdf-store query)))))))
(defn check-ns-metadata
"Logs a warning when `kwi` is in a namespace with no metadata."
[kwi]
(let [n (symbol (namespace kwi))]
(when-let [the-ns (find-ns n)]
(when (not (meta the-ns))
(warn ::NoMetaDataInNS
:glog/message "The namespace for {{kwi}} is in a namespace with no associated metadata."
:kwi kwi))))
kwi)
(defn check-qname
"Traps the keyword assertion error in voc and throws a more meaningful error
about blank nodes not being supported as first-class identifiers."
[uri-spec]
(if (bnode-kwi? uri-spec)
(name uri-spec)
(try
(voc/qname-for (check-ns-metadata uri-spec))
(catch Throwable e
(throw (ex-info (str "The URI spec " uri-spec " is invalid.\nCould it be a blank node?")
(merge (ex-data e)
{:type ::Invalid-URI-spec
::uri-spec uri-spec
})))))))
(def query-for-p-o-template "A 'stache template for a query ref'd in `query-for-p-o`, informed by `query-template-map`"
"
Select ?p ?o
{{{from-clauses}}}
Where
{
{{{subject}}} ?_p ?_o.
Bind ({{{rebind-_p}}} as ?p)
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-p-o
"Returns {`p` #{`o`...}...} for `s` from query to `rdf-store`
Where
- `p` is a predicate URI rendered per binding translator of `rdf-store`
- `o` is an object value, rendered per the binding translator of `rdf-store`
- `s` is a subject uri keyword. ~ voc/voc-re
- `rdf-store` is and RDF store.
- `query-fn` := fn [repo] -> bindings
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(or nil if DEFAULT graph)
"
([query-fn rdf-store s]
(query-for-p-o nil query-fn rdf-store s)
)
([graph-uri query-fn rdf-store s]
{:pre [(not (nil? s))
]
}
(debug ::Starting_query-for-p-o
::graph-uri graph-uri
::query-fn query-fn
::rdf-store rdf-store
::s s)
(let [query (prefixed
(stache/render query-for-p-o-template
(merge (query-template-map graph-uri rdf-store)
{:subject (check-qname s)})))
collect-bindings (fn [acc b]
(update acc (:p b)
(fn[os] (set (conj os (:o b))))))
]
(value-debug
::query-for-po
[::query query ::subject s]
(reduce collect-bindings {}
(query-fn rdf-store query))))))
(def query-for-o-template "A 'stache template for a query ref'd in `query-for-o`, informed by `query-template-map`"
"
Select ?o
{{{from-clauses}}}
Where
{
{{{subject}}} {{{predicate}}} ?_o.
Bind ({{{rebind-_o}}} as ?o)
}
")
(defn query-for-o
"Returns #{`o`...} for `s` and `p` at endpoint of `rdf-store`
Where:
- `o` is an object rendered per binding translator of `rdf-store`
- `s` is a subject URI rendered per binding translator of `rdf-store`
- `p` is a predicate URI rendered per binding translator of `rdf-store`
- `rdf-store` is an RDF store
- `query-fn` := fn [repo] -> bindings
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(or nil if DEFAULT graph)
"
([query-fn rdf-store s p]
(query-for-o nil query-fn rdf-store s p))
([graph-uri query-fn rdf-store s p]
(let [query (prefixed
(stache/render
query-for-o-template
(merge (query-template-map graph-uri rdf-store)
{:subject (check-qname s)
:predicate (check-qname p)})))
collect-bindings (fn [acc b]
(conj acc (:o b)))
]
(value-debug
::query-for-o-return
[::query query
::subject s
::predicate p]
(reduce collect-bindings #{}
(query-fn rdf-store query))))))
(def ask-s-p-o-template "A 'stache template for a query ref'd in `ask-s-p-o`, informed by `query-template-map`"
"ASK
{{{from-clauses}}}
where
{
{{{subject}}} {{{predicate}}} {{{object}}}.
}"
)
(defn ask-s-p-o
"Returns true if `s` `p` `o` is a triple at endpoint of `rdf-store`
Where:
- `s` `p` `o` are subject, predicate and object
- `rdf-store` is an RDF store
- `graph-uri` is a URI or KWI naming the graph, or a set of them
(or nil if DEFAULT graph)
- `ask-fn` := fn [repo] -> bindings
"
([ask-fn rdf-store s p o]
(ask-s-p-o nil ask-fn rdf-store s p o)
)
([graph-uri ask-fn rdf-store s p o]
(let [query (prefixed
(stache/render
ask-s-p-o-template
(merge (query-template-map graph-uri rdf-store)
{:subject (check-qname s)
:predicate (check-qname p)
:object (if (keyword? o)
(voc/qname-for o)
(render-literal o))})))
starting (debug ::Starting_ask-s-p-o
:query query
:subject s
:predicate p
:object o)
]
(value-debug
::ask-s-p-o-return
[:resultOf starting]
(ask-fn rdf-store query)))))
^:deprecated
[ls]
(str (quote-str (.s ls)) "@" (.lang ls)))
|
1876dc16904739c154998dc8e3ea57851507341cf64980ce23b6b057ad783cae | ushitora-anqou/alqo | game.erl | -module(game).
-include("game.hrl").
-export([
new_board/1,
can_stay/1,
num_players/1,
attacker_card/1,
current_turn/1,
next_turn/1,
has_player_lost/2,
check_finished/1,
hand/2,
deck_top/1,
choose_attacker_card/1,
choose_attacker_card/2,
attack/4,
stay/1,
board_to_map/2,
board_to_map/1
% attacker_card_from_others/1,
% hand_from_others/2,
% get_deck_top_from_others/1,
]).
-spec new_board(2..4) -> board().
new_board(NumPlayers) ->
Cards = [
#card{num = N, hidden = true, uuid = gen_uuid()}
|| N <- shuffle_list(lists:seq(0, 23))
],
{HandList, Deck} =
case NumPlayers of
2 ->
[C1, C2, C3, C4, C5, C6, C7, C8 | D] = Cards,
{[[C1, C2, C3, C4], [C5, C6, C7, C8]], D};
3 ->
[C1, C2, C3, C4, C5, C6, C7, C8, C9 | D] = Cards,
{[[C1, C2, C3], [C4, C5, C6], [C7, C8, C9]], D};
4 ->
[C1, C2, C3, C4, C5, C6, C7, C8 | D] = Cards,
{[[C1, C2], [C3, C4], [C5, C6], [C7, C8]], D}
end,
SortedHandList = [sorted_cards(L) || L <- HandList],
Hands = nested_list_to_array(SortedHandList),
#board{hands = Hands, deck = Deck, turn = 1, can_stay = false, attacker_card = undefined}.
-spec can_stay(board()) -> boolean().
can_stay(Board) -> Board#board.can_stay.
-spec num_players(board()) -> pos_integer().
num_players(Board) -> array:size(Board#board.hands).
-spec attacker_card(board()) -> 'undefined' | {'deck', card()} | {'hand', hand_index()}.
attacker_card(Board) -> Board#board.attacker_card.
-spec current_turn(board()) -> player_index().
current_turn(Board) -> Board#board.turn.
-spec next_turn(board()) -> player_index().
next_turn(Board) ->
case check_finished(Board) of
{finished, _} ->
throw(game_already_finished);
not_finished ->
NumPlayers = num_players(Board),
Can1 = Board#board.turn rem num_players(Board) + 1,
Can2 = Can1 rem NumPlayers + 1,
Can3 = Can2 rem NumPlayers + 1,
case
{has_player_lost(Board, Can1), has_player_lost(Board, Can2),
has_player_lost(Board, Can3)}
of
{false, _, _} -> Can1;
{true, false, _} -> Can2;
{true, true, false} -> Can3
end
end.
-spec has_player_lost(board(), player_index()) -> boolean().
has_player_lost(Board, PlayerIndex) ->
% i.e., all cards of hand are revealed?
lists:all(fun(C) -> not C#card.hidden end, hand(Board, PlayerIndex)).
-spec check_finished(board()) -> not_finished | {finished, player_index()}.
check_finished(Board) ->
L = [has_player_lost(Board, PI) || PI <- lists:seq(1, num_players(Board))],
case count_true(L) >= num_players(Board) - 1 of
false -> not_finished;
true -> {finished, util:find_first_index(fun(B) -> not B end, L)}
end.
-spec hand(board(), player_index()) -> [card()].
hand(Board, PlayerIndex) ->
array:to_list(get_hand(Board, PlayerIndex)).
-spec deck_top(board()) -> 'undefined' | card().
deck_top(#board{deck = []}) -> undefined;
deck_top(#board{deck = [C | _]}) -> C.
-spec choose_attacker_card(board(), 'undefined' | hand_index()) -> board().
choose_attacker_card(Board = #board{deck = [C | NewDeck]}, _) ->
% Deck is not empty.
Board#board{deck = NewDeck, attacker_card = {deck, C}};
choose_attacker_card(Board = #board{deck = []}, HandIndex) ->
Deck is empty ! Use HandIndex .
% The chosen card should be hidden.
C = get_hand(Board, current_turn(Board), HandIndex),
case C#card.hidden of
false -> throw(invalid_card_state);
true -> Board#board{attacker_card = {hand, HandIndex}}
end.
-spec choose_attacker_card(board()) -> board().
choose_attacker_card(Board) ->
choose_attacker_card(Board, undefined).
-spec attack(board(), player_index(), hand_index(), card_number()) ->
{'failure', board()} | {'success', board()}.
attack(Board, TargetPlayer, TargetIndex, Guess) ->
case check_attack(Board, TargetPlayer, TargetIndex, Guess) of
failure ->
NewBoard = reset_attacker_card(Board, false),
{failure, NewBoard#board{
turn = next_turn(Board),
can_stay = false
}};
success ->
NewBoard = reveal_hand(Board, TargetPlayer, TargetIndex),
{success, NewBoard#board{
can_stay = true
}}
end.
-spec stay(board()) -> board().
stay(Board = #board{can_stay = true}) ->
NewBoard = reset_attacker_card(Board, true),
NewBoard#board{
turn = next_turn(Board),
can_stay = false
};
stay(#board{can_stay = false}) ->
throw(cannot_stay).
-spec board_to_map(board(), 'undefined' | player_index()) -> #{any() => any()}.
board_to_map(Board, PlayerIndex) ->
Card2List = fun
(#card{num = N, hidden = true, uuid = UUID}) -> [N rem 2, true, UUID];
(#card{num = N, hidden = false, uuid = UUID}) -> [N, false, UUID];
(undefined) -> null
end,
Map = #{
can_stay => can_stay(Board),
current_turn => current_turn(Board),
next_turn =>
case check_finished(Board) of
not_finished -> next_turn(Board);
_ -> null
end,
num_players => num_players(Board),
winner =>
case check_finished(Board) of
not_finished -> null;
{finished, Winner} -> Winner
end,
hands => [[Card2List(C) || C <- hand(Board, PI)] || PI <- lists:seq(1, num_players(Board))],
deck_top => Card2List(deck_top(Board)),
attacker_card =>
case attacker_card(Board) of
undefined -> null;
{deck, C} -> [1, Card2List(C)];
{hand, HI} -> [2, HI]
end
},
case PlayerIndex of
undefined ->
Map;
PI ->
Map#{
your_player_index => PI,
your_hand => [C#card.num || C <- hand(Board, PI)],
your_attacker_card_from_deck =>
case {current_turn(Board), attacker_card(Board)} of
{PI, {deck, #card{num = N1}}} -> N1;
_ -> null
end
}
end.
board_to_map(Board) ->
board_to_map(Board, undefined).
%%%%%%%%%%%%%%%%%%%%%%
%%% Private functions
%%%%%%%%%%%%%%%%%%%%%%
shuffle_list(L) when is_list(L) ->
% Thanks to:
[X || {_, X} <- lists:sort([{rand:uniform(), N} || N <- L])].
nested_list_to_array(L) when is_list(L) -> array:from_list([nested_list_to_array(E) || E <- L]);
nested_list_to_array(E) -> E.
gen_uuid() ->
list_to_binary(uuid:uuid_to_string(uuid:get_v4(), nodash)).
count_true([], Sum) -> Sum;
count_true([H | T], Sum) when H =:= true -> count_true(T, Sum + 1);
count_true([H | T], Sum) when H =:= false -> count_true(T, Sum).
count_true(L) -> count_true(L, 0).
-spec get_hand(board(), player_index()) -> array:array(card()).
get_hand(Board = #board{hands = Hands}, PlayerIndex) ->
case 1 =< PlayerIndex andalso PlayerIndex =< num_players(Board) of
false ->
throw(invalid_player_index);
true ->
array:get(PlayerIndex - 1, Hands)
end.
-spec get_hand(board(), player_index(), hand_index()) -> card().
get_hand(Board = #board{}, PlayerIndex, HandIndex) ->
Hand = get_hand(Board, PlayerIndex),
case 1 =< HandIndex andalso HandIndex =< array:size(Hand) of
false -> throw(invalid_hand_index);
true -> array:get(HandIndex - 1, Hand)
end.
-spec set_hand(board(), player_index(), array:array(card())) -> board().
set_hand(Board = #board{hands = OldHands}, PlayerIndex, NewHand) ->
NewHands = array:set(PlayerIndex - 1, NewHand, OldHands),
Board#board{hands = NewHands}.
-spec set_hand(board(), player_index(), hand_index(), card()) -> board().
set_hand(Board, PlayerIndex, HandIndex, NewCard) ->
OldHand = get_hand(Board, PlayerIndex),
NewHand = array:set(HandIndex - 1, NewCard, OldHand),
set_hand(Board, PlayerIndex, NewHand).
-spec reveal_hand(board(), player_index(), hand_index()) -> board().
reveal_hand(Board, PlayerIndex, HandIndex) ->
OldCard = get_hand(Board, PlayerIndex, HandIndex),
case OldCard of
#card{hidden = false} ->
throw(invalid_card_state);
_ ->
NewCard = OldCard#card{hidden = false},
set_hand(Board, PlayerIndex, HandIndex, NewCard)
end.
-spec check_attack(board(), player_index(), hand_index(), card_number()) -> 'success' | 'failure'.
check_attack(#board{attacker_card = undefined}, _, _, _) ->
throw(attacker_card_not_set);
check_attack(Board, TargetPlayer, _, _) when TargetPlayer =:= Board#board.turn ->
throw(invalid_player_index);
check_attack(Board, TargetPlayer, TargetIndex, Guess) ->
case get_hand(Board, TargetPlayer, TargetIndex) of
#card{hidden = false} -> throw(invalid_card_state);
#card{hidden = true, num = Guess} -> success;
_ -> failure
end.
-spec sorted_cards([card()]) -> [card()].
sorted_cards(L) ->
lists:sort(fun(#card{num = A}, #card{num = B}) -> A =< B end, L).
-spec reset_attacker_card(board(), boolean()) -> board().
reset_attacker_card(Board, Hidden) ->
Turn = current_turn(Board),
NewBoard =
case Board#board.attacker_card of
{deck, C} ->
OldHand = array:to_list(get_hand(Board, Turn)),
NewHand = sorted_cards([C#card{hidden = Hidden} | OldHand]),
set_hand(Board, Turn, array:from_list(NewHand));
{hand, HI} when Hidden =:= false ->
reveal_hand(Board, Turn, HI);
{hand, _} ->
Board
end,
NewBoard#board{
attacker_card = undefined
}.
| null | https://raw.githubusercontent.com/ushitora-anqou/alqo/9900172d765100dec40c00a7aec3c2dc971956f1/src/game.erl | erlang | attacker_card_from_others/1,
hand_from_others/2,
get_deck_top_from_others/1,
i.e., all cards of hand are revealed?
Deck is not empty.
The chosen card should be hidden.
Private functions
Thanks to: | -module(game).
-include("game.hrl").
-export([
new_board/1,
can_stay/1,
num_players/1,
attacker_card/1,
current_turn/1,
next_turn/1,
has_player_lost/2,
check_finished/1,
hand/2,
deck_top/1,
choose_attacker_card/1,
choose_attacker_card/2,
attack/4,
stay/1,
board_to_map/2,
board_to_map/1
]).
-spec new_board(2..4) -> board().
new_board(NumPlayers) ->
Cards = [
#card{num = N, hidden = true, uuid = gen_uuid()}
|| N <- shuffle_list(lists:seq(0, 23))
],
{HandList, Deck} =
case NumPlayers of
2 ->
[C1, C2, C3, C4, C5, C6, C7, C8 | D] = Cards,
{[[C1, C2, C3, C4], [C5, C6, C7, C8]], D};
3 ->
[C1, C2, C3, C4, C5, C6, C7, C8, C9 | D] = Cards,
{[[C1, C2, C3], [C4, C5, C6], [C7, C8, C9]], D};
4 ->
[C1, C2, C3, C4, C5, C6, C7, C8 | D] = Cards,
{[[C1, C2], [C3, C4], [C5, C6], [C7, C8]], D}
end,
SortedHandList = [sorted_cards(L) || L <- HandList],
Hands = nested_list_to_array(SortedHandList),
#board{hands = Hands, deck = Deck, turn = 1, can_stay = false, attacker_card = undefined}.
-spec can_stay(board()) -> boolean().
can_stay(Board) -> Board#board.can_stay.
-spec num_players(board()) -> pos_integer().
num_players(Board) -> array:size(Board#board.hands).
-spec attacker_card(board()) -> 'undefined' | {'deck', card()} | {'hand', hand_index()}.
attacker_card(Board) -> Board#board.attacker_card.
-spec current_turn(board()) -> player_index().
current_turn(Board) -> Board#board.turn.
-spec next_turn(board()) -> player_index().
next_turn(Board) ->
case check_finished(Board) of
{finished, _} ->
throw(game_already_finished);
not_finished ->
NumPlayers = num_players(Board),
Can1 = Board#board.turn rem num_players(Board) + 1,
Can2 = Can1 rem NumPlayers + 1,
Can3 = Can2 rem NumPlayers + 1,
case
{has_player_lost(Board, Can1), has_player_lost(Board, Can2),
has_player_lost(Board, Can3)}
of
{false, _, _} -> Can1;
{true, false, _} -> Can2;
{true, true, false} -> Can3
end
end.
-spec has_player_lost(board(), player_index()) -> boolean().
has_player_lost(Board, PlayerIndex) ->
lists:all(fun(C) -> not C#card.hidden end, hand(Board, PlayerIndex)).
-spec check_finished(board()) -> not_finished | {finished, player_index()}.
check_finished(Board) ->
L = [has_player_lost(Board, PI) || PI <- lists:seq(1, num_players(Board))],
case count_true(L) >= num_players(Board) - 1 of
false -> not_finished;
true -> {finished, util:find_first_index(fun(B) -> not B end, L)}
end.
-spec hand(board(), player_index()) -> [card()].
hand(Board, PlayerIndex) ->
array:to_list(get_hand(Board, PlayerIndex)).
-spec deck_top(board()) -> 'undefined' | card().
deck_top(#board{deck = []}) -> undefined;
deck_top(#board{deck = [C | _]}) -> C.
-spec choose_attacker_card(board(), 'undefined' | hand_index()) -> board().
choose_attacker_card(Board = #board{deck = [C | NewDeck]}, _) ->
Board#board{deck = NewDeck, attacker_card = {deck, C}};
choose_attacker_card(Board = #board{deck = []}, HandIndex) ->
Deck is empty ! Use HandIndex .
C = get_hand(Board, current_turn(Board), HandIndex),
case C#card.hidden of
false -> throw(invalid_card_state);
true -> Board#board{attacker_card = {hand, HandIndex}}
end.
-spec choose_attacker_card(board()) -> board().
choose_attacker_card(Board) ->
choose_attacker_card(Board, undefined).
-spec attack(board(), player_index(), hand_index(), card_number()) ->
{'failure', board()} | {'success', board()}.
attack(Board, TargetPlayer, TargetIndex, Guess) ->
case check_attack(Board, TargetPlayer, TargetIndex, Guess) of
failure ->
NewBoard = reset_attacker_card(Board, false),
{failure, NewBoard#board{
turn = next_turn(Board),
can_stay = false
}};
success ->
NewBoard = reveal_hand(Board, TargetPlayer, TargetIndex),
{success, NewBoard#board{
can_stay = true
}}
end.
-spec stay(board()) -> board().
stay(Board = #board{can_stay = true}) ->
NewBoard = reset_attacker_card(Board, true),
NewBoard#board{
turn = next_turn(Board),
can_stay = false
};
stay(#board{can_stay = false}) ->
throw(cannot_stay).
-spec board_to_map(board(), 'undefined' | player_index()) -> #{any() => any()}.
board_to_map(Board, PlayerIndex) ->
Card2List = fun
(#card{num = N, hidden = true, uuid = UUID}) -> [N rem 2, true, UUID];
(#card{num = N, hidden = false, uuid = UUID}) -> [N, false, UUID];
(undefined) -> null
end,
Map = #{
can_stay => can_stay(Board),
current_turn => current_turn(Board),
next_turn =>
case check_finished(Board) of
not_finished -> next_turn(Board);
_ -> null
end,
num_players => num_players(Board),
winner =>
case check_finished(Board) of
not_finished -> null;
{finished, Winner} -> Winner
end,
hands => [[Card2List(C) || C <- hand(Board, PI)] || PI <- lists:seq(1, num_players(Board))],
deck_top => Card2List(deck_top(Board)),
attacker_card =>
case attacker_card(Board) of
undefined -> null;
{deck, C} -> [1, Card2List(C)];
{hand, HI} -> [2, HI]
end
},
case PlayerIndex of
undefined ->
Map;
PI ->
Map#{
your_player_index => PI,
your_hand => [C#card.num || C <- hand(Board, PI)],
your_attacker_card_from_deck =>
case {current_turn(Board), attacker_card(Board)} of
{PI, {deck, #card{num = N1}}} -> N1;
_ -> null
end
}
end.
board_to_map(Board) ->
board_to_map(Board, undefined).
shuffle_list(L) when is_list(L) ->
[X || {_, X} <- lists:sort([{rand:uniform(), N} || N <- L])].
nested_list_to_array(L) when is_list(L) -> array:from_list([nested_list_to_array(E) || E <- L]);
nested_list_to_array(E) -> E.
gen_uuid() ->
list_to_binary(uuid:uuid_to_string(uuid:get_v4(), nodash)).
count_true([], Sum) -> Sum;
count_true([H | T], Sum) when H =:= true -> count_true(T, Sum + 1);
count_true([H | T], Sum) when H =:= false -> count_true(T, Sum).
count_true(L) -> count_true(L, 0).
-spec get_hand(board(), player_index()) -> array:array(card()).
get_hand(Board = #board{hands = Hands}, PlayerIndex) ->
case 1 =< PlayerIndex andalso PlayerIndex =< num_players(Board) of
false ->
throw(invalid_player_index);
true ->
array:get(PlayerIndex - 1, Hands)
end.
-spec get_hand(board(), player_index(), hand_index()) -> card().
get_hand(Board = #board{}, PlayerIndex, HandIndex) ->
Hand = get_hand(Board, PlayerIndex),
case 1 =< HandIndex andalso HandIndex =< array:size(Hand) of
false -> throw(invalid_hand_index);
true -> array:get(HandIndex - 1, Hand)
end.
-spec set_hand(board(), player_index(), array:array(card())) -> board().
set_hand(Board = #board{hands = OldHands}, PlayerIndex, NewHand) ->
NewHands = array:set(PlayerIndex - 1, NewHand, OldHands),
Board#board{hands = NewHands}.
-spec set_hand(board(), player_index(), hand_index(), card()) -> board().
set_hand(Board, PlayerIndex, HandIndex, NewCard) ->
OldHand = get_hand(Board, PlayerIndex),
NewHand = array:set(HandIndex - 1, NewCard, OldHand),
set_hand(Board, PlayerIndex, NewHand).
-spec reveal_hand(board(), player_index(), hand_index()) -> board().
reveal_hand(Board, PlayerIndex, HandIndex) ->
OldCard = get_hand(Board, PlayerIndex, HandIndex),
case OldCard of
#card{hidden = false} ->
throw(invalid_card_state);
_ ->
NewCard = OldCard#card{hidden = false},
set_hand(Board, PlayerIndex, HandIndex, NewCard)
end.
-spec check_attack(board(), player_index(), hand_index(), card_number()) -> 'success' | 'failure'.
check_attack(#board{attacker_card = undefined}, _, _, _) ->
throw(attacker_card_not_set);
check_attack(Board, TargetPlayer, _, _) when TargetPlayer =:= Board#board.turn ->
throw(invalid_player_index);
check_attack(Board, TargetPlayer, TargetIndex, Guess) ->
case get_hand(Board, TargetPlayer, TargetIndex) of
#card{hidden = false} -> throw(invalid_card_state);
#card{hidden = true, num = Guess} -> success;
_ -> failure
end.
-spec sorted_cards([card()]) -> [card()].
sorted_cards(L) ->
lists:sort(fun(#card{num = A}, #card{num = B}) -> A =< B end, L).
-spec reset_attacker_card(board(), boolean()) -> board().
reset_attacker_card(Board, Hidden) ->
Turn = current_turn(Board),
NewBoard =
case Board#board.attacker_card of
{deck, C} ->
OldHand = array:to_list(get_hand(Board, Turn)),
NewHand = sorted_cards([C#card{hidden = Hidden} | OldHand]),
set_hand(Board, Turn, array:from_list(NewHand));
{hand, HI} when Hidden =:= false ->
reveal_hand(Board, Turn, HI);
{hand, _} ->
Board
end,
NewBoard#board{
attacker_card = undefined
}.
|
957305df7fcb72961cfa9e1046e7f547f803c5657f738791d94bcc74e5498c98 | processone/ejabberd | mod_vcard_mnesia_opt.erl | %% Generated automatically
%% DO NOT EDIT: run `make options` instead
-module(mod_vcard_mnesia_opt).
-export([search_all_hosts/1]).
-spec search_all_hosts(gen_mod:opts() | global | binary()) -> boolean().
search_all_hosts(Opts) when is_map(Opts) ->
gen_mod:get_opt(search_all_hosts, Opts);
search_all_hosts(Host) ->
gen_mod:get_module_opt(Host, mod_vcard, search_all_hosts).
| null | https://raw.githubusercontent.com/processone/ejabberd/b860a25c82515ba51b044e13ea4e040e3b9bbc41/src/mod_vcard_mnesia_opt.erl | erlang | Generated automatically
DO NOT EDIT: run `make options` instead |
-module(mod_vcard_mnesia_opt).
-export([search_all_hosts/1]).
-spec search_all_hosts(gen_mod:opts() | global | binary()) -> boolean().
search_all_hosts(Opts) when is_map(Opts) ->
gen_mod:get_opt(search_all_hosts, Opts);
search_all_hosts(Host) ->
gen_mod:get_module_opt(Host, mod_vcard, search_all_hosts).
|
fecd3c4d72f55378eb34ce51d533e34c2a0833b2570adda6e694f9badf7f781d | basho/riak-erlang-http-client | rhc_dt.erl | %% -------------------------------------------------------------------
%%
%% riakhttpc: Riak HTTP Client
%%
Copyright ( c ) 2013 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%% @doc Utility functions for datatypes.
-module(rhc_dt).
-export([
datatype_from_json/1,
encode_update_request/3,
decode_error/2
]).
-define(FIELD_PATTERN, "^(.*)_(counter|set|hll|register|flag|map)$").
datatype_from_json({struct, Props}) ->
Value = proplists:get_value(<<"value">>, Props),
Type = binary_to_existing_atom(proplists:get_value(<<"type">>, Props), utf8),
Context = proplists:get_value(<<"context">>, Props, undefined),
Mod = riakc_datatype:module_for_type(Type),
Mod:new(decode_value(Type, Value), Context).
decode_value(counter, Value) -> Value;
decode_value(set, Value) -> Value;
decode_value(gset, Value) -> Value;
decode_value(hll, Value) -> Value;
decode_value(flag, Value) -> Value;
decode_value(register, Value) -> Value;
decode_value(map, {struct, Fields}) ->
[ begin
{Name, Type} = field_from_json(Field),
{{Name,Type}, decode_value(Type, Value)}
end || {Field, Value} <- Fields ].
field_from_json(Bin) when is_binary(Bin) ->
{match, [Name, BinType]} = re:run(Bin, ?FIELD_PATTERN, [anchored, {capture, all_but_first, binary}]),
{Name, binary_to_existing_atom(BinType, utf8)}.
field_to_json({Name, Type}) when is_binary(Name), is_atom(Type) ->
BinType = atom_to_binary(Type, utf8),
<<Name/bytes, $_, BinType/bytes>>.
decode_error(fetch, {ok, "404", Headers, Body}) ->
case proplists:get_value("Content-Type", Headers) of
"application/json" ->
%% We need to extract the type when not found
{struct, Props} = mochijson2:decode(Body),
Type = binary_to_existing_atom(proplists:get_value(<<"type">>, Props), utf8),
{notfound, Type};
"text/" ++ _ ->
Body
end;
decode_error(_, {ok, "400", _, Body}) ->
{bad_request, Body};
decode_error(_, {ok, "301", _, Body}) ->
{legacy_counter, Body};
decode_error(_, {ok, "403", _, Body}) ->
{forbidden, Body};
decode_error(_, {ok, _, _, Body}) ->
Body.
encode_update_request(register, {assign, Bin}, _Context) ->
{struct, [{<<"assign">>, Bin}]};
encode_update_request(flag, Atom, _Context) ->
atom_to_binary(Atom, utf8);
encode_update_request(counter, Op, _Context) ->
{struct, [Op]};
encode_update_request(set, {update, Ops}, Context) ->
{struct, Ops ++ include_context(Context)};
encode_update_request(set, Op, Context) ->
{struct, [Op|include_context(Context)]};
encode_update_request(hll, {update, Ops}, Context) ->
{struct, Ops ++ include_context(Context)};
encode_update_request(hll, Op, Context) ->
{struct, [Op|include_context(Context)]};
encode_update_request(map, {update, Ops}, Context) ->
{struct, orddict:to_list(lists:foldl(fun encode_map_op/2, orddict:new(), Ops)) ++
include_context(Context)};
encode_update_request(gset, {update, Ops}, Context) ->
{struct, Ops ++ include_context(Context)};
encode_update_request(gset, Op, Context) ->
{struct, [Op|include_context(Context)]}.
encode_map_op({add, Entry}, Ops) ->
orddict:append(add, field_to_json(Entry), Ops);
encode_map_op({remove, Entry}, Ops) ->
orddict:append(remove, field_to_json(Entry), Ops);
encode_map_op({update, {_Key,Type}=Field, Op}, Ops) ->
EncOp = encode_update_request(Type, Op, undefined),
Update = {field_to_json(Field), EncOp},
case orddict:find(update, Ops) of
{ok, {struct, Updates}} ->
orddict:store(update, {struct, [Update|Updates]}, Ops);
error ->
orddict:store(update, {struct, [Update]}, Ops)
end.
include_context(undefined) -> [];
include_context(<<>>) -> [];
include_context(Bin) -> [{<<"context">>, Bin}].
| null | https://raw.githubusercontent.com/basho/riak-erlang-http-client/2d4e58371e4d982bee1e0ad804b1403b1333573c/src/rhc_dt.erl | erlang | -------------------------------------------------------------------
riakhttpc: Riak HTTP Client
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc Utility functions for datatypes.
We need to extract the type when not found | Copyright ( c ) 2013 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(rhc_dt).
-export([
datatype_from_json/1,
encode_update_request/3,
decode_error/2
]).
-define(FIELD_PATTERN, "^(.*)_(counter|set|hll|register|flag|map)$").
datatype_from_json({struct, Props}) ->
Value = proplists:get_value(<<"value">>, Props),
Type = binary_to_existing_atom(proplists:get_value(<<"type">>, Props), utf8),
Context = proplists:get_value(<<"context">>, Props, undefined),
Mod = riakc_datatype:module_for_type(Type),
Mod:new(decode_value(Type, Value), Context).
decode_value(counter, Value) -> Value;
decode_value(set, Value) -> Value;
decode_value(gset, Value) -> Value;
decode_value(hll, Value) -> Value;
decode_value(flag, Value) -> Value;
decode_value(register, Value) -> Value;
decode_value(map, {struct, Fields}) ->
[ begin
{Name, Type} = field_from_json(Field),
{{Name,Type}, decode_value(Type, Value)}
end || {Field, Value} <- Fields ].
field_from_json(Bin) when is_binary(Bin) ->
{match, [Name, BinType]} = re:run(Bin, ?FIELD_PATTERN, [anchored, {capture, all_but_first, binary}]),
{Name, binary_to_existing_atom(BinType, utf8)}.
field_to_json({Name, Type}) when is_binary(Name), is_atom(Type) ->
BinType = atom_to_binary(Type, utf8),
<<Name/bytes, $_, BinType/bytes>>.
decode_error(fetch, {ok, "404", Headers, Body}) ->
case proplists:get_value("Content-Type", Headers) of
"application/json" ->
{struct, Props} = mochijson2:decode(Body),
Type = binary_to_existing_atom(proplists:get_value(<<"type">>, Props), utf8),
{notfound, Type};
"text/" ++ _ ->
Body
end;
decode_error(_, {ok, "400", _, Body}) ->
{bad_request, Body};
decode_error(_, {ok, "301", _, Body}) ->
{legacy_counter, Body};
decode_error(_, {ok, "403", _, Body}) ->
{forbidden, Body};
decode_error(_, {ok, _, _, Body}) ->
Body.
encode_update_request(register, {assign, Bin}, _Context) ->
{struct, [{<<"assign">>, Bin}]};
encode_update_request(flag, Atom, _Context) ->
atom_to_binary(Atom, utf8);
encode_update_request(counter, Op, _Context) ->
{struct, [Op]};
encode_update_request(set, {update, Ops}, Context) ->
{struct, Ops ++ include_context(Context)};
encode_update_request(set, Op, Context) ->
{struct, [Op|include_context(Context)]};
encode_update_request(hll, {update, Ops}, Context) ->
{struct, Ops ++ include_context(Context)};
encode_update_request(hll, Op, Context) ->
{struct, [Op|include_context(Context)]};
encode_update_request(map, {update, Ops}, Context) ->
{struct, orddict:to_list(lists:foldl(fun encode_map_op/2, orddict:new(), Ops)) ++
include_context(Context)};
encode_update_request(gset, {update, Ops}, Context) ->
{struct, Ops ++ include_context(Context)};
encode_update_request(gset, Op, Context) ->
{struct, [Op|include_context(Context)]}.
encode_map_op({add, Entry}, Ops) ->
orddict:append(add, field_to_json(Entry), Ops);
encode_map_op({remove, Entry}, Ops) ->
orddict:append(remove, field_to_json(Entry), Ops);
encode_map_op({update, {_Key,Type}=Field, Op}, Ops) ->
EncOp = encode_update_request(Type, Op, undefined),
Update = {field_to_json(Field), EncOp},
case orddict:find(update, Ops) of
{ok, {struct, Updates}} ->
orddict:store(update, {struct, [Update|Updates]}, Ops);
error ->
orddict:store(update, {struct, [Update]}, Ops)
end.
include_context(undefined) -> [];
include_context(<<>>) -> [];
include_context(Bin) -> [{<<"context">>, Bin}].
|
d4a1cf1cd84f892ba747511dbf2e189ba6520bbd88a63df01cb677a800d73ebe | geophf/1HaskellADay | Exercise.hs | module Y2018.M06.D20.Exercise where
-
Okay , we 're going to do cosine similarity , but to do cosine similarity , we need
vector - sets to do the comparisons . Now , it 'd be great to have WordNet , but my
$ cabal install wordnet
fails with
Ambiguous type variable ‘ t0 ’ arising from an operator section
prevents the constraint ‘ ( Foldable t0 ) ’ from being solved .
So , no WordNet for me ! Any help , haskellers ?
But , in the meantime , we can construct a SymbolTable from all the words in all
the documents and then , for each document , vectorize from that SymbolTable .
The SymbolTable is devoid of meaning , sure , but it does give us document
vectors .
-
Okay, we're going to do cosine similarity, but to do cosine similarity, we need
vector-sets to do the comparisons. Now, it'd be great to have WordNet, but my
$ cabal install wordnet
fails with
Ambiguous type variable ‘t0’ arising from an operator section
prevents the constraint ‘(Foldable t0)’ from being solved.
So, no WordNet for me! Any help, haskellers?
But, in the meantime, we can construct a SymbolTable from all the words in all
the documents and then, for each document, vectorize from that SymbolTable.
The SymbolTable is devoid of meaning, sure, but it does give us document
vectors.
--}
import Data.Array
below imports available via 1HaskellADay git repository
import Data.SymbolTable
import Y2018.M06.D19.Exercise
from the set of articles from yesterday , construct a symbol table of the
-- words of the text of the articles
{--
>>> arts <- readNonDuplicatedArticles (exDir ++ artJSON)
--}
syms :: [Article] -> SymbolTable
syms arts = undefined
Now that we have all our words in a SymbolTable , arrayed from 0 .. n ,
-- we can convert the documents into arrays of length n and populate those
-- arrays
type WordVect = Array Int Int
art2vect :: SymbolTable -> Article -> WordVect
art2vect syms article = undefined
-- How many arrays do you have? What is the length of the arrays, n?
Also , there may be other approaches than my SymbolTable construction .
-- Thoughts?
{-- BONUS -----------------------------------------------------------------
Compute the cosine similarity for the article set ... eheh, jk: we'll develop
this in future exercises.
--}
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2018/M06/D20/Exercise.hs | haskell | }
words of the text of the articles
-
>>> arts <- readNonDuplicatedArticles (exDir ++ artJSON)
-
we can convert the documents into arrays of length n and populate those
arrays
How many arrays do you have? What is the length of the arrays, n?
Thoughts?
- BONUS -----------------------------------------------------------------
Compute the cosine similarity for the article set ... eheh, jk: we'll develop
this in future exercises.
- | module Y2018.M06.D20.Exercise where
-
Okay , we 're going to do cosine similarity , but to do cosine similarity , we need
vector - sets to do the comparisons . Now , it 'd be great to have WordNet , but my
$ cabal install wordnet
fails with
Ambiguous type variable ‘ t0 ’ arising from an operator section
prevents the constraint ‘ ( Foldable t0 ) ’ from being solved .
So , no WordNet for me ! Any help , haskellers ?
But , in the meantime , we can construct a SymbolTable from all the words in all
the documents and then , for each document , vectorize from that SymbolTable .
The SymbolTable is devoid of meaning , sure , but it does give us document
vectors .
-
Okay, we're going to do cosine similarity, but to do cosine similarity, we need
vector-sets to do the comparisons. Now, it'd be great to have WordNet, but my
$ cabal install wordnet
fails with
Ambiguous type variable ‘t0’ arising from an operator section
prevents the constraint ‘(Foldable t0)’ from being solved.
So, no WordNet for me! Any help, haskellers?
But, in the meantime, we can construct a SymbolTable from all the words in all
the documents and then, for each document, vectorize from that SymbolTable.
The SymbolTable is devoid of meaning, sure, but it does give us document
vectors.
import Data.Array
below imports available via 1HaskellADay git repository
import Data.SymbolTable
import Y2018.M06.D19.Exercise
from the set of articles from yesterday , construct a symbol table of the
syms :: [Article] -> SymbolTable
syms arts = undefined
Now that we have all our words in a SymbolTable , arrayed from 0 .. n ,
type WordVect = Array Int Int
art2vect :: SymbolTable -> Article -> WordVect
art2vect syms article = undefined
Also , there may be other approaches than my SymbolTable construction .
|
b6686d1c65e8ec06ccfc82fb624f5a05ad81ac9c4fff27d5d77e7421bf8aa66e | Bike/hare | unknown.lisp | (in-package #:hare.ast)
;;; This is a pseudo-AST marking a parse failure, e.g. due to whether something
is a macro being unknown . It will be change - class'd into a real AST .
(defclass unknown (ast)
((%expr :initarg :expr :accessor expr)
;; the env is kept around to make reparsing later more convenient.
(%env :initarg :env :accessor environment)))
Mutate an UNKNOWN into being a real AST .
(defgeneric transform-unknown (unknown ast)
(:argument-precedence-order ast unknown))
;;; Note that none of these transfer the type. When this function is used the
;;; UNKNOWN will probably not have one. But even if it did, change-class would
;;; just keep it where it is, since it's a slot the source and destination
;;; classes both have.
(defmethod transform-unknown ((unknown unknown) (ast seq))
(change-class unknown 'seq :asts (asts ast) :value (value ast)))
(defmethod transform-unknown ((unknown unknown) (ast call))
(change-class unknown 'call :callee (callee ast) :args (args ast)))
(defmethod transform-unknown ((unknown unknown) (ast literal))
(change-class unknown 'literal :initializer (initializer ast)))
(defmethod transform-unknown ((unknown unknown) (ast reference))
(change-class unknown 'reference :variable (variable ast)))
(defmethod transform-unknown ((uk unknown) (ast bind))
(change-class uk 'bind :bindings (bindings ast) :body (body ast)))
(defmethod transform-unknown ((uk unknown) (ast with))
(change-class uk 'with :variable (variable ast)
:nelements (nelements ast) :body (body ast)))
(defmethod transform-unknown ((uk unknown) (ast initialize))
(change-class uk 'initialize :value (value ast)
:initializer (initializer ast)))
(defmethod transform-unknown ((uk unknown) (ast primitive))
(change-class uk 'primitive :name (name ast) :args (args ast)))
(defmethod transform-unknown ((uk unknown) (ast case))
(change-class uk 'case :value (value ast) :adt-def (adt-def ast)
:clauses (clauses ast) :case!p (case!p ast)))
(defmethod transform-unknown ((uk unknown) (ast construct))
(change-class uk 'construct :constructor (constructor ast)
:args (args ast)))
| null | https://raw.githubusercontent.com/Bike/hare/c9173f4b0fd82e79b94196714f8b02b96a823f75/ast/unknown.lisp | lisp | This is a pseudo-AST marking a parse failure, e.g. due to whether something
the env is kept around to make reparsing later more convenient.
Note that none of these transfer the type. When this function is used the
UNKNOWN will probably not have one. But even if it did, change-class would
just keep it where it is, since it's a slot the source and destination
classes both have. | (in-package #:hare.ast)
is a macro being unknown . It will be change - class'd into a real AST .
(defclass unknown (ast)
((%expr :initarg :expr :accessor expr)
(%env :initarg :env :accessor environment)))
Mutate an UNKNOWN into being a real AST .
(defgeneric transform-unknown (unknown ast)
(:argument-precedence-order ast unknown))
(defmethod transform-unknown ((unknown unknown) (ast seq))
(change-class unknown 'seq :asts (asts ast) :value (value ast)))
(defmethod transform-unknown ((unknown unknown) (ast call))
(change-class unknown 'call :callee (callee ast) :args (args ast)))
(defmethod transform-unknown ((unknown unknown) (ast literal))
(change-class unknown 'literal :initializer (initializer ast)))
(defmethod transform-unknown ((unknown unknown) (ast reference))
(change-class unknown 'reference :variable (variable ast)))
(defmethod transform-unknown ((uk unknown) (ast bind))
(change-class uk 'bind :bindings (bindings ast) :body (body ast)))
(defmethod transform-unknown ((uk unknown) (ast with))
(change-class uk 'with :variable (variable ast)
:nelements (nelements ast) :body (body ast)))
(defmethod transform-unknown ((uk unknown) (ast initialize))
(change-class uk 'initialize :value (value ast)
:initializer (initializer ast)))
(defmethod transform-unknown ((uk unknown) (ast primitive))
(change-class uk 'primitive :name (name ast) :args (args ast)))
(defmethod transform-unknown ((uk unknown) (ast case))
(change-class uk 'case :value (value ast) :adt-def (adt-def ast)
:clauses (clauses ast) :case!p (case!p ast)))
(defmethod transform-unknown ((uk unknown) (ast construct))
(change-class uk 'construct :constructor (constructor ast)
:args (args ast)))
|
c5c3cb663a58744710005a102998596c6ae5c1aafc368035a5f745dfcc27344a | HealthSamurai/stresty | core.clj | (ns stresty.operations.core
(:require [zen.core :as zen]
[stresty.actions.core :as acts]
[stresty.matchers.core :as match]
[stresty.sci]
[stresty.format.core :as fmt]
[stresty.operations.gen]
[stresty.reports.core]
[clojure.string :as str]))
(defmulti call-op (fn [ztx op args] (:zen/name op)))
(defn op [ztx args]
(if-let [op (when-let [m (:method args)]
(zen/get-symbol ztx (symbol m)))]
(call-op ztx op args)
(do
(println (str "Operation " (:method args) " is not defined."))
{:error {:message (str "Operation " (:method args) " is not defined.")}})))
(defmethod call-op :default
[ztx op args]
(println (str "Op " (:zen/name op) " is not implemented!"))
{:error {:message (str "Op " (:zen/name op) " is not implemented!")}})
(defmethod call-op 'sty/echo
[ztx op {params :params}]
{:result params})
(defmethod call-op 'sty/get-namespaces
[ztx op _]
(let [cases (zen/get-tag ztx 'sty/case)]
{:result {:namespaces (group-by (fn [e] (first (str/split (str e) #"\/"))) cases)}}))
(defmethod call-op 'sty/get-case
[ztx op {params :params}]
(if-let [case (zen/get-symbol ztx (symbol (:case params)))]
{:result case}
{:error {:message "Case not found"}}))
(defn- get-case-state [ztx enm cnm]
(or (get-in @ztx [:state enm cnm]) {}))
(defn- save-case-state [ztx enm cnm key state]
(swap! ztx (fn [old] (update-in old [:state enm cnm] (fn [old] (assoc old key state))))))
(defn- save-step-result [ztx cnm {idx :_index :as step} result]
(swap! ztx update :result #(assoc-in % [cnm idx] result)))
(defn sty-url [& args]
(str "/" (str/join "/" args)))
(defn run-step [ztx {enm :zen/name :as env} {cnm :zen/name :as case} {id :id idx :_index action :do :as step}]
(fmt/emit ztx (assoc step :type 'sty/on-run-step))
(let [state (get-case-state ztx enm cnm)
action (stresty.sci/eval-data {:namespaces {'sty {'env env 'step step 'case case 'state state 'url sty-url}}} action)
ev-base {:type 'sty/on-step-start
:env env
:case case
:step (assoc step :id (or id idx))
:verbose (get-in @ztx [:opts :verbose])
:do action}]
(fmt/emit ztx ev-base)
(try
(let [{result :result error :error} (stresty.actions.core/run-action ztx {:state state :case case :env env} action)]
(fmt/emit ztx (assoc ev-base :type 'sty/on-action-result :result result :error error))
(if error
(do
(save-step-result ztx cnm step {:status :error :error error})
(fmt/emit ztx (assoc ev-base :type 'sty/on-step-error :error error))
(assoc step :status :error :error error))
(do
(when id (save-case-state ztx enm cnm id result))
(if-let [matcher (:match step)]
(let [*matcher (stresty.sci/eval-data {:namespaces {'sty {'env env 'step step 'case case 'state state}}} matcher)
{errors :errors} (stresty.matchers.core/match ztx *matcher result)]
(if (empty? errors)
(do
(save-step-result ztx cnm step {:status :success})
(fmt/emit ztx (assoc ev-base :type 'sty/on-match-ok :result result :matcher matcher))
(assoc step :status :ok :result result))
(do
(save-step-result ztx cnm step {:status :error :error error :result result})
(fmt/emit ztx (assoc ev-base :type 'sty/on-match-fail :errors errors :result result :matcher matcher))
(assoc step :status :fail :match-errors errors :result result))))
(do (fmt/emit ztx (assoc ev-base :type 'sty/on-match-ok))
(assoc step :status :ok :result result))))))
(catch Exception e
(fmt/emit ztx (assoc ev-base :type 'sty/on-step-error :error {:message (.getMessage e)}))
(assoc step :status :error :error {:message (.getMessage e)})))))
(defn run-case [ztx env case]
(fmt/emit ztx {:type 'sty/on-case-start :env env :case case})
(let [res (->> (:steps case)
(map-indexed (fn [idx step]
(let [step (assoc step :_index idx)]
(run-step ztx env case step))))
(into []))
stats (->> res (reduce (fn [acc {st :status}]
(cond
(= :ok st) (update acc :passed inc)
(= :error st) (update acc :errored inc)
(= :fail st) (update acc :failed inc)
:else acc))
{:passed 0 :errored 0 :failed 0}))]
(fmt/emit ztx {:type 'sty/on-case-end :env env :case case :result res :stats stats})
{:case case :stats stats :steps res
:status (if (or (> (:errored stats) 0) (> (:failed stats) 0)) :fail :ok)}))
(defn run-env [ztx env]
(fmt/emit ztx {:type 'sty/on-env-start :env env})
(let [cases (->> (zen/get-tag ztx 'sty/case)
(mapv (fn [case-ref] (zen/get-symbol ztx case-ref))))
result (->> cases
(reduce (fn [res case]
(assoc res (:zen/name case) (run-case ztx env case)))
{}))
stats (->> result
(reduce
(fn [acc [_ {stats :stats}]]
(-> acc
(update :passed + (or (:passed stats) 0))
(update :failed + (or (:failed stats) 0))
(update :errored + (or (:errored stats) 0))))
{:passed 0 :errored 0 :failed 0}))]
(fmt/emit ztx {:type 'sty/on-env-end :env env :result result :stats stats})
{:cases result :env env :stats stats}))
(defmethod call-op 'sty/run-tests
[ztx op {params :params}]
(fmt/set-formatter ztx (:format params))
(fmt/emit ztx {:type 'sty/on-tests-start})
(let [envs-filter (when (:env params) (into #{} (mapv symbol (:env params))))
envs (->> (zen/get-tag ztx 'sty/env)
(filter (fn [env-ref] (or (nil? envs-filter) (contains? envs-filter env-ref))))
(map (fn [env-ref]
(zen/get-symbol ztx env-ref))))
result (->> envs
(reduce (fn [report env]
(let [res (run-env ztx env)]
(assoc report (:zen/name env) res))) {}))]
(stresty.reports.core/build-report ztx params result)
(fmt/emit ztx {:type 'sty/on-tests-done :result result})
result))
(defmethod call-op 'sty/gen
[ztx op {params :params}]
(println "Generate" params)
(stresty.operations.gen/generate ztx params))
| null | https://raw.githubusercontent.com/HealthSamurai/stresty/d73771841ffc9899c5981f9981f5974744ac4170/src/stresty/operations/core.clj | clojure | (ns stresty.operations.core
(:require [zen.core :as zen]
[stresty.actions.core :as acts]
[stresty.matchers.core :as match]
[stresty.sci]
[stresty.format.core :as fmt]
[stresty.operations.gen]
[stresty.reports.core]
[clojure.string :as str]))
(defmulti call-op (fn [ztx op args] (:zen/name op)))
(defn op [ztx args]
(if-let [op (when-let [m (:method args)]
(zen/get-symbol ztx (symbol m)))]
(call-op ztx op args)
(do
(println (str "Operation " (:method args) " is not defined."))
{:error {:message (str "Operation " (:method args) " is not defined.")}})))
(defmethod call-op :default
[ztx op args]
(println (str "Op " (:zen/name op) " is not implemented!"))
{:error {:message (str "Op " (:zen/name op) " is not implemented!")}})
(defmethod call-op 'sty/echo
[ztx op {params :params}]
{:result params})
(defmethod call-op 'sty/get-namespaces
[ztx op _]
(let [cases (zen/get-tag ztx 'sty/case)]
{:result {:namespaces (group-by (fn [e] (first (str/split (str e) #"\/"))) cases)}}))
(defmethod call-op 'sty/get-case
[ztx op {params :params}]
(if-let [case (zen/get-symbol ztx (symbol (:case params)))]
{:result case}
{:error {:message "Case not found"}}))
(defn- get-case-state [ztx enm cnm]
(or (get-in @ztx [:state enm cnm]) {}))
(defn- save-case-state [ztx enm cnm key state]
(swap! ztx (fn [old] (update-in old [:state enm cnm] (fn [old] (assoc old key state))))))
(defn- save-step-result [ztx cnm {idx :_index :as step} result]
(swap! ztx update :result #(assoc-in % [cnm idx] result)))
(defn sty-url [& args]
(str "/" (str/join "/" args)))
(defn run-step [ztx {enm :zen/name :as env} {cnm :zen/name :as case} {id :id idx :_index action :do :as step}]
(fmt/emit ztx (assoc step :type 'sty/on-run-step))
(let [state (get-case-state ztx enm cnm)
action (stresty.sci/eval-data {:namespaces {'sty {'env env 'step step 'case case 'state state 'url sty-url}}} action)
ev-base {:type 'sty/on-step-start
:env env
:case case
:step (assoc step :id (or id idx))
:verbose (get-in @ztx [:opts :verbose])
:do action}]
(fmt/emit ztx ev-base)
(try
(let [{result :result error :error} (stresty.actions.core/run-action ztx {:state state :case case :env env} action)]
(fmt/emit ztx (assoc ev-base :type 'sty/on-action-result :result result :error error))
(if error
(do
(save-step-result ztx cnm step {:status :error :error error})
(fmt/emit ztx (assoc ev-base :type 'sty/on-step-error :error error))
(assoc step :status :error :error error))
(do
(when id (save-case-state ztx enm cnm id result))
(if-let [matcher (:match step)]
(let [*matcher (stresty.sci/eval-data {:namespaces {'sty {'env env 'step step 'case case 'state state}}} matcher)
{errors :errors} (stresty.matchers.core/match ztx *matcher result)]
(if (empty? errors)
(do
(save-step-result ztx cnm step {:status :success})
(fmt/emit ztx (assoc ev-base :type 'sty/on-match-ok :result result :matcher matcher))
(assoc step :status :ok :result result))
(do
(save-step-result ztx cnm step {:status :error :error error :result result})
(fmt/emit ztx (assoc ev-base :type 'sty/on-match-fail :errors errors :result result :matcher matcher))
(assoc step :status :fail :match-errors errors :result result))))
(do (fmt/emit ztx (assoc ev-base :type 'sty/on-match-ok))
(assoc step :status :ok :result result))))))
(catch Exception e
(fmt/emit ztx (assoc ev-base :type 'sty/on-step-error :error {:message (.getMessage e)}))
(assoc step :status :error :error {:message (.getMessage e)})))))
(defn run-case [ztx env case]
(fmt/emit ztx {:type 'sty/on-case-start :env env :case case})
(let [res (->> (:steps case)
(map-indexed (fn [idx step]
(let [step (assoc step :_index idx)]
(run-step ztx env case step))))
(into []))
stats (->> res (reduce (fn [acc {st :status}]
(cond
(= :ok st) (update acc :passed inc)
(= :error st) (update acc :errored inc)
(= :fail st) (update acc :failed inc)
:else acc))
{:passed 0 :errored 0 :failed 0}))]
(fmt/emit ztx {:type 'sty/on-case-end :env env :case case :result res :stats stats})
{:case case :stats stats :steps res
:status (if (or (> (:errored stats) 0) (> (:failed stats) 0)) :fail :ok)}))
(defn run-env [ztx env]
(fmt/emit ztx {:type 'sty/on-env-start :env env})
(let [cases (->> (zen/get-tag ztx 'sty/case)
(mapv (fn [case-ref] (zen/get-symbol ztx case-ref))))
result (->> cases
(reduce (fn [res case]
(assoc res (:zen/name case) (run-case ztx env case)))
{}))
stats (->> result
(reduce
(fn [acc [_ {stats :stats}]]
(-> acc
(update :passed + (or (:passed stats) 0))
(update :failed + (or (:failed stats) 0))
(update :errored + (or (:errored stats) 0))))
{:passed 0 :errored 0 :failed 0}))]
(fmt/emit ztx {:type 'sty/on-env-end :env env :result result :stats stats})
{:cases result :env env :stats stats}))
(defmethod call-op 'sty/run-tests
[ztx op {params :params}]
(fmt/set-formatter ztx (:format params))
(fmt/emit ztx {:type 'sty/on-tests-start})
(let [envs-filter (when (:env params) (into #{} (mapv symbol (:env params))))
envs (->> (zen/get-tag ztx 'sty/env)
(filter (fn [env-ref] (or (nil? envs-filter) (contains? envs-filter env-ref))))
(map (fn [env-ref]
(zen/get-symbol ztx env-ref))))
result (->> envs
(reduce (fn [report env]
(let [res (run-env ztx env)]
(assoc report (:zen/name env) res))) {}))]
(stresty.reports.core/build-report ztx params result)
(fmt/emit ztx {:type 'sty/on-tests-done :result result})
result))
(defmethod call-op 'sty/gen
[ztx op {params :params}]
(println "Generate" params)
(stresty.operations.gen/generate ztx params))
|
|
70a0033da2d26620623a8933a8eed1a8e1128e2753f36f48549456f7c9b0f353 | GNOME/aisleriot | will-o-the-wisp.scm | AisleRiot - will_o_the_wisp.scm
Copyright ( C ) 2001 < >
;
; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program. If not, see </>.
(use-modules (aisleriot interface) (aisleriot api))
(primitive-load-path "spider")
(define stock 0)
(define foundation '(1 2 3 4))
(define tableau '(5 6 7 8 9 10 11))
(define winning-score 48)
(define (new-game)
(initialize-playing-area)
(set-ace-low)
(make-standard-deck)
(shuffle-deck)
(add-normal-slot DECK)
(add-blank-slot)
(add-blank-slot)
(add-normal-slot '())
(add-normal-slot '())
(add-normal-slot '())
(add-normal-slot '())
(add-carriage-return-slot)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(deal-cards 0 '(5 6 7 8 9 10 11 5 6 7 8 9 10 11))
(deal-cards-face-up 0 '(5 6 7 8 9 10 11 ))
(give-status-message)
(list 7 4))
(define (get-options) #f)
(define (apply-options options) #f)
(set-lambda! 'new-game new-game)
(set-lambda! 'get-options get-options)
(set-lambda! 'apply-options apply-options)
| null | https://raw.githubusercontent.com/GNOME/aisleriot/5ab7f90d8a196f1fcfe5a552cef4a4c1a4b5ac39/games/will-o-the-wisp.scm | scheme |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | AisleRiot - will_o_the_wisp.scm
Copyright ( C ) 2001 < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(use-modules (aisleriot interface) (aisleriot api))
(primitive-load-path "spider")
(define stock 0)
(define foundation '(1 2 3 4))
(define tableau '(5 6 7 8 9 10 11))
(define winning-score 48)
(define (new-game)
(initialize-playing-area)
(set-ace-low)
(make-standard-deck)
(shuffle-deck)
(add-normal-slot DECK)
(add-blank-slot)
(add-blank-slot)
(add-normal-slot '())
(add-normal-slot '())
(add-normal-slot '())
(add-normal-slot '())
(add-carriage-return-slot)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(deal-cards 0 '(5 6 7 8 9 10 11 5 6 7 8 9 10 11))
(deal-cards-face-up 0 '(5 6 7 8 9 10 11 ))
(give-status-message)
(list 7 4))
(define (get-options) #f)
(define (apply-options options) #f)
(set-lambda! 'new-game new-game)
(set-lambda! 'get-options get-options)
(set-lambda! 'apply-options apply-options)
|
d00dc40d498c2b8adaa0a2d7f8c7205969605f77a0f5cd2df7405d3cb7283353 | roburio/udns | dns_resolver_utils.mli | ( c ) 2017 , 2018 , all rights reserved
open Dns
val scrub : ?mode:[ `Recursive | `Stub ] -> [ `raw ] Domain_name.t -> Packet.Question.qtype -> Packet.t ->
((Rr_map.k * [ `raw ] Domain_name.t * Dns_resolver_cache.rank * Dns_resolver_cache.res) list,
Rcode.t) result
* [ scrub ~mode bailiwick packet ] returns a list of entries to - be - added to the
cache . This respects only in - bailiwick resources records , and qualifies the
[ packet ] . The purpose is to avoid cache poisoning by not accepting all
resource records .
cache. This respects only in-bailiwick resources records, and qualifies the
[packet]. The purpose is to avoid cache poisoning by not accepting all
resource records. *)
val invalid_soa : [ `raw ] Domain_name.t -> Soa.t (** [invalid_soa name] returns a stub
SOA for [name]. *)
| null | https://raw.githubusercontent.com/roburio/udns/585c40933ac3d5eceb351f7edd3f45cf2615a9f8/resolver/dns_resolver_utils.mli | ocaml | * [invalid_soa name] returns a stub
SOA for [name]. | ( c ) 2017 , 2018 , all rights reserved
open Dns
val scrub : ?mode:[ `Recursive | `Stub ] -> [ `raw ] Domain_name.t -> Packet.Question.qtype -> Packet.t ->
((Rr_map.k * [ `raw ] Domain_name.t * Dns_resolver_cache.rank * Dns_resolver_cache.res) list,
Rcode.t) result
* [ scrub ~mode bailiwick packet ] returns a list of entries to - be - added to the
cache . This respects only in - bailiwick resources records , and qualifies the
[ packet ] . The purpose is to avoid cache poisoning by not accepting all
resource records .
cache. This respects only in-bailiwick resources records, and qualifies the
[packet]. The purpose is to avoid cache poisoning by not accepting all
resource records. *)
|
ac93d70095c300c32cc4ef1fafe3411bf7e7437b77aee34aaefa507330d505e1 | crisptrutski/matchbox | atom.cljc | (ns matchbox.atom
(:require [clojure.walk :refer [postwalk]]
[matchbox.core :as m]
[matchbox.registry :as mr])
#?(:clj
(:import (clojure.lang Atom))))
Shim CLJS - style prototypes into CLJ
#?(:clj
(defprotocol ISwap
(-swap!
[_ f]
[_ f a]
[_ f a b]
[_ f a b xs])))
#?(:clj
(defprotocol IDeref
(-deref [_])))
#?(:clj
(extend-protocol IDeref
Atom
(-deref [this] @this)))
#?(:clj
(defprotocol IWatchable
(-add-watch [_ k f])
(-remove-watch [_ k])))
;; Watch strategies
(def ^:dynamic *local-sync*)
(def ^:dynamic *remote-sync*)
(defn- strip-nils [data]
(postwalk
(fn [x]
(if (map? x)
(into (empty x) (remove (comp nil? second) x))
x))
data))
(defn- reset-atom
"Generate ref listener to sync values back to atom"
[atom & [xform]]
(fn [[_ val]]
(when-not (= atom *local-sync*)
(binding [*remote-sync* atom]
(reset! atom (if xform (xform val) val))))))
(defn- reset-in-atom
"Generate ref listener to sync values back to atom. Scoped to path inside atom."
[atom path]
(fn [[_ val]]
(when-not (= atom *local-sync*)
(binding [*remote-sync* atom]
(let [val (if (nil? val)
(let [old (get-in @atom path)]
(if (coll? old) (empty old)))
val)]
(swap! atom assoc-in path val))))))
(defn- cascade
"Cascade deletes locally, but do not remove the root (keep type and existence stable)"
[o n]
(or (strip-nils n)
(if (coll? n) (empty n))
(if (coll? o) (empty o))))
(defn- reset-ref
"Generate atom-watch function to sync values back to ref"
[ref]
(fn [_ atom o n]
(when-not (or (= o n) (= atom *remote-sync*))
(let [cascaded (cascade o n)]
(if-not (= cascaded n)
(binding [*remote-sync* atom]
(reset! atom cascaded))))
(binding [*local-sync* atom]
(m/reset! ref n)))))
(defn- reset-in-ref
"Generate atom-watch function to sync values back to ref. Scoped to path inside atom."
[ref path]
(fn [_ atom o n]
(let [o (get-in o path)
n (get-in n path)]
(when-not (or (= o n) (= atom *remote-sync*))
(let [cascaded (cascade o n)]
(if-not (= cascaded n)
(binding [*remote-sync* atom]
(swap! atom assoc-in path cascaded))))
(binding [*local-sync* atom]
(m/reset! ref n))))))
;; Proxy strategies
(defn- swap-failover [cache f args]
(if-not (:matchbox-unsubs (meta cache))
(apply swap! cache f args)))
(defn- swap-ref-local [ref cache]
(fn [f & args]
(or (swap-failover cache f args)
(m/reset! ref (apply f @cache args)))))
(defn- swap-ref-remote [ref cache]
(fn [f & args]
(or (swap-failover cache f args)
(apply m/swap! ref f args))))
;; Wrapper type
(declare unlink!)
(defprotocol IUnlink
(-unlink [_] "Remove any sync between local and firebase state"))
(deftype FireAtom [ref cache ->update]
#?(:cjs IAtom)
ISwap
(-swap! [_ f]
(->update f))
(-swap! [_ f a]
(->update f a))
(-swap! [_ f a b]
(->update f a b))
(-swap! [_ f a b xs]
(apply ->update f a b xs))
IDeref
(-deref [_] (-deref cache))
IUnlink
(-unlink [_] (unlink! cache))
IWatchable
(-add-watch [_ k f]
(-add-watch cache k f))
(-remove-watch [_ k]
(-remove-watch cache k)))
Watcher / Listener management
(defn- attach-unsub [atom unsub]
(alter-meta! atom update-in [:matchbox-unsubs] #(conj % unsub)))
(defn <-ref
"Track changes in ref back to atom, via update function f."
[ref atom f]
(attach-unsub atom (m/listen-to ref :value f)))
(defn ->ref
"Track changes in atom back to ref, via update function f."
[ref atom f]
(let [id (gensym)]
(alter-meta! atom assoc :matchbox-watch id)
(add-watch atom id f)))
;; Atom factories / decorators
(defn- init-ref!
"Set ref with value, if value is not empty or nil."
[ref value update? update!]
(when-not (or (nil? value) (and (coll? value) (empty? value)))
(m/deref ref
;; don't update if the ship has already sailed
#(when (update? value)
(if (nil? %)
(m/reset! ref value)
(update! %))))))
;; Atom coordination
(defn sync-r
"Set up one-way sync of atom tracking ref changes. Useful for queries."
[atom query & [xform]]
(<-ref query atom (reset-atom atom xform))
atom)
(defn sync-list
"Set up one-way sync of atom tracking ordered list of elements. Useful for queries."
[atom query & [xform]]
(attach-unsub atom (m/listen-list query #(reset! atom (if xform (xform %) %))))
atom)
(defn sync-rw
"Set up two-way data sync between ref and atom."
[atom ref]
(init-ref! ref @atom #(reset! atom %) #(= % @atom))
(<-ref ref atom (reset-atom atom))
(->ref ref atom (reset-ref ref))
atom)
(defn- update-path [atom path & [xform]]
#(swap! atom assoc-in path (if xform (xform %) %)))
(defn sync-r-in [atom path query & [xform]]
(m/listen-to query :value (update-path atom path xform))
atom)
(defn sync-list-in [atom path query & [xform]]
(attach-unsub atom (m/listen-list query (update-path atom path xform)))
atom)
(defn sync-rw-in [atom path ref]
(init-ref! ref (get-in @atom path)
(update-path atom path nil)
#(= % (get-in @atom path)))
(<-ref ref atom (reset-in-atom atom path))
(->ref ref atom (reset-in-ref ref path))
atom)
(defn atom-wrapper
"Build atom-proxy with given sync strategies."
[atom ref ->update <-update]
(<-ref ref atom <-update)
(FireAtom. ref atom ->update))
(defn wrap-atom
"Build atom-proxy which synchronises with ref via brute force."
[atom ref]
(init-ref! ref @atom #(reset! atom %) #(= % @atom))
(atom-wrapper atom ref
(swap-ref-local ref atom)
(reset-atom atom)))
(defn unlink!
"Stop synchronising atom with Firebase."
[atom]
(if (instance? FireAtom atom)
(-unlink atom)
(let [{id :matchbox-watch, unsubs :matchbox-unsubs} (meta atom)]
(when id (remove-watch atom id))
(doseq [unsub unsubs]
(mr/disable-listener! unsub))
(alter-meta! atom dissoc :matchbox-watch :matchbox-unsubs))))
| null | https://raw.githubusercontent.com/crisptrutski/matchbox/5bb9ba96f5df01bce302a8232f6cddd9d64a1d71/src/matchbox/atom.cljc | clojure | Watch strategies
Proxy strategies
Wrapper type
Atom factories / decorators
don't update if the ship has already sailed
Atom coordination | (ns matchbox.atom
(:require [clojure.walk :refer [postwalk]]
[matchbox.core :as m]
[matchbox.registry :as mr])
#?(:clj
(:import (clojure.lang Atom))))
Shim CLJS - style prototypes into CLJ
#?(:clj
(defprotocol ISwap
(-swap!
[_ f]
[_ f a]
[_ f a b]
[_ f a b xs])))
#?(:clj
(defprotocol IDeref
(-deref [_])))
#?(:clj
(extend-protocol IDeref
Atom
(-deref [this] @this)))
#?(:clj
(defprotocol IWatchable
(-add-watch [_ k f])
(-remove-watch [_ k])))
(def ^:dynamic *local-sync*)
(def ^:dynamic *remote-sync*)
(defn- strip-nils [data]
(postwalk
(fn [x]
(if (map? x)
(into (empty x) (remove (comp nil? second) x))
x))
data))
(defn- reset-atom
"Generate ref listener to sync values back to atom"
[atom & [xform]]
(fn [[_ val]]
(when-not (= atom *local-sync*)
(binding [*remote-sync* atom]
(reset! atom (if xform (xform val) val))))))
(defn- reset-in-atom
"Generate ref listener to sync values back to atom. Scoped to path inside atom."
[atom path]
(fn [[_ val]]
(when-not (= atom *local-sync*)
(binding [*remote-sync* atom]
(let [val (if (nil? val)
(let [old (get-in @atom path)]
(if (coll? old) (empty old)))
val)]
(swap! atom assoc-in path val))))))
(defn- cascade
"Cascade deletes locally, but do not remove the root (keep type and existence stable)"
[o n]
(or (strip-nils n)
(if (coll? n) (empty n))
(if (coll? o) (empty o))))
(defn- reset-ref
"Generate atom-watch function to sync values back to ref"
[ref]
(fn [_ atom o n]
(when-not (or (= o n) (= atom *remote-sync*))
(let [cascaded (cascade o n)]
(if-not (= cascaded n)
(binding [*remote-sync* atom]
(reset! atom cascaded))))
(binding [*local-sync* atom]
(m/reset! ref n)))))
(defn- reset-in-ref
"Generate atom-watch function to sync values back to ref. Scoped to path inside atom."
[ref path]
(fn [_ atom o n]
(let [o (get-in o path)
n (get-in n path)]
(when-not (or (= o n) (= atom *remote-sync*))
(let [cascaded (cascade o n)]
(if-not (= cascaded n)
(binding [*remote-sync* atom]
(swap! atom assoc-in path cascaded))))
(binding [*local-sync* atom]
(m/reset! ref n))))))
(defn- swap-failover [cache f args]
(if-not (:matchbox-unsubs (meta cache))
(apply swap! cache f args)))
(defn- swap-ref-local [ref cache]
(fn [f & args]
(or (swap-failover cache f args)
(m/reset! ref (apply f @cache args)))))
(defn- swap-ref-remote [ref cache]
(fn [f & args]
(or (swap-failover cache f args)
(apply m/swap! ref f args))))
(declare unlink!)
(defprotocol IUnlink
(-unlink [_] "Remove any sync between local and firebase state"))
(deftype FireAtom [ref cache ->update]
#?(:cjs IAtom)
ISwap
(-swap! [_ f]
(->update f))
(-swap! [_ f a]
(->update f a))
(-swap! [_ f a b]
(->update f a b))
(-swap! [_ f a b xs]
(apply ->update f a b xs))
IDeref
(-deref [_] (-deref cache))
IUnlink
(-unlink [_] (unlink! cache))
IWatchable
(-add-watch [_ k f]
(-add-watch cache k f))
(-remove-watch [_ k]
(-remove-watch cache k)))
Watcher / Listener management
(defn- attach-unsub [atom unsub]
(alter-meta! atom update-in [:matchbox-unsubs] #(conj % unsub)))
(defn <-ref
"Track changes in ref back to atom, via update function f."
[ref atom f]
(attach-unsub atom (m/listen-to ref :value f)))
(defn ->ref
"Track changes in atom back to ref, via update function f."
[ref atom f]
(let [id (gensym)]
(alter-meta! atom assoc :matchbox-watch id)
(add-watch atom id f)))
(defn- init-ref!
"Set ref with value, if value is not empty or nil."
[ref value update? update!]
(when-not (or (nil? value) (and (coll? value) (empty? value)))
(m/deref ref
#(when (update? value)
(if (nil? %)
(m/reset! ref value)
(update! %))))))
(defn sync-r
"Set up one-way sync of atom tracking ref changes. Useful for queries."
[atom query & [xform]]
(<-ref query atom (reset-atom atom xform))
atom)
(defn sync-list
"Set up one-way sync of atom tracking ordered list of elements. Useful for queries."
[atom query & [xform]]
(attach-unsub atom (m/listen-list query #(reset! atom (if xform (xform %) %))))
atom)
(defn sync-rw
"Set up two-way data sync between ref and atom."
[atom ref]
(init-ref! ref @atom #(reset! atom %) #(= % @atom))
(<-ref ref atom (reset-atom atom))
(->ref ref atom (reset-ref ref))
atom)
(defn- update-path [atom path & [xform]]
#(swap! atom assoc-in path (if xform (xform %) %)))
(defn sync-r-in [atom path query & [xform]]
(m/listen-to query :value (update-path atom path xform))
atom)
(defn sync-list-in [atom path query & [xform]]
(attach-unsub atom (m/listen-list query (update-path atom path xform)))
atom)
(defn sync-rw-in [atom path ref]
(init-ref! ref (get-in @atom path)
(update-path atom path nil)
#(= % (get-in @atom path)))
(<-ref ref atom (reset-in-atom atom path))
(->ref ref atom (reset-in-ref ref path))
atom)
(defn atom-wrapper
"Build atom-proxy with given sync strategies."
[atom ref ->update <-update]
(<-ref ref atom <-update)
(FireAtom. ref atom ->update))
(defn wrap-atom
"Build atom-proxy which synchronises with ref via brute force."
[atom ref]
(init-ref! ref @atom #(reset! atom %) #(= % @atom))
(atom-wrapper atom ref
(swap-ref-local ref atom)
(reset-atom atom)))
(defn unlink!
"Stop synchronising atom with Firebase."
[atom]
(if (instance? FireAtom atom)
(-unlink atom)
(let [{id :matchbox-watch, unsubs :matchbox-unsubs} (meta atom)]
(when id (remove-watch atom id))
(doseq [unsub unsubs]
(mr/disable-listener! unsub))
(alter-meta! atom dissoc :matchbox-watch :matchbox-unsubs))))
|
013788bc4befcc9c4afb209e48a53420543ed2e01b6b95f14bd38455b21f4ac0 | hbr/fmlib | generic.mli | (** A Generic Parser where all parameters are customizable. *)
open Fmlib_std.Interfaces
module Make
(Token: ANY)
(State: ANY)
(Expect: ANY)
(Semantic: ANY)
(Final: ANY):
sig
(**
- [Token.t] Token type
- [State.t] Type of the user state
- [Expect.t] Type of syntax messages which are generated, when
something has been expected but not found.
- [Semantic.t] Type of semantic error messages. Triggered by [fail
error].
- [Final.t] Type of the returned object, when parsing has finished.
*)
(** {1 Final parser} *)
(** The final parser.
*)
module Parser:
sig
include Interfaces.PARSER
with type token = Token.t
and type final = Final.t
and type expect = Expect.t
and type semantic = Semantic.t
and type state = State.t
* @inline
end
(** {1 Generic Combinators} *)
include Interfaces.COMBINATOR
with
type state = State.t
and type expect = Expect.t
and type semantic = Semantic.t
* @inline
* { 1 Elementary Parsing Step }
val step:
(State.t -> Token.t option -> ('a * State.t, Expect.t) result)
->
'a t
* [ step f ]
Elementary parsing step .
The function [ f ] is called with two arguments :
- The current state
- The next lookahead token ( or none , if the end of the token stream has
been reached ) .
[ f ] must return either an object of type [ ' a ] and a new state if it
accepts the token , or a failed expectation if it rejects the token .
Elementary parsing step.
The function [f] is called with two arguments:
- The current state
- The next lookahead token (or none, if the end of the token stream has
been reached).
[f] must return either an object of type ['a] and a new state if it
accepts the token, or a failed expectation if it rejects the token.
*)
val expect_end:
(State.t -> Expect.t) -> 'a -> 'a t
(** [expect_end error a] Expect the end of input.
In case of success return [a]. In case of failure (i.e. not yet at the
end of input) then compute via [error] the syntax error from the state.
WARNING: This combinator only makes sense if you generate your parser
with [make_parser]. If you generate your parser with [make] then the end
of input is automatically expected after the toplevel construct.
*)
(** {1 Update Failed Expectations} *)
val update_expectations:
(State.t -> Token.t option -> Expect.t) -> 'a t -> 'a t
(** {1 Make the Final Parser} *)
val make: State.t -> Final.t t -> (State.t -> Expect.t) -> Parser.t
(** [make state p e] Makes a parser.
- [state] Initial state
- [p] Combinator which returns in case of success an object of type
[Final.t]
- [e] Error function. Generates an expectation from the state. The
function is used if an other token arrives at the expected end of input.
The generated parser expects a token stream which can be successfully
parsed by the combinator [p]. It can succeed only if an end token is
pushed to the parser.
*)
val make_parser: State.t -> Final.t t -> Parser.t
(** [make_parser state p].
Makes a parser which starts in state [state] and parses a construct
defined by the combinator [p]. The parser can succeed, even if no end
token is pushed to the parser.
*)
end
| null | https://raw.githubusercontent.com/hbr/fmlib/0c7b923605a211e9c706d427fb33c5ba40248321/src/parse/generic.mli | ocaml | * A Generic Parser where all parameters are customizable.
*
- [Token.t] Token type
- [State.t] Type of the user state
- [Expect.t] Type of syntax messages which are generated, when
something has been expected but not found.
- [Semantic.t] Type of semantic error messages. Triggered by [fail
error].
- [Final.t] Type of the returned object, when parsing has finished.
* {1 Final parser}
* The final parser.
* {1 Generic Combinators}
* [expect_end error a] Expect the end of input.
In case of success return [a]. In case of failure (i.e. not yet at the
end of input) then compute via [error] the syntax error from the state.
WARNING: This combinator only makes sense if you generate your parser
with [make_parser]. If you generate your parser with [make] then the end
of input is automatically expected after the toplevel construct.
* {1 Update Failed Expectations}
* {1 Make the Final Parser}
* [make state p e] Makes a parser.
- [state] Initial state
- [p] Combinator which returns in case of success an object of type
[Final.t]
- [e] Error function. Generates an expectation from the state. The
function is used if an other token arrives at the expected end of input.
The generated parser expects a token stream which can be successfully
parsed by the combinator [p]. It can succeed only if an end token is
pushed to the parser.
* [make_parser state p].
Makes a parser which starts in state [state] and parses a construct
defined by the combinator [p]. The parser can succeed, even if no end
token is pushed to the parser.
|
open Fmlib_std.Interfaces
module Make
(Token: ANY)
(State: ANY)
(Expect: ANY)
(Semantic: ANY)
(Final: ANY):
sig
module Parser:
sig
include Interfaces.PARSER
with type token = Token.t
and type final = Final.t
and type expect = Expect.t
and type semantic = Semantic.t
and type state = State.t
* @inline
end
include Interfaces.COMBINATOR
with
type state = State.t
and type expect = Expect.t
and type semantic = Semantic.t
* @inline
* { 1 Elementary Parsing Step }
val step:
(State.t -> Token.t option -> ('a * State.t, Expect.t) result)
->
'a t
* [ step f ]
Elementary parsing step .
The function [ f ] is called with two arguments :
- The current state
- The next lookahead token ( or none , if the end of the token stream has
been reached ) .
[ f ] must return either an object of type [ ' a ] and a new state if it
accepts the token , or a failed expectation if it rejects the token .
Elementary parsing step.
The function [f] is called with two arguments:
- The current state
- The next lookahead token (or none, if the end of the token stream has
been reached).
[f] must return either an object of type ['a] and a new state if it
accepts the token, or a failed expectation if it rejects the token.
*)
val expect_end:
(State.t -> Expect.t) -> 'a -> 'a t
val update_expectations:
(State.t -> Token.t option -> Expect.t) -> 'a t -> 'a t
val make: State.t -> Final.t t -> (State.t -> Expect.t) -> Parser.t
val make_parser: State.t -> Final.t t -> Parser.t
end
|
43038018f2273a1d11dd51e555605356959d3fa3d371a5ef2368b1dbc8ee59f4 | puffnfresh/sonic2 | Main.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
import qualified Codec.Compression.Kosinski as Kosinski
import Control.Lens
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import Data.Array.Bounded
import Data.Array.Bounded ((!))
import Data.Bits
import qualified Data.ByteString as BS
import Data.ByteString.Lens
import Data.Halves (collectHalves)
import Data.Int
import Data.Maybe (fromMaybe)
import Data.Semigroup ((<>))
import Data.Time (diffUTCTime, getCurrentTime)
import Data.Word
import Foreign.C.Types (CInt)
import Game.Sega.Sonic.Animation
import Game.Sega.Sonic.Blocks
import Game.Sega.Sonic.Chunks
import Game.Sega.Sonic.Collision
import Game.Sega.Sonic.Error
import Game.Sega.Sonic.Game
import Game.Sega.Sonic.Layout
import Game.Sega.Sonic.Offsets as Offsets
import Game.Sega.Sonic.Palette
import Game.Sega.Sonic.Player
import Game.Sega.Sonic.Sine
import Game.Sega.Sonic.SpriteMappings
import Game.Sega.Sonic.Sprites
import Game.Sega.Sonic.Tiles
import SDL
import Sega.MegaDrive.Palette
import Numeric
import Debug.Trace
decompressFile :: (HasRom g, MonadReader g m, MonadError SonicError m, MonadIO m) => Offset -> m BS.ByteString
decompressFile offset = do
maybeContent <- Kosinski.compressed <$> sliceRom offset
content <- maybe (throwError $ SonicLoadError offset) pure maybeContent
maybe (throwError $ SonicDecompressionError offset) pure $ Kosinski.decompress content
-- NTSC
frameRate :: Double
frameRate =
60
class HasLevel s where
layout :: s -> [[Word8]]
chunkBlocks :: s -> BoundedArray Word8 (BoundedArray Word8 ChunkBlock)
data LevelData
= LevelData AngleData [[Word8]] (BoundedArray Word8 (BoundedArray Word8 ChunkBlock))
instance HasAngleData LevelData where
angleData (LevelData a _ _) =
a
instance HasLevel LevelData where
layout (LevelData _ a _) =
a
chunkBlocks (LevelData _ _ a) =
a
findTile :: (HasLevel s, MonadReader s m) => V2 CInt -> m Word16
findTile p = do
layout' <- asks layout
let
p' =
p ^. pixels
V2 layoutX layoutY =
(`div` 0x80) <$> p'
chunkIndex =
layout' !! fromIntegral layoutY !! fromIntegral layoutX
blockIndex =
fromIntegral chunkIndex * (0x80 :: Word16)
+ fromIntegral (p' ^. _y .&. 0x70)
+ fromIntegral (p' ^. _x .&. 0xE)
pure blockIndex
data WallDist
= WallDist Word16 CInt Word8
deriving (Eq, Ord, Show)
Scans horizontally for up to 2 16x16 blocks to find solid walls .
-- d2 = y_pos
d3 = x_pos
-- d5 = ($c,$d) or ($e,$f) - solidity type bit (L/R/B or top)
d6 = $ 0000 for no flip , $ 0400 for horizontal flip
-- a3 = delta-x for next location to check if current one is empty
-- a4 = pointer to angle buffer
-- returns relevant block ID in (a1)
-- returns distance to left/right in d1
-- returns angle in (a4)
findWall :: (HasLevel s, MonadReader s m) => V2 CInt -> CInt -> m WallDist
findWall p delta = do
blockIndex <- findTile p
if blockIndex .&. 0x3FF == 0
then do
WallDist a1 d1 a4 <- findWall2 (p & _x +~ delta)
dist & distance + ~ 0x10
pure $ WallDist a1 (d1 + 0x10) a4
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
findWall2 :: (HasLevel s, MonadReader s m) => V2 CInt -> m WallDist
findWall2 p = do
blockIndex <- (.&. 0x3FF) <$> findTile p
if blockIndex == 0
then do
let
d1 =
0xF - (p ^. _x .&. 0xF)
pure $ WallDist blockIndex d1 0
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
findFloor :: (HasLevel s, MonadReader s m) => V2 CInt -> CInt -> m WallDist
findFloor p delta = do
blockIndex <- (.&. 0x3FF) <$> findTile p
let d5 = 0xC
if blockIndex == 0 || not (testBit blockIndex d5)
then do
WallDist a1 d1 a4 <- findFloor2 (p & _y +~ delta)
dist & distance + ~ 0x10
pure $ WallDist a1 (d1 + 0x10) a4
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
findFloor2 :: (HasLevel s, MonadReader s m) => V2 CInt -> m WallDist
findFloor2 p = do
blockIndex <- (.&. 0x3FF) <$> findTile p
let d5 = 0xC
if blockIndex == 0 || not (testBit blockIndex d5)
then do
let
d1 =
0xF - (p ^. _y .&. 0xF)
pure $ WallDist blockIndex d1 0
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
Checks a 16x16 block to find solid walls . May check an additional
16x16 block up for walls .
-- d5 = ($c,$d) or ($e,$f) - solidity type bit (L/R/B or top)
-- returns relevant block ID in (a1)
-- returns distance in d1
returns angle in d3 , or zero if angle was odd
checkLeftWallDist :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkLeftWallDist = do
p <- use (player . position)
findWall p (-0x10)
checkRightWallDist :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkRightWallDist = do
p <- use (player . position)
findWall p (0x10)
checkCeiling :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkCeiling = do
p <- use (player . position)
findFloor p (-0x10)
checkFloor :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkFloor = do
p <- use (player . position)
findFloor p 0x10
hitLeftWall :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m ()
hitLeftWall = do
WallDist _ d1 _ <- checkLeftWallDist
traceShow ("hitLeftWall", d1) $ pure ()
if d1 >= 0
then hitCeiling
else do
player . position . _x -= d1
player . playerVelocity . _x .= 0
y_vel <- use (player . playerVelocity . _y)
player . playerInertia .= y_vel
hitCeiling :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitCeiling = do
WallDist _ d1 _ <- checkCeiling
traceShow ("hitCeiling", d1) $ pure ()
if d1 >= 0
then hitFloor
else do
player . position . _y -= d1
y_vel <- use (player . playerVelocity . _y)
when (y_vel < 0) $
player . playerVelocity . _y .= 0
hitFloor :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitFloor = do
y_vel <- use (player . playerVelocity . _y)
unless (y_vel < 0) $ do
WallDist _ d1 d3 <- checkFloor
traceShow ("hitFloor", d1) $ pure ()
when (d1 < 0) $ do
player . position . _y += d1
player . playerAngle .= d3
resetOnFloor
player . playerVelocity . _y .= 0
x_vel <- use (player . playerVelocity . _x)
player . playerInertia .= x_vel
hitCeilingAndWalls :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitCeilingAndWalls = do
WallDist _ d1 _ <- checkLeftWallDist
when (d1 < 0) $ do
player . position . _x -= d1
player . playerVelocity . _x .= 0
WallDist _ d1' _ <- checkRightWallDist
when (d1' < 0) $ do
player . position . _x += d1
player . playerVelocity . _x .= 0
WallDist _ d1'' d3 <- checkCeiling
when (d1'' < 0) $ do
player . position . _y -= d1''
let d0 = (d3 + 0x20) .&. 0x40
if (d0 /= 0)
then do
player . playerAngle .= d3
resetOnFloor
y_vel <- use (player . playerVelocity . _y)
player . playerInertia .= y_vel
inertia <- use (player . playerInertia)
unless (d3 < 0) $
player . playerInertia .= (-inertia)
else player . playerVelocity . _y .= 0;
hitRightWall :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitRightWall = do
WallDist _ d1 _ <- checkRightWallDist
traceShow ("hitRightWall", d1) $ pure ()
if d1 >= 0
then hitCeiling
else do
player . position . _x += d1
player . playerVelocity . _x .= 0
y_vel <- use (player . playerVelocity . _y)
player . playerInertia .= y_vel
doLevelCollision :: (HasAngleData g, HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
doLevelCollision = do
-- TODO: Check left/right/bottom solid bit
v <- use (player . playerVelocity)
a <- calcAngle v
traceShow ("doLevelCollision", (a - 0x20) .&. 0xC0) $ pure ()
case (a - 0x20) .&. 0xC0 of
0x40 -> hitLeftWall
0x80 -> hitCeilingAndWalls
0xC0 -> hitRightWall
_ -> do
WallDist _ d1 _ <- checkLeftWallDist
when (d1 < 0) $ do
p->x_pos -= d1 ;
p->x_vel = 0 ;
traceShow "TODO" $ pure ()
WallDist _ d1' _ <- checkLeftWallDist
when (d1' < 0) $ do
p->x_pos + = d1 ;
p->x_vel = 0 ;
traceShow "TODO" $ pure ()
WallDist _ d1'' d3 <- checkFloor
unless (d1'' < 0) $ do
v <- use (player . playerVelocity)
-- let d2 = negate ((v ^. _y `shiftR` 8) + 8)
player . position . _y += d1''
player . playerAngle .= d3
resetOnFloor
-- d0 = (d3 + 0x10) & 0x20;
-- if((char)d0 == 0)
-- goto loc_1AF5A;
if(p->y_vel < 0 ) { // p->y_vel /= 2 ; -- DONE THIS WAY FOR ACCURACY
p->y_vel > > = 1 ;
p->y_vel |= 0x80000000 ;
-- }
-- else
p->y_vel > > = 1 ;
-- goto loc_1AF7C;
Subroutine to change Sonic 's angle as he walks along the floor
sonicAngle :: (Applicative m) => Word8 -> m ()
sonicAngle _ =
pure ()
anglePos :: (HasLevel g, HasAngleData g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
anglePos = do
-- unless onobject
a <- use (player . playerAngle)
let
a' =
if a + 0x20 >= 0
then (if a < 0 then a + 1 else a) + 0x1F
else error "angle pos 1"
case (a' + 0x20) .&. 0xC0 of
0x40 -> pure ()
0x80 -> pure ()
0xC0 -> pure ()
_ -> do
p <- use (player . position)
r <- use (player . playerRadius)
WallDist _ d1 a4 <- findFloor (p + r) 0x10
sonicAngle a4
unless (d1 == 0) $ do
if d1 >= 0
then do
v <- use (player . playerVelocity)
let d0 = min 0xE (abs (v ^. _x `shiftR` 8) + 4)
if d1 > fromIntegral d0
then player . statuses . mdAir .= MdAirOn
player . status & = 0xDF
-- pure ()
else player . position . _y += d1
else
unless (d1 < (-0xE)) $
player . position . _y += d1
x :: (HasLevel g, MonadReader g m) => V2 CInt -> m WallDist
x p = do
l <- asks layout
c <- asks chunkBlocks
let
reindexedCollisionBlocks =
undefined
reindexedCurves =
undefined
V2 layoutX layoutY =
(`div` 0x80) <$> p
chunkIndex =
l !! fromIntegral layoutY !! fromIntegral layoutX
V2 blockX blockY =
((`div` 0x10) . (`rem` 0x80)) <$> p
ChunkBlock blockIndex flipX flipY =
(c ! chunkIndex) ! fromIntegral ((blockY * 8) + blockX)
V2 pixelX pixelY =
(`rem` 0x10) <$> p
CollisionBlock heights =
reindexedCollisionBlocks ! blockIndex
angle' =
(if flipX then negate else id) $ reindexedCurves ! blockIndex
flip' flag n =
if flag then 0xF - n else n
height =
fromMaybe 0 (heights ! fromIntegral (flip' flipX pixelX))
heightDifference =
(0x10 - flip' flipY pixelY) - (fromIntegral height + 2)
pure $ WallDist blockIndex heightDifference angle'
loadAndRun :: (MonadReader Game m, MonadError SonicError m, MonadIO m) => m ()
loadAndRun = do
sonicMappings <- loadSpriteMappings sonicOffsets
tailsMappings <- loadSpriteMappings tailsOffsets
curves <- listArrayFill 0 . BS.unpack <$> sliceRom curveAndResistanceMapping
sonicAnimationScript <- loadAnimation . BS.unpack <$> sliceRom animationSonicWait
tailsAnimationScript <- loadAnimation . BS.unpack <$> sliceRom animationTailsWait
let offsets = ehz1
maybeSonicPalette <- readPalette <$> sliceRom paletteSonic
maybePalette <- readPalette <$> sliceRom (levelPaletteOffset offsets)
palette <- maybe (throwError . SonicPaletteError $ levelPaletteOffset offsets) (pure . loadPalette) (maybeSonicPalette <> maybePalette)
tileContent <- decompressFile $ levelArtOffset offsets
tileSurfaces <- loadTiles tileContent
blockContent <- decompressFile $ levelBlocksOffset offsets
blockTextures <- loadBlocks palette tileSurfaces blockContent
chunkContent <- decompressFile $ levelChunksOffset offsets
let chunkBlocks = loadChunks chunkContent
chunkTextures <- traverse (loadChunkTexture blockTextures) chunkBlocks
layoutContent <- decompressFile $ levelLayoutOffset offsets
let
layout =
loadLayout layoutContent
layoutChunkTextures =
mapChunkTextures chunkTextures layout
collisionIndexContent <- decompressFile $ levelCollisionOffset offsets
collisionIndex <- loadCollisionIndex collisionIndexContent
collisionContent <- sliceRom collisionArray1
let collisionBlocks = loadCollisionBlocks collisionContent
collisionBlockTextures <- traverse loadCollisionTexture collisionBlocks
let reindexedCollisionTextures = (collisionBlockTextures !) <$> collisionIndex
reindexedCollisionBlocks = (collisionBlocks !) <$> collisionIndex
reindexedCurves = (curves !) <$> collisionIndex
now <- liftIO getCurrentTime
chunksContent <- decompressFile $ levelChunksOffset offsets
liftIO $ putStrLn "Loading chunks..."
let chunksBlocks = loadChunks chunksContent
chunksTextures <- traverse (loadChunkTexture reindexedCollisionTextures) chunksBlocks
now' <- liftIO getCurrentTime
liftIO . putStrLn $ "Chunks loaded in " <> show (diffUTCTime now' now)
sineData' <- SineData . listArrayFill 0 . fmap fromIntegral . view (unpackedBytes . collectHalves) <$> sliceRom Offsets.sineData
angleData' <- AngleData . listArrayFill 0 . fmap fromIntegral . view (unpackedBytes . collectHalves) <$> sliceRom Offsets.angleData
let
collisionTextures = mapChunkTextures chunksTextures layout
levelData = LevelData angleData' layout chunkBlocks
startPos <- sliceRom $ levelStartPos ehz1
let
playerStart =
case (startPos ^. unpackedBytes . collectHalves) of
[x, y] ->
V2 (fromIntegral x) (fromIntegral y)
_ ->
V2 0 0
r <- view renderer
rendererRenderTarget r $= Nothing
let
playerSprite =
Sprite sonicMappings (V2 0 0) sonicAnimationScript emptyAnimationState
render textures (V2 o p) =
ifor_ textures $ \y row ->
ifor_ row $ \x texture ->
let
rectangle =
Rectangle (P (V2 ((fromIntegral x * 0x80) - o) ((fromIntegral y * 0x80) - p))) 0x80
in copy r texture Nothing (Just rectangle)
appLoop playerSprite' game = do
-- startTicks <- ticks
events <- pollEvents
let
eventIsPress keycode event =
case eventPayload event of
KeyboardEvent keyboardEvent ->
keyboardEventKeyMotion keyboardEvent == Pressed &&
keysymKeycode (keyboardEventKeysym keyboardEvent) == keycode
_ ->
False
isPressed keycode =
any (eventIsPress keycode) events
qPressed =
isPressed KeycodeQ
jumpPressed =
isPressed KeycodeA || isPressed KeycodeS || isPressed KeycodeD
leftPressed =
isPressed KeycodeLeft
rightPressed =
isPressed KeycodeRight
-- downPressed =
isPressed KeycodeDown
-- upPressed =
-- isPressed KeycodeUp
playerSprite'' =
playerSprite' & position .~ (fromIntegral <$> (game ^. player . position . pixels))
updateGame = do
zoom player $ do
s <- use statuses
traceShow (playerRoutine s) $ pure ()
case playerRoutine s of
MdNormal -> do
if jumpPressed
then runReaderT jump sineData'
else do
if rightPressed
then moveRight
else when leftPressed moveLeft
when (not rightPressed && not leftPressed) settle
objectMove
traction
runReaderT anglePos levelData
MdAir -> do
objectMoveAndFall
runReaderT doLevelCollision levelData
MdRoll ->
pure ()
MdJump -> do
objectMoveAndFall
runReaderT doLevelCollision levelData
p' <- use (player . position . pixels)
camera .= (fromIntegral <$> p') - V2 160 128 -- V2 o' p'
game' =
execState updateGame game
rendererDrawColor r $= V4 0 0 0 0xFF
clear r
render layoutChunkTextures (game' ^. camera)
runReaderT (renderSprite playerSprite'') game'
present r
delay 16
unless qPressed (appLoop (stepSprite playerSprite'') game')
game <- ask
appLoop playerSprite (game & player . position . pixels .~ playerStart)
main :: IO ()
main = do
rom' <- BS.readFile "sonic2.md"
window <- createWindow "Sonic 2" defaultWindow { windowInitialSize = V2 320 224 }
renderer' <- createRenderer window (-1) defaultRenderer
rendererLogicalSize renderer' $= Just (V2 320 224)
e <- runReaderT (runExceptT loadAndRun) (Game renderer' 0 rom' $ Player (V2 0 0) (V2 0 0) (V2 0 0x13) normalTopSpeed normalAcceleration normalDeceleration 0 0 initialStatuses)
either print pure e
| null | https://raw.githubusercontent.com/puffnfresh/sonic2/0abc3e109a847582c2e16edb13e83e611419fc8a/Main.hs | haskell | # LANGUAGE FlexibleContexts #
NTSC
d2 = y_pos
d5 = ($c,$d) or ($e,$f) - solidity type bit (L/R/B or top)
a3 = delta-x for next location to check if current one is empty
a4 = pointer to angle buffer
returns relevant block ID in (a1)
returns distance to left/right in d1
returns angle in (a4)
d5 = ($c,$d) or ($e,$f) - solidity type bit (L/R/B or top)
returns relevant block ID in (a1)
returns distance in d1
TODO: Check left/right/bottom solid bit
let d2 = negate ((v ^. _y `shiftR` 8) + 8)
d0 = (d3 + 0x10) & 0x20;
if((char)d0 == 0)
goto loc_1AF5A;
DONE THIS WAY FOR ACCURACY
}
else
goto loc_1AF7C;
unless onobject
pure ()
startTicks <- ticks
downPressed =
upPressed =
isPressed KeycodeUp
V2 o' p' | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
import qualified Codec.Compression.Kosinski as Kosinski
import Control.Lens
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import Data.Array.Bounded
import Data.Array.Bounded ((!))
import Data.Bits
import qualified Data.ByteString as BS
import Data.ByteString.Lens
import Data.Halves (collectHalves)
import Data.Int
import Data.Maybe (fromMaybe)
import Data.Semigroup ((<>))
import Data.Time (diffUTCTime, getCurrentTime)
import Data.Word
import Foreign.C.Types (CInt)
import Game.Sega.Sonic.Animation
import Game.Sega.Sonic.Blocks
import Game.Sega.Sonic.Chunks
import Game.Sega.Sonic.Collision
import Game.Sega.Sonic.Error
import Game.Sega.Sonic.Game
import Game.Sega.Sonic.Layout
import Game.Sega.Sonic.Offsets as Offsets
import Game.Sega.Sonic.Palette
import Game.Sega.Sonic.Player
import Game.Sega.Sonic.Sine
import Game.Sega.Sonic.SpriteMappings
import Game.Sega.Sonic.Sprites
import Game.Sega.Sonic.Tiles
import SDL
import Sega.MegaDrive.Palette
import Numeric
import Debug.Trace
decompressFile :: (HasRom g, MonadReader g m, MonadError SonicError m, MonadIO m) => Offset -> m BS.ByteString
decompressFile offset = do
maybeContent <- Kosinski.compressed <$> sliceRom offset
content <- maybe (throwError $ SonicLoadError offset) pure maybeContent
maybe (throwError $ SonicDecompressionError offset) pure $ Kosinski.decompress content
frameRate :: Double
frameRate =
60
class HasLevel s where
layout :: s -> [[Word8]]
chunkBlocks :: s -> BoundedArray Word8 (BoundedArray Word8 ChunkBlock)
data LevelData
= LevelData AngleData [[Word8]] (BoundedArray Word8 (BoundedArray Word8 ChunkBlock))
instance HasAngleData LevelData where
angleData (LevelData a _ _) =
a
instance HasLevel LevelData where
layout (LevelData _ a _) =
a
chunkBlocks (LevelData _ _ a) =
a
findTile :: (HasLevel s, MonadReader s m) => V2 CInt -> m Word16
findTile p = do
layout' <- asks layout
let
p' =
p ^. pixels
V2 layoutX layoutY =
(`div` 0x80) <$> p'
chunkIndex =
layout' !! fromIntegral layoutY !! fromIntegral layoutX
blockIndex =
fromIntegral chunkIndex * (0x80 :: Word16)
+ fromIntegral (p' ^. _y .&. 0x70)
+ fromIntegral (p' ^. _x .&. 0xE)
pure blockIndex
data WallDist
= WallDist Word16 CInt Word8
deriving (Eq, Ord, Show)
Scans horizontally for up to 2 16x16 blocks to find solid walls .
d3 = x_pos
d6 = $ 0000 for no flip , $ 0400 for horizontal flip
findWall :: (HasLevel s, MonadReader s m) => V2 CInt -> CInt -> m WallDist
findWall p delta = do
blockIndex <- findTile p
if blockIndex .&. 0x3FF == 0
then do
WallDist a1 d1 a4 <- findWall2 (p & _x +~ delta)
dist & distance + ~ 0x10
pure $ WallDist a1 (d1 + 0x10) a4
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
findWall2 :: (HasLevel s, MonadReader s m) => V2 CInt -> m WallDist
findWall2 p = do
blockIndex <- (.&. 0x3FF) <$> findTile p
if blockIndex == 0
then do
let
d1 =
0xF - (p ^. _x .&. 0xF)
pure $ WallDist blockIndex d1 0
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
findFloor :: (HasLevel s, MonadReader s m) => V2 CInt -> CInt -> m WallDist
findFloor p delta = do
blockIndex <- (.&. 0x3FF) <$> findTile p
let d5 = 0xC
if blockIndex == 0 || not (testBit blockIndex d5)
then do
WallDist a1 d1 a4 <- findFloor2 (p & _y +~ delta)
dist & distance + ~ 0x10
pure $ WallDist a1 (d1 + 0x10) a4
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
findFloor2 :: (HasLevel s, MonadReader s m) => V2 CInt -> m WallDist
findFloor2 p = do
blockIndex <- (.&. 0x3FF) <$> findTile p
let d5 = 0xC
if blockIndex == 0 || not (testBit blockIndex d5)
then do
let
d1 =
0xF - (p ^. _y .&. 0xF)
pure $ WallDist blockIndex d1 0
else do
let
d1 =
0
a4 =
0
pure $ WallDist blockIndex d1 a4
Checks a 16x16 block to find solid walls . May check an additional
16x16 block up for walls .
returns angle in d3 , or zero if angle was odd
checkLeftWallDist :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkLeftWallDist = do
p <- use (player . position)
findWall p (-0x10)
checkRightWallDist :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkRightWallDist = do
p <- use (player . position)
findWall p (0x10)
checkCeiling :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkCeiling = do
p <- use (player . position)
findFloor p (-0x10)
checkFloor :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m WallDist
checkFloor = do
p <- use (player . position)
findFloor p 0x10
hitLeftWall :: (HasLevel r, MonadReader r m, HasPlayer s, MonadState s m) => m ()
hitLeftWall = do
WallDist _ d1 _ <- checkLeftWallDist
traceShow ("hitLeftWall", d1) $ pure ()
if d1 >= 0
then hitCeiling
else do
player . position . _x -= d1
player . playerVelocity . _x .= 0
y_vel <- use (player . playerVelocity . _y)
player . playerInertia .= y_vel
hitCeiling :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitCeiling = do
WallDist _ d1 _ <- checkCeiling
traceShow ("hitCeiling", d1) $ pure ()
if d1 >= 0
then hitFloor
else do
player . position . _y -= d1
y_vel <- use (player . playerVelocity . _y)
when (y_vel < 0) $
player . playerVelocity . _y .= 0
hitFloor :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitFloor = do
y_vel <- use (player . playerVelocity . _y)
unless (y_vel < 0) $ do
WallDist _ d1 d3 <- checkFloor
traceShow ("hitFloor", d1) $ pure ()
when (d1 < 0) $ do
player . position . _y += d1
player . playerAngle .= d3
resetOnFloor
player . playerVelocity . _y .= 0
x_vel <- use (player . playerVelocity . _x)
player . playerInertia .= x_vel
hitCeilingAndWalls :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitCeilingAndWalls = do
WallDist _ d1 _ <- checkLeftWallDist
when (d1 < 0) $ do
player . position . _x -= d1
player . playerVelocity . _x .= 0
WallDist _ d1' _ <- checkRightWallDist
when (d1' < 0) $ do
player . position . _x += d1
player . playerVelocity . _x .= 0
WallDist _ d1'' d3 <- checkCeiling
when (d1'' < 0) $ do
player . position . _y -= d1''
let d0 = (d3 + 0x20) .&. 0x40
if (d0 /= 0)
then do
player . playerAngle .= d3
resetOnFloor
y_vel <- use (player . playerVelocity . _y)
player . playerInertia .= y_vel
inertia <- use (player . playerInertia)
unless (d3 < 0) $
player . playerInertia .= (-inertia)
else player . playerVelocity . _y .= 0;
hitRightWall :: (HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
hitRightWall = do
WallDist _ d1 _ <- checkRightWallDist
traceShow ("hitRightWall", d1) $ pure ()
if d1 >= 0
then hitCeiling
else do
player . position . _x += d1
player . playerVelocity . _x .= 0
y_vel <- use (player . playerVelocity . _y)
player . playerInertia .= y_vel
doLevelCollision :: (HasAngleData g, HasLevel g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
doLevelCollision = do
v <- use (player . playerVelocity)
a <- calcAngle v
traceShow ("doLevelCollision", (a - 0x20) .&. 0xC0) $ pure ()
case (a - 0x20) .&. 0xC0 of
0x40 -> hitLeftWall
0x80 -> hitCeilingAndWalls
0xC0 -> hitRightWall
_ -> do
WallDist _ d1 _ <- checkLeftWallDist
when (d1 < 0) $ do
p->x_pos -= d1 ;
p->x_vel = 0 ;
traceShow "TODO" $ pure ()
WallDist _ d1' _ <- checkLeftWallDist
when (d1' < 0) $ do
p->x_pos + = d1 ;
p->x_vel = 0 ;
traceShow "TODO" $ pure ()
WallDist _ d1'' d3 <- checkFloor
unless (d1'' < 0) $ do
v <- use (player . playerVelocity)
player . position . _y += d1''
player . playerAngle .= d3
resetOnFloor
p->y_vel > > = 1 ;
p->y_vel |= 0x80000000 ;
p->y_vel > > = 1 ;
Subroutine to change Sonic 's angle as he walks along the floor
sonicAngle :: (Applicative m) => Word8 -> m ()
sonicAngle _ =
pure ()
anglePos :: (HasLevel g, HasAngleData g, MonadReader g m, HasPlayer s, MonadState s m) => m ()
anglePos = do
a <- use (player . playerAngle)
let
a' =
if a + 0x20 >= 0
then (if a < 0 then a + 1 else a) + 0x1F
else error "angle pos 1"
case (a' + 0x20) .&. 0xC0 of
0x40 -> pure ()
0x80 -> pure ()
0xC0 -> pure ()
_ -> do
p <- use (player . position)
r <- use (player . playerRadius)
WallDist _ d1 a4 <- findFloor (p + r) 0x10
sonicAngle a4
unless (d1 == 0) $ do
if d1 >= 0
then do
v <- use (player . playerVelocity)
let d0 = min 0xE (abs (v ^. _x `shiftR` 8) + 4)
if d1 > fromIntegral d0
then player . statuses . mdAir .= MdAirOn
player . status & = 0xDF
else player . position . _y += d1
else
unless (d1 < (-0xE)) $
player . position . _y += d1
x :: (HasLevel g, MonadReader g m) => V2 CInt -> m WallDist
x p = do
l <- asks layout
c <- asks chunkBlocks
let
reindexedCollisionBlocks =
undefined
reindexedCurves =
undefined
V2 layoutX layoutY =
(`div` 0x80) <$> p
chunkIndex =
l !! fromIntegral layoutY !! fromIntegral layoutX
V2 blockX blockY =
((`div` 0x10) . (`rem` 0x80)) <$> p
ChunkBlock blockIndex flipX flipY =
(c ! chunkIndex) ! fromIntegral ((blockY * 8) + blockX)
V2 pixelX pixelY =
(`rem` 0x10) <$> p
CollisionBlock heights =
reindexedCollisionBlocks ! blockIndex
angle' =
(if flipX then negate else id) $ reindexedCurves ! blockIndex
flip' flag n =
if flag then 0xF - n else n
height =
fromMaybe 0 (heights ! fromIntegral (flip' flipX pixelX))
heightDifference =
(0x10 - flip' flipY pixelY) - (fromIntegral height + 2)
pure $ WallDist blockIndex heightDifference angle'
loadAndRun :: (MonadReader Game m, MonadError SonicError m, MonadIO m) => m ()
loadAndRun = do
sonicMappings <- loadSpriteMappings sonicOffsets
tailsMappings <- loadSpriteMappings tailsOffsets
curves <- listArrayFill 0 . BS.unpack <$> sliceRom curveAndResistanceMapping
sonicAnimationScript <- loadAnimation . BS.unpack <$> sliceRom animationSonicWait
tailsAnimationScript <- loadAnimation . BS.unpack <$> sliceRom animationTailsWait
let offsets = ehz1
maybeSonicPalette <- readPalette <$> sliceRom paletteSonic
maybePalette <- readPalette <$> sliceRom (levelPaletteOffset offsets)
palette <- maybe (throwError . SonicPaletteError $ levelPaletteOffset offsets) (pure . loadPalette) (maybeSonicPalette <> maybePalette)
tileContent <- decompressFile $ levelArtOffset offsets
tileSurfaces <- loadTiles tileContent
blockContent <- decompressFile $ levelBlocksOffset offsets
blockTextures <- loadBlocks palette tileSurfaces blockContent
chunkContent <- decompressFile $ levelChunksOffset offsets
let chunkBlocks = loadChunks chunkContent
chunkTextures <- traverse (loadChunkTexture blockTextures) chunkBlocks
layoutContent <- decompressFile $ levelLayoutOffset offsets
let
layout =
loadLayout layoutContent
layoutChunkTextures =
mapChunkTextures chunkTextures layout
collisionIndexContent <- decompressFile $ levelCollisionOffset offsets
collisionIndex <- loadCollisionIndex collisionIndexContent
collisionContent <- sliceRom collisionArray1
let collisionBlocks = loadCollisionBlocks collisionContent
collisionBlockTextures <- traverse loadCollisionTexture collisionBlocks
let reindexedCollisionTextures = (collisionBlockTextures !) <$> collisionIndex
reindexedCollisionBlocks = (collisionBlocks !) <$> collisionIndex
reindexedCurves = (curves !) <$> collisionIndex
now <- liftIO getCurrentTime
chunksContent <- decompressFile $ levelChunksOffset offsets
liftIO $ putStrLn "Loading chunks..."
let chunksBlocks = loadChunks chunksContent
chunksTextures <- traverse (loadChunkTexture reindexedCollisionTextures) chunksBlocks
now' <- liftIO getCurrentTime
liftIO . putStrLn $ "Chunks loaded in " <> show (diffUTCTime now' now)
sineData' <- SineData . listArrayFill 0 . fmap fromIntegral . view (unpackedBytes . collectHalves) <$> sliceRom Offsets.sineData
angleData' <- AngleData . listArrayFill 0 . fmap fromIntegral . view (unpackedBytes . collectHalves) <$> sliceRom Offsets.angleData
let
collisionTextures = mapChunkTextures chunksTextures layout
levelData = LevelData angleData' layout chunkBlocks
startPos <- sliceRom $ levelStartPos ehz1
let
playerStart =
case (startPos ^. unpackedBytes . collectHalves) of
[x, y] ->
V2 (fromIntegral x) (fromIntegral y)
_ ->
V2 0 0
r <- view renderer
rendererRenderTarget r $= Nothing
let
playerSprite =
Sprite sonicMappings (V2 0 0) sonicAnimationScript emptyAnimationState
render textures (V2 o p) =
ifor_ textures $ \y row ->
ifor_ row $ \x texture ->
let
rectangle =
Rectangle (P (V2 ((fromIntegral x * 0x80) - o) ((fromIntegral y * 0x80) - p))) 0x80
in copy r texture Nothing (Just rectangle)
appLoop playerSprite' game = do
events <- pollEvents
let
eventIsPress keycode event =
case eventPayload event of
KeyboardEvent keyboardEvent ->
keyboardEventKeyMotion keyboardEvent == Pressed &&
keysymKeycode (keyboardEventKeysym keyboardEvent) == keycode
_ ->
False
isPressed keycode =
any (eventIsPress keycode) events
qPressed =
isPressed KeycodeQ
jumpPressed =
isPressed KeycodeA || isPressed KeycodeS || isPressed KeycodeD
leftPressed =
isPressed KeycodeLeft
rightPressed =
isPressed KeycodeRight
isPressed KeycodeDown
playerSprite'' =
playerSprite' & position .~ (fromIntegral <$> (game ^. player . position . pixels))
updateGame = do
zoom player $ do
s <- use statuses
traceShow (playerRoutine s) $ pure ()
case playerRoutine s of
MdNormal -> do
if jumpPressed
then runReaderT jump sineData'
else do
if rightPressed
then moveRight
else when leftPressed moveLeft
when (not rightPressed && not leftPressed) settle
objectMove
traction
runReaderT anglePos levelData
MdAir -> do
objectMoveAndFall
runReaderT doLevelCollision levelData
MdRoll ->
pure ()
MdJump -> do
objectMoveAndFall
runReaderT doLevelCollision levelData
p' <- use (player . position . pixels)
game' =
execState updateGame game
rendererDrawColor r $= V4 0 0 0 0xFF
clear r
render layoutChunkTextures (game' ^. camera)
runReaderT (renderSprite playerSprite'') game'
present r
delay 16
unless qPressed (appLoop (stepSprite playerSprite'') game')
game <- ask
appLoop playerSprite (game & player . position . pixels .~ playerStart)
main :: IO ()
main = do
rom' <- BS.readFile "sonic2.md"
window <- createWindow "Sonic 2" defaultWindow { windowInitialSize = V2 320 224 }
renderer' <- createRenderer window (-1) defaultRenderer
rendererLogicalSize renderer' $= Just (V2 320 224)
e <- runReaderT (runExceptT loadAndRun) (Game renderer' 0 rom' $ Player (V2 0 0) (V2 0 0) (V2 0 0x13) normalTopSpeed normalAcceleration normalDeceleration 0 0 initialStatuses)
either print pure e
|
15731c82eb7375f648ce71a041ddb569e510392298bad15098baf55a2485eeb4 | bsansouci/reasonglexampleproject | gui.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1999 - 2004 ,
Institut National de Recherche en Informatique et en Automatique .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : gui.ml , v 1.27 2008/02/19 12:44:04 furuse Exp $
open Gdk
open GDraw
open GMain
let () = ignore @@ GMain.Main.init ()
let active = ref true
let sync () = while Glib.Main.iteration false do () done
let window = GWindow.window ~title : " liv " ~allow_shrink : true : true ( )
let window = GWindow.window ~title: "liv" ()
(* We should not set allow_shrink and allow_grow here. *)
let () =
ignore @@ window#connect#destroy ~callback:Main.quit;
window#misc#set_size_request ~width: 1 ~height: 1 ();
window#resize ~width: 1 ~height: 1;
window#misc#set_app_paintable true
let drawing = window
let fixed = GPack.fixed ~packing: window#add ~show: true ()
(*
let drawing =
GMisc.drawing_area
~width:150 ~height:150
~packing: window#add ~show:true ()
*)
(* let fixed = GPack.fixed ~packing: box#add () *)
window#event#connect#configure ( fun ev - >
prerr_endline ( Printf.sprintf " Configure % dx%d+%d+%d "
( GdkEvent.Configure.width ev )
( GdkEvent.Configure.height ev )
( GdkEvent . Configure.x ev )
( GdkEvent . Configure.y ev ) ) ;
false ( * continue configure event handling
window#event#connect#configure (fun ev ->
prerr_endline (Printf.sprintf "Configure %dx%d+%d+%d"
(GdkEvent.Configure.width ev)
(GdkEvent.Configure.height ev)
(GdkEvent.Configure.x ev)
(GdkEvent.Configure.y ev));
false (* continue configure event handling *))
*)
class new_progress_bar obj = object
inherit GRange.progress_bar obj as super
val mutable previous = 0.0
method! set_fraction x =
let x = floor (x *. 10.0) /. 10.0 in
if x <> previous then begin
super#set_fraction x; sync (); previous <- x
end
end
let new_progress_bar =
GtkRange.ProgressBar.make_params []
~cont:(fun pl ?packing ?show () ->
GObj.pack_return
(new new_progress_bar (GtkRange.ProgressBar.create pl))
~packing ~show)
let prog_on_image = true
class prog_nop = object
method map () = ()
method unmap () = ()
method set_text (_s : string) = ()
method set_fraction (_s : float) = ()
end
class prog (p : GRange.progress_bar) = object
method map () = fixed#misc#map ()
method unmap () = fixed#misc#unmap ()
method set_text = p#set_text
method set_fraction = p#set_fraction
end
let prog1 =
if prog_on_image then
let p =
new_progress_bar ~packing: (fixed#put ~x:0 ~y:0) ()
in
new prog p
else (new prog_nop :> prog)
let visual = window#misc#visual
let screen_width = Screen.width ()
let screen_height = Screen.height ()
let colormap = Gdk.Color.get_system_colormap ()
let quick_color_create = Truecolor.color_creator visual
let quick_color_parser = Truecolor.color_parser visual
let root_win = Window.root_parent ()
let root_size = Drawable.get_size root_win
let drawing_root = new drawable root_win
let infowindow = GWindow.window ~title:"liv info" ~width:300 ~height:150 ()
let () =
infowindow#misc#set_size_request ~width: 300 ~height: 150 ();
infowindow#resize ~width: 300 ~height: 150;
ignore @@ infowindow#connect#destroy ~callback:Main.quit;
()
let imglbox0 = GPack.vbox ~packing:infowindow#add ()
let imglbox = GPack.hbox ~packing:imglbox0#add ()
let sb = GRange.scrollbar `VERTICAL
~packing:(imglbox#pack ~from:`END ~expand:false) ()
let imglist =
((GList.clist ~shadow_type:`OUT
~columns: 1 ~packing: imglbox#add ~vadjustment:sb#adjustment ())
: string GList.clist)
let () = imglist#misc#set_size_request ~width:300 ~height: 150 ()
let prog2 = GRange.progress_bar ~packing: (imglbox0#pack ~expand: false) ()
class progs = object
method map = prog1#map
method unmap = prog1#unmap
method set_format_string s =
prog1#set_text s;
prog2#set_text s
method set_fraction s =
prog1#set_fraction s;
prog2#set_fraction s
end
let prog = new progs
let () = sync()
| null | https://raw.githubusercontent.com/bsansouci/reasonglexampleproject/4ecef2cdad3a1a157318d1d64dba7def92d8a924/vendor/camlimages/examples/liv/gui.ml | ocaml | *********************************************************************
Objective Caml
Distributed only by permission.
*********************************************************************
We should not set allow_shrink and allow_grow here.
let drawing =
GMisc.drawing_area
~width:150 ~height:150
~packing: window#add ~show:true ()
let fixed = GPack.fixed ~packing: box#add ()
continue configure event handling | , projet Cristal , INRIA Rocquencourt
Copyright 1999 - 2004 ,
Institut National de Recherche en Informatique et en Automatique .
$ I d : gui.ml , v 1.27 2008/02/19 12:44:04 furuse Exp $
open Gdk
open GDraw
open GMain
let () = ignore @@ GMain.Main.init ()
let active = ref true
let sync () = while Glib.Main.iteration false do () done
let window = GWindow.window ~title : " liv " ~allow_shrink : true : true ( )
let window = GWindow.window ~title: "liv" ()
let () =
ignore @@ window#connect#destroy ~callback:Main.quit;
window#misc#set_size_request ~width: 1 ~height: 1 ();
window#resize ~width: 1 ~height: 1;
window#misc#set_app_paintable true
let drawing = window
let fixed = GPack.fixed ~packing: window#add ~show: true ()
window#event#connect#configure ( fun ev - >
prerr_endline ( Printf.sprintf " Configure % dx%d+%d+%d "
( GdkEvent.Configure.width ev )
( GdkEvent.Configure.height ev )
( GdkEvent . Configure.x ev )
( GdkEvent . Configure.y ev ) ) ;
false ( * continue configure event handling
window#event#connect#configure (fun ev ->
prerr_endline (Printf.sprintf "Configure %dx%d+%d+%d"
(GdkEvent.Configure.width ev)
(GdkEvent.Configure.height ev)
(GdkEvent.Configure.x ev)
(GdkEvent.Configure.y ev));
*)
class new_progress_bar obj = object
inherit GRange.progress_bar obj as super
val mutable previous = 0.0
method! set_fraction x =
let x = floor (x *. 10.0) /. 10.0 in
if x <> previous then begin
super#set_fraction x; sync (); previous <- x
end
end
let new_progress_bar =
GtkRange.ProgressBar.make_params []
~cont:(fun pl ?packing ?show () ->
GObj.pack_return
(new new_progress_bar (GtkRange.ProgressBar.create pl))
~packing ~show)
let prog_on_image = true
class prog_nop = object
method map () = ()
method unmap () = ()
method set_text (_s : string) = ()
method set_fraction (_s : float) = ()
end
class prog (p : GRange.progress_bar) = object
method map () = fixed#misc#map ()
method unmap () = fixed#misc#unmap ()
method set_text = p#set_text
method set_fraction = p#set_fraction
end
let prog1 =
if prog_on_image then
let p =
new_progress_bar ~packing: (fixed#put ~x:0 ~y:0) ()
in
new prog p
else (new prog_nop :> prog)
let visual = window#misc#visual
let screen_width = Screen.width ()
let screen_height = Screen.height ()
let colormap = Gdk.Color.get_system_colormap ()
let quick_color_create = Truecolor.color_creator visual
let quick_color_parser = Truecolor.color_parser visual
let root_win = Window.root_parent ()
let root_size = Drawable.get_size root_win
let drawing_root = new drawable root_win
let infowindow = GWindow.window ~title:"liv info" ~width:300 ~height:150 ()
let () =
infowindow#misc#set_size_request ~width: 300 ~height: 150 ();
infowindow#resize ~width: 300 ~height: 150;
ignore @@ infowindow#connect#destroy ~callback:Main.quit;
()
let imglbox0 = GPack.vbox ~packing:infowindow#add ()
let imglbox = GPack.hbox ~packing:imglbox0#add ()
let sb = GRange.scrollbar `VERTICAL
~packing:(imglbox#pack ~from:`END ~expand:false) ()
let imglist =
((GList.clist ~shadow_type:`OUT
~columns: 1 ~packing: imglbox#add ~vadjustment:sb#adjustment ())
: string GList.clist)
let () = imglist#misc#set_size_request ~width:300 ~height: 150 ()
let prog2 = GRange.progress_bar ~packing: (imglbox0#pack ~expand: false) ()
class progs = object
method map = prog1#map
method unmap = prog1#unmap
method set_format_string s =
prog1#set_text s;
prog2#set_text s
method set_fraction s =
prog1#set_fraction s;
prog2#set_fraction s
end
let prog = new progs
let () = sync()
|
6a4479af50d12710d7934a61c53839b2aed52e1abdaf9f841a71a699885672b7 | spurious/sagittarius-scheme-mirror | vector.scm | (import (rnrs)
(util vector)
(srfi :64))
(test-begin "Vector utilities")
(test-equal '#(1 3 5) (vector-filter odd? '#(1 2 3 4 5)))
(test-equal '#(1 3 5) (vector-remove even? '#(1 2 3 4 5)))
(test-equal '(1) (vector-find (lambda (e) (equal? '(1) e)) '#(1 2 (1) (2))))
(test-end)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/tests/util/vector.scm | scheme | (import (rnrs)
(util vector)
(srfi :64))
(test-begin "Vector utilities")
(test-equal '#(1 3 5) (vector-filter odd? '#(1 2 3 4 5)))
(test-equal '#(1 3 5) (vector-remove even? '#(1 2 3 4 5)))
(test-equal '(1) (vector-find (lambda (e) (equal? '(1) e)) '#(1 2 (1) (2))))
(test-end)
|
|
bb2415b1c0fd26ed68ebdf3872772925186943362d2483930d628f115679247a | avsm/eeww | aliases.ml | (* TEST
* expect
*)
module C = Char;;
C.chr 66;;
module C' : module type of Char = C;;
C'.chr 66;;
module C3 = struct include Char end;;
C3.chr 66;;
[%%expect{|
module C = Char
- : char = 'B'
module C' :
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
- : char = 'B'
module C3 :
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
- : char = 'B'
|}];;
let f x = let module M = struct module L = List end in M.L.length x;;
let g x = let module L = List in L.length (L.map succ x);;
[%%expect{|
val f : 'a list -> int = <fun>
val g : int list -> int = <fun>
|}];;
module F(X:sig end) = Char;;
module C4 = F(struct end);;
C4.chr 66;;
[%%expect{|
module F :
functor (X : sig end) ->
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
module C4 :
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
- : char = 'B'
|}];;
module G(X:sig end) = struct module M = X end;; (* does not alias X *)
module M = G(struct end);;
[%%expect{|
module G : functor (X : sig end) -> sig module M : sig end end
module M : sig module M : sig end end
|}];;
module M' = struct
module N = struct let x = 1 end
module N' = N
end;;
M'.N'.x;;
[%%expect{|
module M' : sig module N : sig val x : int end module N' = N end
- : int = 1
|}];;
module M'' : sig module N' : sig val x : int end end = M';;
M''.N'.x;;
module M2 = struct include M' end;;
module M3 : sig module N' : sig val x : int end end = struct include M' end;;
M3.N'.x;;
module M3' : sig module N' : sig val x : int end end = M2;;
M3'.N'.x;;
[%%expect{|
module M'' : sig module N' : sig val x : int end end
- : int = 1
module M2 : sig module N = M'.N module N' = N end
module M3 : sig module N' : sig val x : int end end
- : int = 1
module M3' : sig module N' : sig val x : int end end
- : int = 1
|}];;
module M4 : sig module N' : sig val x : int end end = struct
module N = struct let x = 1 end
module N' = N
end;;
M4.N'.x;;
[%%expect{|
module M4 : sig module N' : sig val x : int end end
- : int = 1
|}];;
module F(X:sig end) = struct
module N = struct let x = 1 end
module N' = N
end;;
module G : functor(X:sig end) -> sig module N' : sig val x : int end end = F;;
module M5 = G(struct end);;
M5.N'.x;;
[%%expect{|
module F :
functor (X : sig end) ->
sig module N : sig val x : int end module N' = N end
module G : functor (X : sig end) -> sig module N' : sig val x : int end end
module M5 : sig module N' : sig val x : int end end
- : int = 1
|}];;
module M = struct
module D = struct let y = 3 end
module N = struct let x = 1 end
module N' = N
end;;
module M1 : sig module N : sig val x : int end module N' = N end = M;;
M1.N'.x;;
module M2 : sig module N' : sig val x : int end end =
(M : sig module N : sig val x : int end module N' = N end);;
M2.N'.x;;
open M;;
N'.x;;
[%%expect{|
module M :
sig
module D : sig val y : int end
module N : sig val x : int end
module N' = N
end
module M1 : sig module N : sig val x : int end module N' = N end
- : int = 1
module M2 : sig module N' : sig val x : int end end
- : int = 1
- : int = 1
|}];;
module M = struct
module C = Char
module C' = C
end;;
module M1
: sig module C : sig val escaped : char -> string end module C' = C end
= M;; (* sound, but should probably fail *)
M1.C'.escaped 'A';;
module M2 : sig module C' : sig val chr : int -> char end end =
(M : sig module C : sig val chr : int -> char end module C' = C end);;
M2.C'.chr 66;;
[%%expect{|
module M : sig module C = Char module C' = C end
module M1 :
sig module C : sig val escaped : char -> string end module C' = C end
- : string = "A"
module M2 : sig module C' : sig val chr : int -> char end end
- : char = 'B'
|}];;
StdLabels.List.map;;
[%%expect{|
- : f:('a -> 'b) -> 'a list -> 'b list = <fun>
|}];;
module Q = Queue;;
exception QE = Q.Empty;;
try Q.pop (Q.create ()) with QE -> "Ok";;
[%%expect{|
module Q = Queue
exception QE
- : string = "Ok"
|}];;
module type Complex = module type of Complex with type t = Complex.t;;
module M : sig module C : Complex end = struct module C = Complex end;;
module C = Complex;;
C.one.Complex.re;;
include C;;
[%%expect{|
module type Complex =
sig
type t = Complex.t = { re : float; im : float; }
val zero : t
val one : t
val i : t
val neg : t -> t
val conj : t -> t
val add : t -> t -> t
val sub : t -> t -> t
val mul : t -> t -> t
val inv : t -> t
val div : t -> t -> t
val sqrt : t -> t
val norm2 : t -> float
val norm : t -> float
val arg : t -> float
val polar : float -> float -> t
val exp : t -> t
val log : t -> t
val pow : t -> t -> t
end
module M : sig module C : Complex end
module C = Complex
- : float = 1.
type t = Complex.t = { re : float; im : float; }
val zero : t = {re = 0.; im = 0.}
val one : t = {re = 1.; im = 0.}
val i : t = {re = 0.; im = 1.}
val neg : t -> t = <fun>
val conj : t -> t = <fun>
val add : t -> t -> t = <fun>
val sub : t -> t -> t = <fun>
val mul : t -> t -> t = <fun>
val inv : t -> t = <fun>
val div : t -> t -> t = <fun>
val sqrt : t -> t = <fun>
val norm2 : t -> float = <fun>
val norm : t -> float = <fun>
val arg : t -> float = <fun>
val polar : float -> float -> t = <fun>
val exp : t -> t = <fun>
val log : t -> t = <fun>
val pow : t -> t -> t = <fun>
|}];;
module F(X:sig module C = Char end) = struct module C = X.C end;;
[%%expect{|
module F : functor (X : sig module C = Char end) -> sig module C = Char end
|}];;
(* Applicative functors *)
module S = String
module StringSet = Set.Make(String)
module SSet = Set.Make(S);;
let f (x : StringSet.t) = (x : SSet.t);;
[%%expect{|
module S = String
module StringSet :
sig
type elt = String.t
type t = Set.Make(String).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
module SSet :
sig
type elt = S.t
type t = Set.Make(S).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
val f : StringSet.t -> SSet.t = <fun>
|}];;
Also using include ( cf . 's mail 2013 - 11 - 16 )
module F (M : sig end) : sig type t end = struct type t = int end
module T = struct
module M = struct end
include F(M)
end;;
include T;;
let f (x : t) : T.t = x ;;
[%%expect{|
module F : functor (M : sig end) -> sig type t end
module T : sig module M : sig end type t = F(M).t end
module M = T.M
type t = F(M).t
val f : t -> T.t = <fun>
|}];;
PR#4049
(* This works thanks to abbreviations *)
module A = struct
module B = struct type t let compare x y = 0 end
module S = Set.Make(B)
let empty = S.empty
end
module A1 = A;;
A1.empty = A.empty;;
[%%expect{|
module A :
sig
module B : sig type t val compare : 'a -> 'b -> int end
module S :
sig
type elt = B.t
type t = Set.Make(B).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
val empty : S.t
end
module A1 = A
- : bool = true
|}];;
PR#3476 :
module FF(X : sig end) = struct type t end
module M = struct
module X = struct end
module Y = FF (X)
type t = Y.t
end
module F (Y : sig type t end) (M : sig type t = Y.t end) = struct end;;
module G = F (M.Y);;
module N = G (M);;
module N = F (M.Y) (M);;
[%%expect{|
module FF : functor (X : sig end) -> sig type t end
module M :
sig module X : sig end module Y : sig type t = FF(X).t end type t = Y.t end
module F : functor (Y : sig type t end) (M : sig type t = Y.t end) -> sig end
module G : functor (M : sig type t = M.Y.t end) -> sig end
module N : sig end
module N : sig end
|}];;
PR#5058
module F (M : sig end) : sig type t end = struct type t = int end
module T = struct
module M = struct end
include F(M)
end
include T
let f (x : t) : T.t = x
[%%expect {|
module F : functor (M : sig end) -> sig type t end
module T : sig module M : sig end type t = F(M).t end
module M = T.M
type t = F(M).t
val f : t -> T.t = <fun>
|}]
(* PR#6307 *)
module A1 = struct end
module A2 = struct end
module L1 = struct module X = A1 end
module L2 = struct module X = A2 end;;
module F (L : (module type of L1 [@remove_aliases])) = struct end;;
module F1 = F(L1);; (* ok *)
module F2 = F(L2);; (* should succeed too *)
[%%expect{|
module A1 : sig end
module A2 : sig end
module L1 : sig module X = A1 end
module L2 : sig module X = A2 end
module F : functor (L : sig module X : sig end end) -> sig end
module F1 : sig end
module F2 : sig end
|}];;
(* Counter example: why we need to be careful with PR#6307 *)
module Int = struct type t = int let compare = compare end
module SInt = Set.Make(Int)
type (_,_) eq = Eq : ('a,'a) eq
type wrap = W of (SInt.t, SInt.t) eq
module M = struct
module I = Int
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
end;;
module type S = module type of M [@remove_aliases];; (* keep alias *)
module Int2 = struct type t = int let compare x y = compare y x end;;
module type S' = sig
module I = Int2
include S with module I := I
end;; (* fail *)
[%%expect{|
module Int : sig type t = int val compare : 'a -> 'a -> int end
module SInt :
sig
type elt = Int.t
type t = Set.Make(Int).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
type (_, _) eq = Eq : ('a, 'a) eq
type wrap = W of (SInt.t, SInt.t) eq
module M :
sig
module I = Int
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
end
module type S =
sig
module I = Int
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
end
module Int2 : sig type t = int val compare : 'a -> 'a -> int end
Line 15, characters 10-30:
15 | include S with module I := I
^^^^^^^^^^^^^^^^^^^^
Error: In this `with' constraint, the new definition of I
does not match its original definition in the constrained signature:
Modules do not match: (module Int2) is not included in (module Int)
|}];;
(* (* if the above succeeded, one could break invariants *)
module rec M2 : S' = M2;; (* should succeed! (but this is bad) *)
let M2.W eq = W Eq;;
let s = List.fold_right SInt.add [1;2;3] SInt.empty;;
module SInt2 = Set.Make(Int2);;
let conv : type a b. (a,b) eq -> a -> b = fun Eq x -> x;;
let s' : SInt2.t = conv eq s;;
SInt2.elements s';;
SInt2.mem 2 s';; (* invariants are broken *)
*)
(* Check behavior with submodules *)
module M = struct
module N = struct module I = Int end
module P = struct module I = N.I end
module Q = struct
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq
end
end;;
module type S = module type of M [@remove_aliases];;
[%%expect{|
module M :
sig
module N : sig module I = Int end
module P : sig module I = N.I end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq end
end
module type S =
sig
module N : sig module I = Int end
module P : sig module I = N.I end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq end
end
|}];;
module M = struct
module N = struct module I = Int end
module P = struct module I = N.I end
module Q = struct
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq
end
end;;
module type S = module type of M [@remove_aliases];;
[%%expect{|
module M :
sig
module N : sig module I = Int end
module P : sig module I = N.I end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq end
end
module type S =
sig
module N : sig module I = Int end
module P :
sig module I : sig type t = int val compare : 'a -> 'a -> int end end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq end
end
|}];;
(* PR#6365 *)
module type S = sig module M : sig type t val x : t end end;;
module H = struct type t = A let x = A end;;
module H' = H;;
module type S' = S with module M = H';; (* shouldn't introduce an alias *)
[%%expect{|
module type S = sig module M : sig type t val x : t end end
module H : sig type t = A val x : t end
module H' = H
module type S' = sig module M : sig type t = H.t = A val x : t end end
|}];;
(* PR#6376 *)
module type Alias = sig module N : sig end module M = N end;;
module F (X : sig end) = struct type t end;;
module type A = Alias with module N := F(List);;
module rec Bad : A = Bad;;
[%%expect{|
module type Alias = sig module N : sig end module M = N end
module F : functor (X : sig end) -> sig type t end
Line 1:
Error: Module type declarations do not match:
module type A = sig module M = F(List) end
does not match
module type A = sig module M = F(List) end
At position module type A = <here>
Module types do not match:
sig module M = F(List) end
is not equal to
sig module M = F(List) end
At position module type A = sig module M : <here> end
Module F(List) cannot be aliased
|}];;
Shinwell 2014 - 04 - 23
module B = struct
module R = struct
type t = string
end
module O = R
end
module K = struct
module E = B
module N = E.O
end;;
let x : K.N.t = "foo";;
[%%expect{|
module B : sig module R : sig type t = string end module O = R end
module K : sig module E = B module N = E.O end
val x : K.N.t = "foo"
|}];;
(* PR#6465 *)
module M = struct type t = A module B = struct type u = B end end;;
module P : sig type t = M.t = A module B = M.B end = M;;
module P : sig type t = M.t = A module B = M.B end = struct include M end;;
[%%expect{|
module M : sig type t = A module B : sig type u = B end end
module P : sig type t = M.t = A module B = M.B end
module P : sig type t = M.t = A module B = M.B end
|}];;
module type S = sig
module M : sig module P : sig end end
module Q = M
end;;
[%%expect{|
module type S = sig module M : sig module P : sig end end module Q = M end
|}];;
module type S = sig
module M : sig module N : sig end module P : sig end end
module Q : sig module N = M.N module P = M.P end
end;;
module R = struct
module M = struct module N = struct end module P = struct end end
module Q = M
end;;
module R' : S = R;;
[%%expect{|
module type S =
sig
module M : sig module N : sig end module P : sig end end
module Q : sig module N = M.N module P = M.P end
end
module R :
sig
module M : sig module N : sig end module P : sig end end
module Q = M
end
module R' : S
|}];;
module F (X : sig end) = struct type t end;;
module M : sig
type a
module Foo : sig
module Bar : sig end
type b = a
end
end = struct
module Foo = struct
module Bar = struct end
type b = F(Bar).t
end
type a = Foo.b
end;;
[%%expect{|
module F : functor (X : sig end) -> sig type t end
module M :
sig type a module Foo : sig module Bar : sig end type b = a end end
|}];;
PR#6578
module M = struct let f x = x end
module rec R : sig module M : sig val f : 'a -> 'a end end =
struct module M = M end;;
R.M.f 3;;
[%%expect{|
module M : sig val f : 'a -> 'a end
module rec R : sig module M : sig val f : 'a -> 'a end end
- : int = 3
|}];;
module rec R : sig module M = M end = struct module M = M end;;
R.M.f 3;;
[%%expect{|
module rec R : sig module M = M end
- : int = 3
|}];;
module M = struct type t end
module type S = sig module N = M val x : N.t end
module type T = S with module N := M;;
[%%expect{|
module M : sig type t end
module type S = sig module N = M val x : N.t end
module type T = sig val x : M.t end
|}];;
module X = struct module N = struct end end
module Y : sig
module type S = sig module N = X.N end
end = struct
module type S = module type of struct include X end
end;;
[%%expect{|
module X : sig module N : sig end end
module Y : sig module type S = sig module N = X.N end end
|}];;
module type S = sig
module M : sig
module A : sig end
module B : sig end
end
module N = M.A
end
module Foo = struct
module B = struct let x = 0 end
module A = struct let x = "hello" end
end
module Bar : S with module M := Foo = struct module N = Foo.A end
let s : string = Bar.N.x
[%%expect {|
module type S =
sig
module M : sig module A : sig end module B : sig end end
module N = M.A
end
module Foo :
sig module B : sig val x : int end module A : sig val x : string end end
module Bar : sig module N = Foo.A end
val s : string = "hello"
|}]
module M : sig
module N : sig
module A : sig val x : string end
module B : sig val x : int end
end
module F (X : sig module A = N.A end) : sig val s : string end
end = struct
module N = struct
module B = struct let x = 0 end
module A = struct let x = "hello" end
end
module F (X : sig module A : sig val x : string end end) = struct
let s = X.A.x
end
end
module N = M.F(struct module A = M.N.A end)
let s : string = N.s
[%%expect {|
module M :
sig
module N :
sig
module A : sig val x : string end
module B : sig val x : int end
end
module F : functor (X : sig module A = N.A end) -> sig val s : string end
end
module N : sig val s : string end
val s : string = "hello"
|}]
| null | https://raw.githubusercontent.com/avsm/eeww/4d65720b5dd51376842ffe5c8c220d5329c1dc10/boot/ocaml/testsuite/tests/typing-modules/aliases.ml | ocaml | TEST
* expect
does not alias X
sound, but should probably fail
Applicative functors
This works thanks to abbreviations
PR#6307
ok
should succeed too
Counter example: why we need to be careful with PR#6307
keep alias
fail
(* if the above succeeded, one could break invariants
should succeed! (but this is bad)
invariants are broken
Check behavior with submodules
PR#6365
shouldn't introduce an alias
PR#6376
PR#6465 |
module C = Char;;
C.chr 66;;
module C' : module type of Char = C;;
C'.chr 66;;
module C3 = struct include Char end;;
C3.chr 66;;
[%%expect{|
module C = Char
- : char = 'B'
module C' :
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
- : char = 'B'
module C3 :
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
- : char = 'B'
|}];;
let f x = let module M = struct module L = List end in M.L.length x;;
let g x = let module L = List in L.length (L.map succ x);;
[%%expect{|
val f : 'a list -> int = <fun>
val g : int list -> int = <fun>
|}];;
module F(X:sig end) = Char;;
module C4 = F(struct end);;
C4.chr 66;;
[%%expect{|
module F :
functor (X : sig end) ->
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
module C4 :
sig
external code : char -> int = "%identity"
val chr : int -> char
val escaped : char -> string
val lowercase_ascii : char -> char
val uppercase_ascii : char -> char
type t = char
val compare : t -> t -> int
val equal : t -> t -> bool
val seeded_hash : int -> t -> int
val hash : t -> int
external unsafe_chr : int -> char = "%identity"
end
- : char = 'B'
|}];;
module M = G(struct end);;
[%%expect{|
module G : functor (X : sig end) -> sig module M : sig end end
module M : sig module M : sig end end
|}];;
module M' = struct
module N = struct let x = 1 end
module N' = N
end;;
M'.N'.x;;
[%%expect{|
module M' : sig module N : sig val x : int end module N' = N end
- : int = 1
|}];;
module M'' : sig module N' : sig val x : int end end = M';;
M''.N'.x;;
module M2 = struct include M' end;;
module M3 : sig module N' : sig val x : int end end = struct include M' end;;
M3.N'.x;;
module M3' : sig module N' : sig val x : int end end = M2;;
M3'.N'.x;;
[%%expect{|
module M'' : sig module N' : sig val x : int end end
- : int = 1
module M2 : sig module N = M'.N module N' = N end
module M3 : sig module N' : sig val x : int end end
- : int = 1
module M3' : sig module N' : sig val x : int end end
- : int = 1
|}];;
module M4 : sig module N' : sig val x : int end end = struct
module N = struct let x = 1 end
module N' = N
end;;
M4.N'.x;;
[%%expect{|
module M4 : sig module N' : sig val x : int end end
- : int = 1
|}];;
module F(X:sig end) = struct
module N = struct let x = 1 end
module N' = N
end;;
module G : functor(X:sig end) -> sig module N' : sig val x : int end end = F;;
module M5 = G(struct end);;
M5.N'.x;;
[%%expect{|
module F :
functor (X : sig end) ->
sig module N : sig val x : int end module N' = N end
module G : functor (X : sig end) -> sig module N' : sig val x : int end end
module M5 : sig module N' : sig val x : int end end
- : int = 1
|}];;
module M = struct
module D = struct let y = 3 end
module N = struct let x = 1 end
module N' = N
end;;
module M1 : sig module N : sig val x : int end module N' = N end = M;;
M1.N'.x;;
module M2 : sig module N' : sig val x : int end end =
(M : sig module N : sig val x : int end module N' = N end);;
M2.N'.x;;
open M;;
N'.x;;
[%%expect{|
module M :
sig
module D : sig val y : int end
module N : sig val x : int end
module N' = N
end
module M1 : sig module N : sig val x : int end module N' = N end
- : int = 1
module M2 : sig module N' : sig val x : int end end
- : int = 1
- : int = 1
|}];;
module M = struct
module C = Char
module C' = C
end;;
module M1
: sig module C : sig val escaped : char -> string end module C' = C end
M1.C'.escaped 'A';;
module M2 : sig module C' : sig val chr : int -> char end end =
(M : sig module C : sig val chr : int -> char end module C' = C end);;
M2.C'.chr 66;;
[%%expect{|
module M : sig module C = Char module C' = C end
module M1 :
sig module C : sig val escaped : char -> string end module C' = C end
- : string = "A"
module M2 : sig module C' : sig val chr : int -> char end end
- : char = 'B'
|}];;
StdLabels.List.map;;
[%%expect{|
- : f:('a -> 'b) -> 'a list -> 'b list = <fun>
|}];;
module Q = Queue;;
exception QE = Q.Empty;;
try Q.pop (Q.create ()) with QE -> "Ok";;
[%%expect{|
module Q = Queue
exception QE
- : string = "Ok"
|}];;
module type Complex = module type of Complex with type t = Complex.t;;
module M : sig module C : Complex end = struct module C = Complex end;;
module C = Complex;;
C.one.Complex.re;;
include C;;
[%%expect{|
module type Complex =
sig
type t = Complex.t = { re : float; im : float; }
val zero : t
val one : t
val i : t
val neg : t -> t
val conj : t -> t
val add : t -> t -> t
val sub : t -> t -> t
val mul : t -> t -> t
val inv : t -> t
val div : t -> t -> t
val sqrt : t -> t
val norm2 : t -> float
val norm : t -> float
val arg : t -> float
val polar : float -> float -> t
val exp : t -> t
val log : t -> t
val pow : t -> t -> t
end
module M : sig module C : Complex end
module C = Complex
- : float = 1.
type t = Complex.t = { re : float; im : float; }
val zero : t = {re = 0.; im = 0.}
val one : t = {re = 1.; im = 0.}
val i : t = {re = 0.; im = 1.}
val neg : t -> t = <fun>
val conj : t -> t = <fun>
val add : t -> t -> t = <fun>
val sub : t -> t -> t = <fun>
val mul : t -> t -> t = <fun>
val inv : t -> t = <fun>
val div : t -> t -> t = <fun>
val sqrt : t -> t = <fun>
val norm2 : t -> float = <fun>
val norm : t -> float = <fun>
val arg : t -> float = <fun>
val polar : float -> float -> t = <fun>
val exp : t -> t = <fun>
val log : t -> t = <fun>
val pow : t -> t -> t = <fun>
|}];;
module F(X:sig module C = Char end) = struct module C = X.C end;;
[%%expect{|
module F : functor (X : sig module C = Char end) -> sig module C = Char end
|}];;
module S = String
module StringSet = Set.Make(String)
module SSet = Set.Make(S);;
let f (x : StringSet.t) = (x : SSet.t);;
[%%expect{|
module S = String
module StringSet :
sig
type elt = String.t
type t = Set.Make(String).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
module SSet :
sig
type elt = S.t
type t = Set.Make(S).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
val f : StringSet.t -> SSet.t = <fun>
|}];;
Also using include ( cf . 's mail 2013 - 11 - 16 )
module F (M : sig end) : sig type t end = struct type t = int end
module T = struct
module M = struct end
include F(M)
end;;
include T;;
let f (x : t) : T.t = x ;;
[%%expect{|
module F : functor (M : sig end) -> sig type t end
module T : sig module M : sig end type t = F(M).t end
module M = T.M
type t = F(M).t
val f : t -> T.t = <fun>
|}];;
PR#4049
module A = struct
module B = struct type t let compare x y = 0 end
module S = Set.Make(B)
let empty = S.empty
end
module A1 = A;;
A1.empty = A.empty;;
[%%expect{|
module A :
sig
module B : sig type t val compare : 'a -> 'b -> int end
module S :
sig
type elt = B.t
type t = Set.Make(B).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
val empty : S.t
end
module A1 = A
- : bool = true
|}];;
PR#3476 :
module FF(X : sig end) = struct type t end
module M = struct
module X = struct end
module Y = FF (X)
type t = Y.t
end
module F (Y : sig type t end) (M : sig type t = Y.t end) = struct end;;
module G = F (M.Y);;
module N = G (M);;
module N = F (M.Y) (M);;
[%%expect{|
module FF : functor (X : sig end) -> sig type t end
module M :
sig module X : sig end module Y : sig type t = FF(X).t end type t = Y.t end
module F : functor (Y : sig type t end) (M : sig type t = Y.t end) -> sig end
module G : functor (M : sig type t = M.Y.t end) -> sig end
module N : sig end
module N : sig end
|}];;
PR#5058
module F (M : sig end) : sig type t end = struct type t = int end
module T = struct
module M = struct end
include F(M)
end
include T
let f (x : t) : T.t = x
[%%expect {|
module F : functor (M : sig end) -> sig type t end
module T : sig module M : sig end type t = F(M).t end
module M = T.M
type t = F(M).t
val f : t -> T.t = <fun>
|}]
module A1 = struct end
module A2 = struct end
module L1 = struct module X = A1 end
module L2 = struct module X = A2 end;;
module F (L : (module type of L1 [@remove_aliases])) = struct end;;
[%%expect{|
module A1 : sig end
module A2 : sig end
module L1 : sig module X = A1 end
module L2 : sig module X = A2 end
module F : functor (L : sig module X : sig end end) -> sig end
module F1 : sig end
module F2 : sig end
|}];;
module Int = struct type t = int let compare = compare end
module SInt = Set.Make(Int)
type (_,_) eq = Eq : ('a,'a) eq
type wrap = W of (SInt.t, SInt.t) eq
module M = struct
module I = Int
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
end;;
module Int2 = struct type t = int let compare x y = compare y x end;;
module type S' = sig
module I = Int2
include S with module I := I
[%%expect{|
module Int : sig type t = int val compare : 'a -> 'a -> int end
module SInt :
sig
type elt = Int.t
type t = Set.Make(Int).t
val empty : t
val add : elt -> t -> t
val singleton : elt -> t
val remove : elt -> t -> t
val union : t -> t -> t
val inter : t -> t -> t
val disjoint : t -> t -> bool
val diff : t -> t -> t
val cardinal : t -> int
val elements : t -> elt list
val min_elt : t -> elt
val min_elt_opt : t -> elt option
val max_elt : t -> elt
val max_elt_opt : t -> elt option
val choose : t -> elt
val choose_opt : t -> elt option
val find : elt -> t -> elt
val find_opt : elt -> t -> elt option
val find_first : (elt -> bool) -> t -> elt
val find_first_opt : (elt -> bool) -> t -> elt option
val find_last : (elt -> bool) -> t -> elt
val find_last_opt : (elt -> bool) -> t -> elt option
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc
val map : (elt -> elt) -> t -> t
val filter : (elt -> bool) -> t -> t
val filter_map : (elt -> elt option) -> t -> t
val partition : (elt -> bool) -> t -> t * t
val split : elt -> t -> t * bool * t
val is_empty : t -> bool
val mem : elt -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val subset : t -> t -> bool
val for_all : (elt -> bool) -> t -> bool
val exists : (elt -> bool) -> t -> bool
val to_list : t -> elt list
val of_list : elt list -> t
val to_seq_from : elt -> t -> elt Seq.t
val to_seq : t -> elt Seq.t
val to_rev_seq : t -> elt Seq.t
val add_seq : elt Seq.t -> t -> t
val of_seq : elt Seq.t -> t
end
type (_, _) eq = Eq : ('a, 'a) eq
type wrap = W of (SInt.t, SInt.t) eq
module M :
sig
module I = Int
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
end
module type S =
sig
module I = Int
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(I).t) eq
end
module Int2 : sig type t = int val compare : 'a -> 'a -> int end
Line 15, characters 10-30:
15 | include S with module I := I
^^^^^^^^^^^^^^^^^^^^
Error: In this `with' constraint, the new definition of I
does not match its original definition in the constrained signature:
Modules do not match: (module Int2) is not included in (module Int)
|}];;
let M2.W eq = W Eq;;
let s = List.fold_right SInt.add [1;2;3] SInt.empty;;
module SInt2 = Set.Make(Int2);;
let conv : type a b. (a,b) eq -> a -> b = fun Eq x -> x;;
let s' : SInt2.t = conv eq s;;
SInt2.elements s';;
*)
module M = struct
module N = struct module I = Int end
module P = struct module I = N.I end
module Q = struct
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq
end
end;;
module type S = module type of M [@remove_aliases];;
[%%expect{|
module M :
sig
module N : sig module I = Int end
module P : sig module I = N.I end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq end
end
module type S =
sig
module N : sig module I = Int end
module P : sig module I = N.I end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(P.I).t) eq end
end
|}];;
module M = struct
module N = struct module I = Int end
module P = struct module I = N.I end
module Q = struct
type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq
end
end;;
module type S = module type of M [@remove_aliases];;
[%%expect{|
module M :
sig
module N : sig module I = Int end
module P : sig module I = N.I end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq end
end
module type S =
sig
module N : sig module I = Int end
module P :
sig module I : sig type t = int val compare : 'a -> 'a -> int end end
module Q :
sig type wrap' = wrap = W of (Set.Make(Int).t, Set.Make(N.I).t) eq end
end
|}];;
module type S = sig module M : sig type t val x : t end end;;
module H = struct type t = A let x = A end;;
module H' = H;;
[%%expect{|
module type S = sig module M : sig type t val x : t end end
module H : sig type t = A val x : t end
module H' = H
module type S' = sig module M : sig type t = H.t = A val x : t end end
|}];;
module type Alias = sig module N : sig end module M = N end;;
module F (X : sig end) = struct type t end;;
module type A = Alias with module N := F(List);;
module rec Bad : A = Bad;;
[%%expect{|
module type Alias = sig module N : sig end module M = N end
module F : functor (X : sig end) -> sig type t end
Line 1:
Error: Module type declarations do not match:
module type A = sig module M = F(List) end
does not match
module type A = sig module M = F(List) end
At position module type A = <here>
Module types do not match:
sig module M = F(List) end
is not equal to
sig module M = F(List) end
At position module type A = sig module M : <here> end
Module F(List) cannot be aliased
|}];;
Shinwell 2014 - 04 - 23
module B = struct
module R = struct
type t = string
end
module O = R
end
module K = struct
module E = B
module N = E.O
end;;
let x : K.N.t = "foo";;
[%%expect{|
module B : sig module R : sig type t = string end module O = R end
module K : sig module E = B module N = E.O end
val x : K.N.t = "foo"
|}];;
module M = struct type t = A module B = struct type u = B end end;;
module P : sig type t = M.t = A module B = M.B end = M;;
module P : sig type t = M.t = A module B = M.B end = struct include M end;;
[%%expect{|
module M : sig type t = A module B : sig type u = B end end
module P : sig type t = M.t = A module B = M.B end
module P : sig type t = M.t = A module B = M.B end
|}];;
module type S = sig
module M : sig module P : sig end end
module Q = M
end;;
[%%expect{|
module type S = sig module M : sig module P : sig end end module Q = M end
|}];;
module type S = sig
module M : sig module N : sig end module P : sig end end
module Q : sig module N = M.N module P = M.P end
end;;
module R = struct
module M = struct module N = struct end module P = struct end end
module Q = M
end;;
module R' : S = R;;
[%%expect{|
module type S =
sig
module M : sig module N : sig end module P : sig end end
module Q : sig module N = M.N module P = M.P end
end
module R :
sig
module M : sig module N : sig end module P : sig end end
module Q = M
end
module R' : S
|}];;
module F (X : sig end) = struct type t end;;
module M : sig
type a
module Foo : sig
module Bar : sig end
type b = a
end
end = struct
module Foo = struct
module Bar = struct end
type b = F(Bar).t
end
type a = Foo.b
end;;
[%%expect{|
module F : functor (X : sig end) -> sig type t end
module M :
sig type a module Foo : sig module Bar : sig end type b = a end end
|}];;
PR#6578
module M = struct let f x = x end
module rec R : sig module M : sig val f : 'a -> 'a end end =
struct module M = M end;;
R.M.f 3;;
[%%expect{|
module M : sig val f : 'a -> 'a end
module rec R : sig module M : sig val f : 'a -> 'a end end
- : int = 3
|}];;
module rec R : sig module M = M end = struct module M = M end;;
R.M.f 3;;
[%%expect{|
module rec R : sig module M = M end
- : int = 3
|}];;
module M = struct type t end
module type S = sig module N = M val x : N.t end
module type T = S with module N := M;;
[%%expect{|
module M : sig type t end
module type S = sig module N = M val x : N.t end
module type T = sig val x : M.t end
|}];;
module X = struct module N = struct end end
module Y : sig
module type S = sig module N = X.N end
end = struct
module type S = module type of struct include X end
end;;
[%%expect{|
module X : sig module N : sig end end
module Y : sig module type S = sig module N = X.N end end
|}];;
module type S = sig
module M : sig
module A : sig end
module B : sig end
end
module N = M.A
end
module Foo = struct
module B = struct let x = 0 end
module A = struct let x = "hello" end
end
module Bar : S with module M := Foo = struct module N = Foo.A end
let s : string = Bar.N.x
[%%expect {|
module type S =
sig
module M : sig module A : sig end module B : sig end end
module N = M.A
end
module Foo :
sig module B : sig val x : int end module A : sig val x : string end end
module Bar : sig module N = Foo.A end
val s : string = "hello"
|}]
module M : sig
module N : sig
module A : sig val x : string end
module B : sig val x : int end
end
module F (X : sig module A = N.A end) : sig val s : string end
end = struct
module N = struct
module B = struct let x = 0 end
module A = struct let x = "hello" end
end
module F (X : sig module A : sig val x : string end end) = struct
let s = X.A.x
end
end
module N = M.F(struct module A = M.N.A end)
let s : string = N.s
[%%expect {|
module M :
sig
module N :
sig
module A : sig val x : string end
module B : sig val x : int end
end
module F : functor (X : sig module A = N.A end) -> sig val s : string end
end
module N : sig val s : string end
val s : string = "hello"
|}]
|
10d15bc902579aba7c6e227bafe4f3d9a4a725344517a8f9e54aa4b73e403a28 | mbutterick/beautiful-racket | list.rkt | #lang racket/base
(require br/define (for-syntax racket/base syntax/parse))
(provide (all-defined-out))
(define-macro (values->list EXPR)
#'(call-with-values (λ () EXPR) list))
(define-syntax (push! stx)
(syntax-parse stx
[(_ ID:id VAL)
#'(set! ID (cons VAL ID))]))
(define-syntax (pop! stx)
(syntax-parse stx
[(_ ID:id)
#'(let ([x (car ID)])
(set! ID (cdr ID))
x)]))
(module+ test
(require rackunit)
(check-equal? '(1 2 3) (values->list (values 1 2 3)))
(check-equal? (let ([xs '(2 3)])
(push! xs 1)
xs) '(1 2 3))
(check-equal? (let ([xs '(1 2 3)])
(define x (pop! xs))
(cons x xs)) '(1 2 3))) | null | https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-lib/br/list.rkt | racket | #lang racket/base
(require br/define (for-syntax racket/base syntax/parse))
(provide (all-defined-out))
(define-macro (values->list EXPR)
#'(call-with-values (λ () EXPR) list))
(define-syntax (push! stx)
(syntax-parse stx
[(_ ID:id VAL)
#'(set! ID (cons VAL ID))]))
(define-syntax (pop! stx)
(syntax-parse stx
[(_ ID:id)
#'(let ([x (car ID)])
(set! ID (cdr ID))
x)]))
(module+ test
(require rackunit)
(check-equal? '(1 2 3) (values->list (values 1 2 3)))
(check-equal? (let ([xs '(2 3)])
(push! xs 1)
xs) '(1 2 3))
(check-equal? (let ([xs '(1 2 3)])
(define x (pop! xs))
(cons x xs)) '(1 2 3))) |
|
f0d9384a663735d243bdebeaeaf57af86442ede55026b78ce440fb12da4f2d1d | ExtremaIS/ttc-haskell | invalid.hs | ------------------------------------------------------------------------------
-- |
-- Module : Main
-- Description : example of compile-time validation error
Copyright : Copyright ( c ) 2019 - 2022
License : MIT
--
-- 'TTC.valid' is used to create validated constants. The sample username
-- is (in)validated at compile-time.
------------------------------------------------------------------------------
# LANGUAGE TemplateHaskell #
module Main (main) where
import qualified Data.TTC as TTC
-- (ttc-examples:example-valid)
import Username (Username)
------------------------------------------------------------------------------
sample :: Username
sample = $$(TTC.valid "bad-username")
------------------------------------------------------------------------------
main :: IO ()
main = print sample
| null | https://raw.githubusercontent.com/ExtremaIS/ttc-haskell/283ca48904f7e94905cc5b2f59abf9bad75a3bff/examples/invalid/invalid.hs | haskell | ----------------------------------------------------------------------------
|
Module : Main
Description : example of compile-time validation error
'TTC.valid' is used to create validated constants. The sample username
is (in)validated at compile-time.
----------------------------------------------------------------------------
(ttc-examples:example-valid)
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | Copyright : Copyright ( c ) 2019 - 2022
License : MIT
# LANGUAGE TemplateHaskell #
module Main (main) where
import qualified Data.TTC as TTC
import Username (Username)
sample :: Username
sample = $$(TTC.valid "bad-username")
main :: IO ()
main = print sample
|
65234091015bc4bccceb29c88860013eeaa0dc5011efde4166363245cd6b602f | robrix/sequoia | Implicative.hs | module Sequoia.Connective.Implicative
( elimFun
, funPar1
, funPar2
-- * Connectives
, module Sequoia.Connective.Function
, module Sequoia.Connective.Subtraction
) where
import Fresnel.Iso
import Sequoia.Connective.Function
import Sequoia.Connective.Not
import Sequoia.Connective.Par
import Sequoia.Connective.Subtraction
import Sequoia.Disjunction
import Sequoia.Profunctor
import Sequoia.Profunctor.Continuation
import Sequoia.Profunctor.Exp (elimExp, (↑), (↓))
elimFun :: a ~~Fun r~> b -> b >-Sub r-~ a -> r
elimFun f s = elimExp (runFunExp f) • runSubCoexp s
funPar1 :: Iso' ((a ¬ r ⅋ b) • r) ((a ~~Fun r~> b) • r)
funPar1 = iso
(\ k -> k <<^ mkPar (inrL k))
(<<^ mkFun)
funPar2 :: Iso' ((a ¬ r ⅋ b) •• r) ((a ~~Fun r~> b) •• r)
funPar2 = iso
(<<^ (<<^ mkFun))
(<<^ (\ k -> k <<^ mkPar (inrL k)))
mkPar :: b • r -> a ~~Fun r~> b -> (a ¬ r ⅋ b)
mkPar p f = inl (inK (\ a -> p ↓ runFunExp f ↑ a))
mkFun :: a ¬ r ⅋ b -> a ~~Fun r~> b
mkFun p = fun (\ b a -> ((• a) <--> (b •)) p)
| null | https://raw.githubusercontent.com/robrix/sequoia/1895ab90eb2fd7332ffb901fd8d932ad7637a695/src/Sequoia/Connective/Implicative.hs | haskell | * Connectives
> (b •)) p) | module Sequoia.Connective.Implicative
( elimFun
, funPar1
, funPar2
, module Sequoia.Connective.Function
, module Sequoia.Connective.Subtraction
) where
import Fresnel.Iso
import Sequoia.Connective.Function
import Sequoia.Connective.Not
import Sequoia.Connective.Par
import Sequoia.Connective.Subtraction
import Sequoia.Disjunction
import Sequoia.Profunctor
import Sequoia.Profunctor.Continuation
import Sequoia.Profunctor.Exp (elimExp, (↑), (↓))
elimFun :: a ~~Fun r~> b -> b >-Sub r-~ a -> r
elimFun f s = elimExp (runFunExp f) • runSubCoexp s
funPar1 :: Iso' ((a ¬ r ⅋ b) • r) ((a ~~Fun r~> b) • r)
funPar1 = iso
(\ k -> k <<^ mkPar (inrL k))
(<<^ mkFun)
funPar2 :: Iso' ((a ¬ r ⅋ b) •• r) ((a ~~Fun r~> b) •• r)
funPar2 = iso
(<<^ (<<^ mkFun))
(<<^ (\ k -> k <<^ mkPar (inrL k)))
mkPar :: b • r -> a ~~Fun r~> b -> (a ¬ r ⅋ b)
mkPar p f = inl (inK (\ a -> p ↓ runFunExp f ↑ a))
mkFun :: a ¬ r ⅋ b -> a ~~Fun r~> b
|
dff76ff9a3e077ea3cd5a4d4c8752a0bc0cbe803a4095bae3683e499ce9ca875 | ragkousism/Guix-on-Hurd | qt.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 , 2014 , 2015 < >
Copyright © 2015 < >
Copyright © 2015 < >
Copyright © 2015 , 2016 , 2017 < >
Copyright © 2016 , 2017 ng0 < >
Copyright © 2016 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages qt)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build utils)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix packages)
#:use-module (guix utils)
#:use-module (gnu packages)
#:use-module (gnu packages bison)
#:use-module (gnu packages compression)
#:use-module (gnu packages cups)
#:use-module (gnu packages databases)
#:use-module (gnu packages documentation)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages flex)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gl)
#:use-module (gnu packages glib)
#:use-module (gnu packages gnuzilla)
#:use-module (gnu packages gperf)
#:use-module (gnu packages gtk)
#:use-module (gnu packages icu4c)
#:use-module (gnu packages image)
#:use-module (gnu packages linux)
#:use-module (gnu packages databases)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages pcre)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages pulseaudio)
#:use-module (gnu packages python)
#:use-module (gnu packages ruby)
#:use-module (gnu packages sdl)
#:use-module (gnu packages tls)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xorg)
#:use-module (gnu packages xml))
(define-public grantlee
(package
(name "grantlee")
(version "5.1.0")
(source
(origin
(method url-fetch)
(uri (string-append ""
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32 "1lf9rkv0i0kd7fvpgg5l8jb87zw8dzcwd1liv6hji7g4wlpmfdiq"))))
(native-inputs
`(("doxygen" ,doxygen)))
(inputs
`(("qtbase" ,qtbase)
("qtscript" ,qtscript)))
(build-system cmake-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'check
(lambda _
exclude 2 tests which require a display
"-E" "htmlbuildertest|plainmarkupbuildertest")))))))
(home-page "")
(synopsis "Libraries for text templating with Qt")
(description "Grantlee Templates can be used for theming and generation of
other text such as code. The syntax uses the syntax of the Django template
system, and the core design of Django is reused in Grantlee.")
(license license:lgpl2.0+)))
(define-public qt
(package
(name "qt")
(version "5.6.2")
(source (origin
(method url-fetch)
(uri
(string-append
"/"
(version-major+minor version)
"/" version
"/single/qt-everywhere-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1cw93mrlkqbwndfqyjpsvjzkpzi39px2is040xvk18mvg3y1prl3"))
(modules '((guix build utils)))
(snippet
'(begin
;; Remove qtwebengine, which relies on a bundled copy of
chromium . Not only does it fail compilation in qt 5.5 :
3rdparty / chromium / ui / gfx / codec / jpeg_codec.cc:362:10 :
;; error: cannot convert ‘bool’ to ‘boolean’ in return
;; it might also pose security problems.
;; Alternatively, we could use the "-skip qtwebengine"
;; configuration option.
(delete-file-recursively "qtwebengine")
Remove one of the two bundled harfbuzz copies in addition
;; to passing "-system-harfbuzz".
(delete-file-recursively "qtbase/src/3rdparty/harfbuzz-ng")
;; Remove the bundled sqlite copy in addition to
;; passing "-system-sqlite".
(delete-file-recursively "qtbase/src/3rdparty/sqlite")))))
(build-system gnu-build-system)
(propagated-inputs
`(("mesa" ,mesa)))
(inputs
`(("alsa-lib" ,alsa-lib)
("dbus" ,dbus)
("cups" ,cups)
("expat" ,expat)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("glib" ,glib)
("harfbuzz" ,harfbuzz)
("icu4c" ,icu4c)
("libjpeg" ,libjpeg)
("libmng" ,libmng)
("libpci" ,pciutils)
("libpng" ,libpng)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)
("libxcursor" ,libxcursor)
("libxfixes" ,libxfixes)
("libxi" ,libxi)
("libxinerama" ,libxinerama)
("libxkbcommon" ,libxkbcommon)
("libxml2" ,libxml2)
("libxrandr" ,libxrandr)
("libxrender" ,libxrender)
("libxslt" ,libxslt)
("libxtst" ,libxtst)
("mtdev" ,mtdev)
("mysql" ,mysql)
("nss" ,nss)
("openssl" ,openssl)
("postgresql" ,postgresql)
("pulseaudio" ,pulseaudio)
("pcre" ,pcre)
("sqlite" ,sqlite)
("udev" ,eudev)
("unixodbc" ,unixodbc)
("xcb-util" ,xcb-util)
("xcb-util-image" ,xcb-util-image)
("xcb-util-keysyms" ,xcb-util-keysyms)
("xcb-util-renderutil" ,xcb-util-renderutil)
("xcb-util-wm" ,xcb-util-wm)
("zlib" ,zlib)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("gperf" ,gperf)
("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("ruby" ,ruby)
("which" ,(@ (gnu packages base) which))))
(arguments
`(;; FIXME: Disabling parallel building is a quick hack to avoid the
;; failure described in
;; -devel/2016-01/msg00837.html
;; A more structural fix is needed.
#:parallel-build? #f
#:phases
(modify-phases %standard-phases
(add-after 'configure 'patch-bin-sh
(lambda _
(substitute* '("qtbase/config.status"
"qtbase/configure"
"qtbase/mkspecs/features/qt_functions.prf"
"qtbase/qmake/library/qmakebuiltins.cpp")
(("/bin/sh") (which "sh")))
#t))
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(substitute* '("configure" "qtbase/configure")
(("/bin/pwd") (which "pwd")))
(substitute* "qtbase/src/corelib/global/global.pri"
(("/bin/ls") (which "ls")))
;; do not pass "--enable-fast-install", which makes the
;; configure process fail
(zero? (system*
"./configure"
"-verbose"
"-prefix" out
"-opensource"
"-confirm-license"
;; Do not build examples; if desired, these could go
;; into a separate output, but for the time being, we
;; prefer to save the space and build time.
"-nomake" "examples"
;; Most "-system-..." are automatic, but some use
;; the bundled copy by default.
"-system-sqlite"
"-system-harfbuzz"
;; explicitly link with openssl instead of dlopening it
"-openssl-linked"
explicitly link with dbus instead of dlopening it
"-dbus-linked"
;; drop special machine instructions not supported
;; on all instances of the target
,@(if (string-prefix? "x86_64"
(or (%current-target-system)
(%current-system)))
'()
'("-no-sse2"))
"-no-sse3"
"-no-ssse3"
"-no-sse4.1"
"-no-sse4.2"
"-no-avx"
"-no-avx2"
"-no-mips_dsp"
"-no-mips_dspr2"))))))))
(home-page "/")
(synopsis "Cross-platform GUI library")
(description "Qt is a cross-platform application and UI framework for
developers using C++ or QML, a CSS & JavaScript like language.")
(license license:lgpl2.1)
Qt 4 : ' QBasicAtomicPointer ' leads to build failures on MIPS ;
;; see <>.
Qt 5 : assembler error ; see < > .
(supported-systems (delete "mips64el-linux" %supported-systems))))
(define-public qt-4
(package (inherit qt)
(version "4.8.7")
(source (origin
(method url-fetch)
(uri (string-append "-project.org/official_releases/qt/"
(string-copy version 0 (string-rindex version #\.))
"/" version
"/qt-everywhere-opensource-src-"
version ".tar.gz"))
(sha256
(base32
"183fca7n7439nlhxyg1z7aky0izgbyll3iwakw4gwivy16aj5272"))
(patches (search-patches "qt4-ldflags.patch"))
(modules '((guix build utils)))
(snippet
;; Remove webkit module, which is not built.
'(delete-file-recursively "src/3rdparty/webkit"))))
(inputs `(,@(alist-delete "harfbuzz"
(alist-delete "libjpeg" (package-inputs qt)))
("libjepg" ,libjpeg-8)
("libsm" ,libsm)))
Note : there are 37 MiB of examples and a ' -exampledir ' configure flags ,
;; but we can't make them a separate output because "out" and "examples"
;; would refer to each other.
112MiB core + 37MiB examples
280MiB of HTML + code
(arguments
`(#:phases
(modify-phases %standard-phases
(replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc")))
(substitute* '("configure")
(("/bin/pwd") (which "pwd")))
(zero? (system*
"./configure"
"-verbose"
"-prefix" out
;; Note: Don't pass '-docdir' since 'qmake' and
;; libQtCore would record its value, thereby defeating
;; the whole point of having a separate output.
"-datadir" (string-append out "/share/qt-" ,version
"/data")
"-importdir" (string-append out "/lib/qt-4"
"/imports")
"-plugindir" (string-append out "/lib/qt-4"
"/plugins")
"-translationdir" (string-append out "/share/qt-" ,version
"/translations")
"-demosdir" (string-append out "/share/qt-" ,version
"/demos")
"-examplesdir" (string-append out "/share/qt-" ,version
"/examples")
"-opensource"
"-confirm-license"
explicitly link with dbus instead of dlopening it
"-dbus-linked"
;; Skip the webkit module; it fails to build on armhf
;; and, apart from that, may pose security risks.
"-no-webkit"
;; drop special machine instructions not supported
;; on all instances of the target
,@(if (string-prefix? "x86_64"
(or (%current-target-system)
(%current-system)))
'()
'("-no-mmx"
"-no-3dnow"
"-no-sse"
"-no-sse2"))
"-no-sse3"
"-no-ssse3"
"-no-sse4.1"
"-no-sse4.2"
"-no-avx")))))
(add-after
'install 'move-doc
(lambda* (#:key outputs #:allow-other-keys)
Because of qt4-documentation-path.patch , documentation ends up
being installed in OUT . Move it to the right place .
(let* ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc"))
(olddoc (string-append out "/doc"))
(docdir (string-append doc "/share/doc/qt-" ,version)))
(mkdir-p (dirname docdir))
Note : We ca n't use ' rename - file ' here because OUT and DOC are
;; different "devices" due to bind-mounts.
(copy-recursively olddoc docdir)
(delete-file-recursively olddoc)
#t))))))))
(define-public qtbase
(package
(name "qtbase")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0zjmcrmnnmaz1lr9wc5i6y565hsvl8ycn790ivqaz62dv54zbkgd"))
(modules '((guix build utils)))
(snippet
'(begin
Remove one of the two bundled harfbuzz copies in addition
;; to passing "-system-harfbuzz".
(delete-file-recursively "src/3rdparty/harfbuzz-ng")
;; Remove the bundled sqlite copy in addition to
;; passing "-system-sqlite".
(delete-file-recursively "src/3rdparty/sqlite")))))
(build-system gnu-build-system)
(propagated-inputs
`(("mesa" ,mesa)))
(inputs
`(("alsa-lib" ,alsa-lib)
("cups" ,cups)
("dbus" ,dbus)
("eudev" ,eudev)
("expat" ,expat)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("glib" ,glib)
("harfbuzz" ,harfbuzz)
("icu4c" ,icu4c)
("libinput" ,libinput)
("libjpeg" ,libjpeg)
("libmng" ,libmng)
("libpng" ,libpng)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)
("libxcursor" ,libxcursor)
("libxfixes" ,libxfixes)
("libxi" ,libxi)
("libxinerama" ,libxinerama)
("libxkbcommon" ,libxkbcommon)
("libxml2" ,libxml2)
("libxrandr" ,libxrandr)
("libxrender" ,libxrender)
("libxslt" ,libxslt)
("libxtst" ,libxtst)
("mtdev" ,mtdev)
("mysql" ,mysql)
("nss" ,nss)
("openssl" ,openssl)
("pcre" ,pcre)
("postgresql" ,postgresql)
("pulseaudio" ,pulseaudio)
("sqlite" ,sqlite)
("unixodbc" ,unixodbc)
("xcb-util" ,xcb-util)
("xcb-util-image" ,xcb-util-image)
("xcb-util-keysyms" ,xcb-util-keysyms)
("xcb-util-renderutil" ,xcb-util-renderutil)
("xcb-util-wm" ,xcb-util-wm)
("zlib" ,zlib)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("gperf" ,gperf)
("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("ruby" ,ruby)
("which" ,(@ (gnu packages base) which))))
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'configure 'patch-bin-sh
(lambda _
(substitute* '("config.status"
"configure"
"mkspecs/features/qt_functions.prf"
"qmake/library/qmakebuiltins.cpp")
(("/bin/sh") (which "sh")))
#t))
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(substitute* "configure"
(("/bin/pwd") (which "pwd")))
(substitute* "src/corelib/global/global.pri"
(("/bin/ls") (which "ls")))
The configuration files for other Qt5 packages are searched
;; through a call to "find_package" in Qt5Config.cmake, which
;; disables the use of CMAKE_PREFIX_PATH via the parameter
;; "NO_DEFAULT_PATH". Re-enable it so that the different
;; components can be installed in different places.
(substitute* (find-files "." ".*\\.cmake")
(("NO_DEFAULT_PATH") ""))
;; do not pass "--enable-fast-install", which makes the
;; configure process fail
(zero? (system*
"./configure"
"-verbose"
"-prefix" out
"-opensource"
"-confirm-license"
;; Do not build examples; if desired, these could go
;; into a separate output, but for the time being, we
;; prefer to save the space and build time.
"-nomake" "examples"
;; Most "-system-..." are automatic, but some use
;; the bundled copy by default.
"-system-sqlite"
"-system-harfbuzz"
;; explicitly link with openssl instead of dlopening it
"-openssl-linked"
explicitly link with dbus instead of dlopening it
"-dbus-linked"
;; drop special machine instructions not supported
;; on all instances of the target
,@(if (string-prefix? "x86_64"
(or (%current-target-system)
(%current-system)))
'()
'("-no-sse2"))
"-no-sse3"
"-no-ssse3"
"-no-sse4.1"
"-no-sse4.2"
"-no-avx"
"-no-avx2"
"-no-mips_dsp"
"-no-mips_dspr2")))))
(add-after 'install 'patch-qt_config.prf
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(qt_config.prf (string-append
out "/mkspecs/features/qt_config.prf")))
;; For each Qt module, let `qmake' uses search paths in the
;; module directory instead of all in QT_INSTALL_PREFIX.
(substitute* qt_config.prf
(("\\$\\$\\[QT_INSTALL_HEADERS\\]")
"$$replace(dir, mkspecs/modules, include)")
(("\\$\\$\\[QT_INSTALL_LIBS\\]")
"$$replace(dir, mkspecs/modules, lib)")
(("\\$\\$\\[QT_HOST_LIBS\\]")
"$$replace(dir, mkspecs/modules, lib)")
(("\\$\\$\\[QT_INSTALL_PLUGINS\\]")
"$$replace(dir, mkspecs/modules, plugins)")
(("\\$\\$\\[QT_INSTALL_LIBEXECS\\]")
"$$replace(dir, mkspecs/modules, libexec)")
(("\\$\\$\\[QT_INSTALL_BINS\\]")
"$$replace(dir, mkspecs/modules, bin)")
(("\\$\\$\\[QT_INSTALL_IMPORTS\\]")
"$$replace(dir, mkspecs/modules, imports)")
(("\\$\\$\\[QT_INSTALL_QML\\]")
"$$replace(dir, mkspecs/modules, qml)"))
#t))))))
(native-search-paths
(list (search-path-specification
(variable "QMAKEPATH")
(files '("")))
(search-path-specification
(variable "QML2_IMPORT_PATH")
(files '("qml")))
(search-path-specification
(variable "QT_PLUGIN_PATH")
(files '("plugins")))
(search-path-specification
(variable "XDG_DATA_DIRS")
(files '("share")))
(search-path-specification
(variable "XDG_CONFIG_DIRS")
(files '("etc/xdg")))))
(home-page "/")
(synopsis "Cross-platform GUI library")
(description "Qt is a cross-platform application and UI framework for
developers using C++ or QML, a CSS & JavaScript like language.")
(license (list license:lgpl2.1 license:lgpl3))))
(define-public qtsvg
(package (inherit qtbase)
(name "qtsvg")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0irr9h566hl9nx8p919rz276zbfvvd6vqdb6i9g6b3piikdigw5h"))))
(propagated-inputs `())
(native-inputs `(("perl" ,perl)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)
("zlib" ,zlib)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
variables are :
libs tools tests examples demos docs translations
(zero? (system* "qmake" "QT_BUILD_PARTS = libs tools tests"
(string-append "PREFIX=" out))))))
(add-before 'install 'fix-Makefiles
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(qtbase (assoc-ref inputs "qtbase")))
(substitute* (find-files "." "Makefile")
(((string-append "INSTALL_ROOT)" qtbase))
(string-append "INSTALL_ROOT)" out)))
#t)))
(add-before 'check 'set-display
(lambda _
(setenv "QT_QPA_PLATFORM" "offscreen")
#t)))))))
(define-public qtimageformats
(package (inherit qtsvg)
(name "qtimageformats")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1x3p1xmw7spxa4bwriyrwsfrq31jabsdjsi5fras9y39naia55sg"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively "src/3rdparty")))))
(native-inputs `())
(inputs
`(("jasper" ,jasper)
("libmng" ,libmng)
("libtiff" ,libtiff)
("libwebp" ,libwebp)
("mesa" ,mesa)
("qtbase" ,qtbase)
("zlib" ,zlib)))))
(define-public qtx11extras
(package (inherit qtsvg)
(name "qtx11extras")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"09z49jm70f5i0gcdz9a16z00pg96x8pz7vri5wpirh3fqqn0qnjz"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(native-inputs `(("perl" ,perl)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)))))
(define-public qtxmlpatterns
(package (inherit qtsvg)
(name "qtxmlpatterns")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1rgqnpg64gn5agmvjwy0am8hp5fpxl3cdkixr1yrsdxi5a6961d8"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:phases phases)
`(modify-phases ,phases
(add-after 'unpack 'disable-network-tests
(lambda _ (substitute* "tests/auto/auto.pro"
(("qxmlquery") "# qxmlquery")
(("xmlpatterns") "# xmlpatterns"))
#t))))))
(native-inputs `(("perl" ,perl)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtdeclarative
(package (inherit qtsvg)
(name "qtdeclarative")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0mjxfwnplpx60jc6y94krg00isddl9bfwc7dayl981njb4qds4zx"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("qtsvg" ,qtsvg)
("qtxmlpatterns" ,qtxmlpatterns)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)))))
(define-public qtconnectivity
(package (inherit qtsvg)
(name "qtconnectivity")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0rmr7bd4skby7bax9hpj2sid2bq3098nkw7xm02mdp04hc3bks5k"))))
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("bluez" ,bluez)
("qtbase" ,qtbase)))))
(define-public qtwebsockets
(package (inherit qtsvg)
(name "qtwebsockets")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1laj0slwibs0bg69kgrdhc9k1s6yisq3pcsr0r9rhbkzisv7aajw"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtsensors
(package (inherit qtsvg)
(name "qtsensors")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"041v1x8pwfzpyk6y0sy5zgm915pi15xdhiy18fd5wqayvcp99cyc"))))
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtmultimedia
(package (inherit qtsvg)
(name "qtmultimedia")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1vvxmgmvjnz9w1h2ph1j2fy77ij141ycx5fric60lq02pxzifax5"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively
"examples/multimedia/spectrum/3rdparty")
;; We also prevent the spectrum example from being built.
(substitute* "examples/multimedia/multimedia.pro"
(("spectrum") "#"))))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("alsa-lib" ,alsa-lib)
("mesa" ,mesa)
("pulseaudio" ,pulseaudio)
("qtbase" ,qtbase)))))
(define-public qtwayland
(package (inherit qtsvg)
(name "qtwayland")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1iq1c89y4ggq0dxjlf62jyhh8a9l3x7y914x84w5pby8h3hwagzj"))))
(native-inputs
`(("glib" ,glib)
("perl" ,perl)
("pkg-config" ,pkg-config)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("fontconfig" ,fontconfig)
("freetype" ,freetype)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)
("libxext" ,libxext)
("libxkbcommon" ,libxkbcommon)
("libxrender" ,libxrender)
("mesa" ,mesa)
("mtdev" ,mtdev)
("qtbase" ,qtbase)
("wayland" ,wayland)))))
(define-public qtserialport
(package (inherit qtsvg)
(name "qtserialport")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"09jsryc0z49cz9783kq48rkn42f10c6krzivp812ddwjsfdy3mbn"))))
(native-inputs `(("perl" ,perl)))
(inputs
`(("qtbase" ,qtbase)
("eudev" ,eudev)))))
(define-public qtserialbus
(package (inherit qtsvg)
(name "qtserialbus")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0mxi43l2inpbar8rmg21qjg33bv3f1ycxjgvzjf12ncnybhdnzkj"))))
(inputs
`(("qtbase" ,qtbase)
("qtserialport" ,qtserialport)))))
(define-public qtwebchannel
(package (inherit qtsvg)
(name "qtwebchannel")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"16rij92dxy4k5231l3dpmhy7cnz0cjkn50cpzaf014zrdz3kmav3"))))
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)
("qtwebsockets" ,qtwebsockets)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtlocation
(package (inherit qtsvg)
(name "qtlocation")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"17zkzffzwbg6aqhsggs23cmwzq4y45m938842lsc423hfm7fdsgr"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)
("qtquickcontrols" ,qtquickcontrols)
("qtserialport" ,qtserialport)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qttools
(package (inherit qtsvg)
(name "qttools")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1b6zqa5690b8lqms7rrhb8rcq0xg5hp117v3m08qngbcd0i706b4"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)))))
(define-public qtscript
(package (inherit qtsvg)
(name "qtscript")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"09m41n95448pszr7inlg03ycb66s1a9hzfylaka92382acf1myav"))))
(native-inputs
`(("perl" ,perl)
("qttools" ,qttools)))
(inputs
`(("qtbase" ,qtbase)))))
(define-public qtquickcontrols
(package (inherit qtsvg)
(name "qtquickcontrols")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"17cyfyqzjbm9dhq9pjscz36y84y16rmxwk6h826gjfprddrimsvg"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtquickcontrols2
(package (inherit qtsvg)
(name "qtquickcontrols2")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1v77ydy4k15lksp3bi2kgha2h7m79g4n7c2qhbr09xnvpb8ars7j"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtgraphicaleffects
(package (inherit qtsvg)
(name "qtgraphicaleffects")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1j2drnx7zp3w6cgvy7bn00fyk5v7vw1j1hidaqcg78lzb6zgls1c"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtdeclarative-render2d
(package (inherit qtsvg)
(name "qtdeclarative-render2d")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0zwch9vn17f3bpy300jcfxx6cx9qymk5j7khx0x9k1xqid4166c3"))
(modules '((guix build utils)))
(snippet
'(delete-file-recursively "tools/opengldummy/3rdparty"))))
(native-inputs `())
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtgamepad
(package (inherit qtsvg)
(name "qtgamepad")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"10lijbsg9xx5ddbbjymdgl41nxz99yn1qgiww2kkggxwwdjj2axv"))))
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)))
(inputs
`(("fontconfig" ,fontconfig)
("freetype" ,freetype)
("libxrender" ,libxrender)
("sdl2" ,sdl2)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtscxml
(package (inherit qtsvg)
(name "qtscxml")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"135kknqdmib2cjryfmvfgv7a2qx9pyba3m7i7nkbc5d742r4mbcx"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively "tests/3rdparty")
the scion test refers to the bundled 3rd party test code .
(substitute* "tests/auto/auto.pro"
(("scion") "#"))))))
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtpurchasing
(package (inherit qtsvg)
(name "qtpurchasing")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0hkvrgafz1hx9q4yc3nskv3pd3fszghvvd5a7mj33ynf55wpb57n"))))
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtcanvas3d
(package (inherit qtsvg)
(name "qtcanvas3d")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1d5xpq3mhjg4ipxzap7s2vnlfcd02d3yq720npv10xxp2ww0i1x8"))
(modules '((guix build utils)))
(snippet
'(delete-file-recursively "examples/canvas3d/3rdparty"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
Building the tests depends on the bundled 3rd party javascript files ,
and the test phase fails to import QtCanvas3D , causing the phase to
;; fail, so we skip building them for now.
((#:phases phases)
`(modify-phases ,phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero? (system* "qmake" "QT_BUILD_PARTS = libs tools"
(string-append "PREFIX=" out))))))))
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(native-inputs `())
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtcharts
(package (inherit qtsvg)
(name "qtcharts")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1qrzcddwff2hxsbxrraff16j4abah2zkra2756s1mvydj9lyxzl5"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtdatavis3d
(package (inherit qtsvg)
(name "qtdatavis3d")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1y00p0wyj5cw9c2925y537vpmmg9q3kpf7qr1s7sv67dvvf8bzqv"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:tests? _ #f) #f))) ; TODO: Enable the tests
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public python-sip
(package
(name "python-sip")
(version "4.18.1")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"sip-" version "/sip-" version ".tar.gz"))
(sha256
(base32
"1452zy3g0qv4fpd9c0y4gq437kn0xf7bbfniibv5n43zpwnpmklv"))))
(build-system gnu-build-system)
(native-inputs
`(("python" ,python-wrapper)))
(arguments
`(#:tests? #f ; no check target
#:modules ((srfi srfi-1)
,@%gnu-build-system-modules)
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(include (string-append out "/include"))
(python (assoc-ref inputs "python"))
(python-version
(last (string-split python #\-)))
(python-major+minor
(string-join
(take (string-split python-version #\.) 2)
"."))
(lib (string-append out "/lib/python"
python-major+minor
"/site-packages")))
(zero?
(system* "python" "configure.py"
"--bindir" bin
"--destdir" lib
"--incdir" include))))))))
(home-page "")
(synopsis "Python binding creator for C and C++ libraries")
(description
"SIP is a tool to create Python bindings for C and C++ libraries. It
was originally developed to create PyQt, the Python bindings for the Qt
toolkit, but can be used to create bindings for any C or C++ library.
SIP comprises a code generator and a Python module. The code generator
processes a set of specification files and generates C or C++ code, which
is then compiled to create the bindings extension module. The SIP Python
module provides support functions to the automatically generated code.")
;; There is a choice between a python like license, gpl2 and gpl3.
For compatibility with pyqt , we need gpl3 .
(license license:gpl3)))
(define-public python2-sip
(package (inherit python-sip)
(name "python2-sip")
(native-inputs
`(("python" ,python-2)))))
(define-public python-pyqt
(package
(name "python-pyqt")
(version "5.7")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"PyQt-" version "/PyQt5_gpl-"
version ".tar.gz"))
(sha256
(base32
"01avscn1bir0h8zzfh1jvpljgwg6qkax5nk142xrm63rbyx969l9"))
(patches (search-patches "pyqt-configure.patch"))))
(build-system gnu-build-system)
(native-inputs
`(("python-sip" ,python-sip)
("qtbase" ,qtbase))) ; for qmake
(inputs
`(("python" ,python-wrapper)
("qtbase" ,qtbase)
("qtconnectivity" ,qtconnectivity)
("qtdeclarative" ,qtdeclarative)
("qtlocation" ,qtlocation)
("qtmultimedia" ,qtmultimedia)
("qtsensors" ,qtsensors)
("qtserialport" ,qtserialport)
("qtsvg" ,qtsvg)
("qttools" ,qttools)
("qtwebchannel" ,qtwebchannel)
("qtwebkit" ,qtwebkit)
("qtwebsockets" ,qtwebsockets)
("qtx11extras" ,qtx11extras)
("qtxmlpatterns" ,qtxmlpatterns)))
(arguments
`(#:modules ((srfi srfi-1)
,@%gnu-build-system-modules)
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(sip (string-append out "/share/sip"))
(plugins (string-append out "/plugins"))
(designer (string-append plugins "/designer"))
(qml (string-append plugins "/PyQt5"))
(python (assoc-ref inputs "python"))
(python-version
(last (string-split python #\-)))
(python-major+minor
(string-join
(take (string-split python-version #\.) 2)
"."))
(lib (string-append out "/lib/python"
python-major+minor
"/site-packages"))
(stubs (string-append lib "/PyQt5")))
(zero? (system* "python" "configure.py"
"--confirm-license"
"--bindir" bin
"--destdir" lib
"--designer-plugindir" designer
"--qml-plugindir" qml
Where to install the PEP 484 Type Hints stub
; files. Without this the stubs are tried to be
; installed into the python package's
; site-package directory, which is read-only.
"--stubsdir" stubs
"--sipdir" sip))))))))
(home-page "")
(synopsis "Python bindings for Qt")
(description
"PyQt is a set of Python v2 and v3 bindings for the Qt application
framework. The bindings are implemented as a set of Python modules and
contain over 620 classes.")
(license license:gpl3)))
(define-public python2-pyqt
(package (inherit python-pyqt)
(name "python2-pyqt")
(native-inputs
`(("python-sip" ,python2-sip)
("qtbase" ,qtbase)))
(inputs
`(("python" ,python-2)
,@(alist-delete "python" (package-inputs python-pyqt))))))
(define-public python-pyqt-4
(package (inherit python-pyqt)
(name "python-pyqt")
(version "4.11.4")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"PyQt-" version "/PyQt-x11-gpl-"
version ".tar.gz"))
(sha256
(base32
"01zlviy5lq8g6db84wnvvpsrfnip9lbcpxagsyqa6as3jmsff7zw"))))
(native-inputs
`(("python-sip" ,python-sip)
("qt" ,qt-4)))
(inputs `(("python" ,python-wrapper)))
(arguments
`(#:tests? #f ; no check target
#:modules ((srfi srfi-1)
,@%gnu-build-system-modules)
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(sip (string-append out "/share/sip"))
(python (assoc-ref inputs "python"))
(python-version
(last (string-split python #\-)))
(python-major+minor
(string-join
(take (string-split python-version #\.) 2)
"."))
(lib (string-append out "/lib/python"
python-major+minor
"/site-packages")))
(zero? (system* "python" "configure.py"
"--confirm-license"
"--bindir" bin
"--destdir" lib
"--sipdir" sip))))))))
(license (list license:gpl2 license:gpl3)))) ; choice of either license
(define-public python2-pyqt-4
(package (inherit python-pyqt-4)
(name "python2-pyqt")
(native-inputs
`(("python-sip" ,python2-sip)
("qt" ,qt-4)))
(inputs
`(("python" ,python-2)))))
(define-public qtkeychain
(package
(name "qtkeychain")
(version "0.7.0")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"archive/v" version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32 "0fka5q5cdzlf79igcjgbnb2smvwbwfasqawkzkbr34whispgm6lz"))))
(build-system cmake-build-system)
(native-inputs
`(("qttools" ,qttools)))
(inputs
`(("qtbase" ,qtbase)))
(arguments
`(#:tests? #f ; No tests included
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-qt-trans-dir
(lambda _
(substitute* "CMakeLists.txt"
(("\\$\\{qt_translations_dir\\}")
"${CMAKE_INSTALL_PREFIX}/share/qt/translations")))))))
(home-page "")
(synopsis "Qt API to store passwords")
(description
"QtKeychain is a Qt library to store passwords and other secret data
securely. It will not store any data unencrypted unless explicitly requested.")
(license license:bsd-3)))
(define-public qwt
(package
(name "qwt")
(version "6.1.3")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
version "/qwt-" version ".tar.bz2"))
(sha256
(base32 "0cwp63s03dw351xavb3pzbjlqvx7kj88wv7v4a2b18m9f97d7v7k"))))
(build-system gnu-build-system)
(inputs
`(("qtbase" ,qtbase)
("qtsvg" ,qtsvg)
("qttools" ,qttools)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(substitute* '("qwtconfig.pri")
(("/usr/local/qwt-\\$\\$QWT\\_VERSION") out))
(zero? (system* "qmake")))))
(add-after 'install 'install-documentation
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(man (string-append out "/share/man")))
;; Remove some incomplete manual pages.
(for-each delete-file (find-files "doc/man/man3" "^_tmp.*"))
(mkdir-p man)
(copy-recursively "doc/man" man)
#t))))))
(home-page "")
(synopsis "Qt widgets for plots, scales, dials and other technical software
GUI components")
(description
"The Qwt library contains widgets and components which are primarily useful
for technical and scientific purposes. It includes a 2-D plotting widget,
different kinds of sliders, and much more.")
(license
(list
The Qwt license is LGPL2.1 with some exceptions .
(license:non-copyleft "")
textengines / mathml / qwt_mml_document.{cpp , h } is dual LGPL2.1 / GPL3 ( either ) .
license:lgpl2.1 license:gpl3))))
(define-public qtwebkit
(package
(name "qtwebkit")
(version "5.7.1")
(source
(origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version)
"/" version "/qtwebkit-opensource-src-" version
".tar.xz"))
Note : since Qt 5.6 , Qt no longer officially supports :
;; <-project.org/pipermail/development/2016-May/025923.html>.
(sha256
(base32
"00szgcra6pf2myfjrdbsr1gmrxycpbjqlzkplna5yr1rjg4gfv54"))))
(build-system gnu-build-system)
(native-inputs
`(("perl" ,perl)
("python" ,python-2.7)
("ruby" ,ruby)
("bison" ,bison)
("flex" ,flex)
("gperf" ,gperf)
("pkg-config" ,pkg-config)))
(inputs
`(("icu" ,icu4c)
("libjpeg" ,libjpeg)
("libpng" ,libpng)
("libwebp" ,libwebp)
("sqlite" ,sqlite)
("fontconfig" ,fontconfig)
("libxrender", libxrender)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)
("qtmultimedia" ,qtmultimedia)
("libxml2" ,libxml2)
("libxslt" ,libxslt)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(setenv "QMAKEPATH"
(string-append (getcwd) "/Tools/qmake:"
(getenv "QMAKEPATH")))
(system* "qmake"))))
prevent webkit from trying to install into the qtbase store directory ,
;; and replace references to the build directory in linker options:
(add-before 'build 'patch-installpaths
(lambda* (#:key outputs inputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(qtbase (assoc-ref inputs "qtbase"))
(builddir (getcwd))
(linkbuild (string-append "-L" builddir))
(linkout (string-append "-L" out))
(makefiles
(map-in-order
(lambda (i)
(let* ((in (car i))
(mf (string-append (dirname in) "/"
(cdr i))))
;; by default, these Makefiles are
;; generated during install, but we need
;; to generate them now
(system* "qmake" in "-o" mf)
mf))
'(("Source/api.pri" . "Makefile.api")
("Source/widgetsapi.pri"
. "Makefile.widgetsapi")
("Source/WebKit2/WebProcess.pro"
. "Makefile.WebProcess")
("Source/WebKit2/PluginProcess.pro"
. "Makefile.PluginProcess")
("Source/WebKit/qt/declarative/public.pri"
. "Makefile.declarative.public")
("Source/WebKit/qt/declarative/experimental/experimental.pri"
. "Makefile.declarative.experimental")
("Source/WebKit/qt/examples/platformplugin/platformplugin.pro"
. "Makefile")))))
;; Order of qmake calls and substitutions matters here.
(system* "qmake" "-prl" "Source/widgetsapi.pri"
"-o" "Source/Makefile")
(substitute* (find-files "lib" "libQt5.*\\.prl")
((linkbuild) linkout))
(substitute* (find-files "lib"
"libQt5WebKit.*\\.la")
(("libdir='.*'")
(string-append "libdir='" out "/lib'"))
((linkbuild) linkout))
(substitute* (find-files "lib/pkgconfig"
"Qt5WebKit.*\\.pc")
(((string-append "prefix=" qtbase))
(string-append "prefix=" out))
((linkbuild) linkout))
Makefiles must be modified after .prl/.la/.pc
;; files, lest they get rebuilt:
(substitute* makefiles
(((string-append "\\$\\(INSTALL_ROOT\\)" qtbase))
out )
(((string-append "-Wl,-rpath," builddir))
(string-append "-Wl,-rpath," out)))))))))
(home-page "")
(synopsis "Web browser engine and classes to render and interact with web
content")
(description "QtWebKit provides a Web browser engine that makes it easy to
embed content from the World Wide Web into your Qt application. At the same
time Web content can be enhanced with native controls.")
(license license:lgpl2.1+)))
(define-public dotherside
(package
(name "dotherside")
(version "0.5.2")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"archive/v" version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0pqlrvy4ajjir80ra79ka3n0rjj0ir0f0m91cq86iz3nnw8w148z"))))
(build-system cmake-build-system)
(native-inputs
`(("qttools" ,qttools)))
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))
(home-page "")
(synopsis "C language library for creating bindings for the Qt QML language")
(description
"DOtherSide is a C language library for creating bindings for the
QT QML language. The following features are implementable from
a binding language:
@itemize
@item Creating custom QObject
@item Creating custom QAbstractListModels
@item Creating custom properties, signals and slots
@item Creating from QML QObject defined in the binded language
@item Creating from Singleton QML QObject defined in the binded language
@end itemize\n")
version 3 only ( + exception )
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/qt.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Remove qtwebengine, which relies on a bundled copy of
error: cannot convert ‘bool’ to ‘boolean’ in return
it might also pose security problems.
Alternatively, we could use the "-skip qtwebengine"
configuration option.
to passing "-system-harfbuzz".
Remove the bundled sqlite copy in addition to
passing "-system-sqlite".
FIXME: Disabling parallel building is a quick hack to avoid the
failure described in
-devel/2016-01/msg00837.html
A more structural fix is needed.
do not pass "--enable-fast-install", which makes the
configure process fail
Do not build examples; if desired, these could go
into a separate output, but for the time being, we
prefer to save the space and build time.
Most "-system-..." are automatic, but some use
the bundled copy by default.
explicitly link with openssl instead of dlopening it
drop special machine instructions not supported
on all instances of the target
see <>.
see < > .
Remove webkit module, which is not built.
but we can't make them a separate output because "out" and "examples"
would refer to each other.
Note: Don't pass '-docdir' since 'qmake' and
libQtCore would record its value, thereby defeating
the whole point of having a separate output.
Skip the webkit module; it fails to build on armhf
and, apart from that, may pose security risks.
drop special machine instructions not supported
on all instances of the target
different "devices" due to bind-mounts.
to passing "-system-harfbuzz".
Remove the bundled sqlite copy in addition to
passing "-system-sqlite".
through a call to "find_package" in Qt5Config.cmake, which
disables the use of CMAKE_PREFIX_PATH via the parameter
"NO_DEFAULT_PATH". Re-enable it so that the different
components can be installed in different places.
do not pass "--enable-fast-install", which makes the
configure process fail
Do not build examples; if desired, these could go
into a separate output, but for the time being, we
prefer to save the space and build time.
Most "-system-..." are automatic, but some use
the bundled copy by default.
explicitly link with openssl instead of dlopening it
drop special machine instructions not supported
on all instances of the target
For each Qt module, let `qmake' uses search paths in the
module directory instead of all in QT_INSTALL_PREFIX.
TODO: Enable the tests
TODO: Enable the tests
TODO: Enable the tests
We also prevent the spectrum example from being built.
TODO: Enable the tests
TODO: Enable the tests
TODO: Enable the tests
TODO: Enable the tests
TODO: Enable the tests
TODO: Enable the tests
fail, so we skip building them for now.
TODO: Enable the tests
TODO: Enable the tests
TODO: Enable the tests
no check target
There is a choice between a python like license, gpl2 and gpl3.
for qmake
files. Without this the stubs are tried to be
installed into the python package's
site-package directory, which is read-only.
no check target
choice of either license
No tests included
Remove some incomplete manual pages.
<-project.org/pipermail/development/2016-May/025923.html>.
and replace references to the build directory in linker options:
by default, these Makefiles are
generated during install, but we need
to generate them now
Order of qmake calls and substitutions matters here.
files, lest they get rebuilt: | Copyright © 2013 , 2014 , 2015 < >
Copyright © 2015 < >
Copyright © 2015 < >
Copyright © 2015 , 2016 , 2017 < >
Copyright © 2016 , 2017 ng0 < >
Copyright © 2016 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages qt)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build utils)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix packages)
#:use-module (guix utils)
#:use-module (gnu packages)
#:use-module (gnu packages bison)
#:use-module (gnu packages compression)
#:use-module (gnu packages cups)
#:use-module (gnu packages databases)
#:use-module (gnu packages documentation)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages flex)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages gl)
#:use-module (gnu packages glib)
#:use-module (gnu packages gnuzilla)
#:use-module (gnu packages gperf)
#:use-module (gnu packages gtk)
#:use-module (gnu packages icu4c)
#:use-module (gnu packages image)
#:use-module (gnu packages linux)
#:use-module (gnu packages databases)
#:use-module (gnu packages pciutils)
#:use-module (gnu packages pcre)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages pulseaudio)
#:use-module (gnu packages python)
#:use-module (gnu packages ruby)
#:use-module (gnu packages sdl)
#:use-module (gnu packages tls)
#:use-module (gnu packages xdisorg)
#:use-module (gnu packages xorg)
#:use-module (gnu packages xml))
(define-public grantlee
(package
(name "grantlee")
(version "5.1.0")
(source
(origin
(method url-fetch)
(uri (string-append ""
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32 "1lf9rkv0i0kd7fvpgg5l8jb87zw8dzcwd1liv6hji7g4wlpmfdiq"))))
(native-inputs
`(("doxygen" ,doxygen)))
(inputs
`(("qtbase" ,qtbase)
("qtscript" ,qtscript)))
(build-system cmake-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'check
(lambda _
exclude 2 tests which require a display
"-E" "htmlbuildertest|plainmarkupbuildertest")))))))
(home-page "")
(synopsis "Libraries for text templating with Qt")
(description "Grantlee Templates can be used for theming and generation of
other text such as code. The syntax uses the syntax of the Django template
system, and the core design of Django is reused in Grantlee.")
(license license:lgpl2.0+)))
(define-public qt
(package
(name "qt")
(version "5.6.2")
(source (origin
(method url-fetch)
(uri
(string-append
"/"
(version-major+minor version)
"/" version
"/single/qt-everywhere-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1cw93mrlkqbwndfqyjpsvjzkpzi39px2is040xvk18mvg3y1prl3"))
(modules '((guix build utils)))
(snippet
'(begin
chromium . Not only does it fail compilation in qt 5.5 :
3rdparty / chromium / ui / gfx / codec / jpeg_codec.cc:362:10 :
(delete-file-recursively "qtwebengine")
Remove one of the two bundled harfbuzz copies in addition
(delete-file-recursively "qtbase/src/3rdparty/harfbuzz-ng")
(delete-file-recursively "qtbase/src/3rdparty/sqlite")))))
(build-system gnu-build-system)
(propagated-inputs
`(("mesa" ,mesa)))
(inputs
`(("alsa-lib" ,alsa-lib)
("dbus" ,dbus)
("cups" ,cups)
("expat" ,expat)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("glib" ,glib)
("harfbuzz" ,harfbuzz)
("icu4c" ,icu4c)
("libjpeg" ,libjpeg)
("libmng" ,libmng)
("libpci" ,pciutils)
("libpng" ,libpng)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)
("libxcursor" ,libxcursor)
("libxfixes" ,libxfixes)
("libxi" ,libxi)
("libxinerama" ,libxinerama)
("libxkbcommon" ,libxkbcommon)
("libxml2" ,libxml2)
("libxrandr" ,libxrandr)
("libxrender" ,libxrender)
("libxslt" ,libxslt)
("libxtst" ,libxtst)
("mtdev" ,mtdev)
("mysql" ,mysql)
("nss" ,nss)
("openssl" ,openssl)
("postgresql" ,postgresql)
("pulseaudio" ,pulseaudio)
("pcre" ,pcre)
("sqlite" ,sqlite)
("udev" ,eudev)
("unixodbc" ,unixodbc)
("xcb-util" ,xcb-util)
("xcb-util-image" ,xcb-util-image)
("xcb-util-keysyms" ,xcb-util-keysyms)
("xcb-util-renderutil" ,xcb-util-renderutil)
("xcb-util-wm" ,xcb-util-wm)
("zlib" ,zlib)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("gperf" ,gperf)
("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("ruby" ,ruby)
("which" ,(@ (gnu packages base) which))))
(arguments
#:parallel-build? #f
#:phases
(modify-phases %standard-phases
(add-after 'configure 'patch-bin-sh
(lambda _
(substitute* '("qtbase/config.status"
"qtbase/configure"
"qtbase/mkspecs/features/qt_functions.prf"
"qtbase/qmake/library/qmakebuiltins.cpp")
(("/bin/sh") (which "sh")))
#t))
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(substitute* '("configure" "qtbase/configure")
(("/bin/pwd") (which "pwd")))
(substitute* "qtbase/src/corelib/global/global.pri"
(("/bin/ls") (which "ls")))
(zero? (system*
"./configure"
"-verbose"
"-prefix" out
"-opensource"
"-confirm-license"
"-nomake" "examples"
"-system-sqlite"
"-system-harfbuzz"
"-openssl-linked"
explicitly link with dbus instead of dlopening it
"-dbus-linked"
,@(if (string-prefix? "x86_64"
(or (%current-target-system)
(%current-system)))
'()
'("-no-sse2"))
"-no-sse3"
"-no-ssse3"
"-no-sse4.1"
"-no-sse4.2"
"-no-avx"
"-no-avx2"
"-no-mips_dsp"
"-no-mips_dspr2"))))))))
(home-page "/")
(synopsis "Cross-platform GUI library")
(description "Qt is a cross-platform application and UI framework for
developers using C++ or QML, a CSS & JavaScript like language.")
(license license:lgpl2.1)
(supported-systems (delete "mips64el-linux" %supported-systems))))
(define-public qt-4
(package (inherit qt)
(version "4.8.7")
(source (origin
(method url-fetch)
(uri (string-append "-project.org/official_releases/qt/"
(string-copy version 0 (string-rindex version #\.))
"/" version
"/qt-everywhere-opensource-src-"
version ".tar.gz"))
(sha256
(base32
"183fca7n7439nlhxyg1z7aky0izgbyll3iwakw4gwivy16aj5272"))
(patches (search-patches "qt4-ldflags.patch"))
(modules '((guix build utils)))
(snippet
'(delete-file-recursively "src/3rdparty/webkit"))))
(inputs `(,@(alist-delete "harfbuzz"
(alist-delete "libjpeg" (package-inputs qt)))
("libjepg" ,libjpeg-8)
("libsm" ,libsm)))
Note : there are 37 MiB of examples and a ' -exampledir ' configure flags ,
112MiB core + 37MiB examples
280MiB of HTML + code
(arguments
`(#:phases
(modify-phases %standard-phases
(replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc")))
(substitute* '("configure")
(("/bin/pwd") (which "pwd")))
(zero? (system*
"./configure"
"-verbose"
"-prefix" out
"-datadir" (string-append out "/share/qt-" ,version
"/data")
"-importdir" (string-append out "/lib/qt-4"
"/imports")
"-plugindir" (string-append out "/lib/qt-4"
"/plugins")
"-translationdir" (string-append out "/share/qt-" ,version
"/translations")
"-demosdir" (string-append out "/share/qt-" ,version
"/demos")
"-examplesdir" (string-append out "/share/qt-" ,version
"/examples")
"-opensource"
"-confirm-license"
explicitly link with dbus instead of dlopening it
"-dbus-linked"
"-no-webkit"
,@(if (string-prefix? "x86_64"
(or (%current-target-system)
(%current-system)))
'()
'("-no-mmx"
"-no-3dnow"
"-no-sse"
"-no-sse2"))
"-no-sse3"
"-no-ssse3"
"-no-sse4.1"
"-no-sse4.2"
"-no-avx")))))
(add-after
'install 'move-doc
(lambda* (#:key outputs #:allow-other-keys)
Because of qt4-documentation-path.patch , documentation ends up
being installed in OUT . Move it to the right place .
(let* ((out (assoc-ref outputs "out"))
(doc (assoc-ref outputs "doc"))
(olddoc (string-append out "/doc"))
(docdir (string-append doc "/share/doc/qt-" ,version)))
(mkdir-p (dirname docdir))
Note : We ca n't use ' rename - file ' here because OUT and DOC are
(copy-recursively olddoc docdir)
(delete-file-recursively olddoc)
#t))))))))
(define-public qtbase
(package
(name "qtbase")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0zjmcrmnnmaz1lr9wc5i6y565hsvl8ycn790ivqaz62dv54zbkgd"))
(modules '((guix build utils)))
(snippet
'(begin
Remove one of the two bundled harfbuzz copies in addition
(delete-file-recursively "src/3rdparty/harfbuzz-ng")
(delete-file-recursively "src/3rdparty/sqlite")))))
(build-system gnu-build-system)
(propagated-inputs
`(("mesa" ,mesa)))
(inputs
`(("alsa-lib" ,alsa-lib)
("cups" ,cups)
("dbus" ,dbus)
("eudev" ,eudev)
("expat" ,expat)
("fontconfig" ,fontconfig)
("freetype" ,freetype)
("glib" ,glib)
("harfbuzz" ,harfbuzz)
("icu4c" ,icu4c)
("libinput" ,libinput)
("libjpeg" ,libjpeg)
("libmng" ,libmng)
("libpng" ,libpng)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)
("libxcursor" ,libxcursor)
("libxfixes" ,libxfixes)
("libxi" ,libxi)
("libxinerama" ,libxinerama)
("libxkbcommon" ,libxkbcommon)
("libxml2" ,libxml2)
("libxrandr" ,libxrandr)
("libxrender" ,libxrender)
("libxslt" ,libxslt)
("libxtst" ,libxtst)
("mtdev" ,mtdev)
("mysql" ,mysql)
("nss" ,nss)
("openssl" ,openssl)
("pcre" ,pcre)
("postgresql" ,postgresql)
("pulseaudio" ,pulseaudio)
("sqlite" ,sqlite)
("unixodbc" ,unixodbc)
("xcb-util" ,xcb-util)
("xcb-util-image" ,xcb-util-image)
("xcb-util-keysyms" ,xcb-util-keysyms)
("xcb-util-renderutil" ,xcb-util-renderutil)
("xcb-util-wm" ,xcb-util-wm)
("zlib" ,zlib)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("gperf" ,gperf)
("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("ruby" ,ruby)
("which" ,(@ (gnu packages base) which))))
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'configure 'patch-bin-sh
(lambda _
(substitute* '("config.status"
"configure"
"mkspecs/features/qt_functions.prf"
"qmake/library/qmakebuiltins.cpp")
(("/bin/sh") (which "sh")))
#t))
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(substitute* "configure"
(("/bin/pwd") (which "pwd")))
(substitute* "src/corelib/global/global.pri"
(("/bin/ls") (which "ls")))
The configuration files for other Qt5 packages are searched
(substitute* (find-files "." ".*\\.cmake")
(("NO_DEFAULT_PATH") ""))
(zero? (system*
"./configure"
"-verbose"
"-prefix" out
"-opensource"
"-confirm-license"
"-nomake" "examples"
"-system-sqlite"
"-system-harfbuzz"
"-openssl-linked"
explicitly link with dbus instead of dlopening it
"-dbus-linked"
,@(if (string-prefix? "x86_64"
(or (%current-target-system)
(%current-system)))
'()
'("-no-sse2"))
"-no-sse3"
"-no-ssse3"
"-no-sse4.1"
"-no-sse4.2"
"-no-avx"
"-no-avx2"
"-no-mips_dsp"
"-no-mips_dspr2")))))
(add-after 'install 'patch-qt_config.prf
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(qt_config.prf (string-append
out "/mkspecs/features/qt_config.prf")))
(substitute* qt_config.prf
(("\\$\\$\\[QT_INSTALL_HEADERS\\]")
"$$replace(dir, mkspecs/modules, include)")
(("\\$\\$\\[QT_INSTALL_LIBS\\]")
"$$replace(dir, mkspecs/modules, lib)")
(("\\$\\$\\[QT_HOST_LIBS\\]")
"$$replace(dir, mkspecs/modules, lib)")
(("\\$\\$\\[QT_INSTALL_PLUGINS\\]")
"$$replace(dir, mkspecs/modules, plugins)")
(("\\$\\$\\[QT_INSTALL_LIBEXECS\\]")
"$$replace(dir, mkspecs/modules, libexec)")
(("\\$\\$\\[QT_INSTALL_BINS\\]")
"$$replace(dir, mkspecs/modules, bin)")
(("\\$\\$\\[QT_INSTALL_IMPORTS\\]")
"$$replace(dir, mkspecs/modules, imports)")
(("\\$\\$\\[QT_INSTALL_QML\\]")
"$$replace(dir, mkspecs/modules, qml)"))
#t))))))
(native-search-paths
(list (search-path-specification
(variable "QMAKEPATH")
(files '("")))
(search-path-specification
(variable "QML2_IMPORT_PATH")
(files '("qml")))
(search-path-specification
(variable "QT_PLUGIN_PATH")
(files '("plugins")))
(search-path-specification
(variable "XDG_DATA_DIRS")
(files '("share")))
(search-path-specification
(variable "XDG_CONFIG_DIRS")
(files '("etc/xdg")))))
(home-page "/")
(synopsis "Cross-platform GUI library")
(description "Qt is a cross-platform application and UI framework for
developers using C++ or QML, a CSS & JavaScript like language.")
(license (list license:lgpl2.1 license:lgpl3))))
(define-public qtsvg
(package (inherit qtbase)
(name "qtsvg")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0irr9h566hl9nx8p919rz276zbfvvd6vqdb6i9g6b3piikdigw5h"))))
(propagated-inputs `())
(native-inputs `(("perl" ,perl)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)
("zlib" ,zlib)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
variables are :
libs tools tests examples demos docs translations
(zero? (system* "qmake" "QT_BUILD_PARTS = libs tools tests"
(string-append "PREFIX=" out))))))
(add-before 'install 'fix-Makefiles
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(qtbase (assoc-ref inputs "qtbase")))
(substitute* (find-files "." "Makefile")
(((string-append "INSTALL_ROOT)" qtbase))
(string-append "INSTALL_ROOT)" out)))
#t)))
(add-before 'check 'set-display
(lambda _
(setenv "QT_QPA_PLATFORM" "offscreen")
#t)))))))
(define-public qtimageformats
(package (inherit qtsvg)
(name "qtimageformats")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1x3p1xmw7spxa4bwriyrwsfrq31jabsdjsi5fras9y39naia55sg"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively "src/3rdparty")))))
(native-inputs `())
(inputs
`(("jasper" ,jasper)
("libmng" ,libmng)
("libtiff" ,libtiff)
("libwebp" ,libwebp)
("mesa" ,mesa)
("qtbase" ,qtbase)
("zlib" ,zlib)))))
(define-public qtx11extras
(package (inherit qtsvg)
(name "qtx11extras")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"09z49jm70f5i0gcdz9a16z00pg96x8pz7vri5wpirh3fqqn0qnjz"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(native-inputs `(("perl" ,perl)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)))))
(define-public qtxmlpatterns
(package (inherit qtsvg)
(name "qtxmlpatterns")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1rgqnpg64gn5agmvjwy0am8hp5fpxl3cdkixr1yrsdxi5a6961d8"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
((#:phases phases)
`(modify-phases ,phases
(add-after 'unpack 'disable-network-tests
(lambda _ (substitute* "tests/auto/auto.pro"
(("qxmlquery") "# qxmlquery")
(("xmlpatterns") "# xmlpatterns"))
#t))))))
(native-inputs `(("perl" ,perl)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtdeclarative
(package (inherit qtsvg)
(name "qtdeclarative")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0mjxfwnplpx60jc6y94krg00isddl9bfwc7dayl981njb4qds4zx"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("qtsvg" ,qtsvg)
("qtxmlpatterns" ,qtxmlpatterns)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)))))
(define-public qtconnectivity
(package (inherit qtsvg)
(name "qtconnectivity")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0rmr7bd4skby7bax9hpj2sid2bq3098nkw7xm02mdp04hc3bks5k"))))
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("bluez" ,bluez)
("qtbase" ,qtbase)))))
(define-public qtwebsockets
(package (inherit qtsvg)
(name "qtwebsockets")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1laj0slwibs0bg69kgrdhc9k1s6yisq3pcsr0r9rhbkzisv7aajw"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtsensors
(package (inherit qtsvg)
(name "qtsensors")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"041v1x8pwfzpyk6y0sy5zgm915pi15xdhiy18fd5wqayvcp99cyc"))))
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtmultimedia
(package (inherit qtsvg)
(name "qtmultimedia")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1vvxmgmvjnz9w1h2ph1j2fy77ij141ycx5fric60lq02pxzifax5"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively
"examples/multimedia/spectrum/3rdparty")
(substitute* "examples/multimedia/multimedia.pro"
(("spectrum") "#"))))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)
("python" ,python-2)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("alsa-lib" ,alsa-lib)
("mesa" ,mesa)
("pulseaudio" ,pulseaudio)
("qtbase" ,qtbase)))))
(define-public qtwayland
(package (inherit qtsvg)
(name "qtwayland")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1iq1c89y4ggq0dxjlf62jyhh8a9l3x7y914x84w5pby8h3hwagzj"))))
(native-inputs
`(("glib" ,glib)
("perl" ,perl)
("pkg-config" ,pkg-config)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("fontconfig" ,fontconfig)
("freetype" ,freetype)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)
("libxext" ,libxext)
("libxkbcommon" ,libxkbcommon)
("libxrender" ,libxrender)
("mesa" ,mesa)
("mtdev" ,mtdev)
("qtbase" ,qtbase)
("wayland" ,wayland)))))
(define-public qtserialport
(package (inherit qtsvg)
(name "qtserialport")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"09jsryc0z49cz9783kq48rkn42f10c6krzivp812ddwjsfdy3mbn"))))
(native-inputs `(("perl" ,perl)))
(inputs
`(("qtbase" ,qtbase)
("eudev" ,eudev)))))
(define-public qtserialbus
(package (inherit qtsvg)
(name "qtserialbus")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0mxi43l2inpbar8rmg21qjg33bv3f1ycxjgvzjf12ncnybhdnzkj"))))
(inputs
`(("qtbase" ,qtbase)
("qtserialport" ,qtserialport)))))
(define-public qtwebchannel
(package (inherit qtsvg)
(name "qtwebchannel")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"16rij92dxy4k5231l3dpmhy7cnz0cjkn50cpzaf014zrdz3kmav3"))))
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)
("qtwebsockets" ,qtwebsockets)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qtlocation
(package (inherit qtsvg)
(name "qtlocation")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"17zkzffzwbg6aqhsggs23cmwzq4y45m938842lsc423hfm7fdsgr"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)
("qtquickcontrols" ,qtquickcontrols)
("qtserialport" ,qtserialport)))
(inputs `(("qtbase" ,qtbase)))))
(define-public qttools
(package (inherit qtsvg)
(name "qttools")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1b6zqa5690b8lqms7rrhb8rcq0xg5hp117v3m08qngbcd0i706b4"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(native-inputs
`(("perl" ,perl)
("qtdeclarative" ,qtdeclarative)))
(inputs
`(("mesa" ,mesa)
("qtbase" ,qtbase)))))
(define-public qtscript
(package (inherit qtsvg)
(name "qtscript")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"09m41n95448pszr7inlg03ycb66s1a9hzfylaka92382acf1myav"))))
(native-inputs
`(("perl" ,perl)
("qttools" ,qttools)))
(inputs
`(("qtbase" ,qtbase)))))
(define-public qtquickcontrols
(package (inherit qtsvg)
(name "qtquickcontrols")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"17cyfyqzjbm9dhq9pjscz36y84y16rmxwk6h826gjfprddrimsvg"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtquickcontrols2
(package (inherit qtsvg)
(name "qtquickcontrols2")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1v77ydy4k15lksp3bi2kgha2h7m79g4n7c2qhbr09xnvpb8ars7j"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtgraphicaleffects
(package (inherit qtsvg)
(name "qtgraphicaleffects")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1j2drnx7zp3w6cgvy7bn00fyk5v7vw1j1hidaqcg78lzb6zgls1c"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtdeclarative-render2d
(package (inherit qtsvg)
(name "qtdeclarative-render2d")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0zwch9vn17f3bpy300jcfxx6cx9qymk5j7khx0x9k1xqid4166c3"))
(modules '((guix build utils)))
(snippet
'(delete-file-recursively "tools/opengldummy/3rdparty"))))
(native-inputs `())
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtgamepad
(package (inherit qtsvg)
(name "qtgamepad")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"10lijbsg9xx5ddbbjymdgl41nxz99yn1qgiww2kkggxwwdjj2axv"))))
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)))
(inputs
`(("fontconfig" ,fontconfig)
("freetype" ,freetype)
("libxrender" ,libxrender)
("sdl2" ,sdl2)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtscxml
(package (inherit qtsvg)
(name "qtscxml")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"135kknqdmib2cjryfmvfgv7a2qx9pyba3m7i7nkbc5d742r4mbcx"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively "tests/3rdparty")
the scion test refers to the bundled 3rd party test code .
(substitute* "tests/auto/auto.pro"
(("scion") "#"))))))
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtpurchasing
(package (inherit qtsvg)
(name "qtpurchasing")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"0hkvrgafz1hx9q4yc3nskv3pd3fszghvvd5a7mj33ynf55wpb57n"))))
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtcanvas3d
(package (inherit qtsvg)
(name "qtcanvas3d")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1d5xpq3mhjg4ipxzap7s2vnlfcd02d3yq720npv10xxp2ww0i1x8"))
(modules '((guix build utils)))
(snippet
'(delete-file-recursively "examples/canvas3d/3rdparty"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
Building the tests depends on the bundled 3rd party javascript files ,
and the test phase fails to import QtCanvas3D , causing the phase to
((#:phases phases)
`(modify-phases ,phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero? (system* "qmake" "QT_BUILD_PARTS = libs tools"
(string-append "PREFIX=" out))))))))
(native-inputs `())
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtcharts
(package (inherit qtsvg)
(name "qtcharts")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1qrzcddwff2hxsbxrraff16j4abah2zkra2756s1mvydj9lyxzl5"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public qtdatavis3d
(package (inherit qtsvg)
(name "qtdatavis3d")
(version "5.7.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version) "/" version
"/submodules/" name "-opensource-src-"
version ".tar.xz"))
(sha256
(base32
"1y00p0wyj5cw9c2925y537vpmmg9q3kpf7qr1s7sv67dvvf8bzqv"))))
(arguments
(substitute-keyword-arguments (package-arguments qtsvg)
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))))
(define-public python-sip
(package
(name "python-sip")
(version "4.18.1")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"sip-" version "/sip-" version ".tar.gz"))
(sha256
(base32
"1452zy3g0qv4fpd9c0y4gq437kn0xf7bbfniibv5n43zpwnpmklv"))))
(build-system gnu-build-system)
(native-inputs
`(("python" ,python-wrapper)))
(arguments
#:modules ((srfi srfi-1)
,@%gnu-build-system-modules)
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(include (string-append out "/include"))
(python (assoc-ref inputs "python"))
(python-version
(last (string-split python #\-)))
(python-major+minor
(string-join
(take (string-split python-version #\.) 2)
"."))
(lib (string-append out "/lib/python"
python-major+minor
"/site-packages")))
(zero?
(system* "python" "configure.py"
"--bindir" bin
"--destdir" lib
"--incdir" include))))))))
(home-page "")
(synopsis "Python binding creator for C and C++ libraries")
(description
"SIP is a tool to create Python bindings for C and C++ libraries. It
was originally developed to create PyQt, the Python bindings for the Qt
toolkit, but can be used to create bindings for any C or C++ library.
SIP comprises a code generator and a Python module. The code generator
processes a set of specification files and generates C or C++ code, which
is then compiled to create the bindings extension module. The SIP Python
module provides support functions to the automatically generated code.")
For compatibility with pyqt , we need gpl3 .
(license license:gpl3)))
(define-public python2-sip
(package (inherit python-sip)
(name "python2-sip")
(native-inputs
`(("python" ,python-2)))))
(define-public python-pyqt
(package
(name "python-pyqt")
(version "5.7")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"PyQt-" version "/PyQt5_gpl-"
version ".tar.gz"))
(sha256
(base32
"01avscn1bir0h8zzfh1jvpljgwg6qkax5nk142xrm63rbyx969l9"))
(patches (search-patches "pyqt-configure.patch"))))
(build-system gnu-build-system)
(native-inputs
`(("python-sip" ,python-sip)
(inputs
`(("python" ,python-wrapper)
("qtbase" ,qtbase)
("qtconnectivity" ,qtconnectivity)
("qtdeclarative" ,qtdeclarative)
("qtlocation" ,qtlocation)
("qtmultimedia" ,qtmultimedia)
("qtsensors" ,qtsensors)
("qtserialport" ,qtserialport)
("qtsvg" ,qtsvg)
("qttools" ,qttools)
("qtwebchannel" ,qtwebchannel)
("qtwebkit" ,qtwebkit)
("qtwebsockets" ,qtwebsockets)
("qtx11extras" ,qtx11extras)
("qtxmlpatterns" ,qtxmlpatterns)))
(arguments
`(#:modules ((srfi srfi-1)
,@%gnu-build-system-modules)
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(sip (string-append out "/share/sip"))
(plugins (string-append out "/plugins"))
(designer (string-append plugins "/designer"))
(qml (string-append plugins "/PyQt5"))
(python (assoc-ref inputs "python"))
(python-version
(last (string-split python #\-)))
(python-major+minor
(string-join
(take (string-split python-version #\.) 2)
"."))
(lib (string-append out "/lib/python"
python-major+minor
"/site-packages"))
(stubs (string-append lib "/PyQt5")))
(zero? (system* "python" "configure.py"
"--confirm-license"
"--bindir" bin
"--destdir" lib
"--designer-plugindir" designer
"--qml-plugindir" qml
Where to install the PEP 484 Type Hints stub
"--stubsdir" stubs
"--sipdir" sip))))))))
(home-page "")
(synopsis "Python bindings for Qt")
(description
"PyQt is a set of Python v2 and v3 bindings for the Qt application
framework. The bindings are implemented as a set of Python modules and
contain over 620 classes.")
(license license:gpl3)))
(define-public python2-pyqt
(package (inherit python-pyqt)
(name "python2-pyqt")
(native-inputs
`(("python-sip" ,python2-sip)
("qtbase" ,qtbase)))
(inputs
`(("python" ,python-2)
,@(alist-delete "python" (package-inputs python-pyqt))))))
(define-public python-pyqt-4
(package (inherit python-pyqt)
(name "python-pyqt")
(version "4.11.4")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
"PyQt-" version "/PyQt-x11-gpl-"
version ".tar.gz"))
(sha256
(base32
"01zlviy5lq8g6db84wnvvpsrfnip9lbcpxagsyqa6as3jmsff7zw"))))
(native-inputs
`(("python-sip" ,python-sip)
("qt" ,qt-4)))
(inputs `(("python" ,python-wrapper)))
(arguments
#:modules ((srfi srfi-1)
,@%gnu-build-system-modules)
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(sip (string-append out "/share/sip"))
(python (assoc-ref inputs "python"))
(python-version
(last (string-split python #\-)))
(python-major+minor
(string-join
(take (string-split python-version #\.) 2)
"."))
(lib (string-append out "/lib/python"
python-major+minor
"/site-packages")))
(zero? (system* "python" "configure.py"
"--confirm-license"
"--bindir" bin
"--destdir" lib
"--sipdir" sip))))))))
(define-public python2-pyqt-4
(package (inherit python-pyqt-4)
(name "python2-pyqt")
(native-inputs
`(("python-sip" ,python2-sip)
("qt" ,qt-4)))
(inputs
`(("python" ,python-2)))))
(define-public qtkeychain
(package
(name "qtkeychain")
(version "0.7.0")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"archive/v" version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32 "0fka5q5cdzlf79igcjgbnb2smvwbwfasqawkzkbr34whispgm6lz"))))
(build-system cmake-build-system)
(native-inputs
`(("qttools" ,qttools)))
(inputs
`(("qtbase" ,qtbase)))
(arguments
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-qt-trans-dir
(lambda _
(substitute* "CMakeLists.txt"
(("\\$\\{qt_translations_dir\\}")
"${CMAKE_INSTALL_PREFIX}/share/qt/translations")))))))
(home-page "")
(synopsis "Qt API to store passwords")
(description
"QtKeychain is a Qt library to store passwords and other secret data
securely. It will not store any data unencrypted unless explicitly requested.")
(license license:bsd-3)))
(define-public qwt
(package
(name "qwt")
(version "6.1.3")
(source
(origin
(method url-fetch)
(uri
(string-append "mirror/"
version "/qwt-" version ".tar.bz2"))
(sha256
(base32 "0cwp63s03dw351xavb3pzbjlqvx7kj88wv7v4a2b18m9f97d7v7k"))))
(build-system gnu-build-system)
(inputs
`(("qtbase" ,qtbase)
("qtsvg" ,qtsvg)
("qttools" ,qttools)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(substitute* '("qwtconfig.pri")
(("/usr/local/qwt-\\$\\$QWT\\_VERSION") out))
(zero? (system* "qmake")))))
(add-after 'install 'install-documentation
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(man (string-append out "/share/man")))
(for-each delete-file (find-files "doc/man/man3" "^_tmp.*"))
(mkdir-p man)
(copy-recursively "doc/man" man)
#t))))))
(home-page "")
(synopsis "Qt widgets for plots, scales, dials and other technical software
GUI components")
(description
"The Qwt library contains widgets and components which are primarily useful
for technical and scientific purposes. It includes a 2-D plotting widget,
different kinds of sliders, and much more.")
(license
(list
The Qwt license is LGPL2.1 with some exceptions .
(license:non-copyleft "")
textengines / mathml / qwt_mml_document.{cpp , h } is dual LGPL2.1 / GPL3 ( either ) .
license:lgpl2.1 license:gpl3))))
(define-public qtwebkit
(package
(name "qtwebkit")
(version "5.7.1")
(source
(origin
(method url-fetch)
(uri (string-append "/"
(version-major+minor version)
"/" version "/qtwebkit-opensource-src-" version
".tar.xz"))
Note : since Qt 5.6 , Qt no longer officially supports :
(sha256
(base32
"00szgcra6pf2myfjrdbsr1gmrxycpbjqlzkplna5yr1rjg4gfv54"))))
(build-system gnu-build-system)
(native-inputs
`(("perl" ,perl)
("python" ,python-2.7)
("ruby" ,ruby)
("bison" ,bison)
("flex" ,flex)
("gperf" ,gperf)
("pkg-config" ,pkg-config)))
(inputs
`(("icu" ,icu4c)
("libjpeg" ,libjpeg)
("libpng" ,libpng)
("libwebp" ,libwebp)
("sqlite" ,sqlite)
("fontconfig" ,fontconfig)
("libxrender", libxrender)
("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)
("qtmultimedia" ,qtmultimedia)
("libxml2" ,libxml2)
("libxslt" ,libxslt)
("libx11" ,libx11)
("libxcomposite" ,libxcomposite)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(setenv "QMAKEPATH"
(string-append (getcwd) "/Tools/qmake:"
(getenv "QMAKEPATH")))
(system* "qmake"))))
prevent webkit from trying to install into the qtbase store directory ,
(add-before 'build 'patch-installpaths
(lambda* (#:key outputs inputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(qtbase (assoc-ref inputs "qtbase"))
(builddir (getcwd))
(linkbuild (string-append "-L" builddir))
(linkout (string-append "-L" out))
(makefiles
(map-in-order
(lambda (i)
(let* ((in (car i))
(mf (string-append (dirname in) "/"
(cdr i))))
(system* "qmake" in "-o" mf)
mf))
'(("Source/api.pri" . "Makefile.api")
("Source/widgetsapi.pri"
. "Makefile.widgetsapi")
("Source/WebKit2/WebProcess.pro"
. "Makefile.WebProcess")
("Source/WebKit2/PluginProcess.pro"
. "Makefile.PluginProcess")
("Source/WebKit/qt/declarative/public.pri"
. "Makefile.declarative.public")
("Source/WebKit/qt/declarative/experimental/experimental.pri"
. "Makefile.declarative.experimental")
("Source/WebKit/qt/examples/platformplugin/platformplugin.pro"
. "Makefile")))))
(system* "qmake" "-prl" "Source/widgetsapi.pri"
"-o" "Source/Makefile")
(substitute* (find-files "lib" "libQt5.*\\.prl")
((linkbuild) linkout))
(substitute* (find-files "lib"
"libQt5WebKit.*\\.la")
(("libdir='.*'")
(string-append "libdir='" out "/lib'"))
((linkbuild) linkout))
(substitute* (find-files "lib/pkgconfig"
"Qt5WebKit.*\\.pc")
(((string-append "prefix=" qtbase))
(string-append "prefix=" out))
((linkbuild) linkout))
Makefiles must be modified after .prl/.la/.pc
(substitute* makefiles
(((string-append "\\$\\(INSTALL_ROOT\\)" qtbase))
out )
(((string-append "-Wl,-rpath," builddir))
(string-append "-Wl,-rpath," out)))))))))
(home-page "")
(synopsis "Web browser engine and classes to render and interact with web
content")
(description "QtWebKit provides a Web browser engine that makes it easy to
embed content from the World Wide Web into your Qt application. At the same
time Web content can be enhanced with native controls.")
(license license:lgpl2.1+)))
(define-public dotherside
(package
(name "dotherside")
(version "0.5.2")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"archive/v" version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0pqlrvy4ajjir80ra79ka3n0rjj0ir0f0m91cq86iz3nnw8w148z"))))
(build-system cmake-build-system)
(native-inputs
`(("qttools" ,qttools)))
(inputs
`(("qtbase" ,qtbase)
("qtdeclarative" ,qtdeclarative)))
(home-page "")
(synopsis "C language library for creating bindings for the Qt QML language")
(description
"DOtherSide is a C language library for creating bindings for the
QT QML language. The following features are implementable from
a binding language:
@itemize
@item Creating custom QObject
@item Creating custom QAbstractListModels
@item Creating custom properties, signals and slots
@item Creating from QML QObject defined in the binded language
@item Creating from Singleton QML QObject defined in the binded language
@end itemize\n")
version 3 only ( + exception )
|
8bd3287ea9591cfa4835283005873a8f192bafa333483692a6c867a7b4a912f2 | khigia/eocarve | seamcarving.ml |
* seamcarve , content - aware image resizing using seam carving
* Copyright ( C ) 2007 < >
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
* seamcarve, content-aware image resizing using seam carving
* Copyright (C) 2007 Mauricio Fernandez <>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*)
type image = { width : int; height : int; rgb : Images.rgb array array; }
type path = int array
let load_image file =
let img = OImages.rgb24 (OImages.load file []) in
let rgb = Array.init img#height
(fun _ -> Array.make img#width {Color.r = 0; g = 0; b = 0}) in
for y = 0 to img#height - 1 do
for x = 0 to img#width - 1 do
rgb.(y).(x) <- img#get x y
done
done;
{ width = img#width; height = img#height; rgb = rgb }
let copy_image img =
let rgb' = Array.init img.height (fun i -> Array.copy img.rgb.(i)) in
{ img with rgb = rgb' }
let enlarge_image img n =
if n < 0 then invalid_arg "enlarge_image: negative increase";
let oldw = img.width in
let w = oldw + n in
let px = {Color.r = 0; g = 0; b = 0} in
let rgb' = Array.init img.height
(fun i ->
let a = Array.make w px in
Array.blit img.rgb.(i) 0 a 0 oldw; a) in
{ img with rgb = rgb' }
let save_image image filename =
let canvas = Rgb24.create image.width image.height in
let src = image.rgb in
for j = 0 to image.height - 1 do
let row = src.(j) in
for i = 0 to image.width - 1 do
Rgb24.set canvas i j row.(i)
done
done;
Images.save filename None [] (Images.Rgb24 canvas)
let rotate_image_cw img =
let src = img.rgb in
let w = img.width and h = img.height in
let rgb = Array.init w
(fun y -> Array.init h (fun x -> src.(h - x - 1).(y)))
in { width = img.height; height = img.width; rgb = rgb }
let rotate_image_ccw img =
let src = img.rgb in
let w = img.width and h = img.height in
let rgb = Array.init w
(fun y -> Array.init h
(fun x -> src.(x).(w - y - 1)))
in { width = img.height; height = img.width; rgb = rgb }
let average_color c1 c2 =
{ Color.r = (c1.Color.r + c2.Color.r) / 2;
Color.g = (c1.Color.g + c2.Color.g) / 2;
Color.b = (c1.Color.b + c2.Color.b) / 2; }
module type ENERGY_COMPUTATION =
sig
type energy
type t
val compute_energy : t -> image -> energy
val extract_energy_matrix : energy -> int array array
val update_energy_h : energy -> image -> path -> unit
end
module type S =
sig
type t
type energy_computation
val make : energy_computation -> image -> t
val image : t -> image
val save_energy : t -> string -> unit
val seam_carve_h : t -> t
val seam_carve_h' : t -> t * int array
end
module Make(M : ENERGY_COMPUTATION) : S with type energy_computation = M.t =
struct
type mono_bitmap = int array array
type mono_vector = int array
type t = {
cost : mono_bitmap;
energy : M.energy;
image : image;
}
type energy_computation = M.t
let image t = t.image
let dim2 b = Array.length b.(0)
let dim1 b = Array.length b
let dim b = Array.length b
let create_mono_bitmap w h = Array.init h (fun _ -> Array.make w 0)
let matrix_maximum src =
let rec vect_max (v : mono_vector) i limit max =
if i < limit then
vect_max v (i+1) limit (let c = v.(i) in if c > max then c else max)
else max
in
Array.fold_left (fun s x -> vect_max x 0 (Array.length x) s) min_int src
let normalize_matrix src =
let max = matrix_maximum src in
for j = 0 to dim1 src - 1 do
let row = src.(j) in
for i = 0 to dim2 src - 1 do
row.(i) <- 255 * row.(i) / max;
done
done
let blit w h src dst =
for j = 0 to h - 1 do
Array.blit src.(j) 0 dst.(j) 0 w
done
let save_energy t filename =
let h = t.image.height in
let w = t.image.width in
let e = create_mono_bitmap w h in
let canvas = Rgb24.create w h in
blit w h (M.extract_energy_matrix t.energy) e;
normalize_matrix e;
for j = 0 to h - 1 do
let row = e.(j) in
for i = 0 to w - 1 do
let c = row.(i) in
Rgb24.set canvas i j {Color.r = c; g = c; b = c}
done
done;
Images.save filename None [] (Images.Rgb24 canvas)
let min_index (arr : mono_vector) w =
let rec loop arr i max x v =
if i < max then begin
let v' = arr.(i) in
if v' < v then loop arr (i+1) max i v'
else loop arr (i+1) max x v
end else x
in
loop arr 0 w 0 arr.(0)
let print_path path =
print_endline
(String.concat "; "
(Array.to_list (Array.map string_of_int path)))
let shortest_path cost w h =
let int_max (a : int) b = if a > b then a else b in
let int_min (a : int) b = if a < b then a else b in
let path = Array.make h 0 in
let x = ref (min_index cost.(h - 1) w) in
path.(h-1) <- !x;
for j = h-2 downto 0 do
let best = ref max_int in
for i = int_max 0 (!x - 1) to int_min (w - 1) (!x + 1) do
let c = cost.(j).(i) in
if c < !best then begin
best := c;
x := i
end
done;
path.(j) <- !x;
done;
path
let make ecomputation img =
let energy = M.compute_energy ecomputation img in
let cost = create_mono_bitmap img.width img.height in
{ cost = cost; energy = energy; image = img }
let update_cost (cost : mono_bitmap) (e : mono_bitmap) w h =
let int_min (c1 : int) c2 = if c1 < c2 then c1 else c2 in
let int_min3 (c1 : int) c2 c3 =
if c1 < c2 then
if c1 < c3 then c1 else c3
else
if c2 < c3 then c2 else c3 in
let src = e.(0) in
let dst = cost.(0) in
Array.blit src 0 dst 0 (Array.length src);
for y = 1 to h - 1 do
let prev = cost.(y-1) in
let cur = cost.(y) in
let cur_e = e.(y) in
cur.(0) <- int_min prev.(0) prev.(1) + cur_e.(0);
for x = 1 to w - 2 do
let best = int_min3 prev.(x-1) prev.(x) prev.(x+1) in
cur.(x) <- best + cur_e.(x)
done;
cur.(w-1) <- int_min prev.(w-2) prev.(w-1) + cur_e.(w-1);
done
let seam_carve_h_aux f t =
let energy = t.energy in
let img = t.image in
let cost = t.cost in
let w = img.width in
let h = img.height in
let e = M.extract_energy_matrix energy in
if w < 10 then failwith "The image is too small to carve any further seams.";
update_cost cost e w h;
let path = shortest_path cost img.width img.height in
for j = 0 to h - 1 do
let row = img.rgb.(j) in
let rx = path.(j) in
(* (* slower routine which uses the avg color for the mid pixel *)
if rx < w - 1 then
row.(rx) <- average_color row.(rx) row.(rx+1);
- 2 since one pixel has been removed
row.(i) <- row.(i+1)
done
*)
(* hack to avoid caml_modify: pretend row is an int array so
* caml_modify isn't used. This is safe as long as no new objects are
* inserted in row (notably, the average_color thing above would crash
* this). If anybody else modifies rgb it will bomb. *)
let unsafe_row = (Obj.magic row : int array) in
- 2 since one pixel has been removed
(* avoid caml_modify *)
unsafe_row.(i) <- unsafe_row.(i+1)
done
done;
let img' = { img with width = img.width - 1 } in
M.update_energy_h energy img' path;
f { t with image = img'; } path
let seam_carve_h t = seam_carve_h_aux (fun t _ -> t) t
let seam_carve_h' t = seam_carve_h_aux (fun t path -> (t, path)) t
end
| null | https://raw.githubusercontent.com/khigia/eocarve/8a5f65b8175b27bfc0d792719485b5d31b72760a/seamcarve/seamcarving.ml | ocaml | (* slower routine which uses the avg color for the mid pixel
hack to avoid caml_modify: pretend row is an int array so
* caml_modify isn't used. This is safe as long as no new objects are
* inserted in row (notably, the average_color thing above would crash
* this). If anybody else modifies rgb it will bomb.
avoid caml_modify |
* seamcarve , content - aware image resizing using seam carving
* Copyright ( C ) 2007 < >
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
* seamcarve, content-aware image resizing using seam carving
* Copyright (C) 2007 Mauricio Fernandez <>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*)
type image = { width : int; height : int; rgb : Images.rgb array array; }
type path = int array
let load_image file =
let img = OImages.rgb24 (OImages.load file []) in
let rgb = Array.init img#height
(fun _ -> Array.make img#width {Color.r = 0; g = 0; b = 0}) in
for y = 0 to img#height - 1 do
for x = 0 to img#width - 1 do
rgb.(y).(x) <- img#get x y
done
done;
{ width = img#width; height = img#height; rgb = rgb }
let copy_image img =
let rgb' = Array.init img.height (fun i -> Array.copy img.rgb.(i)) in
{ img with rgb = rgb' }
let enlarge_image img n =
if n < 0 then invalid_arg "enlarge_image: negative increase";
let oldw = img.width in
let w = oldw + n in
let px = {Color.r = 0; g = 0; b = 0} in
let rgb' = Array.init img.height
(fun i ->
let a = Array.make w px in
Array.blit img.rgb.(i) 0 a 0 oldw; a) in
{ img with rgb = rgb' }
let save_image image filename =
let canvas = Rgb24.create image.width image.height in
let src = image.rgb in
for j = 0 to image.height - 1 do
let row = src.(j) in
for i = 0 to image.width - 1 do
Rgb24.set canvas i j row.(i)
done
done;
Images.save filename None [] (Images.Rgb24 canvas)
let rotate_image_cw img =
let src = img.rgb in
let w = img.width and h = img.height in
let rgb = Array.init w
(fun y -> Array.init h (fun x -> src.(h - x - 1).(y)))
in { width = img.height; height = img.width; rgb = rgb }
let rotate_image_ccw img =
let src = img.rgb in
let w = img.width and h = img.height in
let rgb = Array.init w
(fun y -> Array.init h
(fun x -> src.(x).(w - y - 1)))
in { width = img.height; height = img.width; rgb = rgb }
let average_color c1 c2 =
{ Color.r = (c1.Color.r + c2.Color.r) / 2;
Color.g = (c1.Color.g + c2.Color.g) / 2;
Color.b = (c1.Color.b + c2.Color.b) / 2; }
module type ENERGY_COMPUTATION =
sig
type energy
type t
val compute_energy : t -> image -> energy
val extract_energy_matrix : energy -> int array array
val update_energy_h : energy -> image -> path -> unit
end
module type S =
sig
type t
type energy_computation
val make : energy_computation -> image -> t
val image : t -> image
val save_energy : t -> string -> unit
val seam_carve_h : t -> t
val seam_carve_h' : t -> t * int array
end
module Make(M : ENERGY_COMPUTATION) : S with type energy_computation = M.t =
struct
type mono_bitmap = int array array
type mono_vector = int array
type t = {
cost : mono_bitmap;
energy : M.energy;
image : image;
}
type energy_computation = M.t
let image t = t.image
let dim2 b = Array.length b.(0)
let dim1 b = Array.length b
let dim b = Array.length b
let create_mono_bitmap w h = Array.init h (fun _ -> Array.make w 0)
let matrix_maximum src =
let rec vect_max (v : mono_vector) i limit max =
if i < limit then
vect_max v (i+1) limit (let c = v.(i) in if c > max then c else max)
else max
in
Array.fold_left (fun s x -> vect_max x 0 (Array.length x) s) min_int src
let normalize_matrix src =
let max = matrix_maximum src in
for j = 0 to dim1 src - 1 do
let row = src.(j) in
for i = 0 to dim2 src - 1 do
row.(i) <- 255 * row.(i) / max;
done
done
let blit w h src dst =
for j = 0 to h - 1 do
Array.blit src.(j) 0 dst.(j) 0 w
done
let save_energy t filename =
let h = t.image.height in
let w = t.image.width in
let e = create_mono_bitmap w h in
let canvas = Rgb24.create w h in
blit w h (M.extract_energy_matrix t.energy) e;
normalize_matrix e;
for j = 0 to h - 1 do
let row = e.(j) in
for i = 0 to w - 1 do
let c = row.(i) in
Rgb24.set canvas i j {Color.r = c; g = c; b = c}
done
done;
Images.save filename None [] (Images.Rgb24 canvas)
let min_index (arr : mono_vector) w =
let rec loop arr i max x v =
if i < max then begin
let v' = arr.(i) in
if v' < v then loop arr (i+1) max i v'
else loop arr (i+1) max x v
end else x
in
loop arr 0 w 0 arr.(0)
let print_path path =
print_endline
(String.concat "; "
(Array.to_list (Array.map string_of_int path)))
let shortest_path cost w h =
let int_max (a : int) b = if a > b then a else b in
let int_min (a : int) b = if a < b then a else b in
let path = Array.make h 0 in
let x = ref (min_index cost.(h - 1) w) in
path.(h-1) <- !x;
for j = h-2 downto 0 do
let best = ref max_int in
for i = int_max 0 (!x - 1) to int_min (w - 1) (!x + 1) do
let c = cost.(j).(i) in
if c < !best then begin
best := c;
x := i
end
done;
path.(j) <- !x;
done;
path
let make ecomputation img =
let energy = M.compute_energy ecomputation img in
let cost = create_mono_bitmap img.width img.height in
{ cost = cost; energy = energy; image = img }
let update_cost (cost : mono_bitmap) (e : mono_bitmap) w h =
let int_min (c1 : int) c2 = if c1 < c2 then c1 else c2 in
let int_min3 (c1 : int) c2 c3 =
if c1 < c2 then
if c1 < c3 then c1 else c3
else
if c2 < c3 then c2 else c3 in
let src = e.(0) in
let dst = cost.(0) in
Array.blit src 0 dst 0 (Array.length src);
for y = 1 to h - 1 do
let prev = cost.(y-1) in
let cur = cost.(y) in
let cur_e = e.(y) in
cur.(0) <- int_min prev.(0) prev.(1) + cur_e.(0);
for x = 1 to w - 2 do
let best = int_min3 prev.(x-1) prev.(x) prev.(x+1) in
cur.(x) <- best + cur_e.(x)
done;
cur.(w-1) <- int_min prev.(w-2) prev.(w-1) + cur_e.(w-1);
done
let seam_carve_h_aux f t =
let energy = t.energy in
let img = t.image in
let cost = t.cost in
let w = img.width in
let h = img.height in
let e = M.extract_energy_matrix energy in
if w < 10 then failwith "The image is too small to carve any further seams.";
update_cost cost e w h;
let path = shortest_path cost img.width img.height in
for j = 0 to h - 1 do
let row = img.rgb.(j) in
let rx = path.(j) in
if rx < w - 1 then
row.(rx) <- average_color row.(rx) row.(rx+1);
- 2 since one pixel has been removed
row.(i) <- row.(i+1)
done
*)
let unsafe_row = (Obj.magic row : int array) in
- 2 since one pixel has been removed
unsafe_row.(i) <- unsafe_row.(i+1)
done
done;
let img' = { img with width = img.width - 1 } in
M.update_energy_h energy img' path;
f { t with image = img'; } path
let seam_carve_h t = seam_carve_h_aux (fun t _ -> t) t
let seam_carve_h' t = seam_carve_h_aux (fun t path -> (t, path)) t
end
|
64773661d9c4ab8766ae0339f0b15824cd12b3ca8187f70ff17dc62f8679c9bb | lukehoersten/activitypub | Properties.hs | module Network.ActivityPub.Vocabulary.Properties where
import Data.Either (Either)
import Data.Text (Text)
import Data.Time (NominalDiffTime, UTCTime)
import Data.Word (Word)
import Network.URI (URI)
data Unit = Cm | Feed | Inches | Km | M | Miles deriving (Show, Eq)
type Accuracy = Float
type Altitude = Float
type Content = Text
type Name = Text
type Duration = NominalDiffTime
type Height = Word
type Href = URI
type HrefLang = Text -- [BCP47] Language Tag
type Latitude = Float
type Longitude = Float
type MediaType = Text -- MIME Media Type
type EndTime = UTCTime
type Published = UTCTime
type StartTime = UTCTime
type Radius = Float
type Rel = [Text] -- [RFC5988] or [HTML5] Link Relation
type StartIndex = Word
type Summary = Text
type TotalItems = Word
type Updated = UTCTime
type Width = Word
type Deleted = UTCTime
| null | https://raw.githubusercontent.com/lukehoersten/activitypub/b10e19f08b854b0c2aef768a8c972bcf61911c3a/src/Network/ActivityPub/Vocabulary/Properties.hs | haskell | [BCP47] Language Tag
MIME Media Type
[RFC5988] or [HTML5] Link Relation | module Network.ActivityPub.Vocabulary.Properties where
import Data.Either (Either)
import Data.Text (Text)
import Data.Time (NominalDiffTime, UTCTime)
import Data.Word (Word)
import Network.URI (URI)
data Unit = Cm | Feed | Inches | Km | M | Miles deriving (Show, Eq)
type Accuracy = Float
type Altitude = Float
type Content = Text
type Name = Text
type Duration = NominalDiffTime
type Height = Word
type Href = URI
type Latitude = Float
type Longitude = Float
type EndTime = UTCTime
type Published = UTCTime
type StartTime = UTCTime
type Radius = Float
type StartIndex = Word
type Summary = Text
type TotalItems = Word
type Updated = UTCTime
type Width = Word
type Deleted = UTCTime
|
0ab29a350ee4d7c876b3b221635ec1c6a50292024c213e642bc02d691284b475 | MichelBoucey/IPv6DB | Types.hs | # LANGUAGE DuplicateRecordFields #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
module Network.IPv6DB.Types where
import Data.Aeson as A
import qualified Data.Text as T
import qualified Data.Vector as V
import Text.IPv6Addr
newtype Addresses = Addresses [IPv6Addr]
instance FromJSON Addresses where
parseJSON (Array v) = do
let rslts = fromJSON <$> V.toList v
if all isSuccess rslts
then pure (Addresses $ fromSuccess <$> rslts)
else fail "Bad JSON Array Of IPv6 Addresses"
parseJSON _ = fail "JSON Array Expected"
data Entry =
Entry
{ list :: !T.Text
, address :: IPv6Addr
} deriving (Eq, Show)
instance FromJSON Entry where
parseJSON (Object o) = do
list <- o .: "list"
address <- o .: "address"
pure Entry{..}
parseJSON _ = fail "JSON Object Expected"
newtype Entries = Entries [Entry]
instance FromJSON Entries where
parseJSON (Array v) = do
let ents = fromJSON <$> V.toList v
if all isSuccess ents
then pure (Entries $ fromSuccess <$> ents)
else fail "Malformed JSON Array"
parseJSON _ = fail "JSON Array Expected"
newtype Source = Source Value deriving (Eq, Show)
instance ToJSON Source where
toJSON (Source v) = v
instance FromJSON Source where
parseJSON v = pure (Source v)
data Resource
= Resource
{ list :: !T.Text
, address :: !IPv6Addr
, ttl :: !(Maybe Integer)
, source :: !Source
}
| ResourceError
{ list :: !T.Text
, address :: !IPv6Addr
, error :: !T.Text
}
deriving (Eq, Show)
instance ToJSON Resource where
toJSON Resource{..} =
object
[ "list" .= list
, "address" .= address
, "ttl" .= ttl
, "source" .= source
]
toJSON ResourceError{error=err, ..} =
object
[ "list" .= list
, "address" .= address
, "error" .= err
]
instance FromJSON Resource where
parseJSON =
withObject "resource" $
\o -> do
list <- o .: "list"
address <- do
ma <- o .: "address"
case maybeIPv6Addr ma of
Just a -> pure a
Nothing -> fail "Not an IPv6 Address"
ttl <- o .:? "ttl"
source <- o .: "source"
return Resource{..}
newtype Resources = Resources [Resource] deriving (Eq, Show)
instance ToJSON Resources where
toJSON (Resources rs) =
object [ ("resources", Array (V.fromList $ toJSON <$> rs)) ]
instance FromJSON Resources where
parseJSON (Array v) = do
let rsrcs = fromJSON <$> V.toList v
if all isSuccess rsrcs
then pure (Resources $ fromSuccess <$> rsrcs)
else fail "Malformed JSON Array Of Resources"
parseJSON _ = fail "JSON Array Expected"
isSuccess :: Result a -> Bool
isSuccess (A.Success _) = True
isSuccess (A.Error _) = False
fromSuccess :: Result a -> a
fromSuccess (A.Success e) = e
fromSuccess (A.Error _) = Prelude.error "Success value only"
| null | https://raw.githubusercontent.com/MichelBoucey/IPv6DB/27f3f30264c2a890d364eb679c3a93cd3314075d/src/Network/IPv6DB/Types.hs | haskell | # LANGUAGE DuplicateRecordFields #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
module Network.IPv6DB.Types where
import Data.Aeson as A
import qualified Data.Text as T
import qualified Data.Vector as V
import Text.IPv6Addr
newtype Addresses = Addresses [IPv6Addr]
instance FromJSON Addresses where
parseJSON (Array v) = do
let rslts = fromJSON <$> V.toList v
if all isSuccess rslts
then pure (Addresses $ fromSuccess <$> rslts)
else fail "Bad JSON Array Of IPv6 Addresses"
parseJSON _ = fail "JSON Array Expected"
data Entry =
Entry
{ list :: !T.Text
, address :: IPv6Addr
} deriving (Eq, Show)
instance FromJSON Entry where
parseJSON (Object o) = do
list <- o .: "list"
address <- o .: "address"
pure Entry{..}
parseJSON _ = fail "JSON Object Expected"
newtype Entries = Entries [Entry]
instance FromJSON Entries where
parseJSON (Array v) = do
let ents = fromJSON <$> V.toList v
if all isSuccess ents
then pure (Entries $ fromSuccess <$> ents)
else fail "Malformed JSON Array"
parseJSON _ = fail "JSON Array Expected"
newtype Source = Source Value deriving (Eq, Show)
instance ToJSON Source where
toJSON (Source v) = v
instance FromJSON Source where
parseJSON v = pure (Source v)
data Resource
= Resource
{ list :: !T.Text
, address :: !IPv6Addr
, ttl :: !(Maybe Integer)
, source :: !Source
}
| ResourceError
{ list :: !T.Text
, address :: !IPv6Addr
, error :: !T.Text
}
deriving (Eq, Show)
instance ToJSON Resource where
toJSON Resource{..} =
object
[ "list" .= list
, "address" .= address
, "ttl" .= ttl
, "source" .= source
]
toJSON ResourceError{error=err, ..} =
object
[ "list" .= list
, "address" .= address
, "error" .= err
]
instance FromJSON Resource where
parseJSON =
withObject "resource" $
\o -> do
list <- o .: "list"
address <- do
ma <- o .: "address"
case maybeIPv6Addr ma of
Just a -> pure a
Nothing -> fail "Not an IPv6 Address"
ttl <- o .:? "ttl"
source <- o .: "source"
return Resource{..}
newtype Resources = Resources [Resource] deriving (Eq, Show)
instance ToJSON Resources where
toJSON (Resources rs) =
object [ ("resources", Array (V.fromList $ toJSON <$> rs)) ]
instance FromJSON Resources where
parseJSON (Array v) = do
let rsrcs = fromJSON <$> V.toList v
if all isSuccess rsrcs
then pure (Resources $ fromSuccess <$> rsrcs)
else fail "Malformed JSON Array Of Resources"
parseJSON _ = fail "JSON Array Expected"
isSuccess :: Result a -> Bool
isSuccess (A.Success _) = True
isSuccess (A.Error _) = False
fromSuccess :: Result a -> a
fromSuccess (A.Success e) = e
fromSuccess (A.Error _) = Prelude.error "Success value only"
|
|
252521601650b6d3f5278a3ce4780605b6e703d37eb3b1785f91b2e0518422b4 | nikita-volkov/rebase | Semigroupoid.hs | module Rebase.Data.Semigroupoid
(
module Data.Semigroupoid
)
where
import Data.Semigroupoid
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Data/Semigroupoid.hs | haskell | module Rebase.Data.Semigroupoid
(
module Data.Semigroupoid
)
where
import Data.Semigroupoid
|
|
e8d64ae039366cbc7f94feddf1f232a2cc59648993f2d41751fa276ecaf744d1 | vmchale/kempe | Warning.hs | {-# LANGUAGE OverloadedStrings #-}
module Kempe.Error.Warning ( Warning (..)
) where
import Control.Exception (Exception)
import Data.Semigroup ((<>))
import Data.Typeable (Typeable)
import Kempe.AST
import Kempe.Name
import Prettyprinter (Pretty (pretty), squotes, (<+>))
data Warning a = NameClash a (Name a)
| DoubleDip a (Atom a a) (Atom a a)
| SwapBinary a (Atom a a) (Atom a a)
| DoubleSwap a
| DipAssoc a (Atom a a)
| Identity a (Atom a a)
| PushDrop a (Atom a a)
instance Pretty a => Pretty (Warning a) where
pretty (NameClash l x) = pretty l <> " '" <> pretty x <> "' is defined more than once."
pretty (DoubleDip l a a') = pretty l <+> pretty a <+> pretty a' <+> "could be written as a single dip()"
pretty (SwapBinary l a a') = pretty l <+> squotes ("swap" <+> pretty a) <+> "is" <+> pretty a'
pretty (DoubleSwap l) = pretty l <+> "double swap"
pretty (DipAssoc l a) = pretty l <+> "dip(" <> pretty a <> ")" <+> pretty a <+> "is equivalent to" <+> pretty a <+> pretty a <+> "by associativity"
pretty (Identity l a) = pretty l <+> squotes ("dup" <+> pretty a) <+> "is identity"
pretty (PushDrop l a) = pretty l <+> squotes (pretty a <+> "drop") <+> "is identity"
instance (Pretty a) => Show (Warning a) where
show = show . pretty
instance (Pretty a, Typeable a) => Exception (Warning a)
| null | https://raw.githubusercontent.com/vmchale/kempe/b757170aeebd1098d1c99c8724ef200ef75b854e/src/Kempe/Error/Warning.hs | haskell | # LANGUAGE OverloadedStrings # |
module Kempe.Error.Warning ( Warning (..)
) where
import Control.Exception (Exception)
import Data.Semigroup ((<>))
import Data.Typeable (Typeable)
import Kempe.AST
import Kempe.Name
import Prettyprinter (Pretty (pretty), squotes, (<+>))
data Warning a = NameClash a (Name a)
| DoubleDip a (Atom a a) (Atom a a)
| SwapBinary a (Atom a a) (Atom a a)
| DoubleSwap a
| DipAssoc a (Atom a a)
| Identity a (Atom a a)
| PushDrop a (Atom a a)
instance Pretty a => Pretty (Warning a) where
pretty (NameClash l x) = pretty l <> " '" <> pretty x <> "' is defined more than once."
pretty (DoubleDip l a a') = pretty l <+> pretty a <+> pretty a' <+> "could be written as a single dip()"
pretty (SwapBinary l a a') = pretty l <+> squotes ("swap" <+> pretty a) <+> "is" <+> pretty a'
pretty (DoubleSwap l) = pretty l <+> "double swap"
pretty (DipAssoc l a) = pretty l <+> "dip(" <> pretty a <> ")" <+> pretty a <+> "is equivalent to" <+> pretty a <+> pretty a <+> "by associativity"
pretty (Identity l a) = pretty l <+> squotes ("dup" <+> pretty a) <+> "is identity"
pretty (PushDrop l a) = pretty l <+> squotes (pretty a <+> "drop") <+> "is identity"
instance (Pretty a) => Show (Warning a) where
show = show . pretty
instance (Pretty a, Typeable a) => Exception (Warning a)
|
7fda9f43ca5bae8a8362b5f5577a65b1bf390ba56685d08943675011067e51c4 | dannypsnl/racket-llvm | optimization.rkt | #lang racket
(require racket-llvm)
; let's create an if-else function
(define mod (llvm-module "optimizeMe"))
(define eng (llvm-create-execution-engine-for-module mod))
(llvm-link-in-mcjit)
(define builder (llvm-builder-create))
(define if-func (llvm-add-function mod
"if"
(llvm-function-type (llvm-int32-type))))
(llvm-builder-position-at-end builder (llvm-append-basic-block if-func))
(define cmp (llvm-build-int-cmp builder
'int-eq
(llvm-const-int (llvm-int32-type) 123)
(llvm-const-int (llvm-int32-type) 321)
"equal"))
(define then (llvm-append-basic-block if-func))
(define els (llvm-append-basic-block if-func))
(define cond-br (llvm-build-cond-br builder cmp then els))
(llvm-builder-position-at-end builder then)
(void (llvm-build-ret builder (llvm-const-int (llvm-int32-type) 111)))
(llvm-builder-position-at-end builder els)
(define sum (llvm-build-add builder
(llvm-const-int (llvm-int32-type) 222)
(llvm-const-int (llvm-int32-type) 93281)
"sum"))
(void (llvm-build-ret builder sum))
(llvm-module-verify mod)
(llvm-function-verify if-func)
(displayln "before:")
(display (llvm-module->string mod))
; let's do an optimization pass
(define pass-manager (llvm-pass-manager-create))
(define pass-manager-builder (llvm-pass-manager-builder-create))
(llvm-pass-manager-builder-set-opt-level pass-manager-builder 3)
(llvm-pass-manager-builder-populate-module-pass-manager pass-manager-builder pass-manager)
(displayln "did the pass change anything?")
(llvm-pass-manager-run pass-manager mod)
(displayln "after:")
(display (llvm-module->string mod))
| null | https://raw.githubusercontent.com/dannypsnl/racket-llvm/37392dcf7a48744eceac700c89d7dffb4122a36a/examples/optimization.rkt | racket | let's create an if-else function
let's do an optimization pass | #lang racket
(require racket-llvm)
(define mod (llvm-module "optimizeMe"))
(define eng (llvm-create-execution-engine-for-module mod))
(llvm-link-in-mcjit)
(define builder (llvm-builder-create))
(define if-func (llvm-add-function mod
"if"
(llvm-function-type (llvm-int32-type))))
(llvm-builder-position-at-end builder (llvm-append-basic-block if-func))
(define cmp (llvm-build-int-cmp builder
'int-eq
(llvm-const-int (llvm-int32-type) 123)
(llvm-const-int (llvm-int32-type) 321)
"equal"))
(define then (llvm-append-basic-block if-func))
(define els (llvm-append-basic-block if-func))
(define cond-br (llvm-build-cond-br builder cmp then els))
(llvm-builder-position-at-end builder then)
(void (llvm-build-ret builder (llvm-const-int (llvm-int32-type) 111)))
(llvm-builder-position-at-end builder els)
(define sum (llvm-build-add builder
(llvm-const-int (llvm-int32-type) 222)
(llvm-const-int (llvm-int32-type) 93281)
"sum"))
(void (llvm-build-ret builder sum))
(llvm-module-verify mod)
(llvm-function-verify if-func)
(displayln "before:")
(display (llvm-module->string mod))
(define pass-manager (llvm-pass-manager-create))
(define pass-manager-builder (llvm-pass-manager-builder-create))
(llvm-pass-manager-builder-set-opt-level pass-manager-builder 3)
(llvm-pass-manager-builder-populate-module-pass-manager pass-manager-builder pass-manager)
(displayln "did the pass change anything?")
(llvm-pass-manager-run pass-manager mod)
(displayln "after:")
(display (llvm-module->string mod))
|
76e69f0393cc655dd1de3eab4ef5fb5164c041893a1c27d89c277c717c6f35a3 | datodev/datodomvc | root.cljs | (ns datodomvc.client.components.root
(:require [clojure.string :as string]
[datascript :as d]
[dato.db.utils :as dsu]
[dato.lib.controller :as con]
[dato.lib.core :as dato]
[dato.lib.db :as db]
[datodomvc.client.routes :as routes]
[datodomvc.client.utils :as utils]
[om.core :as om :include-macros true]
[om-tools.core :refer-macros [defcomponent]]
[sablono.core :as html :refer-macros [html]]))
(defn kill! [event]
(doto event
(.preventDefault)
(.stopPropagation)))
(defn delay-focus!
"Waits 20ms (enough time to queue up a rerender usually, but
racey) and then focus an input"
([root selector]
(delay-focus! root selector false))
([root selector select?]
(js/setTimeout #(when-let [input (utils/sel1 root selector)]
(.focus input)
(when select?
(.select input))) 20)))
;; Useful to show what's being rerendered (everything right now for
the PoC demo )
(defn rand-color []
(str "#" (string/join (repeatedly 6 #(rand-nth [1 2 3 4 5 6 7 8 9 0 "A" "B" "C" "D" "E" "F"])))))
(defmethod con/transition :server/find-tasks-succeeded
[db {:keys [data] :as args}]
;; The pull request is insertable as-is, so we don't need to do any
;; pre-processing, just return the results.
;;
;; XXX: We're not picking up on the ref attr properly, so it's not
;; actually insertable as-is. This can probably be moved love down
;; the Dato stack. Either way, Preprocessing step for ref-attrs (to
;; handle the diff between DS/Datomic re: enums) needs to be
;; eliminated.
(let [results (:results data)]
(mapv (fn [entity-like]
(->> entity-like
(map (fn [[k v]]
(if (and (dsu/ref-attr? db k)
(keyword? v))
[k (db/enum-id db v)]
[k v])))
(into {}))) results)))
(defmethod con/transition :ui/item-inspected
[db {:keys [data] :as args}]
(let [session (dato/local-session db)
inspected-type (keyword (name (:type data)))]
[{:db/id (:db/id session)
:session/task-filter inspected-type}]))
(defmethod con/effect! :server/find-tasks-succeeded
;; Router is from the context we passed in when instantiating our
;; app in core.cljs
[{:keys [router] :as context} old-db new-db exhibit]
(routes/start! router))
(defcomponent root-com [data owner opts]
(display-name [_]
"DatodoMVC")
(did-mount [_]
(d/listen! (dato/conn (om/get-shared owner :dato)) :dato-root #(om/refresh! owner)))
(will-unmount [_]
(d/unlisten! (dato/conn (om/get-shared owner :dato)) :dato-root))
(render [_]
(html
(let [{:keys [dato]} (om/get-shared owner)
db (dato/db dato)
transact! (partial dato/transact! dato)
me (dato/me db)
session (dato/local-session db)
task-filter (:session/task-filter session)
pred (case task-filter
:completed :task/completed?
:active (complement :task/completed?)
(constantly true))
all-tasks (dsu/qes-by db :task/title)
grouped (group-by :task/completed? all-tasks)
active-tasks (get grouped false)
completed-tasks (get grouped true)
shown-tasks (->> all-tasks
(filter pred)
(sort-by :task/order))]
[:div
[:section.todoapp
[:header.header
[:h1 "Todos"]
[:input.new-todo {:placeholder "What needs to be done?"
:autofocus true
:value (om/get-state owner :new-task-title)
:on-change #(om/set-state! owner :new-task-title (.. % -target -value))
:on-key-down (fn [event]
(when (= 13 (.-which event))
(let [task {:db/id (d/tempid :db.part/user)
:dato/guid (d/squuid)
:dato/type (db/enum-id db :datodomvc.types/task)
:task/title (om/get-state owner :new-task-title)
:task/completed? false
:task/order (count all-tasks)}]
(transact! :task-created [task] {:tx/persist? true})
(om/set-state! owner :new-task-title nil))))}]]
[:section.main
(when (first all-tasks)
[:input.toggle-all {:type "checkbox"
:on-change (fn [event]
(let [checked? (.. event -target -checked)]
(transact! (keyword (str "tasks-all-marked-" (if checked? "complete" "incomplete")))
(vec (for [task all-tasks]
[:db/add (:db/id task) :task/completed? checked?])) {:tx/persist? true})))
:checked (not (boolean (first active-tasks)))}])
[:label {:for "toggle-all"} "Mark all as complete"]
(into
[:ul.todo-list]
(for [task shown-tasks]
^{:key (str "task-item-" (:db/id task))}
[:li {:key (str "task-item-" (:db/id task))
:class (cond
(:task/completed? task) "completed"
(= (om/get-state owner [:editing :id]) (:db/id task)) "editing")
:on-double-click (fn [event]
(om/set-state! owner :editing {:id (:db/id task)
:original (:task/title task)})
(delay-focus! (om/get-node owner) (str ".task-" (:db/id task)) true))}
[:div.view
[:input.toggle {:type "checkbox"
:checked (:task/completed? task)
:on-change (fn [event]
(transact! :task-toggled [{:db/id (:db/id task)
:task/completed? (not (:task/completed? task))}]
{:tx/persist? true}))}]
[:label (:task/title task)]
[:button.destroy {:on-click #(transact! :task-destroyed [[:db.fn/retractEntity (:db/id task)]] {:tx/persist? true})}]]
[:input.edit {:class (str "task-" (:db/id task))
:value (:task/title task)
:on-key-down #(condp = (.-which %)
13 (om/set-state! owner :editing {})
27 (do
(transact! :task-title-restored [{:db/id (:db/id task)
:task/title (om/get-state owner [:editing :original])}] {:tx/persist? true})
(om/set-state! owner :editing {}))
nil)
:on-change #(transact! :task-title-edited [{:db/id (:db/id task)
:task/title (.. % -target -value)}] {:tx/persist? true})}]]))]
[:footer.footer
[:span.todo-count [:strong (count active-tasks)] " items left"]
[:ul.filters
[:li
[:a {:href (routes/url-for :tasks/all)
:class (when (or (= :all task-filter) (not task-filter)) "selected")
:on-click (fn [event]
(kill! event)
(transact! :filter-updated [{:db/id (:db/id session)
:session/task-filter :all}]))} "All"]]
[:li
[:a {:href (routes/url-for :tasks/active)
:class (when (= :active task-filter) "selected")
:on-click (fn [event]
(kill! event)
(transact! :filter-updated [{:db/id (:db/id session)
:session/task-filter :active}]))} "Active"]]
[:li
[:a {:href (routes/url-for :tasks/completed)
:class (when (= :completed task-filter) "selected")
:on-click (fn [event]
(kill! event)
(transact! :filter-updated [{:db/id (:db/id session)
:session/task-filter :completed}]))} "Completed"]]]
(when (first completed-tasks)
[:button.clear-completed
{:on-click #(transact! :completed-tasks-cleared (->> all-tasks
(filter :task/completed?)
(mapv (fn [task] [:db.fn/retractEntity (:db/id task)]))) {:tx/persist? true})}
"Clear completed"])]]
[:footer.info
[:p "Double-click to edit a todo"]
[:p "Created by "
[:a {:href ""} "Sean Grove"]]
[:p "Part of "
[:a {:href ""} "TodoMVC"]]]]))))
| null | https://raw.githubusercontent.com/datodev/datodomvc/f6d65b61e2fe135a27e870f9a9613f204ded09a9/src/cljs/datodomvc/client/components/root.cljs | clojure | Useful to show what's being rerendered (everything right now for
The pull request is insertable as-is, so we don't need to do any
pre-processing, just return the results.
XXX: We're not picking up on the ref attr properly, so it's not
actually insertable as-is. This can probably be moved love down
the Dato stack. Either way, Preprocessing step for ref-attrs (to
handle the diff between DS/Datomic re: enums) needs to be
eliminated.
Router is from the context we passed in when instantiating our
app in core.cljs | (ns datodomvc.client.components.root
(:require [clojure.string :as string]
[datascript :as d]
[dato.db.utils :as dsu]
[dato.lib.controller :as con]
[dato.lib.core :as dato]
[dato.lib.db :as db]
[datodomvc.client.routes :as routes]
[datodomvc.client.utils :as utils]
[om.core :as om :include-macros true]
[om-tools.core :refer-macros [defcomponent]]
[sablono.core :as html :refer-macros [html]]))
(defn kill! [event]
(doto event
(.preventDefault)
(.stopPropagation)))
(defn delay-focus!
"Waits 20ms (enough time to queue up a rerender usually, but
racey) and then focus an input"
([root selector]
(delay-focus! root selector false))
([root selector select?]
(js/setTimeout #(when-let [input (utils/sel1 root selector)]
(.focus input)
(when select?
(.select input))) 20)))
the PoC demo )
(defn rand-color []
(str "#" (string/join (repeatedly 6 #(rand-nth [1 2 3 4 5 6 7 8 9 0 "A" "B" "C" "D" "E" "F"])))))
(defmethod con/transition :server/find-tasks-succeeded
[db {:keys [data] :as args}]
(let [results (:results data)]
(mapv (fn [entity-like]
(->> entity-like
(map (fn [[k v]]
(if (and (dsu/ref-attr? db k)
(keyword? v))
[k (db/enum-id db v)]
[k v])))
(into {}))) results)))
(defmethod con/transition :ui/item-inspected
[db {:keys [data] :as args}]
(let [session (dato/local-session db)
inspected-type (keyword (name (:type data)))]
[{:db/id (:db/id session)
:session/task-filter inspected-type}]))
(defmethod con/effect! :server/find-tasks-succeeded
[{:keys [router] :as context} old-db new-db exhibit]
(routes/start! router))
(defcomponent root-com [data owner opts]
(display-name [_]
"DatodoMVC")
(did-mount [_]
(d/listen! (dato/conn (om/get-shared owner :dato)) :dato-root #(om/refresh! owner)))
(will-unmount [_]
(d/unlisten! (dato/conn (om/get-shared owner :dato)) :dato-root))
(render [_]
(html
(let [{:keys [dato]} (om/get-shared owner)
db (dato/db dato)
transact! (partial dato/transact! dato)
me (dato/me db)
session (dato/local-session db)
task-filter (:session/task-filter session)
pred (case task-filter
:completed :task/completed?
:active (complement :task/completed?)
(constantly true))
all-tasks (dsu/qes-by db :task/title)
grouped (group-by :task/completed? all-tasks)
active-tasks (get grouped false)
completed-tasks (get grouped true)
shown-tasks (->> all-tasks
(filter pred)
(sort-by :task/order))]
[:div
[:section.todoapp
[:header.header
[:h1 "Todos"]
[:input.new-todo {:placeholder "What needs to be done?"
:autofocus true
:value (om/get-state owner :new-task-title)
:on-change #(om/set-state! owner :new-task-title (.. % -target -value))
:on-key-down (fn [event]
(when (= 13 (.-which event))
(let [task {:db/id (d/tempid :db.part/user)
:dato/guid (d/squuid)
:dato/type (db/enum-id db :datodomvc.types/task)
:task/title (om/get-state owner :new-task-title)
:task/completed? false
:task/order (count all-tasks)}]
(transact! :task-created [task] {:tx/persist? true})
(om/set-state! owner :new-task-title nil))))}]]
[:section.main
(when (first all-tasks)
[:input.toggle-all {:type "checkbox"
:on-change (fn [event]
(let [checked? (.. event -target -checked)]
(transact! (keyword (str "tasks-all-marked-" (if checked? "complete" "incomplete")))
(vec (for [task all-tasks]
[:db/add (:db/id task) :task/completed? checked?])) {:tx/persist? true})))
:checked (not (boolean (first active-tasks)))}])
[:label {:for "toggle-all"} "Mark all as complete"]
(into
[:ul.todo-list]
(for [task shown-tasks]
^{:key (str "task-item-" (:db/id task))}
[:li {:key (str "task-item-" (:db/id task))
:class (cond
(:task/completed? task) "completed"
(= (om/get-state owner [:editing :id]) (:db/id task)) "editing")
:on-double-click (fn [event]
(om/set-state! owner :editing {:id (:db/id task)
:original (:task/title task)})
(delay-focus! (om/get-node owner) (str ".task-" (:db/id task)) true))}
[:div.view
[:input.toggle {:type "checkbox"
:checked (:task/completed? task)
:on-change (fn [event]
(transact! :task-toggled [{:db/id (:db/id task)
:task/completed? (not (:task/completed? task))}]
{:tx/persist? true}))}]
[:label (:task/title task)]
[:button.destroy {:on-click #(transact! :task-destroyed [[:db.fn/retractEntity (:db/id task)]] {:tx/persist? true})}]]
[:input.edit {:class (str "task-" (:db/id task))
:value (:task/title task)
:on-key-down #(condp = (.-which %)
13 (om/set-state! owner :editing {})
27 (do
(transact! :task-title-restored [{:db/id (:db/id task)
:task/title (om/get-state owner [:editing :original])}] {:tx/persist? true})
(om/set-state! owner :editing {}))
nil)
:on-change #(transact! :task-title-edited [{:db/id (:db/id task)
:task/title (.. % -target -value)}] {:tx/persist? true})}]]))]
[:footer.footer
[:span.todo-count [:strong (count active-tasks)] " items left"]
[:ul.filters
[:li
[:a {:href (routes/url-for :tasks/all)
:class (when (or (= :all task-filter) (not task-filter)) "selected")
:on-click (fn [event]
(kill! event)
(transact! :filter-updated [{:db/id (:db/id session)
:session/task-filter :all}]))} "All"]]
[:li
[:a {:href (routes/url-for :tasks/active)
:class (when (= :active task-filter) "selected")
:on-click (fn [event]
(kill! event)
(transact! :filter-updated [{:db/id (:db/id session)
:session/task-filter :active}]))} "Active"]]
[:li
[:a {:href (routes/url-for :tasks/completed)
:class (when (= :completed task-filter) "selected")
:on-click (fn [event]
(kill! event)
(transact! :filter-updated [{:db/id (:db/id session)
:session/task-filter :completed}]))} "Completed"]]]
(when (first completed-tasks)
[:button.clear-completed
{:on-click #(transact! :completed-tasks-cleared (->> all-tasks
(filter :task/completed?)
(mapv (fn [task] [:db.fn/retractEntity (:db/id task)]))) {:tx/persist? true})}
"Clear completed"])]]
[:footer.info
[:p "Double-click to edit a todo"]
[:p "Created by "
[:a {:href ""} "Sean Grove"]]
[:p "Part of "
[:a {:href ""} "TodoMVC"]]]]))))
|
cbb5233298146ff91719e137b53decc8d3d3e7b1b980cb1a1356ebcbf0a3dadc | codedownio/sandwich | TestTimer.hs | # LANGUAGE TypeOperators #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE MonoLocalBinds #
module Test.Sandwich.TestTimer where
import Control.Concurrent
import Control.Exception.Safe
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.State
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.List as L
import qualified Data.Sequence as S
import Data.String.Interpolate
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Time.Clock.POSIX
import Lens.Micro
import System.Directory
import System.FilePath
import System.IO
import Test.Sandwich.Types.RunTree
import Test.Sandwich.Types.Spec
import Test.Sandwich.Types.TestTimer
import Test.Sandwich.Util (whenJust)
type EventName = T.Text
type ProfileName = T.Text
-- * User functions
-- | Time a given action with a given event name. This name will be the "stack frame" of the given action in the profiling results. This function will use the current timing profile name.
timeAction :: (MonadMask m, MonadIO m, MonadReader context m, HasBaseContext context, HasTestTimer context) => EventName -> m a -> m a
timeAction eventName action = do
tt <- asks getTestTimer
BaseContext {baseContextTestTimerProfile} <- asks getBaseContext
timeAction' tt baseContextTestTimerProfile eventName action
-- | Time a given action with a given profile name and event name. Use when you want to manually specify the profile name.
timeActionByProfile :: (MonadMask m, MonadIO m, MonadReader context m, HasTestTimer context) => ProfileName -> EventName -> m a -> m a
timeActionByProfile profileName eventName action = do
tt <- asks getTestTimer
timeAction' tt profileName eventName action
-- | Introduce a new timing profile name.
withTimingProfile :: (Monad m) => ProfileName -> SpecFree (LabelValue "testTimerProfile" TestTimerProfile :> context) m () -> SpecFree context m ()
withTimingProfile name = introduce' timingNodeOptions [i|Switch test timer profile to '#{name}'|] testTimerProfile (pure $ TestTimerProfile name) (\_ -> return ())
-- | Introduce a new timing profile name dynamically. The given 'ExampleT' should come up with the name and return it.
withTimingProfile' :: (Monad m) => ExampleT context m ProfileName -> SpecFree (LabelValue "testTimerProfile" TestTimerProfile :> context) m () -> SpecFree context m ()
withTimingProfile' getName = introduce' timingNodeOptions [i|Switch test timer profile to dynamic value|] testTimerProfile (TestTimerProfile <$> getName) (\_ -> return ())
-- * Core
timingNodeOptions :: NodeOptions
timingNodeOptions = defaultNodeOptions { nodeOptionsRecordTime = False
, nodeOptionsCreateFolder = False
, nodeOptionsVisibilityThreshold = systemVisibilityThreshold }
newSpeedScopeTestTimer :: FilePath -> Bool -> IO TestTimer
newSpeedScopeTestTimer path writeRawTimings = do
createDirectoryIfMissing True path
maybeHandle <- case writeRawTimings of
False -> return Nothing
True -> do
h <- openFile (path </> "timings_raw.txt") AppendMode
hSetBuffering h LineBuffering
return $ Just h
speedScopeFile <- newMVar emptySpeedScopeFile
return $ SpeedScopeTestTimer path maybeHandle speedScopeFile
finalizeSpeedScopeTestTimer :: TestTimer -> IO ()
finalizeSpeedScopeTestTimer NullTestTimer = return ()
finalizeSpeedScopeTestTimer (SpeedScopeTestTimer {..}) = do
whenJust testTimerHandle hClose
readMVar testTimerSpeedScopeFile >>= BL.writeFile (testTimerBasePath </> "speedscope.json") . A.encode
timeAction' :: (MonadMask m, MonadIO m) => TestTimer -> T.Text -> T.Text -> m a -> m a
timeAction' NullTestTimer _ _ = id
timeAction' (SpeedScopeTestTimer {..}) profileName eventName = bracket_
(liftIO $ modifyMVar_ testTimerSpeedScopeFile $ \file -> do
now <- getPOSIXTime
handleStartEvent file now
)
(liftIO $ modifyMVar_ testTimerSpeedScopeFile $ \file -> do
now <- getPOSIXTime
handleEndEvent file now
)
where
handleStartEvent file time = do
whenJust testTimerHandle $ \h -> T.hPutStrLn h [i|#{time} START #{show profileName} #{eventName}|]
return $ handleSpeedScopeEvent file time SpeedScopeEventTypeOpen
handleEndEvent file time = do
whenJust testTimerHandle $ \h -> T.hPutStrLn h [i|#{time} END #{show profileName} #{eventName}|]
return $ handleSpeedScopeEvent file time SpeedScopeEventTypeClose
-- | TODO: maybe use an intermediate format so the frames (and possibly profiles) aren't stored as lists,
so we do n't have to do O(N ) L.length and S.findIndexL
handleSpeedScopeEvent :: SpeedScopeFile -> POSIXTime -> SpeedScopeEventType -> SpeedScopeFile
handleSpeedScopeEvent initialFile time typ = flip execState initialFile $ do
frameID <- get >>= \f -> case S.findIndexL (== SpeedScopeFrame eventName) (f ^. shared . frames) of
Just j -> return j
Nothing -> do
modify' $ over (shared . frames) (S.|> (SpeedScopeFrame eventName))
return $ S.length $ f ^. shared . frames
profileIndex <- get >>= \f -> case L.findIndex ((== profileName) . (^. name)) (f ^. profiles) of
Just j -> return j
Nothing -> do
modify' $ over profiles (\x -> x <> [newProfile profileName time])
return $ L.length (f ^. profiles)
modify' $ over (profiles . ix profileIndex . events) (S.|> (SpeedScopeEvent typ frameID time))
. over (profiles . ix profileIndex . endValue) (max time)
| null | https://raw.githubusercontent.com/codedownio/sandwich/9c8f56b5aee94ba65c70b3e52bde8959010aecc1/sandwich/src/Test/Sandwich/TestTimer.hs | haskell | # LANGUAGE ConstraintKinds #
* User functions
| Time a given action with a given event name. This name will be the "stack frame" of the given action in the profiling results. This function will use the current timing profile name.
| Time a given action with a given profile name and event name. Use when you want to manually specify the profile name.
| Introduce a new timing profile name.
| Introduce a new timing profile name dynamically. The given 'ExampleT' should come up with the name and return it.
* Core
| TODO: maybe use an intermediate format so the frames (and possibly profiles) aren't stored as lists, | # LANGUAGE TypeOperators #
# LANGUAGE DataKinds #
# LANGUAGE MonoLocalBinds #
module Test.Sandwich.TestTimer where
import Control.Concurrent
import Control.Exception.Safe
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.State
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.List as L
import qualified Data.Sequence as S
import Data.String.Interpolate
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Time.Clock.POSIX
import Lens.Micro
import System.Directory
import System.FilePath
import System.IO
import Test.Sandwich.Types.RunTree
import Test.Sandwich.Types.Spec
import Test.Sandwich.Types.TestTimer
import Test.Sandwich.Util (whenJust)
type EventName = T.Text
type ProfileName = T.Text
timeAction :: (MonadMask m, MonadIO m, MonadReader context m, HasBaseContext context, HasTestTimer context) => EventName -> m a -> m a
timeAction eventName action = do
tt <- asks getTestTimer
BaseContext {baseContextTestTimerProfile} <- asks getBaseContext
timeAction' tt baseContextTestTimerProfile eventName action
timeActionByProfile :: (MonadMask m, MonadIO m, MonadReader context m, HasTestTimer context) => ProfileName -> EventName -> m a -> m a
timeActionByProfile profileName eventName action = do
tt <- asks getTestTimer
timeAction' tt profileName eventName action
withTimingProfile :: (Monad m) => ProfileName -> SpecFree (LabelValue "testTimerProfile" TestTimerProfile :> context) m () -> SpecFree context m ()
withTimingProfile name = introduce' timingNodeOptions [i|Switch test timer profile to '#{name}'|] testTimerProfile (pure $ TestTimerProfile name) (\_ -> return ())
withTimingProfile' :: (Monad m) => ExampleT context m ProfileName -> SpecFree (LabelValue "testTimerProfile" TestTimerProfile :> context) m () -> SpecFree context m ()
withTimingProfile' getName = introduce' timingNodeOptions [i|Switch test timer profile to dynamic value|] testTimerProfile (TestTimerProfile <$> getName) (\_ -> return ())
timingNodeOptions :: NodeOptions
timingNodeOptions = defaultNodeOptions { nodeOptionsRecordTime = False
, nodeOptionsCreateFolder = False
, nodeOptionsVisibilityThreshold = systemVisibilityThreshold }
newSpeedScopeTestTimer :: FilePath -> Bool -> IO TestTimer
newSpeedScopeTestTimer path writeRawTimings = do
createDirectoryIfMissing True path
maybeHandle <- case writeRawTimings of
False -> return Nothing
True -> do
h <- openFile (path </> "timings_raw.txt") AppendMode
hSetBuffering h LineBuffering
return $ Just h
speedScopeFile <- newMVar emptySpeedScopeFile
return $ SpeedScopeTestTimer path maybeHandle speedScopeFile
finalizeSpeedScopeTestTimer :: TestTimer -> IO ()
finalizeSpeedScopeTestTimer NullTestTimer = return ()
finalizeSpeedScopeTestTimer (SpeedScopeTestTimer {..}) = do
whenJust testTimerHandle hClose
readMVar testTimerSpeedScopeFile >>= BL.writeFile (testTimerBasePath </> "speedscope.json") . A.encode
timeAction' :: (MonadMask m, MonadIO m) => TestTimer -> T.Text -> T.Text -> m a -> m a
timeAction' NullTestTimer _ _ = id
timeAction' (SpeedScopeTestTimer {..}) profileName eventName = bracket_
(liftIO $ modifyMVar_ testTimerSpeedScopeFile $ \file -> do
now <- getPOSIXTime
handleStartEvent file now
)
(liftIO $ modifyMVar_ testTimerSpeedScopeFile $ \file -> do
now <- getPOSIXTime
handleEndEvent file now
)
where
handleStartEvent file time = do
whenJust testTimerHandle $ \h -> T.hPutStrLn h [i|#{time} START #{show profileName} #{eventName}|]
return $ handleSpeedScopeEvent file time SpeedScopeEventTypeOpen
handleEndEvent file time = do
whenJust testTimerHandle $ \h -> T.hPutStrLn h [i|#{time} END #{show profileName} #{eventName}|]
return $ handleSpeedScopeEvent file time SpeedScopeEventTypeClose
so we do n't have to do O(N ) L.length and S.findIndexL
handleSpeedScopeEvent :: SpeedScopeFile -> POSIXTime -> SpeedScopeEventType -> SpeedScopeFile
handleSpeedScopeEvent initialFile time typ = flip execState initialFile $ do
frameID <- get >>= \f -> case S.findIndexL (== SpeedScopeFrame eventName) (f ^. shared . frames) of
Just j -> return j
Nothing -> do
modify' $ over (shared . frames) (S.|> (SpeedScopeFrame eventName))
return $ S.length $ f ^. shared . frames
profileIndex <- get >>= \f -> case L.findIndex ((== profileName) . (^. name)) (f ^. profiles) of
Just j -> return j
Nothing -> do
modify' $ over profiles (\x -> x <> [newProfile profileName time])
return $ L.length (f ^. profiles)
modify' $ over (profiles . ix profileIndex . events) (S.|> (SpeedScopeEvent typ frameID time))
. over (profiles . ix profileIndex . endValue) (max time)
|
1a42890088b3e37cd674ae82105c03130537da1254636f4a8286ce25367ba681 | dpiponi/Moodler | snare_drum.hs | do
(x0, y0) <- mouse
let (x, y) = quantise2 quantum (x0, y0)
root <- currentPlane
audio_id0 <- new' "audio_id"
audio_saw1 <- new' "audio_saw"
audio_sin2 <- new' "audio_sin"
audio_square3 <- new' "audio_square"
audio_triangle4 <- new' "audio_triangle"
butterbp5 <- new' "butterbp"
butterbp6 <- new' "butterbp"
butterhp7 <- new' "butterhp"
butterhp8 <- new' "butterhp"
butterlp10 <- new' "butterlp"
butterlp11 <- new' "butterlp"
butterlp9 <- new' "butterlp"
exp_decay12 <- new' "exp_decay"
exp_decay13 <- new' "exp_decay"
id15 <- new' "id"
id16 <- new' "id"
id17 <- new' "id"
id18 <- new' "id"
id19 <- new' "id"
id20 <- new' "id"
id21 <- new' "id"
id22 <- new' "id"
id23 <- new' "id"
id24 <- new' "id"
id25 <- new' "id"
input14 <- new' "input"
input27 <- new' "input"
input28 <- new' "input"
input29 <- new' "input"
input30 <- new' "input"
input31 <- new' "input"
input32 <- new' "input"
input33 <- new' "input"
input34 <- new' "input"
input35 <- new' "input"
input36 <- new' "input"
input37 <- new' "input"
input38 <- new' "input"
input39 <- new' "input"
input40 <- new' "input"
input41 <- new' "input"
input42 <- new' "input"
input43 <- new' "input"
input44 <- new' "input"
input45 <- new' "input"
input57 <- new' "input"
noise47 <- new' "noise"
sum455 <- new' "sum4"
sum48 <- new' "sum"
sum49 <- new' "sum"
sum50 <- new' "sum"
sum51 <- new' "sum"
sum52 <- new' "sum"
sum53 <- new' "sum"
sum54 <- new' "sum"
vca56 <- new' "vca"
vca58 <- new' "vca"
vca59 <- new' "vca"
vca60 <- new' "vca"
vca61 <- new' "vca"
vca62 <- new' "vca"
vca63 <- new' "vca"
vca64 <- new' "vca"
vca65 <- new' "vca"
vca66 <- new' "vca"
container258 <- container' "panel_snare_drum.png" (x+(-96.0), y+(72.0)) (Inside root)
in76 <- plugin' (id24 ++ "." ++ "signal") (x+(-156.0), y+(72.0)) (Outside container258)
setColour in76 "#control"
out77 <- plugout' (audio_id0 ++ "." ++ "result") (x+(-36.0), y+(72.0)) (Outside container258)
setColour out77 "#sample"
proxy78 <- proxy' (x+(-96.0), y+(72.0)) (Outside container258)
hide proxy78
container125 <- container' "panel_3x1.png" (180.0,480.0) (Inside proxy78)
in126 <- plugin' (vca62 ++ "." ++ "cv") (159.0,505.0) (Outside container125)
setColour in126 "#control"
in127 <- plugin' (vca62 ++ "." ++ "signal") (159.0,455.0) (Outside container125)
setColour in127 "#sample"
label128 <- label' "vca" (155.0,555.0) (Outside container125)
out129 <- plugout' (vca62 ++ "." ++ "result") (200.0,480.0) (Outside container125)
setColour out129 "#sample"
container130 <- container' "panel_3x1.png" (0.0,132.0) (Inside proxy78)
in131 <- plugin' (vca66 ++ "." ++ "cv") (-21.0,157.0) (Outside container130)
setColour in131 "#control"
hide in131
in132 <- plugin' (vca66 ++ "." ++ "signal") (-21.0,107.0) (Outside container130)
setColour in132 "#sample"
knob133 <- knob' (input45 ++ "." ++ "result") (-21.0,157.0) (Outside container130)
label134 <- label' "vca" (-25.0,207.0) (Outside container130)
out135 <- plugout' (vca66 ++ "." ++ "result") (20.0,132.0) (Outside container130)
setColour out135 "#sample"
container136 <- container' "panel_vco2.png" (-456.0,-36.0) (Inside proxy78)
in137 <- plugin' (id21 ++ "." ++ "signal") (-420.0,0.0) (Outside container136)
setColour in137 "#control"
in138 <- plugin' (id22 ++ "." ++ "signal") (-443.0,44.0) (Outside container136)
setColour in138 "#sample"
hide in138
in139 <- plugin' (id15 ++ "." ++ "signal") (-425.0,-33.0) (Outside container136)
setColour in139 "#sample"
hide in139
in140 <- plugin' (id16 ++ "." ++ "signal") (-420.0,-72.0) (Outside container136)
setColour in140 "#control"
knob141 <- knob' (input28 ++ "." ++ "result") (-420.0,-36.0) (Outside container136)
knob142 <- knob' (input27 ++ "." ++ "result") (-420.0,36.0) (Outside container136)
out143 <- plugout' (id20 ++ "." ++ "result") (-480.0,-120.0) (Outside container136)
setColour out143 "#sample"
out144 <- plugout' (id17 ++ "." ++ "result") (-408.0,-120.0) (Outside container136)
setColour out144 "#sample"
out145 <- plugout' (id18 ++ "." ++ "result") (-480.0,-156.0) (Outside container136)
setColour out145 "#sample"
out146 <- plugout' (id19 ++ "." ++ "result") (-408.0,-156.0) (Outside container136)
setColour out146 "#sample"
proxy147 <- proxy' (-503.0,46.0) (Outside container136)
hide proxy147
container148 <- container' "panel_3x1.png" (-815.0,439.0) (Inside proxy147)
in149 <- plugin' (sum48 ++ "." ++ "signal2") (-836.0,414.0) (Outside container148)
setColour in149 "#sample"
in150 <- plugin' (sum48 ++ "." ++ "signal1") (-836.0,464.0) (Outside container148)
setColour in150 "#sample"
label151 <- label' "sum" (-840.0,514.0) (Outside container148)
out152 <- plugout' (sum48 ++ "." ++ "result") (-795.0,439.0) (Outside container148)
setColour out152 "#sample"
container153 <- container' "panel_3x1.png" (-434.0,420.0) (Inside proxy147)
in154 <- plugin' (audio_triangle4 ++ "." ++ "freq") (-455.0,445.0) (Outside container153)
setColour in154 "#sample"
in155 <- plugin' (audio_triangle4 ++ "." ++ "sync") (-455.0,395.0) (Outside container153)
setColour in155 "#sample"
label156 <- label' "audio_triangle" (-459.0,495.0) (Outside container153)
out157 <- plugout' (audio_triangle4 ++ "." ++ "result") (-414.0,420.0) (Outside container153)
setColour out157 "#sample"
container158 <- container' "panel_3x1.png" (-318.0,291.0) (Inside proxy147)
in159 <- plugin' (audio_saw1 ++ "." ++ "freq") (-339.0,316.0) (Outside container158)
setColour in159 "#sample"
in160 <- plugin' (audio_saw1 ++ "." ++ "sync") (-339.0,266.0) (Outside container158)
setColour in160 "#sample"
label161 <- label' "audio_saw" (-343.0,366.0) (Outside container158)
out162 <- plugout' (audio_saw1 ++ "." ++ "result") (-298.0,291.0) (Outside container158)
setColour out162 "#sample"
container163 <- container' "panel_3x1.png" (-691.0,453.0) (Inside proxy147)
in164 <- plugin' (audio_sin2 ++ "." ++ "freq") (-712.0,478.0) (Outside container163)
setColour in164 "#sample"
in165 <- plugin' (audio_sin2 ++ "." ++ "sync") (-712.0,428.0) (Outside container163)
setColour in165 "#sample"
label166 <- label' "audio_sin" (-716.0,528.0) (Outside container163)
out167 <- plugout' (audio_sin2 ++ "." ++ "result") (-671.0,453.0) (Outside container163)
setColour out167 "#sample"
container168 <- container' "panel_3x1.png" (-826.0,199.0) (Inside proxy147)
in169 <- plugin' (audio_square3 ++ "." ++ "pwm") (-847.0,199.0) (Outside container168)
setColour in169 "#sample"
in170 <- plugin' (audio_square3 ++ "." ++ "sync") (-847.0,149.0) (Outside container168)
setColour in170 "#sample"
in171 <- plugin' (audio_square3 ++ "." ++ "freq") (-847.0,249.0) (Outside container168)
setColour in171 "#sample"
label172 <- label' "audio_square" (-851.0,274.0) (Outside container168)
out173 <- plugout' (audio_square3 ++ "." ++ "result") (-806.0,199.0) (Outside container168)
setColour out173 "#sample"
in174 <- plugin' (id17 ++ "." ++ "signal") (-753.0,198.0) (Inside proxy147)
setColour in174 "#sample"
in175 <- plugin' (id18 ++ "." ++ "signal") (-360.0,422.0) (Inside proxy147)
setColour in175 "#sample"
in176 <- plugin' (id19 ++ "." ++ "signal") (-247.0,292.0) (Inside proxy147)
setColour in176 "#sample"
in177 <- plugin' (id20 ++ "." ++ "signal") (-556.0,449.0) (Inside proxy147)
setColour in177 "#sample"
out178 <- plugout' (id21 ++ "." ++ "result") (-891.0,413.0) (Inside proxy147)
setColour out178 "#sample"
out179 <- plugout' (id22 ++ "." ++ "result") (-892.0,469.0) (Inside proxy147)
setColour out179 "#sample"
out180 <- plugout' (id15 ++ "." ++ "result") (-894.0,199.0) (Inside proxy147)
setColour out180 "#sample"
out181 <- plugout' (id16 ++ "." ++ "result") (-893.0,146.0) (Inside proxy147)
setColour out181 "#sample"
container182 <- container' "panel_3x1.png" (-48.0,-108.0) (Inside proxy78)
in183 <- plugin' (vca56 ++ "." ++ "cv") (-69.0,-83.0) (Outside container182)
setColour in183 "#control"
hide in183
in184 <- plugin' (vca56 ++ "." ++ "signal") (-69.0,-133.0) (Outside container182)
setColour in184 "#sample"
knob185 <- knob' (input57 ++ "." ++ "result") (-69.0,-83.0) (Outside container182)
label186 <- label' "vca" (-73.0,-33.0) (Outside container182)
out187 <- plugout' (vca56 ++ "." ++ "result") (-28.0,-108.0) (Outside container182)
setColour out187 "#sample"
container188 <- container' "panel_filter.png" (-240.0,-72.0) (Inside proxy78)
in189 <- plugin' (vca58 ++ "." ++ "cv") (-252.0,48.0) (Outside container188)
setColour in189 "#sample"
hide in189
in190 <- plugin' (vca58 ++ "." ++ "signal") (-300.0,-12.0) (Outside container188)
setColour in190 "#control"
in191 <- plugin' (vca59 ++ "." ++ "cv") (-257.0,-74.0) (Outside container188)
setColour in191 "#sample"
hide in191
in192 <- plugin' (vca59 ++ "." ++ "signal") (-300.0,-72.0) (Outside container188)
setColour in192 "#control"
in193 <- plugin' (vca60 ++ "." ++ "cv") (-259.0,-190.0) (Outside container188)
setColour in193 "#sample"
hide in193
in194 <- plugin' (vca60 ++ "." ++ "signal") (-300.0,-132.0) (Outside container188)
setColour in194 "#control"
in195 <- plugin' (id25 ++ "." ++ "signal") (-300.0,48.0) (Outside container188)
setColour in195 "#control"
knob196 <- knob' (input43 ++ "." ++ "result") (-216.0,-12.0) (Outside container188)
setLow knob196 (Just (-1.0))
setHigh knob196 (Just (1.0))
knob197 <- knob' (input36 ++ "." ++ "result") (-264.0,-12.0) (Outside container188)
knob198 <- knob' (input37 ++ "." ++ "result") (-264.0,-72.0) (Outside container188)
knob199 <- knob' (input38 ++ "." ++ "result") (-216.0,-72.0) (Outside container188)
setLow knob199 (Just (-1.0))
setHigh knob199 (Just (1.0))
knob200 <- knob' (input39 ++ "." ++ "result") (-264.0,-132.0) (Outside container188)
knob201 <- knob' (input41 ++ "." ++ "result") (-216.0,-132.0) (Outside container188)
setLow knob201 (Just (-1.0))
setHigh knob201 (Just (1.0))
knob202 <- knob' (input42 ++ "." ++ "result") (-216.0,-180.0) (Outside container188)
setLow knob202 (Just (1.0))
setHigh knob202 (Just (1000.0))
out203 <- plugout' (butterbp5 ++ "." ++ "result") (-180.0,-132.0) (Outside container188)
setColour out203 "#sample"
out204 <- plugout' (butterlp11 ++ "." ++ "result") (-180.0,-12.0) (Outside container188)
setColour out204 "#sample"
out205 <- plugout' (butterhp7 ++ "." ++ "result") (-180.0,-72.0) (Outside container188)
setColour out205 "#sample"
proxy206 <- proxy' (-191.0,38.0) (Outside container188)
hide proxy206
in207 <- plugin' (sum49 ++ "." ++ "signal2") (-129.0,144.0) (Inside proxy206)
setColour in207 "#sample"
hide in207
in208 <- plugin' (sum50 ++ "." ++ "signal1") (-134.0,73.0) (Inside proxy206)
setColour in208 "#sample"
in209 <- plugin' (sum50 ++ "." ++ "signal2") (-134.0,23.0) (Inside proxy206)
setColour in209 "#sample"
hide in209
in210 <- plugin' (sum51 ++ "." ++ "signal1") (-140.0,-40.0) (Inside proxy206)
setColour in210 "#sample"
in211 <- plugin' (sum51 ++ "." ++ "signal2") (-140.0,-90.0) (Inside proxy206)
setColour in211 "#sample"
hide in211
in212 <- plugin' (butterlp11 ++ "." ++ "freq") (-43.0,192.0) (Inside proxy206)
setColour in212 "#sample"
in213 <- plugin' (butterlp11 ++ "." ++ "signal") (-43.0,142.0) (Inside proxy206)
setColour in213 "#sample"
in214 <- plugin' (butterhp7 ++ "." ++ "freq") (-47.0,72.0) (Inside proxy206)
setColour in214 "#sample"
in215 <- plugin' (butterhp7 ++ "." ++ "signal") (-47.0,22.0) (Inside proxy206)
setColour in215 "#sample"
in216 <- plugin' (butterbp5 ++ "." ++ "freq") (-55.0,-41.0) (Inside proxy206)
setColour in216 "#sample"
in217 <- plugin' (butterbp5 ++ "." ++ "bandwidth") (-55.0,-91.0) (Inside proxy206)
setColour in217 "#sample"
hide in217
in218 <- plugin' (butterbp5 ++ "." ++ "signal") (-55.0,-141.0) (Inside proxy206)
setColour in218 "#sample"
in219 <- plugin' (sum49 ++ "." ++ "signal1") (-129.0,194.0) (Inside proxy206)
setColour in219 "#sample"
out220 <- plugout' (sum49 ++ "." ++ "result") (-79.0,194.0) (Inside proxy206)
setColour out220 "#sample"
out221 <- plugout' (sum50 ++ "." ++ "result") (-84.0,73.0) (Inside proxy206)
setColour out221 "#sample"
out222 <- plugout' (sum51 ++ "." ++ "result") (-90.0,-40.0) (Inside proxy206)
setColour out222 "#sample"
out223 <- plugout' (vca58 ++ "." ++ "result") (-200.0,196.0) (Inside proxy206)
setColour out223 "#sample"
out224 <- plugout' (vca59 ++ "." ++ "result") (-205.0,74.0) (Inside proxy206)
setColour out224 "#sample"
out225 <- plugout' (vca60 ++ "." ++ "result") (-207.0,-42.0) (Inside proxy206)
setColour out225 "#sample"
out226 <- plugout' (id25 ++ "." ++ "result") (-163.0,279.0) (Inside proxy206)
setColour out226 "#sample"
container227 <- container' "panel_3x1.png" (60.0,-120.0) (Inside proxy78)
in228 <- plugin' (exp_decay13 ++ "." ++ "decay_time") (39.0,-95.0) (Outside container227)
setColour in228 "#control"
hide in228
in229 <- plugin' (exp_decay13 ++ "." ++ "trigger") (39.0,-145.0) (Outside container227)
setColour in229 "#control"
knob230 <- knob' (input14 ++ "." ++ "result") (39.0,-95.0) (Outside container227)
label231 <- label' "exp_decay" (35.0,-45.0) (Outside container227)
out232 <- plugout' (exp_decay13 ++ "." ++ "result") (80.0,-120.0) (Outside container227)
setColour out232 "#control"
container233 <- container' "panel_3x1.png" (180.0,-108.0) (Inside proxy78)
in234 <- plugin' (vca61 ++ "." ++ "cv") (159.0,-83.0) (Outside container233)
setColour in234 "#control"
in235 <- plugin' (vca61 ++ "." ++ "signal") (159.0,-133.0) (Outside container233)
setColour in235 "#sample"
label236 <- label' "vca" (155.0,-33.0) (Outside container233)
out237 <- plugout' (vca61 ++ "." ++ "result") (200.0,-108.0) (Outside container233)
setColour out237 "#sample"
container238 <- container' "panel_3x1.png" (-156.0,552.0) (Inside proxy78)
in239 <- plugin' (butterlp10 ++ "." ++ "freq") (-177.0,577.0) (Outside container238)
setColour in239 "#control"
hide in239
in240 <- plugin' (butterlp10 ++ "." ++ "signal") (-177.0,527.0) (Outside container238)
setColour in240 "#sample"
knob241 <- knob' (input29 ++ "." ++ "result") (-177.0,577.0) (Outside container238)
label242 <- label' "butterlp" (-181.0,627.0) (Outside container238)
out243 <- plugout' (butterlp10 ++ "." ++ "result") (-136.0,552.0) (Outside container238)
setColour out243 "#sample"
container244 <- container' "panel_3x1.png" (-276.0,564.0) (Inside proxy78)
in245 <- plugin' (exp_decay12 ++ "." ++ "decay_time") (-297.0,589.0) (Outside container244)
setColour in245 "#control"
hide in245
in246 <- plugin' (exp_decay12 ++ "." ++ "trigger") (-297.0,539.0) (Outside container244)
setColour in246 "#control"
knob247 <- knob' (input30 ++ "." ++ "result") (-297.0,589.0) (Outside container244)
label248 <- label' "exp_decay" (-301.0,639.0) (Outside container244)
out249 <- plugout' (exp_decay12 ++ "." ++ "result") (-256.0,564.0) (Outside container244)
setColour out249 "#control"
container250 <- container' "panel_3x1.png" (-420.0,228.0) (Inside proxy78)
label251 <- label' "noise" (-445.0,303.0) (Outside container250)
out252 <- plugout' (noise47 ++ "." ++ "result") (-400.0,228.0) (Outside container250)
setColour out252 "#sample"
container79 <- container' "panel_4x1.png" (168.0,180.0) (Inside proxy78)
in80 <- plugin' (sum455 ++ "." ++ "signal1") (147.0,255.0) (Outside container79)
setColour in80 "#sample"
in81 <- plugin' (sum455 ++ "." ++ "signal2") (147.0,205.0) (Outside container79)
setColour in81 "#sample"
in82 <- plugin' (sum455 ++ "." ++ "signal3") (147.0,155.0) (Outside container79)
setColour in82 "#sample"
in83 <- plugin' (sum455 ++ "." ++ "signal4") (147.0,105.0) (Outside container79)
setColour in83 "#sample"
label84 <- label' "sum4" (143.0,255.0) (Outside container79)
out85 <- plugout' (sum455 ++ "." ++ "result") (188.0,180.0) (Outside container79)
setColour out85 "#sample"
container86 <- container' "panel_filter.png" (-204.0,252.0) (Inside proxy78)
in87 <- plugin' (vca63 ++ "." ++ "cv") (-216.0,372.0) (Outside container86)
setColour in87 "#sample"
hide in87
in88 <- plugin' (vca63 ++ "." ++ "signal") (-264.0,312.0) (Outside container86)
setColour in88 "#control"
in89 <- plugin' (vca64 ++ "." ++ "cv") (-221.0,250.0) (Outside container86)
setColour in89 "#sample"
hide in89
in90 <- plugin' (vca64 ++ "." ++ "signal") (-264.0,252.0) (Outside container86)
setColour in90 "#control"
in91 <- plugin' (vca65 ++ "." ++ "cv") (-223.0,134.0) (Outside container86)
setColour in91 "#sample"
hide in91
in92 <- plugin' (vca65 ++ "." ++ "signal") (-264.0,192.0) (Outside container86)
setColour in92 "#control"
in93 <- plugin' (id23 ++ "." ++ "signal") (-264.0,372.0) (Outside container86)
setColour in93 "#control"
knob100 <- knob' (input40 ++ "." ++ "result") (-180.0,144.0) (Outside container86)
setLow knob100 (Just (1.0))
setHigh knob100 (Just (1000.0))
knob94 <- knob' (input44 ++ "." ++ "result") (-180.0,312.0) (Outside container86)
setLow knob94 (Just (-1.0))
setHigh knob94 (Just (1.0))
knob95 <- knob' (input31 ++ "." ++ "result") (-228.0,312.0) (Outside container86)
knob96 <- knob' (input32 ++ "." ++ "result") (-228.0,252.0) (Outside container86)
knob97 <- knob' (input33 ++ "." ++ "result") (-180.0,252.0) (Outside container86)
setLow knob97 (Just (-1.0))
setHigh knob97 (Just (1.0))
knob98 <- knob' (input34 ++ "." ++ "result") (-228.0,192.0) (Outside container86)
knob99 <- knob' (input35 ++ "." ++ "result") (-180.0,192.0) (Outside container86)
setLow knob99 (Just (-1.0))
setHigh knob99 (Just (1.0))
out101 <- plugout' (butterbp6 ++ "." ++ "result") (-144.0,192.0) (Outside container86)
setColour out101 "#sample"
out102 <- plugout' (butterlp9 ++ "." ++ "result") (-144.0,312.0) (Outside container86)
setColour out102 "#sample"
out103 <- plugout' (butterhp8 ++ "." ++ "result") (-144.0,252.0) (Outside container86)
setColour out103 "#sample"
proxy104 <- proxy' (-155.0,362.0) (Outside container86)
hide proxy104
in105 <- plugin' (sum52 ++ "." ++ "signal2") (-129.0,144.0) (Inside proxy104)
setColour in105 "#sample"
hide in105
in106 <- plugin' (sum53 ++ "." ++ "signal1") (-134.0,73.0) (Inside proxy104)
setColour in106 "#sample"
in107 <- plugin' (sum53 ++ "." ++ "signal2") (-134.0,23.0) (Inside proxy104)
setColour in107 "#sample"
hide in107
in108 <- plugin' (sum54 ++ "." ++ "signal1") (-140.0,-40.0) (Inside proxy104)
setColour in108 "#sample"
in109 <- plugin' (sum54 ++ "." ++ "signal2") (-140.0,-90.0) (Inside proxy104)
setColour in109 "#sample"
hide in109
in110 <- plugin' (butterlp9 ++ "." ++ "freq") (-43.0,192.0) (Inside proxy104)
setColour in110 "#sample"
in111 <- plugin' (butterlp9 ++ "." ++ "signal") (-43.0,142.0) (Inside proxy104)
setColour in111 "#sample"
in112 <- plugin' (butterhp8 ++ "." ++ "freq") (-47.0,72.0) (Inside proxy104)
setColour in112 "#sample"
in113 <- plugin' (butterhp8 ++ "." ++ "signal") (-47.0,22.0) (Inside proxy104)
setColour in113 "#sample"
in114 <- plugin' (butterbp6 ++ "." ++ "freq") (-55.0,-41.0) (Inside proxy104)
setColour in114 "#sample"
in115 <- plugin' (butterbp6 ++ "." ++ "bandwidth") (-55.0,-91.0) (Inside proxy104)
setColour in115 "#sample"
hide in115
in116 <- plugin' (butterbp6 ++ "." ++ "signal") (-55.0,-141.0) (Inside proxy104)
setColour in116 "#sample"
in117 <- plugin' (sum52 ++ "." ++ "signal1") (-129.0,194.0) (Inside proxy104)
setColour in117 "#sample"
out118 <- plugout' (sum52 ++ "." ++ "result") (-79.0,194.0) (Inside proxy104)
setColour out118 "#sample"
out119 <- plugout' (sum53 ++ "." ++ "result") (-84.0,73.0) (Inside proxy104)
setColour out119 "#sample"
out120 <- plugout' (sum54 ++ "." ++ "result") (-90.0,-40.0) (Inside proxy104)
setColour out120 "#sample"
out121 <- plugout' (vca63 ++ "." ++ "result") (-200.0,196.0) (Inside proxy104)
setColour out121 "#sample"
out122 <- plugout' (vca64 ++ "." ++ "result") (-205.0,74.0) (Inside proxy104)
setColour out122 "#sample"
out123 <- plugout' (vca65 ++ "." ++ "result") (-207.0,-42.0) (Inside proxy104)
setColour out123 "#sample"
out124 <- plugout' (id23 ++ "." ++ "result") (-163.0,279.0) (Inside proxy104)
setColour out124 "#sample"
in253 <- plugin' (audio_id0 ++ "." ++ "signal") (273.0,313.0) (Inside proxy78)
setColour in253 "#sample"
out254 <- plugout' (id24 ++ "." ++ "result") (-443.0,391.0) (Inside proxy78)
setColour out254 "#control"
cable out243 in126
cable out85 in127
cable knob133 in131
cable out103 in132
cable knob142 in138
cable knob141 in139
cable out178 in149
cable out179 in150
cable out152 in154
cable out181 in155
cable out152 in159
cable out181 in160
cable out152 in164
cable out181 in165
cable out180 in169
cable out181 in170
cable out152 in171
cable out173 in174
cable out157 in175
cable out162 in176
cable out167 in177
cable knob185 in183
cable out204 in184
cable knob197 in189
cable knob198 in191
cable knob200 in193
cable out146 in195
cable knob196 in207
cable out224 in208
cable knob199 in209
cable out225 in210
cable knob201 in211
cable out220 in212
cable out226 in213
cable out221 in214
cable out226 in215
cable out222 in216
cable knob202 in217
cable out226 in218
cable out223 in219
cable knob230 in228
cable out254 in229
cable out232 in234
cable out187 in235
cable knob241 in239
cable out249 in240
cable knob247 in245
cable out254 in246
cable out102 in80
cable out135 in81
cable out237 in82
cable knob95 in87
cable knob96 in89
cable knob98 in91
cable out252 in93
cable knob94 in105
cable out122 in106
cable knob97 in107
cable out123 in108
cable knob99 in109
cable out118 in110
cable out124 in111
cable out119 in112
cable out124 in113
cable out120 in114
cable knob100 in115
cable out124 in116
cable out121 in117
cable out129 in253
recompile
set knob133 (8.0161564e-2)
set knob141 (0.0)
set knob142 (-1.1291575e-2)
set knob185 (0.25945795)
set knob196 (2.197437e-2)
set knob197 (0.0)
set knob198 (0.0)
set knob199 (0.0)
set knob200 (0.0)
set knob201 (0.0)
set knob202 (250.0)
set knob230 (0.15300322)
set knob241 (9.900498e-3)
set knob247 (8.831644e-2)
set knob100 (265.02878)
set knob94 (4.6845093e-2)
set knob95 (0.14070351)
set knob96 (0.0)
set knob97 (0.43715206)
set knob98 (0.0)
set knob99 (-4.8079353e-2)
return ()
| null | https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/scripts/snare_drum.hs | haskell | do
(x0, y0) <- mouse
let (x, y) = quantise2 quantum (x0, y0)
root <- currentPlane
audio_id0 <- new' "audio_id"
audio_saw1 <- new' "audio_saw"
audio_sin2 <- new' "audio_sin"
audio_square3 <- new' "audio_square"
audio_triangle4 <- new' "audio_triangle"
butterbp5 <- new' "butterbp"
butterbp6 <- new' "butterbp"
butterhp7 <- new' "butterhp"
butterhp8 <- new' "butterhp"
butterlp10 <- new' "butterlp"
butterlp11 <- new' "butterlp"
butterlp9 <- new' "butterlp"
exp_decay12 <- new' "exp_decay"
exp_decay13 <- new' "exp_decay"
id15 <- new' "id"
id16 <- new' "id"
id17 <- new' "id"
id18 <- new' "id"
id19 <- new' "id"
id20 <- new' "id"
id21 <- new' "id"
id22 <- new' "id"
id23 <- new' "id"
id24 <- new' "id"
id25 <- new' "id"
input14 <- new' "input"
input27 <- new' "input"
input28 <- new' "input"
input29 <- new' "input"
input30 <- new' "input"
input31 <- new' "input"
input32 <- new' "input"
input33 <- new' "input"
input34 <- new' "input"
input35 <- new' "input"
input36 <- new' "input"
input37 <- new' "input"
input38 <- new' "input"
input39 <- new' "input"
input40 <- new' "input"
input41 <- new' "input"
input42 <- new' "input"
input43 <- new' "input"
input44 <- new' "input"
input45 <- new' "input"
input57 <- new' "input"
noise47 <- new' "noise"
sum455 <- new' "sum4"
sum48 <- new' "sum"
sum49 <- new' "sum"
sum50 <- new' "sum"
sum51 <- new' "sum"
sum52 <- new' "sum"
sum53 <- new' "sum"
sum54 <- new' "sum"
vca56 <- new' "vca"
vca58 <- new' "vca"
vca59 <- new' "vca"
vca60 <- new' "vca"
vca61 <- new' "vca"
vca62 <- new' "vca"
vca63 <- new' "vca"
vca64 <- new' "vca"
vca65 <- new' "vca"
vca66 <- new' "vca"
container258 <- container' "panel_snare_drum.png" (x+(-96.0), y+(72.0)) (Inside root)
in76 <- plugin' (id24 ++ "." ++ "signal") (x+(-156.0), y+(72.0)) (Outside container258)
setColour in76 "#control"
out77 <- plugout' (audio_id0 ++ "." ++ "result") (x+(-36.0), y+(72.0)) (Outside container258)
setColour out77 "#sample"
proxy78 <- proxy' (x+(-96.0), y+(72.0)) (Outside container258)
hide proxy78
container125 <- container' "panel_3x1.png" (180.0,480.0) (Inside proxy78)
in126 <- plugin' (vca62 ++ "." ++ "cv") (159.0,505.0) (Outside container125)
setColour in126 "#control"
in127 <- plugin' (vca62 ++ "." ++ "signal") (159.0,455.0) (Outside container125)
setColour in127 "#sample"
label128 <- label' "vca" (155.0,555.0) (Outside container125)
out129 <- plugout' (vca62 ++ "." ++ "result") (200.0,480.0) (Outside container125)
setColour out129 "#sample"
container130 <- container' "panel_3x1.png" (0.0,132.0) (Inside proxy78)
in131 <- plugin' (vca66 ++ "." ++ "cv") (-21.0,157.0) (Outside container130)
setColour in131 "#control"
hide in131
in132 <- plugin' (vca66 ++ "." ++ "signal") (-21.0,107.0) (Outside container130)
setColour in132 "#sample"
knob133 <- knob' (input45 ++ "." ++ "result") (-21.0,157.0) (Outside container130)
label134 <- label' "vca" (-25.0,207.0) (Outside container130)
out135 <- plugout' (vca66 ++ "." ++ "result") (20.0,132.0) (Outside container130)
setColour out135 "#sample"
container136 <- container' "panel_vco2.png" (-456.0,-36.0) (Inside proxy78)
in137 <- plugin' (id21 ++ "." ++ "signal") (-420.0,0.0) (Outside container136)
setColour in137 "#control"
in138 <- plugin' (id22 ++ "." ++ "signal") (-443.0,44.0) (Outside container136)
setColour in138 "#sample"
hide in138
in139 <- plugin' (id15 ++ "." ++ "signal") (-425.0,-33.0) (Outside container136)
setColour in139 "#sample"
hide in139
in140 <- plugin' (id16 ++ "." ++ "signal") (-420.0,-72.0) (Outside container136)
setColour in140 "#control"
knob141 <- knob' (input28 ++ "." ++ "result") (-420.0,-36.0) (Outside container136)
knob142 <- knob' (input27 ++ "." ++ "result") (-420.0,36.0) (Outside container136)
out143 <- plugout' (id20 ++ "." ++ "result") (-480.0,-120.0) (Outside container136)
setColour out143 "#sample"
out144 <- plugout' (id17 ++ "." ++ "result") (-408.0,-120.0) (Outside container136)
setColour out144 "#sample"
out145 <- plugout' (id18 ++ "." ++ "result") (-480.0,-156.0) (Outside container136)
setColour out145 "#sample"
out146 <- plugout' (id19 ++ "." ++ "result") (-408.0,-156.0) (Outside container136)
setColour out146 "#sample"
proxy147 <- proxy' (-503.0,46.0) (Outside container136)
hide proxy147
container148 <- container' "panel_3x1.png" (-815.0,439.0) (Inside proxy147)
in149 <- plugin' (sum48 ++ "." ++ "signal2") (-836.0,414.0) (Outside container148)
setColour in149 "#sample"
in150 <- plugin' (sum48 ++ "." ++ "signal1") (-836.0,464.0) (Outside container148)
setColour in150 "#sample"
label151 <- label' "sum" (-840.0,514.0) (Outside container148)
out152 <- plugout' (sum48 ++ "." ++ "result") (-795.0,439.0) (Outside container148)
setColour out152 "#sample"
container153 <- container' "panel_3x1.png" (-434.0,420.0) (Inside proxy147)
in154 <- plugin' (audio_triangle4 ++ "." ++ "freq") (-455.0,445.0) (Outside container153)
setColour in154 "#sample"
in155 <- plugin' (audio_triangle4 ++ "." ++ "sync") (-455.0,395.0) (Outside container153)
setColour in155 "#sample"
label156 <- label' "audio_triangle" (-459.0,495.0) (Outside container153)
out157 <- plugout' (audio_triangle4 ++ "." ++ "result") (-414.0,420.0) (Outside container153)
setColour out157 "#sample"
container158 <- container' "panel_3x1.png" (-318.0,291.0) (Inside proxy147)
in159 <- plugin' (audio_saw1 ++ "." ++ "freq") (-339.0,316.0) (Outside container158)
setColour in159 "#sample"
in160 <- plugin' (audio_saw1 ++ "." ++ "sync") (-339.0,266.0) (Outside container158)
setColour in160 "#sample"
label161 <- label' "audio_saw" (-343.0,366.0) (Outside container158)
out162 <- plugout' (audio_saw1 ++ "." ++ "result") (-298.0,291.0) (Outside container158)
setColour out162 "#sample"
container163 <- container' "panel_3x1.png" (-691.0,453.0) (Inside proxy147)
in164 <- plugin' (audio_sin2 ++ "." ++ "freq") (-712.0,478.0) (Outside container163)
setColour in164 "#sample"
in165 <- plugin' (audio_sin2 ++ "." ++ "sync") (-712.0,428.0) (Outside container163)
setColour in165 "#sample"
label166 <- label' "audio_sin" (-716.0,528.0) (Outside container163)
out167 <- plugout' (audio_sin2 ++ "." ++ "result") (-671.0,453.0) (Outside container163)
setColour out167 "#sample"
container168 <- container' "panel_3x1.png" (-826.0,199.0) (Inside proxy147)
in169 <- plugin' (audio_square3 ++ "." ++ "pwm") (-847.0,199.0) (Outside container168)
setColour in169 "#sample"
in170 <- plugin' (audio_square3 ++ "." ++ "sync") (-847.0,149.0) (Outside container168)
setColour in170 "#sample"
in171 <- plugin' (audio_square3 ++ "." ++ "freq") (-847.0,249.0) (Outside container168)
setColour in171 "#sample"
label172 <- label' "audio_square" (-851.0,274.0) (Outside container168)
out173 <- plugout' (audio_square3 ++ "." ++ "result") (-806.0,199.0) (Outside container168)
setColour out173 "#sample"
in174 <- plugin' (id17 ++ "." ++ "signal") (-753.0,198.0) (Inside proxy147)
setColour in174 "#sample"
in175 <- plugin' (id18 ++ "." ++ "signal") (-360.0,422.0) (Inside proxy147)
setColour in175 "#sample"
in176 <- plugin' (id19 ++ "." ++ "signal") (-247.0,292.0) (Inside proxy147)
setColour in176 "#sample"
in177 <- plugin' (id20 ++ "." ++ "signal") (-556.0,449.0) (Inside proxy147)
setColour in177 "#sample"
out178 <- plugout' (id21 ++ "." ++ "result") (-891.0,413.0) (Inside proxy147)
setColour out178 "#sample"
out179 <- plugout' (id22 ++ "." ++ "result") (-892.0,469.0) (Inside proxy147)
setColour out179 "#sample"
out180 <- plugout' (id15 ++ "." ++ "result") (-894.0,199.0) (Inside proxy147)
setColour out180 "#sample"
out181 <- plugout' (id16 ++ "." ++ "result") (-893.0,146.0) (Inside proxy147)
setColour out181 "#sample"
container182 <- container' "panel_3x1.png" (-48.0,-108.0) (Inside proxy78)
in183 <- plugin' (vca56 ++ "." ++ "cv") (-69.0,-83.0) (Outside container182)
setColour in183 "#control"
hide in183
in184 <- plugin' (vca56 ++ "." ++ "signal") (-69.0,-133.0) (Outside container182)
setColour in184 "#sample"
knob185 <- knob' (input57 ++ "." ++ "result") (-69.0,-83.0) (Outside container182)
label186 <- label' "vca" (-73.0,-33.0) (Outside container182)
out187 <- plugout' (vca56 ++ "." ++ "result") (-28.0,-108.0) (Outside container182)
setColour out187 "#sample"
container188 <- container' "panel_filter.png" (-240.0,-72.0) (Inside proxy78)
in189 <- plugin' (vca58 ++ "." ++ "cv") (-252.0,48.0) (Outside container188)
setColour in189 "#sample"
hide in189
in190 <- plugin' (vca58 ++ "." ++ "signal") (-300.0,-12.0) (Outside container188)
setColour in190 "#control"
in191 <- plugin' (vca59 ++ "." ++ "cv") (-257.0,-74.0) (Outside container188)
setColour in191 "#sample"
hide in191
in192 <- plugin' (vca59 ++ "." ++ "signal") (-300.0,-72.0) (Outside container188)
setColour in192 "#control"
in193 <- plugin' (vca60 ++ "." ++ "cv") (-259.0,-190.0) (Outside container188)
setColour in193 "#sample"
hide in193
in194 <- plugin' (vca60 ++ "." ++ "signal") (-300.0,-132.0) (Outside container188)
setColour in194 "#control"
in195 <- plugin' (id25 ++ "." ++ "signal") (-300.0,48.0) (Outside container188)
setColour in195 "#control"
knob196 <- knob' (input43 ++ "." ++ "result") (-216.0,-12.0) (Outside container188)
setLow knob196 (Just (-1.0))
setHigh knob196 (Just (1.0))
knob197 <- knob' (input36 ++ "." ++ "result") (-264.0,-12.0) (Outside container188)
knob198 <- knob' (input37 ++ "." ++ "result") (-264.0,-72.0) (Outside container188)
knob199 <- knob' (input38 ++ "." ++ "result") (-216.0,-72.0) (Outside container188)
setLow knob199 (Just (-1.0))
setHigh knob199 (Just (1.0))
knob200 <- knob' (input39 ++ "." ++ "result") (-264.0,-132.0) (Outside container188)
knob201 <- knob' (input41 ++ "." ++ "result") (-216.0,-132.0) (Outside container188)
setLow knob201 (Just (-1.0))
setHigh knob201 (Just (1.0))
knob202 <- knob' (input42 ++ "." ++ "result") (-216.0,-180.0) (Outside container188)
setLow knob202 (Just (1.0))
setHigh knob202 (Just (1000.0))
out203 <- plugout' (butterbp5 ++ "." ++ "result") (-180.0,-132.0) (Outside container188)
setColour out203 "#sample"
out204 <- plugout' (butterlp11 ++ "." ++ "result") (-180.0,-12.0) (Outside container188)
setColour out204 "#sample"
out205 <- plugout' (butterhp7 ++ "." ++ "result") (-180.0,-72.0) (Outside container188)
setColour out205 "#sample"
proxy206 <- proxy' (-191.0,38.0) (Outside container188)
hide proxy206
in207 <- plugin' (sum49 ++ "." ++ "signal2") (-129.0,144.0) (Inside proxy206)
setColour in207 "#sample"
hide in207
in208 <- plugin' (sum50 ++ "." ++ "signal1") (-134.0,73.0) (Inside proxy206)
setColour in208 "#sample"
in209 <- plugin' (sum50 ++ "." ++ "signal2") (-134.0,23.0) (Inside proxy206)
setColour in209 "#sample"
hide in209
in210 <- plugin' (sum51 ++ "." ++ "signal1") (-140.0,-40.0) (Inside proxy206)
setColour in210 "#sample"
in211 <- plugin' (sum51 ++ "." ++ "signal2") (-140.0,-90.0) (Inside proxy206)
setColour in211 "#sample"
hide in211
in212 <- plugin' (butterlp11 ++ "." ++ "freq") (-43.0,192.0) (Inside proxy206)
setColour in212 "#sample"
in213 <- plugin' (butterlp11 ++ "." ++ "signal") (-43.0,142.0) (Inside proxy206)
setColour in213 "#sample"
in214 <- plugin' (butterhp7 ++ "." ++ "freq") (-47.0,72.0) (Inside proxy206)
setColour in214 "#sample"
in215 <- plugin' (butterhp7 ++ "." ++ "signal") (-47.0,22.0) (Inside proxy206)
setColour in215 "#sample"
in216 <- plugin' (butterbp5 ++ "." ++ "freq") (-55.0,-41.0) (Inside proxy206)
setColour in216 "#sample"
in217 <- plugin' (butterbp5 ++ "." ++ "bandwidth") (-55.0,-91.0) (Inside proxy206)
setColour in217 "#sample"
hide in217
in218 <- plugin' (butterbp5 ++ "." ++ "signal") (-55.0,-141.0) (Inside proxy206)
setColour in218 "#sample"
in219 <- plugin' (sum49 ++ "." ++ "signal1") (-129.0,194.0) (Inside proxy206)
setColour in219 "#sample"
out220 <- plugout' (sum49 ++ "." ++ "result") (-79.0,194.0) (Inside proxy206)
setColour out220 "#sample"
out221 <- plugout' (sum50 ++ "." ++ "result") (-84.0,73.0) (Inside proxy206)
setColour out221 "#sample"
out222 <- plugout' (sum51 ++ "." ++ "result") (-90.0,-40.0) (Inside proxy206)
setColour out222 "#sample"
out223 <- plugout' (vca58 ++ "." ++ "result") (-200.0,196.0) (Inside proxy206)
setColour out223 "#sample"
out224 <- plugout' (vca59 ++ "." ++ "result") (-205.0,74.0) (Inside proxy206)
setColour out224 "#sample"
out225 <- plugout' (vca60 ++ "." ++ "result") (-207.0,-42.0) (Inside proxy206)
setColour out225 "#sample"
out226 <- plugout' (id25 ++ "." ++ "result") (-163.0,279.0) (Inside proxy206)
setColour out226 "#sample"
container227 <- container' "panel_3x1.png" (60.0,-120.0) (Inside proxy78)
in228 <- plugin' (exp_decay13 ++ "." ++ "decay_time") (39.0,-95.0) (Outside container227)
setColour in228 "#control"
hide in228
in229 <- plugin' (exp_decay13 ++ "." ++ "trigger") (39.0,-145.0) (Outside container227)
setColour in229 "#control"
knob230 <- knob' (input14 ++ "." ++ "result") (39.0,-95.0) (Outside container227)
label231 <- label' "exp_decay" (35.0,-45.0) (Outside container227)
out232 <- plugout' (exp_decay13 ++ "." ++ "result") (80.0,-120.0) (Outside container227)
setColour out232 "#control"
container233 <- container' "panel_3x1.png" (180.0,-108.0) (Inside proxy78)
in234 <- plugin' (vca61 ++ "." ++ "cv") (159.0,-83.0) (Outside container233)
setColour in234 "#control"
in235 <- plugin' (vca61 ++ "." ++ "signal") (159.0,-133.0) (Outside container233)
setColour in235 "#sample"
label236 <- label' "vca" (155.0,-33.0) (Outside container233)
out237 <- plugout' (vca61 ++ "." ++ "result") (200.0,-108.0) (Outside container233)
setColour out237 "#sample"
container238 <- container' "panel_3x1.png" (-156.0,552.0) (Inside proxy78)
in239 <- plugin' (butterlp10 ++ "." ++ "freq") (-177.0,577.0) (Outside container238)
setColour in239 "#control"
hide in239
in240 <- plugin' (butterlp10 ++ "." ++ "signal") (-177.0,527.0) (Outside container238)
setColour in240 "#sample"
knob241 <- knob' (input29 ++ "." ++ "result") (-177.0,577.0) (Outside container238)
label242 <- label' "butterlp" (-181.0,627.0) (Outside container238)
out243 <- plugout' (butterlp10 ++ "." ++ "result") (-136.0,552.0) (Outside container238)
setColour out243 "#sample"
container244 <- container' "panel_3x1.png" (-276.0,564.0) (Inside proxy78)
in245 <- plugin' (exp_decay12 ++ "." ++ "decay_time") (-297.0,589.0) (Outside container244)
setColour in245 "#control"
hide in245
in246 <- plugin' (exp_decay12 ++ "." ++ "trigger") (-297.0,539.0) (Outside container244)
setColour in246 "#control"
knob247 <- knob' (input30 ++ "." ++ "result") (-297.0,589.0) (Outside container244)
label248 <- label' "exp_decay" (-301.0,639.0) (Outside container244)
out249 <- plugout' (exp_decay12 ++ "." ++ "result") (-256.0,564.0) (Outside container244)
setColour out249 "#control"
container250 <- container' "panel_3x1.png" (-420.0,228.0) (Inside proxy78)
label251 <- label' "noise" (-445.0,303.0) (Outside container250)
out252 <- plugout' (noise47 ++ "." ++ "result") (-400.0,228.0) (Outside container250)
setColour out252 "#sample"
container79 <- container' "panel_4x1.png" (168.0,180.0) (Inside proxy78)
in80 <- plugin' (sum455 ++ "." ++ "signal1") (147.0,255.0) (Outside container79)
setColour in80 "#sample"
in81 <- plugin' (sum455 ++ "." ++ "signal2") (147.0,205.0) (Outside container79)
setColour in81 "#sample"
in82 <- plugin' (sum455 ++ "." ++ "signal3") (147.0,155.0) (Outside container79)
setColour in82 "#sample"
in83 <- plugin' (sum455 ++ "." ++ "signal4") (147.0,105.0) (Outside container79)
setColour in83 "#sample"
label84 <- label' "sum4" (143.0,255.0) (Outside container79)
out85 <- plugout' (sum455 ++ "." ++ "result") (188.0,180.0) (Outside container79)
setColour out85 "#sample"
container86 <- container' "panel_filter.png" (-204.0,252.0) (Inside proxy78)
in87 <- plugin' (vca63 ++ "." ++ "cv") (-216.0,372.0) (Outside container86)
setColour in87 "#sample"
hide in87
in88 <- plugin' (vca63 ++ "." ++ "signal") (-264.0,312.0) (Outside container86)
setColour in88 "#control"
in89 <- plugin' (vca64 ++ "." ++ "cv") (-221.0,250.0) (Outside container86)
setColour in89 "#sample"
hide in89
in90 <- plugin' (vca64 ++ "." ++ "signal") (-264.0,252.0) (Outside container86)
setColour in90 "#control"
in91 <- plugin' (vca65 ++ "." ++ "cv") (-223.0,134.0) (Outside container86)
setColour in91 "#sample"
hide in91
in92 <- plugin' (vca65 ++ "." ++ "signal") (-264.0,192.0) (Outside container86)
setColour in92 "#control"
in93 <- plugin' (id23 ++ "." ++ "signal") (-264.0,372.0) (Outside container86)
setColour in93 "#control"
knob100 <- knob' (input40 ++ "." ++ "result") (-180.0,144.0) (Outside container86)
setLow knob100 (Just (1.0))
setHigh knob100 (Just (1000.0))
knob94 <- knob' (input44 ++ "." ++ "result") (-180.0,312.0) (Outside container86)
setLow knob94 (Just (-1.0))
setHigh knob94 (Just (1.0))
knob95 <- knob' (input31 ++ "." ++ "result") (-228.0,312.0) (Outside container86)
knob96 <- knob' (input32 ++ "." ++ "result") (-228.0,252.0) (Outside container86)
knob97 <- knob' (input33 ++ "." ++ "result") (-180.0,252.0) (Outside container86)
setLow knob97 (Just (-1.0))
setHigh knob97 (Just (1.0))
knob98 <- knob' (input34 ++ "." ++ "result") (-228.0,192.0) (Outside container86)
knob99 <- knob' (input35 ++ "." ++ "result") (-180.0,192.0) (Outside container86)
setLow knob99 (Just (-1.0))
setHigh knob99 (Just (1.0))
out101 <- plugout' (butterbp6 ++ "." ++ "result") (-144.0,192.0) (Outside container86)
setColour out101 "#sample"
out102 <- plugout' (butterlp9 ++ "." ++ "result") (-144.0,312.0) (Outside container86)
setColour out102 "#sample"
out103 <- plugout' (butterhp8 ++ "." ++ "result") (-144.0,252.0) (Outside container86)
setColour out103 "#sample"
proxy104 <- proxy' (-155.0,362.0) (Outside container86)
hide proxy104
in105 <- plugin' (sum52 ++ "." ++ "signal2") (-129.0,144.0) (Inside proxy104)
setColour in105 "#sample"
hide in105
in106 <- plugin' (sum53 ++ "." ++ "signal1") (-134.0,73.0) (Inside proxy104)
setColour in106 "#sample"
in107 <- plugin' (sum53 ++ "." ++ "signal2") (-134.0,23.0) (Inside proxy104)
setColour in107 "#sample"
hide in107
in108 <- plugin' (sum54 ++ "." ++ "signal1") (-140.0,-40.0) (Inside proxy104)
setColour in108 "#sample"
in109 <- plugin' (sum54 ++ "." ++ "signal2") (-140.0,-90.0) (Inside proxy104)
setColour in109 "#sample"
hide in109
in110 <- plugin' (butterlp9 ++ "." ++ "freq") (-43.0,192.0) (Inside proxy104)
setColour in110 "#sample"
in111 <- plugin' (butterlp9 ++ "." ++ "signal") (-43.0,142.0) (Inside proxy104)
setColour in111 "#sample"
in112 <- plugin' (butterhp8 ++ "." ++ "freq") (-47.0,72.0) (Inside proxy104)
setColour in112 "#sample"
in113 <- plugin' (butterhp8 ++ "." ++ "signal") (-47.0,22.0) (Inside proxy104)
setColour in113 "#sample"
in114 <- plugin' (butterbp6 ++ "." ++ "freq") (-55.0,-41.0) (Inside proxy104)
setColour in114 "#sample"
in115 <- plugin' (butterbp6 ++ "." ++ "bandwidth") (-55.0,-91.0) (Inside proxy104)
setColour in115 "#sample"
hide in115
in116 <- plugin' (butterbp6 ++ "." ++ "signal") (-55.0,-141.0) (Inside proxy104)
setColour in116 "#sample"
in117 <- plugin' (sum52 ++ "." ++ "signal1") (-129.0,194.0) (Inside proxy104)
setColour in117 "#sample"
out118 <- plugout' (sum52 ++ "." ++ "result") (-79.0,194.0) (Inside proxy104)
setColour out118 "#sample"
out119 <- plugout' (sum53 ++ "." ++ "result") (-84.0,73.0) (Inside proxy104)
setColour out119 "#sample"
out120 <- plugout' (sum54 ++ "." ++ "result") (-90.0,-40.0) (Inside proxy104)
setColour out120 "#sample"
out121 <- plugout' (vca63 ++ "." ++ "result") (-200.0,196.0) (Inside proxy104)
setColour out121 "#sample"
out122 <- plugout' (vca64 ++ "." ++ "result") (-205.0,74.0) (Inside proxy104)
setColour out122 "#sample"
out123 <- plugout' (vca65 ++ "." ++ "result") (-207.0,-42.0) (Inside proxy104)
setColour out123 "#sample"
out124 <- plugout' (id23 ++ "." ++ "result") (-163.0,279.0) (Inside proxy104)
setColour out124 "#sample"
in253 <- plugin' (audio_id0 ++ "." ++ "signal") (273.0,313.0) (Inside proxy78)
setColour in253 "#sample"
out254 <- plugout' (id24 ++ "." ++ "result") (-443.0,391.0) (Inside proxy78)
setColour out254 "#control"
cable out243 in126
cable out85 in127
cable knob133 in131
cable out103 in132
cable knob142 in138
cable knob141 in139
cable out178 in149
cable out179 in150
cable out152 in154
cable out181 in155
cable out152 in159
cable out181 in160
cable out152 in164
cable out181 in165
cable out180 in169
cable out181 in170
cable out152 in171
cable out173 in174
cable out157 in175
cable out162 in176
cable out167 in177
cable knob185 in183
cable out204 in184
cable knob197 in189
cable knob198 in191
cable knob200 in193
cable out146 in195
cable knob196 in207
cable out224 in208
cable knob199 in209
cable out225 in210
cable knob201 in211
cable out220 in212
cable out226 in213
cable out221 in214
cable out226 in215
cable out222 in216
cable knob202 in217
cable out226 in218
cable out223 in219
cable knob230 in228
cable out254 in229
cable out232 in234
cable out187 in235
cable knob241 in239
cable out249 in240
cable knob247 in245
cable out254 in246
cable out102 in80
cable out135 in81
cable out237 in82
cable knob95 in87
cable knob96 in89
cable knob98 in91
cable out252 in93
cable knob94 in105
cable out122 in106
cable knob97 in107
cable out123 in108
cable knob99 in109
cable out118 in110
cable out124 in111
cable out119 in112
cable out124 in113
cable out120 in114
cable knob100 in115
cable out124 in116
cable out121 in117
cable out129 in253
recompile
set knob133 (8.0161564e-2)
set knob141 (0.0)
set knob142 (-1.1291575e-2)
set knob185 (0.25945795)
set knob196 (2.197437e-2)
set knob197 (0.0)
set knob198 (0.0)
set knob199 (0.0)
set knob200 (0.0)
set knob201 (0.0)
set knob202 (250.0)
set knob230 (0.15300322)
set knob241 (9.900498e-3)
set knob247 (8.831644e-2)
set knob100 (265.02878)
set knob94 (4.6845093e-2)
set knob95 (0.14070351)
set knob96 (0.0)
set knob97 (0.43715206)
set knob98 (0.0)
set knob99 (-4.8079353e-2)
return ()
|
|
300aaf9e1f8fc1073f2b82a88214192d02a39b6d8251ec87bd734fd807de5143 | clash-lang/clash-compiler | Main.hs | # LANGUAGE CPP #
# LANGUAGE QuasiQuotes #
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Clash.Util.Interpolate as I
import Clash.Annotations.Primitive (HDL(..))
import qualified Data.Text as Text
import Data.Default (def)
import Data.List ((\\), intercalate)
import Data.Version (versionBranch)
import System.Directory
(getCurrentDirectory, doesDirectoryExist, makeAbsolute)
import System.Environment
import System.Info
import GHC.Conc (numCapabilities)
import GHC.Stack
import GHC.IO.Unsafe (unsafePerformIO)
import Text.Printf (printf)
import Test.Tasty
import Test.Tasty.Common
import Test.Tasty.Clash
| GHC version as major.minor.patch1 . For example : 8.10.2 .
ghcVersion3 :: String
ghcVersion3 =
#ifdef __GLASGOW_HASKELL_PATCHLEVEL2__
let ghc_p1 = __GLASGOW_HASKELL_PATCHLEVEL1__
ghc_p2 = __GLASGOW_HASKELL_PATCHLEVEL2__ in
intercalate "." (map show (versionBranch compilerVersion <> [ghc_p1,ghc_p2]))
#else
let ghc_p1 = __GLASGOW_HASKELL_PATCHLEVEL1__ in
intercalate "." (map show (versionBranch compilerVersion <> [ghc_p1]))
#endif
-- Directory clash binary is expected to live in
cabalClashBinDir :: IO String
cabalClashBinDir = makeAbsolute rel_path
where
rel_path = printf templ platform ghcVersion3 (VERSION_clash_ghc :: String)
platform :: String -- XXX: Hardcoded
platform = case os of
"mingw32" -> arch <> "-windows"
_ -> arch <> "-" <> os
templ = "dist-newstyle/build/%s/ghc-%s/clash-ghc-%s/x/clash/build/clash/" :: String
| Set GHC_PACKAGE_PATH for local Cabal install . Currently hardcoded for Unix ;
-- override by setting @store_dir@ to point to local cabal installation.
setCabalPackagePaths :: IO ()
setCabalPackagePaths = do
ch <- lookupEnv "store_dir"
storeDir <- case ch of
Just dir -> pure dir
Nothing -> case os of
default ghcup location
_ -> (<> "/.cabal/store") <$> getEnv "HOME"
here <- getCurrentDirectory
setEnv "GHC_PACKAGE_PATH" $
storeDir <> "/ghc-" <> ghcVersion3 <> "/package.db"
<> ":"
<> here <> "/dist-newstyle/packagedb/ghc-" <> ghcVersion3
<> ":"
-- | See 'compiledWith'
data RunWith
= Stack
| Cabal
| Global
deriving (Show, Eq)
-- | Detects Clash binary the testsuite should use (in order):
--
* If USE_GLOBAL_CLASH=1 , use globally installed Clash
* If STACK_EXE is present , use Stack 's Clash
* If dist - newstyle is present , use Cabal 's Clash
* Use globally installed Clash
--
compiledWith :: RunWith
compiledWith = unsafePerformIO $ do
clash_global <- lookupEnv "USE_GLOBAL_CLASH"
stack_exe <- lookupEnv "STACK_EXE"
distNewstyleExists <- doesDirectoryExist "dist-newstyle"
pure $ case (clash_global, stack_exe, distNewstyleExists) of
(Just "1", Just _, _ ) -> error "Can't use global clash with 'stack run'"
(Just "1", _, _ ) -> Global
(_, Just _, _ ) -> Stack
(_, _ , True) -> Cabal
(_, _ , _ ) -> Global
# NOINLINE compiledWith #
| Set environment variables that allow Clash to be executed by simply calling
-- 'clash' without extra arguments.
setClashEnvs :: HasCallStack => RunWith -> IO ()
setClashEnvs Global = setEnv "GHC_ENVIRONMENT" "-"
setClashEnvs Stack = pure ()
setClashEnvs Cabal = do
binDir <- cabalClashBinDir
path <- getEnv "PATH"
let seperator = case os of { "mingw32" -> ";"; _ -> ":" }
setEnv "PATH" (binDir <> seperator <> path)
setCabalPackagePaths
clashTestRoot
:: [[TestName] -> TestTree]
-> TestTree
clashTestRoot testTrees =
clashTestGroup "." testTrees []
-- | `clashTestGroup` and `clashTestRoot` make sure that each test knows its
-- fully qualified test name at construction time. This is used to create
-- dependency patterns.
clashTestGroup
:: TestName
-> [[TestName] -> TestTree]
-> ([TestName] -> TestTree)
clashTestGroup testName testTrees =
\parentNames ->
testGroup testName $
zipWith ($) testTrees (repeat (testName : parentNames))
runClashTest :: IO ()
runClashTest = defaultMain $ clashTestRoot
[ clashTestGroup "examples"
[ runTest "ALU" def{hdlSim=[]}
, let _opts = def { hdlSim=[]
, hdlTargets=[VHDL]
, buildTargets=BuildSpecific ["blinker"]
}
in runTest "Blinker" _opts
, runTest "BlockRamTest" def{hdlSim=[]}
, runTest "Calculator" def
, runTest "CHIP8" def{hdlSim=[]}
, runTest "CochleaPlus" def{hdlSim=[]}
,
Vivado segfaults
let _opts = def { clashFlags=["-fclash-component-prefix", "test"]
, buildTargets=BuildSpecific ["test_testBench"]
, hdlSim=hdlSim def \\ [Vivado]
}
in runTest "FIR" _opts
, runTest "Fifo" def{hdlSim=[]}
, runTest "MAC" def
, runTest "MatrixVect" def
, runTest "Queens" def{hdlSim=[]}
, runTest "Reducer" def{hdlSim=[]}
, runTest "Sprockell" def{hdlSim=[]}
, runTest "Windows" def{hdlSim=[]}
, clashTestGroup "crc32"
[ runTest "CRC32" def
]
, clashTestGroup "i2c"
[ let _opts = def { clashFlags=["-O2","-fclash-component-prefix","test"]
, buildTargets=BuildSpecific ["test_i2c"]
, hdlSim=[]
}
in runTest "I2C" _opts
,
TODO : this uses finish_and_return , with is Icarus Verilog only .
-- see: -lang/clash-compiler/issues/2265
let _opts = def { buildTargets = BuildSpecific ["system"]
, hdlTargets = [Verilog]
, hdlLoad = [IVerilog]
, hdlSim = [IVerilog]
, vvpStdoutNonEmptyFail = False
}
in runTest "I2Ctest" _opts
]
]
, clashTestGroup "tests"
[ clashTestGroup "shouldfail"
[ clashTestGroup "BlackBox"
[ runTest "WrongReference" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
Function WrongReference.myMultiply was annotated with an inline
primitive for WrongReference.myMultiplyX. These names should be
the same. |])
}
, runTest "T1945" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Template function for returned False")
}
]
, clashTestGroup "Cores"
[ clashTestGroup "Xilinx"
[ clashTestGroup "VIO"
[ runTest "OutputBusWidthExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "Probe signals must be been between 1 and 256 bits wide.")
}
, runTest "OutputProbesExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "At most 256 input/output probes are supported.")
}
, runTest "InputBusWidthExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "Probe signals must be been between 1 and 256 bits wide.")
}
, runTest "InputProbesExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "At most 256 input/output probes are supported.")
}
]
]
]
, clashTestGroup "InvalidPrimitive"
[ runTest "InvalidPrimitive" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "InvalidPrimitive.primitives")
}
]
, clashTestGroup "GADTs"
[ runTest "T1311" def {
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
Can't translate data types with unconstrained existentials|])
}
]
, clashTestGroup "PrimitiveGuards"
[ runTest "DontTranslate" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
Clash was forced to translate 'DontTranslate.primitive', but this
value was marked with DontTranslate. Did you forget to include a
blackbox for one of the constructs using this?
|])
}
, runTest "HasBlackBox" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
No BlackBox definition for 'HasBlackBox.primitive' even though
this value was annotated with 'HasBlackBox'.
|])
}
]
, clashTestGroup "Signal"
[ runTest "MAC" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Couldn't instantiate blackbox for Clash.Signal.Internal.register#")
}
]
, clashTestGroup "SynthesisAttributes"
[ runTest "ProductInArgs" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Cannot use attribute annotations on product types of top entities")
}
, runTest "ProductInResult" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Cannot use attribute annotations on product types of top entities")
}
]
, clashTestGroup "Testbench"
[ runTest "UnsafeOutputVerifier" def{
expectClashFail=Just ( TestSpecificExitCode 0
, "Clash.Explicit.Testbench.unsafeSimSynchronizer is not safely synthesizable!")
}
]
, clashTestGroup "TopEntity"
[ runTest "T1033" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "PortProduct \"wrong\" []")
}
, runTest "T1063" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Saw a PortProduct in a Synthesize annotation")
}
]
, clashTestGroup "Verification"
GHDL only has VERY basic PSL support
_opts = def { hdlTargets=[VHDL]
, buildTargets=BuildSpecific ["fails" <> show i | i <- [(1::Int)..n]]
, hdlLoad=[GHDL]
, hdlSim=[GHDL]
, expectSimFail=Just (def, "psl assertion failed")
}
in runTest "NonTemporalPSL" _opts
, let n = 13
_opts = def { hdlTargets=[SystemVerilog]
, buildTargets=BuildSpecific ["fails" <> show i | i <- [(1::Int)..n]]
Only QuestaSim supports simulating SVA / PSL , but does check
-- for syntax errors.
, hdlLoad=[ModelSim]
, hdlSim=[]
}
in runTest "NonTemporalPSL" _opts
, let is = [(1::Int)..13] \\ [4, 6, 7, 8, 10, 11, 12] in
runTest "NonTemporalSVA" def{
hdlTargets=[SystemVerilog]
, buildTargets=BuildSpecific ["fails" <> show i | i <- is]
Only QuestaSim supports simulating SVA / PSL , but does check
-- for syntax errors.
, hdlLoad=[ModelSim]
, hdlSim=[]
}
, runTest "SymbiYosys" def{
hdlTargets=[Verilog, SystemVerilog]
, hdlLoad=[]
, hdlSim=[]
, verificationTool=Just SymbiYosys
, expectVerificationFail=Just (def, "Unreached cover statement at B")
}
]
, clashTestGroup "ZeroWidth"
[ runTest "FailGracefully1" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Unexpected projection of zero-width type")
}
, runTest "FailGracefully2" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Unexpected projection of zero-width type")
}
, runTest "FailGracefully3" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Unexpected projection of zero-width type")
}
]
, runTest "LiftRecursiveGroup" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def,"Callgraph after normalization contains following recursive components:")
}
, runTest "Poly" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Clash can only normalize monomorphic functions, but this is polymorphic:")
}
, runTest "Poly2" def{
hdlTargets=[VHDL]
, clashFlags=["-fclash-error-extra"]
, expectClashFail=Just (def, "Even after applying type equality constraints it remained polymorphic:")
}
, runTest "RecursiveBoxed" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, " already inlined 20 times in: ") -- (RecursiveBoxed\.)?topEntity
}
, runTest "RecursiveDatatype" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "This bndr has a non-representable return type and can't be normalized:")
}
-- Disabled, due to it eating gigabytes of memory:
, runTest " RecursivePoly " def {
-- hdlTargets=[VHDL]
-- , expectClashFail=Just (def, "??")
-- }
]
, clashTestGroup "shouldwork"
[ clashTestGroup "AutoReg"
[ outputTest "AutoReg" def
, runTest "T1507" def{hdlSim=[]}
, let _opts = def{hdlSim=[], hdlTargets=[VHDL]}
in runTest "T1632" _opts
]
, clashTestGroup "Basic"
[ runTest "AES" def{hdlSim=[]}
, runTest "BangData" def{hdlSim=[]}
, runTest "CaseOfErr" def{hdlTargets=[VHDL],hdlSim=[]}
, runTest "Trace" def{hdlSim=[]}
, runTest "DivMod" def{hdlSim=[]}
, runTest "DivZero" def
, runTest "LambdaDrop" def{hdlSim=[]}
, runTest "IrrefError" def{hdlSim=[]}
#ifdef CLASH_MULTIPLE_HIDDEN
, runTest "MultipleHidden" def
#endif
, outputTest "NameInlining" def
, runTest "NameInstance" def{hdlSim=[]}
, outputTest "NameInstance" def
, outputTest "SetName" def{hdlTargets=[VHDL]}
, outputTest "SimulationMagic" def{hdlTargets=[VHDL]}
, runTest "PatError" def{hdlSim=[]}
, runTest "ByteSwap32" def
, runTest "CharTest" def
, runTest "ClassOps" def
, runTest "CountTrailingZeros" def
, runTest "DeepseqX" def
, runTest "LotOfStates" def
, let _opts = def { buildTargets = BuildSpecific ["nameoverlap"]
, hdlSim = []
}
in runTest "NameOverlap" _opts
, runTest "NestedPrimitives" def{hdlSim=[]}
, runTest "NestedPrimitives2" def{hdlSim=[]}
, runTest "NORX" def
, runTest "Parameters" def{hdlTargets=[VHDL]}
, runTest "PopCount" def
, runTest "RecordSumOfProducts" def{hdlSim=[]}
, runTest "Replace" def
, runTest "TestIndex" def{hdlSim=[]}
, runTest "Time" def
, runTest "Shift" def{hdlSim=[]}
, runTest "SimpleConstructor" def{hdlSim=[]}
, runTest "SomeNatVal" def{hdlTargets=[VHDL],hdlSim=[]}
, runTest "TyEqConstraints" def{
hdlSim=[]
, buildTargets=BuildSpecific ["top1"]
}
, runTest "T1012" def{hdlSim=[]}
, runTest "T1240" def{hdlSim=[]}
, let _opts = def {hdlTargets = [VHDL], hdlSim = []}
in runTest "T1297" _opts
, runTest "T1254" def{hdlTargets=[VHDL,SystemVerilog],hdlSim=[]}
, runTest "T1242" def{hdlSim=[]}
, runTest "T1292" def{hdlTargets=[VHDL]}
, let _opts = def { hdlTargets = [VHDL], hdlLoad = [], hdlSim=[] }
in runTest "T1304" _opts
, let _opts = def { hdlTargets=[VHDL]
, hdlSim=[]
, clashFlags=["-main-is", "plus"]
, buildTargets=BuildSpecific ["plus"]
}
in runTest "T1305" _opts
, let _opts = def {hdlTargets = [VHDL], hdlSim = []}
in runTest "T1316" _opts
, runTest "T1322" def{hdlTargets=[VHDL]}
, let _opts = def {hdlTargets = [VHDL], hdlSim = []}
in runTest "T1340" _opts
, let _opts = def { hdlTargets = [VHDL], hdlSim = []}
in runTest "T1354A" _opts
, let _opts = def { hdlTargets = [VHDL], hdlSim = []}
in runTest "T1354B" _opts
, runTest "T1402" def{clashFlags=["-O"]}
, runTest "T1402b" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "T1556" def
, runTest "T1591" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "TagToEnum" def{hdlSim=[]}
, runTest "TwoFunctions" def{hdlSim=[]}
, runTest "XToError" def{hdlSim=[]}
]
, clashTestGroup "BitVector"
[ runTest "Box" def
, runTest "BoxGrow" def
, runTest "CLZ" def
, runTest "RePack" def{hdlSim=[]}
, runTest "ReduceZero" def
, runTest "ReduceOne" def
, runTest "ExtendingNumZero" def
, runTest "AppendZero" def
, runTest "GenericBitPack" def{clashFlags=["-fconstraint-solver-iterations=15"]}
, runTest "UnpackUndefined" def{hdlSim=[]}
]
, clashTestGroup "BlackBox"
[ outputTest "TemplateFunction" def{hdlTargets=[VHDL]}
, outputTest "BlackBoxFunction" def{hdlTargets=[VHDL]}
, runTest "BlackBoxFunctionHO" def{hdlTargets=[VHDL]}
, outputTest "ExternalPrimitive" def{hdlTargets=[VHDL]}
, outputTest "ZeroWidth" def{hdlTargets=[VHDL]}
, outputTest "MultiResult" def{hdlTargets=[VHDL]}
, runTest "DSL" def
, runTest "MultiResult" def
, runTest "T919" def{hdlSim=[]}
, runTest "T1524" def
, runTest "T1786" def{
hdlTargets=[VHDL]
, buildTargets=BuildSpecific ["testEnableTB", "testBoolTB"]
}
, outputTest "LITrendering" def{hdlTargets=[Verilog]}
, runTest "T2117" def{
clashFlags=["-fclash-aggressive-x-optimization-blackboxes"]
, hdlTargets=[VHDL]
, buildTargets=BuildSpecific [ "testBenchUndefBV"
, "testBenchUndefTup"
, "testBenchPartialDefTup"]}
]
, clashTestGroup "BoxedFunctions"
[ runTest "DeadRecursiveBoxed" def{hdlSim=[]}
]
, clashTestGroup "Cores"
[ clashTestGroup "Xilinx"
[ let _opts = def{ hdlTargets=[VHDL, Verilog]
, hdlLoad=[Vivado]
, hdlSim=[Vivado]
-- addShortPLTB now segfaults :-(
, buildTargets=BuildSpecific [ "addBasicTB"
, "addEnableTB"
-- , "addShortPLTB"
, "subBasicTB"
, "mulBasicTB"
, "divBasicTB"
, "compareBasicTB"
, "compareEnableTB"
, "fromUBasicTB"
, "fromUEnableTB"
, "fromSBasicTB"
, "fromSEnableTB"
]
}
in runTest "Floating" _opts
, clashTestGroup "DcFifo"
[ let _opts =
def{ hdlTargets=[VHDL, Verilog]
, hdlLoad=[]
, hdlSim=[Vivado]
}
in runTest "Basic" _opts
, let _opts = def{ hdlTargets=[VHDL, Verilog]
, hdlLoad=[]
, hdlSim=[Vivado]
, buildTargets=BuildSpecific [ "testBench_17_2"
, "testBench_2_17"
, "testBench_2_2"
]
}
in runTest "Lfsr" _opts
]
, let _opts =
def{ hdlTargets=[VHDL, Verilog, SystemVerilog]
, hdlLoad=[]
, hdlSim=[]
, buildTargets = BuildSpecific []
}
in runTest "VIO" _opts
]
]
, clashTestGroup "CSignal"
[ runTest "MAC" def{hdlSim=[]}
, runTest "CBlockRamTest" def{hdlSim=[]}
]
#ifdef COSIM
, clashTestGroup "CoSim"
[ runTest "Multiply" def{hdlTargets=[Verilog]}
, runTest "Register" def{hdlTargets=[Verilog]}
]
#endif
, clashTestGroup "CustomReprs"
[ clashTestGroup "RotateC"
[ runTest "RotateC" def
, runTest "ReprCompact" def
, runTest "ReprCompactScrambled" def
, runTest "ReprLastBitConstructor" def
, let _opts = def { hdlTargets = [VHDL, Verilog] }
in runTest "ReprStrangeMasks" _opts
, runTest "ReprWide" def
, runTest "RotateCScrambled" def
]
, clashTestGroup "RotateCNested"
[ runTest "RotateCNested" def
]
, clashTestGroup "Rotate"
[ runTest "Rotate" def
]
, clashTestGroup "Deriving"
[ runTest "BitPackDerivation" def
]
, clashTestGroup "Indexed"
[ runTest "Indexed" def
]
]
, clashTestGroup "CustomReprs"
[ clashTestGroup "ZeroWidth"
[ runTest "ZeroWidth" def{hdlSim=[]}
]
, runTest "T694" def{hdlSim=[],hdlTargets=[VHDL]}
]
, clashTestGroup "DDR"
[ let _opts = def{ buildTargets = BuildSpecific [ "testBenchGA"
, "testBenchGS"
, "testBenchUA"
, "testBenchUS"
]}
in runTest "DDRin" _opts
, let _opts = def{ buildTargets = BuildSpecific [ "testBenchUA"
, "testBenchUS"
, "testBenchGA"
, "testBenchGS"
]}
in runTest "DDRout" _opts
]
, clashTestGroup "DSignal"
[ runTest "DelayedFold" def
, runTest "DelayI" def
, runTest "DelayN" def
]
, clashTestGroup "Feedback"
[ runTest "Fib" def
#ifdef CLASH_MULTIPLE_HIDDEN
, runTest "MutuallyRecursive" def
#endif
]
, clashTestGroup "Fixed"
[ runTest "Mixer" def
, runTest "SFixedTest" def
, runTest "SatWrap" def{hdlSim=[]}
, runTest "ZeroInt" def
]
, clashTestGroup "Floating"
[ runTest "FloatPack" def{hdlSim=[], clashFlags=["-fclash-float-support"]}
, runTest "FloatConstFolding" def{clashFlags=["-fclash-float-support"]}
, runTest "T1803" def{clashFlags=["-fclash-float-support"]}
]
, clashTestGroup "GADTs"
[ runTest "Constrained" def
, runTest "Head" def
, runTest "HeadM" def
, runTest "MonomorphicTopEntity" def
, runTest "Record" def
, runTest "Tail" def
, runTest "TailM" def
, runTest "TailOfTail" def
, runTest "T1310" def{hdlSim=[]}
, runTest "T1536" def{hdlSim=[]}
]
, clashTestGroup "HOPrim"
[ runTest "HOIdx" def
, runTest "HOImap" def
, runTest "Map" def
, runTest "Map2" def
, runTest "TestMap" def
, runTest "Transpose" def
, runTest "VecFun" def
]
, clashTestGroup "Issues" $
[ clashLibTest "T508" def
, let _opts = def { hdlSim = [], hdlTargets = [Verilog] }
in runTest "T1187" _opts
, clashLibTest "T1388" def{hdlTargets=[VHDL]}
, outputTest "T1171" def
, clashLibTest "T1439" def{hdlTargets=[VHDL]}
, runTest "T1477" def{hdlSim=[]}
, runTest "T1506A" def{hdlSim=[], clashFlags=["-fclash-aggressive-x-optimization-blackboxes"]}
, outputTest "T1506B" def
{ clashFlags=["-fclash-aggressive-x-optimization-blackboxes"]
, ghcFlags=["-itests/shouldwork/Issues"]
}
, runTest "T1615" def{hdlSim=[], hdlTargets=[Verilog]}
, runTest "T1663" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "T1669_DEC" def{hdlTargets=[VHDL]}
, runTest "T1715" def
, runTest "T1721" def{hdlSim=[]}
, runTest "T1606A" def{hdlSim=[]}
, runTest "T1606B" def{hdlSim=[]}
, runTest "T1742" def{hdlSim=[], buildTargets=BuildSpecific ["shell"]}
, runTest "T1756" def{hdlSim=[]}
, outputTest "T431" def{hdlTargets=[VHDL]}
, clashLibTest "T779" def{hdlTargets=[Verilog]}
, outputTest "T1881" def{hdlSim=[]}
, runTest "T1921" def{hdlTargets=[Verilog], hdlSim=[]}
, runTest "T1933" def{
hdlTargets=[VHDL]
, expectClashFail=Just (NoTestExitCode, "NOT:WARNING")
}
, outputTest "T1996" def{hdlTargets=[VHDL]}
, runTest "T2040" def{hdlTargets=[VHDL],clashFlags=["-fclash-compile-ultra"]}
-- TODO I wanted to call this T2046A since there are multiple tests
-- for T2046. However, doing so completely breaks HDL loading because
it completely ignores the BuildSpecific ...
, runTest "T2046" def
{ hdlSim=[]
, clashFlags=["-Werror"]
, buildTargets=BuildSpecific["top_bit", "top_bitvector", "top_index", "top_signed", "top_unsigned"]
}
, runTest "T2046B" def{clashFlags=["-Werror"]}
, runTest "T2046C" def{hdlSim=[],clashFlags=["-Werror"]}
, runTest "T2097" def{hdlSim=[]}
, runTest "T2154" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "T2220_toEnumOOB" def{hdlTargets=[VHDL]}
, runTest "T2272" def{hdlTargets=[VHDL], hdlSim=[]}
, outputTest "T2334" def{hdlTargets=[VHDL]}
, outputTest "T2325" def{hdlTargets=[VHDL]}
, outputTest "T2325f" def{hdlTargets=[VHDL]}
, runTest "T2342A" def{hdlSim=[]}
, runTest "T2342B" def{hdlSim=[]}
, runTest "T2360" def{hdlSim=[],clashFlags=["-fclash-force-undefined=0"]}
] <>
if compiledWith == Cabal then
-- This tests fails without environment files present, which are only
generated by Cabal . It complains it is trying to import " "
which is a member of the hidden package ' ghc ' . Passing
' -package ghc ' does n't seem to help though . TODO : Investigate .
[clashLibTest "T1568" def]
else
[]
, clashTestGroup "LoadModules"
[ runTest "T1796" def{hdlSim=[]}
]
, clashTestGroup "Naming"
[ runTest "T967a" def{hdlSim=[]}
, runTest "T967b" def{hdlSim=[]}
, runTest "T967c" def{hdlSim=[]}
, clashLibTest "T1041" def
, clashLibTest "NameHint" def{hdlTargets=[VHDL,Verilog]}
]
, clashTestGroup "Netlist"
[ clashLibTest "Identity" def
, clashLibTest "NoDeDup" def{hdlTargets=[VHDL]}
, clashLibTest "T1766" def
, clashLibTest "T1935" def
]
, clashTestGroup "Numbers"
[ runTest "BitInteger" def
#if MIN_VERSION_base(4,14,0)
, runTest "BitReverse" def
#endif
,
-- vivado segfaults
runTest "Bounds" def { hdlSim=hdlSim def \\ [Vivado] }
, runTest "DivideByZero" def
, let _opts = def { clashFlags=["-fconstraint-solver-iterations=15"] }
in runTest "ExpWithGhcCF" _opts
, let _opts = def { clashFlags=["-fconstraint-solver-iterations=15"] }
in runTest "ExpWithClashCF" _opts
, outputTest "ExpWithClashCF" def{ghcFlags=["-itests/shouldwork/Numbers"]}
, let _opts = def { hdlTargets = [VHDL], hdlSim = [] }
in runTest "HalfAsBlackboxArg" _opts
,
-- see -lang/clash-compiler/issues/2262,
Vivado 's mod misbehaves on negative dividend
runTest "IntegralTB" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "NumConstantFoldingTB_1" def{clashFlags=["-itests/shouldwork/Numbers"]}
, outputTest "NumConstantFolding_1" def
{ clashFlags=["-fconstraint-solver-iterations=15"]
, ghcFlags=["-itests/shouldwork/Numbers"]
}
, let _opts = def { clashFlags=["-itests/shouldwork/Numbers"]
, hdlLoad = hdlLoad def \\ [Verilator]
, hdlSim = hdlSim def \\ [Verilator]
}
in runTest "NumConstantFoldingTB_2" _opts
, outputTest "NumConstantFolding_2" def
{ clashFlags=["-fconstraint-solver-iterations=15"]
, ghcFlags=["-itests/shouldwork/Numbers"]
}
, runTest "Naturals" def
, runTest "NaturalToInteger" def{hdlSim=[]}
, runTest "NegativeLits" def
, runTest "Resize" def
, runTest "Resize2" def
, runTest "Resize3" def
, runTest "SatMult" def{hdlSim=[]}
, runTest "ShiftRotate" def
, runTest "ShiftRotateNegative" def{hdlTargets=[VHDL]}
, runTest "SignedProjectionTB" def
, runTest "SignedZero" def
, runTest "Signum" def
,
-- vivado segfaults
runTest "Strict" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "T1019" def{hdlSim=[]}
, runTest "T1351" def
, runTest "T2149" def
, outputTest "UndefinedConstantFolding" def{ghcFlags=["-itests/shouldwork/Numbers"]}
, runTest "UnsignedZero" def
]
, clashTestGroup "Polymorphism"
[ runTest "ExistentialBoxed" def{hdlSim=[]}
, runTest "FunctionInstances" def
, runTest "GADTExistential" def{hdlSim=[]}
, runTest "LocalPoly" def{hdlSim=[]}
]
, clashTestGroup "PrimitiveGuards"
[ runTest "WarnAlways" def{
hdlTargets=[VHDL]
, expectClashFail=Just (NoTestExitCode, "You shouldn't use 'primitive'!")
}
]
, clashTestGroup "PrimitiveReductions"
[ runTest "Lambda" def
, runTest "ReplaceInt" def
]
, clashTestGroup "RTree"
[ runTest "TZip" def{hdlSim=[]}
, runTest "TFold" def{hdlSim=[]}
, runTest "TRepeat" def
, runTest "TRepeat2" def
]
, clashTestGroup "Shadowing"
[ runTest "T990" def
]
, clashTestGroup "Signal"
[ runTest "AlwaysHigh" def{hdlSim=[]}
, runTest "BangPatterns" def
,
TODO : we do not support memory files in Vivado
--
-- see: -lang/clash-compiler/issues/2269
runTest "BlockRamFile" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "BlockRam0" def
, runTest "BlockRam1" def
, clashTestGroup "BlockRam"
[ runTest "Blob" def
]
, runTest "AndEnable" def
#ifdef CLASH_MULTIPLE_HIDDEN
,
-- TODO: Vivado is disabled because it gives different results, see
-- -lang/clash-compiler/issues/2267
runTest "AndSpecificEnable" def{hdlSim=hdlSim def \\ [Vivado]}
#endif
, runTest "Ram" def
, clashTestGroup "Ram"
[ runTest "RMultiTop" def
, let _opts = def{ buildTargets=BuildSpecific [ "testBench35"
, "testBench53"]}
in runTest "RWMultiTop" _opts
]
, runTest "ResetGen" def
,
TODO : we do not support memory files in Vivado
--
-- see: -lang/clash-compiler/issues/2269
runTest "RomFile" def{hdlSim=hdlSim def \\ [Vivado]}
, outputTest "BlockRamLazy" def
, runTest "BlockRamTest" def{hdlSim=[]}
, runTest "Compression" def
, runTest "DelayedReset" def
Vivado segfaults
hdlLoad=hdlLoad def \\ [Verilator, Vivado]
, hdlSim=hdlSim def \\ [Verilator, Vivado]
, buildTargets=BuildSpecific [ "testBenchAB"
, "testBenchBC"]
}
in runTest "DualBlockRam" _opts
, let _opts = def { buildTargets=BuildSpecific ["example"]
, hdlSim=[]
}
in runTest "NoCPR" _opts
, runTest "DynamicClocks" def
{ hdlLoad = hdlLoad def \\ [Verilator]
, hdlSim = hdlSim def \\ [Verilator]
, clashFlags = ["-fclash-timescale-precision", "1fs"]
}
, runTest "Oversample" def
, runTest "RegisterAR" def
, runTest "RegisterSR" def
, runTest "RegisterAE" def
, runTest "RegisterSE" def
, let _opts = def{ buildTargets=BuildSpecific [ "testBenchAsync"
, "testBenchSync"]}
in runTest "ResetSynchronizer" _opts
, runTest "ResetLow" def
, runTest "Rom" def
, runTest "RomNegative" def
, clashTestGroup "ROM"
[ runTest "Async" def
, runTest "AsyncBlob" def
, runTest "Blob" def
,
TODO : When issue # 2039 is fixed , it should be possible to drop
-- compile-ultra.
-- TODO: Vivado is disabled because it gives different results, see
-- -lang/clash-compiler/issues/2268
let _opts = def { clashFlags=["-fclash-compile-ultra"]
, hdlSim=hdlSim def \\ [Vivado]
}
in runTest "BlobVec" _opts
]
, runTest "SigP" def{hdlSim=[]}
, outputTest "T1102A" def{hdlTargets=[VHDL]}
, outputTest "T1102B" def{hdlTargets=[VHDL]}
, runTest "T2069" def
, clashTestGroup "BiSignal"
[ runTest "Counter" def
, runTest "CounterHalfTuple" def
, runTest "CounterHalfTupleRev" def
]
, runTest "T1007" def{hdlSim=[]}
]
, clashTestGroup "SimIO"
[ let _opts = def { hdlTargets=[Verilog]
, vvpStdoutNonEmptyFail=False
, buildTargets=BuildSpecific ["topEntity"]
, hdlLoad = [IVerilog]
, hdlSim = [IVerilog]
}
in runTest "Test00" _opts
]
, clashTestGroup "SynthesisAttributes"
[ outputTest "Simple" def
, outputTest "Product" def
, outputTest "InstDeclAnnotations" def
, runTest "Product" def
, outputTest "T1771" def
]
, clashTestGroup "Testbench"
[ runTest "TB" def{clashFlags=["-fclash-inline-limit=0"]}
, runTest "SyncTB" def
]
, clashTestGroup "Types"
[ runTest "TypeFamilyReduction" def{hdlSim=[]}
, runTest "NatExp" def{hdlSim=[]}
]
, clashTestGroup "TopEntity"
-- VHDL tests disabled for now: I can't figure out how to generate a static name whilst retaining the ability to actually test..
[ outputTest "PortGeneration" def
, outputTest "PortNamesWithSingletonVector" def{hdlTargets=[Verilog]}
, runTest "TopEntHOArg" def{buildTargets=BuildSpecific ["f"], hdlSim=[]}
, runTest "T701" def {hdlSim=[]}
, runTest "T1033" def {hdlSim=[],buildTargets=BuildSpecific ["top"]}
, outputTest "T1033" def
, outputTest "T1072" def
, outputTest "T1074" def
, outputTest "Multiple" def
{ hdlTargets = [SystemVerilog]
, clashFlags = ["-main-is", "topEntity1"]
}
, outputTest "Multiple" def
{ hdlTargets = [VHDL]
, clashFlags = ["-main-is", "topEntity3"]
}
, runTest "T1139" def{hdlSim=[]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNames_testBench"]
}
in runTest "PortNames" _opts
, outputTest "PortNames" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortProducts_testBench"]
}
in runTest "PortProducts" _opts
, outputTest "PortProducts" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortProductsSum_testBench"]
}
in runTest "PortProductsSum" _opts
, outputTest "PortProductsSum" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNamesWithUnit_testBench"]
}
in runTest "PortNamesWithUnit" _opts
, outputTest "PortNamesWithUnit" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNamesWithVector_testBench"]
}
in runTest "PortNamesWithVector" _opts
, outputTest "PortNamesWithVector" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNamesWithRTree_testBench"]
}
in runTest "PortNamesWithRTree" _opts
, outputTest "PortNamesWithRTree" def{hdlTargets=[Verilog]}
, clashLibTest "T1182A" def
, clashLibTest "T1182B" def
]
, clashTestGroup "Unit"
[ runTest "Imap" def
, runTest "ZipWithUnitVector" def
, runTest "ZipWithTupleWithUnitLeft" def
, runTest "ZipWithTupleWithUnitRight" def
, runTest "ZipWithTripleWithUnitMiddle" def
, runTest "ZipWithUnitSP" def
, runTest "ZipWithUnitSP2" def
]
, clashTestGroup "Vector"
[ runTest "EnumTypes" def{hdlSim=[]}
, runTest "HOCon" def{hdlSim=[]}
, runTest "VMapAccum" def{hdlSim=[]}
, runTest "VScan" def{hdlSim=[]}
, runTest "VZip" def{hdlSim=[]}
, runTest "VecConst" def{hdlSim=[]}
,
-- vivado segfaults
runTest "FirOddSize" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "IndexInt" def
,
Vivado segfaults
runTest "IndexInt2" def {hdlSim=hdlSim def \\ [Vivado]}
, outputTest "IndexInt2" def{hdlTargets=[Verilog]}
, runTest "Concat" def
, let _opts = def { hdlLoad = hdlLoad def \\ [Verilator]
, hdlSim = hdlSim def \\ [Verilator]
}
in runTest "DFold" _opts
, runTest "DFold2" def
, runTest "DTFold" def
,
-- vivado segfaults
runTest "FindIndex" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "Fold" def
, runTest "FoldlFuns" def{hdlSim=[]}
, runTest "Foldr" def
, runTest "FoldrEmpty" def
, runTest "HOClock" def{hdlSim=[]}
, runTest "HOPrim" def{hdlSim=[]}
, runTest "Indices" def
, runTest "Iterate" def
, outputTest "IterateCF" def{hdlTargets=[VHDL]}
, runTest "Minimum" def
, runTest "MovingAvg" def{hdlSim=[]}
, runTest "PatHOCon" def{hdlSim=[]}
, runTest "Scatter" def
, runTest "Split" def{hdlSim=[]}
, runTest "ToList" def
, runTest "Unconcat" def
, runTest "VACC" def{hdlSim=[]}
, runTest "VEmpty" def
, runTest "VIndex" def{hdlSim=[]}
, runTest "VIndicesI" def
, runTest "VFold" def{hdlSim=hdlSim def \\ [Vivado]} -- vivado segfaults
, runTest "VMerge" def
, runTest "VReplace" def
, runTest "VReverse" def
, runTest "VRotate" def
, runTest "VSelect" def
, runTest "VecOfSum" def{hdlSim=[]}
, runTest "T452" def{hdlSim=[]}
, runTest "T478" def{hdlSim=[]}
, let _opts = def {hdlSim = [], hdlTargets = [VHDL]}
in runTest "T895" _opts
, let _opts = def {hdlSim = [], hdlTargets = [VHDL]}
in runTest "T1360" _opts
] -- end vector
, clashTestGroup "Verification" [
runTest "SymbiYosys" def{
hdlTargets=[Verilog, SystemVerilog]
, buildTargets=BuildSpecific ["topEntity"]
, hdlLoad=[]
, hdlSim=[]
, verificationTool=Just SymbiYosys
}
]
, clashTestGroup "XOptimization"
[ outputTest "Conjunction" def
, outputTest "Disjunction" def
, clashLibTest "OneDefinedDataPat" def
, clashLibTest "OneDefinedLitPat" def
, clashLibTest "OneDefinedDefaultPat" def
, clashLibTest "ManyDefined" def
]
, clashTestGroup " PartialEvaluation "
[ clashLibTest " EtaExpansion " def
, clashLibTest " KnownCase " def
, clashLibTest " CaseOfCase " def
, clashLibTest " LazyEvaluation " def
, clashLibTest " MutualRecursion " def
-- ]
] -- end shouldwork
] -- end tests
] -- end .
main :: IO ()
main = do
setEnv "TASTY_NUM_THREADS" (show numCapabilities)
setClashEnvs compiledWith
runClashTest
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/222462d3f21d0851d762c355ee242e44f94f0aef/tests/Main.hs | haskell | # LANGUAGE OverloadedStrings #
Directory clash binary is expected to live in
XXX: Hardcoded
override by setting @store_dir@ to point to local cabal installation.
| See 'compiledWith'
| Detects Clash binary the testsuite should use (in order):
'clash' without extra arguments.
| `clashTestGroup` and `clashTestRoot` make sure that each test knows its
fully qualified test name at construction time. This is used to create
dependency patterns.
see: -lang/clash-compiler/issues/2265
for syntax errors.
for syntax errors.
(RecursiveBoxed\.)?topEntity
Disabled, due to it eating gigabytes of memory:
hdlTargets=[VHDL]
, expectClashFail=Just (def, "??")
}
addShortPLTB now segfaults :-(
, "addShortPLTB"
TODO I wanted to call this T2046A since there are multiple tests
for T2046. However, doing so completely breaks HDL loading because
This tests fails without environment files present, which are only
vivado segfaults
see -lang/clash-compiler/issues/2262,
vivado segfaults
see: -lang/clash-compiler/issues/2269
TODO: Vivado is disabled because it gives different results, see
-lang/clash-compiler/issues/2267
see: -lang/clash-compiler/issues/2269
compile-ultra.
TODO: Vivado is disabled because it gives different results, see
-lang/clash-compiler/issues/2268
VHDL tests disabled for now: I can't figure out how to generate a static name whilst retaining the ability to actually test..
vivado segfaults
vivado segfaults
vivado segfaults
end vector
]
end shouldwork
end tests
end . | # LANGUAGE CPP #
# LANGUAGE QuasiQuotes #
module Main (main) where
import qualified Clash.Util.Interpolate as I
import Clash.Annotations.Primitive (HDL(..))
import qualified Data.Text as Text
import Data.Default (def)
import Data.List ((\\), intercalate)
import Data.Version (versionBranch)
import System.Directory
(getCurrentDirectory, doesDirectoryExist, makeAbsolute)
import System.Environment
import System.Info
import GHC.Conc (numCapabilities)
import GHC.Stack
import GHC.IO.Unsafe (unsafePerformIO)
import Text.Printf (printf)
import Test.Tasty
import Test.Tasty.Common
import Test.Tasty.Clash
| GHC version as major.minor.patch1 . For example : 8.10.2 .
ghcVersion3 :: String
ghcVersion3 =
#ifdef __GLASGOW_HASKELL_PATCHLEVEL2__
let ghc_p1 = __GLASGOW_HASKELL_PATCHLEVEL1__
ghc_p2 = __GLASGOW_HASKELL_PATCHLEVEL2__ in
intercalate "." (map show (versionBranch compilerVersion <> [ghc_p1,ghc_p2]))
#else
let ghc_p1 = __GLASGOW_HASKELL_PATCHLEVEL1__ in
intercalate "." (map show (versionBranch compilerVersion <> [ghc_p1]))
#endif
cabalClashBinDir :: IO String
cabalClashBinDir = makeAbsolute rel_path
where
rel_path = printf templ platform ghcVersion3 (VERSION_clash_ghc :: String)
platform = case os of
"mingw32" -> arch <> "-windows"
_ -> arch <> "-" <> os
templ = "dist-newstyle/build/%s/ghc-%s/clash-ghc-%s/x/clash/build/clash/" :: String
| Set GHC_PACKAGE_PATH for local Cabal install . Currently hardcoded for Unix ;
setCabalPackagePaths :: IO ()
setCabalPackagePaths = do
ch <- lookupEnv "store_dir"
storeDir <- case ch of
Just dir -> pure dir
Nothing -> case os of
default ghcup location
_ -> (<> "/.cabal/store") <$> getEnv "HOME"
here <- getCurrentDirectory
setEnv "GHC_PACKAGE_PATH" $
storeDir <> "/ghc-" <> ghcVersion3 <> "/package.db"
<> ":"
<> here <> "/dist-newstyle/packagedb/ghc-" <> ghcVersion3
<> ":"
data RunWith
= Stack
| Cabal
| Global
deriving (Show, Eq)
* If USE_GLOBAL_CLASH=1 , use globally installed Clash
* If STACK_EXE is present , use Stack 's Clash
* If dist - newstyle is present , use Cabal 's Clash
* Use globally installed Clash
compiledWith :: RunWith
compiledWith = unsafePerformIO $ do
clash_global <- lookupEnv "USE_GLOBAL_CLASH"
stack_exe <- lookupEnv "STACK_EXE"
distNewstyleExists <- doesDirectoryExist "dist-newstyle"
pure $ case (clash_global, stack_exe, distNewstyleExists) of
(Just "1", Just _, _ ) -> error "Can't use global clash with 'stack run'"
(Just "1", _, _ ) -> Global
(_, Just _, _ ) -> Stack
(_, _ , True) -> Cabal
(_, _ , _ ) -> Global
# NOINLINE compiledWith #
| Set environment variables that allow Clash to be executed by simply calling
setClashEnvs :: HasCallStack => RunWith -> IO ()
setClashEnvs Global = setEnv "GHC_ENVIRONMENT" "-"
setClashEnvs Stack = pure ()
setClashEnvs Cabal = do
binDir <- cabalClashBinDir
path <- getEnv "PATH"
let seperator = case os of { "mingw32" -> ";"; _ -> ":" }
setEnv "PATH" (binDir <> seperator <> path)
setCabalPackagePaths
clashTestRoot
:: [[TestName] -> TestTree]
-> TestTree
clashTestRoot testTrees =
clashTestGroup "." testTrees []
clashTestGroup
:: TestName
-> [[TestName] -> TestTree]
-> ([TestName] -> TestTree)
clashTestGroup testName testTrees =
\parentNames ->
testGroup testName $
zipWith ($) testTrees (repeat (testName : parentNames))
runClashTest :: IO ()
runClashTest = defaultMain $ clashTestRoot
[ clashTestGroup "examples"
[ runTest "ALU" def{hdlSim=[]}
, let _opts = def { hdlSim=[]
, hdlTargets=[VHDL]
, buildTargets=BuildSpecific ["blinker"]
}
in runTest "Blinker" _opts
, runTest "BlockRamTest" def{hdlSim=[]}
, runTest "Calculator" def
, runTest "CHIP8" def{hdlSim=[]}
, runTest "CochleaPlus" def{hdlSim=[]}
,
Vivado segfaults
let _opts = def { clashFlags=["-fclash-component-prefix", "test"]
, buildTargets=BuildSpecific ["test_testBench"]
, hdlSim=hdlSim def \\ [Vivado]
}
in runTest "FIR" _opts
, runTest "Fifo" def{hdlSim=[]}
, runTest "MAC" def
, runTest "MatrixVect" def
, runTest "Queens" def{hdlSim=[]}
, runTest "Reducer" def{hdlSim=[]}
, runTest "Sprockell" def{hdlSim=[]}
, runTest "Windows" def{hdlSim=[]}
, clashTestGroup "crc32"
[ runTest "CRC32" def
]
, clashTestGroup "i2c"
[ let _opts = def { clashFlags=["-O2","-fclash-component-prefix","test"]
, buildTargets=BuildSpecific ["test_i2c"]
, hdlSim=[]
}
in runTest "I2C" _opts
,
TODO : this uses finish_and_return , with is Icarus Verilog only .
let _opts = def { buildTargets = BuildSpecific ["system"]
, hdlTargets = [Verilog]
, hdlLoad = [IVerilog]
, hdlSim = [IVerilog]
, vvpStdoutNonEmptyFail = False
}
in runTest "I2Ctest" _opts
]
]
, clashTestGroup "tests"
[ clashTestGroup "shouldfail"
[ clashTestGroup "BlackBox"
[ runTest "WrongReference" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
Function WrongReference.myMultiply was annotated with an inline
primitive for WrongReference.myMultiplyX. These names should be
the same. |])
}
, runTest "T1945" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Template function for returned False")
}
]
, clashTestGroup "Cores"
[ clashTestGroup "Xilinx"
[ clashTestGroup "VIO"
[ runTest "OutputBusWidthExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "Probe signals must be been between 1 and 256 bits wide.")
}
, runTest "OutputProbesExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "At most 256 input/output probes are supported.")
}
, runTest "InputBusWidthExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "Probe signals must be been between 1 and 256 bits wide.")
}
, runTest "InputProbesExceeded" def{
hdlTargets=[VHDL, Verilog, SystemVerilog]
, expectClashFail=Just (def, "At most 256 input/output probes are supported.")
}
]
]
]
, clashTestGroup "InvalidPrimitive"
[ runTest "InvalidPrimitive" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "InvalidPrimitive.primitives")
}
]
, clashTestGroup "GADTs"
[ runTest "T1311" def {
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
Can't translate data types with unconstrained existentials|])
}
]
, clashTestGroup "PrimitiveGuards"
[ runTest "DontTranslate" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
Clash was forced to translate 'DontTranslate.primitive', but this
value was marked with DontTranslate. Did you forget to include a
blackbox for one of the constructs using this?
|])
}
, runTest "HasBlackBox" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, Text.pack [I.i|
No BlackBox definition for 'HasBlackBox.primitive' even though
this value was annotated with 'HasBlackBox'.
|])
}
]
, clashTestGroup "Signal"
[ runTest "MAC" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Couldn't instantiate blackbox for Clash.Signal.Internal.register#")
}
]
, clashTestGroup "SynthesisAttributes"
[ runTest "ProductInArgs" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Cannot use attribute annotations on product types of top entities")
}
, runTest "ProductInResult" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Cannot use attribute annotations on product types of top entities")
}
]
, clashTestGroup "Testbench"
[ runTest "UnsafeOutputVerifier" def{
expectClashFail=Just ( TestSpecificExitCode 0
, "Clash.Explicit.Testbench.unsafeSimSynchronizer is not safely synthesizable!")
}
]
, clashTestGroup "TopEntity"
[ runTest "T1033" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "PortProduct \"wrong\" []")
}
, runTest "T1063" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Saw a PortProduct in a Synthesize annotation")
}
]
, clashTestGroup "Verification"
GHDL only has VERY basic PSL support
_opts = def { hdlTargets=[VHDL]
, buildTargets=BuildSpecific ["fails" <> show i | i <- [(1::Int)..n]]
, hdlLoad=[GHDL]
, hdlSim=[GHDL]
, expectSimFail=Just (def, "psl assertion failed")
}
in runTest "NonTemporalPSL" _opts
, let n = 13
_opts = def { hdlTargets=[SystemVerilog]
, buildTargets=BuildSpecific ["fails" <> show i | i <- [(1::Int)..n]]
Only QuestaSim supports simulating SVA / PSL , but does check
, hdlLoad=[ModelSim]
, hdlSim=[]
}
in runTest "NonTemporalPSL" _opts
, let is = [(1::Int)..13] \\ [4, 6, 7, 8, 10, 11, 12] in
runTest "NonTemporalSVA" def{
hdlTargets=[SystemVerilog]
, buildTargets=BuildSpecific ["fails" <> show i | i <- is]
Only QuestaSim supports simulating SVA / PSL , but does check
, hdlLoad=[ModelSim]
, hdlSim=[]
}
, runTest "SymbiYosys" def{
hdlTargets=[Verilog, SystemVerilog]
, hdlLoad=[]
, hdlSim=[]
, verificationTool=Just SymbiYosys
, expectVerificationFail=Just (def, "Unreached cover statement at B")
}
]
, clashTestGroup "ZeroWidth"
[ runTest "FailGracefully1" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Unexpected projection of zero-width type")
}
, runTest "FailGracefully2" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Unexpected projection of zero-width type")
}
, runTest "FailGracefully3" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Unexpected projection of zero-width type")
}
]
, runTest "LiftRecursiveGroup" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def,"Callgraph after normalization contains following recursive components:")
}
, runTest "Poly" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "Clash can only normalize monomorphic functions, but this is polymorphic:")
}
, runTest "Poly2" def{
hdlTargets=[VHDL]
, clashFlags=["-fclash-error-extra"]
, expectClashFail=Just (def, "Even after applying type equality constraints it remained polymorphic:")
}
, runTest "RecursiveBoxed" def{
hdlTargets=[VHDL]
}
, runTest "RecursiveDatatype" def{
hdlTargets=[VHDL]
, expectClashFail=Just (def, "This bndr has a non-representable return type and can't be normalized:")
}
, runTest " RecursivePoly " def {
]
, clashTestGroup "shouldwork"
[ clashTestGroup "AutoReg"
[ outputTest "AutoReg" def
, runTest "T1507" def{hdlSim=[]}
, let _opts = def{hdlSim=[], hdlTargets=[VHDL]}
in runTest "T1632" _opts
]
, clashTestGroup "Basic"
[ runTest "AES" def{hdlSim=[]}
, runTest "BangData" def{hdlSim=[]}
, runTest "CaseOfErr" def{hdlTargets=[VHDL],hdlSim=[]}
, runTest "Trace" def{hdlSim=[]}
, runTest "DivMod" def{hdlSim=[]}
, runTest "DivZero" def
, runTest "LambdaDrop" def{hdlSim=[]}
, runTest "IrrefError" def{hdlSim=[]}
#ifdef CLASH_MULTIPLE_HIDDEN
, runTest "MultipleHidden" def
#endif
, outputTest "NameInlining" def
, runTest "NameInstance" def{hdlSim=[]}
, outputTest "NameInstance" def
, outputTest "SetName" def{hdlTargets=[VHDL]}
, outputTest "SimulationMagic" def{hdlTargets=[VHDL]}
, runTest "PatError" def{hdlSim=[]}
, runTest "ByteSwap32" def
, runTest "CharTest" def
, runTest "ClassOps" def
, runTest "CountTrailingZeros" def
, runTest "DeepseqX" def
, runTest "LotOfStates" def
, let _opts = def { buildTargets = BuildSpecific ["nameoverlap"]
, hdlSim = []
}
in runTest "NameOverlap" _opts
, runTest "NestedPrimitives" def{hdlSim=[]}
, runTest "NestedPrimitives2" def{hdlSim=[]}
, runTest "NORX" def
, runTest "Parameters" def{hdlTargets=[VHDL]}
, runTest "PopCount" def
, runTest "RecordSumOfProducts" def{hdlSim=[]}
, runTest "Replace" def
, runTest "TestIndex" def{hdlSim=[]}
, runTest "Time" def
, runTest "Shift" def{hdlSim=[]}
, runTest "SimpleConstructor" def{hdlSim=[]}
, runTest "SomeNatVal" def{hdlTargets=[VHDL],hdlSim=[]}
, runTest "TyEqConstraints" def{
hdlSim=[]
, buildTargets=BuildSpecific ["top1"]
}
, runTest "T1012" def{hdlSim=[]}
, runTest "T1240" def{hdlSim=[]}
, let _opts = def {hdlTargets = [VHDL], hdlSim = []}
in runTest "T1297" _opts
, runTest "T1254" def{hdlTargets=[VHDL,SystemVerilog],hdlSim=[]}
, runTest "T1242" def{hdlSim=[]}
, runTest "T1292" def{hdlTargets=[VHDL]}
, let _opts = def { hdlTargets = [VHDL], hdlLoad = [], hdlSim=[] }
in runTest "T1304" _opts
, let _opts = def { hdlTargets=[VHDL]
, hdlSim=[]
, clashFlags=["-main-is", "plus"]
, buildTargets=BuildSpecific ["plus"]
}
in runTest "T1305" _opts
, let _opts = def {hdlTargets = [VHDL], hdlSim = []}
in runTest "T1316" _opts
, runTest "T1322" def{hdlTargets=[VHDL]}
, let _opts = def {hdlTargets = [VHDL], hdlSim = []}
in runTest "T1340" _opts
, let _opts = def { hdlTargets = [VHDL], hdlSim = []}
in runTest "T1354A" _opts
, let _opts = def { hdlTargets = [VHDL], hdlSim = []}
in runTest "T1354B" _opts
, runTest "T1402" def{clashFlags=["-O"]}
, runTest "T1402b" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "T1556" def
, runTest "T1591" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "TagToEnum" def{hdlSim=[]}
, runTest "TwoFunctions" def{hdlSim=[]}
, runTest "XToError" def{hdlSim=[]}
]
, clashTestGroup "BitVector"
[ runTest "Box" def
, runTest "BoxGrow" def
, runTest "CLZ" def
, runTest "RePack" def{hdlSim=[]}
, runTest "ReduceZero" def
, runTest "ReduceOne" def
, runTest "ExtendingNumZero" def
, runTest "AppendZero" def
, runTest "GenericBitPack" def{clashFlags=["-fconstraint-solver-iterations=15"]}
, runTest "UnpackUndefined" def{hdlSim=[]}
]
, clashTestGroup "BlackBox"
[ outputTest "TemplateFunction" def{hdlTargets=[VHDL]}
, outputTest "BlackBoxFunction" def{hdlTargets=[VHDL]}
, runTest "BlackBoxFunctionHO" def{hdlTargets=[VHDL]}
, outputTest "ExternalPrimitive" def{hdlTargets=[VHDL]}
, outputTest "ZeroWidth" def{hdlTargets=[VHDL]}
, outputTest "MultiResult" def{hdlTargets=[VHDL]}
, runTest "DSL" def
, runTest "MultiResult" def
, runTest "T919" def{hdlSim=[]}
, runTest "T1524" def
, runTest "T1786" def{
hdlTargets=[VHDL]
, buildTargets=BuildSpecific ["testEnableTB", "testBoolTB"]
}
, outputTest "LITrendering" def{hdlTargets=[Verilog]}
, runTest "T2117" def{
clashFlags=["-fclash-aggressive-x-optimization-blackboxes"]
, hdlTargets=[VHDL]
, buildTargets=BuildSpecific [ "testBenchUndefBV"
, "testBenchUndefTup"
, "testBenchPartialDefTup"]}
]
, clashTestGroup "BoxedFunctions"
[ runTest "DeadRecursiveBoxed" def{hdlSim=[]}
]
, clashTestGroup "Cores"
[ clashTestGroup "Xilinx"
[ let _opts = def{ hdlTargets=[VHDL, Verilog]
, hdlLoad=[Vivado]
, hdlSim=[Vivado]
, buildTargets=BuildSpecific [ "addBasicTB"
, "addEnableTB"
, "subBasicTB"
, "mulBasicTB"
, "divBasicTB"
, "compareBasicTB"
, "compareEnableTB"
, "fromUBasicTB"
, "fromUEnableTB"
, "fromSBasicTB"
, "fromSEnableTB"
]
}
in runTest "Floating" _opts
, clashTestGroup "DcFifo"
[ let _opts =
def{ hdlTargets=[VHDL, Verilog]
, hdlLoad=[]
, hdlSim=[Vivado]
}
in runTest "Basic" _opts
, let _opts = def{ hdlTargets=[VHDL, Verilog]
, hdlLoad=[]
, hdlSim=[Vivado]
, buildTargets=BuildSpecific [ "testBench_17_2"
, "testBench_2_17"
, "testBench_2_2"
]
}
in runTest "Lfsr" _opts
]
, let _opts =
def{ hdlTargets=[VHDL, Verilog, SystemVerilog]
, hdlLoad=[]
, hdlSim=[]
, buildTargets = BuildSpecific []
}
in runTest "VIO" _opts
]
]
, clashTestGroup "CSignal"
[ runTest "MAC" def{hdlSim=[]}
, runTest "CBlockRamTest" def{hdlSim=[]}
]
#ifdef COSIM
, clashTestGroup "CoSim"
[ runTest "Multiply" def{hdlTargets=[Verilog]}
, runTest "Register" def{hdlTargets=[Verilog]}
]
#endif
, clashTestGroup "CustomReprs"
[ clashTestGroup "RotateC"
[ runTest "RotateC" def
, runTest "ReprCompact" def
, runTest "ReprCompactScrambled" def
, runTest "ReprLastBitConstructor" def
, let _opts = def { hdlTargets = [VHDL, Verilog] }
in runTest "ReprStrangeMasks" _opts
, runTest "ReprWide" def
, runTest "RotateCScrambled" def
]
, clashTestGroup "RotateCNested"
[ runTest "RotateCNested" def
]
, clashTestGroup "Rotate"
[ runTest "Rotate" def
]
, clashTestGroup "Deriving"
[ runTest "BitPackDerivation" def
]
, clashTestGroup "Indexed"
[ runTest "Indexed" def
]
]
, clashTestGroup "CustomReprs"
[ clashTestGroup "ZeroWidth"
[ runTest "ZeroWidth" def{hdlSim=[]}
]
, runTest "T694" def{hdlSim=[],hdlTargets=[VHDL]}
]
, clashTestGroup "DDR"
[ let _opts = def{ buildTargets = BuildSpecific [ "testBenchGA"
, "testBenchGS"
, "testBenchUA"
, "testBenchUS"
]}
in runTest "DDRin" _opts
, let _opts = def{ buildTargets = BuildSpecific [ "testBenchUA"
, "testBenchUS"
, "testBenchGA"
, "testBenchGS"
]}
in runTest "DDRout" _opts
]
, clashTestGroup "DSignal"
[ runTest "DelayedFold" def
, runTest "DelayI" def
, runTest "DelayN" def
]
, clashTestGroup "Feedback"
[ runTest "Fib" def
#ifdef CLASH_MULTIPLE_HIDDEN
, runTest "MutuallyRecursive" def
#endif
]
, clashTestGroup "Fixed"
[ runTest "Mixer" def
, runTest "SFixedTest" def
, runTest "SatWrap" def{hdlSim=[]}
, runTest "ZeroInt" def
]
, clashTestGroup "Floating"
[ runTest "FloatPack" def{hdlSim=[], clashFlags=["-fclash-float-support"]}
, runTest "FloatConstFolding" def{clashFlags=["-fclash-float-support"]}
, runTest "T1803" def{clashFlags=["-fclash-float-support"]}
]
, clashTestGroup "GADTs"
[ runTest "Constrained" def
, runTest "Head" def
, runTest "HeadM" def
, runTest "MonomorphicTopEntity" def
, runTest "Record" def
, runTest "Tail" def
, runTest "TailM" def
, runTest "TailOfTail" def
, runTest "T1310" def{hdlSim=[]}
, runTest "T1536" def{hdlSim=[]}
]
, clashTestGroup "HOPrim"
[ runTest "HOIdx" def
, runTest "HOImap" def
, runTest "Map" def
, runTest "Map2" def
, runTest "TestMap" def
, runTest "Transpose" def
, runTest "VecFun" def
]
, clashTestGroup "Issues" $
[ clashLibTest "T508" def
, let _opts = def { hdlSim = [], hdlTargets = [Verilog] }
in runTest "T1187" _opts
, clashLibTest "T1388" def{hdlTargets=[VHDL]}
, outputTest "T1171" def
, clashLibTest "T1439" def{hdlTargets=[VHDL]}
, runTest "T1477" def{hdlSim=[]}
, runTest "T1506A" def{hdlSim=[], clashFlags=["-fclash-aggressive-x-optimization-blackboxes"]}
, outputTest "T1506B" def
{ clashFlags=["-fclash-aggressive-x-optimization-blackboxes"]
, ghcFlags=["-itests/shouldwork/Issues"]
}
, runTest "T1615" def{hdlSim=[], hdlTargets=[Verilog]}
, runTest "T1663" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "T1669_DEC" def{hdlTargets=[VHDL]}
, runTest "T1715" def
, runTest "T1721" def{hdlSim=[]}
, runTest "T1606A" def{hdlSim=[]}
, runTest "T1606B" def{hdlSim=[]}
, runTest "T1742" def{hdlSim=[], buildTargets=BuildSpecific ["shell"]}
, runTest "T1756" def{hdlSim=[]}
, outputTest "T431" def{hdlTargets=[VHDL]}
, clashLibTest "T779" def{hdlTargets=[Verilog]}
, outputTest "T1881" def{hdlSim=[]}
, runTest "T1921" def{hdlTargets=[Verilog], hdlSim=[]}
, runTest "T1933" def{
hdlTargets=[VHDL]
, expectClashFail=Just (NoTestExitCode, "NOT:WARNING")
}
, outputTest "T1996" def{hdlTargets=[VHDL]}
, runTest "T2040" def{hdlTargets=[VHDL],clashFlags=["-fclash-compile-ultra"]}
it completely ignores the BuildSpecific ...
, runTest "T2046" def
{ hdlSim=[]
, clashFlags=["-Werror"]
, buildTargets=BuildSpecific["top_bit", "top_bitvector", "top_index", "top_signed", "top_unsigned"]
}
, runTest "T2046B" def{clashFlags=["-Werror"]}
, runTest "T2046C" def{hdlSim=[],clashFlags=["-Werror"]}
, runTest "T2097" def{hdlSim=[]}
, runTest "T2154" def{hdlTargets=[VHDL], hdlSim=[]}
, runTest "T2220_toEnumOOB" def{hdlTargets=[VHDL]}
, runTest "T2272" def{hdlTargets=[VHDL], hdlSim=[]}
, outputTest "T2334" def{hdlTargets=[VHDL]}
, outputTest "T2325" def{hdlTargets=[VHDL]}
, outputTest "T2325f" def{hdlTargets=[VHDL]}
, runTest "T2342A" def{hdlSim=[]}
, runTest "T2342B" def{hdlSim=[]}
, runTest "T2360" def{hdlSim=[],clashFlags=["-fclash-force-undefined=0"]}
] <>
if compiledWith == Cabal then
generated by Cabal . It complains it is trying to import " "
which is a member of the hidden package ' ghc ' . Passing
' -package ghc ' does n't seem to help though . TODO : Investigate .
[clashLibTest "T1568" def]
else
[]
, clashTestGroup "LoadModules"
[ runTest "T1796" def{hdlSim=[]}
]
, clashTestGroup "Naming"
[ runTest "T967a" def{hdlSim=[]}
, runTest "T967b" def{hdlSim=[]}
, runTest "T967c" def{hdlSim=[]}
, clashLibTest "T1041" def
, clashLibTest "NameHint" def{hdlTargets=[VHDL,Verilog]}
]
, clashTestGroup "Netlist"
[ clashLibTest "Identity" def
, clashLibTest "NoDeDup" def{hdlTargets=[VHDL]}
, clashLibTest "T1766" def
, clashLibTest "T1935" def
]
, clashTestGroup "Numbers"
[ runTest "BitInteger" def
#if MIN_VERSION_base(4,14,0)
, runTest "BitReverse" def
#endif
,
runTest "Bounds" def { hdlSim=hdlSim def \\ [Vivado] }
, runTest "DivideByZero" def
, let _opts = def { clashFlags=["-fconstraint-solver-iterations=15"] }
in runTest "ExpWithGhcCF" _opts
, let _opts = def { clashFlags=["-fconstraint-solver-iterations=15"] }
in runTest "ExpWithClashCF" _opts
, outputTest "ExpWithClashCF" def{ghcFlags=["-itests/shouldwork/Numbers"]}
, let _opts = def { hdlTargets = [VHDL], hdlSim = [] }
in runTest "HalfAsBlackboxArg" _opts
,
Vivado 's mod misbehaves on negative dividend
runTest "IntegralTB" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "NumConstantFoldingTB_1" def{clashFlags=["-itests/shouldwork/Numbers"]}
, outputTest "NumConstantFolding_1" def
{ clashFlags=["-fconstraint-solver-iterations=15"]
, ghcFlags=["-itests/shouldwork/Numbers"]
}
, let _opts = def { clashFlags=["-itests/shouldwork/Numbers"]
, hdlLoad = hdlLoad def \\ [Verilator]
, hdlSim = hdlSim def \\ [Verilator]
}
in runTest "NumConstantFoldingTB_2" _opts
, outputTest "NumConstantFolding_2" def
{ clashFlags=["-fconstraint-solver-iterations=15"]
, ghcFlags=["-itests/shouldwork/Numbers"]
}
, runTest "Naturals" def
, runTest "NaturalToInteger" def{hdlSim=[]}
, runTest "NegativeLits" def
, runTest "Resize" def
, runTest "Resize2" def
, runTest "Resize3" def
, runTest "SatMult" def{hdlSim=[]}
, runTest "ShiftRotate" def
, runTest "ShiftRotateNegative" def{hdlTargets=[VHDL]}
, runTest "SignedProjectionTB" def
, runTest "SignedZero" def
, runTest "Signum" def
,
runTest "Strict" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "T1019" def{hdlSim=[]}
, runTest "T1351" def
, runTest "T2149" def
, outputTest "UndefinedConstantFolding" def{ghcFlags=["-itests/shouldwork/Numbers"]}
, runTest "UnsignedZero" def
]
, clashTestGroup "Polymorphism"
[ runTest "ExistentialBoxed" def{hdlSim=[]}
, runTest "FunctionInstances" def
, runTest "GADTExistential" def{hdlSim=[]}
, runTest "LocalPoly" def{hdlSim=[]}
]
, clashTestGroup "PrimitiveGuards"
[ runTest "WarnAlways" def{
hdlTargets=[VHDL]
, expectClashFail=Just (NoTestExitCode, "You shouldn't use 'primitive'!")
}
]
, clashTestGroup "PrimitiveReductions"
[ runTest "Lambda" def
, runTest "ReplaceInt" def
]
, clashTestGroup "RTree"
[ runTest "TZip" def{hdlSim=[]}
, runTest "TFold" def{hdlSim=[]}
, runTest "TRepeat" def
, runTest "TRepeat2" def
]
, clashTestGroup "Shadowing"
[ runTest "T990" def
]
, clashTestGroup "Signal"
[ runTest "AlwaysHigh" def{hdlSim=[]}
, runTest "BangPatterns" def
,
TODO : we do not support memory files in Vivado
runTest "BlockRamFile" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "BlockRam0" def
, runTest "BlockRam1" def
, clashTestGroup "BlockRam"
[ runTest "Blob" def
]
, runTest "AndEnable" def
#ifdef CLASH_MULTIPLE_HIDDEN
,
runTest "AndSpecificEnable" def{hdlSim=hdlSim def \\ [Vivado]}
#endif
, runTest "Ram" def
, clashTestGroup "Ram"
[ runTest "RMultiTop" def
, let _opts = def{ buildTargets=BuildSpecific [ "testBench35"
, "testBench53"]}
in runTest "RWMultiTop" _opts
]
, runTest "ResetGen" def
,
TODO : we do not support memory files in Vivado
runTest "RomFile" def{hdlSim=hdlSim def \\ [Vivado]}
, outputTest "BlockRamLazy" def
, runTest "BlockRamTest" def{hdlSim=[]}
, runTest "Compression" def
, runTest "DelayedReset" def
Vivado segfaults
hdlLoad=hdlLoad def \\ [Verilator, Vivado]
, hdlSim=hdlSim def \\ [Verilator, Vivado]
, buildTargets=BuildSpecific [ "testBenchAB"
, "testBenchBC"]
}
in runTest "DualBlockRam" _opts
, let _opts = def { buildTargets=BuildSpecific ["example"]
, hdlSim=[]
}
in runTest "NoCPR" _opts
, runTest "DynamicClocks" def
{ hdlLoad = hdlLoad def \\ [Verilator]
, hdlSim = hdlSim def \\ [Verilator]
, clashFlags = ["-fclash-timescale-precision", "1fs"]
}
, runTest "Oversample" def
, runTest "RegisterAR" def
, runTest "RegisterSR" def
, runTest "RegisterAE" def
, runTest "RegisterSE" def
, let _opts = def{ buildTargets=BuildSpecific [ "testBenchAsync"
, "testBenchSync"]}
in runTest "ResetSynchronizer" _opts
, runTest "ResetLow" def
, runTest "Rom" def
, runTest "RomNegative" def
, clashTestGroup "ROM"
[ runTest "Async" def
, runTest "AsyncBlob" def
, runTest "Blob" def
,
TODO : When issue # 2039 is fixed , it should be possible to drop
let _opts = def { clashFlags=["-fclash-compile-ultra"]
, hdlSim=hdlSim def \\ [Vivado]
}
in runTest "BlobVec" _opts
]
, runTest "SigP" def{hdlSim=[]}
, outputTest "T1102A" def{hdlTargets=[VHDL]}
, outputTest "T1102B" def{hdlTargets=[VHDL]}
, runTest "T2069" def
, clashTestGroup "BiSignal"
[ runTest "Counter" def
, runTest "CounterHalfTuple" def
, runTest "CounterHalfTupleRev" def
]
, runTest "T1007" def{hdlSim=[]}
]
, clashTestGroup "SimIO"
[ let _opts = def { hdlTargets=[Verilog]
, vvpStdoutNonEmptyFail=False
, buildTargets=BuildSpecific ["topEntity"]
, hdlLoad = [IVerilog]
, hdlSim = [IVerilog]
}
in runTest "Test00" _opts
]
, clashTestGroup "SynthesisAttributes"
[ outputTest "Simple" def
, outputTest "Product" def
, outputTest "InstDeclAnnotations" def
, runTest "Product" def
, outputTest "T1771" def
]
, clashTestGroup "Testbench"
[ runTest "TB" def{clashFlags=["-fclash-inline-limit=0"]}
, runTest "SyncTB" def
]
, clashTestGroup "Types"
[ runTest "TypeFamilyReduction" def{hdlSim=[]}
, runTest "NatExp" def{hdlSim=[]}
]
, clashTestGroup "TopEntity"
[ outputTest "PortGeneration" def
, outputTest "PortNamesWithSingletonVector" def{hdlTargets=[Verilog]}
, runTest "TopEntHOArg" def{buildTargets=BuildSpecific ["f"], hdlSim=[]}
, runTest "T701" def {hdlSim=[]}
, runTest "T1033" def {hdlSim=[],buildTargets=BuildSpecific ["top"]}
, outputTest "T1033" def
, outputTest "T1072" def
, outputTest "T1074" def
, outputTest "Multiple" def
{ hdlTargets = [SystemVerilog]
, clashFlags = ["-main-is", "topEntity1"]
}
, outputTest "Multiple" def
{ hdlTargets = [VHDL]
, clashFlags = ["-main-is", "topEntity3"]
}
, runTest "T1139" def{hdlSim=[]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNames_testBench"]
}
in runTest "PortNames" _opts
, outputTest "PortNames" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortProducts_testBench"]
}
in runTest "PortProducts" _opts
, outputTest "PortProducts" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortProductsSum_testBench"]
}
in runTest "PortProductsSum" _opts
, outputTest "PortProductsSum" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNamesWithUnit_testBench"]
}
in runTest "PortNamesWithUnit" _opts
, outputTest "PortNamesWithUnit" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNamesWithVector_testBench"]
}
in runTest "PortNamesWithVector" _opts
, outputTest "PortNamesWithVector" def{hdlTargets=[Verilog]}
, let _opts = def { hdlTargets=[Verilog]
, buildTargets=BuildSpecific ["PortNamesWithRTree_testBench"]
}
in runTest "PortNamesWithRTree" _opts
, outputTest "PortNamesWithRTree" def{hdlTargets=[Verilog]}
, clashLibTest "T1182A" def
, clashLibTest "T1182B" def
]
, clashTestGroup "Unit"
[ runTest "Imap" def
, runTest "ZipWithUnitVector" def
, runTest "ZipWithTupleWithUnitLeft" def
, runTest "ZipWithTupleWithUnitRight" def
, runTest "ZipWithTripleWithUnitMiddle" def
, runTest "ZipWithUnitSP" def
, runTest "ZipWithUnitSP2" def
]
, clashTestGroup "Vector"
[ runTest "EnumTypes" def{hdlSim=[]}
, runTest "HOCon" def{hdlSim=[]}
, runTest "VMapAccum" def{hdlSim=[]}
, runTest "VScan" def{hdlSim=[]}
, runTest "VZip" def{hdlSim=[]}
, runTest "VecConst" def{hdlSim=[]}
,
runTest "FirOddSize" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "IndexInt" def
,
Vivado segfaults
runTest "IndexInt2" def {hdlSim=hdlSim def \\ [Vivado]}
, outputTest "IndexInt2" def{hdlTargets=[Verilog]}
, runTest "Concat" def
, let _opts = def { hdlLoad = hdlLoad def \\ [Verilator]
, hdlSim = hdlSim def \\ [Verilator]
}
in runTest "DFold" _opts
, runTest "DFold2" def
, runTest "DTFold" def
,
runTest "FindIndex" def{hdlSim=hdlSim def \\ [Vivado]}
, runTest "Fold" def
, runTest "FoldlFuns" def{hdlSim=[]}
, runTest "Foldr" def
, runTest "FoldrEmpty" def
, runTest "HOClock" def{hdlSim=[]}
, runTest "HOPrim" def{hdlSim=[]}
, runTest "Indices" def
, runTest "Iterate" def
, outputTest "IterateCF" def{hdlTargets=[VHDL]}
, runTest "Minimum" def
, runTest "MovingAvg" def{hdlSim=[]}
, runTest "PatHOCon" def{hdlSim=[]}
, runTest "Scatter" def
, runTest "Split" def{hdlSim=[]}
, runTest "ToList" def
, runTest "Unconcat" def
, runTest "VACC" def{hdlSim=[]}
, runTest "VEmpty" def
, runTest "VIndex" def{hdlSim=[]}
, runTest "VIndicesI" def
, runTest "VMerge" def
, runTest "VReplace" def
, runTest "VReverse" def
, runTest "VRotate" def
, runTest "VSelect" def
, runTest "VecOfSum" def{hdlSim=[]}
, runTest "T452" def{hdlSim=[]}
, runTest "T478" def{hdlSim=[]}
, let _opts = def {hdlSim = [], hdlTargets = [VHDL]}
in runTest "T895" _opts
, let _opts = def {hdlSim = [], hdlTargets = [VHDL]}
in runTest "T1360" _opts
, clashTestGroup "Verification" [
runTest "SymbiYosys" def{
hdlTargets=[Verilog, SystemVerilog]
, buildTargets=BuildSpecific ["topEntity"]
, hdlLoad=[]
, hdlSim=[]
, verificationTool=Just SymbiYosys
}
]
, clashTestGroup "XOptimization"
[ outputTest "Conjunction" def
, outputTest "Disjunction" def
, clashLibTest "OneDefinedDataPat" def
, clashLibTest "OneDefinedLitPat" def
, clashLibTest "OneDefinedDefaultPat" def
, clashLibTest "ManyDefined" def
]
, clashTestGroup " PartialEvaluation "
[ clashLibTest " EtaExpansion " def
, clashLibTest " KnownCase " def
, clashLibTest " CaseOfCase " def
, clashLibTest " LazyEvaluation " def
, clashLibTest " MutualRecursion " def
main :: IO ()
main = do
setEnv "TASTY_NUM_THREADS" (show numCapabilities)
setClashEnvs compiledWith
runClashTest
|
fa9df1440c21a304c35e7cebaea1a5f6f26ece0eb6f6757c17b805cd60513c63 | joinr/spork | grid.clj | Grids come up a lot in algorithms , game development , and data structures .
;;You have some abstract notion of a set of containers, indexed by a coordinate,
;;that are fully connected to surrounding containers.
Upddate Feb 2017 - EXPERIMENTAL
(ns spork.data.grid
(:require [spork.protocols.core :refer :all]
[spork.util [vectors :as v]
[vecmath :as vmath]]))
(defn set-grid
[m k & [v]]
(if (contains? m k) m (assoc m k v)))
(defn shift [coord idx offset]
(v/set-vec coord idx (long (+ offset (v/vec-nth coord idx)))))
(defn corner-nebs
[x-idx y-idx up right down left]
[(shift up x-idx 1) ;up-right
(shift up x-idx -1) ;up-left
(shift down x-idx 1) ;down-right
(shift down x-idx -1) ;down-left
])
(defn nebs2
[coord & {:keys [x-idx y-idx omni?]
:or {x-idx 0 y-idx 1 omni? true}}]
(let [x (long (v/vec-nth coord x-idx))
y (long (v/vec-nth coord y-idx))
up (v/set-vec coord y-idx (inc y))
right (v/set-vec coord x-idx (inc x))
down (v/set-vec coord y-idx (dec y))
left (v/set-vec coord x-idx (dec x))]
(into [up right down left]
(when omni?
(corner-nebs x-idx y-idx up right down left)))))
(defn nebs [coord & {:keys [omni?] :or {omni? true}}]
(let [bound (v/dimension coord)]
(if (= bound 2)
(nebs2 coord :x-idx 0 :y-idx 1 :omni? omni?)
(let [base-nebs (nebs2 coord :x-idx 0 :y-idx 1 :omni? omni?)]
(loop [dim 2
acc base-nebs]
(if (= dim bound) acc
;;grow the next dimension by expanding our accumulated
;;dimension
(recur (unchecked-inc dim)
(into acc
(concat (map #(shift % dim 1) acc)
(map #(shift % dim -1) acc))))))))))
(defn in-bounds2d [width height & {:keys [left bottom]
:or {left 0 bottom 0}}]
(let [right (+ left width)
top (+ bottom height)]
(fn [coord]
(let [x (v/vec-nth coord 0)
y (v/vec-nth coord 1)]
(and (and (>= x left) (<= x right))
(and (>= y bottom) (<= y top)))))))
(defn neighbors
([coord] (reduce conj #{} (nebs coord)))
([f coord] (reduce conj #{} (filter f (nebs coord)))))
(defn in-bounds3d
[width height depth
& {:keys [left bottom distance] :or {left 0 bottom 0 distance 0}}]
(let [right (+ left width)
top (+ bottom height)
near (+ depth distance)]
(fn [coord]
(let [x (v/vec-nth coord 0)
y (v/vec-nth coord 1)
z (v/vec-nth coord 2)]
(and (and (>= x left) (<= x right))
(and (>= y bottom) (<= y top))
(and (>= z distance) (<= z near)))))))
;;in the grid, connectedness is implied.
;;To keep the arc storage down, we compute connectedness, and
;;retain only arcs that are explicitly blocked/dropped. This is
;;the opposite of the digraph implemention.
(deftype sparse-grid [coordinate-map source-drops sink-drops coord->neighbors dimensions]
IGrid
(grid-neighbors [g coord] (coord->neighbors coord))
(grid-assoc [g coord v]
(sparse-grid. (assoc coordinate-map coord v)
source-drops
sink-drops
coord->neighbors dimensions))
(grid-dissoc [g coord]
(sparse-grid. (dissoc coordinate-map coord)
source-drops
sink-drops
coord->neighbors dimensions))
(grid-coords [g] coordinate-map)
(grid-dimensions [g] dimensions)
ITopograph
(-get-nodes [tg] coordinate-map)
(-set-nodes [tg m]
(sparse-grid. m source-drops sink-drops coord->neighbors dimensions))
(-conj-node [tg k v] (grid-assoc tg k v))
(-disj-node [tg k] (grid-dissoc tg k))
(-has-node? [tg k] (contains? coordinate-map k))
(-conj-arc [tg source sink w]
(-> coordinate-map
(set-grid source)
(set-grid sink)
(sparse-grid. (disj source-drops source)
(disj sink-drops sink) coord->neighbors dimensions)))
(-disj-arc [tg source sink]
(sparse-grid. coordinate-map
(conj source-drops source)
(conj sink-drops sink)
coord->neighbors dimensions))
(-has-arc? [tg source sink]
(and (not (and (contains? source-drops source)
(contains? sink-drops sink)))
(contains? (coord->neighbors source) sink)))
(-get-arc [tg source sink]
(when (-has-arc? tg source sink) [source sink 1]))
(-arc-weight [tg source sink] (when (-has-arc? tg source sink) 1))
(-get-sources [tg k]
(->> (coord->neighbors k)
(filter (fn [v] (not (contains? source-drops v))))))
(-get-sinks [tg k]
(->> (coord->neighbors k)
(filter (fn [v] (not (contains? sink-drops v))))))
(-sink-map [tg k] (throw (Exception. "Operation -sink-map not supported for sparse grids.")))
(-source-map [tg k] (throw (Exception. "Operation -source-map not supported for sparse grids."))))
(defn ->grid2d [width height]
(sparse-grid. {} #{} #{}
(partial neighbors (in-bounds2d width height)) 2))
(defn ->grid3d [width height depth]
(sparse-grid. {} #{} #{}
(partial neighbors (in-bounds3d width height depth)) 3))
;;Note -> we could probably put in handy constructors for torroidal grids, since
;;it's only a modification of the coord->neighbors input functions.
;;testing
(comment
(def the-grid (->grid2d 10 10))
)
| null | https://raw.githubusercontent.com/joinr/spork/bb80eddadf90bf92745bf5315217e25a99fbf9d6/src/spork/data/grid.clj | clojure | You have some abstract notion of a set of containers, indexed by a coordinate,
that are fully connected to surrounding containers.
up-right
up-left
down-right
down-left
grow the next dimension by expanding our accumulated
dimension
in the grid, connectedness is implied.
To keep the arc storage down, we compute connectedness, and
retain only arcs that are explicitly blocked/dropped. This is
the opposite of the digraph implemention.
Note -> we could probably put in handy constructors for torroidal grids, since
it's only a modification of the coord->neighbors input functions.
testing | Grids come up a lot in algorithms , game development , and data structures .
Upddate Feb 2017 - EXPERIMENTAL
(ns spork.data.grid
(:require [spork.protocols.core :refer :all]
[spork.util [vectors :as v]
[vecmath :as vmath]]))
(defn set-grid
[m k & [v]]
(if (contains? m k) m (assoc m k v)))
(defn shift [coord idx offset]
(v/set-vec coord idx (long (+ offset (v/vec-nth coord idx)))))
(defn corner-nebs
[x-idx y-idx up right down left]
])
(defn nebs2
[coord & {:keys [x-idx y-idx omni?]
:or {x-idx 0 y-idx 1 omni? true}}]
(let [x (long (v/vec-nth coord x-idx))
y (long (v/vec-nth coord y-idx))
up (v/set-vec coord y-idx (inc y))
right (v/set-vec coord x-idx (inc x))
down (v/set-vec coord y-idx (dec y))
left (v/set-vec coord x-idx (dec x))]
(into [up right down left]
(when omni?
(corner-nebs x-idx y-idx up right down left)))))
(defn nebs [coord & {:keys [omni?] :or {omni? true}}]
(let [bound (v/dimension coord)]
(if (= bound 2)
(nebs2 coord :x-idx 0 :y-idx 1 :omni? omni?)
(let [base-nebs (nebs2 coord :x-idx 0 :y-idx 1 :omni? omni?)]
(loop [dim 2
acc base-nebs]
(if (= dim bound) acc
(recur (unchecked-inc dim)
(into acc
(concat (map #(shift % dim 1) acc)
(map #(shift % dim -1) acc))))))))))
(defn in-bounds2d [width height & {:keys [left bottom]
:or {left 0 bottom 0}}]
(let [right (+ left width)
top (+ bottom height)]
(fn [coord]
(let [x (v/vec-nth coord 0)
y (v/vec-nth coord 1)]
(and (and (>= x left) (<= x right))
(and (>= y bottom) (<= y top)))))))
(defn neighbors
([coord] (reduce conj #{} (nebs coord)))
([f coord] (reduce conj #{} (filter f (nebs coord)))))
(defn in-bounds3d
[width height depth
& {:keys [left bottom distance] :or {left 0 bottom 0 distance 0}}]
(let [right (+ left width)
top (+ bottom height)
near (+ depth distance)]
(fn [coord]
(let [x (v/vec-nth coord 0)
y (v/vec-nth coord 1)
z (v/vec-nth coord 2)]
(and (and (>= x left) (<= x right))
(and (>= y bottom) (<= y top))
(and (>= z distance) (<= z near)))))))
(deftype sparse-grid [coordinate-map source-drops sink-drops coord->neighbors dimensions]
IGrid
(grid-neighbors [g coord] (coord->neighbors coord))
(grid-assoc [g coord v]
(sparse-grid. (assoc coordinate-map coord v)
source-drops
sink-drops
coord->neighbors dimensions))
(grid-dissoc [g coord]
(sparse-grid. (dissoc coordinate-map coord)
source-drops
sink-drops
coord->neighbors dimensions))
(grid-coords [g] coordinate-map)
(grid-dimensions [g] dimensions)
ITopograph
(-get-nodes [tg] coordinate-map)
(-set-nodes [tg m]
(sparse-grid. m source-drops sink-drops coord->neighbors dimensions))
(-conj-node [tg k v] (grid-assoc tg k v))
(-disj-node [tg k] (grid-dissoc tg k))
(-has-node? [tg k] (contains? coordinate-map k))
(-conj-arc [tg source sink w]
(-> coordinate-map
(set-grid source)
(set-grid sink)
(sparse-grid. (disj source-drops source)
(disj sink-drops sink) coord->neighbors dimensions)))
(-disj-arc [tg source sink]
(sparse-grid. coordinate-map
(conj source-drops source)
(conj sink-drops sink)
coord->neighbors dimensions))
(-has-arc? [tg source sink]
(and (not (and (contains? source-drops source)
(contains? sink-drops sink)))
(contains? (coord->neighbors source) sink)))
(-get-arc [tg source sink]
(when (-has-arc? tg source sink) [source sink 1]))
(-arc-weight [tg source sink] (when (-has-arc? tg source sink) 1))
(-get-sources [tg k]
(->> (coord->neighbors k)
(filter (fn [v] (not (contains? source-drops v))))))
(-get-sinks [tg k]
(->> (coord->neighbors k)
(filter (fn [v] (not (contains? sink-drops v))))))
(-sink-map [tg k] (throw (Exception. "Operation -sink-map not supported for sparse grids.")))
(-source-map [tg k] (throw (Exception. "Operation -source-map not supported for sparse grids."))))
(defn ->grid2d [width height]
(sparse-grid. {} #{} #{}
(partial neighbors (in-bounds2d width height)) 2))
(defn ->grid3d [width height depth]
(sparse-grid. {} #{} #{}
(partial neighbors (in-bounds3d width height depth)) 3))
(comment
(def the-grid (->grid2d 10 10))
)
|
38d727046c31e1d658bd8fcbe2016e5d730bcfa60e94cc1a2d47a6b1e962aed4 | Haskell-Things/ImplicitCAD | extopenscad.hs | {- ORMOLU_DISABLE -}
Implicit CAD . Copyright ( C ) 2011 , ( )
Copyright ( C ) 2014 2015 , ( )
Copyright ( C ) 2014 2016 , ( )
-- Released under the GNU GPL, see LICENSE
An interpreter to run extended OpenScad code . outputs STL , OBJ , SVG , SCAD , PNG , DXF , or GCODE .
-- Allow us to use string literals for Text
{-# LANGUAGE OverloadedStrings #-}
-- Let's be explicit about what we're getting from where :)
import Prelude (Maybe(Just, Nothing), IO, Bool(True, False), FilePath, String, (<>), ($), readFile, fst, putStrLn, show, (>>=), return, unlines, filter, not, null, (||), (&&), (.), print)
-- Our Extended OpenScad interpreter
import Graphics.Implicit (union, runOpenscad)
import Graphics.Implicit.Definitions (ℝ)
-- Use default values when a Maybe is Nothing.
import Data.Maybe (fromMaybe, maybe)
Functions and types for dealing with the types used by runOpenscad .
-- The definition of the symbol type, so we can access variables, and see the requested resolution.
import Graphics.Implicit.ExtOpenScad.Definitions (Message(Message), MessageType(TextOut), ScadOpts(ScadOpts))
import Control.Applicative ((<$>), (<*>), many)
import Options.Applicative (fullDesc, header, auto, info, helper, help, str, argument, long, short, option, metavar, execParser, Parser, optional, strOption, switch, footer)
-- For handling input/output files.
import System.FilePath (splitExtension)
-- For handling handles to output files.
import System.IO (Handle, hPutStr, stdout, stderr, openFile, IOMode(WriteMode))
import Data.Text.Lazy (Text, unpack)
import Graphics.Implicit.Primitives (Object(getBox))
import Graphics.Implicit.Export (export2, export3)
import Graphics.Implicit.Export.OutputFormat (OutputFormat, guessOutputFormat, formatExtension, def2D, def3D)
import Graphics.Implicit.Export.Resolution (estimateResolution)
-- | Our command line options.
data ExtOpenScadOpts = ExtOpenScadOpts
{ outputFile :: Maybe FilePath
, outputFormat :: Maybe OutputFormat
, resolution :: Maybe ℝ
, messageOutputFile :: Maybe FilePath
, quiet :: Bool
, openScadCompatibility :: Bool
, openScadEcho :: Bool
, rawEcho :: Bool
, noImport :: Bool
, rawDefines :: [String]
, inputFile :: FilePath
}
-- | The parser for our command line arguments.
extOpenScadOpts :: Parser ExtOpenScadOpts
extOpenScadOpts = ExtOpenScadOpts
<$> optional (
strOption
( short 'o'
<> long "output"
<> metavar "OUTFILE"
<> help "Output file name"
)
)
<*> optional (
option auto
( short 'f'
<> long "format"
<> metavar "FORMAT"
<> help "Output format"
)
)
<*> optional (
option auto
( short 'r'
<> long "resolution"
<> metavar "RES"
<> help "Mesh granularity (smaller values generate more precise renderings of objects)"
)
)
<*> optional (
strOption
( short 'e'
<> long "echo-output"
<> metavar "ECHOOUTFILE"
<> help "Output file name for text generated by the extended OpenSCAD code"
)
)
<*> switch
( short 'q'
<> long "quiet"
<> help "Supress normal program output, only outputting messages resulting from the parsing or execution of extended OpenSCAD code"
)
<*> switch
( short 'O'
<> long "fopenscad-compat"
<> help "Favour compatibility with OpenSCAD semantics, where they are incompatible with ExtOpenScad semantics"
)
<*> switch
( long "fopenscad-echo"
<> help "Use OpenSCAD's style when displaying text output from the extended OpenSCAD code"
)
<*> switch
( long "fraw-echo"
<> help "Do not use any prefix when displaying text output from the extended OpenSCAD code"
)
<*> switch
( long "fno-import"
<> help "Do not honor \"use\" and \"include\" statements, and instead generate a warning"
)
<*> many (
strOption
( short 'D'
<> help "define variable KEY equal to variable VALUE when running extended OpenSCAD code"
)
)
<*> argument str
( metavar "FILE"
<> help "Input extended OpenSCAD file"
)
| Determine where to direct the text output of running the extopenscad program .
messageOutputHandle :: ExtOpenScadOpts -> IO Handle
messageOutputHandle args = maybe (return stdout) (`openFile` WriteMode) (messageOutputFile args)
textOutOpenScad :: Message -> Text
textOutOpenScad (Message _ _ msg) = "ECHO: " <> msg
textOutBare :: Message -> Text
textOutBare (Message _ _ msg) = msg
isTextOut :: Message -> Bool
isTextOut (Message TextOut _ _ ) = True
isTextOut _ = False
objectMessage :: String -> String -> String -> String -> String -> String
objectMessage dimensions infile outfile res box =
"Rendering " <> dimensions <> " object from " <> infile <> " to " <> outfile <> " with resolution " <> res <> " in box " <> box
using the openscad compat group turns on openscad compatibility options . using related extopenscad options turns them off .
-- FIXME: allow processArgs to generate messages.
processArgs :: ExtOpenScadOpts -> ExtOpenScadOpts
processArgs (ExtOpenScadOpts o f r e q compat echo rawecho noimport defines file) =
ExtOpenScadOpts o f r e q compat echo_flag rawecho noimport defines file
where
echo_flag = (compat || echo) && not rawecho
| decide what options to send the scad engine based on the post - processed arguments passed to extopenscad .
generateScadOpts :: ExtOpenScadOpts -> ScadOpts
generateScadOpts args = ScadOpts (openScadCompatibility args) (not $ noImport args)
-- | Interpret arguments, and render the object defined in the supplied input file.
run :: ExtOpenScadOpts -> IO ()
run rawargs = do
let args = processArgs rawargs
hMessageOutput <- messageOutputHandle args
if quiet args
then return ()
else putStrLn "Loading File."
content <- readFile (inputFile args)
let format =
case () of
_ | Just fmt <- outputFormat args -> Just fmt
_ | Just file <- outputFile args -> Just $ guessOutputFormat file
_ -> Nothing
scadOpts = generateScadOpts args
openscadProgram = runOpenscad scadOpts (rawDefines args) content
if quiet args
then return ()
else putStrLn "Processing File."
s@(_, obj2s, obj3s, messages) <- openscadProgram
let res = fromMaybe (estimateResolution s) (resolution args)
basename = fst (splitExtension $ inputFile args)
If we do n't know the format -- it will be 2D/3D default ( stl )
posDefExt = fromMaybe "stl" (formatExtension <$> format)
case (obj2s, obj3s) of
([], obj:objs) -> do
let output = fromMaybe
(basename <> "." <> posDefExt)
(outputFile args)
target = if null objs
then obj
else union (obj:objs)
if quiet args
then return ()
else putStrLn $ objectMessage "3D" (inputFile args) output (show res) $ show $ getBox target
-- FIXME: construct and use a warning for this.
if null objs
then return ()
else
hPutStr stderr "WARNING: Multiple objects detected. Adding a Union around them.\n"
if quiet args
then return ()
else print target
export3 (fromMaybe def3D format) res output target
(obj:objs, []) -> do
let output = fromMaybe
(basename <> "." <> posDefExt)
(outputFile args)
target = if null objs
then obj
else union (obj:objs)
if quiet args
then return ()
else putStrLn $ objectMessage "2D" (inputFile args) output (show res) $ show $ getBox target
-- FIXME: construct and use a warning for this.
if null objs
then return ()
else
hPutStr stderr "WARNING: Multiple objects detected. Adding a Union around them.\n"
if quiet args
then return ()
else print target
export2 (fromMaybe def2D format) res output target
([], []) ->
if quiet args
then return ()
else putStrLn "No objects to render."
_ -> hPutStr stderr "ERROR: File contains a mixture of 2D and 3D objects, what do you want to render?\n"
-- Always display our warnings, errors, and other non-textout messages on stderr.
hPutStr stderr $ unlines $ show <$> filter (not . isTextOut) messages
let textOutHandler =
case () of
_ | openScadEcho args -> unpack . textOutOpenScad
_ | rawEcho args -> unpack . textOutBare
_ -> show
hPutStr hMessageOutput $ unlines $ textOutHandler <$> filter isTextOut messages
| The entry point . Use the option parser then run the extended OpenScad code .
main :: IO ()
main = execParser opts >>= run
where
opts= info (helper <*> extOpenScadOpts)
( fullDesc
<> header "ImplicitCAD: extopenscad - Extended OpenSCAD interpreter."
<> footer "License: The GNU AGPL version 3 or later <> This program is Free Software; you are free to view, change and redistribute it. There is NO WARRANTY, to the extent permitted by law."
)
| null | https://raw.githubusercontent.com/Haskell-Things/ImplicitCAD/f01a6a49b7f43546185f6ce865fd117b4bf1c897/programs/extopenscad.hs | haskell | ORMOLU_DISABLE
Released under the GNU GPL, see LICENSE
Allow us to use string literals for Text
# LANGUAGE OverloadedStrings #
Let's be explicit about what we're getting from where :)
Our Extended OpenScad interpreter
Use default values when a Maybe is Nothing.
The definition of the symbol type, so we can access variables, and see the requested resolution.
For handling input/output files.
For handling handles to output files.
| Our command line options.
| The parser for our command line arguments.
FIXME: allow processArgs to generate messages.
| Interpret arguments, and render the object defined in the supplied input file.
it will be 2D/3D default ( stl )
FIXME: construct and use a warning for this.
FIXME: construct and use a warning for this.
Always display our warnings, errors, and other non-textout messages on stderr. | Implicit CAD . Copyright ( C ) 2011 , ( )
Copyright ( C ) 2014 2015 , ( )
Copyright ( C ) 2014 2016 , ( )
An interpreter to run extended OpenScad code . outputs STL , OBJ , SVG , SCAD , PNG , DXF , or GCODE .
import Prelude (Maybe(Just, Nothing), IO, Bool(True, False), FilePath, String, (<>), ($), readFile, fst, putStrLn, show, (>>=), return, unlines, filter, not, null, (||), (&&), (.), print)
import Graphics.Implicit (union, runOpenscad)
import Graphics.Implicit.Definitions (ℝ)
import Data.Maybe (fromMaybe, maybe)
Functions and types for dealing with the types used by runOpenscad .
import Graphics.Implicit.ExtOpenScad.Definitions (Message(Message), MessageType(TextOut), ScadOpts(ScadOpts))
import Control.Applicative ((<$>), (<*>), many)
import Options.Applicative (fullDesc, header, auto, info, helper, help, str, argument, long, short, option, metavar, execParser, Parser, optional, strOption, switch, footer)
import System.FilePath (splitExtension)
import System.IO (Handle, hPutStr, stdout, stderr, openFile, IOMode(WriteMode))
import Data.Text.Lazy (Text, unpack)
import Graphics.Implicit.Primitives (Object(getBox))
import Graphics.Implicit.Export (export2, export3)
import Graphics.Implicit.Export.OutputFormat (OutputFormat, guessOutputFormat, formatExtension, def2D, def3D)
import Graphics.Implicit.Export.Resolution (estimateResolution)
data ExtOpenScadOpts = ExtOpenScadOpts
{ outputFile :: Maybe FilePath
, outputFormat :: Maybe OutputFormat
, resolution :: Maybe ℝ
, messageOutputFile :: Maybe FilePath
, quiet :: Bool
, openScadCompatibility :: Bool
, openScadEcho :: Bool
, rawEcho :: Bool
, noImport :: Bool
, rawDefines :: [String]
, inputFile :: FilePath
}
extOpenScadOpts :: Parser ExtOpenScadOpts
extOpenScadOpts = ExtOpenScadOpts
<$> optional (
strOption
( short 'o'
<> long "output"
<> metavar "OUTFILE"
<> help "Output file name"
)
)
<*> optional (
option auto
( short 'f'
<> long "format"
<> metavar "FORMAT"
<> help "Output format"
)
)
<*> optional (
option auto
( short 'r'
<> long "resolution"
<> metavar "RES"
<> help "Mesh granularity (smaller values generate more precise renderings of objects)"
)
)
<*> optional (
strOption
( short 'e'
<> long "echo-output"
<> metavar "ECHOOUTFILE"
<> help "Output file name for text generated by the extended OpenSCAD code"
)
)
<*> switch
( short 'q'
<> long "quiet"
<> help "Supress normal program output, only outputting messages resulting from the parsing or execution of extended OpenSCAD code"
)
<*> switch
( short 'O'
<> long "fopenscad-compat"
<> help "Favour compatibility with OpenSCAD semantics, where they are incompatible with ExtOpenScad semantics"
)
<*> switch
( long "fopenscad-echo"
<> help "Use OpenSCAD's style when displaying text output from the extended OpenSCAD code"
)
<*> switch
( long "fraw-echo"
<> help "Do not use any prefix when displaying text output from the extended OpenSCAD code"
)
<*> switch
( long "fno-import"
<> help "Do not honor \"use\" and \"include\" statements, and instead generate a warning"
)
<*> many (
strOption
( short 'D'
<> help "define variable KEY equal to variable VALUE when running extended OpenSCAD code"
)
)
<*> argument str
( metavar "FILE"
<> help "Input extended OpenSCAD file"
)
| Determine where to direct the text output of running the extopenscad program .
messageOutputHandle :: ExtOpenScadOpts -> IO Handle
messageOutputHandle args = maybe (return stdout) (`openFile` WriteMode) (messageOutputFile args)
textOutOpenScad :: Message -> Text
textOutOpenScad (Message _ _ msg) = "ECHO: " <> msg
textOutBare :: Message -> Text
textOutBare (Message _ _ msg) = msg
isTextOut :: Message -> Bool
isTextOut (Message TextOut _ _ ) = True
isTextOut _ = False
objectMessage :: String -> String -> String -> String -> String -> String
objectMessage dimensions infile outfile res box =
"Rendering " <> dimensions <> " object from " <> infile <> " to " <> outfile <> " with resolution " <> res <> " in box " <> box
using the openscad compat group turns on openscad compatibility options . using related extopenscad options turns them off .
processArgs :: ExtOpenScadOpts -> ExtOpenScadOpts
processArgs (ExtOpenScadOpts o f r e q compat echo rawecho noimport defines file) =
ExtOpenScadOpts o f r e q compat echo_flag rawecho noimport defines file
where
echo_flag = (compat || echo) && not rawecho
| decide what options to send the scad engine based on the post - processed arguments passed to extopenscad .
generateScadOpts :: ExtOpenScadOpts -> ScadOpts
generateScadOpts args = ScadOpts (openScadCompatibility args) (not $ noImport args)
run :: ExtOpenScadOpts -> IO ()
run rawargs = do
let args = processArgs rawargs
hMessageOutput <- messageOutputHandle args
if quiet args
then return ()
else putStrLn "Loading File."
content <- readFile (inputFile args)
let format =
case () of
_ | Just fmt <- outputFormat args -> Just fmt
_ | Just file <- outputFile args -> Just $ guessOutputFormat file
_ -> Nothing
scadOpts = generateScadOpts args
openscadProgram = runOpenscad scadOpts (rawDefines args) content
if quiet args
then return ()
else putStrLn "Processing File."
s@(_, obj2s, obj3s, messages) <- openscadProgram
let res = fromMaybe (estimateResolution s) (resolution args)
basename = fst (splitExtension $ inputFile args)
posDefExt = fromMaybe "stl" (formatExtension <$> format)
case (obj2s, obj3s) of
([], obj:objs) -> do
let output = fromMaybe
(basename <> "." <> posDefExt)
(outputFile args)
target = if null objs
then obj
else union (obj:objs)
if quiet args
then return ()
else putStrLn $ objectMessage "3D" (inputFile args) output (show res) $ show $ getBox target
if null objs
then return ()
else
hPutStr stderr "WARNING: Multiple objects detected. Adding a Union around them.\n"
if quiet args
then return ()
else print target
export3 (fromMaybe def3D format) res output target
(obj:objs, []) -> do
let output = fromMaybe
(basename <> "." <> posDefExt)
(outputFile args)
target = if null objs
then obj
else union (obj:objs)
if quiet args
then return ()
else putStrLn $ objectMessage "2D" (inputFile args) output (show res) $ show $ getBox target
if null objs
then return ()
else
hPutStr stderr "WARNING: Multiple objects detected. Adding a Union around them.\n"
if quiet args
then return ()
else print target
export2 (fromMaybe def2D format) res output target
([], []) ->
if quiet args
then return ()
else putStrLn "No objects to render."
_ -> hPutStr stderr "ERROR: File contains a mixture of 2D and 3D objects, what do you want to render?\n"
hPutStr stderr $ unlines $ show <$> filter (not . isTextOut) messages
let textOutHandler =
case () of
_ | openScadEcho args -> unpack . textOutOpenScad
_ | rawEcho args -> unpack . textOutBare
_ -> show
hPutStr hMessageOutput $ unlines $ textOutHandler <$> filter isTextOut messages
| The entry point . Use the option parser then run the extended OpenScad code .
main :: IO ()
main = execParser opts >>= run
where
opts= info (helper <*> extOpenScadOpts)
( fullDesc
<> header "ImplicitCAD: extopenscad - Extended OpenSCAD interpreter."
<> footer "License: The GNU AGPL version 3 or later <> This program is Free Software; you are free to view, change and redistribute it. There is NO WARRANTY, to the extent permitted by law."
)
|
e0f29ea02c954851a707837cb9d9ab3718c1b87742aa6bb1cbbf7bba16c9dcec | me-box/core-network | dns_service.ml | open Lwt.Infix
let dns = Logs.Src.create "dns" ~doc:"Dns service"
module Log = (val Logs_lwt.src_log dns : Logs_lwt.LOG)
let pp_ip = Ipaddr.V4.pp_hum
let is_dns_query = let open Frame in function
| Ipv4 { payload = Udp { dst = 53; _ }; _ }
| Ipv4 { payload = Tcp { dst = 53; _ }; _ } -> true
| _ -> false
let is_dns_response = let open Frame in function
| Ipv4 { payload = Udp { src = 53; _ }; _ }
| Ipv4 { payload = Tcp { src = 53; _ }; _ } -> true
| _ -> false
let query_of_pkt = let open Frame in function
| Ipv4 { payload = Udp { dst = 53; payload = Payload buf}}
| Ipv4 { payload = Tcp { dst = 53; payload = Payload buf}} ->
let open Dns.Packet in
Lwt.catch (fun () -> Lwt.return @@ parse buf) (fun e ->
Log.err (fun m -> m "dns packet parse err!")
>>= fun () -> Lwt.fail e)
| _ -> Lwt.fail (Invalid_argument "Not dns query")
let try_resolve n () =
Lwt.catch
(fun () ->
let open Lwt_unix in
(*using system resolver*)
gethostbyname n >>= fun {h_addr_list; _} ->
Array.to_list h_addr_list
|> List.map (fun addr ->
Unix.string_of_inet_addr addr
|> Ipaddr.V4.of_string_exn)
|> fun ips -> Lwt.return @@ `Resolved (n , List.hd ips))
(function
| Not_found -> Lwt.return @@ `Later n
| e -> Lwt.fail e)
let ip_of_name n =
let lim = 60 in
let rec keep_trying n cnt =
if cnt > lim then Lwt.fail @@ Invalid_argument n else
try_resolve n () >>= function
| `Later n ->
Log.debug (fun m -> m "resolve %s later..." n) >>= fun () ->
Lwt_unix.sleep 1. >>= fun () ->
keep_trying n (succ cnt)
| `Resolved (n, ip) ->
Log.info (fun m -> m "resolved: %s %a" n pp_ip ip) >>= fun () ->
Lwt.return ip in
Log.info (fun m -> m "try to resolve %s..." n) >>= fun () ->
keep_trying n 1
let to_dns_response pkt resp =
let open Frame in
match pkt with
| Ipv4 {src = dst; dst = src; payload = Udp {src = dst_port; dst = src_port; _}; _}
| Ipv4 {src = dst; dst = src; payload = Tcp {src = dst_port; dst = src_port; _}; _} ->
let payload_len = Udp_wire.sizeof_udp + Cstruct.len resp in
let ip_hd = Ipv4_packet.{options = Cstruct.create 0; src; dst; ttl = 38; proto = Marshal.protocol_to_int `UDP} in
let ip_hd_wire = Cstruct.create Ipv4_wire.sizeof_ipv4 in
(match Ipv4_packet.Marshal.into_cstruct ~payload_len ip_hd ip_hd_wire with
| Error e -> raise @@ Failure "to_response_pkt -> into_cstruct"
| Ok () ->
Ipv4_wire.set_ipv4_id ip_hd_wire (Random.int 65535);
Ipv4_wire.set_ipv4_csum ip_hd_wire 0;
let cs = Tcpip_checksum.ones_complement ip_hd_wire in
Ipv4_wire.set_ipv4_csum ip_hd_wire cs;
let ph = Ipv4_packet.Marshal.pseudoheader ~src ~dst ~proto:`UDP payload_len in
let udp_hd = Udp_packet.{src_port; dst_port} in
let udp_hd_wire = Udp_packet.Marshal.make_cstruct ~pseudoheader:ph ~payload:resp udp_hd in
let buf_resp = Cstruct.concat [ip_hd_wire; udp_hd_wire; resp] in
let pkt_resp =
match Frame.parse_ipv4_pkt buf_resp with
| Ok fr -> fr
| Error (`Msg msg) ->
Log.err (fun m -> m "dispatch -> parse_eth_payload: %s" msg) |> Lwt.ignore_result;
assert false
in
buf_resp, pkt_resp)
| _ -> assert false
let process_dns_query ~resolve pkt =
let open Dns in
query_of_pkt pkt >>= fun query ->
begin
let names = Packet.(List.map (fun {q_name; _} -> q_name) query.questions) in
let name = List.hd names |> Name.to_string in
resolve name >>= function
| Ok (src_ip, resolved) ->
Log.debug (fun m -> m "Dns_service: allowed %a to resolve %s" pp_ip src_ip name) >>= fun () ->
let name = Dns.Name.of_string name in
let rrs = Dns.Packet.[{ name; cls = RR_IN; flush = false; ttl = 0l; rdata = A resolved }] in
Lwt.return Dns.Query.({ rcode = NoError; aa = true; answer = rrs; authority = []; additional = []})
| Error src_ip ->
Log.info (fun m -> m "Dns_service: banned %a to resolve %s" pp_ip src_ip name) >>= fun () ->
Lwt.return Query.({rcode = Packet.NXDomain; aa = true; answer = []; authority = []; additional = []})
end >>= fun answer ->
let resp = Query.response_of_answer query answer in
Lwt.return @@ Packet.marshal resp
| null | https://raw.githubusercontent.com/me-box/core-network/3dca69bc7610ab51f93ea49dcc3d8e43842cd2ae/lib/dns_service.ml | ocaml | using system resolver | open Lwt.Infix
let dns = Logs.Src.create "dns" ~doc:"Dns service"
module Log = (val Logs_lwt.src_log dns : Logs_lwt.LOG)
let pp_ip = Ipaddr.V4.pp_hum
let is_dns_query = let open Frame in function
| Ipv4 { payload = Udp { dst = 53; _ }; _ }
| Ipv4 { payload = Tcp { dst = 53; _ }; _ } -> true
| _ -> false
let is_dns_response = let open Frame in function
| Ipv4 { payload = Udp { src = 53; _ }; _ }
| Ipv4 { payload = Tcp { src = 53; _ }; _ } -> true
| _ -> false
let query_of_pkt = let open Frame in function
| Ipv4 { payload = Udp { dst = 53; payload = Payload buf}}
| Ipv4 { payload = Tcp { dst = 53; payload = Payload buf}} ->
let open Dns.Packet in
Lwt.catch (fun () -> Lwt.return @@ parse buf) (fun e ->
Log.err (fun m -> m "dns packet parse err!")
>>= fun () -> Lwt.fail e)
| _ -> Lwt.fail (Invalid_argument "Not dns query")
let try_resolve n () =
Lwt.catch
(fun () ->
let open Lwt_unix in
gethostbyname n >>= fun {h_addr_list; _} ->
Array.to_list h_addr_list
|> List.map (fun addr ->
Unix.string_of_inet_addr addr
|> Ipaddr.V4.of_string_exn)
|> fun ips -> Lwt.return @@ `Resolved (n , List.hd ips))
(function
| Not_found -> Lwt.return @@ `Later n
| e -> Lwt.fail e)
let ip_of_name n =
let lim = 60 in
let rec keep_trying n cnt =
if cnt > lim then Lwt.fail @@ Invalid_argument n else
try_resolve n () >>= function
| `Later n ->
Log.debug (fun m -> m "resolve %s later..." n) >>= fun () ->
Lwt_unix.sleep 1. >>= fun () ->
keep_trying n (succ cnt)
| `Resolved (n, ip) ->
Log.info (fun m -> m "resolved: %s %a" n pp_ip ip) >>= fun () ->
Lwt.return ip in
Log.info (fun m -> m "try to resolve %s..." n) >>= fun () ->
keep_trying n 1
let to_dns_response pkt resp =
let open Frame in
match pkt with
| Ipv4 {src = dst; dst = src; payload = Udp {src = dst_port; dst = src_port; _}; _}
| Ipv4 {src = dst; dst = src; payload = Tcp {src = dst_port; dst = src_port; _}; _} ->
let payload_len = Udp_wire.sizeof_udp + Cstruct.len resp in
let ip_hd = Ipv4_packet.{options = Cstruct.create 0; src; dst; ttl = 38; proto = Marshal.protocol_to_int `UDP} in
let ip_hd_wire = Cstruct.create Ipv4_wire.sizeof_ipv4 in
(match Ipv4_packet.Marshal.into_cstruct ~payload_len ip_hd ip_hd_wire with
| Error e -> raise @@ Failure "to_response_pkt -> into_cstruct"
| Ok () ->
Ipv4_wire.set_ipv4_id ip_hd_wire (Random.int 65535);
Ipv4_wire.set_ipv4_csum ip_hd_wire 0;
let cs = Tcpip_checksum.ones_complement ip_hd_wire in
Ipv4_wire.set_ipv4_csum ip_hd_wire cs;
let ph = Ipv4_packet.Marshal.pseudoheader ~src ~dst ~proto:`UDP payload_len in
let udp_hd = Udp_packet.{src_port; dst_port} in
let udp_hd_wire = Udp_packet.Marshal.make_cstruct ~pseudoheader:ph ~payload:resp udp_hd in
let buf_resp = Cstruct.concat [ip_hd_wire; udp_hd_wire; resp] in
let pkt_resp =
match Frame.parse_ipv4_pkt buf_resp with
| Ok fr -> fr
| Error (`Msg msg) ->
Log.err (fun m -> m "dispatch -> parse_eth_payload: %s" msg) |> Lwt.ignore_result;
assert false
in
buf_resp, pkt_resp)
| _ -> assert false
let process_dns_query ~resolve pkt =
let open Dns in
query_of_pkt pkt >>= fun query ->
begin
let names = Packet.(List.map (fun {q_name; _} -> q_name) query.questions) in
let name = List.hd names |> Name.to_string in
resolve name >>= function
| Ok (src_ip, resolved) ->
Log.debug (fun m -> m "Dns_service: allowed %a to resolve %s" pp_ip src_ip name) >>= fun () ->
let name = Dns.Name.of_string name in
let rrs = Dns.Packet.[{ name; cls = RR_IN; flush = false; ttl = 0l; rdata = A resolved }] in
Lwt.return Dns.Query.({ rcode = NoError; aa = true; answer = rrs; authority = []; additional = []})
| Error src_ip ->
Log.info (fun m -> m "Dns_service: banned %a to resolve %s" pp_ip src_ip name) >>= fun () ->
Lwt.return Query.({rcode = Packet.NXDomain; aa = true; answer = []; authority = []; additional = []})
end >>= fun answer ->
let resp = Query.response_of_answer query answer in
Lwt.return @@ Packet.marshal resp
|
62b640c56f5bc5c098889f08a5b4b0e4db7f552ca8482e0cee9c87ab260e0389 | learnuidev/patu | assets.cljs | (ns patu.examples.rpg.assets
(:require [patu.core :as p]))
(def main-map ["+++++++|++"
"+ +"
"+ a +"
"+ +"
"+ +"
"+ $ +"
"+ +"
"+ +"
"+ +"
"++++++++++"])
(def characters
{"a" {:sprite :sprite/ch1
:msg "ohhi how are ya"}
"b" {:sprite :sprite/ch2}
:msg "get out!"})
;;
(defn any-handler [ch]
(when-let [char (get characters ch)]
(clj->js [(p/sprite! (:sprite (get characters "b")))
(p/solid!)
:character
{:msg (:msg char)}])))
(defn level-handler []
{:map main-map
:width 11
:height 11
: pos [ 20 20 ]
:any any-handler
:components [[:+
[:sprite :sprite/steel]
[:solid]]
["$"
[:sprite :sprite/key]
[:prop :key]]
["|"
[:sprite :sprite/door]
[:solid]
[:prop :door]]]})
| null | https://raw.githubusercontent.com/learnuidev/patu/b3ea0138350f1063af976bec1a7a9a878d41c841/src/patu/examples/rpg/assets.cljs | clojure | (ns patu.examples.rpg.assets
(:require [patu.core :as p]))
(def main-map ["+++++++|++"
"+ +"
"+ a +"
"+ +"
"+ +"
"+ $ +"
"+ +"
"+ +"
"+ +"
"++++++++++"])
(def characters
{"a" {:sprite :sprite/ch1
:msg "ohhi how are ya"}
"b" {:sprite :sprite/ch2}
:msg "get out!"})
(defn any-handler [ch]
(when-let [char (get characters ch)]
(clj->js [(p/sprite! (:sprite (get characters "b")))
(p/solid!)
:character
{:msg (:msg char)}])))
(defn level-handler []
{:map main-map
:width 11
:height 11
: pos [ 20 20 ]
:any any-handler
:components [[:+
[:sprite :sprite/steel]
[:solid]]
["$"
[:sprite :sprite/key]
[:prop :key]]
["|"
[:sprite :sprite/door]
[:solid]
[:prop :door]]]})
|
|
fd575093638cc1b4c5f764ee23c07b6d27bbbe49e371f678f720a97cead6a129 | repl-electric/cassiopeia | eta.clj | (ns cassiopeia.destination.eta "███████╗████████╗ █████╗
██╔════╝╚══██╔══╝██╔══██╗
█████╗ ██║ ███████║
██╔══╝ ██║ ██╔══██║
███████╗ ██║ ██║ ██║
╚══════╝ ╚═╝ ╚═╝ ╚═╝"
(:require [mud.timing :as time] [overtone.studio.fx :as fx] [cassiopeia.engine.mixers :as mix] [overtone.inst.synth :as s] [shadertone.tone :as t] [cassiopeia.engine.buffers :as b]) (:use [overtone.live] [mud.core] [cassiopeia.engine.scheduled-sampler] [cassiopeia.samples] [cassiopeia.engine.samples] [cassiopeia.view-screen] [cassiopeia.waves.synths] [cassiopeia.waves.soprano]))
(do (ctl time/root-s :rate 4)
( ctl ( foundation - output - group ) : master - volume 1 )
(defonce voice-g (group "main voice")) (defonce backing-voice-g (group "backing voices")) (defonce bass-g (group "bass voice")) (defonce drums-g (group "drums")) (defonce drum-effects-g (group "drums effects for extra sweetness")) (defbufs 96 [bass-notes-buf hats-buf kick-seq-buf white-seq-buf effects-seq-buf effects2-seq-buf bass-notes-buf stella-wind-note-buf nebula-note-buf supernova-dur-buf supernova-note-buf helium-note-buf hydrogen-note-buf supernova-dur-buf helium-dur-buf hydrogen-dur-buf metallicity-note-buf]))
(pattern! kick-seq-buf [1 0 0 0 0 0 0 0])
(pattern! hats-buf [0 0 0 0 0 0 1 1])
(pattern! white-seq-buf [0 1 1 0 1 0 1 1])
(pattern! hats-buf (repeat 4 [1 0 0 0]) (repeat 4 [1 1 0 0]))
(pattern! kick-seq-buf (repeat 6 [1 0 0 0]) (repeat 2 [1 0 1 1]))
(pattern! white-seq-buf (repeat 3 [1 0 0 0]) [1 1 1 0])
(pattern! effects-seq-buf (repeat 4 [1 0 0 0]))
(pattern! effects-seq-buf [1 0 0 0] (repeat 3 [0 0 0 0]))
(pattern! effects2-seq-buf [0 0 0 0] [1 1 1 1] [0 0 0 0] [1 0 1 1])
(pattern! white-seq-buf (repeat 3 [1 0 0 0]) [1 1 1 1])
(pattern! hats-buf (repeat 6 (concat (repeat 3 [0 1 0 0]) [1 1 0 0])))
(pattern! kick-seq-buf (repeat 5 (repeat 4 [1 0 1 1])) (repeat 4 [1 1 1 1]))
(pattern! kick-seq-buf (repeat 5 [1 0 0 0 1 0 0 0 1 0 0 1 1 0 1 1])
(repeat 1 [1 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1]))
(def kicker (doseq [i (range 0 96)] (kick2 [:head drums-g] :note-buf bass-notes-buf :seq-buf kick-seq-buf :num-steps 96 :beat-num i :noise 0 :amp 1)))
(ctl drums-g :mod-freq 10.2 :mod-index 0.1 :noise 0)
(def ghostly-snares (doall (map #(seqer [:head drum-effects-g] :beat-num %1 :pattern effects-seq-buf :amp 0.2 :num-steps 16 :buf (b/buffer-mix-to-mono snare-ghost-s)) (range 0 16))))
(def bass-kicks (doall (map #(seqer [:head drum-effects-g] :beat-num %1 :pattern effects2-seq-buf :amp 0.1 :num-steps 8 :buf (b/buffer-mix-to-mono deep-bass-kick-s)) (range 0 8))))
(def hats (doall (map #(high-hats [:head drums-g] :amp 0.2 :mix (nth (take 32 (cycle [1.0 1.0])) %1) :room 4 :note-buf bass-notes-buf :seq-buf hats-buf :num-steps 32 :beat-num %1) (range 0 32))))
(ctl hats :damp 1.9 :mix 0.2 :room 10 :amp 0.2)
(def white-hats (doall (map #(whitenoise-hat [:head drums-g] :amp 0.2 :seq-buf white-seq-buf :num-steps 16 :beat-num %1) (range 0 16))))
(def nebula (growl [:head bass-g] :amp 0.0 :beat-trg-bus (:beat time/beat-16th) :beat-bus (:count time/beat-16th) :note-buf nebula-note-buf))
(fadein nebula)
(pattern-at! nebula-note-buf time/main-beat 32 (degrees [] :major :A2))
(pattern! hydrogen-dur-buf (repeat 4 [1/8 1/8 1/2 1/2]) (repeat 4 [1/12 1/12 1/12 1/12]))
(pattern! hydrogen-note-buf (degrees [] :major :A2))
(def hydrogen (shrill-pong [:head voice-g] :amp 1.2 :note-buf hydrogen-note-buf :duration-bus hydrogen-dur-buf))
(def helium (shrill-pong [:head voice-g] :amp 1.2 :note-buf helium-note-buf :duration-bus helium-dur-buf))
(def supernova (shrill-pong [:head voice-g] :amp 0.1 :note-buf supernova-note-buf :duration-bus supernova-dur-buf))
(fadeout hydrogen)
(n-overtime! supernova :amp 0.1 1.2 0.01)
(pattern! helium-dur-buf (repeat 16 [1/9]) (repeat 4 (repeat 16 [1/8])))
(pattern! supernova-dur-buf (repeat 4 (repeat 2 [1/2 1/4 1/2 1/2 1/4 1/2 1/2 1/12])) (repeat 4 [1/2 1/2 1/2 1/2]))
(def stellar-wind (pulsar :note-buf stella-wind-note-buf :amp 0.7))
(def metallicity (fizzy-pulsar [:head backing-voice-g] :amp 0.6 :note-buf metallicity-note-buf :duration-bus supernova-dur-buf))
(let [octave 2
[n1 n2 n3 n4] (chord-degree :v (note-at-octave :A octave) :major)
[n11 n12 n13 n14] (chord-degree :i (note-at-octave :A (if (> octave 3) octave (inc octave))) :major)]
(pattern! stella-wind-note-buf
(repeat 4 (repeat 4 [0 0 0 0]))
(repeat 4 [(note-at-octave :F# (+ (if (> octave 3) 0 2) octave)) (note-at-octave :F# (+ (if (> octave 3) 0 2) octave)) 0 0])
(repeat 2 [(note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) (note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) 0 (note-at-octave :G# (+ (if (> octave 3) 0 2) octave))])
(repeat 2 [(note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) (note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) 0 0 ]))
(pattern! supernova-note-buf
(repeat 4 [n1 n3 n3 n3])
[n1 n2 n3 n3] [n3 n3 n1 n1] [n1 n2 n3 n3] [n1 n1 n3 n3]
(repeat 2 [n13 n13 n14 n14]) [n3 n3 n1 n1] [n1 n2 n3 n3] [n1 n1 n13 n13]
[n1 n2 n3 n3] [n3 n3 n1 n1] [n1 n2 n3 n3] [n1 n1 n3 n3]
(repeat 4 [n14 n13 n12 (if (> octave 3) n14 (inc n14))]))
(pattern! helium-note-buf
(degrees [8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
:major (note-at-octave :A (cond (= octave 1) octave
true (dec octave)))))
(pattern! metallicity-note-buf
(repeat 3 [n1 n1 n1 n1])
(repeat 1 [0 0 0 0])
(repeat 3 [n2 n2 n2 n2])
(repeat 1 [0 0 0 0])
(repeat 4 (repeat 4 [0 0 0 0]))))
(pattern! kick-seq-buf [0])
(pattern! bass-notes-buf
(repeat 2 (repeat 4 [:B1 :B1 :B1 :B1]))
(repeat 2 (repeat 4 [:E#1 :E#1 :E#1 :E#1]))
(repeat 2 (repeat 4 [:F#1 :F#1 :F#1 :F#1])))
(do (reset! color-l 1.0) (reset! color-r 1.0) (reset! expand 1.0) (reset! stars-w 1.0) (reset! yinyan 1.0) (reset! cellular-w 0.0))
(reset! heart-w 0.0)
(reset! cutout-w 0.0)
(reset! cellular-w 0.0)
;;(stop)
(comment
(def beats (buffer->tap kick-seq-buf (:count time/beat-1th)))
(reset! heart-w 1.0)
(reset! stars-w 0.0)
(t/start-fullscreen "resources/shaders/electric.glsl"
:textures [:overtone-audio :previous-frame
"resources/textures/repl-electric-t.png"
"resources/textures/tex16.png"]
:user-data {"iMixRate" color-l "iColorStrength" color-r "iRes" res
"iSpace" space "iExpand" expand "iYinYan" yinyan
"iCircleCount" no-circles "iStarDirection" stars-direction
"iCutoutWeight" cutout-w
"iSpaceLightsWeight" stars-w
"iDistortedWeight" heart-w
"iSpaceyWeight" hyper-w
"iCellularWeight" cellular-w
"iCellGrowth" cellular-growth
"iMeasureCount" (atom {:synth beats :tap "measure-count"})
"iBeat" (atom {:synth beats :tap "beat"})
"iBeatCount" (atom {:synth beats :tap "beat-count"})})
;;(t/stop)
(reset! color-l 1.0)
(reset! color-r 1.0)
(reset! expand 1.0)
(reset! yinyan 1.0)
(reset! res 1.0)
(reset! color-l 0.0)
(reset! space 0.5)
(overtime! stars-direction 10.0 0.001)
(reset! cutout-w 0.0)
(reset! heart-w 1.0)
(reset! stars-w 0.0)
(reset! no-circles 1.0)
(kill drums-g)
(kill voice-g)
(kill backing-voice-g)
(kill bass-g)
(ctl drums-g :amp 0)
(ctl drum-effects-g :amp 0)
(ctl supernova :amp 0)
(ctl helium :amp 0)
(ctl hydrogen :amp 0)
(ctl stellar-wind :amp 0)
(ctl metallicity :amp 0)
(ctl nebula :amp 0)
)
(defn full-stop []
(reset! cutout-w 0.0)
(reset! stars-w 0.0)
(reset! heart-w 0.0)
(reset! cellular-w 0.0)
(remove-on-beat-trigger)
(fadeout-master))
| null | https://raw.githubusercontent.com/repl-electric/cassiopeia/a42c01752fc8dd04ea5db95c8037f393c29cdb75/src/cassiopeia/destination/eta.clj | clojure | (stop)
(t/stop) | (ns cassiopeia.destination.eta "███████╗████████╗ █████╗
██╔════╝╚══██╔══╝██╔══██╗
█████╗ ██║ ███████║
██╔══╝ ██║ ██╔══██║
███████╗ ██║ ██║ ██║
╚══════╝ ╚═╝ ╚═╝ ╚═╝"
(:require [mud.timing :as time] [overtone.studio.fx :as fx] [cassiopeia.engine.mixers :as mix] [overtone.inst.synth :as s] [shadertone.tone :as t] [cassiopeia.engine.buffers :as b]) (:use [overtone.live] [mud.core] [cassiopeia.engine.scheduled-sampler] [cassiopeia.samples] [cassiopeia.engine.samples] [cassiopeia.view-screen] [cassiopeia.waves.synths] [cassiopeia.waves.soprano]))
(do (ctl time/root-s :rate 4)
( ctl ( foundation - output - group ) : master - volume 1 )
(defonce voice-g (group "main voice")) (defonce backing-voice-g (group "backing voices")) (defonce bass-g (group "bass voice")) (defonce drums-g (group "drums")) (defonce drum-effects-g (group "drums effects for extra sweetness")) (defbufs 96 [bass-notes-buf hats-buf kick-seq-buf white-seq-buf effects-seq-buf effects2-seq-buf bass-notes-buf stella-wind-note-buf nebula-note-buf supernova-dur-buf supernova-note-buf helium-note-buf hydrogen-note-buf supernova-dur-buf helium-dur-buf hydrogen-dur-buf metallicity-note-buf]))
(pattern! kick-seq-buf [1 0 0 0 0 0 0 0])
(pattern! hats-buf [0 0 0 0 0 0 1 1])
(pattern! white-seq-buf [0 1 1 0 1 0 1 1])
(pattern! hats-buf (repeat 4 [1 0 0 0]) (repeat 4 [1 1 0 0]))
(pattern! kick-seq-buf (repeat 6 [1 0 0 0]) (repeat 2 [1 0 1 1]))
(pattern! white-seq-buf (repeat 3 [1 0 0 0]) [1 1 1 0])
(pattern! effects-seq-buf (repeat 4 [1 0 0 0]))
(pattern! effects-seq-buf [1 0 0 0] (repeat 3 [0 0 0 0]))
(pattern! effects2-seq-buf [0 0 0 0] [1 1 1 1] [0 0 0 0] [1 0 1 1])
(pattern! white-seq-buf (repeat 3 [1 0 0 0]) [1 1 1 1])
(pattern! hats-buf (repeat 6 (concat (repeat 3 [0 1 0 0]) [1 1 0 0])))
(pattern! kick-seq-buf (repeat 5 (repeat 4 [1 0 1 1])) (repeat 4 [1 1 1 1]))
(pattern! kick-seq-buf (repeat 5 [1 0 0 0 1 0 0 0 1 0 0 1 1 0 1 1])
(repeat 1 [1 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1]))
(def kicker (doseq [i (range 0 96)] (kick2 [:head drums-g] :note-buf bass-notes-buf :seq-buf kick-seq-buf :num-steps 96 :beat-num i :noise 0 :amp 1)))
(ctl drums-g :mod-freq 10.2 :mod-index 0.1 :noise 0)
(def ghostly-snares (doall (map #(seqer [:head drum-effects-g] :beat-num %1 :pattern effects-seq-buf :amp 0.2 :num-steps 16 :buf (b/buffer-mix-to-mono snare-ghost-s)) (range 0 16))))
(def bass-kicks (doall (map #(seqer [:head drum-effects-g] :beat-num %1 :pattern effects2-seq-buf :amp 0.1 :num-steps 8 :buf (b/buffer-mix-to-mono deep-bass-kick-s)) (range 0 8))))
(def hats (doall (map #(high-hats [:head drums-g] :amp 0.2 :mix (nth (take 32 (cycle [1.0 1.0])) %1) :room 4 :note-buf bass-notes-buf :seq-buf hats-buf :num-steps 32 :beat-num %1) (range 0 32))))
(ctl hats :damp 1.9 :mix 0.2 :room 10 :amp 0.2)
(def white-hats (doall (map #(whitenoise-hat [:head drums-g] :amp 0.2 :seq-buf white-seq-buf :num-steps 16 :beat-num %1) (range 0 16))))
(def nebula (growl [:head bass-g] :amp 0.0 :beat-trg-bus (:beat time/beat-16th) :beat-bus (:count time/beat-16th) :note-buf nebula-note-buf))
(fadein nebula)
(pattern-at! nebula-note-buf time/main-beat 32 (degrees [] :major :A2))
(pattern! hydrogen-dur-buf (repeat 4 [1/8 1/8 1/2 1/2]) (repeat 4 [1/12 1/12 1/12 1/12]))
(pattern! hydrogen-note-buf (degrees [] :major :A2))
(def hydrogen (shrill-pong [:head voice-g] :amp 1.2 :note-buf hydrogen-note-buf :duration-bus hydrogen-dur-buf))
(def helium (shrill-pong [:head voice-g] :amp 1.2 :note-buf helium-note-buf :duration-bus helium-dur-buf))
(def supernova (shrill-pong [:head voice-g] :amp 0.1 :note-buf supernova-note-buf :duration-bus supernova-dur-buf))
(fadeout hydrogen)
(n-overtime! supernova :amp 0.1 1.2 0.01)
(pattern! helium-dur-buf (repeat 16 [1/9]) (repeat 4 (repeat 16 [1/8])))
(pattern! supernova-dur-buf (repeat 4 (repeat 2 [1/2 1/4 1/2 1/2 1/4 1/2 1/2 1/12])) (repeat 4 [1/2 1/2 1/2 1/2]))
(def stellar-wind (pulsar :note-buf stella-wind-note-buf :amp 0.7))
(def metallicity (fizzy-pulsar [:head backing-voice-g] :amp 0.6 :note-buf metallicity-note-buf :duration-bus supernova-dur-buf))
(let [octave 2
[n1 n2 n3 n4] (chord-degree :v (note-at-octave :A octave) :major)
[n11 n12 n13 n14] (chord-degree :i (note-at-octave :A (if (> octave 3) octave (inc octave))) :major)]
(pattern! stella-wind-note-buf
(repeat 4 (repeat 4 [0 0 0 0]))
(repeat 4 [(note-at-octave :F# (+ (if (> octave 3) 0 2) octave)) (note-at-octave :F# (+ (if (> octave 3) 0 2) octave)) 0 0])
(repeat 2 [(note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) (note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) 0 (note-at-octave :G# (+ (if (> octave 3) 0 2) octave))])
(repeat 2 [(note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) (note-at-octave :G# (+ (if (> octave 3) 0 2) octave)) 0 0 ]))
(pattern! supernova-note-buf
(repeat 4 [n1 n3 n3 n3])
[n1 n2 n3 n3] [n3 n3 n1 n1] [n1 n2 n3 n3] [n1 n1 n3 n3]
(repeat 2 [n13 n13 n14 n14]) [n3 n3 n1 n1] [n1 n2 n3 n3] [n1 n1 n13 n13]
[n1 n2 n3 n3] [n3 n3 n1 n1] [n1 n2 n3 n3] [n1 n1 n3 n3]
(repeat 4 [n14 n13 n12 (if (> octave 3) n14 (inc n14))]))
(pattern! helium-note-buf
(degrees [8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
:major (note-at-octave :A (cond (= octave 1) octave
true (dec octave)))))
(pattern! metallicity-note-buf
(repeat 3 [n1 n1 n1 n1])
(repeat 1 [0 0 0 0])
(repeat 3 [n2 n2 n2 n2])
(repeat 1 [0 0 0 0])
(repeat 4 (repeat 4 [0 0 0 0]))))
(pattern! kick-seq-buf [0])
(pattern! bass-notes-buf
(repeat 2 (repeat 4 [:B1 :B1 :B1 :B1]))
(repeat 2 (repeat 4 [:E#1 :E#1 :E#1 :E#1]))
(repeat 2 (repeat 4 [:F#1 :F#1 :F#1 :F#1])))
(do (reset! color-l 1.0) (reset! color-r 1.0) (reset! expand 1.0) (reset! stars-w 1.0) (reset! yinyan 1.0) (reset! cellular-w 0.0))
(reset! heart-w 0.0)
(reset! cutout-w 0.0)
(reset! cellular-w 0.0)
(comment
(def beats (buffer->tap kick-seq-buf (:count time/beat-1th)))
(reset! heart-w 1.0)
(reset! stars-w 0.0)
(t/start-fullscreen "resources/shaders/electric.glsl"
:textures [:overtone-audio :previous-frame
"resources/textures/repl-electric-t.png"
"resources/textures/tex16.png"]
:user-data {"iMixRate" color-l "iColorStrength" color-r "iRes" res
"iSpace" space "iExpand" expand "iYinYan" yinyan
"iCircleCount" no-circles "iStarDirection" stars-direction
"iCutoutWeight" cutout-w
"iSpaceLightsWeight" stars-w
"iDistortedWeight" heart-w
"iSpaceyWeight" hyper-w
"iCellularWeight" cellular-w
"iCellGrowth" cellular-growth
"iMeasureCount" (atom {:synth beats :tap "measure-count"})
"iBeat" (atom {:synth beats :tap "beat"})
"iBeatCount" (atom {:synth beats :tap "beat-count"})})
(reset! color-l 1.0)
(reset! color-r 1.0)
(reset! expand 1.0)
(reset! yinyan 1.0)
(reset! res 1.0)
(reset! color-l 0.0)
(reset! space 0.5)
(overtime! stars-direction 10.0 0.001)
(reset! cutout-w 0.0)
(reset! heart-w 1.0)
(reset! stars-w 0.0)
(reset! no-circles 1.0)
(kill drums-g)
(kill voice-g)
(kill backing-voice-g)
(kill bass-g)
(ctl drums-g :amp 0)
(ctl drum-effects-g :amp 0)
(ctl supernova :amp 0)
(ctl helium :amp 0)
(ctl hydrogen :amp 0)
(ctl stellar-wind :amp 0)
(ctl metallicity :amp 0)
(ctl nebula :amp 0)
)
(defn full-stop []
(reset! cutout-w 0.0)
(reset! stars-w 0.0)
(reset! heart-w 0.0)
(reset! cellular-w 0.0)
(remove-on-beat-trigger)
(fadeout-master))
|
184c802b22ddbe479432fb061242ddd2fa586aaa8a173e6ebe95cb531c5c5366 | mzp/coq-ide-for-ios | certificate.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(* *)
: A reflexive tactic using the
(* *)
( / ) 2006 - 2008
(* *)
(************************************************************************)
(* We take as input a list of polynomials [p1...pn] and return an unfeasibility
certificate polynomial. *)
open . Polynomial
open Big_int
open Num
open Sos_lib
module Mc = Micromega
module Ml2C = Mutils.CamlToCoq
module C2Ml = Mutils.CoqToCaml
let (<+>) = add_num
let (<->) = minus_num
let (<*>) = mult_num
type var = Mc.positive
module Monomial :
sig
type t
val const : t
val var : var -> t
val find : var -> t -> int
val mult : var -> t -> t
val prod : t -> t -> t
val compare : t -> t -> int
val pp : out_channel -> t -> unit
val fold : (var -> int -> 'a -> 'a) -> t -> 'a -> 'a
end
=
struct
(* A monomial is represented by a multiset of variables *)
module Map = Map.Make(struct type t = var let compare = Pervasives.compare end)
open Map
type t = int Map.t
(* The monomial that corresponds to a constant *)
let const = Map.empty
(* The monomial 'x' *)
let var x = Map.add x 1 Map.empty
(* Get the degre of a variable in a monomial *)
let find x m = try find x m with Not_found -> 0
(* Multiply a monomial by a variable *)
let mult x m = add x ( (find x m) + 1) m
(* Product of monomials *)
let prod m1 m2 = Map.fold (fun k d m -> add k ((find k m) + d) m) m1 m2
(* Total ordering of monomials *)
let compare m1 m2 = Map.compare Pervasives.compare m1 m2
let pp o m = Map.iter (fun k v ->
if v = 1 then Printf.fprintf o "x%i." (C2Ml.index k)
else Printf.fprintf o "x%i^%i." (C2Ml.index k) v) m
let fold = fold
end
module Poly :
(* A polynomial is a map of monomials *)
This is probably a naive implementation
( expected to be fast enough - Coq is probably the bottleneck )
* The new ring contribution is using a sparse Horner representation .
This is probably a naive implementation
(expected to be fast enough - Coq is probably the bottleneck)
*The new ring contribution is using a sparse Horner representation.
*)
sig
type t
val get : Monomial.t -> t -> num
val variable : var -> t
val add : Monomial.t -> num -> t -> t
val constant : num -> t
val mult : Monomial.t -> num -> t -> t
val product : t -> t -> t
val addition : t -> t -> t
val uminus : t -> t
val fold : (Monomial.t -> num -> 'a -> 'a) -> t -> 'a -> 'a
val pp : out_channel -> t -> unit
val compare : t -> t -> int
val is_null : t -> bool
end =
struct
(*normalisation bug : 0*x ... *)
module P = Map.Make(Monomial)
open P
type t = num P.t
let pp o p = P.iter (fun k v ->
if compare_num v (Int 0) <> 0
then
if Monomial.compare Monomial.const k = 0
then Printf.fprintf o "%s " (string_of_num v)
else Printf.fprintf o "%s*%a " (string_of_num v) Monomial.pp k) p
(* Get the coefficient of monomial mn *)
let get : Monomial.t -> t -> num =
fun mn p -> try find mn p with Not_found -> (Int 0)
(* The polynomial 1.x *)
let variable : var -> t =
fun x -> add (Monomial.var x) (Int 1) empty
(*The constant polynomial *)
let constant : num -> t =
fun c -> add (Monomial.const) c empty
(* The addition of a monomial *)
let add : Monomial.t -> num -> t -> t =
fun mn v p ->
let vl = (get mn p) <+> v in
add mn vl p
(** Design choice: empty is not a polynomial
I do not remember why ....
**)
(* The product by a monomial *)
let mult : Monomial.t -> num -> t -> t =
fun mn v p ->
fold (fun mn' v' res -> P.add (Monomial.prod mn mn') (v<*>v') res) p empty
let addition : t -> t -> t =
fun p1 p2 -> fold (fun mn v p -> add mn v p) p1 p2
let product : t -> t -> t =
fun p1 p2 ->
fold (fun mn v res -> addition (mult mn v p2) res ) p1 empty
let uminus : t -> t =
fun p -> map (fun v -> minus_num v) p
let fold = P.fold
let is_null p = fold (fun mn vl b -> b & sign_num vl = 0) p true
let compare = compare compare_num
end
open Mutils
type 'a number_spec = {
bigint_to_number : big_int -> 'a;
number_to_num : 'a -> num;
zero : 'a;
unit : 'a;
mult : 'a -> 'a -> 'a;
eqb : 'a -> 'a -> bool
}
let z_spec = {
bigint_to_number = Ml2C.bigint ;
number_to_num = (fun x -> Big_int (C2Ml.z_big_int x));
zero = Mc.Z0;
unit = Mc.Zpos Mc.XH;
mult = Mc.zmult;
eqb = Mc.zeq_bool
}
let q_spec = {
bigint_to_number = (fun x -> {Mc.qnum = Ml2C.bigint x; Mc.qden = Mc.XH});
number_to_num = C2Ml.q_to_num;
zero = {Mc.qnum = Mc.Z0;Mc.qden = Mc.XH};
unit = {Mc.qnum = (Mc.Zpos Mc.XH) ; Mc.qden = Mc.XH};
mult = Mc.qmult;
eqb = Mc.qeq_bool
}
let r_spec = z_spec
let dev_form n_spec p =
let rec dev_form p =
match p with
| Mc.PEc z -> Poly.constant (n_spec.number_to_num z)
| Mc.PEX v -> Poly.variable v
| Mc.PEmul(p1,p2) ->
let p1 = dev_form p1 in
let p2 = dev_form p2 in
Poly.product p1 p2
| Mc.PEadd(p1,p2) -> Poly.addition (dev_form p1) (dev_form p2)
| Mc.PEopp p -> Poly.uminus (dev_form p)
| Mc.PEsub(p1,p2) -> Poly.addition (dev_form p1) (Poly.uminus (dev_form p2))
| Mc.PEpow(p,n) ->
let p = dev_form p in
let n = C2Ml.n n in
let rec pow n =
if n = 0
then Poly.constant (n_spec.number_to_num n_spec.unit)
else Poly.product p (pow (n-1)) in
pow n in
dev_form p
let monomial_to_polynomial mn =
Monomial.fold
(fun v i acc ->
let mn = if i = 1 then Mc.PEX v else Mc.PEpow (Mc.PEX v ,Ml2C.n i) in
if acc = Mc.PEc (Mc.Zpos Mc.XH)
then mn
else Mc.PEmul(mn,acc))
mn
(Mc.PEc (Mc.Zpos Mc.XH))
let list_to_polynomial vars l =
assert (List.for_all (fun x -> ceiling_num x =/ x) l);
let var x = monomial_to_polynomial (List.nth vars x) in
let rec xtopoly p i = function
| [] -> p
| c::l -> if c =/ (Int 0) then xtopoly p (i+1) l
else let c = Mc.PEc (Ml2C.bigint (numerator c)) in
let mn =
if c = Mc.PEc (Mc.Zpos Mc.XH)
then var i
else Mc.PEmul (c,var i) in
let p' = if p = Mc.PEc Mc.Z0 then mn else
Mc.PEadd (mn, p) in
xtopoly p' (i+1) l in
xtopoly (Mc.PEc Mc.Z0) 0 l
let rec fixpoint f x =
let y' = f x in
if y' = x then y'
else fixpoint f y'
let rec_simpl_cone n_spec e =
let simpl_cone =
Mc.simpl_cone n_spec.zero n_spec.unit n_spec.mult n_spec.eqb in
let rec rec_simpl_cone = function
| Mc.PsatzMulE(t1, t2) ->
simpl_cone (Mc.PsatzMulE (rec_simpl_cone t1, rec_simpl_cone t2))
| Mc.PsatzAdd(t1,t2) ->
simpl_cone (Mc.PsatzAdd (rec_simpl_cone t1, rec_simpl_cone t2))
| x -> simpl_cone x in
rec_simpl_cone e
let simplify_cone n_spec c = fixpoint (rec_simpl_cone n_spec) c
type cone_prod =
Const of cone
| Ideal of cone *cone
| Mult of cone * cone
| Other of cone
and cone = Mc.zWitness
let factorise_linear_cone c =
let rec cone_list c l =
match c with
| Mc.PsatzAdd (x,r) -> cone_list r (x::l)
| _ -> c :: l in
let factorise c1 c2 =
match c1 , c2 with
| Mc.PsatzMulC(x,y) , Mc.PsatzMulC(x',y') ->
if x = x' then Some (Mc.PsatzMulC(x, Mc.PsatzAdd(y,y'))) else None
| Mc.PsatzMulE(x,y) , Mc.PsatzMulE(x',y') ->
if x = x' then Some (Mc.PsatzMulE(x, Mc.PsatzAdd(y,y'))) else None
| _ -> None in
let rec rebuild_cone l pending =
match l with
| [] -> (match pending with
| None -> Mc.PsatzZ
| Some p -> p
)
| e::l ->
(match pending with
| None -> rebuild_cone l (Some e)
| Some p -> (match factorise p e with
| None -> Mc.PsatzAdd(p, rebuild_cone l (Some e))
| Some f -> rebuild_cone l (Some f) )
) in
(rebuild_cone (List.sort Pervasives.compare (cone_list c [])) None)
The binding with Fourier might be a bit obsolete
-- how does it handle equalities ?
-- how does it handle equalities ? *)
(* Certificates are elements of the cone such that P = 0 *)
To begin with , we search for certificates of the form :
a1.p1 + ... an.pn + b1.q1 + ... + bn.qn + c = 0
where pi > = 0 qi > 0
ai > = 0
bi > = 0
Sum bi + c > = 1
This is a linear problem : each monomial is considered as a variable .
Hence , we can use fourier .
The variable c is at index 0
a1.p1 + ... an.pn + b1.q1 +... + bn.qn + c = 0
where pi >= 0 qi > 0
ai >= 0
bi >= 0
Sum bi + c >= 1
This is a linear problem: each monomial is considered as a variable.
Hence, we can use fourier.
The variable c is at index 0
*)
open Mfourier
module Fourier = Fourier(Vector . VList)(SysSet(Vector . VList ) )
module . VSparse)(SysSetAlt(Vector . VSparse ) )
module Fourier = Mfourier . Fourier(Vector . VSparse)(*(SysSetAlt(Vector . ) )
module Vect = Fourier . Vect
open Fourier . Cstr
(* fold_left followed by a rev ! *)
let constrain_monomial mn l =
let coeffs = List.fold_left (fun acc p -> (Poly.get mn p)::acc) [] l in
if mn = Monomial.const
then
{ coeffs = Vect.from_list ((Big_int unit_big_int):: (List.rev coeffs)) ;
op = Eq ;
cst = Big_int zero_big_int }
else
{ coeffs = Vect.from_list ((Big_int zero_big_int):: (List.rev coeffs)) ;
op = Eq ;
cst = Big_int zero_big_int }
let positivity l =
let rec xpositivity i l =
match l with
| [] -> []
| (_,Mc.Equal)::l -> xpositivity (i+1) l
| (_,_)::l ->
{coeffs = Vect.update (i+1) (fun _ -> Int 1) Vect.null ;
op = Ge ;
cst = Int 0 } :: (xpositivity (i+1) l)
in
xpositivity 0 l
let string_of_op = function
| Mc.Strict -> "> 0"
| Mc.NonStrict -> ">= 0"
| Mc.Equal -> "= 0"
| Mc.NonEqual -> "<> 0"
If the certificate includes at least one strict inequality ,
the obtained polynomial can also be 0
the obtained polynomial can also be 0 *)
let build_linear_system l =
(* Gather the monomials: HINT add up of the polynomials *)
let l' = List.map fst l in
let monomials =
List.fold_left (fun acc p -> Poly.addition p acc) (Poly.constant (Int 0)) l'
in (* For each monomial, compute a constraint *)
let s0 =
Poly.fold (fun mn _ res -> (constrain_monomial mn l')::res) monomials [] in
(* I need at least something strictly positive *)
let strict = {
coeffs = Vect.from_list ((Big_int unit_big_int)::
(List.map (fun (x,y) ->
match y with Mc.Strict ->
Big_int unit_big_int
| _ -> Big_int zero_big_int) l));
op = Ge ; cst = Big_int unit_big_int } in
(* Add the positivity constraint *)
{coeffs = Vect.from_list ([Big_int unit_big_int]) ;
op = Ge ;
cst = Big_int zero_big_int}::(strict::(positivity l)@s0)
let big_int_to_z = Ml2C.bigint
(* For Q, this is a pity that the certificate has been scaled
-- at a lower layer, certificates are using nums... *)
let make_certificate n_spec (cert,li) =
let bint_to_cst = n_spec.bigint_to_number in
match cert with
| [] -> failwith "empty_certificate"
| e::cert' ->
let cst = match compare_big_int e zero_big_int with
| 0 -> Mc.PsatzZ
| 1 -> Mc.PsatzC (bint_to_cst e)
| _ -> failwith "positivity error"
in
let rec scalar_product cert l =
match cert with
| [] -> Mc.PsatzZ
| c::cert -> match l with
| [] -> failwith "make_certificate(1)"
| i::l ->
let r = scalar_product cert l in
match compare_big_int c zero_big_int with
| -1 -> Mc.PsatzAdd (
Mc.PsatzMulC (Mc.Pc ( bint_to_cst c), Mc.PsatzIn (Ml2C.nat i)),
r)
| 0 -> r
| _ -> Mc.PsatzAdd (
Mc.PsatzMulE (Mc.PsatzC (bint_to_cst c), Mc.PsatzIn (Ml2C.nat i)),
r) in
((factorise_linear_cone
(simplify_cone n_spec (Mc.PsatzAdd (cst, scalar_product cert' li)))))
exception Found of Monomial.t
exception Strict
let primal l =
let vr = ref 0 in
let module Mmn = Map.Make(Monomial) in
let vect_of_poly map p =
Poly.fold (fun mn vl (map,vect) ->
if mn = Monomial.const
then (map,vect)
else
let (mn,m) = try (Mmn.find mn map,map) with Not_found -> let res = (!vr, Mmn.add mn !vr map) in incr vr ; res in
(m,if sign_num vl = 0 then vect else (mn,vl)::vect)) p (map,[]) in
let op_op = function Mc.NonStrict -> Ge |Mc.Equal -> Eq | _ -> raise Strict in
let cmp x y = Pervasives.compare (fst x) (fst y) in
snd (List.fold_right (fun (p,op) (map,l) ->
let (mp,vect) = vect_of_poly map p in
let cstr = {coeffs = List.sort cmp vect; op = op_op op ; cst = minus_num (Poly.get Monomial.const p)} in
(mp,cstr::l)) l (Mmn.empty,[]))
let dual_raw_certificate (l: (Poly.t * Mc.op1) list) =
List.iter ( fun ( p , op ) - > Printf.fprintf stdout " % a % s 0\n " Poly.pp p ( string_of_op op ) ) l ;
let sys = build_linear_system l in
try
match Fourier.find_point sys with
| Inr _ -> None
| Inl cert -> Some (rats_to_ints (Vect.to_list cert))
(* should not use rats_to_ints *)
with x ->
if debug
then (Printf.printf "raw certificate %s" (Printexc.to_string x);
flush stdout) ;
None
let raw_certificate l =
try
let p = primal l in
match Fourier.find_point p with
| Inr prf ->
if debug then Printf.printf "AProof : %a\n" pp_proof prf ;
let cert = List.map (fun (x,n) -> x+1,n) (fst (List.hd (Proof.mk_proof p prf))) in
if debug then Printf.printf "CProof : %a" Vect.pp_vect cert ;
Some (rats_to_ints (Vect.to_list cert))
| Inl _ -> None
with Strict ->
(* Fourier elimination should handle > *)
dual_raw_certificate l
let simple_linear_prover (*to_constant*) l =
let (lc,li) = List.split l in
match raw_certificate lc with
| None -> None (* No certificate *)
| Some cert -> (* make_certificate to_constant*)Some (cert,li)
let linear_prover n_spec l =
let li = List.combine l (interval 0 (List.length l -1)) in
let (l1,l') = List.partition
(fun (x,_) -> if snd x = Mc.NonEqual then true else false) li in
let l' = List.map
(fun ((x,y),i) -> match y with
Mc.NonEqual -> failwith "cannot happen"
| y -> ((dev_form n_spec x, y),i)) l' in
n_spec
let linear_prover n_spec l =
try linear_prover n_spec l with
x -> (print_string (Printexc.to_string x); None)
let linear_prover_with_cert spec l =
match linear_prover spec l with
| None -> None
| Some cert -> Some (make_certificate spec cert)
(* zprover.... *)
I need to gather the set of variables --- >
Then go for fold
Once I have an interval , I need a certificate : 2 other fourier elims .
( I could probably get the certificate directly
as it is done in the fourier contrib . )
Then go for fold
Once I have an interval, I need a certificate : 2 other fourier elims.
(I could probably get the certificate directly
as it is done in the fourier contrib.)
*)
let make_linear_system l =
let l' = List.map fst l in
let monomials = List.fold_left (fun acc p -> Poly.addition p acc)
(Poly.constant (Int 0)) l' in
let monomials = Poly.fold
(fun mn _ l -> if mn = Monomial.const then l else mn::l) monomials [] in
(List.map (fun (c,op) ->
{coeffs = Vect.from_list (List.map (fun mn -> (Poly.get mn c)) monomials) ;
op = op ;
cst = minus_num ( (Poly.get Monomial.const c))}) l
,monomials)
let pplus x y = Mc.PEadd(x,y)
let pmult x y = Mc.PEmul(x,y)
let pconst x = Mc.PEc x
let popp x = Mc.PEopp x
let debug = false
(* keep track of enumerated vectors *)
let rec mem p x l =
match l with [] -> false | e::l -> if p x e then true else mem p x l
let rec remove_assoc p x l =
match l with [] -> [] | e::l -> if p x (fst e) then
remove_assoc p x l else e::(remove_assoc p x l)
let eq x y = Vect.compare x y = 0
let remove e l = List.fold_left (fun l x -> if eq x e then l else x::l) [] l
(* The prover is (probably) incomplete --
only searching for naive cutting planes *)
let candidates sys =
let ll = List.fold_right (
fun (e,k) r ->
match k with
| Mc.NonStrict -> (dev_form z_spec e , Ge)::r
| Mc.Equal -> (dev_form z_spec e , Eq)::r
(* we already know the bound -- don't compute it again *)
| _ -> failwith "Cannot happen candidates") sys [] in
let (sys,var_mn) = make_linear_system ll in
let vars = mapi (fun _ i -> Vect.set i (Int 1) Vect.null) var_mn in
(List.fold_left (fun l cstr ->
let gcd = Big_int (Vect.gcd cstr.coeffs) in
if gcd =/ (Int 1) && cstr.op = Eq
then l
else (Vect.mul (Int 1 // gcd) cstr.coeffs)::l) [] sys) @ vars
let rec xzlinear_prover planes sys =
match linear_prover z_spec sys with
| Some prf -> Some (Mc.RatProof (make_certificate z_spec prf,Mc.DoneProof))
| None -> (* find the candidate with the smallest range *)
Grrr - linear_prover is also calling ' make_linear_system '
let ll = List.fold_right (fun (e,k) r -> match k with
Mc.NonEqual -> r
| k -> (dev_form z_spec e ,
match k with
Mc.NonStrict -> Ge
| Mc.Equal -> Eq
| Mc.Strict | Mc.NonEqual -> failwith "Cannot happen") :: r) sys [] in
let (ll,var) = make_linear_system ll in
let candidates = List.fold_left (fun acc vect ->
match Fourier.optimise vect ll with
| None -> acc
| Some i ->
(* Printf.printf "%s in %s\n" (Vect.string vect) (string_of_intrvl i) ; *)
flush stdout ;
(vect,i) ::acc) [] planes in
let smallest_interval =
match List.fold_left (fun (x1,i1) (x2,i2) ->
if Itv.smaller_itv i1 i2
then (x1,i1) else (x2,i2)) (Vect.null,(None,None)) candidates
with
| (x,(Some i, Some j)) -> Some(i,x,j)
| x -> None (* This might be a cutting plane *)
in
match smallest_interval with
| Some (lb,e,ub) ->
let (lbn,lbd) =
(Ml2C.bigint (sub_big_int (numerator lb) unit_big_int),
Ml2C.bigint (denominator lb)) in
let (ubn,ubd) =
(Ml2C.bigint (add_big_int unit_big_int (numerator ub)) ,
Ml2C.bigint (denominator ub)) in
let expr = list_to_polynomial var (Vect.to_list e) in
(match
(*x <= ub -> x > ub *)
linear_prover z_spec
((pplus (pmult (pconst ubd) expr) (popp (pconst ubn)),
Mc.NonStrict) :: sys),
(* lb <= x -> lb > x *)
linear_prover z_spec
((pplus (popp (pmult (pconst lbd) expr)) (pconst lbn),
Mc.NonStrict)::sys)
with
| Some cub , Some clb ->
(match zlinear_enum (remove e planes) expr
(ceiling_num lb) (floor_num ub) sys
with
| None -> None
| Some prf ->
let bound_proof (c,l) = make_certificate z_spec (List.tl c , List.tl (List.map (fun x -> x -1) l)) in
, expr , Ml2C.q ub ,
| _ -> None
)
| _ -> None
and zlinear_enum planes expr clb cub l =
if clb >/ cub
then Some []
else
let pexpr = pplus (popp (pconst (Ml2C.bigint (numerator clb)))) expr in
let sys' = (pexpr, Mc.Equal)::l in
(*let enum = *)
match xzlinear_prover planes sys' with
| None -> if debug then print_string "zlp?"; None
| Some prf -> if debug then print_string "zlp!";
match zlinear_enum planes expr (clb +/ (Int 1)) cub l with
| None -> None
| Some prfl -> Some (prf :: prfl)
let zlinear_prover sys =
let candidates = candidates sys in
Printf.printf " candidates % d " ( candidates ) ;
(*let t0 = Sys.time () in*)
let res = xzlinear_prover candidates sys in
Printf.printf " Time prover : % f " ( Sys.time ( ) - . t0 ) ;
open Sos_types
open Mutils
let rec scale_term t =
match t with
| Zero -> unit_big_int , Zero
| Const n -> (denominator n) , Const (Big_int (numerator n))
| Var n -> unit_big_int , Var n
| Inv _ -> failwith "scale_term : not implemented"
| Opp t -> let s, t = scale_term t in s, Opp t
| Add(t1,t2) -> let s1,y1 = scale_term t1 and s2,y2 = scale_term t2 in
let g = gcd_big_int s1 s2 in
let s1' = div_big_int s1 g in
let s2' = div_big_int s2 g in
let e = mult_big_int g (mult_big_int s1' s2') in
if (compare_big_int e unit_big_int) = 0
then (unit_big_int, Add (y1,y2))
else e, Add (Mul(Const (Big_int s2'), y1),
Mul (Const (Big_int s1'), y2))
| Sub _ -> failwith "scale term: not implemented"
| Mul(y,z) -> let s1,y1 = scale_term y and s2,y2 = scale_term z in
mult_big_int s1 s2 , Mul (y1, y2)
| Pow(t,n) -> let s,t = scale_term t in
power_big_int_positive_int s n , Pow(t,n)
| _ -> failwith "scale_term : not implemented"
let scale_term t =
let (s,t') = scale_term t in
s,t'
let get_index_of_ith_match f i l =
let rec get j res l =
match l with
| [] -> failwith "bad index"
| e::l -> if f e
then
(if j = i then res else get (j+1) (res+1) l )
else get j (res+1) l in
get 0 0 l
let rec scale_certificate pos = match pos with
| Axiom_eq i -> unit_big_int , Axiom_eq i
| Axiom_le i -> unit_big_int , Axiom_le i
| Axiom_lt i -> unit_big_int , Axiom_lt i
| Monoid l -> unit_big_int , Monoid l
| Rational_eq n -> (denominator n) , Rational_eq (Big_int (numerator n))
| Rational_le n -> (denominator n) , Rational_le (Big_int (numerator n))
| Rational_lt n -> (denominator n) , Rational_lt (Big_int (numerator n))
| Square t -> let s,t' = scale_term t in
mult_big_int s s , Square t'
| Eqmul (t, y) -> let s1,y1 = scale_term t and s2,y2 = scale_certificate y in
mult_big_int s1 s2 , Eqmul (y1,y2)
| Sum (y, z) -> let s1,y1 = scale_certificate y
and s2,y2 = scale_certificate z in
let g = gcd_big_int s1 s2 in
let s1' = div_big_int s1 g in
let s2' = div_big_int s2 g in
mult_big_int g (mult_big_int s1' s2'),
Sum (Product(Rational_le (Big_int s2'), y1),
Product (Rational_le (Big_int s1'), y2))
| Product (y, z) ->
let s1,y1 = scale_certificate y and s2,y2 = scale_certificate z in
mult_big_int s1 s2 , Product (y1,y2)
open Micromega
let rec term_to_q_expr = function
| Const n -> PEc (Ml2C.q n)
| Zero -> PEc ( Ml2C.q (Int 0))
| Var s -> PEX (Ml2C.index
(int_of_string (String.sub s 1 (String.length s - 1))))
| Mul(p1,p2) -> PEmul(term_to_q_expr p1, term_to_q_expr p2)
| Add(p1,p2) -> PEadd(term_to_q_expr p1, term_to_q_expr p2)
| Opp p -> PEopp (term_to_q_expr p)
| Pow(t,n) -> PEpow (term_to_q_expr t,Ml2C.n n)
| Sub(t1,t2) -> PEsub (term_to_q_expr t1, term_to_q_expr t2)
| _ -> failwith "term_to_q_expr: not implemented"
let term_to_q_pol e = Mc.norm_aux (Ml2C.q (Int 0)) (Ml2C.q (Int 1)) Mc.qplus Mc.qmult Mc.qminus Mc.qopp Mc.qeq_bool (term_to_q_expr e)
let rec product l =
match l with
| [] -> Mc.PsatzZ
| [i] -> Mc.PsatzIn (Ml2C.nat i)
| i ::l -> Mc.PsatzMulE(Mc.PsatzIn (Ml2C.nat i), product l)
let q_cert_of_pos pos =
let rec _cert_of_pos = function
Axiom_eq i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_le i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_lt i -> Mc.PsatzIn (Ml2C.nat i)
| Monoid l -> product l
| Rational_eq n | Rational_le n | Rational_lt n ->
if compare_num n (Int 0) = 0 then Mc.PsatzZ else
Mc.PsatzC (Ml2C.q n)
| Square t -> Mc.PsatzSquare (term_to_q_pol t)
| Eqmul (t, y) -> Mc.PsatzMulC(term_to_q_pol t, _cert_of_pos y)
| Sum (y, z) -> Mc.PsatzAdd (_cert_of_pos y, _cert_of_pos z)
| Product (y, z) -> Mc.PsatzMulE (_cert_of_pos y, _cert_of_pos z) in
simplify_cone q_spec (_cert_of_pos pos)
let rec term_to_z_expr = function
| Const n -> PEc (Ml2C.bigint (big_int_of_num n))
| Zero -> PEc ( Z0)
| Var s -> PEX (Ml2C.index
(int_of_string (String.sub s 1 (String.length s - 1))))
| Mul(p1,p2) -> PEmul(term_to_z_expr p1, term_to_z_expr p2)
| Add(p1,p2) -> PEadd(term_to_z_expr p1, term_to_z_expr p2)
| Opp p -> PEopp (term_to_z_expr p)
| Pow(t,n) -> PEpow (term_to_z_expr t,Ml2C.n n)
| Sub(t1,t2) -> PEsub (term_to_z_expr t1, term_to_z_expr t2)
| _ -> failwith "term_to_z_expr: not implemented"
let term_to_z_pol e = Mc.norm_aux (Ml2C.z 0) (Ml2C.z 1) Mc.zplus Mc.zmult Mc.zminus Mc.zopp Mc.zeq_bool (term_to_z_expr e)
let z_cert_of_pos pos =
let s,pos = (scale_certificate pos) in
let rec _cert_of_pos = function
Axiom_eq i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_le i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_lt i -> Mc.PsatzIn (Ml2C.nat i)
| Monoid l -> product l
| Rational_eq n | Rational_le n | Rational_lt n ->
if compare_num n (Int 0) = 0 then Mc.PsatzZ else
Mc.PsatzC (Ml2C.bigint (big_int_of_num n))
| Square t -> Mc.PsatzSquare (term_to_z_pol t)
| Eqmul (t, y) -> Mc.PsatzMulC(term_to_z_pol t, _cert_of_pos y)
| Sum (y, z) -> Mc.PsatzAdd (_cert_of_pos y, _cert_of_pos z)
| Product (y, z) -> Mc.PsatzMulE (_cert_of_pos y, _cert_of_pos z) in
simplify_cone z_spec (_cert_of_pos pos)
(* Local Variables: *)
coding : utf-8
(* End: *)
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/CoqIDE/coq-8.2pl2/plugins/micromega/certificate.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
**********************************************************************
We take as input a list of polynomials [p1...pn] and return an unfeasibility
certificate polynomial.
A monomial is represented by a multiset of variables
The monomial that corresponds to a constant
The monomial 'x'
Get the degre of a variable in a monomial
Multiply a monomial by a variable
Product of monomials
Total ordering of monomials
A polynomial is a map of monomials
normalisation bug : 0*x ...
Get the coefficient of monomial mn
The polynomial 1.x
The constant polynomial
The addition of a monomial
* Design choice: empty is not a polynomial
I do not remember why ....
*
The product by a monomial
Certificates are elements of the cone such that P = 0
(SysSetAlt(Vector . ) )
module Vect = Fourier . Vect
open Fourier . Cstr
(* fold_left followed by a rev !
Gather the monomials: HINT add up of the polynomials
For each monomial, compute a constraint
I need at least something strictly positive
Add the positivity constraint
For Q, this is a pity that the certificate has been scaled
-- at a lower layer, certificates are using nums...
should not use rats_to_ints
Fourier elimination should handle >
to_constant
No certificate
make_certificate to_constant
zprover....
keep track of enumerated vectors
The prover is (probably) incomplete --
only searching for naive cutting planes
we already know the bound -- don't compute it again
find the candidate with the smallest range
Printf.printf "%s in %s\n" (Vect.string vect) (string_of_intrvl i) ;
This might be a cutting plane
x <= ub -> x > ub
lb <= x -> lb > x
let enum =
let t0 = Sys.time () in
Local Variables:
End: | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
: A reflexive tactic using the
( / ) 2006 - 2008
open . Polynomial
open Big_int
open Num
open Sos_lib
module Mc = Micromega
module Ml2C = Mutils.CamlToCoq
module C2Ml = Mutils.CoqToCaml
let (<+>) = add_num
let (<->) = minus_num
let (<*>) = mult_num
type var = Mc.positive
module Monomial :
sig
type t
val const : t
val var : var -> t
val find : var -> t -> int
val mult : var -> t -> t
val prod : t -> t -> t
val compare : t -> t -> int
val pp : out_channel -> t -> unit
val fold : (var -> int -> 'a -> 'a) -> t -> 'a -> 'a
end
=
struct
module Map = Map.Make(struct type t = var let compare = Pervasives.compare end)
open Map
type t = int Map.t
let const = Map.empty
let var x = Map.add x 1 Map.empty
let find x m = try find x m with Not_found -> 0
let mult x m = add x ( (find x m) + 1) m
let prod m1 m2 = Map.fold (fun k d m -> add k ((find k m) + d) m) m1 m2
let compare m1 m2 = Map.compare Pervasives.compare m1 m2
let pp o m = Map.iter (fun k v ->
if v = 1 then Printf.fprintf o "x%i." (C2Ml.index k)
else Printf.fprintf o "x%i^%i." (C2Ml.index k) v) m
let fold = fold
end
module Poly :
This is probably a naive implementation
( expected to be fast enough - Coq is probably the bottleneck )
* The new ring contribution is using a sparse Horner representation .
This is probably a naive implementation
(expected to be fast enough - Coq is probably the bottleneck)
*The new ring contribution is using a sparse Horner representation.
*)
sig
type t
val get : Monomial.t -> t -> num
val variable : var -> t
val add : Monomial.t -> num -> t -> t
val constant : num -> t
val mult : Monomial.t -> num -> t -> t
val product : t -> t -> t
val addition : t -> t -> t
val uminus : t -> t
val fold : (Monomial.t -> num -> 'a -> 'a) -> t -> 'a -> 'a
val pp : out_channel -> t -> unit
val compare : t -> t -> int
val is_null : t -> bool
end =
struct
module P = Map.Make(Monomial)
open P
type t = num P.t
let pp o p = P.iter (fun k v ->
if compare_num v (Int 0) <> 0
then
if Monomial.compare Monomial.const k = 0
then Printf.fprintf o "%s " (string_of_num v)
else Printf.fprintf o "%s*%a " (string_of_num v) Monomial.pp k) p
let get : Monomial.t -> t -> num =
fun mn p -> try find mn p with Not_found -> (Int 0)
let variable : var -> t =
fun x -> add (Monomial.var x) (Int 1) empty
let constant : num -> t =
fun c -> add (Monomial.const) c empty
let add : Monomial.t -> num -> t -> t =
fun mn v p ->
let vl = (get mn p) <+> v in
add mn vl p
let mult : Monomial.t -> num -> t -> t =
fun mn v p ->
fold (fun mn' v' res -> P.add (Monomial.prod mn mn') (v<*>v') res) p empty
let addition : t -> t -> t =
fun p1 p2 -> fold (fun mn v p -> add mn v p) p1 p2
let product : t -> t -> t =
fun p1 p2 ->
fold (fun mn v res -> addition (mult mn v p2) res ) p1 empty
let uminus : t -> t =
fun p -> map (fun v -> minus_num v) p
let fold = P.fold
let is_null p = fold (fun mn vl b -> b & sign_num vl = 0) p true
let compare = compare compare_num
end
open Mutils
type 'a number_spec = {
bigint_to_number : big_int -> 'a;
number_to_num : 'a -> num;
zero : 'a;
unit : 'a;
mult : 'a -> 'a -> 'a;
eqb : 'a -> 'a -> bool
}
let z_spec = {
bigint_to_number = Ml2C.bigint ;
number_to_num = (fun x -> Big_int (C2Ml.z_big_int x));
zero = Mc.Z0;
unit = Mc.Zpos Mc.XH;
mult = Mc.zmult;
eqb = Mc.zeq_bool
}
let q_spec = {
bigint_to_number = (fun x -> {Mc.qnum = Ml2C.bigint x; Mc.qden = Mc.XH});
number_to_num = C2Ml.q_to_num;
zero = {Mc.qnum = Mc.Z0;Mc.qden = Mc.XH};
unit = {Mc.qnum = (Mc.Zpos Mc.XH) ; Mc.qden = Mc.XH};
mult = Mc.qmult;
eqb = Mc.qeq_bool
}
let r_spec = z_spec
let dev_form n_spec p =
let rec dev_form p =
match p with
| Mc.PEc z -> Poly.constant (n_spec.number_to_num z)
| Mc.PEX v -> Poly.variable v
| Mc.PEmul(p1,p2) ->
let p1 = dev_form p1 in
let p2 = dev_form p2 in
Poly.product p1 p2
| Mc.PEadd(p1,p2) -> Poly.addition (dev_form p1) (dev_form p2)
| Mc.PEopp p -> Poly.uminus (dev_form p)
| Mc.PEsub(p1,p2) -> Poly.addition (dev_form p1) (Poly.uminus (dev_form p2))
| Mc.PEpow(p,n) ->
let p = dev_form p in
let n = C2Ml.n n in
let rec pow n =
if n = 0
then Poly.constant (n_spec.number_to_num n_spec.unit)
else Poly.product p (pow (n-1)) in
pow n in
dev_form p
let monomial_to_polynomial mn =
Monomial.fold
(fun v i acc ->
let mn = if i = 1 then Mc.PEX v else Mc.PEpow (Mc.PEX v ,Ml2C.n i) in
if acc = Mc.PEc (Mc.Zpos Mc.XH)
then mn
else Mc.PEmul(mn,acc))
mn
(Mc.PEc (Mc.Zpos Mc.XH))
let list_to_polynomial vars l =
assert (List.for_all (fun x -> ceiling_num x =/ x) l);
let var x = monomial_to_polynomial (List.nth vars x) in
let rec xtopoly p i = function
| [] -> p
| c::l -> if c =/ (Int 0) then xtopoly p (i+1) l
else let c = Mc.PEc (Ml2C.bigint (numerator c)) in
let mn =
if c = Mc.PEc (Mc.Zpos Mc.XH)
then var i
else Mc.PEmul (c,var i) in
let p' = if p = Mc.PEc Mc.Z0 then mn else
Mc.PEadd (mn, p) in
xtopoly p' (i+1) l in
xtopoly (Mc.PEc Mc.Z0) 0 l
let rec fixpoint f x =
let y' = f x in
if y' = x then y'
else fixpoint f y'
let rec_simpl_cone n_spec e =
let simpl_cone =
Mc.simpl_cone n_spec.zero n_spec.unit n_spec.mult n_spec.eqb in
let rec rec_simpl_cone = function
| Mc.PsatzMulE(t1, t2) ->
simpl_cone (Mc.PsatzMulE (rec_simpl_cone t1, rec_simpl_cone t2))
| Mc.PsatzAdd(t1,t2) ->
simpl_cone (Mc.PsatzAdd (rec_simpl_cone t1, rec_simpl_cone t2))
| x -> simpl_cone x in
rec_simpl_cone e
let simplify_cone n_spec c = fixpoint (rec_simpl_cone n_spec) c
type cone_prod =
Const of cone
| Ideal of cone *cone
| Mult of cone * cone
| Other of cone
and cone = Mc.zWitness
let factorise_linear_cone c =
let rec cone_list c l =
match c with
| Mc.PsatzAdd (x,r) -> cone_list r (x::l)
| _ -> c :: l in
let factorise c1 c2 =
match c1 , c2 with
| Mc.PsatzMulC(x,y) , Mc.PsatzMulC(x',y') ->
if x = x' then Some (Mc.PsatzMulC(x, Mc.PsatzAdd(y,y'))) else None
| Mc.PsatzMulE(x,y) , Mc.PsatzMulE(x',y') ->
if x = x' then Some (Mc.PsatzMulE(x, Mc.PsatzAdd(y,y'))) else None
| _ -> None in
let rec rebuild_cone l pending =
match l with
| [] -> (match pending with
| None -> Mc.PsatzZ
| Some p -> p
)
| e::l ->
(match pending with
| None -> rebuild_cone l (Some e)
| Some p -> (match factorise p e with
| None -> Mc.PsatzAdd(p, rebuild_cone l (Some e))
| Some f -> rebuild_cone l (Some f) )
) in
(rebuild_cone (List.sort Pervasives.compare (cone_list c [])) None)
The binding with Fourier might be a bit obsolete
-- how does it handle equalities ?
-- how does it handle equalities ? *)
To begin with , we search for certificates of the form :
a1.p1 + ... an.pn + b1.q1 + ... + bn.qn + c = 0
where pi > = 0 qi > 0
ai > = 0
bi > = 0
Sum bi + c > = 1
This is a linear problem : each monomial is considered as a variable .
Hence , we can use fourier .
The variable c is at index 0
a1.p1 + ... an.pn + b1.q1 +... + bn.qn + c = 0
where pi >= 0 qi > 0
ai >= 0
bi >= 0
Sum bi + c >= 1
This is a linear problem: each monomial is considered as a variable.
Hence, we can use fourier.
The variable c is at index 0
*)
open Mfourier
module Fourier = Fourier(Vector . VList)(SysSet(Vector . VList ) )
module . VSparse)(SysSetAlt(Vector . VSparse ) )
let constrain_monomial mn l =
let coeffs = List.fold_left (fun acc p -> (Poly.get mn p)::acc) [] l in
if mn = Monomial.const
then
{ coeffs = Vect.from_list ((Big_int unit_big_int):: (List.rev coeffs)) ;
op = Eq ;
cst = Big_int zero_big_int }
else
{ coeffs = Vect.from_list ((Big_int zero_big_int):: (List.rev coeffs)) ;
op = Eq ;
cst = Big_int zero_big_int }
let positivity l =
let rec xpositivity i l =
match l with
| [] -> []
| (_,Mc.Equal)::l -> xpositivity (i+1) l
| (_,_)::l ->
{coeffs = Vect.update (i+1) (fun _ -> Int 1) Vect.null ;
op = Ge ;
cst = Int 0 } :: (xpositivity (i+1) l)
in
xpositivity 0 l
let string_of_op = function
| Mc.Strict -> "> 0"
| Mc.NonStrict -> ">= 0"
| Mc.Equal -> "= 0"
| Mc.NonEqual -> "<> 0"
If the certificate includes at least one strict inequality ,
the obtained polynomial can also be 0
the obtained polynomial can also be 0 *)
let build_linear_system l =
let l' = List.map fst l in
let monomials =
List.fold_left (fun acc p -> Poly.addition p acc) (Poly.constant (Int 0)) l'
let s0 =
Poly.fold (fun mn _ res -> (constrain_monomial mn l')::res) monomials [] in
let strict = {
coeffs = Vect.from_list ((Big_int unit_big_int)::
(List.map (fun (x,y) ->
match y with Mc.Strict ->
Big_int unit_big_int
| _ -> Big_int zero_big_int) l));
op = Ge ; cst = Big_int unit_big_int } in
{coeffs = Vect.from_list ([Big_int unit_big_int]) ;
op = Ge ;
cst = Big_int zero_big_int}::(strict::(positivity l)@s0)
let big_int_to_z = Ml2C.bigint
let make_certificate n_spec (cert,li) =
let bint_to_cst = n_spec.bigint_to_number in
match cert with
| [] -> failwith "empty_certificate"
| e::cert' ->
let cst = match compare_big_int e zero_big_int with
| 0 -> Mc.PsatzZ
| 1 -> Mc.PsatzC (bint_to_cst e)
| _ -> failwith "positivity error"
in
let rec scalar_product cert l =
match cert with
| [] -> Mc.PsatzZ
| c::cert -> match l with
| [] -> failwith "make_certificate(1)"
| i::l ->
let r = scalar_product cert l in
match compare_big_int c zero_big_int with
| -1 -> Mc.PsatzAdd (
Mc.PsatzMulC (Mc.Pc ( bint_to_cst c), Mc.PsatzIn (Ml2C.nat i)),
r)
| 0 -> r
| _ -> Mc.PsatzAdd (
Mc.PsatzMulE (Mc.PsatzC (bint_to_cst c), Mc.PsatzIn (Ml2C.nat i)),
r) in
((factorise_linear_cone
(simplify_cone n_spec (Mc.PsatzAdd (cst, scalar_product cert' li)))))
exception Found of Monomial.t
exception Strict
let primal l =
let vr = ref 0 in
let module Mmn = Map.Make(Monomial) in
let vect_of_poly map p =
Poly.fold (fun mn vl (map,vect) ->
if mn = Monomial.const
then (map,vect)
else
let (mn,m) = try (Mmn.find mn map,map) with Not_found -> let res = (!vr, Mmn.add mn !vr map) in incr vr ; res in
(m,if sign_num vl = 0 then vect else (mn,vl)::vect)) p (map,[]) in
let op_op = function Mc.NonStrict -> Ge |Mc.Equal -> Eq | _ -> raise Strict in
let cmp x y = Pervasives.compare (fst x) (fst y) in
snd (List.fold_right (fun (p,op) (map,l) ->
let (mp,vect) = vect_of_poly map p in
let cstr = {coeffs = List.sort cmp vect; op = op_op op ; cst = minus_num (Poly.get Monomial.const p)} in
(mp,cstr::l)) l (Mmn.empty,[]))
let dual_raw_certificate (l: (Poly.t * Mc.op1) list) =
List.iter ( fun ( p , op ) - > Printf.fprintf stdout " % a % s 0\n " Poly.pp p ( string_of_op op ) ) l ;
let sys = build_linear_system l in
try
match Fourier.find_point sys with
| Inr _ -> None
| Inl cert -> Some (rats_to_ints (Vect.to_list cert))
with x ->
if debug
then (Printf.printf "raw certificate %s" (Printexc.to_string x);
flush stdout) ;
None
let raw_certificate l =
try
let p = primal l in
match Fourier.find_point p with
| Inr prf ->
if debug then Printf.printf "AProof : %a\n" pp_proof prf ;
let cert = List.map (fun (x,n) -> x+1,n) (fst (List.hd (Proof.mk_proof p prf))) in
if debug then Printf.printf "CProof : %a" Vect.pp_vect cert ;
Some (rats_to_ints (Vect.to_list cert))
| Inl _ -> None
with Strict ->
dual_raw_certificate l
let (lc,li) = List.split l in
match raw_certificate lc with
let linear_prover n_spec l =
let li = List.combine l (interval 0 (List.length l -1)) in
let (l1,l') = List.partition
(fun (x,_) -> if snd x = Mc.NonEqual then true else false) li in
let l' = List.map
(fun ((x,y),i) -> match y with
Mc.NonEqual -> failwith "cannot happen"
| y -> ((dev_form n_spec x, y),i)) l' in
n_spec
let linear_prover n_spec l =
try linear_prover n_spec l with
x -> (print_string (Printexc.to_string x); None)
let linear_prover_with_cert spec l =
match linear_prover spec l with
| None -> None
| Some cert -> Some (make_certificate spec cert)
I need to gather the set of variables --- >
Then go for fold
Once I have an interval , I need a certificate : 2 other fourier elims .
( I could probably get the certificate directly
as it is done in the fourier contrib . )
Then go for fold
Once I have an interval, I need a certificate : 2 other fourier elims.
(I could probably get the certificate directly
as it is done in the fourier contrib.)
*)
let make_linear_system l =
let l' = List.map fst l in
let monomials = List.fold_left (fun acc p -> Poly.addition p acc)
(Poly.constant (Int 0)) l' in
let monomials = Poly.fold
(fun mn _ l -> if mn = Monomial.const then l else mn::l) monomials [] in
(List.map (fun (c,op) ->
{coeffs = Vect.from_list (List.map (fun mn -> (Poly.get mn c)) monomials) ;
op = op ;
cst = minus_num ( (Poly.get Monomial.const c))}) l
,monomials)
let pplus x y = Mc.PEadd(x,y)
let pmult x y = Mc.PEmul(x,y)
let pconst x = Mc.PEc x
let popp x = Mc.PEopp x
let debug = false
let rec mem p x l =
match l with [] -> false | e::l -> if p x e then true else mem p x l
let rec remove_assoc p x l =
match l with [] -> [] | e::l -> if p x (fst e) then
remove_assoc p x l else e::(remove_assoc p x l)
let eq x y = Vect.compare x y = 0
let remove e l = List.fold_left (fun l x -> if eq x e then l else x::l) [] l
let candidates sys =
let ll = List.fold_right (
fun (e,k) r ->
match k with
| Mc.NonStrict -> (dev_form z_spec e , Ge)::r
| Mc.Equal -> (dev_form z_spec e , Eq)::r
| _ -> failwith "Cannot happen candidates") sys [] in
let (sys,var_mn) = make_linear_system ll in
let vars = mapi (fun _ i -> Vect.set i (Int 1) Vect.null) var_mn in
(List.fold_left (fun l cstr ->
let gcd = Big_int (Vect.gcd cstr.coeffs) in
if gcd =/ (Int 1) && cstr.op = Eq
then l
else (Vect.mul (Int 1 // gcd) cstr.coeffs)::l) [] sys) @ vars
let rec xzlinear_prover planes sys =
match linear_prover z_spec sys with
| Some prf -> Some (Mc.RatProof (make_certificate z_spec prf,Mc.DoneProof))
Grrr - linear_prover is also calling ' make_linear_system '
let ll = List.fold_right (fun (e,k) r -> match k with
Mc.NonEqual -> r
| k -> (dev_form z_spec e ,
match k with
Mc.NonStrict -> Ge
| Mc.Equal -> Eq
| Mc.Strict | Mc.NonEqual -> failwith "Cannot happen") :: r) sys [] in
let (ll,var) = make_linear_system ll in
let candidates = List.fold_left (fun acc vect ->
match Fourier.optimise vect ll with
| None -> acc
| Some i ->
flush stdout ;
(vect,i) ::acc) [] planes in
let smallest_interval =
match List.fold_left (fun (x1,i1) (x2,i2) ->
if Itv.smaller_itv i1 i2
then (x1,i1) else (x2,i2)) (Vect.null,(None,None)) candidates
with
| (x,(Some i, Some j)) -> Some(i,x,j)
in
match smallest_interval with
| Some (lb,e,ub) ->
let (lbn,lbd) =
(Ml2C.bigint (sub_big_int (numerator lb) unit_big_int),
Ml2C.bigint (denominator lb)) in
let (ubn,ubd) =
(Ml2C.bigint (add_big_int unit_big_int (numerator ub)) ,
Ml2C.bigint (denominator ub)) in
let expr = list_to_polynomial var (Vect.to_list e) in
(match
linear_prover z_spec
((pplus (pmult (pconst ubd) expr) (popp (pconst ubn)),
Mc.NonStrict) :: sys),
linear_prover z_spec
((pplus (popp (pmult (pconst lbd) expr)) (pconst lbn),
Mc.NonStrict)::sys)
with
| Some cub , Some clb ->
(match zlinear_enum (remove e planes) expr
(ceiling_num lb) (floor_num ub) sys
with
| None -> None
| Some prf ->
let bound_proof (c,l) = make_certificate z_spec (List.tl c , List.tl (List.map (fun x -> x -1) l)) in
, expr , Ml2C.q ub ,
| _ -> None
)
| _ -> None
and zlinear_enum planes expr clb cub l =
if clb >/ cub
then Some []
else
let pexpr = pplus (popp (pconst (Ml2C.bigint (numerator clb)))) expr in
let sys' = (pexpr, Mc.Equal)::l in
match xzlinear_prover planes sys' with
| None -> if debug then print_string "zlp?"; None
| Some prf -> if debug then print_string "zlp!";
match zlinear_enum planes expr (clb +/ (Int 1)) cub l with
| None -> None
| Some prfl -> Some (prf :: prfl)
let zlinear_prover sys =
let candidates = candidates sys in
Printf.printf " candidates % d " ( candidates ) ;
let res = xzlinear_prover candidates sys in
Printf.printf " Time prover : % f " ( Sys.time ( ) - . t0 ) ;
open Sos_types
open Mutils
let rec scale_term t =
match t with
| Zero -> unit_big_int , Zero
| Const n -> (denominator n) , Const (Big_int (numerator n))
| Var n -> unit_big_int , Var n
| Inv _ -> failwith "scale_term : not implemented"
| Opp t -> let s, t = scale_term t in s, Opp t
| Add(t1,t2) -> let s1,y1 = scale_term t1 and s2,y2 = scale_term t2 in
let g = gcd_big_int s1 s2 in
let s1' = div_big_int s1 g in
let s2' = div_big_int s2 g in
let e = mult_big_int g (mult_big_int s1' s2') in
if (compare_big_int e unit_big_int) = 0
then (unit_big_int, Add (y1,y2))
else e, Add (Mul(Const (Big_int s2'), y1),
Mul (Const (Big_int s1'), y2))
| Sub _ -> failwith "scale term: not implemented"
| Mul(y,z) -> let s1,y1 = scale_term y and s2,y2 = scale_term z in
mult_big_int s1 s2 , Mul (y1, y2)
| Pow(t,n) -> let s,t = scale_term t in
power_big_int_positive_int s n , Pow(t,n)
| _ -> failwith "scale_term : not implemented"
let scale_term t =
let (s,t') = scale_term t in
s,t'
let get_index_of_ith_match f i l =
let rec get j res l =
match l with
| [] -> failwith "bad index"
| e::l -> if f e
then
(if j = i then res else get (j+1) (res+1) l )
else get j (res+1) l in
get 0 0 l
let rec scale_certificate pos = match pos with
| Axiom_eq i -> unit_big_int , Axiom_eq i
| Axiom_le i -> unit_big_int , Axiom_le i
| Axiom_lt i -> unit_big_int , Axiom_lt i
| Monoid l -> unit_big_int , Monoid l
| Rational_eq n -> (denominator n) , Rational_eq (Big_int (numerator n))
| Rational_le n -> (denominator n) , Rational_le (Big_int (numerator n))
| Rational_lt n -> (denominator n) , Rational_lt (Big_int (numerator n))
| Square t -> let s,t' = scale_term t in
mult_big_int s s , Square t'
| Eqmul (t, y) -> let s1,y1 = scale_term t and s2,y2 = scale_certificate y in
mult_big_int s1 s2 , Eqmul (y1,y2)
| Sum (y, z) -> let s1,y1 = scale_certificate y
and s2,y2 = scale_certificate z in
let g = gcd_big_int s1 s2 in
let s1' = div_big_int s1 g in
let s2' = div_big_int s2 g in
mult_big_int g (mult_big_int s1' s2'),
Sum (Product(Rational_le (Big_int s2'), y1),
Product (Rational_le (Big_int s1'), y2))
| Product (y, z) ->
let s1,y1 = scale_certificate y and s2,y2 = scale_certificate z in
mult_big_int s1 s2 , Product (y1,y2)
open Micromega
let rec term_to_q_expr = function
| Const n -> PEc (Ml2C.q n)
| Zero -> PEc ( Ml2C.q (Int 0))
| Var s -> PEX (Ml2C.index
(int_of_string (String.sub s 1 (String.length s - 1))))
| Mul(p1,p2) -> PEmul(term_to_q_expr p1, term_to_q_expr p2)
| Add(p1,p2) -> PEadd(term_to_q_expr p1, term_to_q_expr p2)
| Opp p -> PEopp (term_to_q_expr p)
| Pow(t,n) -> PEpow (term_to_q_expr t,Ml2C.n n)
| Sub(t1,t2) -> PEsub (term_to_q_expr t1, term_to_q_expr t2)
| _ -> failwith "term_to_q_expr: not implemented"
let term_to_q_pol e = Mc.norm_aux (Ml2C.q (Int 0)) (Ml2C.q (Int 1)) Mc.qplus Mc.qmult Mc.qminus Mc.qopp Mc.qeq_bool (term_to_q_expr e)
let rec product l =
match l with
| [] -> Mc.PsatzZ
| [i] -> Mc.PsatzIn (Ml2C.nat i)
| i ::l -> Mc.PsatzMulE(Mc.PsatzIn (Ml2C.nat i), product l)
let q_cert_of_pos pos =
let rec _cert_of_pos = function
Axiom_eq i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_le i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_lt i -> Mc.PsatzIn (Ml2C.nat i)
| Monoid l -> product l
| Rational_eq n | Rational_le n | Rational_lt n ->
if compare_num n (Int 0) = 0 then Mc.PsatzZ else
Mc.PsatzC (Ml2C.q n)
| Square t -> Mc.PsatzSquare (term_to_q_pol t)
| Eqmul (t, y) -> Mc.PsatzMulC(term_to_q_pol t, _cert_of_pos y)
| Sum (y, z) -> Mc.PsatzAdd (_cert_of_pos y, _cert_of_pos z)
| Product (y, z) -> Mc.PsatzMulE (_cert_of_pos y, _cert_of_pos z) in
simplify_cone q_spec (_cert_of_pos pos)
let rec term_to_z_expr = function
| Const n -> PEc (Ml2C.bigint (big_int_of_num n))
| Zero -> PEc ( Z0)
| Var s -> PEX (Ml2C.index
(int_of_string (String.sub s 1 (String.length s - 1))))
| Mul(p1,p2) -> PEmul(term_to_z_expr p1, term_to_z_expr p2)
| Add(p1,p2) -> PEadd(term_to_z_expr p1, term_to_z_expr p2)
| Opp p -> PEopp (term_to_z_expr p)
| Pow(t,n) -> PEpow (term_to_z_expr t,Ml2C.n n)
| Sub(t1,t2) -> PEsub (term_to_z_expr t1, term_to_z_expr t2)
| _ -> failwith "term_to_z_expr: not implemented"
let term_to_z_pol e = Mc.norm_aux (Ml2C.z 0) (Ml2C.z 1) Mc.zplus Mc.zmult Mc.zminus Mc.zopp Mc.zeq_bool (term_to_z_expr e)
let z_cert_of_pos pos =
let s,pos = (scale_certificate pos) in
let rec _cert_of_pos = function
Axiom_eq i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_le i -> Mc.PsatzIn (Ml2C.nat i)
| Axiom_lt i -> Mc.PsatzIn (Ml2C.nat i)
| Monoid l -> product l
| Rational_eq n | Rational_le n | Rational_lt n ->
if compare_num n (Int 0) = 0 then Mc.PsatzZ else
Mc.PsatzC (Ml2C.bigint (big_int_of_num n))
| Square t -> Mc.PsatzSquare (term_to_z_pol t)
| Eqmul (t, y) -> Mc.PsatzMulC(term_to_z_pol t, _cert_of_pos y)
| Sum (y, z) -> Mc.PsatzAdd (_cert_of_pos y, _cert_of_pos z)
| Product (y, z) -> Mc.PsatzMulE (_cert_of_pos y, _cert_of_pos z) in
simplify_cone z_spec (_cert_of_pos pos)
coding : utf-8
|
8f49dfe800cdf3e3793eaceb1176fb9465a2e15d8c3e880c8ecf503c7945907b | wargrey/graphics | hsb.rkt | #lang typed/racket/base
(provide (all-defined-out))
(require racket/math)
(require "../misc.rkt")
(define rgb->hue : (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum Flonum))
(lambda [red green blue]
(define-values (M m) (values (max red green blue) (min red green blue)))
(define chroma : Flonum (- M m))
(define hue : Flonum
(cond [(zero? chroma) +nan.0]
[(= M green) (* 60.0 (+ (/ (- blue red) chroma) 2.0))]
[(= M blue) (* 60.0 (+ (/ (- red green) chroma) 4.0))]
[(< green blue) (* 60.0 (+ (/ (- green blue) chroma) 6.0))]
[else (* 60.0 (/ (- green blue) chroma))]))
(values M m chroma hue)))
(define hue->rgb : (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum))
(lambda [hue chroma m]
(define hue/60 : Flonum (if (nan? hue) 6.0 (/ hue 60.0)))
(define hue. : Integer (exact-floor hue/60))
X = C(1-|H ' mod 2 - 1| )
(define x : Flonum (* chroma (- 1.0 (abs (- (exact->inexact (remainder hue. 2)) (- (exact->inexact hue.) hue/60) 1.0)))))
(define-values (red green blue)
(case hue.
[(0) (values chroma x 0.0)]
[(1) (values x chroma 0.0)]
[(2) (values 0.0 chroma x)]
[(3) (values 0.0 x chroma)]
[(4) (values x 0.0 chroma)]
[(5) (values chroma 0.0 x)]
[else (values 0.0 0.0 0.0)]))
(values (+ red m) (+ green m) (+ blue m))))
(define hsi-sector->rgb : (-> Flonum Flonum Flonum (U 'red 'green 'blue) (Values Flonum Flonum Flonum))
(lambda [hue saturation intensity color]
(define flcosH/cos60-H : Flonum
(cond [(or (zero? hue) (= hue 120.0)) 2.0]
[else (let ([H (* hue (/ pi 180.0))])
(/ (cos H) (cos (- (/ pi 3.0) H))))]))
(define major : Flonum (* intensity (+ 1.0 (* saturation flcosH/cos60-H))))
(define midor : Flonum (* intensity (- 1.0 saturation)))
(define minor : Flonum (- (* 3.0 intensity) (+ major midor)))
(case color
[(red) (values major minor midor)]
[(green) (values midor major minor)]
[else (values minor midor major)])))
| null | https://raw.githubusercontent.com/wargrey/graphics/50751297f244a01ac734099b9a1e9be97cd36f3f/colorspace/digitama/hsb.rkt | racket | #lang typed/racket/base
(provide (all-defined-out))
(require racket/math)
(require "../misc.rkt")
(define rgb->hue : (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum Flonum))
(lambda [red green blue]
(define-values (M m) (values (max red green blue) (min red green blue)))
(define chroma : Flonum (- M m))
(define hue : Flonum
(cond [(zero? chroma) +nan.0]
[(= M green) (* 60.0 (+ (/ (- blue red) chroma) 2.0))]
[(= M blue) (* 60.0 (+ (/ (- red green) chroma) 4.0))]
[(< green blue) (* 60.0 (+ (/ (- green blue) chroma) 6.0))]
[else (* 60.0 (/ (- green blue) chroma))]))
(values M m chroma hue)))
(define hue->rgb : (-> Flonum Flonum Flonum (Values Flonum Flonum Flonum))
(lambda [hue chroma m]
(define hue/60 : Flonum (if (nan? hue) 6.0 (/ hue 60.0)))
(define hue. : Integer (exact-floor hue/60))
X = C(1-|H ' mod 2 - 1| )
(define x : Flonum (* chroma (- 1.0 (abs (- (exact->inexact (remainder hue. 2)) (- (exact->inexact hue.) hue/60) 1.0)))))
(define-values (red green blue)
(case hue.
[(0) (values chroma x 0.0)]
[(1) (values x chroma 0.0)]
[(2) (values 0.0 chroma x)]
[(3) (values 0.0 x chroma)]
[(4) (values x 0.0 chroma)]
[(5) (values chroma 0.0 x)]
[else (values 0.0 0.0 0.0)]))
(values (+ red m) (+ green m) (+ blue m))))
(define hsi-sector->rgb : (-> Flonum Flonum Flonum (U 'red 'green 'blue) (Values Flonum Flonum Flonum))
(lambda [hue saturation intensity color]
(define flcosH/cos60-H : Flonum
(cond [(or (zero? hue) (= hue 120.0)) 2.0]
[else (let ([H (* hue (/ pi 180.0))])
(/ (cos H) (cos (- (/ pi 3.0) H))))]))
(define major : Flonum (* intensity (+ 1.0 (* saturation flcosH/cos60-H))))
(define midor : Flonum (* intensity (- 1.0 saturation)))
(define minor : Flonum (- (* 3.0 intensity) (+ major midor)))
(case color
[(red) (values major minor midor)]
[(green) (values midor major minor)]
[else (values minor midor major)])))
|
|
ae5ed6c83fcc2b1025cdb7515c5e274b938742ea7c8460247f38ff623c18699a | debug-ito/greskell | NonEmptyLike.hs | -- |
-- Module: Data.Greskell.NonEmptyLike
-- Description: Class of non-empty containers
Maintainer : < >
--
@since 1.0.0.0
module Data.Greskell.NonEmptyLike
( NonEmptyLike (..)
) where
import qualified Data.Foldable as F
import Data.List.NonEmpty (NonEmpty (..))
import Data.Semigroup (Semigroup, (<>))
import qualified Data.Semigroup as S
| Non - empty containers . Its cardinality is one or more .
--
@since 1.0.0.0
class F.Foldable t => NonEmptyLike t where
-- | Make a container with a single value.
singleton :: a -> t a
| Append two containers .
append :: t a -> t a -> t a
| Convert the container to ' NonEmpty ' list .
toNonEmpty :: t a -> NonEmpty a
-- | 'append' is '<>' from 'Semigroup'.
instance NonEmptyLike NonEmpty where
singleton a = a :| []
append = (<>)
toNonEmpty = id
-- | 'append' is '<>' from 'Semigroup'.
instance NonEmptyLike S.First where
singleton = S.First
append = (<>)
toNonEmpty (S.First a) = singleton a
-- | 'append' is '<>' from 'Semigroup'.
instance NonEmptyLike S.Last where
singleton = S.Last
append = (<>)
toNonEmpty (S.Last a) = singleton a
| null | https://raw.githubusercontent.com/debug-ito/greskell/ff21b8297a158cb4b5bafcbb85094cef462c5390/greskell/src/Data/Greskell/NonEmptyLike.hs | haskell | |
Module: Data.Greskell.NonEmptyLike
Description: Class of non-empty containers
| Make a container with a single value.
| 'append' is '<>' from 'Semigroup'.
| 'append' is '<>' from 'Semigroup'.
| 'append' is '<>' from 'Semigroup'. | Maintainer : < >
@since 1.0.0.0
module Data.Greskell.NonEmptyLike
( NonEmptyLike (..)
) where
import qualified Data.Foldable as F
import Data.List.NonEmpty (NonEmpty (..))
import Data.Semigroup (Semigroup, (<>))
import qualified Data.Semigroup as S
| Non - empty containers . Its cardinality is one or more .
@since 1.0.0.0
class F.Foldable t => NonEmptyLike t where
singleton :: a -> t a
| Append two containers .
append :: t a -> t a -> t a
| Convert the container to ' NonEmpty ' list .
toNonEmpty :: t a -> NonEmpty a
instance NonEmptyLike NonEmpty where
singleton a = a :| []
append = (<>)
toNonEmpty = id
instance NonEmptyLike S.First where
singleton = S.First
append = (<>)
toNonEmpty (S.First a) = singleton a
instance NonEmptyLike S.Last where
singleton = S.Last
append = (<>)
toNonEmpty (S.Last a) = singleton a
|
140de244890182659414d1408e19b7563922d82e1369eb0edd8ce71880808db3 | onedata/op-worker | storage_import_deletion.erl | %%%-------------------------------------------------------------------
@author
( C ) 2019 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%%--------------------------------------------------------------------
%%% @doc
%%% This module is responsible for detecting which files in the
%%% space with enabled auto storage import mechanism were deleted on
%%% storage and therefore should be deleted from the Onedata file system.
%%% It uses storage_sync_links to compare lists of files on the storage
%%% with files in the database.
%%% Functions in this module are called from master and slave jobs
%%% executed by storage_sync_traverse pool.
%%% @end
%%%-------------------------------------------------------------------
-module(storage_import_deletion).
-author("Jakub Kudzia").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/fslogic/data_access_control.hrl").
-include("proto/oneclient/fuse_messages.hrl").
-include("modules/storage/traverse/storage_traverse.hrl").
-include_lib("ctool/include/logging.hrl").
% API
-export([do_master_job/2, do_slave_job/2, get_master_job/1, delete_file_and_update_counters/3]).
-type master_job() :: storage_sync_traverse:master_job().
-type slave_job() :: storage_sync_traverse:slave_job().
-type file_meta_children() :: [file_meta:link()].
-type sync_links_children() :: [storage_sync_links:link()].
-type file_meta_listing_info() :: #{
is_last := boolean(), % Redundant field (can be obtained from pagination token) for easier matching in function clauses.
token => file_listing:pagination_token()
}.
-define(BATCH_SIZE, op_worker:get_env(storage_import_deletion_batch_size, 1000)).
%%%===================================================================
%%% API functions
%%%===================================================================
-spec get_master_job(master_job()) -> master_job().
get_master_job(Job = #storage_traverse_master{info = Info}) ->
Job#storage_traverse_master{
info = Info#{
deletion_job => true,
sync_links_token => #link_token{},
sync_links_children => [],
file_meta_token => undefined,
file_meta_children => []
}
}.
%%--------------------------------------------------------------------
%% @doc
%% Performs master job responsible for detecting which files in the
%% synchronized space were deleted on storage and therefore should be
%% deleted from the Onedata file system.
It compares list of children of directory associated with ,
%% acquired from storage_sync_links, with list of children of the directory
%% acquired from file_meta links.
%% The lists are sorted in the same order so it is possible to compare them in
%% linear time.
%% This job is executed by storage_sync_traverse pool.
%% Files that are missing on the storage_sync_links list are scheduled to be
%% deleted in slave jobs.
%% NOTE!!!
%% On storages traversed using ?TREE_ITERATOR (posix storages), only direct children are compared.
%% On storages traverse using ?FLAT_ITERATOR (object storages), whole file structure is compared.
%% Traversing whole file structure (on object storages) is performed
%% by scheduling master jobs for directories (virtual directories as they do not exist on storage but exist in
%% the Onedata file system)
%% NOTE!!!
Object storage must have ? CANONICAL_PATH_TYPE so the mechanism can understand the structure of files on
%% the storage.
%% @end
%%--------------------------------------------------------------------
-spec do_master_job(master_job(), traverse:master_job_extended_args()) -> {ok, traverse:master_job_map()}.
do_master_job(Job = #storage_traverse_master{
storage_file_ctx = StorageFileCtx,
info = #{
file_ctx := FileCtx,
sync_links_token := SLToken,
sync_links_children := SLChildren,
file_meta_token := FMToken,
file_meta_children := FMChildren,
iterator_type := IteratorType
}}, _Args) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
reset any_protected_child_changed in case of first batch job
case FMToken =:= undefined andalso SLToken =:= #link_token{} of
true -> storage_sync_info:set_any_protected_child_changed(StorageFileId, SpaceId, false);
false -> ok
end,
Result = try
case refill_file_meta_children(FMChildren, FileCtx, FMToken) of
{error, not_found} ->
{ok, #{}};
{[], #{is_last := true}} ->
{ok, #{finish_callback => finish_callback(Job)}};
{FMChildren2, ListExtendedInfo} ->
case refill_sync_links_children(SLChildren, StorageFileCtx, SLToken) of
{error, not_found} ->
{ok, #{}};
{SLChildren2, SLToken2} ->
{MasterJobs, SlaveJobs} = generate_deletion_jobs(Job, SLChildren2, SLToken2, FMChildren2, ListExtendedInfo),
storage_import_monitoring:increment_queue_length_histograms(SpaceId, length(SlaveJobs) + length(MasterJobs)),
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
storage_sync_info:increase_batches_to_process(StorageFileId, SpaceId, length(MasterJobs)),
{ok, #{
slave_jobs => SlaveJobs,
async_master_jobs => MasterJobs,
finish_callback => finish_callback(Job)
}}
end
end
catch
throw:?ENOENT ->
{ok, #{}}
end,
case IteratorType of
?FLAT_ITERATOR ->
with ? FLAT_ITERATOR , deletion for root triggers traverse of whole storage ( which is
% compared with whole space file system) therefore we cannot delete whole storage_sync_links
tree now ( see storage_sync_links.erl for more details )
ok;
?TREE_ITERATOR ->
% with ?TREE_ITERATOR each directory is processed separately (separate deletion master_jobs)
% so we can safely delete its links tree
storage_sync_links:delete_recursive(StorageFileId, StorageId)
end,
storage_import_monitoring:mark_processed_job(SpaceId),
Result.
%%--------------------------------------------------------------------
%% @doc
%% Performs job responsible for deleting file, which has been deleted on
%% synced storage from the Onedata file system.
%% @end
%%--------------------------------------------------------------------
-spec do_slave_job(slave_job(), traverse:id()) -> ok.
do_slave_job(#storage_traverse_slave{info = #{file_ctx := FileCtx, storage_id := StorageId}}, _Task) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
maybe_delete_file_and_update_counters(FileCtx, SpaceId, StorageId).
%%===================================================================
Internal functions
%%===================================================================
-spec refill_sync_links_children(sync_links_children(), storage_file_ctx:ctx(),
datastore_links_iter:token()) -> {sync_links_children(), datastore_links_iter:token()} | {error, term()}.
refill_sync_links_children(CurrentChildren, StorageFileCtx, Token) ->
case length(CurrentChildren) < ?BATCH_SIZE of
true ->
RootStorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
ToFetch = ?BATCH_SIZE - length(CurrentChildren),
case storage_sync_links:list(RootStorageFileId, StorageId, Token, ToFetch) of
{{ok, NewChildren}, NewToken} ->
{CurrentChildren ++ NewChildren, NewToken};
Error = {error, _} ->
Error
end;
false ->
{CurrentChildren, Token}
end.
-spec refill_file_meta_children(file_meta_children(), file_ctx:ctx(),
file_listing:pagination_token() | undefined) ->
{file_meta_children(), file_meta_listing_info()} | {error, term()}.
refill_file_meta_children(CurrentChildren, FileCtx, Token) ->
case length(CurrentChildren) < ?BATCH_SIZE of
true ->
ListingOpts = case Token of
undefined -> #{tune_for_large_continuous_listing => true};
_ -> #{pagination_token => Token}
end,
FileUuid = file_ctx:get_logical_uuid_const(FileCtx),
ToFetch = ?BATCH_SIZE - length(CurrentChildren),
case file_listing:list(FileUuid, ListingOpts#{limit => ToFetch}) of
{ok, NewChildren, ListingPaginationToken} ->
{CurrentChildren ++ NewChildren, #{
is_last => file_listing:is_finished(ListingPaginationToken),
token => ListingPaginationToken
}};
Error = {error, _} ->
Error
end;
false ->
{CurrentChildren, #{token => Token, is_last => false}}
end.
-spec generate_deletion_jobs(master_job(), sync_links_children(), datastore_links_iter:token(),
file_meta_children(), file_meta_listing_info()) -> {[master_job()], [slave_job()]}.
generate_deletion_jobs(Job, SLChildren, SLToken, FMChildren, FMListExtendedInfo) ->
generate_deletion_jobs(Job, SLChildren, SLToken, FMChildren, FMListExtendedInfo, [], []).
%%-------------------------------------------------------------------
@private
%% @doc
This function is responsible for comparing two lists :
%% * list of file_meta children
%% * list of storage children, acquired from storage_sync_links
%% Both lists are sorted in the same order which allows to compare them
%% in linear time.
%% Function looks for files which are missing in the storage list and
%% are still present in the file_meta list.
%% Such files have potentially been deleted from storage and must be
%% checked whether they might be deleted from the system.
These checks are performed in returned from this function .
The function returns also MasterJob for next batch if one of compared
%% lists is empty.
%% NOTE!!!
%% On object storages detecting deletions is performed by a single traverse
%% over whole file system to avoid efficiency issues associated with
%% listing files in a canonical-like way on storage.
%% Files are listed using listobjects function which returns a flat structure.
%% Basing on the files absolute paths, we created storage_sync_links trees
%% which are then compared with file_meta links by this function.
%% In such case storage_sync_links are created for all files from the storage
%% and therefore we have to traverse whole structure, not only direct children.
%% @end
%%-------------------------------------------------------------------
-spec generate_deletion_jobs(master_job(), sync_links_children(), datastore_links_iter:token(),
file_meta_children(), file_meta_listing_info(), [master_job()], [slave_job()]) -> {[master_job()], [slave_job()]}.
generate_deletion_jobs(_Job, _SLChildren, _SLFinished, [], #{is_last := true}, MasterJobs, SlaveJobs) ->
% there are no more children in file_meta links, we can finish the job;
{MasterJobs, SlaveJobs};
generate_deletion_jobs(Job, SLChildren, SLToken, [], #{is_last := false, token := FMToken}, MasterJobs, SlaveJobs) ->
% sync_links must be processed after refilling file_meta children list
NextBatchJob = next_batch_master_job(Job, SLChildren, SLToken, [], FMToken),
{[NextBatchJob | MasterJobs], SlaveJobs};
generate_deletion_jobs(Job, [], #link_token{is_last = true}, FMChildren, #{is_last := true}, MasterJobs, SlaveJobs) ->
there are no more children in sync links and in file_meta ( except those in )
all left file_meta children ( those in ) must be deleted
SlaveJobs2 = lists:foldl(fun({_ChildName, ChildUuid}, AccIn) ->
% order of slave jobs doesn't matter as they will be processed in parallel
[new_slave_job(Job, ChildUuid) | AccIn]
end, SlaveJobs, FMChildren),
{MasterJobs, SlaveJobs2};
generate_deletion_jobs(Job, [], SLToken = #link_token{is_last = true}, FMChildren, #{token := FMToken}, MasterJobs, SlaveJobs) ->
% there are no more children in sync links
% all left file_meta children must be deleted
SlaveJobs2 = lists:foldl(fun({_ChildName, ChildUuid}, AccIn) ->
% order of slave jobs doesn't matter as they will be processed in parallel
[new_slave_job(Job, ChildUuid) | AccIn]
end, SlaveJobs, FMChildren),
% we must schedule next batch to refill file_meta children
NextBatchJob = next_batch_master_job(Job, [], SLToken, [], FMToken),
{[NextBatchJob | MasterJobs], SlaveJobs2};
generate_deletion_jobs(Job, [], SLToken, FMChildren, #{token := FMToken}, MasterJobs, SlaveJobs) ->
% all left file_meta children must be processed after refilling sl children
NextBatchJob = next_batch_master_job(Job, [], SLToken, FMChildren, FMToken),
{[NextBatchJob | MasterJobs], SlaveJobs};
generate_deletion_jobs(Job = #storage_traverse_master{info = #{iterator_type := ?TREE_ITERATOR}},
[{Name, _} | RestSLChildren], SLToken, [{Name, _ChildUuid} | RestFMChildren], FMListExtendedInfo,
MasterJobs, SlaveJobs
) ->
% file with name Name is on both lists therefore we cannot delete it
% on storage iterated using ?TREE_ITERATOR (block storage) we process only direct children of a directory,
% we do not go deeper in the files' structure as separate deletion_jobs will be scheduled for subdirectories
generate_deletion_jobs(Job, RestSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, MasterJobs, SlaveJobs);
generate_deletion_jobs(Job = #storage_traverse_master{info = #{iterator_type := ?FLAT_ITERATOR}},
[{Name, undefined} | RestSLChildren], SLToken, [{Name, _ChildUuid} | RestFMChildren], FMListExtendedInfo,
MasterJobs, SlaveJobs
) ->
% file with name Name is on both lists therefore we cannot delete it
% on storage iterated using ?FLAT_ITERATOR (object storage) if child link's target is undefined it
% means that it's a regular file's link
generate_deletion_jobs(Job, RestSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, MasterJobs, SlaveJobs);
generate_deletion_jobs(Job = #storage_traverse_master{info = #{iterator_type := ?FLAT_ITERATOR}},
[{Name, _} | RestSLChildren], SLToken, [{Name, Uuid} | RestFMChildren], FMListExtendedInfo,
MasterJobs, SlaveJobs
) ->
% file with name Name is on both lists therefore we cannot delete it
% on storage iterated using ?FLAT_ITERATOR (object storage) if child link's target is NOT undefined
% it means that it's a directory's link therefore we schedule master job for this directory,
% as with ?FLAT_ITERATOR deletion_jobs for root traverses whole file system
% for more info read the function's doc
ChildMasterJob = new_flat_iterator_child_master_job(Job, Name, Uuid),
generate_deletion_jobs(Job, RestSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, [ChildMasterJob | MasterJobs], SlaveJobs);
generate_deletion_jobs(Job, AllSLChildren = [{SLName, _} | _], SLToken,
[{FMName, ChildUuid} | RestFMChildren], FMListExtendedInfo, MasterJobs, SlaveJobs)
when SLName > FMName ->
% FMName is missing on the sync links list so it probably was deleted on storage
SlaveJob = new_slave_job(Job, ChildUuid),
generate_deletion_jobs(Job, AllSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, MasterJobs, [SlaveJob | SlaveJobs]);
generate_deletion_jobs(Job, [{SLName, _} | RestSLChildren], SLToken,
AllFMChildren = [{FMName, _} | _], FMListExtendedInfo, MasterJobs, SlaveJobs)
when SLName < FMName ->
SLName is missing on the file_meta list , we can ignore it , storage import will synchronise this file
generate_deletion_jobs(Job, RestSLChildren, SLToken, AllFMChildren, FMListExtendedInfo, MasterJobs, SlaveJobs).
-spec new_slave_job(master_job(), file_meta:uuid()) -> slave_job().
new_slave_job(#storage_traverse_master{storage_file_ctx = StorageFileCtx}, ChildUuid) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
#storage_traverse_slave{
info = #{
deletion_job => true,
file_ctx => file_ctx:new_by_uuid(ChildUuid, SpaceId),
storage_id => StorageId
}}.
-spec next_batch_master_job(master_job(), sync_links_children(), datastore_links_iter:token(),
file_meta_children(), datastore_links_iter:token()) -> master_job().
next_batch_master_job(Job = #storage_traverse_master{info = Info}, SLChildrenToProcess, SLToken, FMChildrenToProcess, FMToken) ->
Job#storage_traverse_master{
info = Info#{
sync_links_token => SLToken,
sync_links_children => SLChildrenToProcess,
file_meta_token => FMToken,
file_meta_children => FMChildrenToProcess
}}.
-spec new_flat_iterator_child_master_job(master_job(), file_meta:name(), file_meta:uuid()) -> master_job().
new_flat_iterator_child_master_job(Job = #storage_traverse_master{
storage_file_ctx = StorageFileCtx,
info = #{iterator_type := IteratorType}
}, ChildName, ChildUuid) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
ChildStorageFileId = filename:join([StorageFileId, ChildName]),
ChildCtx = flat_storage_iterator:get_virtual_directory_ctx(ChildStorageFileId, SpaceId, StorageId),
ChildMasterJob = Job#storage_traverse_master{
storage_file_ctx = ChildCtx,
info = #{
iterator_type => IteratorType,
file_ctx => file_ctx:new_by_uuid(ChildUuid, SpaceId)}
},
get_master_job(ChildMasterJob).
%%-------------------------------------------------------------------
%% @doc
%% This functions checks whether file is a directory or a regular file
%% and delegates decision about deleting or not deleting file to
%% suitable functions.
%% @end
%%-------------------------------------------------------------------
-spec maybe_delete_file_and_update_counters(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
maybe_delete_file_and_update_counters(FileCtx, SpaceId, StorageId) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
try
{SDHandle, FileCtx2} = storage_driver:new_handle(?ROOT_SESS_ID, FileCtx),
{IsStorageFileCreated, FileCtx3} = file_ctx:is_storage_file_created(FileCtx2),
{StorageFileId, FileCtx4} = file_ctx:get_storage_file_id(FileCtx3),
Uuid = file_ctx:get_logical_uuid_const(FileCtx3),
IsNotSymlink = not fslogic_file_id:is_symlink_uuid(Uuid),
{FileDoc, FileCtx5} = file_ctx:get_file_doc_including_deleted(FileCtx4),
{ok, ProtectionFlags} = dataset_eff_cache:get_eff_protection_flags(FileDoc),
IsProtected = ProtectionFlags =/= ?no_flags_mask,
case
IsNotSymlink
andalso IsStorageFileCreated
andalso (not storage_driver:exists(SDHandle))
andalso (not IsProtected)
of
true ->
% file is still missing on storage we can delete it from db
delete_file_and_update_counters(FileCtx5, SpaceId, StorageId);
false ->
case IsProtected of
true -> storage_sync_info:mark_protected_child_has_changed(filename:dirname(StorageFileId), SpaceId);
false -> ok
end,
storage_import_monitoring:mark_processed_job(SpaceId)
end
catch
throw:?ENOENT ->
storage_import_monitoring:mark_processed_job(SpaceId),
ok;
error:{badmatch, ?ERROR_NOT_FOUND} ->
storage_import_monitoring:mark_processed_job(SpaceId),
ok;
Error:Reason:Stacktrace ->
?error_stacktrace("~p:maybe_delete_file_and_update_counters failed due to ~p",
[?MODULE, {Error, Reason}], Stacktrace),
storage_import_monitoring:mark_failed_file(SpaceId)
end.
-spec delete_file_and_update_counters(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
delete_file_and_update_counters(FileCtx, SpaceId, StorageId) ->
case file_ctx:is_dir(FileCtx) of
{true, FileCtx2} ->
delete_dir_recursive_and_update_counters(FileCtx2, SpaceId, StorageId);
{false, FileCtx2} ->
delete_regular_file_and_update_counters(FileCtx2, SpaceId)
end.
%%-------------------------------------------------------------------
%% @doc
%% This function deletes directory recursively it and updates sync counters.
%% @end
%%-------------------------------------------------------------------
-spec delete_dir_recursive_and_update_counters(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
delete_dir_recursive_and_update_counters(FileCtx, SpaceId, StorageId) ->
{StorageFileId, FileCtx2} = file_ctx:get_storage_file_id(FileCtx),
{CanonicalPath, FileCtx3} = file_ctx:get_canonical_path(FileCtx2),
FileUuid = file_ctx:get_logical_uuid_const(FileCtx3),
delete_dir_recursive(FileCtx3, SpaceId, StorageId),
storage_import_logger:log_deletion(StorageFileId, CanonicalPath, FileUuid, SpaceId),
storage_import_monitoring:mark_deleted_file(SpaceId).
%%-------------------------------------------------------------------
%% @doc
%% This function deletes regular file and updates sync counters.
%% @end
%%-------------------------------------------------------------------
-spec delete_regular_file_and_update_counters(file_ctx:ctx(), od_space:id()) -> ok.
delete_regular_file_and_update_counters(FileCtx, SpaceId) ->
{StorageFileId, FileCtx2} = file_ctx:get_storage_file_id(FileCtx),
{CanonicalPath, FileCtx3} = file_ctx:get_canonical_path(FileCtx2),
FileUuid = file_ctx:get_logical_uuid_const(FileCtx3),
delete_file(FileCtx3),
storage_import_logger:log_deletion(StorageFileId, CanonicalPath, FileUuid, SpaceId),
storage_import_monitoring:mark_deleted_file(SpaceId).
%%-------------------------------------------------------------------
@private
%% @doc
%% Deletes directory that has been deleted on storage from the system.
%% It deletes directory recursively.
%% @end
%%-------------------------------------------------------------------
-spec delete_dir_recursive(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
delete_dir_recursive(FileCtx, SpaceId, StorageId) ->
RootUserCtx = user_ctx:new(?ROOT_SESS_ID),
ListOpts = #{tune_for_large_continuous_listing => true},
{ok, FileCtx2} = delete_children(FileCtx, RootUserCtx, ListOpts, SpaceId, StorageId),
delete_file(FileCtx2).
%%-------------------------------------------------------------------
@private
%% @doc
%% Recursively deletes children of directory.
%% @end
%%-------------------------------------------------------------------
-spec delete_children(file_ctx:ctx(), user_ctx:ctx(), file_listing:options(),
od_space:id(), storage:id()) -> {ok, file_ctx:ctx()}.
delete_children(FileCtx, UserCtx, ListOpts, SpaceId, StorageId) ->
try
{ChildrenCtxs, ListingPaginationToken, FileCtx2} = file_tree:list_children(
FileCtx, UserCtx, ListOpts
),
storage_import_monitoring:increment_queue_length_histograms(SpaceId, length(ChildrenCtxs)),
lists:foreach(fun(ChildCtx) ->
delete_file_and_update_counters(ChildCtx, SpaceId, StorageId)
end, ChildrenCtxs),
case file_listing:is_finished(ListingPaginationToken) of
true ->
{ok, FileCtx2};
false ->
delete_children(FileCtx2, UserCtx, #{pagination_token => ListingPaginationToken}, SpaceId, StorageId)
end
catch
throw:?ENOENT ->
{ok, FileCtx}
end.
%%-------------------------------------------------------------------
@private
%% @doc
%% Deletes file that has been deleted on storage from the system.
%% It deletes both regular files and directories.
%% NOTE!!!
%% This function does not delete directory recursively.
%% Directory children must be deleted before calling this function.
%% @end
%%-------------------------------------------------------------------
-spec delete_file(file_ctx:ctx()) -> ok.
delete_file(FileCtx) ->
try
fslogic_delete:handle_file_deleted_on_imported_storage(FileCtx)
catch
throw:?ENOENT ->
ok
end.
-spec finish_callback(storage_traverse:master_job()) -> function().
finish_callback(#storage_traverse_master{
storage_file_ctx = StorageFileCtx,
depth = Depth,
max_depth = MaxDepth,
info = #{file_ctx := FileCtx}
}) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
MTime = try
{#statbuf{st_mtime = STMtime}, _} = storage_file_ctx:stat(StorageFileCtx),
STMtime
catch
throw:?ENOENT ->
undefined
end,
?ON_SUCCESSFUL_SLAVE_JOBS(fun() ->
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
Guid = file_ctx:get_logical_guid_const(FileCtx),
case Depth =:= MaxDepth of
true -> storage_sync_info:mark_processed_batch(StorageFileId, SpaceId, Guid, undefined);
false -> storage_sync_info:mark_processed_batch(StorageFileId, SpaceId, Guid, MTime)
end
end). | null | https://raw.githubusercontent.com/onedata/op-worker/e0f8d666ff664a558050d1fc8f0e33f939a18030/src/modules/storage/import/storage_import_deletion.erl | erlang | -------------------------------------------------------------------
--------------------------------------------------------------------
@doc
This module is responsible for detecting which files in the
space with enabled auto storage import mechanism were deleted on
storage and therefore should be deleted from the Onedata file system.
It uses storage_sync_links to compare lists of files on the storage
with files in the database.
Functions in this module are called from master and slave jobs
executed by storage_sync_traverse pool.
@end
-------------------------------------------------------------------
API
Redundant field (can be obtained from pagination token) for easier matching in function clauses.
===================================================================
API functions
===================================================================
--------------------------------------------------------------------
@doc
Performs master job responsible for detecting which files in the
synchronized space were deleted on storage and therefore should be
deleted from the Onedata file system.
acquired from storage_sync_links, with list of children of the directory
acquired from file_meta links.
The lists are sorted in the same order so it is possible to compare them in
linear time.
This job is executed by storage_sync_traverse pool.
Files that are missing on the storage_sync_links list are scheduled to be
deleted in slave jobs.
NOTE!!!
On storages traversed using ?TREE_ITERATOR (posix storages), only direct children are compared.
On storages traverse using ?FLAT_ITERATOR (object storages), whole file structure is compared.
Traversing whole file structure (on object storages) is performed
by scheduling master jobs for directories (virtual directories as they do not exist on storage but exist in
the Onedata file system)
NOTE!!!
the storage.
@end
--------------------------------------------------------------------
compared with whole space file system) therefore we cannot delete whole storage_sync_links
with ?TREE_ITERATOR each directory is processed separately (separate deletion master_jobs)
so we can safely delete its links tree
--------------------------------------------------------------------
@doc
Performs job responsible for deleting file, which has been deleted on
synced storage from the Onedata file system.
@end
--------------------------------------------------------------------
===================================================================
===================================================================
-------------------------------------------------------------------
@doc
* list of file_meta children
* list of storage children, acquired from storage_sync_links
Both lists are sorted in the same order which allows to compare them
in linear time.
Function looks for files which are missing in the storage list and
are still present in the file_meta list.
Such files have potentially been deleted from storage and must be
checked whether they might be deleted from the system.
lists is empty.
NOTE!!!
On object storages detecting deletions is performed by a single traverse
over whole file system to avoid efficiency issues associated with
listing files in a canonical-like way on storage.
Files are listed using listobjects function which returns a flat structure.
Basing on the files absolute paths, we created storage_sync_links trees
which are then compared with file_meta links by this function.
In such case storage_sync_links are created for all files from the storage
and therefore we have to traverse whole structure, not only direct children.
@end
-------------------------------------------------------------------
there are no more children in file_meta links, we can finish the job;
sync_links must be processed after refilling file_meta children list
order of slave jobs doesn't matter as they will be processed in parallel
there are no more children in sync links
all left file_meta children must be deleted
order of slave jobs doesn't matter as they will be processed in parallel
we must schedule next batch to refill file_meta children
all left file_meta children must be processed after refilling sl children
file with name Name is on both lists therefore we cannot delete it
on storage iterated using ?TREE_ITERATOR (block storage) we process only direct children of a directory,
we do not go deeper in the files' structure as separate deletion_jobs will be scheduled for subdirectories
file with name Name is on both lists therefore we cannot delete it
on storage iterated using ?FLAT_ITERATOR (object storage) if child link's target is undefined it
means that it's a regular file's link
file with name Name is on both lists therefore we cannot delete it
on storage iterated using ?FLAT_ITERATOR (object storage) if child link's target is NOT undefined
it means that it's a directory's link therefore we schedule master job for this directory,
as with ?FLAT_ITERATOR deletion_jobs for root traverses whole file system
for more info read the function's doc
FMName is missing on the sync links list so it probably was deleted on storage
-------------------------------------------------------------------
@doc
This functions checks whether file is a directory or a regular file
and delegates decision about deleting or not deleting file to
suitable functions.
@end
-------------------------------------------------------------------
file is still missing on storage we can delete it from db
-------------------------------------------------------------------
@doc
This function deletes directory recursively it and updates sync counters.
@end
-------------------------------------------------------------------
-------------------------------------------------------------------
@doc
This function deletes regular file and updates sync counters.
@end
-------------------------------------------------------------------
-------------------------------------------------------------------
@doc
Deletes directory that has been deleted on storage from the system.
It deletes directory recursively.
@end
-------------------------------------------------------------------
-------------------------------------------------------------------
@doc
Recursively deletes children of directory.
@end
-------------------------------------------------------------------
-------------------------------------------------------------------
@doc
Deletes file that has been deleted on storage from the system.
It deletes both regular files and directories.
NOTE!!!
This function does not delete directory recursively.
Directory children must be deleted before calling this function.
@end
------------------------------------------------------------------- | @author
( C ) 2019 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(storage_import_deletion).
-author("Jakub Kudzia").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/fslogic/data_access_control.hrl").
-include("proto/oneclient/fuse_messages.hrl").
-include("modules/storage/traverse/storage_traverse.hrl").
-include_lib("ctool/include/logging.hrl").
-export([do_master_job/2, do_slave_job/2, get_master_job/1, delete_file_and_update_counters/3]).
-type master_job() :: storage_sync_traverse:master_job().
-type slave_job() :: storage_sync_traverse:slave_job().
-type file_meta_children() :: [file_meta:link()].
-type sync_links_children() :: [storage_sync_links:link()].
-type file_meta_listing_info() :: #{
token => file_listing:pagination_token()
}.
-define(BATCH_SIZE, op_worker:get_env(storage_import_deletion_batch_size, 1000)).
-spec get_master_job(master_job()) -> master_job().
get_master_job(Job = #storage_traverse_master{info = Info}) ->
Job#storage_traverse_master{
info = Info#{
deletion_job => true,
sync_links_token => #link_token{},
sync_links_children => [],
file_meta_token => undefined,
file_meta_children => []
}
}.
It compares list of children of directory associated with ,
Object storage must have ? CANONICAL_PATH_TYPE so the mechanism can understand the structure of files on
-spec do_master_job(master_job(), traverse:master_job_extended_args()) -> {ok, traverse:master_job_map()}.
do_master_job(Job = #storage_traverse_master{
storage_file_ctx = StorageFileCtx,
info = #{
file_ctx := FileCtx,
sync_links_token := SLToken,
sync_links_children := SLChildren,
file_meta_token := FMToken,
file_meta_children := FMChildren,
iterator_type := IteratorType
}}, _Args) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
reset any_protected_child_changed in case of first batch job
case FMToken =:= undefined andalso SLToken =:= #link_token{} of
true -> storage_sync_info:set_any_protected_child_changed(StorageFileId, SpaceId, false);
false -> ok
end,
Result = try
case refill_file_meta_children(FMChildren, FileCtx, FMToken) of
{error, not_found} ->
{ok, #{}};
{[], #{is_last := true}} ->
{ok, #{finish_callback => finish_callback(Job)}};
{FMChildren2, ListExtendedInfo} ->
case refill_sync_links_children(SLChildren, StorageFileCtx, SLToken) of
{error, not_found} ->
{ok, #{}};
{SLChildren2, SLToken2} ->
{MasterJobs, SlaveJobs} = generate_deletion_jobs(Job, SLChildren2, SLToken2, FMChildren2, ListExtendedInfo),
storage_import_monitoring:increment_queue_length_histograms(SpaceId, length(SlaveJobs) + length(MasterJobs)),
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
storage_sync_info:increase_batches_to_process(StorageFileId, SpaceId, length(MasterJobs)),
{ok, #{
slave_jobs => SlaveJobs,
async_master_jobs => MasterJobs,
finish_callback => finish_callback(Job)
}}
end
end
catch
throw:?ENOENT ->
{ok, #{}}
end,
case IteratorType of
?FLAT_ITERATOR ->
with ? FLAT_ITERATOR , deletion for root triggers traverse of whole storage ( which is
tree now ( see storage_sync_links.erl for more details )
ok;
?TREE_ITERATOR ->
storage_sync_links:delete_recursive(StorageFileId, StorageId)
end,
storage_import_monitoring:mark_processed_job(SpaceId),
Result.
-spec do_slave_job(slave_job(), traverse:id()) -> ok.
do_slave_job(#storage_traverse_slave{info = #{file_ctx := FileCtx, storage_id := StorageId}}, _Task) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
maybe_delete_file_and_update_counters(FileCtx, SpaceId, StorageId).
Internal functions
-spec refill_sync_links_children(sync_links_children(), storage_file_ctx:ctx(),
datastore_links_iter:token()) -> {sync_links_children(), datastore_links_iter:token()} | {error, term()}.
refill_sync_links_children(CurrentChildren, StorageFileCtx, Token) ->
case length(CurrentChildren) < ?BATCH_SIZE of
true ->
RootStorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
ToFetch = ?BATCH_SIZE - length(CurrentChildren),
case storage_sync_links:list(RootStorageFileId, StorageId, Token, ToFetch) of
{{ok, NewChildren}, NewToken} ->
{CurrentChildren ++ NewChildren, NewToken};
Error = {error, _} ->
Error
end;
false ->
{CurrentChildren, Token}
end.
-spec refill_file_meta_children(file_meta_children(), file_ctx:ctx(),
file_listing:pagination_token() | undefined) ->
{file_meta_children(), file_meta_listing_info()} | {error, term()}.
refill_file_meta_children(CurrentChildren, FileCtx, Token) ->
case length(CurrentChildren) < ?BATCH_SIZE of
true ->
ListingOpts = case Token of
undefined -> #{tune_for_large_continuous_listing => true};
_ -> #{pagination_token => Token}
end,
FileUuid = file_ctx:get_logical_uuid_const(FileCtx),
ToFetch = ?BATCH_SIZE - length(CurrentChildren),
case file_listing:list(FileUuid, ListingOpts#{limit => ToFetch}) of
{ok, NewChildren, ListingPaginationToken} ->
{CurrentChildren ++ NewChildren, #{
is_last => file_listing:is_finished(ListingPaginationToken),
token => ListingPaginationToken
}};
Error = {error, _} ->
Error
end;
false ->
{CurrentChildren, #{token => Token, is_last => false}}
end.
-spec generate_deletion_jobs(master_job(), sync_links_children(), datastore_links_iter:token(),
file_meta_children(), file_meta_listing_info()) -> {[master_job()], [slave_job()]}.
generate_deletion_jobs(Job, SLChildren, SLToken, FMChildren, FMListExtendedInfo) ->
generate_deletion_jobs(Job, SLChildren, SLToken, FMChildren, FMListExtendedInfo, [], []).
@private
This function is responsible for comparing two lists :
These checks are performed in returned from this function .
The function returns also MasterJob for next batch if one of compared
-spec generate_deletion_jobs(master_job(), sync_links_children(), datastore_links_iter:token(),
file_meta_children(), file_meta_listing_info(), [master_job()], [slave_job()]) -> {[master_job()], [slave_job()]}.
generate_deletion_jobs(_Job, _SLChildren, _SLFinished, [], #{is_last := true}, MasterJobs, SlaveJobs) ->
{MasterJobs, SlaveJobs};
generate_deletion_jobs(Job, SLChildren, SLToken, [], #{is_last := false, token := FMToken}, MasterJobs, SlaveJobs) ->
NextBatchJob = next_batch_master_job(Job, SLChildren, SLToken, [], FMToken),
{[NextBatchJob | MasterJobs], SlaveJobs};
generate_deletion_jobs(Job, [], #link_token{is_last = true}, FMChildren, #{is_last := true}, MasterJobs, SlaveJobs) ->
there are no more children in sync links and in file_meta ( except those in )
all left file_meta children ( those in ) must be deleted
SlaveJobs2 = lists:foldl(fun({_ChildName, ChildUuid}, AccIn) ->
[new_slave_job(Job, ChildUuid) | AccIn]
end, SlaveJobs, FMChildren),
{MasterJobs, SlaveJobs2};
generate_deletion_jobs(Job, [], SLToken = #link_token{is_last = true}, FMChildren, #{token := FMToken}, MasterJobs, SlaveJobs) ->
SlaveJobs2 = lists:foldl(fun({_ChildName, ChildUuid}, AccIn) ->
[new_slave_job(Job, ChildUuid) | AccIn]
end, SlaveJobs, FMChildren),
NextBatchJob = next_batch_master_job(Job, [], SLToken, [], FMToken),
{[NextBatchJob | MasterJobs], SlaveJobs2};
generate_deletion_jobs(Job, [], SLToken, FMChildren, #{token := FMToken}, MasterJobs, SlaveJobs) ->
NextBatchJob = next_batch_master_job(Job, [], SLToken, FMChildren, FMToken),
{[NextBatchJob | MasterJobs], SlaveJobs};
generate_deletion_jobs(Job = #storage_traverse_master{info = #{iterator_type := ?TREE_ITERATOR}},
[{Name, _} | RestSLChildren], SLToken, [{Name, _ChildUuid} | RestFMChildren], FMListExtendedInfo,
MasterJobs, SlaveJobs
) ->
generate_deletion_jobs(Job, RestSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, MasterJobs, SlaveJobs);
generate_deletion_jobs(Job = #storage_traverse_master{info = #{iterator_type := ?FLAT_ITERATOR}},
[{Name, undefined} | RestSLChildren], SLToken, [{Name, _ChildUuid} | RestFMChildren], FMListExtendedInfo,
MasterJobs, SlaveJobs
) ->
generate_deletion_jobs(Job, RestSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, MasterJobs, SlaveJobs);
generate_deletion_jobs(Job = #storage_traverse_master{info = #{iterator_type := ?FLAT_ITERATOR}},
[{Name, _} | RestSLChildren], SLToken, [{Name, Uuid} | RestFMChildren], FMListExtendedInfo,
MasterJobs, SlaveJobs
) ->
ChildMasterJob = new_flat_iterator_child_master_job(Job, Name, Uuid),
generate_deletion_jobs(Job, RestSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, [ChildMasterJob | MasterJobs], SlaveJobs);
generate_deletion_jobs(Job, AllSLChildren = [{SLName, _} | _], SLToken,
[{FMName, ChildUuid} | RestFMChildren], FMListExtendedInfo, MasterJobs, SlaveJobs)
when SLName > FMName ->
SlaveJob = new_slave_job(Job, ChildUuid),
generate_deletion_jobs(Job, AllSLChildren, SLToken, RestFMChildren, FMListExtendedInfo, MasterJobs, [SlaveJob | SlaveJobs]);
generate_deletion_jobs(Job, [{SLName, _} | RestSLChildren], SLToken,
AllFMChildren = [{FMName, _} | _], FMListExtendedInfo, MasterJobs, SlaveJobs)
when SLName < FMName ->
SLName is missing on the file_meta list , we can ignore it , storage import will synchronise this file
generate_deletion_jobs(Job, RestSLChildren, SLToken, AllFMChildren, FMListExtendedInfo, MasterJobs, SlaveJobs).
-spec new_slave_job(master_job(), file_meta:uuid()) -> slave_job().
new_slave_job(#storage_traverse_master{storage_file_ctx = StorageFileCtx}, ChildUuid) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
#storage_traverse_slave{
info = #{
deletion_job => true,
file_ctx => file_ctx:new_by_uuid(ChildUuid, SpaceId),
storage_id => StorageId
}}.
-spec next_batch_master_job(master_job(), sync_links_children(), datastore_links_iter:token(),
file_meta_children(), datastore_links_iter:token()) -> master_job().
next_batch_master_job(Job = #storage_traverse_master{info = Info}, SLChildrenToProcess, SLToken, FMChildrenToProcess, FMToken) ->
Job#storage_traverse_master{
info = Info#{
sync_links_token => SLToken,
sync_links_children => SLChildrenToProcess,
file_meta_token => FMToken,
file_meta_children => FMChildrenToProcess
}}.
-spec new_flat_iterator_child_master_job(master_job(), file_meta:name(), file_meta:uuid()) -> master_job().
new_flat_iterator_child_master_job(Job = #storage_traverse_master{
storage_file_ctx = StorageFileCtx,
info = #{iterator_type := IteratorType}
}, ChildName, ChildUuid) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx),
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
ChildStorageFileId = filename:join([StorageFileId, ChildName]),
ChildCtx = flat_storage_iterator:get_virtual_directory_ctx(ChildStorageFileId, SpaceId, StorageId),
ChildMasterJob = Job#storage_traverse_master{
storage_file_ctx = ChildCtx,
info = #{
iterator_type => IteratorType,
file_ctx => file_ctx:new_by_uuid(ChildUuid, SpaceId)}
},
get_master_job(ChildMasterJob).
-spec maybe_delete_file_and_update_counters(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
maybe_delete_file_and_update_counters(FileCtx, SpaceId, StorageId) ->
SpaceId = file_ctx:get_space_id_const(FileCtx),
try
{SDHandle, FileCtx2} = storage_driver:new_handle(?ROOT_SESS_ID, FileCtx),
{IsStorageFileCreated, FileCtx3} = file_ctx:is_storage_file_created(FileCtx2),
{StorageFileId, FileCtx4} = file_ctx:get_storage_file_id(FileCtx3),
Uuid = file_ctx:get_logical_uuid_const(FileCtx3),
IsNotSymlink = not fslogic_file_id:is_symlink_uuid(Uuid),
{FileDoc, FileCtx5} = file_ctx:get_file_doc_including_deleted(FileCtx4),
{ok, ProtectionFlags} = dataset_eff_cache:get_eff_protection_flags(FileDoc),
IsProtected = ProtectionFlags =/= ?no_flags_mask,
case
IsNotSymlink
andalso IsStorageFileCreated
andalso (not storage_driver:exists(SDHandle))
andalso (not IsProtected)
of
true ->
delete_file_and_update_counters(FileCtx5, SpaceId, StorageId);
false ->
case IsProtected of
true -> storage_sync_info:mark_protected_child_has_changed(filename:dirname(StorageFileId), SpaceId);
false -> ok
end,
storage_import_monitoring:mark_processed_job(SpaceId)
end
catch
throw:?ENOENT ->
storage_import_monitoring:mark_processed_job(SpaceId),
ok;
error:{badmatch, ?ERROR_NOT_FOUND} ->
storage_import_monitoring:mark_processed_job(SpaceId),
ok;
Error:Reason:Stacktrace ->
?error_stacktrace("~p:maybe_delete_file_and_update_counters failed due to ~p",
[?MODULE, {Error, Reason}], Stacktrace),
storage_import_monitoring:mark_failed_file(SpaceId)
end.
-spec delete_file_and_update_counters(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
delete_file_and_update_counters(FileCtx, SpaceId, StorageId) ->
case file_ctx:is_dir(FileCtx) of
{true, FileCtx2} ->
delete_dir_recursive_and_update_counters(FileCtx2, SpaceId, StorageId);
{false, FileCtx2} ->
delete_regular_file_and_update_counters(FileCtx2, SpaceId)
end.
-spec delete_dir_recursive_and_update_counters(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
delete_dir_recursive_and_update_counters(FileCtx, SpaceId, StorageId) ->
{StorageFileId, FileCtx2} = file_ctx:get_storage_file_id(FileCtx),
{CanonicalPath, FileCtx3} = file_ctx:get_canonical_path(FileCtx2),
FileUuid = file_ctx:get_logical_uuid_const(FileCtx3),
delete_dir_recursive(FileCtx3, SpaceId, StorageId),
storage_import_logger:log_deletion(StorageFileId, CanonicalPath, FileUuid, SpaceId),
storage_import_monitoring:mark_deleted_file(SpaceId).
-spec delete_regular_file_and_update_counters(file_ctx:ctx(), od_space:id()) -> ok.
delete_regular_file_and_update_counters(FileCtx, SpaceId) ->
{StorageFileId, FileCtx2} = file_ctx:get_storage_file_id(FileCtx),
{CanonicalPath, FileCtx3} = file_ctx:get_canonical_path(FileCtx2),
FileUuid = file_ctx:get_logical_uuid_const(FileCtx3),
delete_file(FileCtx3),
storage_import_logger:log_deletion(StorageFileId, CanonicalPath, FileUuid, SpaceId),
storage_import_monitoring:mark_deleted_file(SpaceId).
@private
-spec delete_dir_recursive(file_ctx:ctx(), od_space:id(), storage:id()) -> ok.
delete_dir_recursive(FileCtx, SpaceId, StorageId) ->
RootUserCtx = user_ctx:new(?ROOT_SESS_ID),
ListOpts = #{tune_for_large_continuous_listing => true},
{ok, FileCtx2} = delete_children(FileCtx, RootUserCtx, ListOpts, SpaceId, StorageId),
delete_file(FileCtx2).
@private
-spec delete_children(file_ctx:ctx(), user_ctx:ctx(), file_listing:options(),
od_space:id(), storage:id()) -> {ok, file_ctx:ctx()}.
delete_children(FileCtx, UserCtx, ListOpts, SpaceId, StorageId) ->
try
{ChildrenCtxs, ListingPaginationToken, FileCtx2} = file_tree:list_children(
FileCtx, UserCtx, ListOpts
),
storage_import_monitoring:increment_queue_length_histograms(SpaceId, length(ChildrenCtxs)),
lists:foreach(fun(ChildCtx) ->
delete_file_and_update_counters(ChildCtx, SpaceId, StorageId)
end, ChildrenCtxs),
case file_listing:is_finished(ListingPaginationToken) of
true ->
{ok, FileCtx2};
false ->
delete_children(FileCtx2, UserCtx, #{pagination_token => ListingPaginationToken}, SpaceId, StorageId)
end
catch
throw:?ENOENT ->
{ok, FileCtx}
end.
@private
-spec delete_file(file_ctx:ctx()) -> ok.
delete_file(FileCtx) ->
try
fslogic_delete:handle_file_deleted_on_imported_storage(FileCtx)
catch
throw:?ENOENT ->
ok
end.
-spec finish_callback(storage_traverse:master_job()) -> function().
finish_callback(#storage_traverse_master{
storage_file_ctx = StorageFileCtx,
depth = Depth,
max_depth = MaxDepth,
info = #{file_ctx := FileCtx}
}) ->
SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx),
MTime = try
{#statbuf{st_mtime = STMtime}, _} = storage_file_ctx:stat(StorageFileCtx),
STMtime
catch
throw:?ENOENT ->
undefined
end,
?ON_SUCCESSFUL_SLAVE_JOBS(fun() ->
StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx),
Guid = file_ctx:get_logical_guid_const(FileCtx),
case Depth =:= MaxDepth of
true -> storage_sync_info:mark_processed_batch(StorageFileId, SpaceId, Guid, undefined);
false -> storage_sync_info:mark_processed_batch(StorageFileId, SpaceId, Guid, MTime)
end
end). |
ad75bfd1ad17a25d3906d5d01f7a6d0cc58852cee7d508840f8aa344e1a4d2b5 | 2600hz/kazoo | kzd_dialplans.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
%%% @doc
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(kzd_dialplans).
-export([new/0]).
-export([system/1, system/2, set_system/2]).
-include("kz_documents.hrl").
-type doc() :: kz_json:object().
-export_type([doc/0]).
-define(SCHEMA, <<"dialplans">>).
-spec new() -> doc().
new() ->
kz_json_schema:default_object(?SCHEMA).
-spec system(doc()) -> kz_term:api_ne_binaries().
system(Doc) ->
system(Doc, 'undefined').
-spec system(doc(), Default) -> kz_term:ne_binaries() | Default.
system(Doc, Default) ->
kz_json:get_list_value([<<"system">>], Doc, Default).
-spec set_system(doc(), kz_term:ne_binaries()) -> doc().
set_system(Doc, System) ->
kz_json:set_value([<<"system">>], System, Doc).
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_documents/src/kzd_dialplans.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
----------------------------------------------------------------------------- | ( C ) 2010 - 2020 , 2600Hz
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(kzd_dialplans).
-export([new/0]).
-export([system/1, system/2, set_system/2]).
-include("kz_documents.hrl").
-type doc() :: kz_json:object().
-export_type([doc/0]).
-define(SCHEMA, <<"dialplans">>).
-spec new() -> doc().
new() ->
kz_json_schema:default_object(?SCHEMA).
-spec system(doc()) -> kz_term:api_ne_binaries().
system(Doc) ->
system(Doc, 'undefined').
-spec system(doc(), Default) -> kz_term:ne_binaries() | Default.
system(Doc, Default) ->
kz_json:get_list_value([<<"system">>], Doc, Default).
-spec set_system(doc(), kz_term:ne_binaries()) -> doc().
set_system(Doc, System) ->
kz_json:set_value([<<"system">>], System, Doc).
|
8d65c0da1c3445b0ec90bd54c10b47139aeed9cd20773d81e656c84870559058 | cl-axon/shop2 | state-utils.lisp | -*- Mode : common - lisp ; package : ; -*-
;;;
Version : MPL 1.1 / GPL 2.0 / LGPL 2.1
;;;
The contents of this file are subject to the Mozilla Public License
;;; Version 1.1 (the "License"); you may not use this file except in
;;; compliance with the License. You may obtain a copy of the License at
;;; /
;;;
Software distributed under the License is distributed on an " AS IS "
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
;;; License for the specific language governing rights and limitations under
;;; the License.
;;;
The Original Code is SHOP2 .
;;;
The Initial Developer of the Original Code is the University of
Maryland . Portions created by the Initial Developer are Copyright ( C )
2002,2003 the Initial Developer . All Rights Reserved .
;;;
Additional developments made by , .
;;; Portions created by Drs. Goldman and Maraist are Copyright (C)
2004 - 2007 SIFT , LLC . These additions and modifications are also
available under the MPL / GPL / LGPL licensing terms .
;;;
;;;
;;; Alternatively, the contents of this file may be used under the terms of
either of the GNU General Public License Version 2 or later ( the " GPL " ) ,
or the GNU Lesser General Public License Version 2.1 or later ( the
;;; "LGPL"), in which case the provisions of the GPL or the LGPL are
;;; applicable instead of those above. If you wish to allow use of your
;;; version of this file only under the terms of either the GPL or the LGPL,
;;; and not to allow others to use your version of this file under the terms
of the MPL , indicate your decision by deleting the provisions above and
;;; replace them with the notice and other provisions required by the GPL or
;;; the LGPL. If you do not delete the provisions above, a recipient may use
your version of this file under the terms of any one of the MPL , the GPL
;;; or the LGPL.
;;; ----------------------------------------------------------------------
Smart Information Flow Technologies Copyright 2006 - 2007 Unpublished work
;;;
;;; GOVERNMENT PURPOSE RIGHTS
;;;
;;; Contract No. FA8650-06-C-7606,
Contractor Name Smart Information Flow Technologies , LLC
d / b / a SIFT , LLC
Contractor Address 211 N 1st Street , Suite 300
Minneapolis , MN 55401
Expiration Date 5/2/2011
;;;
;;; The Government's rights to use, modify, reproduce, release,
;;; perform, display, or disclose this software are restricted by
paragraph ( b)(2 ) of the Rights in Noncommercial Computer Software
and Noncommercial Computer Software Documentation clause contained
;;; in the above identified contract. No restrictions apply after the
;;; expiration date shown above. Any reproduction of the software or
;;; portions thereof marked with this legend must also reproduce the
;;; markings.
(in-package :shop2.common)
;;;
;;; The "state" class
(defstruct (state (:constructor nil) (:copier nil))
body)
;; here for backward compatibility -- don't use this
(defun make-state (atoms &optional (state-encoding *state-encoding*))
(warn "MAKE-STATE is deprecated and will be removed; you should be ~
using MAKE-INITIAL-STATE.")
(ecase state-encoding
(:list (make-list-state atoms))
(:mixed (make-mixed-state atoms))
(:hash (make-hash-state atoms))
(:bit (make-bit-state atoms))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The "tagged-state" class
;;; Tags-info is a list of tag-info entries. Each tag-info is a list whose
first element is a tag ( represented by an integer ) and whose remaining
;;; elements are a list of changes made to the state while that tag was active.
;;; The command tag-state activates a new tag and returns it. The command
;;; retract-state-changes retracts all changes which were made while the given
;;; tag was active. It is expected that retractions will typically involve the
;;; most recently added tag, but the system does allow older tags to be
;;; retracted instead.
(defstruct (tagged-state (:include state) (:constructor nil) (:copier nil))
(tags-info (list (list 0))))
(deftype action-type () '(member add delete))
(defstruct state-update
(action 'add :type action-type)
(literal nil :type list))
(defmethod tag-state ((st tagged-state))
(let ((new-tag (1+ (first (first (tagged-state-tags-info st))))))
(push (list new-tag) (tagged-state-tags-info st))
new-tag))
(defmethod include-in-tag (action atom (st tagged-state))
(unless (typep action 'action-type)
(error "Unacceptable action ~S" action))
(push (make-state-update :action action :literal atom)
(rest (first (tagged-state-tags-info st)))))
(defmethod retract-state-changes ((st tagged-state) tag)
(multiple-value-bind (new-tags-info changes)
(pull-tag-info (tagged-state-tags-info st) tag)
(setf (tagged-state-tags-info st) new-tags-info)
(dolist (change changes)
(undo-state-update (state-update-action change) change st))))
(defmethod undo-state-update ((keyword (eql 'add)) change state)
(remove-atom (state-update-literal change) state))
(defmethod undo-state-update ((keyword (eql 'delete)) change state)
(insert-atom (state-update-literal change) state))
(defmethod add-atom-to-state (atom (st tagged-state) depth operator)
;;; (let ((shop2::state st))
; ; the above binding makes the trace - print work properly --- it references state [ 2006/12/06 : rpg ]
(trace-print :effects (car atom) st
"~2%Depth ~s, adding atom to current state~% atom ~s~% operator ~s"
depth atom operator)
;;; )
(unless (atom-in-state-p atom st)
( unless ( member ( cons ' delete atom ) ( first ( first st ) ) : test # ' equal )
(include-in-tag 'add atom st)
(insert-atom atom st)))
(defmethod delete-atom-from-state (atom (st tagged-state) depth operator)
;;; (let ((shop2::state st))
; ; the above binding makes the trace - print work properly --- it references state [ 2006/12/06 : rpg ]
(trace-print :effects (car atom) st
"~2%Depth ~s, deleting atom from current state~% atom ~s~% operator ~s"
depth atom operator)
;;; )
(when (atom-in-state-p atom st)
(include-in-tag 'delete atom st)
(remove-atom atom st)))
(defun pull-tag-info (tags-info tag)
(if (null tags-info)
(error "Attempt to retract to nonexistent state")
(let ((first-info (first tags-info)))
(if (= tag (first first-info))
(values (rest tags-info) (rest first-info))
(multiple-value-bind
(rest-info rest-changes)
(pull-tag-info (rest tags-info) (rest first-info))
(values (cons first-info rest-info) rest-changes))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The "list-state" class
(defstruct (list-state (:include tagged-state)
(:constructor makeliststate)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :list)) atoms &key)
(declare (ignore domain))
(make-list-state atoms)
)
(defun make-list-state (atoms)
(let ((st (makeliststate)))
(setf (state-body st) nil)
(dolist (atom atoms) (insert-atom atom st))
st))
(defmethod insert-atom (atom (st list-state))
(setf (state-body st) (LIST-insert-atom-into-statebody atom (state-body st))))
(defmethod remove-atom (atom (st list-state))
(setf (state-body st) (LIST-remove-atom-from-statebody atom (state-body st))))
(defmethod state-atoms ((st list-state))
(mapcan #'(lambda (entry) (copy-list (cdr entry))) (state-body st)))
(defmethod atom-in-state-p (atom (st list-state))
(member atom (rest (assoc (first atom) (state-body st))) :test #'equal))
(defmethod state-all-atoms-for-predicate ((st list-state) pred)
(rest (assoc pred (state-body st))))
(defmethod state-candidate-atoms-for-goal ((st list-state) goal)
(state-all-atoms-for-predicate st (first goal)))
(defmethod copy-state ((st list-state))
(let ((the-copy (make-list-state nil)))
(setf (state-body the-copy) (copy-tree (state-body st)))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
Unlike for MIXED , HASH , and BIT encodings , LIST - insert - atom - into - statebody and
;;; LIST-remove-atom-from-statebody are recursive, requiring their arguments to be
;;; statebodies and not states. So until we redo the way these functions work,
;;; they have to stay.
I think this code is going to be pretty inefficient , since it 's not properly tail - recursive . I do n't think it would be terribly difficult to replace this with a properly tail - recursive program . Alternatively , a simple destructive update using ( setf ( ( car atom ) ) .... ) might work , but I do n't know whether a destructive version of this operation would be acceptable . [ 2008 - 02 - 06 : rpg
(defun LIST-insert-atom-into-statebody (atom statebody)
;; the statebody here is evidently implemented as an associative structure, indexed on the predicate, of cells whose cdr is a LIST of atoms
(cond
((null statebody)
(list (list (car atom) atom)))
((string< (car atom) (caar statebody))
(cons (list (car atom) atom) statebody))
((eq (car atom) (caar statebody))
(cons
(cons (caar statebody)
(if (member atom (cdar statebody) :test #'equal)
(cdar statebody)
(cons atom (cdar statebody))))
(cdr statebody)))
(t (cons (car statebody)
(LIST-insert-atom-into-statebody atom (cdr statebody))))))
(defun LIST-remove-atom-from-statebody (atom statebody)
(cond ((null statebody) nil)
((string< (car atom) (caar statebody)) statebody)
((eq (car atom) (caar statebody))
(let ((newval (remove atom (cdar statebody) :test #'equal)))
(if newval
(cons (cons (car atom) newval) (cdr statebody))
;; if there are no remaining propositions for this
;; predicate, we just drop the entry
altogether . [ 2006/08/02 : rpg ]
(cdr statebody))))
(t (cons (car statebody)
(LIST-remove-atom-from-statebody atom (cdr statebody))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The "hash-state" class
(defstruct (hash-state (:include tagged-state)
(:constructor makehashstate)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :hash)) atoms &key)
(declare (ignore domain))
(make-hash-state atoms)
)
(defun make-hash-state (atoms)
(let ((st (makehashstate)))
(setf (state-body st) (make-hash-table :test #'equal))
(dolist (atom atoms) (insert-atom atom st))
st)
)
(defmethod insert-atom (atom (st hash-state))
(setf (gethash atom (state-body st)) t))
(defmethod remove-atom (atom (st hash-state))
(remhash atom (state-body st)))
(defmethod state-atoms ((st hash-state))
(let ((statebody (state-body st))
(acc nil))
(maphash #'(lambda (key val)
(declare (ignore val)) (setf acc (cons key acc)))
statebody)
acc))
(defmethod atom-in-state-p (atom (st hash-state))
(gethash atom (state-body st)))
(defmethod state-all-atoms-for-predicate ((st hash-state) pred)
(remove-if-not
#'(lambda (atom)
(eq (first atom) pred))
(state-atoms st)))
(defmethod state-candidate-atoms-for-goal ((st hash-state) goal)
(cond
((find-if-not #'(lambda (term) (and (atom term) (not (variablep term))))
(rest goal))
(state-all-atoms-for-predicate st (first goal)))
((atom-in-state-p goal st)
(list goal))
(t nil)))
(defmethod copy-state ((st hash-state))
(let ((the-copy (make-hash-state nil)))
(setf (state-body the-copy) (copy-hash-table (state-body st)))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The "mixed-state" class
(defstruct (mixed-state (:include tagged-state)
(:constructor makemixedstate)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :mixed)) atoms &key)
(declare (ignore domain))
(make-mixed-state atoms)
)
(defun make-mixed-state (atoms)
(let ((st (makemixedstate)))
(setf (state-body st) (make-hash-table :test #'eq))
(dolist (atom atoms) (insert-atom atom st))
st))
(defmethod insert-atom (atom (st mixed-state))
(push (rest atom) (gethash (first atom) (state-body st))))
(defmethod remove-atom (atom (st mixed-state))
(let ((statebody (state-body st)))
(setf
(gethash (first atom) statebody)
(delete
(rest atom)
(gethash (first atom) statebody)
:test #'equal))))
(defmethod state-atoms ((st mixed-state))
(let ((statebody (state-body st)))
(let ((acc nil))
(maphash #'(lambda (pred lis)
(setf acc
(append (mapcar #'(lambda (entry) (cons pred entry)) lis)
acc)))
statebody)
acc)))
(defmethod atom-in-state-p (atom (st mixed-state))
(member (rest atom) (gethash (first atom) (state-body st)) :test #'equal))
(defmethod state-all-atoms-for-predicate ((st mixed-state) pred)
(let ((lis (gethash pred (state-body st))))
(mapcar #'(lambda (entry) (cons pred entry)) lis)))
(defmethod state-candidate-atoms-for-goal ((st mixed-state) goal)
;(format t "state-body: ~A~%~%" (state-atoms st))
(cond
((find-if-not #'(lambda (term)
(and (atom term) (not (variablep term))))
(rest goal))
(state-all-atoms-for-predicate st (first goal)))
((atom-in-state-p goal st) (list goal))
(t nil)))
(defmethod copy-state ((st mixed-state))
(let ((the-copy (make-mixed-state nil)))
(setf (state-body the-copy) (copy-hash-table (state-body st)))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
; If we don't trust that copy-hash-table copies a mixed-state correctly, we can
; replace the preceding function with:
( defmethod copy - state ( ( st mixed - state ) )
; (let ((the-copy (make-mixed-state (state-atoms st))))
( setf ( tagged - state - tags - info the - copy )
; (copy-tree (tagged-state-tags-info st)))
; the-copy))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The "bit-state" class
(defstruct (bit-state (:include tagged-state)
(:constructor %make-bit-state)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :bit)) atoms &key)
(declare (ignore domain))
(make-bit-state atoms)
)
(defun make-bit-state (atoms)
(let ((st (%make-bit-state)))
;; The previous version of shop2.lisp did some strange initialization work
when making a new : bit which I did n't understand .
;; This doesn't do that. It seems to me like this just makes bit-states into
;; list-states that carry around some useless empty hash tables. That is, I
;; don't think the hash tables in the statebody do anything in this
;; implementation.
(setf (state-body st)
(list (make-hash-table :test #'eq)
(make-hash-table :test #'equal)
(make-hash-table :test #'eq)
nil))
(dolist (atom atoms) (insert-atom atom st))
st))
(defmethod insert-atom (atom (st bit-state))
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(extras (fourth statebody))
(entities (rest atom))
(types (mapcar #'(lambda (entity)
(first (gethash entity entity-table)))
entities))
(entity-numbers (mapcar #'(lambda (entity)
(second (gethash entity entity-table)))
entities))
(pred-entry (gethash (first atom) pred-table))
(pred-types (first pred-entry))
(pred-array (third pred-entry)))
(if (and entities (equal types pred-types))
(setf (apply #'aref pred-array entity-numbers) 1)
(setf (fourth statebody)
(LIST-insert-atom-into-statebody atom extras)))))
(defmethod remove-atom (atom (st bit-state))
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(extras (fourth statebody))
(entities (rest atom))
(types (mapcar #'(lambda (entity)
(first (gethash entity entity-table)))
entities))
(entity-numbers (mapcar #'(lambda (entity)
(second (gethash entity entity-table)))
entities))
(pred-entry (gethash (first atom) pred-table))
(pred-types (first pred-entry))
(pred-array (third pred-entry)))
(if (and entities (equal types pred-types))
(setf (apply #'aref pred-array entity-numbers) 0)
(setf (fourth statebody)
(LIST-remove-atom-from-statebody atom extras)))))
(defmethod state-atoms ((st bit-state))
(let ((acc nil))
(maphash #'(lambda (pred lis)
(declare (ignore lis))
(setf acc
(append
(state-all-atoms-for-predicate st pred)
acc)))
(first (state-body st)))
(remove-duplicates (append
acc
(mapcan #'(lambda (entry) (copy-list (cdr entry)))
(fourth (state-body st)))))))
(defmethod atom-in-state-p (atom (st bit-state))
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(extras (fourth statebody))
(entities (rest atom))
(types (mapcar #'(lambda (entity)
(first (gethash entity entity-table)))
entities))
(entity-numbers (mapcar #'(lambda (entity)
(second (gethash entity entity-table)))
entities))
(pred-entry (gethash (first atom) pred-table))
(pred-types (first pred-entry))
(pred-array (third pred-entry)))
(if (and entities (equal types pred-types))
(= (apply #'aref pred-array entity-numbers) 1)
(member atom (rest (assoc (first atom) extras)) :test #'equal))))
(defmethod state-all-atoms-for-predicate ((st bit-state) pred)
(let* ((statebody (state-body st))
(pred-table (first statebody))
(type-table (third statebody))
(extras (fourth statebody))
(pred-entry (gethash pred pred-table))
(pred-types (first pred-entry))
(pred-type-counts (second pred-entry))
(pred-array (third pred-entry)))
(append
(when pred-entry
(mapcar #'(lambda (entities)
(cons pred entities))
(BIT-statebody-search-array
pred-array pred-type-counts
(mapcar #'(lambda (type-name)
(second (gethash type-name type-table)))
pred-types)
(mapcar #'(lambda (x) (declare (ignore x)) (list :variable 0))
pred-types))))
(rest (assoc pred extras)))))
(defmethod state-candidate-atoms-for-goal ((st bit-state) goal)
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(type-table (third statebody))
(extras (fourth statebody))
(pred (first goal))
(goal-terms (rest goal))
(pred-entry (gethash pred pred-table))
(pred-types (first pred-entry))
(pred-type-counts (second pred-entry))
(pred-array (third pred-entry)))
(append
(when (and pred-entry
(= (length goal-terms) (length pred-types)))
(let ((initial-counter
(mapcar #'(lambda (entity pred-type)
(if (variablep entity)
(list :variable 0)
(let ((entry (gethash entity entity-table)))
(if (eq (first entry) pred-type)
(list :fixed (second entry))
nil))))
goal-terms pred-types)))
(unless (member nil initial-counter)
(mapcar #'(lambda (entities)
(cons pred entities))
(BIT-statebody-search-array
pred-array pred-type-counts
(mapcar #'(lambda (type-name)
(second (gethash type-name type-table)))
pred-types)
initial-counter)))))
(rest (assoc pred extras)))))
;;; This is very different from what was in state-utils before, but I'm pretty
;;; sure this does the job.
(defmethod copy-state ((st bit-state))
(let ((the-copy (make-bit-state (state-atoms st))))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
I do n't know what these next two functions do , so I left them as defuns
;;; rather than trying to define them as methods for the bit-state class.
(defun BIT-statebody-search-array
(pred-array pred-type-counts entity-number-tables complex-position)
(let ((position (mapcar #'second complex-position)))
(cond
((null position)
nil)
((= (apply #'aref pred-array position) 1)
(cons
(mapcar #'(lambda (num entity-number-table)
(gethash num entity-number-table))
position entity-number-tables)
(BIT-statebody-search-array
pred-array pred-type-counts entity-number-tables
(BIT-statebody-increment-position
complex-position pred-type-counts))))
(t
(BIT-statebody-search-array
pred-array pred-type-counts entity-number-tables
(BIT-statebody-increment-position
complex-position pred-type-counts))))))
(defun BIT-statebody-increment-position
(position pred-type-counts)
(cond
((null position) nil)
((eq :fixed (first (first position)))
(if (BIT-statebody-increment-position
(rest position) (rest pred-type-counts))
position
nil))
(t
(incf (second (first position)))
(cond
((< (second (first position)) (first pred-type-counts))
position)
((null (rest position))
nil)
((BIT-statebody-increment-position
(rest position) (rest pred-type-counts))
(setf (second (first position)) 0)
position)
(t nil)))))
(defun copy-hash-table (H1 &optional (copy-fn #'identity))
;; modified this to use the hash-table-test function, instead of always building
;; an "EQUAL" hash-table. Also initialized to be the same size, avoiding
resizes in building , I hope . [ 2002/10/08 : rpg ]
(let ((H2 (make-hash-table :size (hash-table-size H1) :test (hash-table-test H1))))
(maphash #'(lambda (key val) (setf (gethash key H2) (funcall copy-fn val)))
H1)
H2))
(defmethod state-trajectory ((st tagged-state))
(let ((state (copy-state st)))
(loop for state-info in (tagged-state-tags-info state)
for state-list = (state-atoms state)
with trajectory
do (push state-list trajectory)
(retract-state-changes state (first state-info))
finally (return trajectory))))
| null | https://raw.githubusercontent.com/cl-axon/shop2/9136e51f7845b46232cc17ca3618f515ddcf2787/common/state-utils.lisp | lisp | package : ; -*-
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations under
the License.
Portions created by Drs. Goldman and Maraist are Copyright (C)
Alternatively, the contents of this file may be used under the terms of
"LGPL"), in which case the provisions of the GPL or the LGPL are
applicable instead of those above. If you wish to allow use of your
version of this file only under the terms of either the GPL or the LGPL,
and not to allow others to use your version of this file under the terms
replace them with the notice and other provisions required by the GPL or
the LGPL. If you do not delete the provisions above, a recipient may use
or the LGPL.
----------------------------------------------------------------------
GOVERNMENT PURPOSE RIGHTS
Contract No. FA8650-06-C-7606,
The Government's rights to use, modify, reproduce, release,
perform, display, or disclose this software are restricted by
in the above identified contract. No restrictions apply after the
expiration date shown above. Any reproduction of the software or
portions thereof marked with this legend must also reproduce the
markings.
The "state" class
here for backward compatibility -- don't use this
you should be ~
The "tagged-state" class
Tags-info is a list of tag-info entries. Each tag-info is a list whose
elements are a list of changes made to the state while that tag was active.
The command tag-state activates a new tag and returns it. The command
retract-state-changes retracts all changes which were made while the given
tag was active. It is expected that retractions will typically involve the
most recently added tag, but the system does allow older tags to be
retracted instead.
(let ((shop2::state st))
; the above binding makes the trace - print work properly --- it references state [ 2006/12/06 : rpg ]
)
(let ((shop2::state st))
; the above binding makes the trace - print work properly --- it references state [ 2006/12/06 : rpg ]
)
The "list-state" class
LIST-remove-atom-from-statebody are recursive, requiring their arguments to be
statebodies and not states. So until we redo the way these functions work,
they have to stay.
the statebody here is evidently implemented as an associative structure, indexed on the predicate, of cells whose cdr is a LIST of atoms
if there are no remaining propositions for this
predicate, we just drop the entry
The "hash-state" class
The "mixed-state" class
(format t "state-body: ~A~%~%" (state-atoms st))
If we don't trust that copy-hash-table copies a mixed-state correctly, we can
replace the preceding function with:
(let ((the-copy (make-mixed-state (state-atoms st))))
(copy-tree (tagged-state-tags-info st)))
the-copy))
The "bit-state" class
The previous version of shop2.lisp did some strange initialization work
This doesn't do that. It seems to me like this just makes bit-states into
list-states that carry around some useless empty hash tables. That is, I
don't think the hash tables in the statebody do anything in this
implementation.
This is very different from what was in state-utils before, but I'm pretty
sure this does the job.
rather than trying to define them as methods for the bit-state class.
modified this to use the hash-table-test function, instead of always building
an "EQUAL" hash-table. Also initialized to be the same size, avoiding | Version : MPL 1.1 / GPL 2.0 / LGPL 2.1
The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is SHOP2 .
The Initial Developer of the Original Code is the University of
Maryland . Portions created by the Initial Developer are Copyright ( C )
2002,2003 the Initial Developer . All Rights Reserved .
Additional developments made by , .
2004 - 2007 SIFT , LLC . These additions and modifications are also
available under the MPL / GPL / LGPL licensing terms .
either of the GNU General Public License Version 2 or later ( the " GPL " ) ,
or the GNU Lesser General Public License Version 2.1 or later ( the
of the MPL , indicate your decision by deleting the provisions above and
your version of this file under the terms of any one of the MPL , the GPL
Smart Information Flow Technologies Copyright 2006 - 2007 Unpublished work
Contractor Name Smart Information Flow Technologies , LLC
d / b / a SIFT , LLC
Contractor Address 211 N 1st Street , Suite 300
Minneapolis , MN 55401
Expiration Date 5/2/2011
paragraph ( b)(2 ) of the Rights in Noncommercial Computer Software
and Noncommercial Computer Software Documentation clause contained
(in-package :shop2.common)
(defstruct (state (:constructor nil) (:copier nil))
body)
(defun make-state (atoms &optional (state-encoding *state-encoding*))
using MAKE-INITIAL-STATE.")
(ecase state-encoding
(:list (make-list-state atoms))
(:mixed (make-mixed-state atoms))
(:hash (make-hash-state atoms))
(:bit (make-bit-state atoms))))
first element is a tag ( represented by an integer ) and whose remaining
(defstruct (tagged-state (:include state) (:constructor nil) (:copier nil))
(tags-info (list (list 0))))
(deftype action-type () '(member add delete))
(defstruct state-update
(action 'add :type action-type)
(literal nil :type list))
(defmethod tag-state ((st tagged-state))
(let ((new-tag (1+ (first (first (tagged-state-tags-info st))))))
(push (list new-tag) (tagged-state-tags-info st))
new-tag))
(defmethod include-in-tag (action atom (st tagged-state))
(unless (typep action 'action-type)
(error "Unacceptable action ~S" action))
(push (make-state-update :action action :literal atom)
(rest (first (tagged-state-tags-info st)))))
(defmethod retract-state-changes ((st tagged-state) tag)
(multiple-value-bind (new-tags-info changes)
(pull-tag-info (tagged-state-tags-info st) tag)
(setf (tagged-state-tags-info st) new-tags-info)
(dolist (change changes)
(undo-state-update (state-update-action change) change st))))
(defmethod undo-state-update ((keyword (eql 'add)) change state)
(remove-atom (state-update-literal change) state))
(defmethod undo-state-update ((keyword (eql 'delete)) change state)
(insert-atom (state-update-literal change) state))
(defmethod add-atom-to-state (atom (st tagged-state) depth operator)
(trace-print :effects (car atom) st
"~2%Depth ~s, adding atom to current state~% atom ~s~% operator ~s"
depth atom operator)
(unless (atom-in-state-p atom st)
( unless ( member ( cons ' delete atom ) ( first ( first st ) ) : test # ' equal )
(include-in-tag 'add atom st)
(insert-atom atom st)))
(defmethod delete-atom-from-state (atom (st tagged-state) depth operator)
(trace-print :effects (car atom) st
"~2%Depth ~s, deleting atom from current state~% atom ~s~% operator ~s"
depth atom operator)
(when (atom-in-state-p atom st)
(include-in-tag 'delete atom st)
(remove-atom atom st)))
(defun pull-tag-info (tags-info tag)
(if (null tags-info)
(error "Attempt to retract to nonexistent state")
(let ((first-info (first tags-info)))
(if (= tag (first first-info))
(values (rest tags-info) (rest first-info))
(multiple-value-bind
(rest-info rest-changes)
(pull-tag-info (rest tags-info) (rest first-info))
(values (cons first-info rest-info) rest-changes))))))
(defstruct (list-state (:include tagged-state)
(:constructor makeliststate)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :list)) atoms &key)
(declare (ignore domain))
(make-list-state atoms)
)
(defun make-list-state (atoms)
(let ((st (makeliststate)))
(setf (state-body st) nil)
(dolist (atom atoms) (insert-atom atom st))
st))
(defmethod insert-atom (atom (st list-state))
(setf (state-body st) (LIST-insert-atom-into-statebody atom (state-body st))))
(defmethod remove-atom (atom (st list-state))
(setf (state-body st) (LIST-remove-atom-from-statebody atom (state-body st))))
(defmethod state-atoms ((st list-state))
(mapcan #'(lambda (entry) (copy-list (cdr entry))) (state-body st)))
(defmethod atom-in-state-p (atom (st list-state))
(member atom (rest (assoc (first atom) (state-body st))) :test #'equal))
(defmethod state-all-atoms-for-predicate ((st list-state) pred)
(rest (assoc pred (state-body st))))
(defmethod state-candidate-atoms-for-goal ((st list-state) goal)
(state-all-atoms-for-predicate st (first goal)))
(defmethod copy-state ((st list-state))
(let ((the-copy (make-list-state nil)))
(setf (state-body the-copy) (copy-tree (state-body st)))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
Unlike for MIXED , HASH , and BIT encodings , LIST - insert - atom - into - statebody and
I think this code is going to be pretty inefficient , since it 's not properly tail - recursive . I do n't think it would be terribly difficult to replace this with a properly tail - recursive program . Alternatively , a simple destructive update using ( setf ( ( car atom ) ) .... ) might work , but I do n't know whether a destructive version of this operation would be acceptable . [ 2008 - 02 - 06 : rpg
(defun LIST-insert-atom-into-statebody (atom statebody)
(cond
((null statebody)
(list (list (car atom) atom)))
((string< (car atom) (caar statebody))
(cons (list (car atom) atom) statebody))
((eq (car atom) (caar statebody))
(cons
(cons (caar statebody)
(if (member atom (cdar statebody) :test #'equal)
(cdar statebody)
(cons atom (cdar statebody))))
(cdr statebody)))
(t (cons (car statebody)
(LIST-insert-atom-into-statebody atom (cdr statebody))))))
(defun LIST-remove-atom-from-statebody (atom statebody)
(cond ((null statebody) nil)
((string< (car atom) (caar statebody)) statebody)
((eq (car atom) (caar statebody))
(let ((newval (remove atom (cdar statebody) :test #'equal)))
(if newval
(cons (cons (car atom) newval) (cdr statebody))
altogether . [ 2006/08/02 : rpg ]
(cdr statebody))))
(t (cons (car statebody)
(LIST-remove-atom-from-statebody atom (cdr statebody))))))
(defstruct (hash-state (:include tagged-state)
(:constructor makehashstate)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :hash)) atoms &key)
(declare (ignore domain))
(make-hash-state atoms)
)
(defun make-hash-state (atoms)
(let ((st (makehashstate)))
(setf (state-body st) (make-hash-table :test #'equal))
(dolist (atom atoms) (insert-atom atom st))
st)
)
(defmethod insert-atom (atom (st hash-state))
(setf (gethash atom (state-body st)) t))
(defmethod remove-atom (atom (st hash-state))
(remhash atom (state-body st)))
(defmethod state-atoms ((st hash-state))
(let ((statebody (state-body st))
(acc nil))
(maphash #'(lambda (key val)
(declare (ignore val)) (setf acc (cons key acc)))
statebody)
acc))
(defmethod atom-in-state-p (atom (st hash-state))
(gethash atom (state-body st)))
(defmethod state-all-atoms-for-predicate ((st hash-state) pred)
(remove-if-not
#'(lambda (atom)
(eq (first atom) pred))
(state-atoms st)))
(defmethod state-candidate-atoms-for-goal ((st hash-state) goal)
(cond
((find-if-not #'(lambda (term) (and (atom term) (not (variablep term))))
(rest goal))
(state-all-atoms-for-predicate st (first goal)))
((atom-in-state-p goal st)
(list goal))
(t nil)))
(defmethod copy-state ((st hash-state))
(let ((the-copy (make-hash-state nil)))
(setf (state-body the-copy) (copy-hash-table (state-body st)))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
(defstruct (mixed-state (:include tagged-state)
(:constructor makemixedstate)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :mixed)) atoms &key)
(declare (ignore domain))
(make-mixed-state atoms)
)
(defun make-mixed-state (atoms)
(let ((st (makemixedstate)))
(setf (state-body st) (make-hash-table :test #'eq))
(dolist (atom atoms) (insert-atom atom st))
st))
(defmethod insert-atom (atom (st mixed-state))
(push (rest atom) (gethash (first atom) (state-body st))))
(defmethod remove-atom (atom (st mixed-state))
(let ((statebody (state-body st)))
(setf
(gethash (first atom) statebody)
(delete
(rest atom)
(gethash (first atom) statebody)
:test #'equal))))
(defmethod state-atoms ((st mixed-state))
(let ((statebody (state-body st)))
(let ((acc nil))
(maphash #'(lambda (pred lis)
(setf acc
(append (mapcar #'(lambda (entry) (cons pred entry)) lis)
acc)))
statebody)
acc)))
(defmethod atom-in-state-p (atom (st mixed-state))
(member (rest atom) (gethash (first atom) (state-body st)) :test #'equal))
(defmethod state-all-atoms-for-predicate ((st mixed-state) pred)
(let ((lis (gethash pred (state-body st))))
(mapcar #'(lambda (entry) (cons pred entry)) lis)))
(defmethod state-candidate-atoms-for-goal ((st mixed-state) goal)
(cond
((find-if-not #'(lambda (term)
(and (atom term) (not (variablep term))))
(rest goal))
(state-all-atoms-for-predicate st (first goal)))
((atom-in-state-p goal st) (list goal))
(t nil)))
(defmethod copy-state ((st mixed-state))
(let ((the-copy (make-mixed-state nil)))
(setf (state-body the-copy) (copy-hash-table (state-body st)))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
( defmethod copy - state ( ( st mixed - state ) )
( setf ( tagged - state - tags - info the - copy )
(defstruct (bit-state (:include tagged-state)
(:constructor %make-bit-state)
(:copier nil)))
(defmethod make-initial-state (domain (state-encoding (eql :bit)) atoms &key)
(declare (ignore domain))
(make-bit-state atoms)
)
(defun make-bit-state (atoms)
(let ((st (%make-bit-state)))
when making a new : bit which I did n't understand .
(setf (state-body st)
(list (make-hash-table :test #'eq)
(make-hash-table :test #'equal)
(make-hash-table :test #'eq)
nil))
(dolist (atom atoms) (insert-atom atom st))
st))
(defmethod insert-atom (atom (st bit-state))
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(extras (fourth statebody))
(entities (rest atom))
(types (mapcar #'(lambda (entity)
(first (gethash entity entity-table)))
entities))
(entity-numbers (mapcar #'(lambda (entity)
(second (gethash entity entity-table)))
entities))
(pred-entry (gethash (first atom) pred-table))
(pred-types (first pred-entry))
(pred-array (third pred-entry)))
(if (and entities (equal types pred-types))
(setf (apply #'aref pred-array entity-numbers) 1)
(setf (fourth statebody)
(LIST-insert-atom-into-statebody atom extras)))))
(defmethod remove-atom (atom (st bit-state))
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(extras (fourth statebody))
(entities (rest atom))
(types (mapcar #'(lambda (entity)
(first (gethash entity entity-table)))
entities))
(entity-numbers (mapcar #'(lambda (entity)
(second (gethash entity entity-table)))
entities))
(pred-entry (gethash (first atom) pred-table))
(pred-types (first pred-entry))
(pred-array (third pred-entry)))
(if (and entities (equal types pred-types))
(setf (apply #'aref pred-array entity-numbers) 0)
(setf (fourth statebody)
(LIST-remove-atom-from-statebody atom extras)))))
(defmethod state-atoms ((st bit-state))
(let ((acc nil))
(maphash #'(lambda (pred lis)
(declare (ignore lis))
(setf acc
(append
(state-all-atoms-for-predicate st pred)
acc)))
(first (state-body st)))
(remove-duplicates (append
acc
(mapcan #'(lambda (entry) (copy-list (cdr entry)))
(fourth (state-body st)))))))
(defmethod atom-in-state-p (atom (st bit-state))
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(extras (fourth statebody))
(entities (rest atom))
(types (mapcar #'(lambda (entity)
(first (gethash entity entity-table)))
entities))
(entity-numbers (mapcar #'(lambda (entity)
(second (gethash entity entity-table)))
entities))
(pred-entry (gethash (first atom) pred-table))
(pred-types (first pred-entry))
(pred-array (third pred-entry)))
(if (and entities (equal types pred-types))
(= (apply #'aref pred-array entity-numbers) 1)
(member atom (rest (assoc (first atom) extras)) :test #'equal))))
(defmethod state-all-atoms-for-predicate ((st bit-state) pred)
(let* ((statebody (state-body st))
(pred-table (first statebody))
(type-table (third statebody))
(extras (fourth statebody))
(pred-entry (gethash pred pred-table))
(pred-types (first pred-entry))
(pred-type-counts (second pred-entry))
(pred-array (third pred-entry)))
(append
(when pred-entry
(mapcar #'(lambda (entities)
(cons pred entities))
(BIT-statebody-search-array
pred-array pred-type-counts
(mapcar #'(lambda (type-name)
(second (gethash type-name type-table)))
pred-types)
(mapcar #'(lambda (x) (declare (ignore x)) (list :variable 0))
pred-types))))
(rest (assoc pred extras)))))
(defmethod state-candidate-atoms-for-goal ((st bit-state) goal)
(let* ((statebody (state-body st))
(pred-table (first statebody))
(entity-table (second statebody))
(type-table (third statebody))
(extras (fourth statebody))
(pred (first goal))
(goal-terms (rest goal))
(pred-entry (gethash pred pred-table))
(pred-types (first pred-entry))
(pred-type-counts (second pred-entry))
(pred-array (third pred-entry)))
(append
(when (and pred-entry
(= (length goal-terms) (length pred-types)))
(let ((initial-counter
(mapcar #'(lambda (entity pred-type)
(if (variablep entity)
(list :variable 0)
(let ((entry (gethash entity entity-table)))
(if (eq (first entry) pred-type)
(list :fixed (second entry))
nil))))
goal-terms pred-types)))
(unless (member nil initial-counter)
(mapcar #'(lambda (entities)
(cons pred entities))
(BIT-statebody-search-array
pred-array pred-type-counts
(mapcar #'(lambda (type-name)
(second (gethash type-name type-table)))
pred-types)
initial-counter)))))
(rest (assoc pred extras)))))
(defmethod copy-state ((st bit-state))
(let ((the-copy (make-bit-state (state-atoms st))))
(setf (tagged-state-tags-info the-copy)
(copy-tree (tagged-state-tags-info st)))
the-copy))
I do n't know what these next two functions do , so I left them as defuns
(defun BIT-statebody-search-array
(pred-array pred-type-counts entity-number-tables complex-position)
(let ((position (mapcar #'second complex-position)))
(cond
((null position)
nil)
((= (apply #'aref pred-array position) 1)
(cons
(mapcar #'(lambda (num entity-number-table)
(gethash num entity-number-table))
position entity-number-tables)
(BIT-statebody-search-array
pred-array pred-type-counts entity-number-tables
(BIT-statebody-increment-position
complex-position pred-type-counts))))
(t
(BIT-statebody-search-array
pred-array pred-type-counts entity-number-tables
(BIT-statebody-increment-position
complex-position pred-type-counts))))))
(defun BIT-statebody-increment-position
(position pred-type-counts)
(cond
((null position) nil)
((eq :fixed (first (first position)))
(if (BIT-statebody-increment-position
(rest position) (rest pred-type-counts))
position
nil))
(t
(incf (second (first position)))
(cond
((< (second (first position)) (first pred-type-counts))
position)
((null (rest position))
nil)
((BIT-statebody-increment-position
(rest position) (rest pred-type-counts))
(setf (second (first position)) 0)
position)
(t nil)))))
(defun copy-hash-table (H1 &optional (copy-fn #'identity))
resizes in building , I hope . [ 2002/10/08 : rpg ]
(let ((H2 (make-hash-table :size (hash-table-size H1) :test (hash-table-test H1))))
(maphash #'(lambda (key val) (setf (gethash key H2) (funcall copy-fn val)))
H1)
H2))
(defmethod state-trajectory ((st tagged-state))
(let ((state (copy-state st)))
(loop for state-info in (tagged-state-tags-info state)
for state-list = (state-atoms state)
with trajectory
do (push state-list trajectory)
(retract-state-changes state (first state-info))
finally (return trajectory))))
|
4b90b104eec0779b081f68b77497402396dbe18c03b6d24841c9044798c4c4d8 | ocaml/num | arith_status.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Flags that control rational arithmetic. *)
val arith_status: unit -> unit
(** Print the current status of the arithmetic flags. *)
val get_error_when_null_denominator : unit -> bool
(** See {!Arith_status.set_error_when_null_denominator}.*)
val set_error_when_null_denominator : bool -> unit
(** Get or set the flag [null_denominator]. When on, attempting to
create a rational with a null denominator raises an exception.
When off, rationals with null denominators are accepted.
Initially: on. *)
val get_normalize_ratio : unit -> bool
(** See {!Arith_status.set_normalize_ratio}.*)
val set_normalize_ratio : bool -> unit
(** Get or set the flag [normalize_ratio]. When on, rational
numbers are normalized after each operation. When off,
rational numbers are not normalized until printed.
Initially: off. *)
val get_normalize_ratio_when_printing : unit -> bool
* See { ! Arith_status.set_normalize_ratio_when_printing } .
val set_normalize_ratio_when_printing : bool -> unit
(** Get or set the flag [normalize_ratio_when_printing].
When on, rational numbers are normalized before being printed.
When off, rational numbers are printed as is, without normalization.
Initially: on. *)
val get_approx_printing : unit -> bool
(** See {!Arith_status.set_approx_printing}.*)
val set_approx_printing : bool -> unit
(** Get or set the flag [approx_printing].
When on, rational numbers are printed as a decimal approximation.
When off, rational numbers are printed as a fraction.
Initially: off. *)
val get_floating_precision : unit -> int
(** See {!Arith_status.set_floating_precision}.*)
val set_floating_precision : int -> unit
* Get or set the parameter [ floating_precision ] .
This parameter is the number of digits displayed when
[ approx_printing ] is on .
Initially : 12 .
This parameter is the number of digits displayed when
[approx_printing] is on.
Initially: 12. *)
| null | https://raw.githubusercontent.com/ocaml/num/a635233b5c3da673e617de2cfe210fc869050e12/src/arith_status.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Flags that control rational arithmetic.
* Print the current status of the arithmetic flags.
* See {!Arith_status.set_error_when_null_denominator}.
* Get or set the flag [null_denominator]. When on, attempting to
create a rational with a null denominator raises an exception.
When off, rationals with null denominators are accepted.
Initially: on.
* See {!Arith_status.set_normalize_ratio}.
* Get or set the flag [normalize_ratio]. When on, rational
numbers are normalized after each operation. When off,
rational numbers are not normalized until printed.
Initially: off.
* Get or set the flag [normalize_ratio_when_printing].
When on, rational numbers are normalized before being printed.
When off, rational numbers are printed as is, without normalization.
Initially: on.
* See {!Arith_status.set_approx_printing}.
* Get or set the flag [approx_printing].
When on, rational numbers are printed as a decimal approximation.
When off, rational numbers are printed as a fraction.
Initially: off.
* See {!Arith_status.set_floating_precision}. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
val arith_status: unit -> unit
val get_error_when_null_denominator : unit -> bool
val set_error_when_null_denominator : bool -> unit
val get_normalize_ratio : unit -> bool
val set_normalize_ratio : bool -> unit
val get_normalize_ratio_when_printing : unit -> bool
* See { ! Arith_status.set_normalize_ratio_when_printing } .
val set_normalize_ratio_when_printing : bool -> unit
val get_approx_printing : unit -> bool
val set_approx_printing : bool -> unit
val get_floating_precision : unit -> int
val set_floating_precision : int -> unit
* Get or set the parameter [ floating_precision ] .
This parameter is the number of digits displayed when
[ approx_printing ] is on .
Initially : 12 .
This parameter is the number of digits displayed when
[approx_printing] is on.
Initially: 12. *)
|
b917e574a0fc1f385077cd480eccad1166cae44159ff96972968d923121d66a8 | ucsd-progsys/liquidhaskell | Fst01.hs | {-@ LIQUID "--expect-any-error" @-}
-- TAG: measure
test if the " builtin " fst and snd measures work .
module Fst01 where
@ splitter : : x : Int - > { v:(Int , Int ) | fst v + snd v = x + 1 } @
splitter :: Int -> (Int, Int)
splitter x = (0, x)
joiner :: Int -> Int
{-@ joiner :: y:Int -> {v:Int | v = y} @-}
joiner y = a + b
where
(a, b) = splitter y
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/measure/neg/Fst01.hs | haskell | @ LIQUID "--expect-any-error" @
TAG: measure
@ joiner :: y:Int -> {v:Int | v = y} @ | test if the " builtin " fst and snd measures work .
module Fst01 where
@ splitter : : x : Int - > { v:(Int , Int ) | fst v + snd v = x + 1 } @
splitter :: Int -> (Int, Int)
splitter x = (0, x)
joiner :: Int -> Int
joiner y = a + b
where
(a, b) = splitter y
|
a2f55920915fc4476fca7a6d40f43bcc65ad5484ecd0c574cf1a67835157ffda | compiling-to-categories/concat | Polynomial.hs | # LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE ConstraintKinds #-}
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -fno - warn - unused - imports #
-- {-# OPTIONS_GHC -fno-warn-orphans #-} -- see orphans
-- | Category of polynomials
module ConCat.Polynomial where
import Prelude hiding (id,(.),const,curry,uncurry)
import Data.Pointed
import Data.Key
import Control.Comonad.Cofree
import Control.Newtype.Generics
import ConCat.Category
import ConCat.Free.VectorSpace
import ConCat . Orphans
Scalar - valued power series from free vector space
type SPower f s = Cofree f s
-- Vector-valued power series between free vector spaces
type Power f g s = g (SPower f s)
-- Semantic function
spower :: (Zip f, Foldable f, Num s) => SPower f s -> (f s -> s)
spower (s :< p) u = s + u <.> vpower p u
-- Semantic function
vpower :: (Zip f, Foldable f, Functor g, Num s) => Power f g s -> (f s -> g s)
vpower ps u = flip spower u <$> ps
-- TODO: finite representations.
TODO : exploit Cofree , Comonad , etc .
szero :: (Pointed f, Num s) => SPower f s
szero = sconst 0
-- szero = point 0
vzero :: (Pointed f, Pointed g, Num s) => Power f g s
vzero = point szero
sconst :: (Pointed f, Num s) => s -> SPower f s
sconst s = s :< vzero
memo :: (Pointed f, Keyed f) => (Key f -> v) -> f v
memo h = mapWithKey (const . h) (point ())
keys :: (Pointed f, Keyed f) => f (Key f)
keys = memo id
idP :: (Pointed f, Keyed f, Num s, Eq (Key f)) => Power f f s
idP = memo (\ k -> 0 :< memo (\ k' -> sconst (delta k k')))
delta :: (Eq a, Num n) => a -> a -> n
delta a b = if a == b then 1 else 0
newtype Series s a b = Series (Power (V s a) (V s b) s)
instance Newtype (Series s a b) where
type O (Series s a b) = Power (V s a) (V s b) s
pack p = Series p
unpack (Series p) = p
type OkF f = (Pointed f, Zip f, Foldable f, Keyed f, Eq (Key f))
type OkS' s a = (HasV s a, OkF (V s a), Num s)
class OkS' s a => OkS s a
instance OkS' s a => OkS s a
mu :: Ok2 (Series s) a b => Series s a b -> (a -> b)
mu = onV . vpower . unpack
mu ( Series p ) = onV ( vpower p )
-- unV . . toV
-- mu (Series p) a = unV (vpower p (toV a))
instance Category (Series s) where
type Ok (Series s) = OkS s
id = pack idP
| null | https://raw.githubusercontent.com/compiling-to-categories/concat/49e554856576245f583dfd2484e5f7c19f688028/examples/src/ConCat/Polynomial.hs | haskell | # LANGUAGE ConstraintKinds #
{-# OPTIONS_GHC -fno-warn-orphans #-} -- see orphans
| Category of polynomials
Vector-valued power series between free vector spaces
Semantic function
Semantic function
TODO: finite representations.
szero = point 0
unV . . toV
mu (Series p) a = unV (vpower p (toV a)) | # LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -fno - warn - unused - imports #
module ConCat.Polynomial where
import Prelude hiding (id,(.),const,curry,uncurry)
import Data.Pointed
import Data.Key
import Control.Comonad.Cofree
import Control.Newtype.Generics
import ConCat.Category
import ConCat.Free.VectorSpace
import ConCat . Orphans
Scalar - valued power series from free vector space
type SPower f s = Cofree f s
type Power f g s = g (SPower f s)
spower :: (Zip f, Foldable f, Num s) => SPower f s -> (f s -> s)
spower (s :< p) u = s + u <.> vpower p u
vpower :: (Zip f, Foldable f, Functor g, Num s) => Power f g s -> (f s -> g s)
vpower ps u = flip spower u <$> ps
TODO : exploit Cofree , Comonad , etc .
szero :: (Pointed f, Num s) => SPower f s
szero = sconst 0
vzero :: (Pointed f, Pointed g, Num s) => Power f g s
vzero = point szero
sconst :: (Pointed f, Num s) => s -> SPower f s
sconst s = s :< vzero
memo :: (Pointed f, Keyed f) => (Key f -> v) -> f v
memo h = mapWithKey (const . h) (point ())
keys :: (Pointed f, Keyed f) => f (Key f)
keys = memo id
idP :: (Pointed f, Keyed f, Num s, Eq (Key f)) => Power f f s
idP = memo (\ k -> 0 :< memo (\ k' -> sconst (delta k k')))
delta :: (Eq a, Num n) => a -> a -> n
delta a b = if a == b then 1 else 0
newtype Series s a b = Series (Power (V s a) (V s b) s)
instance Newtype (Series s a b) where
type O (Series s a b) = Power (V s a) (V s b) s
pack p = Series p
unpack (Series p) = p
type OkF f = (Pointed f, Zip f, Foldable f, Keyed f, Eq (Key f))
type OkS' s a = (HasV s a, OkF (V s a), Num s)
class OkS' s a => OkS s a
instance OkS' s a => OkS s a
mu :: Ok2 (Series s) a b => Series s a b -> (a -> b)
mu = onV . vpower . unpack
mu ( Series p ) = onV ( vpower p )
instance Category (Series s) where
type Ok (Series s) = OkS s
id = pack idP
|
b46e2d64b40e4dfcda0c51b856d9aa2726912fa2a35e200dd52849ea6a22ca2c | footprintanalytics/footprint-web | info.clj | (ns metabase.api.info
(:require [clojure.core.async :as a]
[clojure.data :as data]
[clojure.tools.logging :as log]
[compojure.core :refer [DELETE GET POST PUT]]
[medley.core :as m]
[metabase.api.common :as api]
[metabase.models.card :as card :refer [Card]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.database :refer [Database]]
[metabase.models.interface :as mi]
[metabase.models.query :as query]
[metabase.query-processor :as qp]
[metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.query-processor.streaming :as qp.streaming]
[metabase.query-processor.middleware.constraints :as constraints]
[metabase.query-processor.util :as qputil]
[metabase.related :as related]
[metabase.sync.analyze.query-results :as qr]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[metabase.task.send-pulses :as send-pulses]
[toucan.db :as db])
(:import java.util.UUID)
(:import java.util.Base64))
(defn query-for-card
"Generate a query for a saved Card"
[{query :dataset_query
:as card} parameters constraints middleware & [ids]]
(log/info "query-for-card")
(let [query (-> query
;; don't want default constraints overridding anything that's already there
(m/dissoc-in [:middleware :add-default-userland-constraints?])
(assoc :constraints constraints
:parameters parameters
:middleware middleware))
dashboard (db/select-one [Dashboard :cache_ttl] :id (:dashboard-id ids))
database (db/select-one [Database :cache_ttl] :id (:database_id card))
]
query))
(defn run-query-for-card-async
"Run the query for Card with `parameters` and `constraints`, and return results in a `StreamingResponse` that should
be returned as the result of an API endpoint fn. Will throw an Exception if preconditions (such as read perms) are
not met before returning the `StreamingResponse`."
[card-id export-format
& {:keys [parameters constraints context dashboard-id middleware qp-runner run ignore_cache]
:or {constraints (constraints/default-query-constraints)
context :question
qp-runner qp/process-query-and-save-execution!}}]
{:pre [(u/maybe? sequential? parameters)]}
(log/info "run-query-for-card-async" qp-runner)
(let [run (or run
;; param `run` can be used to control how the query is ran, e.g. if you need to
customize the ` context ` passed to the QP
(^:once fn* [query info]
(qp.streaming/streaming-response [context export-format (u/slugify (:card-name info))]
(binding [qp.perms/*card-id* card-id]
(qp-runner query info context)))))
card (db/select-one [Card :id :name :dataset_query :database_id :cache_ttl :collection_id] :id card-id)
query (-> (assoc (query-for-card card parameters constraints middleware {:dashboard-id dashboard-id}) :async? true)
(update :middleware (fn [middleware]
(merge
{:js-int-to-string? true :ignore-cached-results? ignore_cache :get-the-cache-info? true}
middleware))))
info {:executed-by api/*current-user-id*
:context context
:card-id card-id
:card-name (:name card)
:dashboard-id dashboard-id}]
(run query info)))
(api/defendpoint ^:streaming POST "/card/:card-id/cache"
"Get cache info based on card."
[card-id :as {{:keys [parameters ignore_cache dashboard_id], :or {ignore_cache false dashboard_id nil}} :body}]
{ignore_cache (s/maybe s/Bool)
dashboard_id (s/maybe su/IntGreaterThanZero)}
(run-query-for-card-async
card-id :api
:parameters parameters,
:ignore_cache ignore_cache
:dashboard-id dashboard_id
:middleware {:process-viz-settings? false}))
(api/defendpoint ^:streaming POST "/alertNow"
[]
(log/info "=====> alert now")
(#'send-pulses/send-pulses! 0 "fri" :first :first))
(api/define-routes)
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d93dbf5f1627ad55c9172de1130603fcbe8398e9/src/metabase/api/info.clj | clojure | don't want default constraints overridding anything that's already there
param `run` can be used to control how the query is ran, e.g. if you need to | (ns metabase.api.info
(:require [clojure.core.async :as a]
[clojure.data :as data]
[clojure.tools.logging :as log]
[compojure.core :refer [DELETE GET POST PUT]]
[medley.core :as m]
[metabase.api.common :as api]
[metabase.models.card :as card :refer [Card]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.database :refer [Database]]
[metabase.models.interface :as mi]
[metabase.models.query :as query]
[metabase.query-processor :as qp]
[metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.query-processor.streaming :as qp.streaming]
[metabase.query-processor.middleware.constraints :as constraints]
[metabase.query-processor.util :as qputil]
[metabase.related :as related]
[metabase.sync.analyze.query-results :as qr]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[metabase.task.send-pulses :as send-pulses]
[toucan.db :as db])
(:import java.util.UUID)
(:import java.util.Base64))
(defn query-for-card
"Generate a query for a saved Card"
[{query :dataset_query
:as card} parameters constraints middleware & [ids]]
(log/info "query-for-card")
(let [query (-> query
(m/dissoc-in [:middleware :add-default-userland-constraints?])
(assoc :constraints constraints
:parameters parameters
:middleware middleware))
dashboard (db/select-one [Dashboard :cache_ttl] :id (:dashboard-id ids))
database (db/select-one [Database :cache_ttl] :id (:database_id card))
]
query))
(defn run-query-for-card-async
"Run the query for Card with `parameters` and `constraints`, and return results in a `StreamingResponse` that should
be returned as the result of an API endpoint fn. Will throw an Exception if preconditions (such as read perms) are
not met before returning the `StreamingResponse`."
[card-id export-format
& {:keys [parameters constraints context dashboard-id middleware qp-runner run ignore_cache]
:or {constraints (constraints/default-query-constraints)
context :question
qp-runner qp/process-query-and-save-execution!}}]
{:pre [(u/maybe? sequential? parameters)]}
(log/info "run-query-for-card-async" qp-runner)
(let [run (or run
customize the ` context ` passed to the QP
(^:once fn* [query info]
(qp.streaming/streaming-response [context export-format (u/slugify (:card-name info))]
(binding [qp.perms/*card-id* card-id]
(qp-runner query info context)))))
card (db/select-one [Card :id :name :dataset_query :database_id :cache_ttl :collection_id] :id card-id)
query (-> (assoc (query-for-card card parameters constraints middleware {:dashboard-id dashboard-id}) :async? true)
(update :middleware (fn [middleware]
(merge
{:js-int-to-string? true :ignore-cached-results? ignore_cache :get-the-cache-info? true}
middleware))))
info {:executed-by api/*current-user-id*
:context context
:card-id card-id
:card-name (:name card)
:dashboard-id dashboard-id}]
(run query info)))
(api/defendpoint ^:streaming POST "/card/:card-id/cache"
"Get cache info based on card."
[card-id :as {{:keys [parameters ignore_cache dashboard_id], :or {ignore_cache false dashboard_id nil}} :body}]
{ignore_cache (s/maybe s/Bool)
dashboard_id (s/maybe su/IntGreaterThanZero)}
(run-query-for-card-async
card-id :api
:parameters parameters,
:ignore_cache ignore_cache
:dashboard-id dashboard_id
:middleware {:process-viz-settings? false}))
(api/defendpoint ^:streaming POST "/alertNow"
[]
(log/info "=====> alert now")
(#'send-pulses/send-pulses! 0 "fri" :first :first))
(api/define-routes)
|
dfa96cf9704eaec9ba24bf4d7a946afc647f928814a7eb9d7403424fe553e967 | Clozure/ccl-tests | format-s.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Tue Aug 3 11:55:07 2004
;;;; Contains: Test of the ~S format directive
(in-package :cl-test)
(compile-and-load "printer-aux.lsp")
(deftest format.s.1
(let ((*print-readably* nil)
(*print-case* :upcase))
(format nil "~s" nil))
"NIL")
(deftest formatter.s.1
(let ((*print-readably* nil)
(*print-case* :upcase))
(formatter-call-to-string (formatter "~s") nil))
"NIL")
(def-format-test format.s.2
"~:s" (nil) "()")
(deftest format.s.3
(let ((*print-readably* nil)
(*print-case* :upcase))
(format nil "~:s" '(nil)))
"(NIL)")
(deftest formatter.s.3
(let ((*print-readably* nil)
(*print-case* :upcase))
(formatter-call-to-string (formatter "~:s") '(nil)))
"(NIL)")
(deftest format.s.4
(let ((*print-readably* nil)
(*print-case* :downcase))
(format nil "~s" 'nil))
"nil")
(deftest formatter.s.4
(let ((*print-readably* nil)
(*print-case* :downcase))
(formatter-call-to-string (formatter "~s") 'nil))
"nil")
(deftest format.s.5
(let ((*print-readably* nil)
(*print-case* :capitalize))
(format nil "~s" 'nil))
"Nil")
(deftest formatter.s.5
(let ((*print-readably* nil)
(*print-case* :capitalize))
(formatter-call-to-string (formatter "~s") 'nil))
"Nil")
(def-format-test format.s.6
"~:s" (#(nil)) "#(NIL)")
(deftest format.s.7
(let ((fn (formatter "~S")))
(with-standard-io-syntax
(let ((*print-readably* nil))
(loop for c across +standard-chars+
for s = (format nil "~S" c)
for s2 = (formatter-call-to-string fn c)
for c2 = (read-from-string s)
unless (and (eql c c2) (string= s s2))
collect (list c s c2 s2)))))
nil)
(deftest format.s.8
(let ((fn (formatter "~s")))
(with-standard-io-syntax
(let ((*print-readably* nil))
(loop with count = 0
for i from 0 below (min #x10000 char-code-limit)
for c = (code-char i)
for s1 = (and c (format nil "#\\~:c" c))
for s2 = (and c (format nil "~S" c))
for s3 = (formatter-call-to-string fn c)
unless (or (null c)
(graphic-char-p c)
(and (string= s1 s2) (string= s2 s3)))
do (incf count) and collect (list c s1 s2)
when (> count 100)
collect "count limit exceeded"
and do (loop-finish)))))
nil)
(deftest format.s.9
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~d@s" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"NIL"
"NIL"
"NIL"
" NIL"
" NIL"
" NIL"
" NIL"
" NIL"
" NIL"
" NIL")
(deftest format.s.10
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~dS" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"NIL"
"NIL"
"NIL"
"NIL "
"NIL "
"NIL "
"NIL "
"NIL "
"NIL "
"NIL ")
(deftest format.s.11
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~d@:S" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()")
(deftest format.s.12
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~d:s" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
"() "
"() "
"() "
"() "
"() "
"() "
"() "
"() ")
(deftest format.s.13
(with-standard-io-syntax
(let ((*print-readably* nil)
(fn (formatter "~V:s")))
(apply
#'values
(loop for i from 1 to 10
for s = (format nil "~v:S" i nil)
for s2 = (formatter-call-to-string fn i nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
"() "
"() "
"() "
"() "
"() "
"() "
"() "
"() ")
(deftest format.s.14
(with-standard-io-syntax
(let ((*print-readably* nil)
(fn (formatter "~V@:s")))
(apply
#'values
(loop for i from 1 to 10
for s = (format nil "~v:@s" i nil)
for s2 = (formatter-call-to-string fn i nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()")
(def-format-test format.s.15
"~vS" (nil nil) "NIL")
(def-format-test format.s.16
"~v:S" (nil nil) "()")
(def-format-test format.s.17
"~@S" (nil) "NIL")
(def-format-test format.s.18
"~v@S" (nil nil) "NIL")
(def-format-test format.s.19
"~v:@s" (nil nil) "()")
(def-format-test format.s.20
"~v@:s" (nil nil) "()")
;;; With colinc specified
(def-format-test format.s.21
"~3,1s" (nil) "NIL")
(def-format-test format.s.22
"~4,3s" (nil) "NIL ")
(def-format-test format.s.23
"~3,3@s" (nil) "NIL")
(def-format-test format.s.24
"~4,4@s" (nil) " NIL")
(def-format-test format.s.25
"~5,3@s" (nil) " NIL")
(def-format-test format.s.26
"~5,3S" (nil) "NIL ")
(def-format-test format.s.27
"~7,3@s" (nil) " NIL")
(def-format-test format.s.28
"~7,3S" (nil) "NIL ")
;;; With minpad
(deftest format.s.29
(with-standard-io-syntax
(let ((*print-readably* nil)
(*package* (find-package :cl-test))
(fn (formatter "~V,,2s")))
(loop for i from -4 to 10
for s = (format nil "~v,,2S" i 'ABC)
for s2 = (formatter-call-to-string fn i 'ABC)
do (assert (string= s s2))
collect s)))
("ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "))
(def-format-test format.s.30
"~3,,+2S" ('ABC) "ABC ")
(def-format-test format.s.31
"~3,,0S" ('ABC) "ABC")
(def-format-test format.s.32
"~3,,-1S" ('ABC) "ABC")
(def-format-test format.s.33
"~3,,0S" ('ABCD) "ABCD")
(def-format-test format.s.34
"~3,,-1S" ('ABCD) "ABCD")
;;; With padchar
(def-format-test format.s.35
"~4,,,'XS" ('AB) "ABXX")
(def-format-test format.s.36
"~4,,,s" ('AB) "AB ")
(def-format-test format.s.37
"~4,,,'X@s" ('AB) "XXAB")
(def-format-test format.s.38
"~4,,,@S" ('AB) " AB")
(def-format-test format.s.39
"~10,,,vS" (nil 'ABCDE) "ABCDE ")
(def-format-test format.s.40
"~10,,,v@S" (nil 'ABCDE) " ABCDE")
(def-format-test format.s.41
"~10,,,vs" (#\* 'ABCDE) "ABCDE*****")
(def-format-test format.s.42
"~10,,,v@s" (#\* 'ABCDE) "*****ABCDE")
;;; Other tests
(def-format-test format.s.43
"~3,,vS" (nil 246) "246")
(deftest format.s.44
(with-standard-io-syntax
(let ((*print-readably* nil)
(*package* (find-package :cl-test))
(fn (formatter "~3,,vs")))
(loop for i from 0 to 6
for s = (format nil "~3,,vS" i 'ABC)
for s2 = (formatter-call-to-string fn i 'ABC)
do (assert (string= s s2))
collect s)))
("ABC"
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "))
(deftest format.s.44a
(with-standard-io-syntax
(let ((*print-readably* nil)
(*package* (find-package :cl-test))
(fn (formatter "~3,,V@S")))
(loop for i from 0 to 6
for s = (format nil "~3,,v@S" i 'ABC)
for s2 = (formatter-call-to-string fn i 'ABC)
do (assert (string= s s2))
collect s)))
("ABC"
" ABC"
" ABC"
" ABC"
" ABC"
" ABC"
" ABC"))
(def-format-test format.s.45
"~4,,vs" (-1 1234) "1234")
(def-format-test format.s.46
"~5,vS" (nil 123) "123 ")
(def-format-test format.s.47
"~5,vS" (3 456) "456 ")
(def-format-test format.s.48
"~5,v@S" (3 789) " 789")
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/format-s.lsp | lisp | -*- Mode: Lisp -*-
Contains: Test of the ~S format directive
With colinc specified
With minpad
With padchar
Other tests | Author :
Created : Tue Aug 3 11:55:07 2004
(in-package :cl-test)
(compile-and-load "printer-aux.lsp")
(deftest format.s.1
(let ((*print-readably* nil)
(*print-case* :upcase))
(format nil "~s" nil))
"NIL")
(deftest formatter.s.1
(let ((*print-readably* nil)
(*print-case* :upcase))
(formatter-call-to-string (formatter "~s") nil))
"NIL")
(def-format-test format.s.2
"~:s" (nil) "()")
(deftest format.s.3
(let ((*print-readably* nil)
(*print-case* :upcase))
(format nil "~:s" '(nil)))
"(NIL)")
(deftest formatter.s.3
(let ((*print-readably* nil)
(*print-case* :upcase))
(formatter-call-to-string (formatter "~:s") '(nil)))
"(NIL)")
(deftest format.s.4
(let ((*print-readably* nil)
(*print-case* :downcase))
(format nil "~s" 'nil))
"nil")
(deftest formatter.s.4
(let ((*print-readably* nil)
(*print-case* :downcase))
(formatter-call-to-string (formatter "~s") 'nil))
"nil")
(deftest format.s.5
(let ((*print-readably* nil)
(*print-case* :capitalize))
(format nil "~s" 'nil))
"Nil")
(deftest formatter.s.5
(let ((*print-readably* nil)
(*print-case* :capitalize))
(formatter-call-to-string (formatter "~s") 'nil))
"Nil")
(def-format-test format.s.6
"~:s" (#(nil)) "#(NIL)")
(deftest format.s.7
(let ((fn (formatter "~S")))
(with-standard-io-syntax
(let ((*print-readably* nil))
(loop for c across +standard-chars+
for s = (format nil "~S" c)
for s2 = (formatter-call-to-string fn c)
for c2 = (read-from-string s)
unless (and (eql c c2) (string= s s2))
collect (list c s c2 s2)))))
nil)
(deftest format.s.8
(let ((fn (formatter "~s")))
(with-standard-io-syntax
(let ((*print-readably* nil))
(loop with count = 0
for i from 0 below (min #x10000 char-code-limit)
for c = (code-char i)
for s1 = (and c (format nil "#\\~:c" c))
for s2 = (and c (format nil "~S" c))
for s3 = (formatter-call-to-string fn c)
unless (or (null c)
(graphic-char-p c)
(and (string= s1 s2) (string= s2 s3)))
do (incf count) and collect (list c s1 s2)
when (> count 100)
collect "count limit exceeded"
and do (loop-finish)))))
nil)
(deftest format.s.9
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~d@s" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"NIL"
"NIL"
"NIL"
" NIL"
" NIL"
" NIL"
" NIL"
" NIL"
" NIL"
" NIL")
(deftest format.s.10
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~dS" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"NIL"
"NIL"
"NIL"
"NIL "
"NIL "
"NIL "
"NIL "
"NIL "
"NIL "
"NIL ")
(deftest format.s.11
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~d@:S" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()")
(deftest format.s.12
(with-standard-io-syntax
(let ((*print-readably* nil))
(apply
#'values
(loop for i from 1 to 10
for fmt = (format nil "~~~d:s" i)
for s = (format nil fmt nil)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
"() "
"() "
"() "
"() "
"() "
"() "
"() "
"() ")
(deftest format.s.13
(with-standard-io-syntax
(let ((*print-readably* nil)
(fn (formatter "~V:s")))
(apply
#'values
(loop for i from 1 to 10
for s = (format nil "~v:S" i nil)
for s2 = (formatter-call-to-string fn i nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
"() "
"() "
"() "
"() "
"() "
"() "
"() "
"() ")
(deftest format.s.14
(with-standard-io-syntax
(let ((*print-readably* nil)
(fn (formatter "~V@:s")))
(apply
#'values
(loop for i from 1 to 10
for s = (format nil "~v:@s" i nil)
for s2 = (formatter-call-to-string fn i nil)
do (assert (string= s s2))
collect s))))
"()"
"()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()"
" ()")
(def-format-test format.s.15
"~vS" (nil nil) "NIL")
(def-format-test format.s.16
"~v:S" (nil nil) "()")
(def-format-test format.s.17
"~@S" (nil) "NIL")
(def-format-test format.s.18
"~v@S" (nil nil) "NIL")
(def-format-test format.s.19
"~v:@s" (nil nil) "()")
(def-format-test format.s.20
"~v@:s" (nil nil) "()")
(def-format-test format.s.21
"~3,1s" (nil) "NIL")
(def-format-test format.s.22
"~4,3s" (nil) "NIL ")
(def-format-test format.s.23
"~3,3@s" (nil) "NIL")
(def-format-test format.s.24
"~4,4@s" (nil) " NIL")
(def-format-test format.s.25
"~5,3@s" (nil) " NIL")
(def-format-test format.s.26
"~5,3S" (nil) "NIL ")
(def-format-test format.s.27
"~7,3@s" (nil) " NIL")
(def-format-test format.s.28
"~7,3S" (nil) "NIL ")
(deftest format.s.29
(with-standard-io-syntax
(let ((*print-readably* nil)
(*package* (find-package :cl-test))
(fn (formatter "~V,,2s")))
(loop for i from -4 to 10
for s = (format nil "~v,,2S" i 'ABC)
for s2 = (formatter-call-to-string fn i 'ABC)
do (assert (string= s s2))
collect s)))
("ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "))
(def-format-test format.s.30
"~3,,+2S" ('ABC) "ABC ")
(def-format-test format.s.31
"~3,,0S" ('ABC) "ABC")
(def-format-test format.s.32
"~3,,-1S" ('ABC) "ABC")
(def-format-test format.s.33
"~3,,0S" ('ABCD) "ABCD")
(def-format-test format.s.34
"~3,,-1S" ('ABCD) "ABCD")
(def-format-test format.s.35
"~4,,,'XS" ('AB) "ABXX")
(def-format-test format.s.36
"~4,,,s" ('AB) "AB ")
(def-format-test format.s.37
"~4,,,'X@s" ('AB) "XXAB")
(def-format-test format.s.38
"~4,,,@S" ('AB) " AB")
(def-format-test format.s.39
"~10,,,vS" (nil 'ABCDE) "ABCDE ")
(def-format-test format.s.40
"~10,,,v@S" (nil 'ABCDE) " ABCDE")
(def-format-test format.s.41
"~10,,,vs" (#\* 'ABCDE) "ABCDE*****")
(def-format-test format.s.42
"~10,,,v@s" (#\* 'ABCDE) "*****ABCDE")
(def-format-test format.s.43
"~3,,vS" (nil 246) "246")
(deftest format.s.44
(with-standard-io-syntax
(let ((*print-readably* nil)
(*package* (find-package :cl-test))
(fn (formatter "~3,,vs")))
(loop for i from 0 to 6
for s = (format nil "~3,,vS" i 'ABC)
for s2 = (formatter-call-to-string fn i 'ABC)
do (assert (string= s s2))
collect s)))
("ABC"
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "
"ABC "))
(deftest format.s.44a
(with-standard-io-syntax
(let ((*print-readably* nil)
(*package* (find-package :cl-test))
(fn (formatter "~3,,V@S")))
(loop for i from 0 to 6
for s = (format nil "~3,,v@S" i 'ABC)
for s2 = (formatter-call-to-string fn i 'ABC)
do (assert (string= s s2))
collect s)))
("ABC"
" ABC"
" ABC"
" ABC"
" ABC"
" ABC"
" ABC"))
(def-format-test format.s.45
"~4,,vs" (-1 1234) "1234")
(def-format-test format.s.46
"~5,vS" (nil 123) "123 ")
(def-format-test format.s.47
"~5,vS" (3 456) "456 ")
(def-format-test format.s.48
"~5,v@S" (3 789) " 789")
|
f97546f66a9ebeb95a37b808a897f1dc3c9a513ba1a2ff8d61048eb520c3514d | mfikes/fifth-postulate | ns166.cljs | (ns fifth-postulate.ns166)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns166.cljs | clojure | (ns fifth-postulate.ns166)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
|
|
27665565f499e17d95d20715bdacebdb9d0c8327b93c669c4f6133c70f2b4cfe | angavrilov/ecl-compute | formula.lisp | ;;; -*- mode:lisp; indent-tabs-mode: nil; -*-
(defpackage formula
(:documentation "A reader macro to support Waterloo Maple infix expressions in code")
(:use "COMMON-LISP" "ALEXANDRIA" "LEXICAL-CONTEXTS")
(:export "*INDEX-ACCESS-SYMBOL*" "ENABLE-EXPR-QUOTES"))
(in-package formula)
;;; Symbol to use for array indexing
(defparameter *index-access-symbol* 'aref)
;;; Allow underscores in identifiers
(defun ident-char-p (c) (or (alpha-char-p c) (eql c #\_)))
(defun ident-num-char-p (c) (or (alphanumericp c) (eql c #\_)))
(defun float-num-char-p (c) (or (digit-char-p c) (eql c #\.)))
(defun whitespace-char-p (c)
(case c
((#\space #\return #\linefeed #\tab #\newline) t)
(t nil)))
(defun append-str-char (s c)
(concatenate 'string s (coerce (list c) 'string)))
;;; ***** SCANNER *****
(defcontext formula-scanner (stream recursive-p)
(defun read-c (&optional force)
(read-char stream force nil recursive-p))
(defun peek-c (&optional mode force)
(peek-char mode stream force nil recursive-p))
(defun unread-c (c)
(unread-char c stream))
;; Read characters that match cond-p as a string
(defun read-string (cond-p)
(do ((c (read-c) (read-c))
(lst () (cons c lst)))
((or (null c) (not (funcall cond-p c)))
(when c (unread-c c))
(coerce (reverse lst) 'string))))
;; Read a token from the stream
(defun read-token ()
(let ((c (peek-c t t))) ; Skip whitespace & require non-eof
(cond
;; Number
((or (digit-char-p c) (eql c #\.))
(let ((num-text (read-string #'float-num-char-p))
(next-c (peek-c)))
(when (find next-c '(#\E #\e)) ; Exponent
(read-c)
(setq num-text (append-str-char num-text next-c)
next-c (peek-c))
(when (find next-c '(#\+ #\-)) ; Allow sign after exponent
(read-c)
(setq num-text (append-str-char num-text next-c)))
(setq num-text ; Eat the actual digits
(concatenate 'string num-text
(read-string #'digit-char-p))))
(read-from-string num-text)))
;; Symbol token: quoted
((eql c #\$)
(read-c)
(if (or (eql (peek-c) #\() ; $(...) - lisp code splicing
(eql (peek-c) #\,)) ; $,... - lisp antiquotation
(read stream t nil recursive-p)
;; Quoted symbol
(let* ((name (read-string #'(lambda (cc) (not (eql cc #\$)))))
(split-pos (search ":" name))
(package (if split-pos
(string-upcase (subseq name 0 split-pos))
*package*))
(ident (if split-pos
(subseq name (1+ split-pos))
name)))
(read-c t)
(intern (string-upcase ident) package))))
;; Symbol token: plain
((ident-char-p c)
(let ((name (read-string #'ident-num-char-p))
(package *package*)
(next-c (peek-c)))
;; Handle package names:
(when (eql next-c #\:)
(read-c)
(setq package (string-upcase name))
(setq name (read-string #'ident-num-char-p)))
(intern (string-upcase name) package)))
;; Comparisons
((find c '(#\/ #\< #\> #\! #\:))
(let ((cc (read-c))
(next-c (peek-c)))
(if (eql next-c #\=)
(progn
(read-c)
(intern (coerce (list cc next-c) 'string) 'formula))
cc)))
;; Logical ops
((eql c #\&)
(read-c)
(let ((nc (peek-c)))
(if (eql nc c)
(progn (read-c) '|&&|)
c)))
((eql c #\|)
(read-c)
(let ((nc (peek-c)))
(if (eql nc c)
(progn (read-c) '|\|\||)
c)))
Semicolon
((eql c #\;)
(prog1
(read-c)
;; Semicolons are used as a comment marker by lisp, so disallow
;; any non-whitespace between the semicolon and the newline in
;; order to avoid confusing syntax highlighting, etc.
(let ((line (read-line stream nil "" recursive-p)))
(unless (every #'whitespace-char-p line)
(error "Semicolon must be followed by a newline in formula: ...;~A" line)))))
;; Comment: support #| ... |#
((eql c #\#)
(read-c)
(if (eql (peek-c) #\|)
(progn
(read-c)
(loop
(when (and (eql (read-c t) #\|)
(eql (peek-c) #\#))
(read-c)
(return)))
(read-token))
#\#))
;; Any other character
(t (read-c)))))
;; Reads tokens until a certain one is reached
(defun read-tokens-until (end)
(do ((item (read-token) (read-token))
(lst () (cons item lst)))
((eql item end)
(reverse lst)))))
;;; ***** PARSER *****
;;; Read a comma-delimited list of expressions
(defun parse-expr-list (tokens &optional lst)
(multiple-value-bind (expr tail) (parse-expr tokens)
(if (eql (car tail) #\,)
(parse-expr-list (cdr tail) (cons expr lst))
(values (reverse (cons expr lst)) tail))))
;;; Read an expression and eat a token after it
(defun parse-wrapped (tokens parser rbrace msg &optional (wrapper #'identity))
(multiple-value-bind (rv tail) (funcall parser (cdr tokens))
(unless (eql (car tail) rbrace)
(error "Expecting '~A' after ~A, '~A' found" rbrace msg (car tail)))
(values (funcall wrapper rv) (cdr tail))))
Parse array indexes and function arguments
(defun parse-expr-atom-idx (expr tokens)
(case (car tokens)
(#\[
(parse-wrapped tokens #'parse-expr-list #\] "index list"
#'(lambda (indexes) `(,*index-access-symbol* ,expr ,@indexes))))
(#\(
(parse-wrapped tokens #'parse-expr-list #\) "argument list"
#'(lambda (args) `(,expr ,@args))))
(t
(values expr tokens))))
Parse atomic expressions
(defun parse-expr-atom (tokens)
(let ((head (car tokens)))
(cond
((or (symbolp head) (numberp head) (consp head))
(parse-expr-atom-idx head (cdr tokens)))
((eql head #\()
(parse-wrapped tokens #'parse-expr #\) "nested expression"))
(t
(error "Invalid token '~A' in expression" (car tokens))))))
;;; A macro for binary operator parsing
(defmacro binary-ops (lhs lassoc &body oplst)
"Args: (lhs lassoc &body oplst)"
(let* ((cont-expr (if lassoc 'loop-fun 'values))
(rule-list (mapcar #'(lambda (opspec)
`(,(first opspec) ; Operator token
(multiple-value-bind (right-expr tail)
(,(second opspec) (cdr tail)) ; Handler function
Expression
oplst))
(op-checks `(case (car tail)
,@rule-list
(t (values left-expr tail)))))
(if lassoc
`(multiple-value-bind (left-expr tail) ,lhs
(labels ((loop-fun (left-expr tail) ,op-checks))
(loop-fun left-expr tail)))
`(multiple-value-bind (left-expr tail) ,lhs ,op-checks))))
;;; Main recursive descent grammar
(defun parse-expr-pow (tokens)
(binary-ops (parse-expr-atom tokens) nil
(#\^ parse-expr-unary `(expt ,left-expr ,right-expr))))
(defun parse-expr-unary (tokens) ; Parse unary + and -
(case (car tokens)
(#\+ (parse-expr-pow (cdr tokens)))
(#\- (multiple-value-bind (pexpr tail) (parse-expr-pow (cdr tokens))
(values `(- ,pexpr) tail)))
(#\! (multiple-value-bind (pexpr tail) (parse-expr-pow (cdr tokens))
(values `(not ,pexpr) tail)))
(t (parse-expr-pow tokens))))
(defun parse-expr-mul (tokens)
(binary-ops (parse-expr-unary tokens) t
(#\* parse-expr-unary `(* ,left-expr ,right-expr))
(#\/ parse-expr-unary `(/ ,left-expr ,right-expr))))
(defun parse-expr-add (tokens)
(binary-ops (parse-expr-mul tokens) t
(#\+ parse-expr-mul `(+ ,left-expr ,right-expr))
(#\- parse-expr-mul `(- ,left-expr ,right-expr))))
(defun parse-expr-cmp (tokens)
(binary-ops (parse-expr-add tokens) nil
(#\= parse-expr-add `(= ,left-expr ,right-expr))
(#\< parse-expr-add `(< ,left-expr ,right-expr))
(<= parse-expr-add `(<= ,left-expr ,right-expr))
(>= parse-expr-add `(>= ,left-expr ,right-expr))
(!= parse-expr-add `(/= ,left-expr ,right-expr))
(/= parse-expr-add `(/= ,left-expr ,right-expr))
(#\> parse-expr-add `(> ,left-expr ,right-expr))))
(defun parse-expr-and (tokens)
(binary-ops (parse-expr-cmp tokens) t
(|&&| parse-expr-cmp `(and ,left-expr ,right-expr))))
(defun parse-expr-or (tokens)
(binary-ops (parse-expr-and tokens) t
(|\|\|| parse-expr-and `(or ,left-expr ,right-expr))))
(defun parse-expr (tokens)
(labels ((read-branch (tokens)
(multiple-value-bind (texpr tail)
(parse-wrapped (cons nil tokens) ; parse-wrapped ignores car
#'parse-expr #\: "conditional")
(multiple-value-bind (fexpr tail)
(parse-expr tail)
(values (list texpr fexpr) tail)))))
(binary-ops (parse-expr-or tokens) nil
(#\? read-branch `(if ,left-expr ,@right-expr)))))
(defun parse-expr-assn (tokens)
(binary-ops (parse-expr tokens) nil
(|:=| parse-expr `(setf ,left-expr ,right-expr))))
(defun parse-expr-progn (tokens)
(binary-ops (parse-expr-assn tokens) t
(#\; parse-expr-assn
(if (and (consp left-expr)
(eql (car left-expr) 'progn))
(append left-expr (list right-expr))
`(progn ,left-expr ,right-expr)))))
* * * * * * * * * *
;;; A reader macro to parse infix expressions
(defun expr-reader (stream sc &optional arg)
(let ((tokens (with-context (formula-scanner stream t)
(read-tokens-until #\}))))
(multiple-value-bind (expr tail) (parse-expr-progn tokens)
(if (null tail)
expr
(error "Tokens beyond the end of expression: ~A" tail)))))
(defmacro enable-expr-quotes ()
`(eval-when (:compile-toplevel :execute)
(set-macro-character #\{ #'expr-reader)
(set-dispatch-macro-character #\# #\{ #'expr-reader)
(set-macro-character #\} (get-macro-character #\) nil))))
| null | https://raw.githubusercontent.com/angavrilov/ecl-compute/466f0d287f8b6ab0e2b5c2ac03693ad4f4df6a3f/formula.lisp | lisp | -*- mode:lisp; indent-tabs-mode: nil; -*-
Symbol to use for array indexing
Allow underscores in identifiers
***** SCANNER *****
Read characters that match cond-p as a string
Read a token from the stream
Skip whitespace & require non-eof
Number
Exponent
Allow sign after exponent
Eat the actual digits
Symbol token: quoted
$(...) - lisp code splicing
$,... - lisp antiquotation
Quoted symbol
Symbol token: plain
Handle package names:
Comparisons
Logical ops
)
Semicolons are used as a comment marker by lisp, so disallow
any non-whitespace between the semicolon and the newline in
order to avoid confusing syntax highlighting, etc.
Comment: support #| ... |#
Any other character
Reads tokens until a certain one is reached
***** PARSER *****
Read a comma-delimited list of expressions
Read an expression and eat a token after it
A macro for binary operator parsing
Operator token
Handler function
Main recursive descent grammar
Parse unary + and -
parse-wrapped ignores car
parse-expr-assn
A reader macro to parse infix expressions |
(defpackage formula
(:documentation "A reader macro to support Waterloo Maple infix expressions in code")
(:use "COMMON-LISP" "ALEXANDRIA" "LEXICAL-CONTEXTS")
(:export "*INDEX-ACCESS-SYMBOL*" "ENABLE-EXPR-QUOTES"))
(in-package formula)
(defparameter *index-access-symbol* 'aref)
(defun ident-char-p (c) (or (alpha-char-p c) (eql c #\_)))
(defun ident-num-char-p (c) (or (alphanumericp c) (eql c #\_)))
(defun float-num-char-p (c) (or (digit-char-p c) (eql c #\.)))
(defun whitespace-char-p (c)
(case c
((#\space #\return #\linefeed #\tab #\newline) t)
(t nil)))
(defun append-str-char (s c)
(concatenate 'string s (coerce (list c) 'string)))
(defcontext formula-scanner (stream recursive-p)
(defun read-c (&optional force)
(read-char stream force nil recursive-p))
(defun peek-c (&optional mode force)
(peek-char mode stream force nil recursive-p))
(defun unread-c (c)
(unread-char c stream))
(defun read-string (cond-p)
(do ((c (read-c) (read-c))
(lst () (cons c lst)))
((or (null c) (not (funcall cond-p c)))
(when c (unread-c c))
(coerce (reverse lst) 'string))))
(defun read-token ()
(cond
((or (digit-char-p c) (eql c #\.))
(let ((num-text (read-string #'float-num-char-p))
(next-c (peek-c)))
(read-c)
(setq num-text (append-str-char num-text next-c)
next-c (peek-c))
(read-c)
(setq num-text (append-str-char num-text next-c)))
(concatenate 'string num-text
(read-string #'digit-char-p))))
(read-from-string num-text)))
((eql c #\$)
(read-c)
(read stream t nil recursive-p)
(let* ((name (read-string #'(lambda (cc) (not (eql cc #\$)))))
(split-pos (search ":" name))
(package (if split-pos
(string-upcase (subseq name 0 split-pos))
*package*))
(ident (if split-pos
(subseq name (1+ split-pos))
name)))
(read-c t)
(intern (string-upcase ident) package))))
((ident-char-p c)
(let ((name (read-string #'ident-num-char-p))
(package *package*)
(next-c (peek-c)))
(when (eql next-c #\:)
(read-c)
(setq package (string-upcase name))
(setq name (read-string #'ident-num-char-p)))
(intern (string-upcase name) package)))
((find c '(#\/ #\< #\> #\! #\:))
(let ((cc (read-c))
(next-c (peek-c)))
(if (eql next-c #\=)
(progn
(read-c)
(intern (coerce (list cc next-c) 'string) 'formula))
cc)))
((eql c #\&)
(read-c)
(let ((nc (peek-c)))
(if (eql nc c)
(progn (read-c) '|&&|)
c)))
((eql c #\|)
(read-c)
(let ((nc (peek-c)))
(if (eql nc c)
(progn (read-c) '|\|\||)
c)))
Semicolon
(prog1
(read-c)
(let ((line (read-line stream nil "" recursive-p)))
(unless (every #'whitespace-char-p line)
(error "Semicolon must be followed by a newline in formula: ...;~A" line)))))
((eql c #\#)
(read-c)
(if (eql (peek-c) #\|)
(progn
(read-c)
(loop
(when (and (eql (read-c t) #\|)
(eql (peek-c) #\#))
(read-c)
(return)))
(read-token))
#\#))
(t (read-c)))))
(defun read-tokens-until (end)
(do ((item (read-token) (read-token))
(lst () (cons item lst)))
((eql item end)
(reverse lst)))))
(defun parse-expr-list (tokens &optional lst)
(multiple-value-bind (expr tail) (parse-expr tokens)
(if (eql (car tail) #\,)
(parse-expr-list (cdr tail) (cons expr lst))
(values (reverse (cons expr lst)) tail))))
(defun parse-wrapped (tokens parser rbrace msg &optional (wrapper #'identity))
(multiple-value-bind (rv tail) (funcall parser (cdr tokens))
(unless (eql (car tail) rbrace)
(error "Expecting '~A' after ~A, '~A' found" rbrace msg (car tail)))
(values (funcall wrapper rv) (cdr tail))))
Parse array indexes and function arguments
(defun parse-expr-atom-idx (expr tokens)
(case (car tokens)
(#\[
(parse-wrapped tokens #'parse-expr-list #\] "index list"
#'(lambda (indexes) `(,*index-access-symbol* ,expr ,@indexes))))
(#\(
(parse-wrapped tokens #'parse-expr-list #\) "argument list"
#'(lambda (args) `(,expr ,@args))))
(t
(values expr tokens))))
Parse atomic expressions
(defun parse-expr-atom (tokens)
(let ((head (car tokens)))
(cond
((or (symbolp head) (numberp head) (consp head))
(parse-expr-atom-idx head (cdr tokens)))
((eql head #\()
(parse-wrapped tokens #'parse-expr #\) "nested expression"))
(t
(error "Invalid token '~A' in expression" (car tokens))))))
(defmacro binary-ops (lhs lassoc &body oplst)
"Args: (lhs lassoc &body oplst)"
(let* ((cont-expr (if lassoc 'loop-fun 'values))
(rule-list (mapcar #'(lambda (opspec)
(multiple-value-bind (right-expr tail)
Expression
oplst))
(op-checks `(case (car tail)
,@rule-list
(t (values left-expr tail)))))
(if lassoc
`(multiple-value-bind (left-expr tail) ,lhs
(labels ((loop-fun (left-expr tail) ,op-checks))
(loop-fun left-expr tail)))
`(multiple-value-bind (left-expr tail) ,lhs ,op-checks))))
(defun parse-expr-pow (tokens)
(binary-ops (parse-expr-atom tokens) nil
(#\^ parse-expr-unary `(expt ,left-expr ,right-expr))))
(case (car tokens)
(#\+ (parse-expr-pow (cdr tokens)))
(#\- (multiple-value-bind (pexpr tail) (parse-expr-pow (cdr tokens))
(values `(- ,pexpr) tail)))
(#\! (multiple-value-bind (pexpr tail) (parse-expr-pow (cdr tokens))
(values `(not ,pexpr) tail)))
(t (parse-expr-pow tokens))))
(defun parse-expr-mul (tokens)
(binary-ops (parse-expr-unary tokens) t
(#\* parse-expr-unary `(* ,left-expr ,right-expr))
(#\/ parse-expr-unary `(/ ,left-expr ,right-expr))))
(defun parse-expr-add (tokens)
(binary-ops (parse-expr-mul tokens) t
(#\+ parse-expr-mul `(+ ,left-expr ,right-expr))
(#\- parse-expr-mul `(- ,left-expr ,right-expr))))
(defun parse-expr-cmp (tokens)
(binary-ops (parse-expr-add tokens) nil
(#\= parse-expr-add `(= ,left-expr ,right-expr))
(#\< parse-expr-add `(< ,left-expr ,right-expr))
(<= parse-expr-add `(<= ,left-expr ,right-expr))
(>= parse-expr-add `(>= ,left-expr ,right-expr))
(!= parse-expr-add `(/= ,left-expr ,right-expr))
(/= parse-expr-add `(/= ,left-expr ,right-expr))
(#\> parse-expr-add `(> ,left-expr ,right-expr))))
(defun parse-expr-and (tokens)
(binary-ops (parse-expr-cmp tokens) t
(|&&| parse-expr-cmp `(and ,left-expr ,right-expr))))
(defun parse-expr-or (tokens)
(binary-ops (parse-expr-and tokens) t
(|\|\|| parse-expr-and `(or ,left-expr ,right-expr))))
(defun parse-expr (tokens)
(labels ((read-branch (tokens)
(multiple-value-bind (texpr tail)
#'parse-expr #\: "conditional")
(multiple-value-bind (fexpr tail)
(parse-expr tail)
(values (list texpr fexpr) tail)))))
(binary-ops (parse-expr-or tokens) nil
(#\? read-branch `(if ,left-expr ,@right-expr)))))
(defun parse-expr-assn (tokens)
(binary-ops (parse-expr tokens) nil
(|:=| parse-expr `(setf ,left-expr ,right-expr))))
(defun parse-expr-progn (tokens)
(binary-ops (parse-expr-assn tokens) t
(if (and (consp left-expr)
(eql (car left-expr) 'progn))
(append left-expr (list right-expr))
`(progn ,left-expr ,right-expr)))))
* * * * * * * * * *
(defun expr-reader (stream sc &optional arg)
(let ((tokens (with-context (formula-scanner stream t)
(read-tokens-until #\}))))
(multiple-value-bind (expr tail) (parse-expr-progn tokens)
(if (null tail)
expr
(error "Tokens beyond the end of expression: ~A" tail)))))
(defmacro enable-expr-quotes ()
`(eval-when (:compile-toplevel :execute)
(set-macro-character #\{ #'expr-reader)
(set-dispatch-macro-character #\# #\{ #'expr-reader)
(set-macro-character #\} (get-macro-character #\) nil))))
|
1a8a95f1c5de90930b1d19350a2ddd318663086e9519a77d0742f62d897377cd | adrieng/pulsar | type.ml | This file is part of Pulsar , a temporal functional language .
* Copyright ( C ) 2017
*
* This program is free software : you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation , either version 3 of the License , or ( at your option ) any later
* version .
*
* This program is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE . See the LICENSE file in the top - level directory .
* Copyright (C) 2017 Adrien Guatto
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the LICENSE file in the top-level directory.
*)
(* Base types *)
type base =
| Unit
| Bool
| Char
| Int
| Float
let string_of_base bty =
match bty with
| Unit -> "unit"
| Bool -> "bool"
| Char -> "char"
| Int -> "int"
| Float -> "float"
let print_base fmt bty =
Format.fprintf fmt "%s" (string_of_base bty)
let compare_base bty1 bty2 =
if bty1 == bty2 then 0
else
let tag_to_int bty =
match bty with
| Unit -> 0
| Bool -> 1
| Char -> 2
| Int -> 3
| Float -> 4
in
match bty1, bty2 with
| Unit, Unit | Bool, Bool | Char, Char | Int, Int | Float, Float ->
0
| (Unit | Bool | Char | Int | Float), _ ->
Warp.Utils.compare_int (tag_to_int bty1) (tag_to_int bty2)
let equal_base bty1 bty2 =
compare_base bty1 bty2 = 0
(* Types *)
type t =
| Base of base
| Stream of t
| Prod of t * t
| Fun of t * t
| Warped of Warp.Formal.t * t
let priority ty =
match ty with
| Base _ | Stream _ ->
0
| Warped _ ->
10
| Fun _ ->
20
| Prod _ ->
30
let rec print pri fmt ty =
let pri' = priority ty in
let print_rec = print pri' in
let paren = pri < pri' in
if paren then Format.fprintf fmt "(@[";
begin match ty with
| Base bty ->
print_base fmt bty
| Stream ty ->
Format.fprintf fmt "stream %a" print_rec ty
| Prod (ty1, ty2) ->
Format.fprintf fmt "@[%a %a@ %a@]"
print_rec ty1
Warp.Print.pp_times ()
print_rec ty2;
| Fun (ty1, ty2) ->
Format.fprintf fmt "@[%a %a@ %a@]"
(print (pri' - 1)) ty1
Warp.Print.pp_arrow ()
print_rec ty2
| Warped (p, ty) ->
Format.fprintf fmt "@[%a %a@ %a@]"
Warp.Formal.print p
Warp.Print.pp_circledast ()
print_rec ty
end;
if paren then Format.fprintf fmt "@])"
let print =
print 500
let rec normalize ty =
let box p ty =
let p = Warp.Formal.(periodic @@ normalize p) in
if Warp.Formal.(equal p one) then ty else Warped (p, ty)
in
let rec push p ty =
match ty with
| Base _ ->
TODO we could simplify 0(3 2 0)*int to 0(1)*int .
FIXME
| Stream ty ->
box p (Stream (normalize ty))
| Prod (ty1, ty2) ->
Prod (push p ty1, push p ty2)
| Fun (ty1, ty2) ->
box p (Fun (normalize ty1, normalize ty2))
| Warped (p', ty) ->
push (Warp.Formal.on p p') ty
in
push Warp.Formal.one ty
let print_normalized fmt ty =
print fmt @@ normalize ty
let print fmt ty =
if !Options.display_normalized_types
then print_normalized fmt ty
else print fmt ty
let rec compare ty1 ty2 =
if ty1 == ty2 then 0
else
let tag_to_int ty =
match ty with
| Base _ -> 0
| Stream _ -> 1
| Prod _ -> 2
| Fun _ -> 3
| Warped _ -> 4
in
match ty1, ty2 with
| Base bty1, Base bty2 ->
compare_base bty1 bty2
| Stream ty1, Stream ty2 ->
compare ty1 ty2
| Prod (ty1, ty2), Prod (ty1', ty2')
| Fun (ty1, ty2), Fun (ty1', ty2') ->
Warp.Utils.compare_both
(compare ty1 ty1')
(fun () -> compare ty2 ty2')
| Warped (ck, ty), Warped (ck', ty') ->
Warp.Utils.compare_both
(Warp.Formal.compare ck ck')
(fun () -> compare ty ty')
| (Base _ | Stream _ | Prod _ | Fun _ | Warped _), _ ->
Warp.Utils.compare_int (tag_to_int ty1) (tag_to_int ty2)
let equal ty1 ty2 = compare ty1 ty2 = 0
let equiv ty1 ty2 = equal (normalize ty1) (normalize ty2)
let later ty =
Warped (Warp.Formal.zero_one, ty)
let constant ty =
Warped (Warp.Formal.omega, ty)
let get_base ty =
match ty with
| Base bty ->
bty
| _ ->
invalid_arg "get_base"
let get_stream ty =
match ty with
| Stream bty ->
bty
| _ ->
invalid_arg "get_stream"
let get_fun ty =
match ty with
| Fun (ty1, ty2) ->
ty1, ty2
| _ ->
invalid_arg "get_fun"
let get_prod ty =
match ty with
| Prod (ty1, ty2) ->
ty1, ty2
| _ ->
invalid_arg "get_prod"
let get_warped ty =
match ty with
| Warped (p, ty) ->
p, ty
| _ ->
invalid_arg "get_warped"
| null | https://raw.githubusercontent.com/adrieng/pulsar/c3901388659d9c7978b04dce0815e3ff9aea1a0c/pulsar-lib/type.ml | ocaml | Base types
Types | This file is part of Pulsar , a temporal functional language .
* Copyright ( C ) 2017
*
* This program is free software : you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation , either version 3 of the License , or ( at your option ) any later
* version .
*
* This program is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE . See the LICENSE file in the top - level directory .
* Copyright (C) 2017 Adrien Guatto
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the LICENSE file in the top-level directory.
*)
type base =
| Unit
| Bool
| Char
| Int
| Float
let string_of_base bty =
match bty with
| Unit -> "unit"
| Bool -> "bool"
| Char -> "char"
| Int -> "int"
| Float -> "float"
let print_base fmt bty =
Format.fprintf fmt "%s" (string_of_base bty)
let compare_base bty1 bty2 =
if bty1 == bty2 then 0
else
let tag_to_int bty =
match bty with
| Unit -> 0
| Bool -> 1
| Char -> 2
| Int -> 3
| Float -> 4
in
match bty1, bty2 with
| Unit, Unit | Bool, Bool | Char, Char | Int, Int | Float, Float ->
0
| (Unit | Bool | Char | Int | Float), _ ->
Warp.Utils.compare_int (tag_to_int bty1) (tag_to_int bty2)
let equal_base bty1 bty2 =
compare_base bty1 bty2 = 0
type t =
| Base of base
| Stream of t
| Prod of t * t
| Fun of t * t
| Warped of Warp.Formal.t * t
let priority ty =
match ty with
| Base _ | Stream _ ->
0
| Warped _ ->
10
| Fun _ ->
20
| Prod _ ->
30
let rec print pri fmt ty =
let pri' = priority ty in
let print_rec = print pri' in
let paren = pri < pri' in
if paren then Format.fprintf fmt "(@[";
begin match ty with
| Base bty ->
print_base fmt bty
| Stream ty ->
Format.fprintf fmt "stream %a" print_rec ty
| Prod (ty1, ty2) ->
Format.fprintf fmt "@[%a %a@ %a@]"
print_rec ty1
Warp.Print.pp_times ()
print_rec ty2;
| Fun (ty1, ty2) ->
Format.fprintf fmt "@[%a %a@ %a@]"
(print (pri' - 1)) ty1
Warp.Print.pp_arrow ()
print_rec ty2
| Warped (p, ty) ->
Format.fprintf fmt "@[%a %a@ %a@]"
Warp.Formal.print p
Warp.Print.pp_circledast ()
print_rec ty
end;
if paren then Format.fprintf fmt "@])"
let print =
print 500
let rec normalize ty =
let box p ty =
let p = Warp.Formal.(periodic @@ normalize p) in
if Warp.Formal.(equal p one) then ty else Warped (p, ty)
in
let rec push p ty =
match ty with
| Base _ ->
TODO we could simplify 0(3 2 0)*int to 0(1)*int .
FIXME
| Stream ty ->
box p (Stream (normalize ty))
| Prod (ty1, ty2) ->
Prod (push p ty1, push p ty2)
| Fun (ty1, ty2) ->
box p (Fun (normalize ty1, normalize ty2))
| Warped (p', ty) ->
push (Warp.Formal.on p p') ty
in
push Warp.Formal.one ty
let print_normalized fmt ty =
print fmt @@ normalize ty
let print fmt ty =
if !Options.display_normalized_types
then print_normalized fmt ty
else print fmt ty
let rec compare ty1 ty2 =
if ty1 == ty2 then 0
else
let tag_to_int ty =
match ty with
| Base _ -> 0
| Stream _ -> 1
| Prod _ -> 2
| Fun _ -> 3
| Warped _ -> 4
in
match ty1, ty2 with
| Base bty1, Base bty2 ->
compare_base bty1 bty2
| Stream ty1, Stream ty2 ->
compare ty1 ty2
| Prod (ty1, ty2), Prod (ty1', ty2')
| Fun (ty1, ty2), Fun (ty1', ty2') ->
Warp.Utils.compare_both
(compare ty1 ty1')
(fun () -> compare ty2 ty2')
| Warped (ck, ty), Warped (ck', ty') ->
Warp.Utils.compare_both
(Warp.Formal.compare ck ck')
(fun () -> compare ty ty')
| (Base _ | Stream _ | Prod _ | Fun _ | Warped _), _ ->
Warp.Utils.compare_int (tag_to_int ty1) (tag_to_int ty2)
let equal ty1 ty2 = compare ty1 ty2 = 0
let equiv ty1 ty2 = equal (normalize ty1) (normalize ty2)
let later ty =
Warped (Warp.Formal.zero_one, ty)
let constant ty =
Warped (Warp.Formal.omega, ty)
let get_base ty =
match ty with
| Base bty ->
bty
| _ ->
invalid_arg "get_base"
let get_stream ty =
match ty with
| Stream bty ->
bty
| _ ->
invalid_arg "get_stream"
let get_fun ty =
match ty with
| Fun (ty1, ty2) ->
ty1, ty2
| _ ->
invalid_arg "get_fun"
let get_prod ty =
match ty with
| Prod (ty1, ty2) ->
ty1, ty2
| _ ->
invalid_arg "get_prod"
let get_warped ty =
match ty with
| Warped (p, ty) ->
p, ty
| _ ->
invalid_arg "get_warped"
|
f4f088d9ac17ec7a8e204b0ed326b8272b942844bdc76489fd8eb3ec88524a83 | tweag/lagoon | Cookie.hs | Copyright 2020 Pfizer 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.
# OPTIONS_GHC -fno - warn - orphans #
module Lagoon.Server.Servant.Cookie (ServerWithCookie(..)) where
import Network.HTTP.Types (ok200)
import Servant
import Servant.API.ContentTypes
import Servant.Server.Internal
import Web.Cookie
import qualified Data.ByteString.Builder as BS.Bld
import qualified Data.ByteString.Lazy.UTF8 as BS.L.UTF8
import qualified Data.Text as Text
import Lagoon.Interface.API
| Adapted from the ' HasServer ' instance for ' Verb .. Headers '
--
-- TODO: This would make more sense:
--
> instance ( ( Verb method status ctypes a ) ) where
> type ServerT ( ( Verb method status ctypes a ) ) m = m ( ServerWithCookie a )
--
-- but it doens't work for some reason. I don't know why.
instance AllCTRender ctypes a => HasServer (WithCookie (Post ctypes a)) ctxt where
type ServerT (WithCookie (Post ctypes a)) m = m (ServerWithCookie a)
route Proxy _ctxt sub =
methodRouterHeaders
method
(Proxy :: Proxy ctypes)
status
(fmap aux <$> sub)
where
aux :: ServerWithCookie a -> Headers '[Header "Set-Cookie" SetCookie] a
aux (NoCookie a) = noHeader a
aux (WithCookie cookie a) = addHeader cookie a
method = reflectMethod (Proxy :: Proxy 'POST)
status = ok200
| Server - side interpretation of ' '
data ServerWithCookie a =
WithCookie SetCookie a
| NoCookie a
{-------------------------------------------------------------------------------
Auxiliary
-------------------------------------------------------------------------------}
-- | Annoyingly @cookie@ provides 'Text' versions for 'Cookies'
but not for ' SetCookie '
instance ToHttpApiData SetCookie where
toQueryParam = Text.pack
. BS.L.UTF8.toString
. BS.Bld.toLazyByteString
. renderSetCookie
| null | https://raw.githubusercontent.com/tweag/lagoon/2ef0440db810f4f45dbed160b369daf41d92bfa4/server/src/Lagoon/Server/Servant/Cookie.hs | haskell | 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.
TODO: This would make more sense:
but it doens't work for some reason. I don't know why.
------------------------------------------------------------------------------
Auxiliary
------------------------------------------------------------------------------
| Annoyingly @cookie@ provides 'Text' versions for 'Cookies' | Copyright 2020 Pfizer Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
# OPTIONS_GHC -fno - warn - orphans #
module Lagoon.Server.Servant.Cookie (ServerWithCookie(..)) where
import Network.HTTP.Types (ok200)
import Servant
import Servant.API.ContentTypes
import Servant.Server.Internal
import Web.Cookie
import qualified Data.ByteString.Builder as BS.Bld
import qualified Data.ByteString.Lazy.UTF8 as BS.L.UTF8
import qualified Data.Text as Text
import Lagoon.Interface.API
| Adapted from the ' HasServer ' instance for ' Verb .. Headers '
> instance ( ( Verb method status ctypes a ) ) where
> type ServerT ( ( Verb method status ctypes a ) ) m = m ( ServerWithCookie a )
instance AllCTRender ctypes a => HasServer (WithCookie (Post ctypes a)) ctxt where
type ServerT (WithCookie (Post ctypes a)) m = m (ServerWithCookie a)
route Proxy _ctxt sub =
methodRouterHeaders
method
(Proxy :: Proxy ctypes)
status
(fmap aux <$> sub)
where
aux :: ServerWithCookie a -> Headers '[Header "Set-Cookie" SetCookie] a
aux (NoCookie a) = noHeader a
aux (WithCookie cookie a) = addHeader cookie a
method = reflectMethod (Proxy :: Proxy 'POST)
status = ok200
| Server - side interpretation of ' '
data ServerWithCookie a =
WithCookie SetCookie a
| NoCookie a
but not for ' SetCookie '
instance ToHttpApiData SetCookie where
toQueryParam = Text.pack
. BS.L.UTF8.toString
. BS.Bld.toLazyByteString
. renderSetCookie
|
c9f1c6a5469dd211ff44855a82d30776bb7e51fe546cfa476b2e4973b654db56 | xh4/web-toolkit | comparison.lisp | (in-package #:local-time.test)
(defsuite* (comparison :in simple))
(defmacro defcmptest (comparator-name &body args)
`(deftest ,(symbolicate 'test/simple/comparison/ comparator-name) ()
(flet ((make (day &optional (sec 0) (nsec 0))
(make-timestamp :day day :sec sec :nsec nsec)))
,@(loop
:for entry :in args
:when (= (length entry) 1)
:do (push 'is entry)
:else
:do (if (member (car entry) '(t true is) :test #'eq)
'is
'is)
collect (let ((body `(,comparator-name (make ,@(second entry))
(make ,@(third entry)))))
(cond
((eq (car entry) 'true)
`(is ,body))
((eq (car entry) 'false)
`(is (not ,body)))
(t (error "Don't know how to interpret ~S" entry))))))))
(defcmptest timestamp<
(true (1 0 0)
(2 0 0))
(true (0 1 0)
(0 2 0))
(true (0 0 1)
(0 0 2))
(false (2 0 0)
(1 0 0))
(false (0 2 0)
(0 1 0))
(false (0 0 2)
(0 0 1)))
(defcmptest timestamp<=
(true (1 0 0)
(2 0 0))
(true (0 1 0)
(0 2 0))
(true (0 0 1)
(0 0 2))
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (2 0 0)
(1 0 0))
(false (0 2 0)
(0 1 0))
(false (0 0 2)
(0 0 1)))
(defcmptest timestamp>
(true (2 0 0)
(1 0 0))
(true (0 2 0)
(0 1 0))
(true (0 0 2)
(0 0 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(defcmptest timestamp>=
(true (2 0 0)
(1 0 0))
(true (0 2 0)
(0 1 0))
(true (0 0 2)
(0 0 1))
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(defcmptest timestamp=
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(deftest test/simple/comparison/timestamp=/2 ()
(is (timestamp= (make-timestamp) (make-timestamp)))
(is (not (timestamp= (make-timestamp) (make-timestamp :nsec 1)))))
(deftest test/simple/comparison/timestamp=/3 ()
(is (eql (handler-case
(timestamp= (make-timestamp) nil)
(type-error ()
:correct-error))
:correct-error)))
(deftest test/simple/comparison/timestamp/= ()
(is (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2)))
(is (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2) (make-timestamp :nsec 3)))
(is (not (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2) (make-timestamp :nsec 1))))
(is (not (timestamp/= (make-timestamp) (make-timestamp)))))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/local-time-20190710-git/test/comparison.lisp | lisp | (in-package #:local-time.test)
(defsuite* (comparison :in simple))
(defmacro defcmptest (comparator-name &body args)
`(deftest ,(symbolicate 'test/simple/comparison/ comparator-name) ()
(flet ((make (day &optional (sec 0) (nsec 0))
(make-timestamp :day day :sec sec :nsec nsec)))
,@(loop
:for entry :in args
:when (= (length entry) 1)
:do (push 'is entry)
:else
:do (if (member (car entry) '(t true is) :test #'eq)
'is
'is)
collect (let ((body `(,comparator-name (make ,@(second entry))
(make ,@(third entry)))))
(cond
((eq (car entry) 'true)
`(is ,body))
((eq (car entry) 'false)
`(is (not ,body)))
(t (error "Don't know how to interpret ~S" entry))))))))
(defcmptest timestamp<
(true (1 0 0)
(2 0 0))
(true (0 1 0)
(0 2 0))
(true (0 0 1)
(0 0 2))
(false (2 0 0)
(1 0 0))
(false (0 2 0)
(0 1 0))
(false (0 0 2)
(0 0 1)))
(defcmptest timestamp<=
(true (1 0 0)
(2 0 0))
(true (0 1 0)
(0 2 0))
(true (0 0 1)
(0 0 2))
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (2 0 0)
(1 0 0))
(false (0 2 0)
(0 1 0))
(false (0 0 2)
(0 0 1)))
(defcmptest timestamp>
(true (2 0 0)
(1 0 0))
(true (0 2 0)
(0 1 0))
(true (0 0 2)
(0 0 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(defcmptest timestamp>=
(true (2 0 0)
(1 0 0))
(true (0 2 0)
(0 1 0))
(true (0 0 2)
(0 0 1))
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(defcmptest timestamp=
(true (1 0 0)
(1 0 0))
(true (1 1 0)
(1 1 0))
(true (1 1 1)
(1 1 1))
(false (1 0 0)
(2 0 0))
(false (0 1 0)
(0 2 0))
(false (0 0 1)
(0 0 2)))
(deftest test/simple/comparison/timestamp=/2 ()
(is (timestamp= (make-timestamp) (make-timestamp)))
(is (not (timestamp= (make-timestamp) (make-timestamp :nsec 1)))))
(deftest test/simple/comparison/timestamp=/3 ()
(is (eql (handler-case
(timestamp= (make-timestamp) nil)
(type-error ()
:correct-error))
:correct-error)))
(deftest test/simple/comparison/timestamp/= ()
(is (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2)))
(is (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2) (make-timestamp :nsec 3)))
(is (not (timestamp/= (make-timestamp :nsec 1) (make-timestamp :nsec 2) (make-timestamp :nsec 1))))
(is (not (timestamp/= (make-timestamp) (make-timestamp)))))
|
|
11843dc960bff51281b0d215b3543328437c2003ad3ca3ece0e9ccd7a8af1c96 | melisgl/try | package.lisp | (mgl-pax:define-package #:try-test
(:use #:common-lisp #:alexandria #:try))
| null | https://raw.githubusercontent.com/melisgl/try/a37c61f8b81d4bdf38f559bca54eef3868bb87a1/test/package.lisp | lisp | (mgl-pax:define-package #:try-test
(:use #:common-lisp #:alexandria #:try))
|
|
412d41a19cb1f61963aea767ca70842530e5a64b95612fe86685d50a46d53cea | lisp-korea/sicp2014 | ex-2-59.scm | ex 2.59
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-of-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((not (element-of-set? (car set1) set2))
(cons (car set1)
(union-set (cdr set1) set2)))
(else (union-set (cdr set1) set2))))
(union-set '(1 2 3 4) '(3 4 5 6))
;;=> (1 2 3 4 5 6)
| null | https://raw.githubusercontent.com/lisp-korea/sicp2014/9e60f70cb84ad2ad5987a71aebe1069db288b680/vvalkyrie/2.3/ex-2-59.scm | scheme | => (1 2 3 4 5 6) | ex 2.59
(define (element-of-set? x set)
(cond ((null? set) #f)
((equal? x (car set)) #t)
(else (element-of-set? x (cdr set)))))
(define (adjoin-of-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((not (element-of-set? (car set1) set2))
(cons (car set1)
(union-set (cdr set1) set2)))
(else (union-set (cdr set1) set2))))
(union-set '(1 2 3 4) '(3 4 5 6))
|
38b58d36912fd79a23fad02d6b138a93590163a88a7c75f88f2607f1c51e8c2a | SquidDev/urn | alist.lisp | (import core/prelude ())
(defun assoc (list key or-val)
"Return the value given by KEY in the association list LIST, or, in the
case that it does not exist, the value OR-VAL, which can be nil.
### Example:
```cl
> (assoc '((\"foo\" 1) (\"bar\" 2)) \"foo\" \"?\")
out = 1
> (assoc '((\"foo\" 1) (\"bar\" 2)) \"baz\" \"?\")
out = \"?\"
```"
(cond
[(or (not (list? list))
(empty? list))
or-val]
[(eq? (caar list) key)
(cadar list)]
[else (assoc (cdr list) key or-val)]))
(defun assoc? (list key)
"Check that KEY is bound in the association list LIST.
### Example:
```cl
> (assoc? '((\"foo\" 1) (\"bar\" 2)) \"foo\")
out = true
> (assoc? '((\"foo\" 1) (\"bar\" 2)) \"baz\")
out = false
```"
(cond
[(or (not (list? list)) (empty? list)) false]
[(eq? (caar list) key) true]
[else (assoc? (cdr list) key)]))
(defun insert (alist key val)
"Extend the association list ALIST by inserting VAL, bound to the key
KEY.
### Example:
```cl
> (insert '((\"foo\" 1)) \"bar\" 2)
out = ((\"foo\" 1) (\"bar\" 2))
```"
(snoc alist (list key val)))
(defun extend (ls key val)
"Extend the association list LIST_ by inserting VAL, bound to the key
KEY, overriding any previous value.
### Example:
```cl
> (extend '((\"foo\" 1)) \"bar\" 2)
out = ((\"bar\" 2) (\"foo\" 1))
```"
(cons (list key val) ls))
(defun insert! (alist key val)
"Extend the association list ALIST in place by inserting VAL, bound to
the key KEY.
### Example:
```cl
> (define x '((\"foo\" 1)))
> (insert! x \"bar\" 2)
> x
out = ((\"foo\" 1) (\"bar\" 2))
```"
(push! alist (list key val)))
(defun assoc->struct (list)
"Convert the association list LIST into a structure. Much like
[[assoc]], in the case there are several values bound to the same key,
the first value is chosen.
### Example:
```cl
> (assoc->struct '((\"a\" 1)))
out = {\"a\" 1}
```"
(assert-type! list list)
(let [(ret {})]
(for-each x list
(let [(hd (cond
[(key? (car x)) (.> (car x) "value")]
[else (car x)]))]
(unless (.> ret hd)
(.<! ret hd (cadr x)))))
ret))
(defun struct->assoc (tbl)
"Convert the structure TBL into an association list. Note that
`(eq? x (struct->assoc (assoc->struct x)))` is not guaranteed,
because duplicate elements will be removed.
### Example
```cl
> (struct->assoc { :a 1 })
out = ((\"a\" 1))
```"
(with (out '())
(for-pairs (k v) tbl
(push! out (list k v)))
out))
| null | https://raw.githubusercontent.com/SquidDev/urn/6e6717cf1376b0950e569e3771cb7e287aed291d/lib/data/alist.lisp | lisp | (import core/prelude ())
(defun assoc (list key or-val)
"Return the value given by KEY in the association list LIST, or, in the
case that it does not exist, the value OR-VAL, which can be nil.
### Example:
```cl
> (assoc '((\"foo\" 1) (\"bar\" 2)) \"foo\" \"?\")
out = 1
> (assoc '((\"foo\" 1) (\"bar\" 2)) \"baz\" \"?\")
out = \"?\"
```"
(cond
[(or (not (list? list))
(empty? list))
or-val]
[(eq? (caar list) key)
(cadar list)]
[else (assoc (cdr list) key or-val)]))
(defun assoc? (list key)
"Check that KEY is bound in the association list LIST.
### Example:
```cl
> (assoc? '((\"foo\" 1) (\"bar\" 2)) \"foo\")
out = true
> (assoc? '((\"foo\" 1) (\"bar\" 2)) \"baz\")
out = false
```"
(cond
[(or (not (list? list)) (empty? list)) false]
[(eq? (caar list) key) true]
[else (assoc? (cdr list) key)]))
(defun insert (alist key val)
"Extend the association list ALIST by inserting VAL, bound to the key
KEY.
### Example:
```cl
> (insert '((\"foo\" 1)) \"bar\" 2)
out = ((\"foo\" 1) (\"bar\" 2))
```"
(snoc alist (list key val)))
(defun extend (ls key val)
"Extend the association list LIST_ by inserting VAL, bound to the key
KEY, overriding any previous value.
### Example:
```cl
> (extend '((\"foo\" 1)) \"bar\" 2)
out = ((\"bar\" 2) (\"foo\" 1))
```"
(cons (list key val) ls))
(defun insert! (alist key val)
"Extend the association list ALIST in place by inserting VAL, bound to
the key KEY.
### Example:
```cl
> (define x '((\"foo\" 1)))
> (insert! x \"bar\" 2)
> x
out = ((\"foo\" 1) (\"bar\" 2))
```"
(push! alist (list key val)))
(defun assoc->struct (list)
"Convert the association list LIST into a structure. Much like
[[assoc]], in the case there are several values bound to the same key,
the first value is chosen.
### Example:
```cl
> (assoc->struct '((\"a\" 1)))
out = {\"a\" 1}
```"
(assert-type! list list)
(let [(ret {})]
(for-each x list
(let [(hd (cond
[(key? (car x)) (.> (car x) "value")]
[else (car x)]))]
(unless (.> ret hd)
(.<! ret hd (cadr x)))))
ret))
(defun struct->assoc (tbl)
"Convert the structure TBL into an association list. Note that
`(eq? x (struct->assoc (assoc->struct x)))` is not guaranteed,
because duplicate elements will be removed.
### Example
```cl
> (struct->assoc { :a 1 })
out = ((\"a\" 1))
```"
(with (out '())
(for-pairs (k v) tbl
(push! out (list k v)))
out))
|
|
103367329551b23c4df558e3ec46e0d9f1b71059ee82356ed772d61bf038c470 | WorksHub/client | subs.cljc | (ns wh.promotions.create-promotion.subs
(:require [clojure.set :as set]
[re-frame.core :refer [reg-sub reg-sub-raw]]
[wh.common.blog :as blog]
[wh.common.job :as job]
[wh.common.subs]
[wh.promotions.create-promotion.db :as db]
[wh.re-frame.subs :refer [<sub]])
(:require-macros [wh.re-frame.subs :refer [reaction]]))
(reg-sub
::object-type
:<- [:wh/page-param :type]
(fn [type _] type))
(reg-sub
::object-id
:<- [:wh/page-param :id]
(fn [id _] id))
(defn- object-state
"Takes object and condition that determines whether object should be blocked
from promoting (when it's unpublished, or closed), and returns object,
or information why object is not given, or nil when object is totally absent."
[obj not-allowed]
(cond
(nil? obj) nil
not-allowed :not-allowed
(map? obj) obj
:else :not-recognized))
(defn- prepare-job-preview
"Prepare job data structure to be previewed safely on feed and jobsboard"
[job]
(->> (set/rename-keys (:company job) {:logo :image-url})
(assoc job :job-company)))
(reg-sub-raw
::job
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
;; use some-> to make sure data is here, and we do not try to process absent data
job (some-> (<sub [:graphql/result :job {:id id}])
(:job)
(job/translate-job)
(prepare-job-preview))]
(object-state job (not (:published job)))))))
(reg-sub-raw
::company
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
company (some-> (<sub [:graphql/result :company {:id id}])
(:company)
(update :size keyword))]
(object-state company (not (:profile-enabled company)))))))
(reg-sub-raw
::issue
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
issue (some-> (<sub [:graphql/result :issue {:id id}])
(:issue)
(set/rename-keys
{:company :issue-company})
(update
:issue-company
(fn [company]
(set/rename-keys company {:logo :image-url}))))]
(object-state issue (= "closed" (:status issue)))))))
(reg-sub-raw
::article
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
blog (some-> (<sub [:graphql/result :blog {:id id}])
(:blog)
(blog/translate-blog))]
(object-state blog (not (:published blog)))))))
(reg-sub-raw
::object
(fn [_ _]
(reaction
;; create qualified keyword from object type: #{::issue ::job ::company ::article}
(<sub [(keyword :wh.promotions.create-promotion.subs (<sub [::object-type]))]))))
(reg-sub
::promoter
:<- [:user/sub-db]
(fn [{:keys [wh.user.db/name wh.user.db/image-url wh.user.db/id] :as user} _]
{:image-url image-url
:name name
:id id}))
(reg-sub
::description
(fn [{:keys [::db/description] :as db} _]
description))
(reg-sub-raw
::can-publish?
(fn [_ [_ channel]]
(reaction
(let [status (<sub [::send-promotion-status channel])
object (<sub [::object])
description (<sub [::description])]
(and (map? object)
(not (#{:sending :success} status))
(or (not= channel :feed)
(> (count description) 3)))))))
(reg-sub
::send-promotion-status
(fn [db [_ channel]]
(get-in db [::db/promotion-status channel])))
(reg-sub
::selected-channel
(fn [db [_ channel]]
(get db ::db/selected-channel :feed)))
| null | https://raw.githubusercontent.com/WorksHub/client/a51729585c2b9d7692e57b3edcd5217c228cf47c/client/src/wh/promotions/create_promotion/subs.cljc | clojure | use some-> to make sure data is here, and we do not try to process absent data
create qualified keyword from object type: #{::issue ::job ::company ::article} | (ns wh.promotions.create-promotion.subs
(:require [clojure.set :as set]
[re-frame.core :refer [reg-sub reg-sub-raw]]
[wh.common.blog :as blog]
[wh.common.job :as job]
[wh.common.subs]
[wh.promotions.create-promotion.db :as db]
[wh.re-frame.subs :refer [<sub]])
(:require-macros [wh.re-frame.subs :refer [reaction]]))
(reg-sub
::object-type
:<- [:wh/page-param :type]
(fn [type _] type))
(reg-sub
::object-id
:<- [:wh/page-param :id]
(fn [id _] id))
(defn- object-state
"Takes object and condition that determines whether object should be blocked
from promoting (when it's unpublished, or closed), and returns object,
or information why object is not given, or nil when object is totally absent."
[obj not-allowed]
(cond
(nil? obj) nil
not-allowed :not-allowed
(map? obj) obj
:else :not-recognized))
(defn- prepare-job-preview
"Prepare job data structure to be previewed safely on feed and jobsboard"
[job]
(->> (set/rename-keys (:company job) {:logo :image-url})
(assoc job :job-company)))
(reg-sub-raw
::job
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
job (some-> (<sub [:graphql/result :job {:id id}])
(:job)
(job/translate-job)
(prepare-job-preview))]
(object-state job (not (:published job)))))))
(reg-sub-raw
::company
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
company (some-> (<sub [:graphql/result :company {:id id}])
(:company)
(update :size keyword))]
(object-state company (not (:profile-enabled company)))))))
(reg-sub-raw
::issue
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
issue (some-> (<sub [:graphql/result :issue {:id id}])
(:issue)
(set/rename-keys
{:company :issue-company})
(update
:issue-company
(fn [company]
(set/rename-keys company {:logo :image-url}))))]
(object-state issue (= "closed" (:status issue)))))))
(reg-sub-raw
::article
(fn [_ _]
(reaction
(let [id (<sub [::object-id])
blog (some-> (<sub [:graphql/result :blog {:id id}])
(:blog)
(blog/translate-blog))]
(object-state blog (not (:published blog)))))))
(reg-sub-raw
::object
(fn [_ _]
(reaction
(<sub [(keyword :wh.promotions.create-promotion.subs (<sub [::object-type]))]))))
(reg-sub
::promoter
:<- [:user/sub-db]
(fn [{:keys [wh.user.db/name wh.user.db/image-url wh.user.db/id] :as user} _]
{:image-url image-url
:name name
:id id}))
(reg-sub
::description
(fn [{:keys [::db/description] :as db} _]
description))
(reg-sub-raw
::can-publish?
(fn [_ [_ channel]]
(reaction
(let [status (<sub [::send-promotion-status channel])
object (<sub [::object])
description (<sub [::description])]
(and (map? object)
(not (#{:sending :success} status))
(or (not= channel :feed)
(> (count description) 3)))))))
(reg-sub
::send-promotion-status
(fn [db [_ channel]]
(get-in db [::db/promotion-status channel])))
(reg-sub
::selected-channel
(fn [db [_ channel]]
(get db ::db/selected-channel :feed)))
|
a4648dfb6ea50f1db9d1c9a1234c2014478df48c37ec4177fa0326d429e4a63d | travisbrady/flajolet | card.ml |
* Simple example utility
* reads strings from stdin and when done prints the count of unique
* strings stdin to stdout
* A bit like cat somefile.txt | sort -u | wc -l
* Simple example utility
* reads strings from stdin and when done prints the count of unique
* strings stdin to stdout
* A bit like cat somefile.txt | sort -u | wc -l
*)
open Core.Std
let printf = Printf.printf
let () =
let hll = Hyperloglog.create 0.03 in
In_channel.iter_lines stdin ~f:(fun line ->
Hyperloglog.offer hll line
);
printf "%f\n" (Hyperloglog.card hll)
| null | https://raw.githubusercontent.com/travisbrady/flajolet/a6c530bf1dd73b9fa8b7185d84a5e20458a3d8af/examples/card.ml | ocaml |
* Simple example utility
* reads strings from stdin and when done prints the count of unique
* strings stdin to stdout
* A bit like cat somefile.txt | sort -u | wc -l
* Simple example utility
* reads strings from stdin and when done prints the count of unique
* strings stdin to stdout
* A bit like cat somefile.txt | sort -u | wc -l
*)
open Core.Std
let printf = Printf.printf
let () =
let hll = Hyperloglog.create 0.03 in
In_channel.iter_lines stdin ~f:(fun line ->
Hyperloglog.offer hll line
);
printf "%f\n" (Hyperloglog.card hll)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.