_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 |
|---|---|---|---|---|---|---|---|---|
ddab271df1a2f7506651fce58ac53fd2da5cbf4c4a840279b69cf31e4f2bc07e | mmirman/rpc-framework | RPC.hs | |
Module : Network . Remote . RPC
Copyright : ( c ) 2012
License : BSD - style ( see the file LICENSE )
Maintainer : < >
Stability : experimental
Portability : Many GHC only extensions
Declaration of the frontend for RPC .
Module : Network.Remote.RPC
Copyright : (c) Matthew Mirman 2012
License : BSD-style (see the file LICENSE)
Maintainer : Matthew Mirman <>
Stability : experimental
Portability : Many GHC only extensions
Declaration of the frontend for RPC.
-}
module Network.Remote.RPC ( Host(..)
, WIO()
, world
, Servable()
, liftIO
, runServer
, runServerBG
, onHost
, autoService
, makeHost
, makeServices
, rpcCall
, Forkable(..)
-- * Example: Making remote Calls
$ remoteExample
, MonadTrans(..)
) where
import Network.Remote.RPC.Internal.Runtime
import Network.Remote.RPC.Internal.Templates
import Control.Concurrent.ForkableRPC
import Control.Monad.Trans.Class ( MonadTrans(..))
$ remoteExample
This example shows how to make remote procedure from a Client to a Host .
It also shows how to send functions , which can now be collected .
> -- LANGUAGE TemplateHaskell , KindSignatures , FlexibleContexts
> module Main where
> import Network . Remote . RPC
First , hosts must be declared .
In the future , hosts might be declared in a configuration file such that
they can be configured at runtime rather than only at compile time .
@
$ ( ' makeHost ' \"Client\ " \"localhost\ " 9000 )
$ ( ' makeHost ' \"Server\ " \"localhost\ " 9001 )
@
The following services will run on the server .
@
doubleServer : : Integer - > ' WIO ' Server IO Integer
doubleServer t = return $ t + t
addServer : : Integer - > ' WIO ' Server IO ( Integer - > Integer )
addServer t = return ( t + )
@
When used , @addServer@ will return a function of type @Integer - > ' WIO ' w IO Integer@
because the resulting function will actually be a remote call . Every time @addServer@
is called , it turns the function into a service which is collected when the function is no
longer needed .
> client = do
> onHost Client
> double < - $ ( rpcCall ' doubleServer ) 3
> liftIO $ putStrLn $ " r(h3+h3 ) ? " + + show double
>
> add < - $ ( rpcCall ' addServer ) 4
> r < - add 6 -- add : : Integer - > WIO Client IO Integer
> liftIO $ putStrLn $ " r(h4 + ) h6 ? " + + show r
Despite ' rpcCall ' being a template splice , the resulting splice is type safe :
@ $ ( ' rpcCall ' ' doubleServer ) : : ( ' Host ' w , ' Servable ' m ) = > Integer - > ' WIO ' w m Integer @
Now we declare the runtime . Usually this would be in two different mains , but for
educational and testing purposes , both the client and server can be run from the same main .
@
main = do
' runServerBG ' $ ( autoService ' Server )
' runServer ' client
@
( 1 ) @$('autoService ' ' looks for services declared in the file which definitely run on server , and
runs them as services on the intended host ( @Server@ in this case ) .
( 1 ) ' runServerBG ' runs a service server on a background OS thread , and returns
( 1 ) ' runServer ' runs a service server and does not return .
( 1 ) When run :
> > > : main
r(h3+h3 ) ? 6
r(h4 + ) h6 ? 10
Where @rVal@ means is on the server and means is on the client .
This example shows how to make remote procedure from a Client to a Host.
It also shows how to send functions, which can now be collected.
>-- LANGUAGE TemplateHaskell, KindSignatures, FlexibleContexts
>module Main where
>import Network.Remote.RPC
First, hosts must be declared.
In the future, hosts might be declared in a configuration file such that
they can be configured at runtime rather than only at compile time.
@
$('makeHost' \"Client\" \"localhost\" 9000)
$('makeHost' \"Server\" \"localhost\" 9001)
@
The following services will run on the server.
@
doubleServer :: Integer -> 'WIO' Server IO Integer
doubleServer t = return $ t + t
addServer :: Integer -> 'WIO' Server IO (Integer -> Integer)
addServer t = return (t +)
@
When used, @addServer@ will return a function of type @Integer -> 'WIO' w IO Integer@
because the resulting function will actually be a remote call. Every time @addServer@
is called, it turns the function into a service which is collected when the function is no
longer needed.
>client = do
> onHost Client
> double <- $(rpcCall 'doubleServer) 3
> liftIO $ putStrLn $ "r(h3+h3) ? " ++ show double
>
> add <- $(rpcCall 'addServer) 4
> r <- add 6 -- add :: Integer -> WIO Client IO Integer
> liftIO $ putStrLn $ "r(h4 +) h6 ? " ++ show r
Despite 'rpcCall' being a template splice, the resulting splice is type safe:
@ $('rpcCall' 'doubleServer) :: ('Host' w, 'Servable' m) => Integer -> 'WIO' w m Integer @
Now we declare the runtime. Usually this would be in two different mains, but for
educational and testing purposes, both the client and server can be run from the same main.
@
main = do
'runServerBG' $(autoService 'Server)
'runServer' client
@
(1) @$('autoService' 'Server)@ looks for services declared in the file which definitely run on server, and
runs them as services on the intended host (@Server@ in this case).
(1) 'runServerBG' runs a service server on a background OS thread, and returns
(1) 'runServer' runs a service server and does not return.
(1) When run:
>>> :main
r(h3+h3) ? 6
r(h4 +) h6 ? 10
Where @rVal@ means Val is on the server and @hVal@ means Val is on the client.
-}
| null | https://raw.githubusercontent.com/mmirman/rpc-framework/63568adc07e0b9e8e7e8cfdf5f9ee116668c5b21/src/Network/Remote/RPC.hs | haskell | * Example: Making remote Calls
LANGUAGE TemplateHaskell , KindSignatures , FlexibleContexts
add : : Integer - > WIO Client IO Integer
LANGUAGE TemplateHaskell, KindSignatures, FlexibleContexts
add :: Integer -> WIO Client IO Integer | |
Module : Network . Remote . RPC
Copyright : ( c ) 2012
License : BSD - style ( see the file LICENSE )
Maintainer : < >
Stability : experimental
Portability : Many GHC only extensions
Declaration of the frontend for RPC .
Module : Network.Remote.RPC
Copyright : (c) Matthew Mirman 2012
License : BSD-style (see the file LICENSE)
Maintainer : Matthew Mirman <>
Stability : experimental
Portability : Many GHC only extensions
Declaration of the frontend for RPC.
-}
module Network.Remote.RPC ( Host(..)
, WIO()
, world
, Servable()
, liftIO
, runServer
, runServerBG
, onHost
, autoService
, makeHost
, makeServices
, rpcCall
, Forkable(..)
$ remoteExample
, MonadTrans(..)
) where
import Network.Remote.RPC.Internal.Runtime
import Network.Remote.RPC.Internal.Templates
import Control.Concurrent.ForkableRPC
import Control.Monad.Trans.Class ( MonadTrans(..))
$ remoteExample
This example shows how to make remote procedure from a Client to a Host .
It also shows how to send functions , which can now be collected .
> module Main where
> import Network . Remote . RPC
First , hosts must be declared .
In the future , hosts might be declared in a configuration file such that
they can be configured at runtime rather than only at compile time .
@
$ ( ' makeHost ' \"Client\ " \"localhost\ " 9000 )
$ ( ' makeHost ' \"Server\ " \"localhost\ " 9001 )
@
The following services will run on the server .
@
doubleServer : : Integer - > ' WIO ' Server IO Integer
doubleServer t = return $ t + t
addServer : : Integer - > ' WIO ' Server IO ( Integer - > Integer )
addServer t = return ( t + )
@
When used , @addServer@ will return a function of type @Integer - > ' WIO ' w IO Integer@
because the resulting function will actually be a remote call . Every time @addServer@
is called , it turns the function into a service which is collected when the function is no
longer needed .
> client = do
> onHost Client
> double < - $ ( rpcCall ' doubleServer ) 3
> liftIO $ putStrLn $ " r(h3+h3 ) ? " + + show double
>
> add < - $ ( rpcCall ' addServer ) 4
> liftIO $ putStrLn $ " r(h4 + ) h6 ? " + + show r
Despite ' rpcCall ' being a template splice , the resulting splice is type safe :
@ $ ( ' rpcCall ' ' doubleServer ) : : ( ' Host ' w , ' Servable ' m ) = > Integer - > ' WIO ' w m Integer @
Now we declare the runtime . Usually this would be in two different mains , but for
educational and testing purposes , both the client and server can be run from the same main .
@
main = do
' runServerBG ' $ ( autoService ' Server )
' runServer ' client
@
( 1 ) @$('autoService ' ' looks for services declared in the file which definitely run on server , and
runs them as services on the intended host ( @Server@ in this case ) .
( 1 ) ' runServerBG ' runs a service server on a background OS thread , and returns
( 1 ) ' runServer ' runs a service server and does not return .
( 1 ) When run :
> > > : main
r(h3+h3 ) ? 6
r(h4 + ) h6 ? 10
Where @rVal@ means is on the server and means is on the client .
This example shows how to make remote procedure from a Client to a Host.
It also shows how to send functions, which can now be collected.
>module Main where
>import Network.Remote.RPC
First, hosts must be declared.
In the future, hosts might be declared in a configuration file such that
they can be configured at runtime rather than only at compile time.
@
$('makeHost' \"Client\" \"localhost\" 9000)
$('makeHost' \"Server\" \"localhost\" 9001)
@
The following services will run on the server.
@
doubleServer :: Integer -> 'WIO' Server IO Integer
doubleServer t = return $ t + t
addServer :: Integer -> 'WIO' Server IO (Integer -> Integer)
addServer t = return (t +)
@
When used, @addServer@ will return a function of type @Integer -> 'WIO' w IO Integer@
because the resulting function will actually be a remote call. Every time @addServer@
is called, it turns the function into a service which is collected when the function is no
longer needed.
>client = do
> onHost Client
> double <- $(rpcCall 'doubleServer) 3
> liftIO $ putStrLn $ "r(h3+h3) ? " ++ show double
>
> add <- $(rpcCall 'addServer) 4
> liftIO $ putStrLn $ "r(h4 +) h6 ? " ++ show r
Despite 'rpcCall' being a template splice, the resulting splice is type safe:
@ $('rpcCall' 'doubleServer) :: ('Host' w, 'Servable' m) => Integer -> 'WIO' w m Integer @
Now we declare the runtime. Usually this would be in two different mains, but for
educational and testing purposes, both the client and server can be run from the same main.
@
main = do
'runServerBG' $(autoService 'Server)
'runServer' client
@
(1) @$('autoService' 'Server)@ looks for services declared in the file which definitely run on server, and
runs them as services on the intended host (@Server@ in this case).
(1) 'runServerBG' runs a service server on a background OS thread, and returns
(1) 'runServer' runs a service server and does not return.
(1) When run:
>>> :main
r(h3+h3) ? 6
r(h4 +) h6 ? 10
Where @rVal@ means Val is on the server and @hVal@ means Val is on the client.
-}
|
c7b6a8013eb85bf7abfb3c7259d0d0ff8a6c7df062b3e9e76e8d6c3c74d07373 | well-typed/large-records | R020.hs | # LANGUAGE TypeApplications #
#if PROFILE_CORESIZE
{-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-}
#endif
#if PROFILE_TIMING
{-# OPTIONS_GHC -ddump-to-file -ddump-timings #-}
#endif
module Experiment.PreEval_Phantom.Sized.R020 where
import Data.Proxy
import Common.EmptyClass_Tree_Phantom
import Common.HListOfSize.HL020
requiresInstance :: ()
requiresInstance = requireEmptyClass_preEval (Proxy @ExampleFields)
| null | https://raw.githubusercontent.com/well-typed/large-records/c6c2b51af11e90f30822543d7ce4d1cb28cee294/large-records-benchmarks/bench/experiments/Experiment/PreEval_Phantom/Sized/R020.hs | haskell | # OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #
# OPTIONS_GHC -ddump-to-file -ddump-timings # | # LANGUAGE TypeApplications #
#if PROFILE_CORESIZE
#endif
#if PROFILE_TIMING
#endif
module Experiment.PreEval_Phantom.Sized.R020 where
import Data.Proxy
import Common.EmptyClass_Tree_Phantom
import Common.HListOfSize.HL020
requiresInstance :: ()
requiresInstance = requireEmptyClass_preEval (Proxy @ExampleFields)
|
12d566422eb39d61b7fe42194c4bf55542a0ff8c21a4322130c2a655a2957145 | eu90h/ascii-painter | generator.rkt | #lang racket/gui
(provide fill-generator% uniform-random-fill-generator% rogue-dungeon-generator%)
(require "scene.rkt" "point.rkt" "util.rkt" "room.rkt")
(define fill-generator%
(class object%
(init-field scene canvas tiles)
(field [tile null] [new-scene null])
(super-new)
(define/public (get-scene) new-scene)
(define dialog (new (class dialog% (init label)
(super-new [label label])
(define/override (on-subwindow-char receiver event)
(case (send event get-key-code)
[(#\return) (set-tile ok-btn event)]
[(escape) (send this show #f)]
[else #f])))
[label "Choose a tile"]))
(define hpanel (new horizontal-panel% [parent dialog]))
(define tile-choices
(new choice% [label "Tiles"] [parent hpanel] [choices (map tile-descr tiles)]))
(define choice->tile ((curry list-ref) tiles))
(define (set-tile btn evt)
(when (not (null? scene))
(let* ([t (choice->tile (send tile-choices get-selection))]
[s (make-object scene% (send scene get-width) (send scene get-height) t)])
(set! new-scene s)
(send dialog show #f))))
(define ok-btn (new button% [label "OK"] [parent hpanel] [callback set-tile]))
(define/public (process)
(send dialog show #t))))
(define uniform-random-fill-generator%
(class object%
(init-field scene canvas tiles num-tiles)
(super-new)
(define (place-random-tile tiles)
(send scene set
(sub1 (random (send scene get-width)))
(sub1 (random (send scene get-height)))
(random-element tiles)))
(define dialog (new (class dialog% (init label)
(super-new [label label])
(define/override (on-subwindow-char receiver event)
(case (send event get-key-code)
[(#\return) (set-tile ok-btn event)]
[(escape) (send this show #f)]
[else #f])))
[label "Choose a tile"]))
(define hpanel (new horizontal-panel% [parent dialog]))
(define tile-choices
(new list-box% [label ""] [parent hpanel] [choices (map tile-descr tiles)]
[style (list 'multiple)] [min-width 200] [min-height 200]))
(define vpanel (new vertical-panel% [parent hpanel]))
(define choice->tile ((curry list-ref) tiles))
(define number-field (new text-field% [label "Amount to add"] [parent vpanel]))
(define (set-tile btn evt)
(if (null? (send tile-choices get-selections)) (send this process)
(let ([tiles (map choice->tile (send tile-choices get-selections))])
(let loop ([n (string->number (send number-field get-value))])
(place-random-tile tiles)
(unless (zero? n) (loop (sub1 n))))
(send dialog show #f))))
(define ok-btn (new button% [label "OK"] [parent vpanel] [callback set-tile]))
(define/public (process)
(send number-field set-value "10")
(send dialog show #t))))
(define rogue-dungeon-generator%
(class object%
(init-field scene canvas tiles rooms)
(field [new-rooms null]
[paths null]
[tile null]
[xmin 5]
[xmax 7]
[ymin 5]
[ymax 7]
[num-rooms 6])
(super-new)
(define (add-room! r) (set! new-rooms (append new-rooms (list r))))
(define dialog (new dialog% [label "Choose a tile"]))
(define hpanel (new horizontal-panel% [parent dialog]))
(define tile-choices (new choice% [label "Tiles"] [parent hpanel] [choices (map tile-descr tiles)]))
(define (room-ok? r rs) (and (andmap (lambda (v) (< v 3)) (map (lambda (v) (room-distance v r)) rs))
(andmap (lambda (v) (room-intersects? r v)) rs)))
(define (set-tile btn evt)
(send dialog show #f)
(let place-rooms ([n num-rooms])
(unless (<= n 0)
(let* ([p (random-pt 0 (send scene get-width) 0 (send scene get-height))]
[width (random-integer xmin xmax)] [height (random-integer ymin ymax)]
[q (pt-add p (pt width height))] [walls null] [interior null])
(trace-filled-rectangle (lambda (x y)
(if (or (= x (pt-x q)) (= x (pt-x p)) (= y (pt-y p)) (= y (pt-y q)))
(set! walls (append walls (list (pt x y))))
(set! interior (append interior (list (pt x y)))))) p q)
(let ([r (room walls interior)])
(if (room-ok? r (append rooms new-rooms))
(begin (set! new-rooms (append new-rooms (list r))) (place-rooms (sub1 n)))
(place-rooms n))))))
(let connect-rooms ([unconnected-rooms (append rooms new-rooms)])
(unless (null? unconnected-rooms)
(when (= 1 (length unconnected-rooms))
(set! unconnected-rooms (append unconnected-rooms (random-element rooms))))
(let* ([r1 (random-element unconnected-rooms)]
[r2 (random-element (filter (lambda (r) (false? (equal? r r1))) unconnected-rooms))])
(let* ([pts null] [p1 (random-wall-pt r1)] [p3 (random-wall-pt r2)] [p2 (pt (pt-x p1) (pt-y p3))])
(trace-line (lambda (x y) (set! pts (append pts (list (pt x y))))) p1 p2)
(trace-line (lambda (x y) (set! pts (append pts (list (pt x y))))) p2 p3)
(set! paths (append paths (list (path r1 r2 pts)))))
(connect-rooms (filter (lambda (r) (and (false? (equal? r r1)) (false? (equal? r r2))))
unconnected-rooms)))))
(let ([t (list-ref tiles (send tile-choices get-selection))])
(map (lambda (r) (map (lambda (p) (send scene set (pt-x p) (pt-y p) t)) (room-wall-pts r))) new-rooms)
(map (lambda (path) (map (lambda (p) (send scene set (pt-x p) (pt-y p) t)) (path-pts path))) paths)))
(define ok-btn (new button% [label "OK"] [parent hpanel] [callback set-tile]))
(define/public (get-rooms) (append rooms new-rooms))
(define/public (process)
(send dialog show #t))))
| null | https://raw.githubusercontent.com/eu90h/ascii-painter/23297b324d855c96d3ca12742f4991e7c10127be/generator.rkt | racket | #lang racket/gui
(provide fill-generator% uniform-random-fill-generator% rogue-dungeon-generator%)
(require "scene.rkt" "point.rkt" "util.rkt" "room.rkt")
(define fill-generator%
(class object%
(init-field scene canvas tiles)
(field [tile null] [new-scene null])
(super-new)
(define/public (get-scene) new-scene)
(define dialog (new (class dialog% (init label)
(super-new [label label])
(define/override (on-subwindow-char receiver event)
(case (send event get-key-code)
[(#\return) (set-tile ok-btn event)]
[(escape) (send this show #f)]
[else #f])))
[label "Choose a tile"]))
(define hpanel (new horizontal-panel% [parent dialog]))
(define tile-choices
(new choice% [label "Tiles"] [parent hpanel] [choices (map tile-descr tiles)]))
(define choice->tile ((curry list-ref) tiles))
(define (set-tile btn evt)
(when (not (null? scene))
(let* ([t (choice->tile (send tile-choices get-selection))]
[s (make-object scene% (send scene get-width) (send scene get-height) t)])
(set! new-scene s)
(send dialog show #f))))
(define ok-btn (new button% [label "OK"] [parent hpanel] [callback set-tile]))
(define/public (process)
(send dialog show #t))))
(define uniform-random-fill-generator%
(class object%
(init-field scene canvas tiles num-tiles)
(super-new)
(define (place-random-tile tiles)
(send scene set
(sub1 (random (send scene get-width)))
(sub1 (random (send scene get-height)))
(random-element tiles)))
(define dialog (new (class dialog% (init label)
(super-new [label label])
(define/override (on-subwindow-char receiver event)
(case (send event get-key-code)
[(#\return) (set-tile ok-btn event)]
[(escape) (send this show #f)]
[else #f])))
[label "Choose a tile"]))
(define hpanel (new horizontal-panel% [parent dialog]))
(define tile-choices
(new list-box% [label ""] [parent hpanel] [choices (map tile-descr tiles)]
[style (list 'multiple)] [min-width 200] [min-height 200]))
(define vpanel (new vertical-panel% [parent hpanel]))
(define choice->tile ((curry list-ref) tiles))
(define number-field (new text-field% [label "Amount to add"] [parent vpanel]))
(define (set-tile btn evt)
(if (null? (send tile-choices get-selections)) (send this process)
(let ([tiles (map choice->tile (send tile-choices get-selections))])
(let loop ([n (string->number (send number-field get-value))])
(place-random-tile tiles)
(unless (zero? n) (loop (sub1 n))))
(send dialog show #f))))
(define ok-btn (new button% [label "OK"] [parent vpanel] [callback set-tile]))
(define/public (process)
(send number-field set-value "10")
(send dialog show #t))))
(define rogue-dungeon-generator%
(class object%
(init-field scene canvas tiles rooms)
(field [new-rooms null]
[paths null]
[tile null]
[xmin 5]
[xmax 7]
[ymin 5]
[ymax 7]
[num-rooms 6])
(super-new)
(define (add-room! r) (set! new-rooms (append new-rooms (list r))))
(define dialog (new dialog% [label "Choose a tile"]))
(define hpanel (new horizontal-panel% [parent dialog]))
(define tile-choices (new choice% [label "Tiles"] [parent hpanel] [choices (map tile-descr tiles)]))
(define (room-ok? r rs) (and (andmap (lambda (v) (< v 3)) (map (lambda (v) (room-distance v r)) rs))
(andmap (lambda (v) (room-intersects? r v)) rs)))
(define (set-tile btn evt)
(send dialog show #f)
(let place-rooms ([n num-rooms])
(unless (<= n 0)
(let* ([p (random-pt 0 (send scene get-width) 0 (send scene get-height))]
[width (random-integer xmin xmax)] [height (random-integer ymin ymax)]
[q (pt-add p (pt width height))] [walls null] [interior null])
(trace-filled-rectangle (lambda (x y)
(if (or (= x (pt-x q)) (= x (pt-x p)) (= y (pt-y p)) (= y (pt-y q)))
(set! walls (append walls (list (pt x y))))
(set! interior (append interior (list (pt x y)))))) p q)
(let ([r (room walls interior)])
(if (room-ok? r (append rooms new-rooms))
(begin (set! new-rooms (append new-rooms (list r))) (place-rooms (sub1 n)))
(place-rooms n))))))
(let connect-rooms ([unconnected-rooms (append rooms new-rooms)])
(unless (null? unconnected-rooms)
(when (= 1 (length unconnected-rooms))
(set! unconnected-rooms (append unconnected-rooms (random-element rooms))))
(let* ([r1 (random-element unconnected-rooms)]
[r2 (random-element (filter (lambda (r) (false? (equal? r r1))) unconnected-rooms))])
(let* ([pts null] [p1 (random-wall-pt r1)] [p3 (random-wall-pt r2)] [p2 (pt (pt-x p1) (pt-y p3))])
(trace-line (lambda (x y) (set! pts (append pts (list (pt x y))))) p1 p2)
(trace-line (lambda (x y) (set! pts (append pts (list (pt x y))))) p2 p3)
(set! paths (append paths (list (path r1 r2 pts)))))
(connect-rooms (filter (lambda (r) (and (false? (equal? r r1)) (false? (equal? r r2))))
unconnected-rooms)))))
(let ([t (list-ref tiles (send tile-choices get-selection))])
(map (lambda (r) (map (lambda (p) (send scene set (pt-x p) (pt-y p) t)) (room-wall-pts r))) new-rooms)
(map (lambda (path) (map (lambda (p) (send scene set (pt-x p) (pt-y p) t)) (path-pts path))) paths)))
(define ok-btn (new button% [label "OK"] [parent hpanel] [callback set-tile]))
(define/public (get-rooms) (append rooms new-rooms))
(define/public (process)
(send dialog show #t))))
| |
691f0f3fc8b4953755a21478e0c04b2dedf47042c71dc8387aefbd000aefd098 | ChrisPenner/proton | Withering.hs | module Data.Profunctor.Withering where
import Data.Profunctor
import Data.Profunctor.Traversing
import Control.Applicative
class (Traversing p) => Withering p where
cull :: (forall f. Alternative f => (a -> f b) -> (s -> f t)) -> p a b -> p s t
instance Alternative f => Withering (Star f) where
cull f (Star amb) = Star (f amb)
instance Monoid m => Withering (Forget m) where
cull f (Forget h) = Forget (getAnnihilation . f (AltConst . Just . h))
where
getAnnihilation (AltConst Nothing) = mempty
getAnnihilation (AltConst (Just m)) = m
newtype AltConst a b = AltConst (Maybe a)
deriving stock (Eq, Ord, Show, Functor)
instance Monoid a => Applicative (AltConst a) where
pure _ = (AltConst (Just mempty))
(AltConst Nothing) <*> _ = (AltConst Nothing)
_ <*> (AltConst Nothing) = (AltConst Nothing)
(AltConst (Just a)) <*> (AltConst (Just b)) = AltConst (Just (a <> b))
instance (Semigroup a) => Semigroup (AltConst a x) where
(AltConst Nothing) <> _ = (AltConst Nothing)
_ <> (AltConst Nothing) = (AltConst Nothing)
(AltConst (Just a)) <> (AltConst (Just b)) = AltConst (Just (a <> b))
instance (Monoid a) => Monoid (AltConst a x) where
mempty = (AltConst (Just mempty))
instance Monoid m => Alternative (AltConst m) where
empty = (AltConst Nothing)
(AltConst Nothing) <|> a = a
a <|> (AltConst Nothing) = a
(AltConst (Just a)) <|> (AltConst (Just b)) = (AltConst (Just (a <> b)))
| null | https://raw.githubusercontent.com/ChrisPenner/proton/4ce22d473ce5bece8322c841bd2cf7f18673d57d/src/Data/Profunctor/Withering.hs | haskell | module Data.Profunctor.Withering where
import Data.Profunctor
import Data.Profunctor.Traversing
import Control.Applicative
class (Traversing p) => Withering p where
cull :: (forall f. Alternative f => (a -> f b) -> (s -> f t)) -> p a b -> p s t
instance Alternative f => Withering (Star f) where
cull f (Star amb) = Star (f amb)
instance Monoid m => Withering (Forget m) where
cull f (Forget h) = Forget (getAnnihilation . f (AltConst . Just . h))
where
getAnnihilation (AltConst Nothing) = mempty
getAnnihilation (AltConst (Just m)) = m
newtype AltConst a b = AltConst (Maybe a)
deriving stock (Eq, Ord, Show, Functor)
instance Monoid a => Applicative (AltConst a) where
pure _ = (AltConst (Just mempty))
(AltConst Nothing) <*> _ = (AltConst Nothing)
_ <*> (AltConst Nothing) = (AltConst Nothing)
(AltConst (Just a)) <*> (AltConst (Just b)) = AltConst (Just (a <> b))
instance (Semigroup a) => Semigroup (AltConst a x) where
(AltConst Nothing) <> _ = (AltConst Nothing)
_ <> (AltConst Nothing) = (AltConst Nothing)
(AltConst (Just a)) <> (AltConst (Just b)) = AltConst (Just (a <> b))
instance (Monoid a) => Monoid (AltConst a x) where
mempty = (AltConst (Just mempty))
instance Monoid m => Alternative (AltConst m) where
empty = (AltConst Nothing)
(AltConst Nothing) <|> a = a
a <|> (AltConst Nothing) = a
(AltConst (Just a)) <|> (AltConst (Just b)) = (AltConst (Just (a <> b)))
| |
c08de7f7b7113305903015e4438a0c806ba53e5bba9834b66c942c29ba0de95a | mejgun/haskell-tdlib | ChatPermissions.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Data.ChatPermissions where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
-- |
data ChatPermissions = -- | Describes actions that a user is allowed to take in a chat
ChatPermissions
{ -- | True, if the user can manage topics
can_manage_topics :: Maybe Bool,
-- | True, if the user can pin messages
can_pin_messages :: Maybe Bool,
-- | True, if the user can invite new users to the chat
can_invite_users :: Maybe Bool,
-- | True, if the user can change the chat title, photo, and other settings
can_change_info :: Maybe Bool,
-- | True, if the user may add a web page preview to their messages
can_add_web_page_previews :: Maybe Bool,
-- | True, if the user can send animations, games, stickers, and dice and use inline bots
can_send_other_messages :: Maybe Bool,
-- | True, if the user can send polls
can_send_polls :: Maybe Bool,
-- | True, if the user can send voice notes
can_send_voice_notes :: Maybe Bool,
-- | True, if the user can send video notes
can_send_video_notes :: Maybe Bool,
-- | True, if the user can send audio videos
can_send_videos :: Maybe Bool,
-- | True, if the user can send audio photos
can_send_photos :: Maybe Bool,
-- | True, if the user can send documents
can_send_documents :: Maybe Bool,
-- | True, if the user can send music files
can_send_audios :: Maybe Bool,
-- | True, if the user can send text messages, contacts, invoices, locations, and venues
can_send_messages :: Maybe Bool
}
deriving (Eq)
instance Show ChatPermissions where
show
ChatPermissions
{ can_manage_topics = can_manage_topics_,
can_pin_messages = can_pin_messages_,
can_invite_users = can_invite_users_,
can_change_info = can_change_info_,
can_add_web_page_previews = can_add_web_page_previews_,
can_send_other_messages = can_send_other_messages_,
can_send_polls = can_send_polls_,
can_send_voice_notes = can_send_voice_notes_,
can_send_video_notes = can_send_video_notes_,
can_send_videos = can_send_videos_,
can_send_photos = can_send_photos_,
can_send_documents = can_send_documents_,
can_send_audios = can_send_audios_,
can_send_messages = can_send_messages_
} =
"ChatPermissions"
++ U.cc
[ U.p "can_manage_topics" can_manage_topics_,
U.p "can_pin_messages" can_pin_messages_,
U.p "can_invite_users" can_invite_users_,
U.p "can_change_info" can_change_info_,
U.p "can_add_web_page_previews" can_add_web_page_previews_,
U.p "can_send_other_messages" can_send_other_messages_,
U.p "can_send_polls" can_send_polls_,
U.p "can_send_voice_notes" can_send_voice_notes_,
U.p "can_send_video_notes" can_send_video_notes_,
U.p "can_send_videos" can_send_videos_,
U.p "can_send_photos" can_send_photos_,
U.p "can_send_documents" can_send_documents_,
U.p "can_send_audios" can_send_audios_,
U.p "can_send_messages" can_send_messages_
]
instance T.FromJSON ChatPermissions where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"chatPermissions" -> parseChatPermissions v
_ -> mempty
where
parseChatPermissions :: A.Value -> T.Parser ChatPermissions
parseChatPermissions = A.withObject "ChatPermissions" $ \o -> do
can_manage_topics_ <- o A..:? "can_manage_topics"
can_pin_messages_ <- o A..:? "can_pin_messages"
can_invite_users_ <- o A..:? "can_invite_users"
can_change_info_ <- o A..:? "can_change_info"
can_add_web_page_previews_ <- o A..:? "can_add_web_page_previews"
can_send_other_messages_ <- o A..:? "can_send_other_messages"
can_send_polls_ <- o A..:? "can_send_polls"
can_send_voice_notes_ <- o A..:? "can_send_voice_notes"
can_send_video_notes_ <- o A..:? "can_send_video_notes"
can_send_videos_ <- o A..:? "can_send_videos"
can_send_photos_ <- o A..:? "can_send_photos"
can_send_documents_ <- o A..:? "can_send_documents"
can_send_audios_ <- o A..:? "can_send_audios"
can_send_messages_ <- o A..:? "can_send_messages"
return $ ChatPermissions {can_manage_topics = can_manage_topics_, can_pin_messages = can_pin_messages_, can_invite_users = can_invite_users_, can_change_info = can_change_info_, can_add_web_page_previews = can_add_web_page_previews_, can_send_other_messages = can_send_other_messages_, can_send_polls = can_send_polls_, can_send_voice_notes = can_send_voice_notes_, can_send_video_notes = can_send_video_notes_, can_send_videos = can_send_videos_, can_send_photos = can_send_photos_, can_send_documents = can_send_documents_, can_send_audios = can_send_audios_, can_send_messages = can_send_messages_}
parseJSON _ = mempty
instance T.ToJSON ChatPermissions where
toJSON
ChatPermissions
{ can_manage_topics = can_manage_topics_,
can_pin_messages = can_pin_messages_,
can_invite_users = can_invite_users_,
can_change_info = can_change_info_,
can_add_web_page_previews = can_add_web_page_previews_,
can_send_other_messages = can_send_other_messages_,
can_send_polls = can_send_polls_,
can_send_voice_notes = can_send_voice_notes_,
can_send_video_notes = can_send_video_notes_,
can_send_videos = can_send_videos_,
can_send_photos = can_send_photos_,
can_send_documents = can_send_documents_,
can_send_audios = can_send_audios_,
can_send_messages = can_send_messages_
} =
A.object
[ "@type" A..= T.String "chatPermissions",
"can_manage_topics" A..= can_manage_topics_,
"can_pin_messages" A..= can_pin_messages_,
"can_invite_users" A..= can_invite_users_,
"can_change_info" A..= can_change_info_,
"can_add_web_page_previews" A..= can_add_web_page_previews_,
"can_send_other_messages" A..= can_send_other_messages_,
"can_send_polls" A..= can_send_polls_,
"can_send_voice_notes" A..= can_send_voice_notes_,
"can_send_video_notes" A..= can_send_video_notes_,
"can_send_videos" A..= can_send_videos_,
"can_send_photos" A..= can_send_photos_,
"can_send_documents" A..= can_send_documents_,
"can_send_audios" A..= can_send_audios_,
"can_send_messages" A..= can_send_messages_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/b088f5062023fa201a68ebda128ab2fc489329ab/src/TD/Data/ChatPermissions.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
| Describes actions that a user is allowed to take in a chat
| True, if the user can manage topics
| True, if the user can pin messages
| True, if the user can invite new users to the chat
| True, if the user can change the chat title, photo, and other settings
| True, if the user may add a web page preview to their messages
| True, if the user can send animations, games, stickers, and dice and use inline bots
| True, if the user can send polls
| True, if the user can send voice notes
| True, if the user can send video notes
| True, if the user can send audio videos
| True, if the user can send audio photos
| True, if the user can send documents
| True, if the user can send music files
| True, if the user can send text messages, contacts, invoices, locations, and venues |
module TD.Data.ChatPermissions where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
ChatPermissions
can_manage_topics :: Maybe Bool,
can_pin_messages :: Maybe Bool,
can_invite_users :: Maybe Bool,
can_change_info :: Maybe Bool,
can_add_web_page_previews :: Maybe Bool,
can_send_other_messages :: Maybe Bool,
can_send_polls :: Maybe Bool,
can_send_voice_notes :: Maybe Bool,
can_send_video_notes :: Maybe Bool,
can_send_videos :: Maybe Bool,
can_send_photos :: Maybe Bool,
can_send_documents :: Maybe Bool,
can_send_audios :: Maybe Bool,
can_send_messages :: Maybe Bool
}
deriving (Eq)
instance Show ChatPermissions where
show
ChatPermissions
{ can_manage_topics = can_manage_topics_,
can_pin_messages = can_pin_messages_,
can_invite_users = can_invite_users_,
can_change_info = can_change_info_,
can_add_web_page_previews = can_add_web_page_previews_,
can_send_other_messages = can_send_other_messages_,
can_send_polls = can_send_polls_,
can_send_voice_notes = can_send_voice_notes_,
can_send_video_notes = can_send_video_notes_,
can_send_videos = can_send_videos_,
can_send_photos = can_send_photos_,
can_send_documents = can_send_documents_,
can_send_audios = can_send_audios_,
can_send_messages = can_send_messages_
} =
"ChatPermissions"
++ U.cc
[ U.p "can_manage_topics" can_manage_topics_,
U.p "can_pin_messages" can_pin_messages_,
U.p "can_invite_users" can_invite_users_,
U.p "can_change_info" can_change_info_,
U.p "can_add_web_page_previews" can_add_web_page_previews_,
U.p "can_send_other_messages" can_send_other_messages_,
U.p "can_send_polls" can_send_polls_,
U.p "can_send_voice_notes" can_send_voice_notes_,
U.p "can_send_video_notes" can_send_video_notes_,
U.p "can_send_videos" can_send_videos_,
U.p "can_send_photos" can_send_photos_,
U.p "can_send_documents" can_send_documents_,
U.p "can_send_audios" can_send_audios_,
U.p "can_send_messages" can_send_messages_
]
instance T.FromJSON ChatPermissions where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"chatPermissions" -> parseChatPermissions v
_ -> mempty
where
parseChatPermissions :: A.Value -> T.Parser ChatPermissions
parseChatPermissions = A.withObject "ChatPermissions" $ \o -> do
can_manage_topics_ <- o A..:? "can_manage_topics"
can_pin_messages_ <- o A..:? "can_pin_messages"
can_invite_users_ <- o A..:? "can_invite_users"
can_change_info_ <- o A..:? "can_change_info"
can_add_web_page_previews_ <- o A..:? "can_add_web_page_previews"
can_send_other_messages_ <- o A..:? "can_send_other_messages"
can_send_polls_ <- o A..:? "can_send_polls"
can_send_voice_notes_ <- o A..:? "can_send_voice_notes"
can_send_video_notes_ <- o A..:? "can_send_video_notes"
can_send_videos_ <- o A..:? "can_send_videos"
can_send_photos_ <- o A..:? "can_send_photos"
can_send_documents_ <- o A..:? "can_send_documents"
can_send_audios_ <- o A..:? "can_send_audios"
can_send_messages_ <- o A..:? "can_send_messages"
return $ ChatPermissions {can_manage_topics = can_manage_topics_, can_pin_messages = can_pin_messages_, can_invite_users = can_invite_users_, can_change_info = can_change_info_, can_add_web_page_previews = can_add_web_page_previews_, can_send_other_messages = can_send_other_messages_, can_send_polls = can_send_polls_, can_send_voice_notes = can_send_voice_notes_, can_send_video_notes = can_send_video_notes_, can_send_videos = can_send_videos_, can_send_photos = can_send_photos_, can_send_documents = can_send_documents_, can_send_audios = can_send_audios_, can_send_messages = can_send_messages_}
parseJSON _ = mempty
instance T.ToJSON ChatPermissions where
toJSON
ChatPermissions
{ can_manage_topics = can_manage_topics_,
can_pin_messages = can_pin_messages_,
can_invite_users = can_invite_users_,
can_change_info = can_change_info_,
can_add_web_page_previews = can_add_web_page_previews_,
can_send_other_messages = can_send_other_messages_,
can_send_polls = can_send_polls_,
can_send_voice_notes = can_send_voice_notes_,
can_send_video_notes = can_send_video_notes_,
can_send_videos = can_send_videos_,
can_send_photos = can_send_photos_,
can_send_documents = can_send_documents_,
can_send_audios = can_send_audios_,
can_send_messages = can_send_messages_
} =
A.object
[ "@type" A..= T.String "chatPermissions",
"can_manage_topics" A..= can_manage_topics_,
"can_pin_messages" A..= can_pin_messages_,
"can_invite_users" A..= can_invite_users_,
"can_change_info" A..= can_change_info_,
"can_add_web_page_previews" A..= can_add_web_page_previews_,
"can_send_other_messages" A..= can_send_other_messages_,
"can_send_polls" A..= can_send_polls_,
"can_send_voice_notes" A..= can_send_voice_notes_,
"can_send_video_notes" A..= can_send_video_notes_,
"can_send_videos" A..= can_send_videos_,
"can_send_photos" A..= can_send_photos_,
"can_send_documents" A..= can_send_documents_,
"can_send_audios" A..= can_send_audios_,
"can_send_messages" A..= can_send_messages_
]
|
90e2b82e80e313b63317275919fbaa2a5d8ee36d6579d54624dc2d403879a16e | qkrgud55/ocamlmulti | printf.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
and , projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : printf.ml 12014 2012 - 01 - 11 15:22:51Z doligez $
external format_float: string -> float -> string
= "caml_format_float_r" "reentrant"
external format_int: string -> int -> string
= "caml_format_int_r" "reentrant"
external format_int32: string -> int32 -> string
= "caml_int32_format_r" "reentrant"
external format_nativeint: string -> nativeint -> string
= "caml_nativeint_format_r" "reentrant"
external format_int64: string -> int64 -> string
= "caml_int64_format_r" "reentrant"
module Sformat = struct
type index;;
external unsafe_index_of_int : int -> index = "%identity"
;;
let index_of_int i =
if i >= 0 then unsafe_index_of_int i
else failwith ("Sformat.index_of_int: negative argument " ^ string_of_int i)
;;
external int_of_index : index -> int = "%identity"
;;
let add_int_index i idx = index_of_int (i + int_of_index idx);;
let succ_index = add_int_index 1;;
Literal position are one - based ( hence pred p instead of p ) .
let index_of_literal_position p = index_of_int (pred p);;
external length : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int
= "%string_length"
;;
external get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_safe_get"
;;
external unsafe_get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_unsafe_get"
;;
external unsafe_to_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
= "%identity"
;;
let sub fmt idx len =
String.sub (unsafe_to_string fmt) (int_of_index idx) len
;;
let to_string fmt = sub fmt (unsafe_index_of_int 0) (length fmt)
;;
end
;;
let bad_conversion sfmt i c =
invalid_arg
("Printf: bad conversion %" ^ String.make 1 c ^ ", at char number " ^
string_of_int i ^ " in format string ``" ^ sfmt ^ "''")
;;
let bad_conversion_format fmt i c =
bad_conversion (Sformat.to_string fmt) i c
;;
let incomplete_format fmt =
invalid_arg
("Printf: premature end of format string ``" ^
Sformat.to_string fmt ^ "''")
;;
(* Parses a string conversion to return the specified length and the padding direction. *)
let parse_string_conversion sfmt =
let rec parse neg i =
if i >= String.length sfmt then (0, neg) else
match String.unsafe_get sfmt i with
| '1'..'9' ->
(int_of_string
(String.sub sfmt i (String.length sfmt - i - 1)),
neg)
| '-' ->
parse true (succ i)
| _ ->
parse neg (succ i) in
try parse false 1 with
| Failure _ -> bad_conversion sfmt 0 's'
;;
(* Pad a (sub) string into a blank string of length [p],
on the right if [neg] is true, on the left otherwise. *)
let pad_string pad_char p neg s i len =
if p = len && i = 0 then s else
if p <= len then String.sub s i len else
let res = String.make p pad_char in
if neg
then String.blit s i res 0 len
else String.blit s i res (p - len) len;
res
;;
Format a string given a % s format , e.g. % 40s or % -20s .
To do ? : ignore other flags ( # , + , etc ) .
To do ?: ignore other flags (#, +, etc). *)
let format_string sfmt s =
let (p, neg) = parse_string_conversion sfmt in
pad_string ' ' p neg s 0 (String.length s)
;;
(* Extract a format string out of [fmt] between [start] and [stop] inclusive.
['*'] in the format are replaced by integers taken from the [widths] list.
[extract_format] returns a string which is the string representation of
the resulting format string. *)
let extract_format fmt start stop widths =
let skip_positional_spec start =
match Sformat.unsafe_get fmt start with
| '0'..'9' ->
let rec skip_int_literal i =
match Sformat.unsafe_get fmt i with
| '0'..'9' -> skip_int_literal (succ i)
| '$' -> succ i
| _ -> start in
skip_int_literal (succ start)
| _ -> start in
let start = skip_positional_spec (succ start) in
let b = Buffer.create (stop - start + 10) in
Buffer.add_char b '%';
let rec fill_format i widths =
if i <= stop then
match (Sformat.unsafe_get fmt i, widths) with
| ('*', h :: t) ->
Buffer.add_string b (string_of_int h);
let i = skip_positional_spec (succ i) in
fill_format i t
| ('*', []) ->
assert false (* Should not happen since this is ill-typed. *)
| (c, _) ->
Buffer.add_char b c;
fill_format (succ i) widths in
fill_format start (List.rev widths);
Buffer.contents b
;;
let extract_format_int conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'n' | 'N' ->
sfmt.[String.length sfmt - 1] <- 'u';
sfmt
| _ -> sfmt
;;
let extract_format_float conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'F' ->
sfmt.[String.length sfmt - 1] <- 'g';
sfmt
| _ -> sfmt
;;
(* Returns the position of the next character following the meta format
string, starting from position [i], inside a given format [fmt].
According to the character [conv], the meta format string is
enclosed by the delimiters %{ and %} (when [conv = '{']) or %( and
%) (when [conv = '(']). Hence, [sub_format] returns the index of
the character following the [')'] or ['}'] that ends the meta format,
according to the character [conv]. *)
let sub_format incomplete_format bad_conversion_format conv fmt i =
let len = Sformat.length fmt in
let rec sub_fmt c i =
let close = if c = '(' then ')' else (* '{' *) '}' in
let rec sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '%' -> sub_sub (succ j)
| _ -> sub (succ j)
and sub_sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '(' | '{' as c ->
let j = sub_fmt c (succ j) in
sub (succ j)
| '}' | ')' as c ->
if c = close then succ j else bad_conversion_format fmt i c
| _ -> sub (succ j) in
sub i in
sub_fmt conv i
;;
let sub_format_for_printf conv =
sub_format incomplete_format bad_conversion_format conv
;;
let iter_on_format_args fmt add_conv add_char =
let lim = Sformat.length fmt - 1 in
let rec scan_flags skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '*' -> scan_flags skip (add_conv skip i 'i')
(* | '$' -> scan_flags skip (succ i) *** PR#4321 *)
| '#' | '-' | ' ' | '+' -> scan_flags skip (succ i)
| '_' -> scan_flags true (succ i)
| '0'..'9'
| '.' -> scan_flags skip (succ i)
| _ -> scan_conv skip i
and scan_conv skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '%' | '@' | '!' | ',' -> succ i
| 's' | 'S' | '[' -> add_conv skip i 's'
| 'c' | 'C' -> add_conv skip i 'c'
| 'd' | 'i' |'o' | 'u' | 'x' | 'X' | 'N' -> add_conv skip i 'i'
| 'f' | 'e' | 'E' | 'g' | 'G' | 'F' -> add_conv skip i 'f'
| 'B' | 'b' -> add_conv skip i 'B'
| 'a' | 'r' | 't' as conv -> add_conv skip i conv
| 'l' | 'n' | 'L' as conv ->
let j = succ i in
if j > lim then add_conv skip i 'i' else begin
match Sformat.get fmt j with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
add_char (add_conv skip i conv) 'i'
| _ -> add_conv skip i 'i' end
| '{' as conv ->
(* Just get a regular argument, skipping the specification. *)
let i = add_conv skip i conv in
(* To go on, find the index of the next char after the meta format. *)
let j = sub_format_for_printf conv fmt i in
(* Add the meta specification to the summary anyway. *)
let rec loop i =
if i < j - 2 then loop (add_char i (Sformat.get fmt i)) in
loop i;
(* Go on, starting at the closing brace to properly close the meta
specification in the summary. *)
scan_conv skip (j - 1)
| '(' as conv ->
(* Use the static format argument specification instead of
the runtime format argument value: they must have the same type
anyway. *)
scan_fmt (add_conv skip i conv)
| '}' | ')' as conv -> add_conv skip i conv
| conv -> bad_conversion_format fmt i conv
and scan_fmt i =
if i < lim then
if Sformat.get fmt i = '%'
then scan_fmt (scan_flags false (succ i))
else scan_fmt (succ i)
else i in
ignore (scan_fmt 0)
;;
(* Returns a string that summarizes the typing information that a given
format string contains.
For instance, [summarize_format_type "A number %d\n"] is "%i".
It also checks the well-formedness of the format string. *)
let summarize_format_type fmt =
let len = Sformat.length fmt in
let b = Buffer.create len in
let add_char i c = Buffer.add_char b c; succ i in
let add_conv skip i c =
if skip then Buffer.add_string b "%_" else Buffer.add_char b '%';
add_char i c in
iter_on_format_args fmt add_conv add_char;
Buffer.contents b
;;
module Ac = struct
type ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
end
;;
open Ac;;
(* Computes the number of arguments of a format (including the flag
arguments if any). *)
let ac_of_format fmt =
let ac = { ac_rglr = 0; ac_skip = 0; ac_rdrs = 0; } in
let incr_ac skip c =
let inc = if c = 'a' then 2 else 1 in
if c = 'r' then ac.ac_rdrs <- ac.ac_rdrs + 1;
if skip
then ac.ac_skip <- ac.ac_skip + inc
else ac.ac_rglr <- ac.ac_rglr + inc in
let add_conv skip i c =
(* Just finishing a meta format: no additional argument to record. *)
if c <> ')' && c <> '}' then incr_ac skip c;
succ i
and add_char i _ = succ i in
iter_on_format_args fmt add_conv add_char;
ac
;;
let count_arguments_of_format fmt =
let ac = ac_of_format fmt in
(* For printing, only the regular arguments have to be counted. *)
ac.ac_rglr
;;
let list_iter_i f l =
let rec loop i = function
| [] -> ()
| [x] -> f i x (* Tail calling [f] *)
| x :: xs -> f i x; loop (succ i) xs in
loop 0 l
;;
` ` Abstracting '' version of : returns a ( curried ) function that
will print when totally applied .
Note : in the following , we are careful not to be badly caught
by the compiler optimizations for the representation of arrays .
will print when totally applied.
Note: in the following, we are careful not to be badly caught
by the compiler optimizations for the representation of arrays. *)
let kapr kpr fmt =
match count_arguments_of_format fmt with
| 0 -> kpr fmt [||]
| 1 -> Obj.magic (fun x ->
let a = Array.make 1 (Obj.repr 0) in
a.(0) <- x;
kpr fmt a)
| 2 -> Obj.magic (fun x y ->
let a = Array.make 2 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y;
kpr fmt a)
| 3 -> Obj.magic (fun x y z ->
let a = Array.make 3 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
kpr fmt a)
| 4 -> Obj.magic (fun x y z t ->
let a = Array.make 4 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t;
kpr fmt a)
| 5 -> Obj.magic (fun x y z t u ->
let a = Array.make 5 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u;
kpr fmt a)
| 6 -> Obj.magic (fun x y z t u v ->
let a = Array.make 6 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u; a.(5) <- v;
kpr fmt a)
| nargs ->
let rec loop i args =
if i >= nargs then
let a = Array.make nargs (Obj.repr 0) in
list_iter_i (fun i arg -> a.(nargs - i - 1) <- arg) args;
kpr fmt a
else Obj.magic (fun x -> loop (succ i) (x :: args)) in
loop 0 []
;;
type positional_specification =
| Spec_none | Spec_index of Sformat.index
;;
(* To scan an optional positional parameter specification,
i.e. an integer followed by a [$].
Calling [got_spec] with appropriate arguments, we ``return'' a positional
specification and an index to go on scanning the [fmt] format at hand.
Note that this is optimized for the regular case, i.e. no positional
parameter, since in this case we juste ``return'' the constant
[Spec_none]; in case we have a positional parameter, we ``return'' a
[Spec_index] [positional_specification] which is a bit more costly.
Note also that we do not support [*$] specifications, since this would
lead to type checking problems: a [*$] positional specification means
``take the next argument to [printf] (which must be an integer value)'',
name this integer value $n$; [*$] now designates parameter $n$.
Unfortunately, the type of a parameter specified via a [*$] positional
specification should be the type of the corresponding argument to
[printf], hence this should be the type of the $n$-th argument to [printf]
with $n$ being the {\em value} of the integer argument defining [*]; we
clearly cannot statically guess the value of this parameter in the general
case. Put it another way: this means type dependency, which is completely
out of scope of the OCaml type algebra. *)
let scan_positional_spec fmt got_spec i =
match Sformat.unsafe_get fmt i with
| '0'..'9' as d ->
let rec get_int_literal accu j =
match Sformat.unsafe_get fmt j with
| '0'..'9' as d ->
get_int_literal (10 * accu + (int_of_char d - 48)) (succ j)
| '$' ->
if accu = 0 then
failwith "printf: bad positional specification (0)." else
got_spec (Spec_index (Sformat.index_of_literal_position accu)) (succ j)
Not a positional specification : tell so the caller , and go back to
scanning the format from the original [ i ] position we were called at
first .
scanning the format from the original [i] position we were called at
first. *)
| _ -> got_spec Spec_none i in
get_int_literal (int_of_char d - 48) (succ i)
(* No positional specification: tell so the caller, and go back to scanning
the format from the original [i] position. *)
| _ -> got_spec Spec_none i
;;
(* Get the index of the next argument to printf, according to the given
positional specification. *)
let next_index spec n =
match spec with
| Spec_none -> Sformat.succ_index n
| Spec_index _ -> n
;;
(* Get the index of the actual argument to printf, according to its
optional positional specification. *)
let get_index spec n =
match spec with
| Spec_none -> n
| Spec_index p -> p
;;
Format a float argument as a valid OCaml lexeme .
let format_float_lexeme =
To be revised : this procedure should be a unique loop that performs the
validity check and the string lexeme modification at the same time .
Otherwise , it is too difficult to handle the strange padding facilities
given by printf . Let alone handling the correct widths indication ,
knowing that we have sometime to add a ' . ' at the end of the result !
validity check and the string lexeme modification at the same time.
Otherwise, it is too difficult to handle the strange padding facilities
given by printf. Let alone handling the correct widths indication,
knowing that we have sometime to add a '.' at the end of the result!
*)
let make_valid_float_lexeme s =
Check if s is already a valid lexeme :
in this case do nothing ,
otherwise turn s into a valid OCaml lexeme .
in this case do nothing,
otherwise turn s into a valid OCaml lexeme. *)
let l = String.length s in
let rec valid_float_loop i =
if i >= l then s ^ "." else
match s.[i] with
Sure , this is already a valid float lexeme .
| '.' | 'e' | 'E' -> s
| _ -> valid_float_loop (i + 1) in
valid_float_loop 0 in
(fun sfmt x ->
let s = format_float sfmt x in
match classify_float x with
| FP_normal | FP_subnormal | FP_zero -> make_valid_float_lexeme s
| FP_nan | FP_infinite -> s)
;;
Decode a format string and act on it .
[ fmt ] is the [ printf ] format string , and [ pos ] points to a [ % ] character in
the format string .
After consuming the appropriate number of arguments and formatting
them , one of the following five continuations described below is called :
- [ cont_s ] for outputting a string ( arguments : arg num , string , next pos )
- [ cont_a ] for performing a % a action ( arguments : arg num , fn , arg , next pos )
- [ cont_t ] for performing a % t action ( arguments : arg num , fn , next pos )
- [ cont_f ] for performing a flush action ( arguments : arg num , next pos )
- [ cont_m ] for performing a % ( action ( arguments : arg num , sfmt , next pos )
" arg num " is the index in array [ args ] of the next argument to [ printf ] .
" next pos " is the position in [ fmt ] of the first character following
the % conversion specification in [ fmt ] .
[fmt] is the [printf] format string, and [pos] points to a [%] character in
the format string.
After consuming the appropriate number of arguments and formatting
them, one of the following five continuations described below is called:
- [cont_s] for outputting a string (arguments: arg num, string, next pos)
- [cont_a] for performing a %a action (arguments: arg num, fn, arg, next pos)
- [cont_t] for performing a %t action (arguments: arg num, fn, next pos)
- [cont_f] for performing a flush action (arguments: arg num, next pos)
- [cont_m] for performing a %( action (arguments: arg num, sfmt, next pos)
"arg num" is the index in array [args] of the next argument to [printf].
"next pos" is the position in [fmt] of the first character following
the %conversion specification in [fmt]. *)
(* Note: here, rather than test explicitly against [Sformat.length fmt]
to detect the end of the format, we use [Sformat.unsafe_get] and
rely on the fact that we'll get a "null" character if we access
one past the end of the string. These "null" characters are then
caught by the [_ -> bad_conversion] clauses below.
Don't do this at home, kids. *)
let scan_format fmt args n pos cont_s cont_a cont_t cont_f cont_m =
let get_arg spec n =
Obj.magic (args.(Sformat.int_of_index (get_index spec n))) in
let rec scan_positional n widths i =
let got_spec spec i = scan_flags spec n widths i in
scan_positional_spec fmt got_spec i
and scan_flags spec n widths i =
match Sformat.unsafe_get fmt i with
| '*' ->
let got_spec wspec i =
let (width : int) = get_arg wspec n in
scan_flags spec (next_index wspec n) (width :: widths) i in
scan_positional_spec fmt got_spec (succ i)
| '0'..'9'
| '.' | '#' | '-' | ' ' | '+' -> scan_flags spec n widths (succ i)
| _ -> scan_conv spec n widths i
and scan_conv spec n widths i =
match Sformat.unsafe_get fmt i with
| '%' | '@' as c ->
cont_s n (String.make 1 c) (succ i)
| '!' -> cont_f n (succ i)
| ',' -> cont_s n "" (succ i)
| 's' | 'S' as conv ->
let (x : string) = get_arg spec n in
let x = if conv = 's' then x else "\"" ^ String.escaped x ^ "\"" in
let s =
(* Optimize for common case %s *)
if i = succ pos then x else
format_string (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| '[' as conv ->
bad_conversion_format fmt i conv
| 'c' | 'C' as conv ->
let (x : char) = get_arg spec n in
let s =
if conv = 'c' then String.make 1 x else "'" ^ Char.escaped x ^ "'" in
cont_s (next_index spec n) s (succ i)
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' | 'N' as conv ->
let (x : int) = get_arg spec n in
let s =
format_int (extract_format_int conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'f' | 'e' | 'E' | 'g' | 'G' ->
let (x : float) = get_arg spec n in
let s = format_float (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'F' as conv ->
let (x : float) = get_arg spec n in
let s =
if widths = [] then Pervasives.string_of_float x else
format_float_lexeme (extract_format_float conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'B' | 'b' ->
let (x : bool) = get_arg spec n in
cont_s (next_index spec n) (string_of_bool x) (succ i)
| 'a' ->
let printer = get_arg spec n in
If the printer spec is Spec_none , go on as usual .
If the printer spec is Spec_index p ,
printer 's argument spec is Spec_index ( succ_index p ) .
If the printer spec is Spec_index p,
printer's argument spec is Spec_index (succ_index p). *)
let n = Sformat.succ_index (get_index spec n) in
let arg = get_arg Spec_none n in
cont_a (next_index spec n) printer arg (succ i)
| 'r' as conv ->
bad_conversion_format fmt i conv
| 't' ->
let printer = get_arg spec n in
cont_t (next_index spec n) printer (succ i)
| 'l' | 'n' | 'L' as conv ->
begin match Sformat.unsafe_get fmt (succ i) with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
let i = succ i in
let s =
match conv with
| 'l' ->
let (x : int32) = get_arg spec n in
format_int32 (extract_format fmt pos i widths) x
| 'n' ->
let (x : nativeint) = get_arg spec n in
format_nativeint (extract_format fmt pos i widths) x
| _ ->
let (x : int64) = get_arg spec n in
format_int64 (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| _ ->
let (x : int) = get_arg spec n in
let s = format_int (extract_format_int 'n' fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
end
| '{' | '(' as conv (* ')' '}' *) ->
let (xf : ('a, 'b, 'c, 'd, 'e, 'f) format6) = get_arg spec n in
let i = succ i in
let j = sub_format_for_printf conv fmt i in
if conv = '{' (* '}' *) then
(* Just print the format argument as a specification. *)
cont_s
(next_index spec n)
(summarize_format_type xf)
j else
(* Use the format argument instead of the format specification. *)
cont_m (next_index spec n) xf j
| (* '(' *) ')' ->
cont_s n "" (succ i)
| conv ->
bad_conversion_format fmt i conv in
scan_positional n [] (succ pos)
;;
let mkprintf to_s get_out outc outs flush k fmt =
(* [out] is global to this definition of [pr], and must be shared by all its
recursive calls (if any). *)
let out = get_out fmt in
let rec pr k n fmt v =
let len = Sformat.length fmt in
let rec doprn n i =
if i >= len then Obj.magic (k out) else
match Sformat.unsafe_get fmt i with
| '%' -> scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m
| c -> outc out c; doprn n (succ i)
and cont_s n s i =
outs out s; doprn n i
and cont_a n printer arg i =
if to_s then
outs out ((Obj.magic printer : unit -> _ -> string) () arg)
else
printer out arg;
doprn n i
and cont_t n printer i =
if to_s then
outs out ((Obj.magic printer : unit -> string) ())
else
printer out;
doprn n i
and cont_f n i =
flush out; doprn n i
and cont_m n xf i =
let m = Sformat.add_int_index (count_arguments_of_format xf) n in
pr (Obj.magic (fun _ -> doprn m i)) n xf v in
doprn n 0 in
let kpr = pr k (Sformat.index_of_int 0) in
kapr kpr fmt
;;
let kfprintf k oc =
mkprintf false (fun _ -> oc) output_char output_string flush k
;;
let ifprintf _ = kapr (fun _ -> Obj.magic ignore);;
let fprintf oc = kfprintf ignore oc;;
let printf fmt = fprintf stdout fmt;;
let eprintf fmt = fprintf stderr fmt;;
let kbprintf k b =
mkprintf false (fun _ -> b) Buffer.add_char Buffer.add_string ignore k
;;
let bprintf b = kbprintf ignore b;;
let get_buff fmt =
let len = 2 * Sformat.length fmt in
Buffer.create len
;;
let get_contents b =
let s = Buffer.contents b in
Buffer.clear b;
s
;;
let get_cont k b = k (get_contents b);;
let ksprintf k =
mkprintf true get_buff Buffer.add_char Buffer.add_string ignore (get_cont k)
;;
let sprintf fmt = ksprintf (fun s -> s) fmt;;
(* Obsolete and deprecated. *)
let kprintf = ksprintf;;
(* For OCaml system internal use only: needed to implement modules [Format]
and [Scanf]. *)
module CamlinternalPr = struct
module Sformat = Sformat;;
module Tformat = struct
type ac =
Ac.ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
;;
let ac_of_format = ac_of_format;;
let sub_format = sub_format;;
let summarize_format_type = summarize_format_type;;
let scan_format = scan_format;;
let kapr = kapr;;
end
;;
end
;;
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/stdlib_r/printf.ml | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../LICENSE.
*********************************************************************
Parses a string conversion to return the specified length and the padding direction.
Pad a (sub) string into a blank string of length [p],
on the right if [neg] is true, on the left otherwise.
Extract a format string out of [fmt] between [start] and [stop] inclusive.
['*'] in the format are replaced by integers taken from the [widths] list.
[extract_format] returns a string which is the string representation of
the resulting format string.
Should not happen since this is ill-typed.
Returns the position of the next character following the meta format
string, starting from position [i], inside a given format [fmt].
According to the character [conv], the meta format string is
enclosed by the delimiters %{ and %} (when [conv = '{']) or %( and
%) (when [conv = '(']). Hence, [sub_format] returns the index of
the character following the [')'] or ['}'] that ends the meta format,
according to the character [conv].
'{'
| '$' -> scan_flags skip (succ i) *** PR#4321
Just get a regular argument, skipping the specification.
To go on, find the index of the next char after the meta format.
Add the meta specification to the summary anyway.
Go on, starting at the closing brace to properly close the meta
specification in the summary.
Use the static format argument specification instead of
the runtime format argument value: they must have the same type
anyway.
Returns a string that summarizes the typing information that a given
format string contains.
For instance, [summarize_format_type "A number %d\n"] is "%i".
It also checks the well-formedness of the format string.
Computes the number of arguments of a format (including the flag
arguments if any).
Just finishing a meta format: no additional argument to record.
For printing, only the regular arguments have to be counted.
Tail calling [f]
To scan an optional positional parameter specification,
i.e. an integer followed by a [$].
Calling [got_spec] with appropriate arguments, we ``return'' a positional
specification and an index to go on scanning the [fmt] format at hand.
Note that this is optimized for the regular case, i.e. no positional
parameter, since in this case we juste ``return'' the constant
[Spec_none]; in case we have a positional parameter, we ``return'' a
[Spec_index] [positional_specification] which is a bit more costly.
Note also that we do not support [*$] specifications, since this would
lead to type checking problems: a [*$] positional specification means
``take the next argument to [printf] (which must be an integer value)'',
name this integer value $n$; [*$] now designates parameter $n$.
Unfortunately, the type of a parameter specified via a [*$] positional
specification should be the type of the corresponding argument to
[printf], hence this should be the type of the $n$-th argument to [printf]
with $n$ being the {\em value} of the integer argument defining [*]; we
clearly cannot statically guess the value of this parameter in the general
case. Put it another way: this means type dependency, which is completely
out of scope of the OCaml type algebra.
No positional specification: tell so the caller, and go back to scanning
the format from the original [i] position.
Get the index of the next argument to printf, according to the given
positional specification.
Get the index of the actual argument to printf, according to its
optional positional specification.
Note: here, rather than test explicitly against [Sformat.length fmt]
to detect the end of the format, we use [Sformat.unsafe_get] and
rely on the fact that we'll get a "null" character if we access
one past the end of the string. These "null" characters are then
caught by the [_ -> bad_conversion] clauses below.
Don't do this at home, kids.
Optimize for common case %s
')' '}'
'}'
Just print the format argument as a specification.
Use the format argument instead of the format specification.
'('
[out] is global to this definition of [pr], and must be shared by all its
recursive calls (if any).
Obsolete and deprecated.
For OCaml system internal use only: needed to implement modules [Format]
and [Scanf]. | and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : printf.ml 12014 2012 - 01 - 11 15:22:51Z doligez $
external format_float: string -> float -> string
= "caml_format_float_r" "reentrant"
external format_int: string -> int -> string
= "caml_format_int_r" "reentrant"
external format_int32: string -> int32 -> string
= "caml_int32_format_r" "reentrant"
external format_nativeint: string -> nativeint -> string
= "caml_nativeint_format_r" "reentrant"
external format_int64: string -> int64 -> string
= "caml_int64_format_r" "reentrant"
module Sformat = struct
type index;;
external unsafe_index_of_int : int -> index = "%identity"
;;
let index_of_int i =
if i >= 0 then unsafe_index_of_int i
else failwith ("Sformat.index_of_int: negative argument " ^ string_of_int i)
;;
external int_of_index : index -> int = "%identity"
;;
let add_int_index i idx = index_of_int (i + int_of_index idx);;
let succ_index = add_int_index 1;;
Literal position are one - based ( hence pred p instead of p ) .
let index_of_literal_position p = index_of_int (pred p);;
external length : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int
= "%string_length"
;;
external get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_safe_get"
;;
external unsafe_get : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> int -> char
= "%string_unsafe_get"
;;
external unsafe_to_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string
= "%identity"
;;
let sub fmt idx len =
String.sub (unsafe_to_string fmt) (int_of_index idx) len
;;
let to_string fmt = sub fmt (unsafe_index_of_int 0) (length fmt)
;;
end
;;
let bad_conversion sfmt i c =
invalid_arg
("Printf: bad conversion %" ^ String.make 1 c ^ ", at char number " ^
string_of_int i ^ " in format string ``" ^ sfmt ^ "''")
;;
let bad_conversion_format fmt i c =
bad_conversion (Sformat.to_string fmt) i c
;;
let incomplete_format fmt =
invalid_arg
("Printf: premature end of format string ``" ^
Sformat.to_string fmt ^ "''")
;;
let parse_string_conversion sfmt =
let rec parse neg i =
if i >= String.length sfmt then (0, neg) else
match String.unsafe_get sfmt i with
| '1'..'9' ->
(int_of_string
(String.sub sfmt i (String.length sfmt - i - 1)),
neg)
| '-' ->
parse true (succ i)
| _ ->
parse neg (succ i) in
try parse false 1 with
| Failure _ -> bad_conversion sfmt 0 's'
;;
let pad_string pad_char p neg s i len =
if p = len && i = 0 then s else
if p <= len then String.sub s i len else
let res = String.make p pad_char in
if neg
then String.blit s i res 0 len
else String.blit s i res (p - len) len;
res
;;
Format a string given a % s format , e.g. % 40s or % -20s .
To do ? : ignore other flags ( # , + , etc ) .
To do ?: ignore other flags (#, +, etc). *)
let format_string sfmt s =
let (p, neg) = parse_string_conversion sfmt in
pad_string ' ' p neg s 0 (String.length s)
;;
let extract_format fmt start stop widths =
let skip_positional_spec start =
match Sformat.unsafe_get fmt start with
| '0'..'9' ->
let rec skip_int_literal i =
match Sformat.unsafe_get fmt i with
| '0'..'9' -> skip_int_literal (succ i)
| '$' -> succ i
| _ -> start in
skip_int_literal (succ start)
| _ -> start in
let start = skip_positional_spec (succ start) in
let b = Buffer.create (stop - start + 10) in
Buffer.add_char b '%';
let rec fill_format i widths =
if i <= stop then
match (Sformat.unsafe_get fmt i, widths) with
| ('*', h :: t) ->
Buffer.add_string b (string_of_int h);
let i = skip_positional_spec (succ i) in
fill_format i t
| ('*', []) ->
| (c, _) ->
Buffer.add_char b c;
fill_format (succ i) widths in
fill_format start (List.rev widths);
Buffer.contents b
;;
let extract_format_int conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'n' | 'N' ->
sfmt.[String.length sfmt - 1] <- 'u';
sfmt
| _ -> sfmt
;;
let extract_format_float conv fmt start stop widths =
let sfmt = extract_format fmt start stop widths in
match conv with
| 'F' ->
sfmt.[String.length sfmt - 1] <- 'g';
sfmt
| _ -> sfmt
;;
let sub_format incomplete_format bad_conversion_format conv fmt i =
let len = Sformat.length fmt in
let rec sub_fmt c i =
let rec sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '%' -> sub_sub (succ j)
| _ -> sub (succ j)
and sub_sub j =
if j >= len then incomplete_format fmt else
match Sformat.get fmt j with
| '(' | '{' as c ->
let j = sub_fmt c (succ j) in
sub (succ j)
| '}' | ')' as c ->
if c = close then succ j else bad_conversion_format fmt i c
| _ -> sub (succ j) in
sub i in
sub_fmt conv i
;;
let sub_format_for_printf conv =
sub_format incomplete_format bad_conversion_format conv
;;
let iter_on_format_args fmt add_conv add_char =
let lim = Sformat.length fmt - 1 in
let rec scan_flags skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '*' -> scan_flags skip (add_conv skip i 'i')
| '#' | '-' | ' ' | '+' -> scan_flags skip (succ i)
| '_' -> scan_flags true (succ i)
| '0'..'9'
| '.' -> scan_flags skip (succ i)
| _ -> scan_conv skip i
and scan_conv skip i =
if i > lim then incomplete_format fmt else
match Sformat.unsafe_get fmt i with
| '%' | '@' | '!' | ',' -> succ i
| 's' | 'S' | '[' -> add_conv skip i 's'
| 'c' | 'C' -> add_conv skip i 'c'
| 'd' | 'i' |'o' | 'u' | 'x' | 'X' | 'N' -> add_conv skip i 'i'
| 'f' | 'e' | 'E' | 'g' | 'G' | 'F' -> add_conv skip i 'f'
| 'B' | 'b' -> add_conv skip i 'B'
| 'a' | 'r' | 't' as conv -> add_conv skip i conv
| 'l' | 'n' | 'L' as conv ->
let j = succ i in
if j > lim then add_conv skip i 'i' else begin
match Sformat.get fmt j with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
add_char (add_conv skip i conv) 'i'
| _ -> add_conv skip i 'i' end
| '{' as conv ->
let i = add_conv skip i conv in
let j = sub_format_for_printf conv fmt i in
let rec loop i =
if i < j - 2 then loop (add_char i (Sformat.get fmt i)) in
loop i;
scan_conv skip (j - 1)
| '(' as conv ->
scan_fmt (add_conv skip i conv)
| '}' | ')' as conv -> add_conv skip i conv
| conv -> bad_conversion_format fmt i conv
and scan_fmt i =
if i < lim then
if Sformat.get fmt i = '%'
then scan_fmt (scan_flags false (succ i))
else scan_fmt (succ i)
else i in
ignore (scan_fmt 0)
;;
let summarize_format_type fmt =
let len = Sformat.length fmt in
let b = Buffer.create len in
let add_char i c = Buffer.add_char b c; succ i in
let add_conv skip i c =
if skip then Buffer.add_string b "%_" else Buffer.add_char b '%';
add_char i c in
iter_on_format_args fmt add_conv add_char;
Buffer.contents b
;;
module Ac = struct
type ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
end
;;
open Ac;;
let ac_of_format fmt =
let ac = { ac_rglr = 0; ac_skip = 0; ac_rdrs = 0; } in
let incr_ac skip c =
let inc = if c = 'a' then 2 else 1 in
if c = 'r' then ac.ac_rdrs <- ac.ac_rdrs + 1;
if skip
then ac.ac_skip <- ac.ac_skip + inc
else ac.ac_rglr <- ac.ac_rglr + inc in
let add_conv skip i c =
if c <> ')' && c <> '}' then incr_ac skip c;
succ i
and add_char i _ = succ i in
iter_on_format_args fmt add_conv add_char;
ac
;;
let count_arguments_of_format fmt =
let ac = ac_of_format fmt in
ac.ac_rglr
;;
let list_iter_i f l =
let rec loop i = function
| [] -> ()
| x :: xs -> f i x; loop (succ i) xs in
loop 0 l
;;
` ` Abstracting '' version of : returns a ( curried ) function that
will print when totally applied .
Note : in the following , we are careful not to be badly caught
by the compiler optimizations for the representation of arrays .
will print when totally applied.
Note: in the following, we are careful not to be badly caught
by the compiler optimizations for the representation of arrays. *)
let kapr kpr fmt =
match count_arguments_of_format fmt with
| 0 -> kpr fmt [||]
| 1 -> Obj.magic (fun x ->
let a = Array.make 1 (Obj.repr 0) in
a.(0) <- x;
kpr fmt a)
| 2 -> Obj.magic (fun x y ->
let a = Array.make 2 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y;
kpr fmt a)
| 3 -> Obj.magic (fun x y z ->
let a = Array.make 3 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
kpr fmt a)
| 4 -> Obj.magic (fun x y z t ->
let a = Array.make 4 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t;
kpr fmt a)
| 5 -> Obj.magic (fun x y z t u ->
let a = Array.make 5 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u;
kpr fmt a)
| 6 -> Obj.magic (fun x y z t u v ->
let a = Array.make 6 (Obj.repr 0) in
a.(0) <- x; a.(1) <- y; a.(2) <- z;
a.(3) <- t; a.(4) <- u; a.(5) <- v;
kpr fmt a)
| nargs ->
let rec loop i args =
if i >= nargs then
let a = Array.make nargs (Obj.repr 0) in
list_iter_i (fun i arg -> a.(nargs - i - 1) <- arg) args;
kpr fmt a
else Obj.magic (fun x -> loop (succ i) (x :: args)) in
loop 0 []
;;
type positional_specification =
| Spec_none | Spec_index of Sformat.index
;;
let scan_positional_spec fmt got_spec i =
match Sformat.unsafe_get fmt i with
| '0'..'9' as d ->
let rec get_int_literal accu j =
match Sformat.unsafe_get fmt j with
| '0'..'9' as d ->
get_int_literal (10 * accu + (int_of_char d - 48)) (succ j)
| '$' ->
if accu = 0 then
failwith "printf: bad positional specification (0)." else
got_spec (Spec_index (Sformat.index_of_literal_position accu)) (succ j)
Not a positional specification : tell so the caller , and go back to
scanning the format from the original [ i ] position we were called at
first .
scanning the format from the original [i] position we were called at
first. *)
| _ -> got_spec Spec_none i in
get_int_literal (int_of_char d - 48) (succ i)
| _ -> got_spec Spec_none i
;;
let next_index spec n =
match spec with
| Spec_none -> Sformat.succ_index n
| Spec_index _ -> n
;;
let get_index spec n =
match spec with
| Spec_none -> n
| Spec_index p -> p
;;
Format a float argument as a valid OCaml lexeme .
let format_float_lexeme =
To be revised : this procedure should be a unique loop that performs the
validity check and the string lexeme modification at the same time .
Otherwise , it is too difficult to handle the strange padding facilities
given by printf . Let alone handling the correct widths indication ,
knowing that we have sometime to add a ' . ' at the end of the result !
validity check and the string lexeme modification at the same time.
Otherwise, it is too difficult to handle the strange padding facilities
given by printf. Let alone handling the correct widths indication,
knowing that we have sometime to add a '.' at the end of the result!
*)
let make_valid_float_lexeme s =
Check if s is already a valid lexeme :
in this case do nothing ,
otherwise turn s into a valid OCaml lexeme .
in this case do nothing,
otherwise turn s into a valid OCaml lexeme. *)
let l = String.length s in
let rec valid_float_loop i =
if i >= l then s ^ "." else
match s.[i] with
Sure , this is already a valid float lexeme .
| '.' | 'e' | 'E' -> s
| _ -> valid_float_loop (i + 1) in
valid_float_loop 0 in
(fun sfmt x ->
let s = format_float sfmt x in
match classify_float x with
| FP_normal | FP_subnormal | FP_zero -> make_valid_float_lexeme s
| FP_nan | FP_infinite -> s)
;;
Decode a format string and act on it .
[ fmt ] is the [ printf ] format string , and [ pos ] points to a [ % ] character in
the format string .
After consuming the appropriate number of arguments and formatting
them , one of the following five continuations described below is called :
- [ cont_s ] for outputting a string ( arguments : arg num , string , next pos )
- [ cont_a ] for performing a % a action ( arguments : arg num , fn , arg , next pos )
- [ cont_t ] for performing a % t action ( arguments : arg num , fn , next pos )
- [ cont_f ] for performing a flush action ( arguments : arg num , next pos )
- [ cont_m ] for performing a % ( action ( arguments : arg num , sfmt , next pos )
" arg num " is the index in array [ args ] of the next argument to [ printf ] .
" next pos " is the position in [ fmt ] of the first character following
the % conversion specification in [ fmt ] .
[fmt] is the [printf] format string, and [pos] points to a [%] character in
the format string.
After consuming the appropriate number of arguments and formatting
them, one of the following five continuations described below is called:
- [cont_s] for outputting a string (arguments: arg num, string, next pos)
- [cont_a] for performing a %a action (arguments: arg num, fn, arg, next pos)
- [cont_t] for performing a %t action (arguments: arg num, fn, next pos)
- [cont_f] for performing a flush action (arguments: arg num, next pos)
- [cont_m] for performing a %( action (arguments: arg num, sfmt, next pos)
"arg num" is the index in array [args] of the next argument to [printf].
"next pos" is the position in [fmt] of the first character following
the %conversion specification in [fmt]. *)
let scan_format fmt args n pos cont_s cont_a cont_t cont_f cont_m =
let get_arg spec n =
Obj.magic (args.(Sformat.int_of_index (get_index spec n))) in
let rec scan_positional n widths i =
let got_spec spec i = scan_flags spec n widths i in
scan_positional_spec fmt got_spec i
and scan_flags spec n widths i =
match Sformat.unsafe_get fmt i with
| '*' ->
let got_spec wspec i =
let (width : int) = get_arg wspec n in
scan_flags spec (next_index wspec n) (width :: widths) i in
scan_positional_spec fmt got_spec (succ i)
| '0'..'9'
| '.' | '#' | '-' | ' ' | '+' -> scan_flags spec n widths (succ i)
| _ -> scan_conv spec n widths i
and scan_conv spec n widths i =
match Sformat.unsafe_get fmt i with
| '%' | '@' as c ->
cont_s n (String.make 1 c) (succ i)
| '!' -> cont_f n (succ i)
| ',' -> cont_s n "" (succ i)
| 's' | 'S' as conv ->
let (x : string) = get_arg spec n in
let x = if conv = 's' then x else "\"" ^ String.escaped x ^ "\"" in
let s =
if i = succ pos then x else
format_string (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| '[' as conv ->
bad_conversion_format fmt i conv
| 'c' | 'C' as conv ->
let (x : char) = get_arg spec n in
let s =
if conv = 'c' then String.make 1 x else "'" ^ Char.escaped x ^ "'" in
cont_s (next_index spec n) s (succ i)
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' | 'N' as conv ->
let (x : int) = get_arg spec n in
let s =
format_int (extract_format_int conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'f' | 'e' | 'E' | 'g' | 'G' ->
let (x : float) = get_arg spec n in
let s = format_float (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'F' as conv ->
let (x : float) = get_arg spec n in
let s =
if widths = [] then Pervasives.string_of_float x else
format_float_lexeme (extract_format_float conv fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| 'B' | 'b' ->
let (x : bool) = get_arg spec n in
cont_s (next_index spec n) (string_of_bool x) (succ i)
| 'a' ->
let printer = get_arg spec n in
If the printer spec is Spec_none , go on as usual .
If the printer spec is Spec_index p ,
printer 's argument spec is Spec_index ( succ_index p ) .
If the printer spec is Spec_index p,
printer's argument spec is Spec_index (succ_index p). *)
let n = Sformat.succ_index (get_index spec n) in
let arg = get_arg Spec_none n in
cont_a (next_index spec n) printer arg (succ i)
| 'r' as conv ->
bad_conversion_format fmt i conv
| 't' ->
let printer = get_arg spec n in
cont_t (next_index spec n) printer (succ i)
| 'l' | 'n' | 'L' as conv ->
begin match Sformat.unsafe_get fmt (succ i) with
| 'd' | 'i' | 'o' | 'u' | 'x' | 'X' ->
let i = succ i in
let s =
match conv with
| 'l' ->
let (x : int32) = get_arg spec n in
format_int32 (extract_format fmt pos i widths) x
| 'n' ->
let (x : nativeint) = get_arg spec n in
format_nativeint (extract_format fmt pos i widths) x
| _ ->
let (x : int64) = get_arg spec n in
format_int64 (extract_format fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
| _ ->
let (x : int) = get_arg spec n in
let s = format_int (extract_format_int 'n' fmt pos i widths) x in
cont_s (next_index spec n) s (succ i)
end
let (xf : ('a, 'b, 'c, 'd, 'e, 'f) format6) = get_arg spec n in
let i = succ i in
let j = sub_format_for_printf conv fmt i in
cont_s
(next_index spec n)
(summarize_format_type xf)
j else
cont_m (next_index spec n) xf j
cont_s n "" (succ i)
| conv ->
bad_conversion_format fmt i conv in
scan_positional n [] (succ pos)
;;
let mkprintf to_s get_out outc outs flush k fmt =
let out = get_out fmt in
let rec pr k n fmt v =
let len = Sformat.length fmt in
let rec doprn n i =
if i >= len then Obj.magic (k out) else
match Sformat.unsafe_get fmt i with
| '%' -> scan_format fmt v n i cont_s cont_a cont_t cont_f cont_m
| c -> outc out c; doprn n (succ i)
and cont_s n s i =
outs out s; doprn n i
and cont_a n printer arg i =
if to_s then
outs out ((Obj.magic printer : unit -> _ -> string) () arg)
else
printer out arg;
doprn n i
and cont_t n printer i =
if to_s then
outs out ((Obj.magic printer : unit -> string) ())
else
printer out;
doprn n i
and cont_f n i =
flush out; doprn n i
and cont_m n xf i =
let m = Sformat.add_int_index (count_arguments_of_format xf) n in
pr (Obj.magic (fun _ -> doprn m i)) n xf v in
doprn n 0 in
let kpr = pr k (Sformat.index_of_int 0) in
kapr kpr fmt
;;
let kfprintf k oc =
mkprintf false (fun _ -> oc) output_char output_string flush k
;;
let ifprintf _ = kapr (fun _ -> Obj.magic ignore);;
let fprintf oc = kfprintf ignore oc;;
let printf fmt = fprintf stdout fmt;;
let eprintf fmt = fprintf stderr fmt;;
let kbprintf k b =
mkprintf false (fun _ -> b) Buffer.add_char Buffer.add_string ignore k
;;
let bprintf b = kbprintf ignore b;;
let get_buff fmt =
let len = 2 * Sformat.length fmt in
Buffer.create len
;;
let get_contents b =
let s = Buffer.contents b in
Buffer.clear b;
s
;;
let get_cont k b = k (get_contents b);;
let ksprintf k =
mkprintf true get_buff Buffer.add_char Buffer.add_string ignore (get_cont k)
;;
let sprintf fmt = ksprintf (fun s -> s) fmt;;
let kprintf = ksprintf;;
module CamlinternalPr = struct
module Sformat = Sformat;;
module Tformat = struct
type ac =
Ac.ac = {
mutable ac_rglr : int;
mutable ac_skip : int;
mutable ac_rdrs : int;
}
;;
let ac_of_format = ac_of_format;;
let sub_format = sub_format;;
let summarize_format_type = summarize_format_type;;
let scan_format = scan_format;;
let kapr = kapr;;
end
;;
end
;;
|
3589a06d1d13b6bcc4c6d3b5171afa3a27e88ba4d74bbc5c66a2d5267900798d | iijlab/postgresql-pure | Pure.hs | # LANGUAGE CPP #
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DerivingStrategies #-}
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedLabels #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wno-redundant-constraints #-} -- These warnings are raised, although constraints are necessary.
These warnings are raised , although " builder " , " parser " fields are necessary for instances .
-- |
-- This is a client library for PostgreSQL Database which has following features.
--
-- - faster and less CPU load
--
-- - especially on multi-core environments
--
- pure implementations
--
-- - no libpq dependency
- easy to build even on Windows
--
-- - implements extended query protocol
--
-- - about extended query protocol, see <-flow.html#PROTOCOL-FLOW-EXT-QUERY>
--
-- = Typical Example
--
-- Prepare a following table.
--
-- @
-- CREATE TABLE person (
-- id serial PRIMARY KEY,
-- name varchar(255) NOT NULL
-- );
-- INSERT INTO person (name) VALUES (\'Ada\');
-- @
--
You can run like following to get the record whose ID is 1 .
--
-- >>> :set -XOverloadedStrings
-- >>> :set -XFlexibleContexts
-- >>> :set -XDataKinds
-- >>> :set -XTypeFamilies
-- >>> :set -XTypeApplications
-- >>>
-- >>> import Database.PostgreSQL.Pure
-- >>> import Data.Default.Class (def)
-- >>> import Data.Int (Int32)
> > > import Data . ByteString ( ByteString )
-- >>> import Data.Tuple.Only (Only (Only))
-- >>> import Data.Tuple.Homotuple.Only ()
-- >>> import Data.Maybe (fromMaybe)
-- >>> import System.Environment (lookupEnv)
-- >>>
> > > name value = fromMaybe value < $ > lookupEnv name
-- >>>
> > > host ' < - getEnvDef " PURE_HOST " " 127.0.0.1 "
> > > port ' < - getEnvDef " PURE_PORT " " 5432 "
-- >>> user' <- getEnvDef "PURE_USER" "postgres"
> > > password ' < - getEnvDef " PURE_PASSWORD " " "
-- >>> database' <- getEnvDef "PURE_DATABASE" "postgres"
-- >>>
-- >>> conn <- connect def { address = AddressNotResolved host' port', user = user', password = password', database = database' }
> > > preparedStatementProcedure = parse " " " SELECT i d , name FROM person WHERE i d = $ 1 " Nothing
> > > portalProcedure < - bind @ _ @2 @ _ @ _ " " BinaryFormat BinaryFormat ( parameters conn ) ( const $ fail " " ) ( Only ( 1 : : Int32 ) ) preparedStatementProcedure
> > > executedProcedure = execute @ _ @ _ @(Int32 , ByteString ) 0 ( const $ fail " " ) portalProcedure
-- >>> ((_, _, e, _), _) <- sync conn executedProcedure
-- >>> records e
-- [(1,"Ada")]
module Database.PostgreSQL.Pure
( -- * Connection
Config (..)
, Connection
, pid
, parameters
, config
, Address (..)
, BackendParameters
, Pid
, withConnection
, connect
, disconnect
-- * Extended Query
, parse
, bind
, execute
, flush
, sync
, close
, PreparedStatement
, PreparedStatementProcedure
, PreparedStatementName (..)
, Portal
, PortalProcedure
, PortalName (..)
, Executed
, ExecutedProcedure
, ExecuteResult (..)
, CloseProcedure
, CommandTag (..)
, Query (..)
, FormatCode (..)
, ColumnInfo
, Message
, MessageResult
, Bind
, Execute
, Close
, StringEncoder
, StringDecoder
, HasName
, Name
, HasParameterOids
, name
, parameterOids
, resultInfos
, result
, records
-- * Transaction
, begin
, commit
, rollback
, TransactionState (..)
-- * Record
, FromField (..)
, FromRecord (..)
, ToField (..)
, ToRecord (..)
, Raw (..)
, Length
-- * Exception
, Exception.Exception (..)
, Exception.ErrorResponse (..)
, Exception.ResponseParsingFailed (..)
-- * OID
, Oid
) where
import Database.PostgreSQL.Pure.Internal.Connection (connect, disconnect, withConnection)
import Database.PostgreSQL.Pure.Internal.Data (Address (AddressNotResolved, AddressResolved),
BackendParameters, CloseProcedure, ColumnInfo,
CommandTag (BeginTag, CommitTag, CopyTag, CreateTableTag, DeleteTag, DropTableTag, FetchTag, InsertTag, MoveTag, RollbackTag, SelectTag, UpdateTag),
Config (Config, address, database, password, receptionBufferSize, sendingBufferSize, user),
Connection (config, parameters, pid), ErrorFields,
ExecuteResult (ExecuteComplete, ExecuteEmptyQuery, ExecuteSuspended),
FormatCode (BinaryFormat, TextFormat),
FromField (fromField), FromRecord (fromRecord),
MessageResult, Oid, Pid, PortalName (PortalName),
PreparedStatementName (PreparedStatementName),
Query (Query), Raw (Null, Value), StringDecoder,
StringEncoder, ToField (toField), ToRecord (toRecord),
TransactionState)
import qualified Database.PostgreSQL.Pure.Internal.Data as Data
import qualified Database.PostgreSQL.Pure.Internal.Exception as Exception
import Database.PostgreSQL.Pure.Internal.Length (Length)
import Database.PostgreSQL.Pure.Internal.Query (Close, Message, close, flush, sync)
import qualified Database.PostgreSQL.Pure.Internal.Query as Query
import Data.Bifunctor (bimap)
import Data.Kind (Type)
import Data.Proxy (Proxy (Proxy))
import Data.Tuple.Homotuple (Homotuple, IsHomolisttuple, IsHomotupleItem)
import qualified Data.Tuple.List as Tuple
import GHC.Exts (IsList (Item, fromList, toList))
import GHC.Records (HasField (getField))
import GHC.TypeLits (KnownNat, Nat, natVal)
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail (MonadFail)
#endif
-- | This represents a prepared statement which is already processed by a server.
--
@parameterLength@ is the number of columns of the parameter and @resultLength@ is the number of columns of the results .
This is the same with ' PreparedStatementProcedure ' , ' Portal ' , ' PortalProcedure ' , ' Executed ' and ' ExecutedProcedure ' .
newtype PreparedStatement (parameterLength :: Nat) (resultLength :: Nat) =
PreparedStatement Data.PreparedStatement
deriving newtype (Show, Eq, Close)
instance HasField "name" (PreparedStatement n m) PreparedStatementName where
getField (PreparedStatement Data.PreparedStatement { name }) = name
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasField "parameterOids" (PreparedStatement n m) oids where
getField (PreparedStatement Data.PreparedStatement { parameterOids }) = fromList parameterOids
-- | To get a list of column infos of the result record.
resultInfos :: (IsHomolisttuple m ColumnInfo, IsHomotupleItem m ColumnInfo) => PreparedStatement n m -> Homotuple m ColumnInfo
resultInfos (PreparedStatement Data.PreparedStatement { resultInfos }) = fromList resultInfos
-- | This represents a prepared statement which is not yet processed by a server.
newtype PreparedStatementProcedure (parameterLength :: Nat) (resultLength :: Nat) =
PreparedStatementProcedure Data.PreparedStatementProcedure
deriving newtype (Show, Message)
instance HasField "name" (PreparedStatementProcedure n m) PreparedStatementName where
getField (PreparedStatementProcedure Data.PreparedStatementProcedure { name }) = name
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasField "parameterOids" (PreparedStatementProcedure n m) (Maybe oids) where
getField (PreparedStatementProcedure Data.PreparedStatementProcedure { parameterOids }) = fromList <$> parameterOids
type instance MessageResult (PreparedStatementProcedure n m) = (PreparedStatement n m)
-- | This represents a portal which is already processed by a server.
newtype Portal (parameterLength :: Nat) (resultLength :: Nat) =
Portal Data.Portal
deriving newtype (Show, Eq, Close)
instance HasField "name" (Portal n m) PortalName where
getField (Portal Data.Portal { name }) = name
-- | This represents a portal which is not yet processed by a server.
newtype PortalProcedure (parameterLength :: Nat) (resultLength :: Nat) =
PortalProcedure Data.PortalProcedure
deriving newtype (Show, Message)
instance HasField "name" (PortalProcedure n m) PortalName where
getField (PortalProcedure Data.PortalProcedure { name }) = name
type instance MessageResult (PortalProcedure n m) = (PreparedStatement n m, Portal n m)
-- | This represents a result of a "Execute" message which is already processed by a server.
newtype Executed (parameterLength :: Nat) (resultLength :: Nat) r =
Executed (Data.Executed r)
deriving newtype (Show, Eq)
-- | To get the result of 'Executed'.
result :: Executed n m r -> ExecuteResult
result (Executed Data.Executed { result }) = result
-- | To get the records of 'Executed'.
records :: Executed n m r -> [r]
records (Executed Data.Executed { records }) = records
-- | This represents a result of a "Execute" message which is not yet processed by a server.
newtype ExecutedProcedure (parameterLength :: Nat) (resultLength :: Nat) r =
ExecutedProcedure (Data.ExecutedProcedure r)
deriving newtype (Show, Message)
type instance MessageResult (ExecutedProcedure n m r) = (PreparedStatement n m, Portal n m, Executed n m r, Maybe ErrorFields) -- TODO don't error fields themselves
-- | This means that @r@ has a 'name' accesser.
class HasName r where
| Type of name of @r@.
type Name r :: Type
| To get a name of @r@.
name :: r -> Name r
default name :: HasField "name" r (Name r) => r -> Name r
name = getField @"name"
instance HasName (PreparedStatement n m) where
type Name (PreparedStatement n m) = PreparedStatementName
instance HasName (PreparedStatementProcedure n m) where
type Name (PreparedStatementProcedure n m) = PreparedStatementName
instance HasName (Portal n m) where
type Name (Portal n m) = PortalName
instance HasName (PortalProcedure n m) where
type Name (PortalProcedure n m) = PortalName
-- | This means that @r@ has a 'parameterOids' accesser.
class HasParameterOids r a where
-- | To get OIDs of a parameter.
parameterOids :: r -> a
default parameterOids :: HasField "parameterOids" r a => r -> a
parameterOids = getField @"parameterOids"
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasParameterOids (PreparedStatement n m) oids
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasParameterOids (PreparedStatementProcedure n m) (Maybe oids)
-- Values
-- | To get the procedure to build the message of parsing SQL query and to parse its response.
parse
:: forall plen rlen.
( KnownNat plen
, KnownNat rlen
, IsHomotupleItem plen Oid
, IsHomotupleItem rlen ColumnInfo
, IsHomotupleItem rlen Oid
, IsHomolisttuple rlen Oid
, IsHomolisttuple plen Oid
, IsHomolisttuple rlen ColumnInfo
)
=> PreparedStatementName -- ^ A new name of prepared statement.
^ SQL whose placeoholder style is dollar style .
-> Maybe (Homotuple plen Oid, Homotuple rlen Oid) -- ^ On 'Nothing' an additional pair of a request and a resposne is necessary.
-- If concrete OIDs are given, it will be pass over.
-> PreparedStatementProcedure plen rlen
parse name query oids =
let
lensOrOids =
case oids of
Nothing -> Left (fromInteger $ natVal (Proxy :: Proxy plen), fromInteger $ natVal (Proxy :: Proxy rlen))
Just v -> Right $ bimap toList toList v
in
PreparedStatementProcedure $ Query.parse name query lensOrOids
-- | This means that @ps@ is a objective of 'bind'.
class Bind ps where
-- | To get the procedure to build the message of binding the parameter and to parse its response.
bind
:: forall rlen param m.
( ToRecord param
, KnownNat rlen
, Tuple.HasLength (Homotuple rlen ColumnInfo)
, MonadFail m
)
=> PortalName -- ^ A new name of portal.
-> FormatCode -- ^ Binary format or text format for the parameter.
-> FormatCode -- ^ Binary format or text format for the results.
-> BackendParameters -- ^ The set of the server parameters.
-> StringEncoder -- ^ How to encode strings.
-> param -- ^ Parameter for this query.
-> ps (Length param) rlen -- ^ Prepared statement.
-> m (PortalProcedure (Length param) rlen)
instance Bind PreparedStatement where
bind
:: forall rlen param m.
( ToRecord param
, Tuple.HasLength (Homotuple rlen ColumnInfo)
, MonadFail m
)
=> PortalName -> FormatCode -> FormatCode -> BackendParameters -> StringEncoder -> param -> PreparedStatement (Length param) rlen -> m (PortalProcedure (Length param) rlen)
bind name parameterFormat resultFormat backendParams encode parameters (PreparedStatement ps) = PortalProcedure <$> Query.bind name parameterFormat resultFormat backendParams encode parameters ps
instance Bind PreparedStatementProcedure where
bind
:: forall rlen param m.
( ToRecord param
, KnownNat rlen
, MonadFail m
)
=> PortalName -> FormatCode -> FormatCode -> BackendParameters -> StringEncoder -> param -> PreparedStatementProcedure (Length param) rlen -> m (PortalProcedure (Length param) rlen)
bind name parameterFormat resultFormat backendParams encode parameters (PreparedStatementProcedure psProc) = PortalProcedure <$> Query.bind name parameterFormat resultFormat backendParams encode parameters psProc
| This means that @p@ is a objective of ' execute ' .
class Execute p where
-- | To get the procedure to build the message of execution and to parse its response.
execute
:: forall plen result.
( FromRecord result
, IsHomotupleItem (Length result) ColumnInfo
, IsHomolisttuple (Length result) ColumnInfo
)
=> Word -- ^ How many records to get. "0" means unlimited.
-> StringDecoder -- ^ How to decode strings.
-> p plen (Length result) -- ^ Portal.
-> ExecutedProcedure plen (Length result) result
instance Execute Portal where
execute rowLimit decode (Portal p) = ExecutedProcedure $ Query.execute rowLimit decode p
instance Execute PortalProcedure where
execute rowLimit decode (PortalProcedure pProc) = ExecutedProcedure $ Query.execute rowLimit decode pProc
-- | To send @BEGIN@ SQL statement.
begin :: ExecutedProcedure 0 0 ()
begin = ExecutedProcedure Query.begin
-- | To send @COMMIT@ SQL statement.
commit :: ExecutedProcedure 0 0 ()
commit = ExecutedProcedure Query.commit
-- | To send @ROLLBACK@ SQL statement.
rollback :: ExecutedProcedure 0 0 ()
rollback = ExecutedProcedure Query.rollback
| null | https://raw.githubusercontent.com/iijlab/postgresql-pure/2a640f102f3e3540aedbcf4cfb5d1ed10310f773/src/Database/PostgreSQL/Pure.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE DefaultSignatures #
# LANGUAGE DerivingStrategies #
# LANGUAGE OverloadedLabels #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno-redundant-constraints #
These warnings are raised, although constraints are necessary.
|
This is a client library for PostgreSQL Database which has following features.
- faster and less CPU load
- especially on multi-core environments
- no libpq dependency
- implements extended query protocol
- about extended query protocol, see <-flow.html#PROTOCOL-FLOW-EXT-QUERY>
= Typical Example
Prepare a following table.
@
CREATE TABLE person (
id serial PRIMARY KEY,
name varchar(255) NOT NULL
);
INSERT INTO person (name) VALUES (\'Ada\');
@
>>> :set -XOverloadedStrings
>>> :set -XFlexibleContexts
>>> :set -XDataKinds
>>> :set -XTypeFamilies
>>> :set -XTypeApplications
>>>
>>> import Database.PostgreSQL.Pure
>>> import Data.Default.Class (def)
>>> import Data.Int (Int32)
>>> import Data.Tuple.Only (Only (Only))
>>> import Data.Tuple.Homotuple.Only ()
>>> import Data.Maybe (fromMaybe)
>>> import System.Environment (lookupEnv)
>>>
>>>
>>> user' <- getEnvDef "PURE_USER" "postgres"
>>> database' <- getEnvDef "PURE_DATABASE" "postgres"
>>>
>>> conn <- connect def { address = AddressNotResolved host' port', user = user', password = password', database = database' }
>>> ((_, _, e, _), _) <- sync conn executedProcedure
>>> records e
[(1,"Ada")]
* Connection
* Extended Query
* Transaction
* Record
* Exception
* OID
| This represents a prepared statement which is already processed by a server.
| To get a list of column infos of the result record.
| This represents a prepared statement which is not yet processed by a server.
| This represents a portal which is already processed by a server.
| This represents a portal which is not yet processed by a server.
| This represents a result of a "Execute" message which is already processed by a server.
| To get the result of 'Executed'.
| To get the records of 'Executed'.
| This represents a result of a "Execute" message which is not yet processed by a server.
TODO don't error fields themselves
| This means that @r@ has a 'name' accesser.
| This means that @r@ has a 'parameterOids' accesser.
| To get OIDs of a parameter.
Values
| To get the procedure to build the message of parsing SQL query and to parse its response.
^ A new name of prepared statement.
^ On 'Nothing' an additional pair of a request and a resposne is necessary.
If concrete OIDs are given, it will be pass over.
| This means that @ps@ is a objective of 'bind'.
| To get the procedure to build the message of binding the parameter and to parse its response.
^ A new name of portal.
^ Binary format or text format for the parameter.
^ Binary format or text format for the results.
^ The set of the server parameters.
^ How to encode strings.
^ Parameter for this query.
^ Prepared statement.
| To get the procedure to build the message of execution and to parse its response.
^ How many records to get. "0" means unlimited.
^ How to decode strings.
^ Portal.
| To send @BEGIN@ SQL statement.
| To send @COMMIT@ SQL statement.
| To send @ROLLBACK@ SQL statement. | # LANGUAGE CPP #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
These warnings are raised , although " builder " , " parser " fields are necessary for instances .
- pure implementations
- easy to build even on Windows
You can run like following to get the record whose ID is 1 .
> > > import Data . ByteString ( ByteString )
> > > name value = fromMaybe value < $ > lookupEnv name
> > > host ' < - getEnvDef " PURE_HOST " " 127.0.0.1 "
> > > port ' < - getEnvDef " PURE_PORT " " 5432 "
> > > password ' < - getEnvDef " PURE_PASSWORD " " "
> > > preparedStatementProcedure = parse " " " SELECT i d , name FROM person WHERE i d = $ 1 " Nothing
> > > portalProcedure < - bind @ _ @2 @ _ @ _ " " BinaryFormat BinaryFormat ( parameters conn ) ( const $ fail " " ) ( Only ( 1 : : Int32 ) ) preparedStatementProcedure
> > > executedProcedure = execute @ _ @ _ @(Int32 , ByteString ) 0 ( const $ fail " " ) portalProcedure
module Database.PostgreSQL.Pure
Config (..)
, Connection
, pid
, parameters
, config
, Address (..)
, BackendParameters
, Pid
, withConnection
, connect
, disconnect
, parse
, bind
, execute
, flush
, sync
, close
, PreparedStatement
, PreparedStatementProcedure
, PreparedStatementName (..)
, Portal
, PortalProcedure
, PortalName (..)
, Executed
, ExecutedProcedure
, ExecuteResult (..)
, CloseProcedure
, CommandTag (..)
, Query (..)
, FormatCode (..)
, ColumnInfo
, Message
, MessageResult
, Bind
, Execute
, Close
, StringEncoder
, StringDecoder
, HasName
, Name
, HasParameterOids
, name
, parameterOids
, resultInfos
, result
, records
, begin
, commit
, rollback
, TransactionState (..)
, FromField (..)
, FromRecord (..)
, ToField (..)
, ToRecord (..)
, Raw (..)
, Length
, Exception.Exception (..)
, Exception.ErrorResponse (..)
, Exception.ResponseParsingFailed (..)
, Oid
) where
import Database.PostgreSQL.Pure.Internal.Connection (connect, disconnect, withConnection)
import Database.PostgreSQL.Pure.Internal.Data (Address (AddressNotResolved, AddressResolved),
BackendParameters, CloseProcedure, ColumnInfo,
CommandTag (BeginTag, CommitTag, CopyTag, CreateTableTag, DeleteTag, DropTableTag, FetchTag, InsertTag, MoveTag, RollbackTag, SelectTag, UpdateTag),
Config (Config, address, database, password, receptionBufferSize, sendingBufferSize, user),
Connection (config, parameters, pid), ErrorFields,
ExecuteResult (ExecuteComplete, ExecuteEmptyQuery, ExecuteSuspended),
FormatCode (BinaryFormat, TextFormat),
FromField (fromField), FromRecord (fromRecord),
MessageResult, Oid, Pid, PortalName (PortalName),
PreparedStatementName (PreparedStatementName),
Query (Query), Raw (Null, Value), StringDecoder,
StringEncoder, ToField (toField), ToRecord (toRecord),
TransactionState)
import qualified Database.PostgreSQL.Pure.Internal.Data as Data
import qualified Database.PostgreSQL.Pure.Internal.Exception as Exception
import Database.PostgreSQL.Pure.Internal.Length (Length)
import Database.PostgreSQL.Pure.Internal.Query (Close, Message, close, flush, sync)
import qualified Database.PostgreSQL.Pure.Internal.Query as Query
import Data.Bifunctor (bimap)
import Data.Kind (Type)
import Data.Proxy (Proxy (Proxy))
import Data.Tuple.Homotuple (Homotuple, IsHomolisttuple, IsHomotupleItem)
import qualified Data.Tuple.List as Tuple
import GHC.Exts (IsList (Item, fromList, toList))
import GHC.Records (HasField (getField))
import GHC.TypeLits (KnownNat, Nat, natVal)
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail (MonadFail)
#endif
@parameterLength@ is the number of columns of the parameter and @resultLength@ is the number of columns of the results .
This is the same with ' PreparedStatementProcedure ' , ' Portal ' , ' PortalProcedure ' , ' Executed ' and ' ExecutedProcedure ' .
newtype PreparedStatement (parameterLength :: Nat) (resultLength :: Nat) =
PreparedStatement Data.PreparedStatement
deriving newtype (Show, Eq, Close)
instance HasField "name" (PreparedStatement n m) PreparedStatementName where
getField (PreparedStatement Data.PreparedStatement { name }) = name
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasField "parameterOids" (PreparedStatement n m) oids where
getField (PreparedStatement Data.PreparedStatement { parameterOids }) = fromList parameterOids
resultInfos :: (IsHomolisttuple m ColumnInfo, IsHomotupleItem m ColumnInfo) => PreparedStatement n m -> Homotuple m ColumnInfo
resultInfos (PreparedStatement Data.PreparedStatement { resultInfos }) = fromList resultInfos
newtype PreparedStatementProcedure (parameterLength :: Nat) (resultLength :: Nat) =
PreparedStatementProcedure Data.PreparedStatementProcedure
deriving newtype (Show, Message)
instance HasField "name" (PreparedStatementProcedure n m) PreparedStatementName where
getField (PreparedStatementProcedure Data.PreparedStatementProcedure { name }) = name
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasField "parameterOids" (PreparedStatementProcedure n m) (Maybe oids) where
getField (PreparedStatementProcedure Data.PreparedStatementProcedure { parameterOids }) = fromList <$> parameterOids
type instance MessageResult (PreparedStatementProcedure n m) = (PreparedStatement n m)
newtype Portal (parameterLength :: Nat) (resultLength :: Nat) =
Portal Data.Portal
deriving newtype (Show, Eq, Close)
instance HasField "name" (Portal n m) PortalName where
getField (Portal Data.Portal { name }) = name
newtype PortalProcedure (parameterLength :: Nat) (resultLength :: Nat) =
PortalProcedure Data.PortalProcedure
deriving newtype (Show, Message)
instance HasField "name" (PortalProcedure n m) PortalName where
getField (PortalProcedure Data.PortalProcedure { name }) = name
type instance MessageResult (PortalProcedure n m) = (PreparedStatement n m, Portal n m)
newtype Executed (parameterLength :: Nat) (resultLength :: Nat) r =
Executed (Data.Executed r)
deriving newtype (Show, Eq)
result :: Executed n m r -> ExecuteResult
result (Executed Data.Executed { result }) = result
records :: Executed n m r -> [r]
records (Executed Data.Executed { records }) = records
newtype ExecutedProcedure (parameterLength :: Nat) (resultLength :: Nat) r =
ExecutedProcedure (Data.ExecutedProcedure r)
deriving newtype (Show, Message)
class HasName r where
| Type of name of @r@.
type Name r :: Type
| To get a name of @r@.
name :: r -> Name r
default name :: HasField "name" r (Name r) => r -> Name r
name = getField @"name"
instance HasName (PreparedStatement n m) where
type Name (PreparedStatement n m) = PreparedStatementName
instance HasName (PreparedStatementProcedure n m) where
type Name (PreparedStatementProcedure n m) = PreparedStatementName
instance HasName (Portal n m) where
type Name (Portal n m) = PortalName
instance HasName (PortalProcedure n m) where
type Name (PortalProcedure n m) = PortalName
class HasParameterOids r a where
parameterOids :: r -> a
default parameterOids :: HasField "parameterOids" r a => r -> a
parameterOids = getField @"parameterOids"
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasParameterOids (PreparedStatement n m) oids
instance (oids ~ Homotuple n Oid, Item oids ~ Oid, IsList oids) => HasParameterOids (PreparedStatementProcedure n m) (Maybe oids)
parse
:: forall plen rlen.
( KnownNat plen
, KnownNat rlen
, IsHomotupleItem plen Oid
, IsHomotupleItem rlen ColumnInfo
, IsHomotupleItem rlen Oid
, IsHomolisttuple rlen Oid
, IsHomolisttuple plen Oid
, IsHomolisttuple rlen ColumnInfo
)
^ SQL whose placeoholder style is dollar style .
-> PreparedStatementProcedure plen rlen
parse name query oids =
let
lensOrOids =
case oids of
Nothing -> Left (fromInteger $ natVal (Proxy :: Proxy plen), fromInteger $ natVal (Proxy :: Proxy rlen))
Just v -> Right $ bimap toList toList v
in
PreparedStatementProcedure $ Query.parse name query lensOrOids
class Bind ps where
bind
:: forall rlen param m.
( ToRecord param
, KnownNat rlen
, Tuple.HasLength (Homotuple rlen ColumnInfo)
, MonadFail m
)
-> m (PortalProcedure (Length param) rlen)
instance Bind PreparedStatement where
bind
:: forall rlen param m.
( ToRecord param
, Tuple.HasLength (Homotuple rlen ColumnInfo)
, MonadFail m
)
=> PortalName -> FormatCode -> FormatCode -> BackendParameters -> StringEncoder -> param -> PreparedStatement (Length param) rlen -> m (PortalProcedure (Length param) rlen)
bind name parameterFormat resultFormat backendParams encode parameters (PreparedStatement ps) = PortalProcedure <$> Query.bind name parameterFormat resultFormat backendParams encode parameters ps
instance Bind PreparedStatementProcedure where
bind
:: forall rlen param m.
( ToRecord param
, KnownNat rlen
, MonadFail m
)
=> PortalName -> FormatCode -> FormatCode -> BackendParameters -> StringEncoder -> param -> PreparedStatementProcedure (Length param) rlen -> m (PortalProcedure (Length param) rlen)
bind name parameterFormat resultFormat backendParams encode parameters (PreparedStatementProcedure psProc) = PortalProcedure <$> Query.bind name parameterFormat resultFormat backendParams encode parameters psProc
| This means that @p@ is a objective of ' execute ' .
class Execute p where
execute
:: forall plen result.
( FromRecord result
, IsHomotupleItem (Length result) ColumnInfo
, IsHomolisttuple (Length result) ColumnInfo
)
-> ExecutedProcedure plen (Length result) result
instance Execute Portal where
execute rowLimit decode (Portal p) = ExecutedProcedure $ Query.execute rowLimit decode p
instance Execute PortalProcedure where
execute rowLimit decode (PortalProcedure pProc) = ExecutedProcedure $ Query.execute rowLimit decode pProc
begin :: ExecutedProcedure 0 0 ()
begin = ExecutedProcedure Query.begin
commit :: ExecutedProcedure 0 0 ()
commit = ExecutedProcedure Query.commit
rollback :: ExecutedProcedure 0 0 ()
rollback = ExecutedProcedure Query.rollback
|
07a79b76d64bb3d6e425bc9c3a74cbcf16e0c284bc944ec13a3a7cdc7f1257b7 | ingesolvoll/kee-frame | api.cljc | (ns kee-frame.api)
(defprotocol Navigator
(dispatch-current! [_])
(navigate! [_ url]))
(defprotocol Router
(data->url [_ data])
(url->data [_ url])) | null | https://raw.githubusercontent.com/ingesolvoll/kee-frame/caeddaf8fdb2bab6e16573453d13141b3ba12378/src/kee_frame/api.cljc | clojure | (ns kee-frame.api)
(defprotocol Navigator
(dispatch-current! [_])
(navigate! [_ url]))
(defprotocol Router
(data->url [_ data])
(url->data [_ url])) | |
f0b1dadc1caf06e6c792be4d49e2514a99830803a06fe875123225a0bb1ee877 | sadiqj/ocaml-esp32 | typedtree.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. *)
(* *)
(**************************************************************************)
(** Abstract syntax tree after typing *)
* By comparison with { ! :
- Every { ! Longindent.t } is accompanied by a resolved { ! Path.t } .
- Every {!Longindent.t} is accompanied by a resolved {!Path.t}.
*)
open Asttypes
open Types
(* Value expressions for the core language *)
type partial = Partial | Total
* { 1 Extension points }
type attribute = Parsetree.attribute
type attributes = attribute list
* { 1 Core language }
type pattern =
{ pat_desc: pattern_desc;
pat_loc: Location.t;
pat_extra : (pat_extra * Location.t * attributes) list;
pat_type: type_expr;
mutable pat_env: Env.t;
pat_attributes: attributes;
}
and pat_extra =
| Tpat_constraint of core_type
* P : T ; pat_extra = ( Tpat_constraint T , _ , _ ) : : ... }
; pat_extra = (Tpat_constraint T, _, _) :: ... }
*)
| Tpat_type of Path.t * Longident.t loc
* # tconst disjunction
; pat_extra = ( Tpat_type ( P , " tconst " ) , _ , _ ) : : ... }
where [ disjunction ] is a [ Tpat_or _ ] representing the
branches of [ tconst ] .
; pat_extra = (Tpat_type (P, "tconst"), _, _) :: ...}
where [disjunction] is a [Tpat_or _] representing the
branches of [tconst].
*)
| Tpat_open of Path.t * Longident.t loc * Env.t
| Tpat_unpack
* ( module P ) Tpat_var " P "
; pat_extra = ( Tpat_unpack , _ , _ ) : : ... }
; pat_extra = (Tpat_unpack, _, _) :: ... }
*)
and pattern_desc =
Tpat_any
(** _ *)
| Tpat_var of Ident.t * string loc
(** x *)
| Tpat_alias of pattern * Ident.t * string loc
(** P as a *)
| Tpat_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Tpat_tuple of pattern list
* ( P1 , ... , Pn )
Invariant : n > = 2
Invariant: n >= 2
*)
| Tpat_construct of
Longident.t loc * constructor_description * pattern list
* C [ ]
C P [ P ]
C ( P1 , ... , Pn ) [ P1 ; ... ; Pn ]
C P [P]
C (P1, ..., Pn) [P1; ...; Pn]
*)
| Tpat_variant of label * pattern option * row_desc ref
(** `A (None)
`A P (Some P)
See {!Types.row_desc} for an explanation of the last parameter.
*)
| Tpat_record of
(Longident.t loc * label_description * pattern) list *
closed_flag
* { l1 = P1 ; ... ; ln = Pn } ( flag = Closed )
{ l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open )
Invariant : n > 0
{ l1=P1; ...; ln=Pn; _} (flag = Open)
Invariant: n > 0
*)
| Tpat_array of pattern list
(** [| P1; ...; Pn |] *)
| Tpat_or of pattern * pattern * row_desc option
(** P1 | P2
[row_desc] = [Some _] when translating [Ppat_type _],
[None] otherwise.
*)
| Tpat_lazy of pattern
(** lazy P *)
and expression =
{ exp_desc: expression_desc;
exp_loc: Location.t;
exp_extra: (exp_extra * Location.t * attributes) list;
exp_type: type_expr;
exp_env: Env.t;
exp_attributes: attributes;
}
and exp_extra =
| Texp_constraint of core_type
(** E : T *)
| Texp_coerce of core_type option * core_type
* E :> T [ Texp_coerce ( None , T ) ]
E : T0 :> T [ Texp_coerce ( Some T0 , T ) ]
E : T0 :> T [Texp_coerce (Some T0, T)]
*)
| Texp_open of override_flag * Path.t * Longident.t loc * Env.t
(** let open[!] M in [Texp_open (!, P, M, env)]
where [env] is the environment after opening [P]
*)
| Texp_poly of core_type option
(** Used for method bodies. *)
| Texp_newtype of string
(** fun (type t) -> *)
and expression_desc =
Texp_ident of Path.t * Longident.t loc * Types.value_description
* x
M.x
*)
| Texp_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Texp_let of rec_flag * value_binding list * expression
* let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Texp_function of { arg_label : arg_label; param : Ident.t;
cases : case list; partial : partial; }
* [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] .
See { ! for more details .
[ param ] is the identifier that is to be used to name the
parameter of the function .
partial =
[ Partial ] if the pattern match is partial
[ Total ] otherwise .
See {!Parsetree} for more details.
[param] is the identifier that is to be used to name the
parameter of the function.
partial =
[Partial] if the pattern match is partial
[Total] otherwise.
*)
| Texp_apply of expression * (arg_label * expression option) list
* E0 ~l1 : E1 ... ~ln : En
The expression can be None if the expression is abstracted over
this argument . It currently appears when a label is applied .
For example :
let f x ~y = x + y in
f ~y:3
The resulting typedtree for the application is :
Texp_apply ( Texp_ident " f/1037 " ,
[ ( Nolabel , None ) ;
( Labelled " y " , Some ( Texp_constant Const_int 3 ) )
] )
The expression can be None if the expression is abstracted over
this argument. It currently appears when a label is applied.
For example:
let f x ~y = x + y in
f ~y:3
The resulting typedtree for the application is:
Texp_apply (Texp_ident "f/1037",
[(Nolabel, None);
(Labelled "y", Some (Texp_constant Const_int 3))
])
*)
| Texp_match of expression * case list * case list * partial
* match E0 with
| P1 - > E1
| P2 - > E2
| exception P3 - > E3
[ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 , E2 ) ] , [ ( P3 , E3 ) ] , _ ) ]
| P1 -> E1
| P2 -> E2
| exception P3 -> E3
[Texp_match (E0, [(P1, E1); (P2, E2)], [(P3, E3)], _)]
*)
| Texp_try of expression * case list
(** try E with P1 -> E1 | ... | PN -> EN *)
| Texp_tuple of expression list
(** (E1, ..., EN) *)
| Texp_construct of
Longident.t loc * constructor_description * expression list
(** C []
C E [E]
C (E1, ..., En) [E1;...;En]
*)
| Texp_variant of label * expression option
| Texp_record of {
fields : ( Types.label_description * record_label_definition ) array;
representation : Types.record_representation;
extended_expression : expression option;
}
* { l1 = P1 ; ... ; ln = Pn } ( extended_expression = None )
{ E0 with l1 = P1 ; ... ; ln = Pn } ( extended_expression = Some E0 )
Invariant : n > 0
If the type is { l1 : t1 ; l2 : t2 } , the expression
{ E0 with t2 = P2 } is represented as
Texp_record
{ fields = [ | l1 , Kept t1 ; l2 Override P2 | ] ; representation ;
extended_expression = Some E0 }
{ E0 with l1=P1; ...; ln=Pn } (extended_expression = Some E0)
Invariant: n > 0
If the type is { l1: t1; l2: t2 }, the expression
{ E0 with t2=P2 } is represented as
Texp_record
{ fields = [| l1, Kept t1; l2 Override P2 |]; representation;
extended_expression = Some E0 }
*)
| Texp_field of expression * Longident.t loc * label_description
| Texp_setfield of
expression * Longident.t loc * label_description * expression
| Texp_array of expression list
| Texp_ifthenelse of expression * expression * expression option
| Texp_sequence of expression * expression
| Texp_while of expression * expression
| Texp_for of
Ident.t * Parsetree.pattern * expression * expression * direction_flag *
expression
| Texp_send of expression * meth * expression option
| Texp_new of Path.t * Longident.t loc * Types.class_declaration
| Texp_instvar of Path.t * Path.t * string loc
| Texp_setinstvar of Path.t * Path.t * string loc * expression
| Texp_override of Path.t * (Path.t * string loc * expression) list
| Texp_letmodule of Ident.t * string loc * module_expr * expression
| Texp_letexception of extension_constructor * expression
| Texp_assert of expression
| Texp_lazy of expression
| Texp_object of class_structure * string list
| Texp_pack of module_expr
| Texp_unreachable
| Texp_extension_constructor of Longident.t loc * Path.t
and meth =
Tmeth_name of string
| Tmeth_val of Ident.t
and case =
{
c_lhs: pattern;
c_guard: expression option;
c_rhs: expression;
}
and record_label_definition =
| Kept of Types.type_expr
| Overridden of Longident.t loc * expression
(* Value expressions for the class language *)
and class_expr =
{
cl_desc: class_expr_desc;
cl_loc: Location.t;
cl_type: Types.class_type;
cl_env: Env.t;
cl_attributes: attributes;
}
and class_expr_desc =
Tcl_ident of Path.t * Longident.t loc * core_type list
| Tcl_structure of class_structure
| Tcl_fun of
arg_label * pattern * (Ident.t * string loc * expression) list
* class_expr * partial
| Tcl_apply of class_expr * (arg_label * expression option) list
| Tcl_let of rec_flag * value_binding list *
(Ident.t * string loc * expression) list * class_expr
| Tcl_constraint of
class_expr * class_type option * string list * string list * Concr.t
(* Visible instance variables, methods and concrete methods *)
| Tcl_open of override_flag * Path.t * Longident.t loc * Env.t * class_expr
and class_structure =
{
cstr_self: pattern;
cstr_fields: class_field list;
cstr_type: Types.class_signature;
cstr_meths: Ident.t Meths.t;
}
and class_field =
{
cf_desc: class_field_desc;
cf_loc: Location.t;
cf_attributes: attributes;
}
and class_field_kind =
| Tcfk_virtual of core_type
| Tcfk_concrete of override_flag * expression
and class_field_desc =
Tcf_inherit of
override_flag * class_expr * string option * (string * Ident.t) list *
(string * Ident.t) list
(* Inherited instance variables and concrete methods *)
| Tcf_val of string loc * mutable_flag * Ident.t * class_field_kind * bool
| Tcf_method of string loc * private_flag * class_field_kind
| Tcf_constraint of core_type * core_type
| Tcf_initializer of expression
| Tcf_attribute of attribute
(* Value expressions for the module language *)
and module_expr =
{ mod_desc: module_expr_desc;
mod_loc: Location.t;
mod_type: Types.module_type;
mod_env: Env.t;
mod_attributes: attributes;
}
(** Annotations for [Tmod_constraint]. *)
and module_type_constraint =
| Tmodtype_implicit
(** The module type constraint has been synthesized during typechecking. *)
| Tmodtype_explicit of module_type
(** The module type was in the source file. *)
and module_expr_desc =
Tmod_ident of Path.t * Longident.t loc
| Tmod_structure of structure
| Tmod_functor of Ident.t * string loc * module_type option * module_expr
| Tmod_apply of module_expr * module_expr * module_coercion
| Tmod_constraint of
module_expr * Types.module_type * module_type_constraint * module_coercion
(** ME (constraint = Tmodtype_implicit)
(ME : MT) (constraint = Tmodtype_explicit MT)
*)
| Tmod_unpack of expression * Types.module_type
and structure = {
str_items : structure_item list;
str_type : Types.signature;
str_final_env : Env.t;
}
and structure_item =
{ str_desc : structure_item_desc;
str_loc : Location.t;
str_env : Env.t
}
and structure_item_desc =
Tstr_eval of expression * attributes
| Tstr_value of rec_flag * value_binding list
| Tstr_primitive of value_description
| Tstr_type of rec_flag * type_declaration list
| Tstr_typext of type_extension
| Tstr_exception of extension_constructor
| Tstr_module of module_binding
| Tstr_recmodule of module_binding list
| Tstr_modtype of module_type_declaration
| Tstr_open of open_description
| Tstr_class of (class_declaration * string list) list
| Tstr_class_type of (Ident.t * string loc * class_type_declaration) list
| Tstr_include of include_declaration
| Tstr_attribute of attribute
and module_binding =
{
mb_id: Ident.t;
mb_name: string loc;
mb_expr: module_expr;
mb_attributes: attributes;
mb_loc: Location.t;
}
and value_binding =
{
vb_pat: pattern;
vb_expr: expression;
vb_attributes: attributes;
vb_loc: Location.t;
}
and module_coercion =
Tcoerce_none
| Tcoerce_structure of (int * module_coercion) list *
(Ident.t * int * module_coercion) list
| Tcoerce_functor of module_coercion * module_coercion
| Tcoerce_primitive of primitive_coercion
| Tcoerce_alias of Path.t * module_coercion
and module_type =
{ mty_desc: module_type_desc;
mty_type : Types.module_type;
mty_env : Env.t;
mty_loc: Location.t;
mty_attributes: attributes;
}
and module_type_desc =
Tmty_ident of Path.t * Longident.t loc
| Tmty_signature of signature
| Tmty_functor of Ident.t * string loc * module_type option * module_type
| Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list
| Tmty_typeof of module_expr
| Tmty_alias of Path.t * Longident.t loc
and primitive_coercion =
{
pc_desc: Primitive.description;
pc_type: type_expr;
pc_env: Env.t;
pc_loc : Location.t;
}
and signature = {
sig_items : signature_item list;
sig_type : Types.signature;
sig_final_env : Env.t;
}
and signature_item =
{ sig_desc: signature_item_desc;
sig_env : Env.t; (* BINANNOT ADDED *)
sig_loc: Location.t }
and signature_item_desc =
Tsig_value of value_description
| Tsig_type of rec_flag * type_declaration list
| Tsig_typext of type_extension
| Tsig_exception of extension_constructor
| Tsig_module of module_declaration
| Tsig_recmodule of module_declaration list
| Tsig_modtype of module_type_declaration
| Tsig_open of open_description
| Tsig_include of include_description
| Tsig_class of class_description list
| Tsig_class_type of class_type_declaration list
| Tsig_attribute of attribute
and module_declaration =
{
md_id: Ident.t;
md_name: string loc;
md_type: module_type;
md_attributes: attributes;
md_loc: Location.t;
}
and module_type_declaration =
{
mtd_id: Ident.t;
mtd_name: string loc;
mtd_type: module_type option;
mtd_attributes: attributes;
mtd_loc: Location.t;
}
and open_description =
{
open_path: Path.t;
open_txt: Longident.t loc;
open_override: override_flag;
open_loc: Location.t;
open_attributes: attribute list;
}
and 'a include_infos =
{
incl_mod: 'a;
incl_type: Types.signature;
incl_loc: Location.t;
incl_attributes: attribute list;
}
and include_description = module_type include_infos
and include_declaration = module_expr include_infos
and with_constraint =
Twith_type of type_declaration
| Twith_module of Path.t * Longident.t loc
| Twith_typesubst of type_declaration
| Twith_modsubst of Path.t * Longident.t loc
and core_type =
{ mutable ctyp_desc : core_type_desc;
(** mutable because of [Typeclass.declare_method] *)
mutable ctyp_type : type_expr;
(** mutable because of [Typeclass.declare_method] *)
ctyp_env : Env.t; (* BINANNOT ADDED *)
ctyp_loc : Location.t;
ctyp_attributes: attributes;
}
and core_type_desc =
Ttyp_any
| Ttyp_var of string
| Ttyp_arrow of arg_label * core_type * core_type
| Ttyp_tuple of core_type list
| Ttyp_constr of Path.t * Longident.t loc * core_type list
| Ttyp_object of object_field list * closed_flag
| Ttyp_class of Path.t * Longident.t loc * core_type list
| Ttyp_alias of core_type * string
| Ttyp_variant of row_field list * closed_flag * label list option
| Ttyp_poly of string list * core_type
| Ttyp_package of package_type
and package_type = {
pack_path : Path.t;
pack_fields : (Longident.t loc * core_type) list;
pack_type : Types.module_type;
pack_txt : Longident.t loc;
}
and row_field =
Ttag of string loc * attributes * bool * core_type list
| Tinherit of core_type
and object_field =
| OTtag of string loc * attributes * core_type
| OTinherit of core_type
and value_description =
{ val_id: Ident.t;
val_name: string loc;
val_desc: core_type;
val_val: Types.value_description;
val_prim: string list;
val_loc: Location.t;
val_attributes: attributes;
}
and type_declaration =
{
typ_id: Ident.t;
typ_name: string loc;
typ_params: (core_type * variance) list;
typ_type: Types.type_declaration;
typ_cstrs: (core_type * core_type * Location.t) list;
typ_kind: type_kind;
typ_private: private_flag;
typ_manifest: core_type option;
typ_loc: Location.t;
typ_attributes: attributes;
}
and type_kind =
Ttype_abstract
| Ttype_variant of constructor_declaration list
| Ttype_record of label_declaration list
| Ttype_open
and label_declaration =
{
ld_id: Ident.t;
ld_name: string loc;
ld_mutable: mutable_flag;
ld_type: core_type;
ld_loc: Location.t;
ld_attributes: attributes;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_name: string loc;
cd_args: constructor_arguments;
cd_res: core_type option;
cd_loc: Location.t;
cd_attributes: attributes;
}
and constructor_arguments =
| Cstr_tuple of core_type list
| Cstr_record of label_declaration list
and type_extension =
{
tyext_path: Path.t;
tyext_txt: Longident.t loc;
tyext_params: (core_type * variance) list;
tyext_constructors: extension_constructor list;
tyext_private: private_flag;
tyext_attributes: attributes;
}
and extension_constructor =
{
ext_id: Ident.t;
ext_name: string loc;
ext_type : Types.extension_constructor;
ext_kind : extension_constructor_kind;
ext_loc : Location.t;
ext_attributes: attributes;
}
and extension_constructor_kind =
Text_decl of constructor_arguments * core_type option
| Text_rebind of Path.t * Longident.t loc
and class_type =
{
cltyp_desc: class_type_desc;
cltyp_type: Types.class_type;
cltyp_env: Env.t;
cltyp_loc: Location.t;
cltyp_attributes: attributes;
}
and class_type_desc =
Tcty_constr of Path.t * Longident.t loc * core_type list
| Tcty_signature of class_signature
| Tcty_arrow of arg_label * core_type * class_type
| Tcty_open of override_flag * Path.t * Longident.t loc * Env.t * class_type
and class_signature = {
csig_self : core_type;
csig_fields : class_type_field list;
csig_type : Types.class_signature;
}
and class_type_field = {
ctf_desc: class_type_field_desc;
ctf_loc: Location.t;
ctf_attributes: attributes;
}
and class_type_field_desc =
| Tctf_inherit of class_type
| Tctf_val of (string * mutable_flag * virtual_flag * core_type)
| Tctf_method of (string * private_flag * virtual_flag * core_type)
| Tctf_constraint of (core_type * core_type)
| Tctf_attribute of attribute
and class_declaration =
class_expr class_infos
and class_description =
class_type class_infos
and class_type_declaration =
class_type class_infos
and 'a class_infos =
{ ci_virt: virtual_flag;
ci_params: (core_type * variance) list;
ci_id_name : string loc;
ci_id_class: Ident.t;
ci_id_class_type : Ident.t;
ci_id_object : Ident.t;
ci_id_typehash : Ident.t;
ci_expr: 'a;
ci_decl: Types.class_declaration;
ci_type_decl : Types.class_type_declaration;
ci_loc: Location.t;
ci_attributes: attributes;
}
(* Auxiliary functions over the a.s.t. *)
val iter_pattern_desc: (pattern -> unit) -> pattern_desc -> unit
val map_pattern_desc: (pattern -> pattern) -> pattern_desc -> pattern_desc
val let_bound_idents: value_binding list -> Ident.t list
val rev_let_bound_idents: value_binding list -> Ident.t list
val let_bound_idents_with_loc:
value_binding list -> (Ident.t * string loc) list
(** Alpha conversion of patterns *)
val alpha_pat: (Ident.t * Ident.t) list -> pattern -> pattern
val mknoloc: 'a -> 'a Asttypes.loc
val mkloc: 'a -> Location.t -> 'a Asttypes.loc
val pat_bound_idents: pattern -> Ident.t list
| null | https://raw.githubusercontent.com/sadiqj/ocaml-esp32/33aad4ca2becb9701eb90d779c1b1183aefeb578/typing/typedtree.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.
************************************************************************
* Abstract syntax tree after typing
Value expressions for the core language
* _
* x
* P as a
* `A (None)
`A P (Some P)
See {!Types.row_desc} for an explanation of the last parameter.
* [| P1; ...; Pn |]
* P1 | P2
[row_desc] = [Some _] when translating [Ppat_type _],
[None] otherwise.
* lazy P
* E : T
* let open[!] M in [Texp_open (!, P, M, env)]
where [env] is the environment after opening [P]
* Used for method bodies.
* fun (type t) ->
* try E with P1 -> E1 | ... | PN -> EN
* (E1, ..., EN)
* C []
C E [E]
C (E1, ..., En) [E1;...;En]
Value expressions for the class language
Visible instance variables, methods and concrete methods
Inherited instance variables and concrete methods
Value expressions for the module language
* Annotations for [Tmod_constraint].
* The module type constraint has been synthesized during typechecking.
* The module type was in the source file.
* ME (constraint = Tmodtype_implicit)
(ME : MT) (constraint = Tmodtype_explicit MT)
BINANNOT ADDED
* mutable because of [Typeclass.declare_method]
* mutable because of [Typeclass.declare_method]
BINANNOT ADDED
Auxiliary functions over the a.s.t.
* Alpha conversion of patterns | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* By comparison with { ! :
- Every { ! Longindent.t } is accompanied by a resolved { ! Path.t } .
- Every {!Longindent.t} is accompanied by a resolved {!Path.t}.
*)
open Asttypes
open Types
type partial = Partial | Total
* { 1 Extension points }
type attribute = Parsetree.attribute
type attributes = attribute list
* { 1 Core language }
type pattern =
{ pat_desc: pattern_desc;
pat_loc: Location.t;
pat_extra : (pat_extra * Location.t * attributes) list;
pat_type: type_expr;
mutable pat_env: Env.t;
pat_attributes: attributes;
}
and pat_extra =
| Tpat_constraint of core_type
* P : T ; pat_extra = ( Tpat_constraint T , _ , _ ) : : ... }
; pat_extra = (Tpat_constraint T, _, _) :: ... }
*)
| Tpat_type of Path.t * Longident.t loc
* # tconst disjunction
; pat_extra = ( Tpat_type ( P , " tconst " ) , _ , _ ) : : ... }
where [ disjunction ] is a [ Tpat_or _ ] representing the
branches of [ tconst ] .
; pat_extra = (Tpat_type (P, "tconst"), _, _) :: ...}
where [disjunction] is a [Tpat_or _] representing the
branches of [tconst].
*)
| Tpat_open of Path.t * Longident.t loc * Env.t
| Tpat_unpack
* ( module P ) Tpat_var " P "
; pat_extra = ( Tpat_unpack , _ , _ ) : : ... }
; pat_extra = (Tpat_unpack, _, _) :: ... }
*)
and pattern_desc =
Tpat_any
| Tpat_var of Ident.t * string loc
| Tpat_alias of pattern * Ident.t * string loc
| Tpat_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Tpat_tuple of pattern list
* ( P1 , ... , Pn )
Invariant : n > = 2
Invariant: n >= 2
*)
| Tpat_construct of
Longident.t loc * constructor_description * pattern list
* C [ ]
C P [ P ]
C ( P1 , ... , Pn ) [ P1 ; ... ; Pn ]
C P [P]
C (P1, ..., Pn) [P1; ...; Pn]
*)
| Tpat_variant of label * pattern option * row_desc ref
| Tpat_record of
(Longident.t loc * label_description * pattern) list *
closed_flag
* { l1 = P1 ; ... ; ln = Pn } ( flag = Closed )
{ l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open )
Invariant : n > 0
{ l1=P1; ...; ln=Pn; _} (flag = Open)
Invariant: n > 0
*)
| Tpat_array of pattern list
| Tpat_or of pattern * pattern * row_desc option
| Tpat_lazy of pattern
and expression =
{ exp_desc: expression_desc;
exp_loc: Location.t;
exp_extra: (exp_extra * Location.t * attributes) list;
exp_type: type_expr;
exp_env: Env.t;
exp_attributes: attributes;
}
and exp_extra =
| Texp_constraint of core_type
| Texp_coerce of core_type option * core_type
* E :> T [ Texp_coerce ( None , T ) ]
E : T0 :> T [ Texp_coerce ( Some T0 , T ) ]
E : T0 :> T [Texp_coerce (Some T0, T)]
*)
| Texp_open of override_flag * Path.t * Longident.t loc * Env.t
| Texp_poly of core_type option
| Texp_newtype of string
and expression_desc =
Texp_ident of Path.t * Longident.t loc * Types.value_description
* x
M.x
*)
| Texp_constant of constant
* 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n
| Texp_let of rec_flag * value_binding list * expression
* let P1 = E1 and ... and Pn = EN in E ( flag = )
let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive )
let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive)
*)
| Texp_function of { arg_label : arg_label; param : Ident.t;
cases : case list; partial : partial; }
* [ Pexp_fun ] and [ Pexp_function ] both translate to [ Texp_function ] .
See { ! for more details .
[ param ] is the identifier that is to be used to name the
parameter of the function .
partial =
[ Partial ] if the pattern match is partial
[ Total ] otherwise .
See {!Parsetree} for more details.
[param] is the identifier that is to be used to name the
parameter of the function.
partial =
[Partial] if the pattern match is partial
[Total] otherwise.
*)
| Texp_apply of expression * (arg_label * expression option) list
* E0 ~l1 : E1 ... ~ln : En
The expression can be None if the expression is abstracted over
this argument . It currently appears when a label is applied .
For example :
let f x ~y = x + y in
f ~y:3
The resulting typedtree for the application is :
Texp_apply ( Texp_ident " f/1037 " ,
[ ( Nolabel , None ) ;
( Labelled " y " , Some ( Texp_constant Const_int 3 ) )
] )
The expression can be None if the expression is abstracted over
this argument. It currently appears when a label is applied.
For example:
let f x ~y = x + y in
f ~y:3
The resulting typedtree for the application is:
Texp_apply (Texp_ident "f/1037",
[(Nolabel, None);
(Labelled "y", Some (Texp_constant Const_int 3))
])
*)
| Texp_match of expression * case list * case list * partial
* match E0 with
| P1 - > E1
| P2 - > E2
| exception P3 - > E3
[ Texp_match ( E0 , [ ( P1 , E1 ) ; ( P2 , E2 ) ] , [ ( P3 , E3 ) ] , _ ) ]
| P1 -> E1
| P2 -> E2
| exception P3 -> E3
[Texp_match (E0, [(P1, E1); (P2, E2)], [(P3, E3)], _)]
*)
| Texp_try of expression * case list
| Texp_tuple of expression list
| Texp_construct of
Longident.t loc * constructor_description * expression list
| Texp_variant of label * expression option
| Texp_record of {
fields : ( Types.label_description * record_label_definition ) array;
representation : Types.record_representation;
extended_expression : expression option;
}
* { l1 = P1 ; ... ; ln = Pn } ( extended_expression = None )
{ E0 with l1 = P1 ; ... ; ln = Pn } ( extended_expression = Some E0 )
Invariant : n > 0
If the type is { l1 : t1 ; l2 : t2 } , the expression
{ E0 with t2 = P2 } is represented as
Texp_record
{ fields = [ | l1 , Kept t1 ; l2 Override P2 | ] ; representation ;
extended_expression = Some E0 }
{ E0 with l1=P1; ...; ln=Pn } (extended_expression = Some E0)
Invariant: n > 0
If the type is { l1: t1; l2: t2 }, the expression
{ E0 with t2=P2 } is represented as
Texp_record
{ fields = [| l1, Kept t1; l2 Override P2 |]; representation;
extended_expression = Some E0 }
*)
| Texp_field of expression * Longident.t loc * label_description
| Texp_setfield of
expression * Longident.t loc * label_description * expression
| Texp_array of expression list
| Texp_ifthenelse of expression * expression * expression option
| Texp_sequence of expression * expression
| Texp_while of expression * expression
| Texp_for of
Ident.t * Parsetree.pattern * expression * expression * direction_flag *
expression
| Texp_send of expression * meth * expression option
| Texp_new of Path.t * Longident.t loc * Types.class_declaration
| Texp_instvar of Path.t * Path.t * string loc
| Texp_setinstvar of Path.t * Path.t * string loc * expression
| Texp_override of Path.t * (Path.t * string loc * expression) list
| Texp_letmodule of Ident.t * string loc * module_expr * expression
| Texp_letexception of extension_constructor * expression
| Texp_assert of expression
| Texp_lazy of expression
| Texp_object of class_structure * string list
| Texp_pack of module_expr
| Texp_unreachable
| Texp_extension_constructor of Longident.t loc * Path.t
and meth =
Tmeth_name of string
| Tmeth_val of Ident.t
and case =
{
c_lhs: pattern;
c_guard: expression option;
c_rhs: expression;
}
and record_label_definition =
| Kept of Types.type_expr
| Overridden of Longident.t loc * expression
and class_expr =
{
cl_desc: class_expr_desc;
cl_loc: Location.t;
cl_type: Types.class_type;
cl_env: Env.t;
cl_attributes: attributes;
}
and class_expr_desc =
Tcl_ident of Path.t * Longident.t loc * core_type list
| Tcl_structure of class_structure
| Tcl_fun of
arg_label * pattern * (Ident.t * string loc * expression) list
* class_expr * partial
| Tcl_apply of class_expr * (arg_label * expression option) list
| Tcl_let of rec_flag * value_binding list *
(Ident.t * string loc * expression) list * class_expr
| Tcl_constraint of
class_expr * class_type option * string list * string list * Concr.t
| Tcl_open of override_flag * Path.t * Longident.t loc * Env.t * class_expr
and class_structure =
{
cstr_self: pattern;
cstr_fields: class_field list;
cstr_type: Types.class_signature;
cstr_meths: Ident.t Meths.t;
}
and class_field =
{
cf_desc: class_field_desc;
cf_loc: Location.t;
cf_attributes: attributes;
}
and class_field_kind =
| Tcfk_virtual of core_type
| Tcfk_concrete of override_flag * expression
and class_field_desc =
Tcf_inherit of
override_flag * class_expr * string option * (string * Ident.t) list *
(string * Ident.t) list
| Tcf_val of string loc * mutable_flag * Ident.t * class_field_kind * bool
| Tcf_method of string loc * private_flag * class_field_kind
| Tcf_constraint of core_type * core_type
| Tcf_initializer of expression
| Tcf_attribute of attribute
and module_expr =
{ mod_desc: module_expr_desc;
mod_loc: Location.t;
mod_type: Types.module_type;
mod_env: Env.t;
mod_attributes: attributes;
}
and module_type_constraint =
| Tmodtype_implicit
| Tmodtype_explicit of module_type
and module_expr_desc =
Tmod_ident of Path.t * Longident.t loc
| Tmod_structure of structure
| Tmod_functor of Ident.t * string loc * module_type option * module_expr
| Tmod_apply of module_expr * module_expr * module_coercion
| Tmod_constraint of
module_expr * Types.module_type * module_type_constraint * module_coercion
| Tmod_unpack of expression * Types.module_type
and structure = {
str_items : structure_item list;
str_type : Types.signature;
str_final_env : Env.t;
}
and structure_item =
{ str_desc : structure_item_desc;
str_loc : Location.t;
str_env : Env.t
}
and structure_item_desc =
Tstr_eval of expression * attributes
| Tstr_value of rec_flag * value_binding list
| Tstr_primitive of value_description
| Tstr_type of rec_flag * type_declaration list
| Tstr_typext of type_extension
| Tstr_exception of extension_constructor
| Tstr_module of module_binding
| Tstr_recmodule of module_binding list
| Tstr_modtype of module_type_declaration
| Tstr_open of open_description
| Tstr_class of (class_declaration * string list) list
| Tstr_class_type of (Ident.t * string loc * class_type_declaration) list
| Tstr_include of include_declaration
| Tstr_attribute of attribute
and module_binding =
{
mb_id: Ident.t;
mb_name: string loc;
mb_expr: module_expr;
mb_attributes: attributes;
mb_loc: Location.t;
}
and value_binding =
{
vb_pat: pattern;
vb_expr: expression;
vb_attributes: attributes;
vb_loc: Location.t;
}
and module_coercion =
Tcoerce_none
| Tcoerce_structure of (int * module_coercion) list *
(Ident.t * int * module_coercion) list
| Tcoerce_functor of module_coercion * module_coercion
| Tcoerce_primitive of primitive_coercion
| Tcoerce_alias of Path.t * module_coercion
and module_type =
{ mty_desc: module_type_desc;
mty_type : Types.module_type;
mty_env : Env.t;
mty_loc: Location.t;
mty_attributes: attributes;
}
and module_type_desc =
Tmty_ident of Path.t * Longident.t loc
| Tmty_signature of signature
| Tmty_functor of Ident.t * string loc * module_type option * module_type
| Tmty_with of module_type * (Path.t * Longident.t loc * with_constraint) list
| Tmty_typeof of module_expr
| Tmty_alias of Path.t * Longident.t loc
and primitive_coercion =
{
pc_desc: Primitive.description;
pc_type: type_expr;
pc_env: Env.t;
pc_loc : Location.t;
}
and signature = {
sig_items : signature_item list;
sig_type : Types.signature;
sig_final_env : Env.t;
}
and signature_item =
{ sig_desc: signature_item_desc;
sig_loc: Location.t }
and signature_item_desc =
Tsig_value of value_description
| Tsig_type of rec_flag * type_declaration list
| Tsig_typext of type_extension
| Tsig_exception of extension_constructor
| Tsig_module of module_declaration
| Tsig_recmodule of module_declaration list
| Tsig_modtype of module_type_declaration
| Tsig_open of open_description
| Tsig_include of include_description
| Tsig_class of class_description list
| Tsig_class_type of class_type_declaration list
| Tsig_attribute of attribute
and module_declaration =
{
md_id: Ident.t;
md_name: string loc;
md_type: module_type;
md_attributes: attributes;
md_loc: Location.t;
}
and module_type_declaration =
{
mtd_id: Ident.t;
mtd_name: string loc;
mtd_type: module_type option;
mtd_attributes: attributes;
mtd_loc: Location.t;
}
and open_description =
{
open_path: Path.t;
open_txt: Longident.t loc;
open_override: override_flag;
open_loc: Location.t;
open_attributes: attribute list;
}
and 'a include_infos =
{
incl_mod: 'a;
incl_type: Types.signature;
incl_loc: Location.t;
incl_attributes: attribute list;
}
and include_description = module_type include_infos
and include_declaration = module_expr include_infos
and with_constraint =
Twith_type of type_declaration
| Twith_module of Path.t * Longident.t loc
| Twith_typesubst of type_declaration
| Twith_modsubst of Path.t * Longident.t loc
and core_type =
{ mutable ctyp_desc : core_type_desc;
mutable ctyp_type : type_expr;
ctyp_loc : Location.t;
ctyp_attributes: attributes;
}
and core_type_desc =
Ttyp_any
| Ttyp_var of string
| Ttyp_arrow of arg_label * core_type * core_type
| Ttyp_tuple of core_type list
| Ttyp_constr of Path.t * Longident.t loc * core_type list
| Ttyp_object of object_field list * closed_flag
| Ttyp_class of Path.t * Longident.t loc * core_type list
| Ttyp_alias of core_type * string
| Ttyp_variant of row_field list * closed_flag * label list option
| Ttyp_poly of string list * core_type
| Ttyp_package of package_type
and package_type = {
pack_path : Path.t;
pack_fields : (Longident.t loc * core_type) list;
pack_type : Types.module_type;
pack_txt : Longident.t loc;
}
and row_field =
Ttag of string loc * attributes * bool * core_type list
| Tinherit of core_type
and object_field =
| OTtag of string loc * attributes * core_type
| OTinherit of core_type
and value_description =
{ val_id: Ident.t;
val_name: string loc;
val_desc: core_type;
val_val: Types.value_description;
val_prim: string list;
val_loc: Location.t;
val_attributes: attributes;
}
and type_declaration =
{
typ_id: Ident.t;
typ_name: string loc;
typ_params: (core_type * variance) list;
typ_type: Types.type_declaration;
typ_cstrs: (core_type * core_type * Location.t) list;
typ_kind: type_kind;
typ_private: private_flag;
typ_manifest: core_type option;
typ_loc: Location.t;
typ_attributes: attributes;
}
and type_kind =
Ttype_abstract
| Ttype_variant of constructor_declaration list
| Ttype_record of label_declaration list
| Ttype_open
and label_declaration =
{
ld_id: Ident.t;
ld_name: string loc;
ld_mutable: mutable_flag;
ld_type: core_type;
ld_loc: Location.t;
ld_attributes: attributes;
}
and constructor_declaration =
{
cd_id: Ident.t;
cd_name: string loc;
cd_args: constructor_arguments;
cd_res: core_type option;
cd_loc: Location.t;
cd_attributes: attributes;
}
and constructor_arguments =
| Cstr_tuple of core_type list
| Cstr_record of label_declaration list
and type_extension =
{
tyext_path: Path.t;
tyext_txt: Longident.t loc;
tyext_params: (core_type * variance) list;
tyext_constructors: extension_constructor list;
tyext_private: private_flag;
tyext_attributes: attributes;
}
and extension_constructor =
{
ext_id: Ident.t;
ext_name: string loc;
ext_type : Types.extension_constructor;
ext_kind : extension_constructor_kind;
ext_loc : Location.t;
ext_attributes: attributes;
}
and extension_constructor_kind =
Text_decl of constructor_arguments * core_type option
| Text_rebind of Path.t * Longident.t loc
and class_type =
{
cltyp_desc: class_type_desc;
cltyp_type: Types.class_type;
cltyp_env: Env.t;
cltyp_loc: Location.t;
cltyp_attributes: attributes;
}
and class_type_desc =
Tcty_constr of Path.t * Longident.t loc * core_type list
| Tcty_signature of class_signature
| Tcty_arrow of arg_label * core_type * class_type
| Tcty_open of override_flag * Path.t * Longident.t loc * Env.t * class_type
and class_signature = {
csig_self : core_type;
csig_fields : class_type_field list;
csig_type : Types.class_signature;
}
and class_type_field = {
ctf_desc: class_type_field_desc;
ctf_loc: Location.t;
ctf_attributes: attributes;
}
and class_type_field_desc =
| Tctf_inherit of class_type
| Tctf_val of (string * mutable_flag * virtual_flag * core_type)
| Tctf_method of (string * private_flag * virtual_flag * core_type)
| Tctf_constraint of (core_type * core_type)
| Tctf_attribute of attribute
and class_declaration =
class_expr class_infos
and class_description =
class_type class_infos
and class_type_declaration =
class_type class_infos
and 'a class_infos =
{ ci_virt: virtual_flag;
ci_params: (core_type * variance) list;
ci_id_name : string loc;
ci_id_class: Ident.t;
ci_id_class_type : Ident.t;
ci_id_object : Ident.t;
ci_id_typehash : Ident.t;
ci_expr: 'a;
ci_decl: Types.class_declaration;
ci_type_decl : Types.class_type_declaration;
ci_loc: Location.t;
ci_attributes: attributes;
}
val iter_pattern_desc: (pattern -> unit) -> pattern_desc -> unit
val map_pattern_desc: (pattern -> pattern) -> pattern_desc -> pattern_desc
val let_bound_idents: value_binding list -> Ident.t list
val rev_let_bound_idents: value_binding list -> Ident.t list
val let_bound_idents_with_loc:
value_binding list -> (Ident.t * string loc) list
val alpha_pat: (Ident.t * Ident.t) list -> pattern -> pattern
val mknoloc: 'a -> 'a Asttypes.loc
val mkloc: 'a -> Location.t -> 'a Asttypes.loc
val pat_bound_idents: pattern -> Ident.t list
|
58ca6e3a56a13264e3a42016af3d1817f539cf26de8e3172a0450c5800248984 | mars0i/masonclj | GUI.clj | This software is copyright 2016 , 2017 , 2018 , 2019 by ,
and is distributed under the Gnu General Public License version 3.0
;; as specified in the the file LICENSE.
;(set! *warn-on-reflection* true)
(ns example.GUI
(:require [example.Sim :as sim]
[masonclj.properties :as props]
[clojure.math.numeric-tower :as math])
(:import [example snipe Sim]
[sim.engine Steppable]
[sim.field.grid ObjectGrid2D]
[sim.portrayal DrawInfo2D]
[sim.portrayal.grid HexaObjectGridPortrayal2D]
[sim.portrayal.simple CircledPortrayal2D OvalPortrayal2D HexagonalPortrayal2D]
[sim.display Console Display2D]
note syntax for Java static nested class
[java.awt Color])
(:gen-class
:name example.GUI
:extends sim.display.GUIState
:main true
:methods [^:static [getName [] java.lang.String]] ; see comment on the implementation below
accessor for field in superclass that will contain my after main creates instances of this class with it .
:exposes-methods {start superStart,
quit superQuit,
init superInit,
getInspector superGetInspector,
getName superGetName}
:state getUIState
:init init-instance-state))
(declare setup-portrayals setup-display! setup-display-frame! attach-portrayals!)
getName ( ) is static in GUIState . You ca n't actually override a static
;; method, normally, in the sense that the method to run would be chosen
;; at runtime by the actual class used. Rather, with a static method,
;; the declared class of a variable determines at compile time which
method to call . * But * MASON uses reflection to figure out which
;; method to call at runtime. Nevertheless, this means that we need
;; a declaration in :methods, which you would not do for overriding
;; non-static methods from a superclass. Also, the declaration should
;; be declared static using metadata *on the entire declaration vector.
(defn -getName
"`\"Overrides\" the no-arg static getName() method in GUIState, and
returns the name to be displayed on the title bar of the main window."
[]
"masonclj example")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CONFIGURATION AND UTILITY FUNCTIONS
;; display parameters:
(def display-backdrop-color (Color. 200 200 200)) ; border color around hex cells and overall field
(def snipe-size 0.70)
(defn snipe-shade-fn [max-energy snipe] (int (+ 64 (* 190 (/ (:energy snipe) max-energy)))))
(defn snipe-color-fn [max-energy snipe] (Color. 0 0 (snipe-shade-fn max-energy snipe)))
with simple hex portrayals to display grid , organisms off center ; pass this to to correct .
For hex grid , need to rescale display ( based on the MASON example
HexaBugsWithUI.java around line 200 in Mason 19 ) . If you use a
;; rectangular grid, you don't need this.
(defn hex-scale-height
"Calculate visually pleasing height for a hex grid relative to normal
rectangular height."
[height]
(+ 0.5 height))
(defn hex-scale-width
"Calculate visually pleasing width for a hex grid relative to normal
rectangular width."
[width]
(* (/ 2.0 (math/sqrt 3))
(+ 1 (* (- width 1)
(/ 3.0 4.0)))))
(defn -getSimulationInspectedObject
"Override methods in sim.display.GUIState so that GUI can make graphs, etc."
[this]
(.state this))
(defn -getInspector [this]
"This function makes the controls for the sim state in the Model tab
(and does other things?)."
(let [i (.superGetInspector this)]
(.setVolatile i true)
i))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; gen-class instance variable initialization function
(defn -init-instance-state
[& args]
[(vec args) {:display (atom nil) ; will be replaced in init because we need to pass the GUI instance to it
:display-frame (atom nil) ; will be replaced in init because we need to pass the display to it
:snipe-field-portrayal (HexaObjectGridPortrayal2D.) ; hex grid on which snipes move (required)
:hexagonal-bg-field-portrayal (HexaObjectGridPortrayal2D.)}]) ; hex grid for background pattern (not required)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MAIN GUI SETUP ROUTINES
(defn -main
[& args]
(let [sim (Sim. (System/currentTimeMillis))] ; CREATE AN INSTANCE OF my Sim
we can do this in -main because we have a
allow functions in to check whether GUI is running
THIS IS WHAT CONNECTS THE GUI TO my SimState subclass
(defn mein
"Externally available wrapper for -main."
[args]
(apply -main args)) ; have to use apply since already in a seq
(defn -init
"Initialization function caused to be run by MASON SimState class."
fyi controller is called c in Java version
(.superInit this controller)
(let [sim (.getState this)
gui-config (.getUIState this)
sim-data @(.simData sim) ; just for env dimensions
display-size (:env-display-size sim-data)
width (hex-scale-width (int (* display-size (:env-width sim-data))))
height (hex-scale-height (int (* display-size (:env-height sim-data))))
snipe-field-portrayal (:snipe-field-portrayal gui-config)
hexagonal-bg-field-portrayal (:hexagonal-bg-field-portrayal gui-config)
display (setup-display! this width height)
display-frame (setup-display-frame! display controller "Example" true)] ; false supposed to hide it, but fails
(reset! (:display gui-config) display)
(reset! (:display-frame gui-config) display-frame)
;; Attach layers to display; later layers will be on top, and can hide earlier ones:
(attach-portrayals! display [[hexagonal-bg-field-portrayal "bg"] ; background pattern, not required
[snipe-field-portrayal "snipes"]] ; snipes have to be on top
0 0 width height)))
(defn -start
"Function run by pause and go buttons when starting from fully stopped state."
[this-gui]
this will call start ( ) on the sim , i.e. in our SimState object
(setup-portrayals this-gui))
(defn attach-portrayals!
"Attach field-portrayals in portrayals-with-labels to display with upper left corner
at x y in display and with width and height. Order of portrayals determines
how they are layered, with earlier portrayals under later ones."
[display portrayals-with-labels x y field-width field-height]
(doseq [[portrayal label] portrayals-with-labels]
(.attach display portrayal label
note Clojure $ syntax for Java static nested classes
(defn setup-portrayals
"Set up MASON 'portrayals' of agents and background fields. That is, associate
with a given entity one or more Java classes that will determine appearances in
the GUI. Usually called from start."
[this-gui] ; instead of 'this': avoid confusion with e.g. proxy below
first get global configuration objects and such :
(let [sim (.getState this-gui)
provided by MASON
sim-data$ (.simData sim) ; configuration data defined by masonclj.params/defparams
sim-data @sim-data$
a MersenneTwisterFast PRNG provided by MASON
popenv (:popenv sim-data) ; In the pasta model this is more complicated
env (:env popenv)
max-energy (:max-energy sim-data)
display @(:display gui-config)
hexagonal-bg-field-portrayal (:hexagonal-bg-field-portrayal gui-config)
Set up the appearance of with a main portrayal inside one
;; that can display a circle around it:
snipe-portrayal (props/make-fnl-circled-portrayal Color/blue
(proxy [OvalPortrayal2D][snipe-size]
(draw [snipe graphics info]
(set! (.-paint this) (snipe-color-fn max-energy snipe)) ; paint var is in superclass
(proxy-super draw snipe graphics (DrawInfo2D. info (* 0.75 org-offset) (* 0.55 org-offset)))))) ; center in cell
snipe-field-portrayal (:snipe-field-portrayal gui-config)] ; appearance of the field on which snipes run around
(.setField hexagonal-bg-field-portrayal (ObjectGrid2D. (:env-width sim-data) (:env-height sim-data))) ; dimensions of background grid
(.setField snipe-field-portrayal (:snipe-field env))
(.setPortrayalForNull hexagonal-bg-field-portrayal (HexagonalPortrayal2D. (Color. 255 255 255) 0.90)) ; show patches at smaller size so borders show
(.setPortrayalForClass snipe-field-portrayal example.snipe.Snipe snipe-portrayal)
(.scheduleRepeatingImmediatelyAfter this-gui ; this stuff is going to happen on every timestep as a result:
(reify Steppable
(step [this sim-state]
(let [{:keys [env]} (:popenv @sim-data$)]
(.setField snipe-field-portrayal (:snipe-field env))))))
;; set up display:
(doto display
(.reset)
(.setBackdrop display-backdrop-color) ; bottom level color--will show through around hexagaons
(.repaint))))
(defn setup-display!
"Creates and configures a MASON display object and returns it. Usually
called from init."
[gui width height]
(let [display (Display2D. width height gui)]
(.setClipping display false)
display))
(defn setup-display-frame!
"Creates and configures a MASON display-frame and returns it. Usually
called from init."
[display controller title visible?]
(let [display-frame (.createFrame display)]
(.registerFrame controller display-frame)
(.setTitle display-frame title)
(.setVisible display-frame visible?)
display-frame))
(defn -quit
"Cleans up state before exiting model."
[this]
(.superQuit this)
(let [gui-config (.getUIState this)
display (:display gui-config)
display-frame (:display-frame gui-config)
sim (.getState this)
sim-data$ (.simData sim)]
(when display-frame (.dispose display-frame))
(reset! (:display gui-config) nil)
(reset! (:display-frame gui-config) nil)))
;; Try this:
;; (let [snipes (.elements (:snipe-field (:popenv @sim-data$))) N (count snipes) energies (map :energy snipes)] [N (/ (apply + energies) N)])
(defn repl-gui
"Convenience function to init and start GUI from the REPL.
Returns the new Sim object. Usage e.g.:
(use 'example.GUI)
(let [[sim gui] (repl-gui)] (def sim sim) (def gui gui)) ; considered bad practice--but convenient in this case
(def data$ (.simData sim))"
[]
(let [sim (Sim. (System/currentTimeMillis))
gui (example.GUI. sim)]
(.setVisible (Console. gui) true)
[sim gui]))
(defmacro repl-gui-with-defs
"Calls repl-gui to start the GUI, then creates top-level definitions:
sim as an example.Sim (i.e. a SimState), gui as an example.GUI
(i.e. a GUIState) that references sim, and data$ as an atom containing
sim's SimData stru."
[]
(let [[sim gui] (repl-gui)]
(def sim sim)
(def gui gui))
(def data$ (.simData sim))
(println "sim is defined as a Sim (i.e. a SimState)")
(println "gui is defined as a GUI (i.e. a GUIState)")
(println "data$ is defined as an atom containing cfg's SimData stru."))
| null | https://raw.githubusercontent.com/mars0i/masonclj/c5ff56c54749832b4c0a390332154072755e7bf0/example/src/example/GUI.clj | clojure | as specified in the the file LICENSE.
(set! *warn-on-reflection* true)
see comment on the implementation below
method, normally, in the sense that the method to run would be chosen
at runtime by the actual class used. Rather, with a static method,
the declared class of a variable determines at compile time which
method to call at runtime. Nevertheless, this means that we need
a declaration in :methods, which you would not do for overriding
non-static methods from a superclass. Also, the declaration should
be declared static using metadata *on the entire declaration vector.
CONFIGURATION AND UTILITY FUNCTIONS
display parameters:
border color around hex cells and overall field
pass this to to correct .
rectangular grid, you don't need this.
gen-class instance variable initialization function
will be replaced in init because we need to pass the GUI instance to it
will be replaced in init because we need to pass the display to it
hex grid on which snipes move (required)
hex grid for background pattern (not required)
CREATE AN INSTANCE OF my Sim
have to use apply since already in a seq
just for env dimensions
false supposed to hide it, but fails
Attach layers to display; later layers will be on top, and can hide earlier ones:
background pattern, not required
snipes have to be on top
instead of 'this': avoid confusion with e.g. proxy below
configuration data defined by masonclj.params/defparams
In the pasta model this is more complicated
that can display a circle around it:
paint var is in superclass
center in cell
appearance of the field on which snipes run around
dimensions of background grid
show patches at smaller size so borders show
this stuff is going to happen on every timestep as a result:
set up display:
bottom level color--will show through around hexagaons
Try this:
(let [snipes (.elements (:snipe-field (:popenv @sim-data$))) N (count snipes) energies (map :energy snipes)] [N (/ (apply + energies) N)])
considered bad practice--but convenient in this case | This software is copyright 2016 , 2017 , 2018 , 2019 by ,
and is distributed under the Gnu General Public License version 3.0
(ns example.GUI
(:require [example.Sim :as sim]
[masonclj.properties :as props]
[clojure.math.numeric-tower :as math])
(:import [example snipe Sim]
[sim.engine Steppable]
[sim.field.grid ObjectGrid2D]
[sim.portrayal DrawInfo2D]
[sim.portrayal.grid HexaObjectGridPortrayal2D]
[sim.portrayal.simple CircledPortrayal2D OvalPortrayal2D HexagonalPortrayal2D]
[sim.display Console Display2D]
note syntax for Java static nested class
[java.awt Color])
(:gen-class
:name example.GUI
:extends sim.display.GUIState
:main true
accessor for field in superclass that will contain my after main creates instances of this class with it .
:exposes-methods {start superStart,
quit superQuit,
init superInit,
getInspector superGetInspector,
getName superGetName}
:state getUIState
:init init-instance-state))
(declare setup-portrayals setup-display! setup-display-frame! attach-portrayals!)
getName ( ) is static in GUIState . You ca n't actually override a static
method to call . * But * MASON uses reflection to figure out which
(defn -getName
"`\"Overrides\" the no-arg static getName() method in GUIState, and
returns the name to be displayed on the title bar of the main window."
[]
"masonclj example")
(def snipe-size 0.70)
(defn snipe-shade-fn [max-energy snipe] (int (+ 64 (* 190 (/ (:energy snipe) max-energy)))))
(defn snipe-color-fn [max-energy snipe] (Color. 0 0 (snipe-shade-fn max-energy snipe)))
For hex grid , need to rescale display ( based on the MASON example
HexaBugsWithUI.java around line 200 in Mason 19 ) . If you use a
(defn hex-scale-height
"Calculate visually pleasing height for a hex grid relative to normal
rectangular height."
[height]
(+ 0.5 height))
(defn hex-scale-width
"Calculate visually pleasing width for a hex grid relative to normal
rectangular width."
[width]
(* (/ 2.0 (math/sqrt 3))
(+ 1 (* (- width 1)
(/ 3.0 4.0)))))
(defn -getSimulationInspectedObject
"Override methods in sim.display.GUIState so that GUI can make graphs, etc."
[this]
(.state this))
(defn -getInspector [this]
"This function makes the controls for the sim state in the Model tab
(and does other things?)."
(let [i (.superGetInspector this)]
(.setVolatile i true)
i))
(defn -init-instance-state
[& args]
MAIN GUI SETUP ROUTINES
(defn -main
[& args]
we can do this in -main because we have a
allow functions in to check whether GUI is running
THIS IS WHAT CONNECTS THE GUI TO my SimState subclass
(defn mein
"Externally available wrapper for -main."
[args]
(defn -init
"Initialization function caused to be run by MASON SimState class."
fyi controller is called c in Java version
(.superInit this controller)
(let [sim (.getState this)
gui-config (.getUIState this)
display-size (:env-display-size sim-data)
width (hex-scale-width (int (* display-size (:env-width sim-data))))
height (hex-scale-height (int (* display-size (:env-height sim-data))))
snipe-field-portrayal (:snipe-field-portrayal gui-config)
hexagonal-bg-field-portrayal (:hexagonal-bg-field-portrayal gui-config)
display (setup-display! this width height)
(reset! (:display gui-config) display)
(reset! (:display-frame gui-config) display-frame)
0 0 width height)))
(defn -start
"Function run by pause and go buttons when starting from fully stopped state."
[this-gui]
this will call start ( ) on the sim , i.e. in our SimState object
(setup-portrayals this-gui))
(defn attach-portrayals!
"Attach field-portrayals in portrayals-with-labels to display with upper left corner
at x y in display and with width and height. Order of portrayals determines
how they are layered, with earlier portrayals under later ones."
[display portrayals-with-labels x y field-width field-height]
(doseq [[portrayal label] portrayals-with-labels]
(.attach display portrayal label
note Clojure $ syntax for Java static nested classes
(defn setup-portrayals
"Set up MASON 'portrayals' of agents and background fields. That is, associate
with a given entity one or more Java classes that will determine appearances in
the GUI. Usually called from start."
first get global configuration objects and such :
(let [sim (.getState this-gui)
provided by MASON
sim-data @sim-data$
a MersenneTwisterFast PRNG provided by MASON
env (:env popenv)
max-energy (:max-energy sim-data)
display @(:display gui-config)
hexagonal-bg-field-portrayal (:hexagonal-bg-field-portrayal gui-config)
Set up the appearance of with a main portrayal inside one
snipe-portrayal (props/make-fnl-circled-portrayal Color/blue
(proxy [OvalPortrayal2D][snipe-size]
(draw [snipe graphics info]
(.setField snipe-field-portrayal (:snipe-field env))
(.setPortrayalForClass snipe-field-portrayal example.snipe.Snipe snipe-portrayal)
(reify Steppable
(step [this sim-state]
(let [{:keys [env]} (:popenv @sim-data$)]
(.setField snipe-field-portrayal (:snipe-field env))))))
(doto display
(.reset)
(.repaint))))
(defn setup-display!
"Creates and configures a MASON display object and returns it. Usually
called from init."
[gui width height]
(let [display (Display2D. width height gui)]
(.setClipping display false)
display))
(defn setup-display-frame!
"Creates and configures a MASON display-frame and returns it. Usually
called from init."
[display controller title visible?]
(let [display-frame (.createFrame display)]
(.registerFrame controller display-frame)
(.setTitle display-frame title)
(.setVisible display-frame visible?)
display-frame))
(defn -quit
"Cleans up state before exiting model."
[this]
(.superQuit this)
(let [gui-config (.getUIState this)
display (:display gui-config)
display-frame (:display-frame gui-config)
sim (.getState this)
sim-data$ (.simData sim)]
(when display-frame (.dispose display-frame))
(reset! (:display gui-config) nil)
(reset! (:display-frame gui-config) nil)))
(defn repl-gui
"Convenience function to init and start GUI from the REPL.
Returns the new Sim object. Usage e.g.:
(use 'example.GUI)
(def data$ (.simData sim))"
[]
(let [sim (Sim. (System/currentTimeMillis))
gui (example.GUI. sim)]
(.setVisible (Console. gui) true)
[sim gui]))
(defmacro repl-gui-with-defs
"Calls repl-gui to start the GUI, then creates top-level definitions:
sim as an example.Sim (i.e. a SimState), gui as an example.GUI
(i.e. a GUIState) that references sim, and data$ as an atom containing
sim's SimData stru."
[]
(let [[sim gui] (repl-gui)]
(def sim sim)
(def gui gui))
(def data$ (.simData sim))
(println "sim is defined as a Sim (i.e. a SimState)")
(println "gui is defined as a GUI (i.e. a GUIState)")
(println "data$ is defined as an atom containing cfg's SimData stru."))
|
395b6970c830911b53e85f4e9498666e76c392fe3048572b2f962754e993054e | tolysz/prepare-ghcjs | PSQ.hs | # LANGUAGE Trustworthy #
# LANGUAGE BangPatterns , NoImplicitPrelude #
Copyright ( c ) 2008 ,
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- * Redistributions of source code must retain the above
-- copyright notice, this list of conditions and the following
-- disclaimer.
--
-- * Redistributions in binary form must reproduce the above
-- copyright notice, this list of conditions and the following
-- disclaimer in the documentation and/or other materials
-- provided with the distribution.
--
-- * The names of the contributors may not be used to endorse or
-- promote products derived from this software without specific
-- prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
-- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-- OF THE POSSIBILITY OF SUCH DAMAGE.
| A /priority search queue/ ( henceforth /queue/ ) efficiently
-- supports the operations of both a search tree and a priority queue.
-- An 'Elem'ent is a product of a key, a priority, and a
-- value. Elements can be inserted, deleted, modified and queried in
-- logarithmic time, and the element with the least priority can be
-- retrieved in constant time. A queue can be built from a list of
-- elements, sorted by keys, in linear time.
--
This implementation is due to with some modifications by
and .
--
* , R. , /A Simple Implementation Technique for Priority Search
Queues/ , ICFP 2001 , pp . 110 - 121
--
-- <>
module GHC.Event.PSQ
(
-- * Binding Type
Elem(..)
, Key
, Prio
-- * Priority Search Queue Type
, PSQ
-- * Query
, size
, null
, lookup
-- * Construction
, empty
, singleton
-- * Insertion
, insert
-- * Delete/Update
, delete
, adjust
-- * Conversion
, toList
, toAscList
, toDescList
, fromList
*
, findMin
, deleteMin
, minView
, atMost
) where
import GHC.Base hiding (empty)
import GHC.Num (Num(..))
import GHC.Show (Show(showsPrec))
import GHC.Event.Unique (Unique)
-- | @E k p@ binds the key @k@ with the priority @p@.
data Elem a = E
{ key :: {-# UNPACK #-} !Key
, prio :: {-# UNPACK #-} !Prio
, value :: a
} deriving (Eq, Show)
------------------------------------------------------------------------
| A mapping from keys @k@ to priorites @p@.
type Prio = Double
type Key = Unique
data PSQ a = Void
| Winner {-# UNPACK #-} !(Elem a)
!(LTree a)
{-# UNPACK #-} !Key -- max key
deriving (Eq, Show)
-- | /O(1)/ The number of elements in a queue.
size :: PSQ a -> Int
size Void = 0
size (Winner _ lt _) = 1 + size' lt
-- | /O(1)/ True if the queue is empty.
null :: PSQ a -> Bool
null Void = True
null (Winner _ _ _) = False
| /O(log n)/ The priority and value of a given key , or Nothing if
-- the key is not bound.
lookup :: Key -> PSQ a -> Maybe (Prio, a)
lookup k q = case tourView q of
Null -> Nothing
Single (E k' p v)
| k == k' -> Just (p, v)
| otherwise -> Nothing
tl `Play` tr
| k <= maxKey tl -> lookup k tl
| otherwise -> lookup k tr
------------------------------------------------------------------------
-- Construction
empty :: PSQ a
empty = Void
| /O(1)/ Build a queue with one element .
singleton :: Key -> Prio -> a -> PSQ a
singleton k p v = Winner (E k p v) Start k
------------------------------------------------------------------------
-- Insertion
| /O(log n)/ Insert a new key , priority and value in the queue . If
-- the key is already present in the queue, the associated priority
-- and value are replaced with the supplied priority and value.
insert :: Key -> Prio -> a -> PSQ a -> PSQ a
insert k p v q = case q of
Void -> singleton k p v
Winner (E k' p' v') Start _ -> case compare k k' of
LT -> singleton k p v `play` singleton k' p' v'
EQ -> singleton k p v
GT -> singleton k' p' v' `play` singleton k p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m')
------------------------------------------------------------------------
-- Delete/Update
| /O(log n)/ Delete a key and its priority and value from the
-- queue. When the key is not a member of the queue, the original
-- queue is returned.
delete :: Key -> PSQ a -> PSQ a
delete k q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> empty
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m')
| /O(log n)/ Update a priority at a specific key with the result
-- of the provided function. When the key is not a member of the
-- queue, the original queue is returned.
adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a
adjust f k q0 = go q0
where
go q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> singleton k' (f p) v
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> go (Winner e tl m) `unsafePlay` (Winner e' tr m')
| otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> go (Winner e' tl m) `unsafePlay` (Winner e tr m')
| otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m')
# INLINE adjust #
------------------------------------------------------------------------
-- Conversion
| /O(n*log n)/ Build a queue from a list of key / priority / value
tuples . If the list contains more than one priority and value for
-- the same key, the last priority and value for the key is retained.
fromList :: [Elem a] -> PSQ a
fromList = foldr (\(E k p v) q -> insert k p v q) empty
-- | /O(n)/ Convert to a list of key/priority/value tuples.
toList :: PSQ a -> [Elem a]
toList = toAscList
-- | /O(n)/ Convert to an ascending list.
toAscList :: PSQ a -> [Elem a]
toAscList q = seqToList (toAscLists q)
toAscLists :: PSQ a -> Sequ (Elem a)
toAscLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toAscLists tl <> toAscLists tr
-- | /O(n)/ Convert to a descending list.
toDescList :: PSQ a -> [ Elem a ]
toDescList q = seqToList (toDescLists q)
toDescLists :: PSQ a -> Sequ (Elem a)
toDescLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toDescLists tr <> toDescLists tl
------------------------------------------------------------------------
-- Min
-- | /O(1)/ The element with the lowest priority.
findMin :: PSQ a -> Maybe (Elem a)
findMin Void = Nothing
findMin (Winner e _ _) = Just e
| /O(log n)/ Delete the element with the lowest priority . Returns
-- an empty queue if the queue is empty.
deleteMin :: PSQ a -> PSQ a
deleteMin Void = Void
deleteMin (Winner _ t m) = secondBest t m
| /O(log n)/ Retrieve the binding with the least priority , and the
-- rest of the queue stripped of that binding.
minView :: PSQ a -> Maybe (Elem a, PSQ a)
minView Void = Nothing
minView (Winner e t m) = Just (e, secondBest t m)
secondBest :: LTree a -> Key -> PSQ a
secondBest Start _ = Void
secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m'
secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m'
-- | /O(r*(log n - log r))/ Return a list of elements ordered by
key whose priorities are at most @pt@.
atMost :: Prio -> PSQ a -> ([Elem a], PSQ a)
atMost pt q = let (sequ, q') = atMosts pt q
in (seqToList sequ, q')
atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a)
atMosts !pt q = case q of
(Winner e _ _)
| prio e > pt -> (emptySequ, q)
Void -> (emptySequ, Void)
Winner e Start _ -> (singleSequ e, Void)
Winner e (RLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e tl m)
(sequ', q'') = atMosts pt (Winner e' tr m')
in (sequ <> sequ', q' `play` q'')
Winner e (LLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e' tl m)
(sequ', q'') = atMosts pt (Winner e tr m')
in (sequ <> sequ', q' `play` q'')
------------------------------------------------------------------------
-- Loser tree
type Size = Int
data LTree a = Start
| LLoser {-# UNPACK #-} !Size
{-# UNPACK #-} !(Elem a)
!(LTree a)
{-# UNPACK #-} !Key -- split key
!(LTree a)
| RLoser {-# UNPACK #-} !Size
{-# UNPACK #-} !(Elem a)
!(LTree a)
{-# UNPACK #-} !Key -- split key
!(LTree a)
deriving (Eq, Show)
size' :: LTree a -> Size
size' Start = 0
size' (LLoser s _ _ _ _) = s
size' (RLoser s _ _ _ _) = s
left, right :: LTree a -> LTree a
left Start = moduleError "left" "empty loser tree"
left (LLoser _ _ tl _ _ ) = tl
left (RLoser _ _ tl _ _ ) = tl
right Start = moduleError "right" "empty loser tree"
right (LLoser _ _ _ _ tr) = tr
right (RLoser _ _ _ _ tr) = tr
maxKey :: PSQ a -> Key
maxKey Void = moduleError "maxKey" "empty queue"
maxKey (Winner _ _ m) = m
lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr
rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr
------------------------------------------------------------------------
-- Balancing
-- | Balance factor
omega :: Int
omega = 4
lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalance k p v l m r
| size' l + size' r < 2 = lloser k p v l m r
| size' r > omega * size' l = lbalanceLeft k p v l m r
| size' l > omega * size' r = lbalanceRight k p v l m r
| otherwise = lloser k p v l m r
rbalance k p v l m r
| size' l + size' r < 2 = rloser k p v l m r
| size' r > omega * size' l = rbalanceLeft k p v l m r
| size' l > omega * size' r = rbalanceRight k p v l m r
| otherwise = rloser k p v l m r
lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceLeft k p v l m r
| size' (left r) < size' (right r) = lsingleLeft k p v l m r
| otherwise = ldoubleLeft k p v l m r
lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceRight k p v l m r
| size' (left l) > size' (right l) = lsingleRight k p v l m r
| otherwise = ldoubleRight k p v l m r
rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceLeft k p v l m r
| size' (left r) < size' (right r) = rsingleLeft k p v l m r
| otherwise = rdoubleLeft k p v l m r
rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceRight k p v l m r
| size' (left l) > size' (right l) = rsingleRight k p v l m r
| otherwise = rdoubleRight k p v l m r
lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3)
| p1 <= p2 = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
| otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree"
rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3
rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree"
lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3)
lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree"
rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3
| p1 <= p2 = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
| otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree"
ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree"
ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree"
rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree"
rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree"
| Take two pennants and returns a new pennant that is the union of
the two with the precondition that the keys in the first tree are
strictly smaller than the keys in the second tree .
play :: PSQ a -> PSQ a -> PSQ a
Void `play` t' = t'
t `play` Void = t
Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rbalance k' p' v' t m t') m'
| otherwise = Winner e' (lbalance k p v t m t') m'
# INLINE play #
-- | A version of 'play' that can be used if the shape of the tree has
-- not changed or if the tree is known to be balanced.
unsafePlay :: PSQ a -> PSQ a -> PSQ a
Void `unsafePlay` t' = t'
t `unsafePlay` Void = t
Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rloser k' p' v' t m t') m'
| otherwise = Winner e' (lloser k p v t m t') m'
# INLINE unsafePlay #
data TourView a = Null
| Single {-# UNPACK #-} !(Elem a)
| (PSQ a) `Play` (PSQ a)
tourView :: PSQ a -> TourView a
tourView Void = Null
tourView (Winner e Start _) = Single e
tourView (Winner e (RLoser _ e' tl m tr) m') =
Winner e tl m `Play` Winner e' tr m'
tourView (Winner e (LLoser _ e' tl m tr) m') =
Winner e' tl m `Play` Winner e tr m'
------------------------------------------------------------------------
-- Utility functions
moduleError :: String -> String -> a
moduleError fun msg = errorWithoutStackTrace ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg)
# NOINLINE moduleError #
------------------------------------------------------------------------
Hughes 's efficient sequence type
newtype Sequ a = Sequ ([a] -> [a])
emptySequ :: Sequ a
emptySequ = Sequ (\as -> as)
singleSequ :: a -> Sequ a
singleSequ a = Sequ (\as -> a : as)
(<>) :: Sequ a -> Sequ a -> Sequ a
Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as))
infixr 5 <>
seqToList :: Sequ a -> [a]
seqToList (Sequ x) = x []
instance Show a => Show (Sequ a) where
showsPrec d a = showsPrec d (seqToList a)
| null | https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts8/base/GHC/Event/PSQ.hs | haskell | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
* The names of the contributors may not be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
supports the operations of both a search tree and a priority queue.
An 'Elem'ent is a product of a key, a priority, and a
value. Elements can be inserted, deleted, modified and queried in
logarithmic time, and the element with the least priority can be
retrieved in constant time. A queue can be built from a list of
elements, sorted by keys, in linear time.
<>
* Binding Type
* Priority Search Queue Type
* Query
* Construction
* Insertion
* Delete/Update
* Conversion
| @E k p@ binds the key @k@ with the priority @p@.
# UNPACK #
# UNPACK #
----------------------------------------------------------------------
# UNPACK #
# UNPACK #
max key
| /O(1)/ The number of elements in a queue.
| /O(1)/ True if the queue is empty.
the key is not bound.
----------------------------------------------------------------------
Construction
----------------------------------------------------------------------
Insertion
the key is already present in the queue, the associated priority
and value are replaced with the supplied priority and value.
----------------------------------------------------------------------
Delete/Update
queue. When the key is not a member of the queue, the original
queue is returned.
of the provided function. When the key is not a member of the
queue, the original queue is returned.
----------------------------------------------------------------------
Conversion
the same key, the last priority and value for the key is retained.
| /O(n)/ Convert to a list of key/priority/value tuples.
| /O(n)/ Convert to an ascending list.
| /O(n)/ Convert to a descending list.
----------------------------------------------------------------------
Min
| /O(1)/ The element with the lowest priority.
an empty queue if the queue is empty.
rest of the queue stripped of that binding.
| /O(r*(log n - log r))/ Return a list of elements ordered by
----------------------------------------------------------------------
Loser tree
# UNPACK #
# UNPACK #
# UNPACK #
split key
# UNPACK #
# UNPACK #
# UNPACK #
split key
----------------------------------------------------------------------
Balancing
| Balance factor
| A version of 'play' that can be used if the shape of the tree has
not changed or if the tree is known to be balanced.
# UNPACK #
----------------------------------------------------------------------
Utility functions
---------------------------------------------------------------------- | # LANGUAGE Trustworthy #
# LANGUAGE BangPatterns , NoImplicitPrelude #
Copyright ( c ) 2008 ,
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT OWNER OR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
| A /priority search queue/ ( henceforth /queue/ ) efficiently
This implementation is due to with some modifications by
and .
* , R. , /A Simple Implementation Technique for Priority Search
Queues/ , ICFP 2001 , pp . 110 - 121
module GHC.Event.PSQ
(
Elem(..)
, Key
, Prio
, PSQ
, size
, null
, lookup
, empty
, singleton
, insert
, delete
, adjust
, toList
, toAscList
, toDescList
, fromList
*
, findMin
, deleteMin
, minView
, atMost
) where
import GHC.Base hiding (empty)
import GHC.Num (Num(..))
import GHC.Show (Show(showsPrec))
import GHC.Event.Unique (Unique)
data Elem a = E
, value :: a
} deriving (Eq, Show)
| A mapping from keys @k@ to priorites @p@.
type Prio = Double
type Key = Unique
data PSQ a = Void
!(LTree a)
deriving (Eq, Show)
size :: PSQ a -> Int
size Void = 0
size (Winner _ lt _) = 1 + size' lt
null :: PSQ a -> Bool
null Void = True
null (Winner _ _ _) = False
| /O(log n)/ The priority and value of a given key , or Nothing if
lookup :: Key -> PSQ a -> Maybe (Prio, a)
lookup k q = case tourView q of
Null -> Nothing
Single (E k' p v)
| k == k' -> Just (p, v)
| otherwise -> Nothing
tl `Play` tr
| k <= maxKey tl -> lookup k tl
| otherwise -> lookup k tr
empty :: PSQ a
empty = Void
| /O(1)/ Build a queue with one element .
singleton :: Key -> Prio -> a -> PSQ a
singleton k p v = Winner (E k p v) Start k
| /O(log n)/ Insert a new key , priority and value in the queue . If
insert :: Key -> Prio -> a -> PSQ a -> PSQ a
insert k p v q = case q of
Void -> singleton k p v
Winner (E k' p' v') Start _ -> case compare k k' of
LT -> singleton k p v `play` singleton k' p' v'
EQ -> singleton k p v
GT -> singleton k' p' v' `play` singleton k p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m')
| /O(log n)/ Delete a key and its priority and value from the
delete :: Key -> PSQ a -> PSQ a
delete k q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> empty
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m')
| /O(log n)/ Update a priority at a specific key with the result
adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a
adjust f k q0 = go q0
where
go q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> singleton k' (f p) v
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> go (Winner e tl m) `unsafePlay` (Winner e' tr m')
| otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> go (Winner e' tl m) `unsafePlay` (Winner e tr m')
| otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m')
# INLINE adjust #
| /O(n*log n)/ Build a queue from a list of key / priority / value
tuples . If the list contains more than one priority and value for
fromList :: [Elem a] -> PSQ a
fromList = foldr (\(E k p v) q -> insert k p v q) empty
toList :: PSQ a -> [Elem a]
toList = toAscList
toAscList :: PSQ a -> [Elem a]
toAscList q = seqToList (toAscLists q)
toAscLists :: PSQ a -> Sequ (Elem a)
toAscLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toAscLists tl <> toAscLists tr
toDescList :: PSQ a -> [ Elem a ]
toDescList q = seqToList (toDescLists q)
toDescLists :: PSQ a -> Sequ (Elem a)
toDescLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toDescLists tr <> toDescLists tl
findMin :: PSQ a -> Maybe (Elem a)
findMin Void = Nothing
findMin (Winner e _ _) = Just e
| /O(log n)/ Delete the element with the lowest priority . Returns
deleteMin :: PSQ a -> PSQ a
deleteMin Void = Void
deleteMin (Winner _ t m) = secondBest t m
| /O(log n)/ Retrieve the binding with the least priority , and the
minView :: PSQ a -> Maybe (Elem a, PSQ a)
minView Void = Nothing
minView (Winner e t m) = Just (e, secondBest t m)
secondBest :: LTree a -> Key -> PSQ a
secondBest Start _ = Void
secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m'
secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m'
key whose priorities are at most @pt@.
atMost :: Prio -> PSQ a -> ([Elem a], PSQ a)
atMost pt q = let (sequ, q') = atMosts pt q
in (seqToList sequ, q')
atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a)
atMosts !pt q = case q of
(Winner e _ _)
| prio e > pt -> (emptySequ, q)
Void -> (emptySequ, Void)
Winner e Start _ -> (singleSequ e, Void)
Winner e (RLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e tl m)
(sequ', q'') = atMosts pt (Winner e' tr m')
in (sequ <> sequ', q' `play` q'')
Winner e (LLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e' tl m)
(sequ', q'') = atMosts pt (Winner e tr m')
in (sequ <> sequ', q' `play` q'')
type Size = Int
data LTree a = Start
!(LTree a)
!(LTree a)
!(LTree a)
!(LTree a)
deriving (Eq, Show)
size' :: LTree a -> Size
size' Start = 0
size' (LLoser s _ _ _ _) = s
size' (RLoser s _ _ _ _) = s
left, right :: LTree a -> LTree a
left Start = moduleError "left" "empty loser tree"
left (LLoser _ _ tl _ _ ) = tl
left (RLoser _ _ tl _ _ ) = tl
right Start = moduleError "right" "empty loser tree"
right (LLoser _ _ _ _ tr) = tr
right (RLoser _ _ _ _ tr) = tr
maxKey :: PSQ a -> Key
maxKey Void = moduleError "maxKey" "empty queue"
maxKey (Winner _ _ m) = m
lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr
rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr
omega :: Int
omega = 4
lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalance k p v l m r
| size' l + size' r < 2 = lloser k p v l m r
| size' r > omega * size' l = lbalanceLeft k p v l m r
| size' l > omega * size' r = lbalanceRight k p v l m r
| otherwise = lloser k p v l m r
rbalance k p v l m r
| size' l + size' r < 2 = rloser k p v l m r
| size' r > omega * size' l = rbalanceLeft k p v l m r
| size' l > omega * size' r = rbalanceRight k p v l m r
| otherwise = rloser k p v l m r
lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceLeft k p v l m r
| size' (left r) < size' (right r) = lsingleLeft k p v l m r
| otherwise = ldoubleLeft k p v l m r
lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceRight k p v l m r
| size' (left l) > size' (right l) = lsingleRight k p v l m r
| otherwise = ldoubleRight k p v l m r
rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceLeft k p v l m r
| size' (left r) < size' (right r) = rsingleLeft k p v l m r
| otherwise = rdoubleLeft k p v l m r
rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceRight k p v l m r
| size' (left l) > size' (right l) = rsingleRight k p v l m r
| otherwise = rdoubleRight k p v l m r
lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3)
| p1 <= p2 = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
| otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree"
rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3
rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree"
lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3)
lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree"
rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3
| p1 <= p2 = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
| otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree"
ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree"
ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree"
rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree"
rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree"
| Take two pennants and returns a new pennant that is the union of
the two with the precondition that the keys in the first tree are
strictly smaller than the keys in the second tree .
play :: PSQ a -> PSQ a -> PSQ a
Void `play` t' = t'
t `play` Void = t
Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rbalance k' p' v' t m t') m'
| otherwise = Winner e' (lbalance k p v t m t') m'
# INLINE play #
unsafePlay :: PSQ a -> PSQ a -> PSQ a
Void `unsafePlay` t' = t'
t `unsafePlay` Void = t
Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rloser k' p' v' t m t') m'
| otherwise = Winner e' (lloser k p v t m t') m'
# INLINE unsafePlay #
data TourView a = Null
| (PSQ a) `Play` (PSQ a)
tourView :: PSQ a -> TourView a
tourView Void = Null
tourView (Winner e Start _) = Single e
tourView (Winner e (RLoser _ e' tl m tr) m') =
Winner e tl m `Play` Winner e' tr m'
tourView (Winner e (LLoser _ e' tl m tr) m') =
Winner e' tl m `Play` Winner e tr m'
moduleError :: String -> String -> a
moduleError fun msg = errorWithoutStackTrace ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg)
# NOINLINE moduleError #
Hughes 's efficient sequence type
newtype Sequ a = Sequ ([a] -> [a])
emptySequ :: Sequ a
emptySequ = Sequ (\as -> as)
singleSequ :: a -> Sequ a
singleSequ a = Sequ (\as -> a : as)
(<>) :: Sequ a -> Sequ a -> Sequ a
Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as))
infixr 5 <>
seqToList :: Sequ a -> [a]
seqToList (Sequ x) = x []
instance Show a => Show (Sequ a) where
showsPrec d a = showsPrec d (seqToList a)
|
f13991b7a8abfe0d4948124047eaea8a64dbe3845d86311be87ddb8bab94a94f | wireless-net/erlang-nommu | ssh_unicode_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2005 - 2014 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online 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.
%%
%% %CopyrightEnd%
%%
%% gerl +fnu
ct : run_test([{suite,"ssh_unicode_SUITE " } , { " } ] ) .
-module(ssh_unicode_SUITE).
%% Note: This directive should only be used in test suites.
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("kernel/include/file.hrl").
% Default timetrap timeout
-define(default_timeout, ?t:minutes(1)).
-define(USER, "åke高兴").
-define(PASSWD, "ärlig日本じん").
-define('sftp.txt', "sftp瑞点.txt").
-define('test.txt', "testハンス.txt").
-define('link_test.txt', "link_test語.txt").
-define(bindata, unicode:characters_to_binary("foobar å 一二三四いちにさんち") ).
-define(NEWLINE, <<"\r\n">>).
%%--------------------------------------------------------------------
%% Common Test interface functions -----------------------------------
%%--------------------------------------------------------------------
%% suite() ->
%% [{ct_hooks,[ts_install_cth]}].
all() ->
[{group, sftp},
{group, shell}
].
init_per_suite(Config) ->
case {file:native_name_encoding(), (catch crypto:start())} of
{utf8, ok} ->
ssh:start(),
Config;
{utf8, _} ->
{skip,"Could not start crypto!"};
_ ->
{skip,"Not unicode filename enabled emulator"}
end.
end_per_suite(Config) ->
ssh:stop(),
crypto:stop(),
Config.
%%--------------------------------------------------------------------
groups() ->
[{shell, [], [shell_no_unicode, shell_unicode_string]},
{sftp, [], [open_close_file, open_close_dir, read_file, read_dir,
write_file, rename_file, mk_rm_dir, remove_file, links,
retrieve_attributes, set_attributes, async_read, async_read_bin,
async_write
, position , pos_read , pos_write
]}].
init_per_group(Group, Config) when Group==sftp
; Group==shell ->
PrivDir = ?config(priv_dir, Config),
SysDir = ?config(data_dir, Config),
Sftpd =
ssh_test_lib:daemon([{system_dir, SysDir},
{user_dir, PrivDir},
{user_passwords, [{?USER, ?PASSWD}]}]),
[{group,Group}, {sftpd, Sftpd} | Config];
init_per_group(Group, Config) ->
[{group,Group} | Config].
end_per_group(erlang_server, Config) ->
Config;
end_per_group(_, Config) ->
Config.
%%--------------------------------------------------------------------
init_per_testcase(_Case, Config) ->
prep(Config),
TmpConfig0 = lists:keydelete(watchdog, 1, Config),
TmpConfig = lists:keydelete(sftp, 1, TmpConfig0),
Dog = ct:timetrap(?default_timeout),
case ?config(group, Config) of
sftp ->
{_Pid, Host, Port} = ?config(sftpd, Config),
{ok, ChannelPid, Connection} =
ssh_sftp:start_channel(Host, Port,
[{user, ?USER},
{password, ?PASSWD},
{user_interaction, false},
{silently_accept_hosts, true}]),
Sftp = {ChannelPid, Connection},
[{sftp, Sftp}, {watchdog, Dog} | TmpConfig];
shell ->
UserDir = ?config(priv_dir, Config),
process_flag(trap_exit, true),
{_Pid, _Host, Port} = ?config(sftpd, Config),
ct:sleep(500),
IO = ssh_test_lib:start_io_server(),
Shell = ssh_test_lib:start_shell(Port, IO, UserDir,
[{silently_accept_hosts, true},
{user,?USER},{password,?PASSWD}]),
ct : pal("IO=~p , Shell=~p , self()=~p",[IO , Shell , self ( ) ] ) ,
wait_for_erlang_first_line([{io,IO}, {shell,Shell} | Config])
end.
wait_for_erlang_first_line(Config) ->
receive
{'EXIT', _, _} ->
{fail,no_ssh_connection};
<<"Eshell ",_/binary>> = ErlShellStart ->
ct : pal("Erlang shell start : ~p ~ n " , [ ] ) ,
Config;
Other ->
ct:pal("Unexpected answer from ssh server: ~p",[Other]),
{fail,unexpected_answer}
after 10000 ->
ct:pal("No answer from ssh-server"),
{fail,timeout}
end.
end_per_testcase(rename_file, Config) ->
PrivDir = ?config(priv_dir, Config),
NewFileName = filename:join(PrivDir, ?'test.txt'),
file:delete(NewFileName),
end_per_testcase(Config);
end_per_testcase(_TC, Config) ->
end_per_testcase(Config).
end_per_testcase(Config) ->
catch exit(?config(shell,Config), kill),
case ?config(sftp, Config) of
{Sftp, Connection} ->
ssh_sftp:stop_channel(Sftp),
ssh:close(Connection);
_ ->
ok
end.
%%--------------------------------------------------------------------
%% Test Cases --------------------------------------------------------
-define(chk_expected(Received,Expected),
(fun(R_,E_) when R_==E_ -> ok;
(R_,E_) -> ct:pal("Expected: ~p~nReceived: ~p~n", [E_,R_]),
E_ = R_
end)(Received,Expected)).
-define(receive_chk(Ref,Expected),
(fun(E__) ->
receive
{async_reply, Ref, Received} when Received==E__ ->
?chk_expected(Received, E__);
{async_reply, Ref, Received} when Received=/=E__ ->
ct:pal("Expected: ~p~nReceived: ~p~n", [E__,Received]),
E__ = Received;
Msg ->
ct:pal("Expected (Ref=~p): ~p", [Ref,E__]),
ct:fail(Msg)
end
end)(Expected)).
%%--------------------------------------------------------------------
open_close_file() ->
[{doc, "Test API functions open/3 and close/2"}].
open_close_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
lists:foreach(
fun(Mode) ->
ct:log("Mode: ~p",[Mode]),
%% list_dir(PrivDir),
ok = open_close_file(Sftp, FileName, Mode)
end,
[
[read],
[write],
[write, creat],
[write, trunc],
[append],
[read, binary]
]).
open_close_file(Server, File, Mode) ->
{ok, Handle} = ssh_sftp:open(Server, File, Mode),
ok = ssh_sftp:close(Server, Handle).
%%--------------------------------------------------------------------
open_close_dir() ->
[{doc, "Test API functions opendir/2 and close/2"}].
open_close_dir(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
{Sftp, _} = ?config(sftp, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{ok, Handle} = ssh_sftp:opendir(Sftp, PrivDir),
ok = ssh_sftp:close(Sftp, Handle),
{error, _} = ssh_sftp:opendir(Sftp, FileName).
%%--------------------------------------------------------------------
read_file() ->
[{doc, "Test API funtion read_file/2"}].
read_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
?chk_expected(ssh_sftp:read_file(Sftp,FileName), file:read_file(FileName)).
%%--------------------------------------------------------------------
read_dir() ->
[{doc,"Test API function list_dir/2"}].
read_dir(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
{Sftp, _} = ?config(sftp, Config),
{ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
ct:pal("sftp list dir: ~ts~n", [Files]).
%%--------------------------------------------------------------------
write_file() ->
[{doc, "Test API function write_file/2"}].
write_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
ok = ssh_sftp:write_file(Sftp, FileName, [?bindata]),
?chk_expected(file:read_file(FileName), {ok,?bindata}).
%%--------------------------------------------------------------------
remove_file() ->
[{doc,"Test API function delete/2"}].
remove_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
true = lists:member(filename:basename(FileName), Files),
ok = ssh_sftp:delete(Sftp, FileName),
{ok, NewFiles} = ssh_sftp:list_dir(Sftp, PrivDir),
false = lists:member(filename:basename(FileName), NewFiles),
{error, _} = ssh_sftp:delete(Sftp, FileName).
%%--------------------------------------------------------------------
rename_file() ->
[{doc, "Test API function rename_file/2"}].
rename_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
NewFileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
ct:pal("FileName: ~ts~nFiles: ~ts~n", [FileName, [[$\n,$ ,F]||F<-Files] ]),
true = lists:member(filename:basename(FileName), Files),
false = lists:member(filename:basename(NewFileName), Files),
ok = ssh_sftp:rename(Sftp, FileName, NewFileName),
{ok, NewFiles} = ssh_sftp:list_dir(Sftp, PrivDir),
ct:pal("FileName: ~ts, Files: ~ts~n", [FileName, [[$\n,F]||F<-NewFiles] ]),
false = lists:member(filename:basename(FileName), NewFiles),
true = lists:member(filename:basename(NewFileName), NewFiles).
%%--------------------------------------------------------------------
mk_rm_dir() ->
[{doc,"Test API functions make_dir/2, del_dir/2"}].
mk_rm_dir(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
{Sftp, _} = ?config(sftp, Config),
DirName = filename:join(PrivDir, "test"),
ok = ssh_sftp:make_dir(Sftp, DirName),
ok = ssh_sftp:del_dir(Sftp, DirName),
NewDirName = filename:join(PrivDir, "foo/bar"),
{error, _} = ssh_sftp:make_dir(Sftp, NewDirName),
{error, _} = ssh_sftp:del_dir(Sftp, PrivDir).
%%--------------------------------------------------------------------
links() ->
[{doc,"Tests API function make_symlink/3"}].
links(Config) when is_list(Config) ->
case os:type() of
{win32, _} ->
{skip, "Links are not fully supported by windows"};
_ ->
{Sftp, _} = ?config(sftp, Config),
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
LinkFileName = filename:join(PrivDir, ?'link_test.txt'),
ok = ssh_sftp:make_symlink(Sftp, LinkFileName, FileName),
{ok, FileName} = ssh_sftp:read_link(Sftp, LinkFileName)
end.
%%--------------------------------------------------------------------
retrieve_attributes() ->
[{doc, "Test API function read_file_info/3"}].
retrieve_attributes(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, FileInfo} = ssh_sftp:read_file_info(Sftp, FileName),
{ok, NewFileInfo} = file:read_file_info(FileName),
%% TODO comparison. There are some differences now is that ok?
ct:pal("SFTP: ~p~nFILE: ~p~n", [FileInfo, NewFileInfo]).
%%--------------------------------------------------------------------
set_attributes() ->
[{doc,"Test API function write_file_info/3"}].
set_attributes(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok,Fd} = file:open(FileName, write),
io:put_chars(Fd,"foo"),
ok = ssh_sftp:write_file_info(Sftp, FileName, #file_info{mode=8#400}),
{error, eacces} = file:write_file(FileName, "hello again"),
ssh_sftp:write_file_info(Sftp, FileName, #file_info{mode=8#600}),
ok = file:write_file(FileName, "hello again").
%%--------------------------------------------------------------------
async_read() ->
[{doc,"Test API aread/3"}].
async_read(Config) when is_list(Config) ->
do_async_read(Config, false).
async_read_bin() ->
[{doc,"Test API aread/3"}].
async_read_bin(Config) when is_list(Config) ->
do_async_read(Config, true).
do_async_read(Config, BinaryFlag) ->
{Sftp, _} = ?config(sftp, Config),
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{ok,ExpDataBin} = file:read_file(FileName),
ExpData = case BinaryFlag of
true -> ExpDataBin;
false -> binary_to_list(ExpDataBin)
end,
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [read|case BinaryFlag of
true -> [binary];
false -> []
end]),
{async, Ref} = ssh_sftp:aread(Sftp, Handle, 20),
?receive_chk(Ref, {ok,ExpData}).
%%--------------------------------------------------------------------
async_write() ->
[{doc,"Test API awrite/3"}].
async_write(Config) when is_list(Config) ->
{Sftp, _} = ?config(sftp, Config),
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [write]),
Expected = ?bindata,
{async, Ref} = ssh_sftp:awrite(Sftp, Handle, Expected),
receive
{async_reply, Ref, ok} ->
{ok, Data} = file:read_file(FileName),
?chk_expected(Data, Expected);
Msg ->
ct:fail(Msg)
end.
%%--------------------------------------------------------------------
position() ->
[{doc, "Test API functions position/3"}].
position(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
Data = list_to_binary("1234567890"),
ssh_sftp:write_file(Sftp, FileName, [Data]),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [read]),
{ok, 3} = ssh_sftp:position(Sftp, Handle, {bof, 3}),
{ok, "4"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 10} = ssh_sftp:position(Sftp, Handle, eof),
eof = ssh_sftp:read(Sftp, Handle, 1),
{ok, 6} = ssh_sftp:position(Sftp, Handle, {bof, 6}),
{ok, "7"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 9} = ssh_sftp:position(Sftp, Handle, {cur, 2}),
{ok, "0"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 0} = ssh_sftp:position(Sftp, Handle, bof),
{ok, "1"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 1} = ssh_sftp:position(Sftp, Handle, cur),
{ok, "2"} = ssh_sftp:read(Sftp, Handle, 1).
%%--------------------------------------------------------------------
pos_read() ->
[{doc,"Test API functions pread/3 and apread/3"}].
pos_read(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
Data = ?bindata,
ssh_sftp:write_file(Sftp, FileName, [Data]),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [read]),
{async, Ref} = ssh_sftp:apread(Sftp, Handle, {bof,5}, 4),
?receive_chk(Ref, {ok,binary_part(Data,5,4)}),
?chk_expected(ssh_sftp:pread(Sftp,Handle,{bof,4},4), {ok,binary_part(Data,4,4)}).
%%--------------------------------------------------------------------
pos_write() ->
[{doc,"Test API functions pwrite/4 and apwrite/4"}].
pos_write(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [write]),
Data = unicode:characters_to_list("再见"),
ssh_sftp:write_file(Sftp, FileName, [Data]),
NewData = unicode:characters_to_list(" さようなら"),
{async, Ref} = ssh_sftp:apwrite(Sftp, Handle, {bof, 2}, NewData),
?receive_chk(Ref, ok),
ok = ssh_sftp:pwrite(Sftp, Handle, eof, unicode:characters_to_list(" adjö ")),
?chk_expected(ssh_sftp:read_file(Sftp,FileName),
{ok,unicode:characters_to_binary("再见 さようなら adjö ")}).
%%--------------------------------------------------------------------
sftp_nonexistent_subsystem() ->
[{doc, "Try to execute sftp subsystem on a server that does not support it"}].
sftp_nonexistent_subsystem(Config) when is_list(Config) ->
{_,Host, Port} = ?config(sftpd, Config),
{error,"server failed to start sftp subsystem"} =
ssh_sftp:start_channel(Host, Port,
[{user_interaction, false},
{user, ?USER},
{password, ?PASSWD},
{silently_accept_hosts, true}]).
%%--------------------------------------------------------------------
shell_no_unicode(Config) ->
do_shell(?config(io,Config),
[new_prompt,
{type,"io:format(\"hej ~p~n\",[42])."},
{expect,"hej 42"}
]).
%%--------------------------------------------------------------------
shell_unicode_string(Config) ->
do_shell(?config(io,Config),
[new_prompt,
{type,"io:format(\"こにちわ~ts~n\",[\"四二\"])."},
{expect,"こにちわ四二"},
{expect,"ok"}
]).
%%--------------------------------------------------------------------
Internal functions ------------------------------------------------
%%--------------------------------------------------------------------
prep(Config) ->
PrivDir = ?config(priv_dir, Config),
TestFile = filename:join(PrivDir, ?'sftp.txt'),
TestFile1 = filename:join(PrivDir, ?'test.txt'),
TestLink = filename:join(PrivDir, ?'link_test.txt'),
file:delete(TestFile),
file:delete(TestFile1),
file:delete(TestLink),
%% Initial config
DataDir = ?config(data_dir, Config),
FileName = filename:join(DataDir, ?'sftp.txt'),
{ok,_BytesCopied} = file:copy(FileName, TestFile),
Mode = 8#00400 bor 8#00200 bor 8#00040, % read & write owner, read group
{ok, FileInfo} = file:read_file_info(TestFile),
ok = file:write_file_info(TestFile,
FileInfo#file_info{mode = Mode}).
%% list_dir(Dir) ->
%% ct:pal("prep/1: ls(~p):~n~p~n~ts",[Dir, file:list_dir(Dir),
%% begin
%% {ok,DL} = file:list_dir(Dir),
%% [[$\n|FN] || FN <- DL]
%% end]).
%%--------------------------------------------------------------------
do_shell(IO, List) -> do_shell(IO, 0, List).
do_shell(IO, N, [new_prompt|More]) ->
do_shell(IO, N+1, More);
do_shell(IO, N, Ops=[{Order,Arg}|More]) ->
receive
X = <<"\r\n">> ->
%% ct:pal("Skip newline ~p",[X]),
do_shell(IO, N, Ops);
<<P1,"> ">> when (P1-$0)==N ->
do_shell_prompt(IO, N, Order, Arg, More);
<<P1,P2,"> ">> when (P1-$0)*10 + (P2-$0) == N ->
do_shell_prompt(IO, N, Order, Arg, More);
Err when element(1,Err)==error ->
ct:fail("do_shell error: ~p~n",[Err]);
RecBin when Order==expect ; Order==expect_echo ->
%% ct:pal("received ~p",[RecBin]),
RecStr = string:strip(unicode:characters_to_list(RecBin)),
ExpStr = string:strip(Arg),
case lists:prefix(ExpStr, RecStr) of
true when Order==expect ->
ct:pal("Matched ~ts",[RecStr]),
do_shell(IO, N, More);
true when Order==expect_echo ->
ct:pal("Matched echo ~ts",[RecStr]),
do_shell(IO, N, More);
false ->
ct:fail("*** Expected ~p, but got ~p",[string:strip(ExpStr),RecStr])
end
after 10000 ->
case Order of
expect -> ct:fail("timeout, expected ~p",[string:strip(Arg)]);
type -> ct:fail("timeout, no prompt")
end
end;
do_shell(_, _, []) ->
ok.
do_shell_prompt(IO, N, type, Str, More) ->
%% ct:pal("Matched prompt ~p to trigger sending of next line to server",[N]),
IO ! {input, self(), Str++"\r\n"},
ct:pal("Promt '~p> ', Sent ~ts",[N,Str++"\r\n"]),
do_shell(IO, N, [{expect_echo,Str}|More]); % expect echo of the sent line
do_shell_prompt(IO, N, Op, Str, More) ->
%% ct:pal("Matched prompt ~p",[N]),
do_shell(IO, N, [{Op,Str}|More]).
%%--------------------------------------------------------------------
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/ssh/test/ssh_unicode_SUITE.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online 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.
%CopyrightEnd%
gerl +fnu
Note: This directive should only be used in test suites.
Default timetrap timeout
--------------------------------------------------------------------
Common Test interface functions -----------------------------------
--------------------------------------------------------------------
suite() ->
[{ct_hooks,[ts_install_cth]}].
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Test Cases --------------------------------------------------------
--------------------------------------------------------------------
list_dir(PrivDir),
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
TODO comparison. There are some differences now is that ok?
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Initial config
read & write owner, read group
list_dir(Dir) ->
ct:pal("prep/1: ls(~p):~n~p~n~ts",[Dir, file:list_dir(Dir),
begin
{ok,DL} = file:list_dir(Dir),
[[$\n|FN] || FN <- DL]
end]).
--------------------------------------------------------------------
ct:pal("Skip newline ~p",[X]),
ct:pal("received ~p",[RecBin]),
ct:pal("Matched prompt ~p to trigger sending of next line to server",[N]),
expect echo of the sent line
ct:pal("Matched prompt ~p",[N]),
-------------------------------------------------------------------- | Copyright Ericsson AB 2005 - 2014 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
ct : run_test([{suite,"ssh_unicode_SUITE " } , { " } ] ) .
-module(ssh_unicode_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("kernel/include/file.hrl").
-define(default_timeout, ?t:minutes(1)).
-define(USER, "åke高兴").
-define(PASSWD, "ärlig日本じん").
-define('sftp.txt', "sftp瑞点.txt").
-define('test.txt', "testハンス.txt").
-define('link_test.txt', "link_test語.txt").
-define(bindata, unicode:characters_to_binary("foobar å 一二三四いちにさんち") ).
-define(NEWLINE, <<"\r\n">>).
all() ->
[{group, sftp},
{group, shell}
].
init_per_suite(Config) ->
case {file:native_name_encoding(), (catch crypto:start())} of
{utf8, ok} ->
ssh:start(),
Config;
{utf8, _} ->
{skip,"Could not start crypto!"};
_ ->
{skip,"Not unicode filename enabled emulator"}
end.
end_per_suite(Config) ->
ssh:stop(),
crypto:stop(),
Config.
groups() ->
[{shell, [], [shell_no_unicode, shell_unicode_string]},
{sftp, [], [open_close_file, open_close_dir, read_file, read_dir,
write_file, rename_file, mk_rm_dir, remove_file, links,
retrieve_attributes, set_attributes, async_read, async_read_bin,
async_write
, position , pos_read , pos_write
]}].
init_per_group(Group, Config) when Group==sftp
; Group==shell ->
PrivDir = ?config(priv_dir, Config),
SysDir = ?config(data_dir, Config),
Sftpd =
ssh_test_lib:daemon([{system_dir, SysDir},
{user_dir, PrivDir},
{user_passwords, [{?USER, ?PASSWD}]}]),
[{group,Group}, {sftpd, Sftpd} | Config];
init_per_group(Group, Config) ->
[{group,Group} | Config].
end_per_group(erlang_server, Config) ->
Config;
end_per_group(_, Config) ->
Config.
init_per_testcase(_Case, Config) ->
prep(Config),
TmpConfig0 = lists:keydelete(watchdog, 1, Config),
TmpConfig = lists:keydelete(sftp, 1, TmpConfig0),
Dog = ct:timetrap(?default_timeout),
case ?config(group, Config) of
sftp ->
{_Pid, Host, Port} = ?config(sftpd, Config),
{ok, ChannelPid, Connection} =
ssh_sftp:start_channel(Host, Port,
[{user, ?USER},
{password, ?PASSWD},
{user_interaction, false},
{silently_accept_hosts, true}]),
Sftp = {ChannelPid, Connection},
[{sftp, Sftp}, {watchdog, Dog} | TmpConfig];
shell ->
UserDir = ?config(priv_dir, Config),
process_flag(trap_exit, true),
{_Pid, _Host, Port} = ?config(sftpd, Config),
ct:sleep(500),
IO = ssh_test_lib:start_io_server(),
Shell = ssh_test_lib:start_shell(Port, IO, UserDir,
[{silently_accept_hosts, true},
{user,?USER},{password,?PASSWD}]),
ct : pal("IO=~p , Shell=~p , self()=~p",[IO , Shell , self ( ) ] ) ,
wait_for_erlang_first_line([{io,IO}, {shell,Shell} | Config])
end.
wait_for_erlang_first_line(Config) ->
receive
{'EXIT', _, _} ->
{fail,no_ssh_connection};
<<"Eshell ",_/binary>> = ErlShellStart ->
ct : pal("Erlang shell start : ~p ~ n " , [ ] ) ,
Config;
Other ->
ct:pal("Unexpected answer from ssh server: ~p",[Other]),
{fail,unexpected_answer}
after 10000 ->
ct:pal("No answer from ssh-server"),
{fail,timeout}
end.
end_per_testcase(rename_file, Config) ->
PrivDir = ?config(priv_dir, Config),
NewFileName = filename:join(PrivDir, ?'test.txt'),
file:delete(NewFileName),
end_per_testcase(Config);
end_per_testcase(_TC, Config) ->
end_per_testcase(Config).
end_per_testcase(Config) ->
catch exit(?config(shell,Config), kill),
case ?config(sftp, Config) of
{Sftp, Connection} ->
ssh_sftp:stop_channel(Sftp),
ssh:close(Connection);
_ ->
ok
end.
-define(chk_expected(Received,Expected),
(fun(R_,E_) when R_==E_ -> ok;
(R_,E_) -> ct:pal("Expected: ~p~nReceived: ~p~n", [E_,R_]),
E_ = R_
end)(Received,Expected)).
-define(receive_chk(Ref,Expected),
(fun(E__) ->
receive
{async_reply, Ref, Received} when Received==E__ ->
?chk_expected(Received, E__);
{async_reply, Ref, Received} when Received=/=E__ ->
ct:pal("Expected: ~p~nReceived: ~p~n", [E__,Received]),
E__ = Received;
Msg ->
ct:pal("Expected (Ref=~p): ~p", [Ref,E__]),
ct:fail(Msg)
end
end)(Expected)).
open_close_file() ->
[{doc, "Test API functions open/3 and close/2"}].
open_close_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
lists:foreach(
fun(Mode) ->
ct:log("Mode: ~p",[Mode]),
ok = open_close_file(Sftp, FileName, Mode)
end,
[
[read],
[write],
[write, creat],
[write, trunc],
[append],
[read, binary]
]).
open_close_file(Server, File, Mode) ->
{ok, Handle} = ssh_sftp:open(Server, File, Mode),
ok = ssh_sftp:close(Server, Handle).
open_close_dir() ->
[{doc, "Test API functions opendir/2 and close/2"}].
open_close_dir(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
{Sftp, _} = ?config(sftp, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{ok, Handle} = ssh_sftp:opendir(Sftp, PrivDir),
ok = ssh_sftp:close(Sftp, Handle),
{error, _} = ssh_sftp:opendir(Sftp, FileName).
read_file() ->
[{doc, "Test API funtion read_file/2"}].
read_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
?chk_expected(ssh_sftp:read_file(Sftp,FileName), file:read_file(FileName)).
read_dir() ->
[{doc,"Test API function list_dir/2"}].
read_dir(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
{Sftp, _} = ?config(sftp, Config),
{ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
ct:pal("sftp list dir: ~ts~n", [Files]).
write_file() ->
[{doc, "Test API function write_file/2"}].
write_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
ok = ssh_sftp:write_file(Sftp, FileName, [?bindata]),
?chk_expected(file:read_file(FileName), {ok,?bindata}).
remove_file() ->
[{doc,"Test API function delete/2"}].
remove_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
true = lists:member(filename:basename(FileName), Files),
ok = ssh_sftp:delete(Sftp, FileName),
{ok, NewFiles} = ssh_sftp:list_dir(Sftp, PrivDir),
false = lists:member(filename:basename(FileName), NewFiles),
{error, _} = ssh_sftp:delete(Sftp, FileName).
rename_file() ->
[{doc, "Test API function rename_file/2"}].
rename_file(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
NewFileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, Files} = ssh_sftp:list_dir(Sftp, PrivDir),
ct:pal("FileName: ~ts~nFiles: ~ts~n", [FileName, [[$\n,$ ,F]||F<-Files] ]),
true = lists:member(filename:basename(FileName), Files),
false = lists:member(filename:basename(NewFileName), Files),
ok = ssh_sftp:rename(Sftp, FileName, NewFileName),
{ok, NewFiles} = ssh_sftp:list_dir(Sftp, PrivDir),
ct:pal("FileName: ~ts, Files: ~ts~n", [FileName, [[$\n,F]||F<-NewFiles] ]),
false = lists:member(filename:basename(FileName), NewFiles),
true = lists:member(filename:basename(NewFileName), NewFiles).
mk_rm_dir() ->
[{doc,"Test API functions make_dir/2, del_dir/2"}].
mk_rm_dir(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
{Sftp, _} = ?config(sftp, Config),
DirName = filename:join(PrivDir, "test"),
ok = ssh_sftp:make_dir(Sftp, DirName),
ok = ssh_sftp:del_dir(Sftp, DirName),
NewDirName = filename:join(PrivDir, "foo/bar"),
{error, _} = ssh_sftp:make_dir(Sftp, NewDirName),
{error, _} = ssh_sftp:del_dir(Sftp, PrivDir).
links() ->
[{doc,"Tests API function make_symlink/3"}].
links(Config) when is_list(Config) ->
case os:type() of
{win32, _} ->
{skip, "Links are not fully supported by windows"};
_ ->
{Sftp, _} = ?config(sftp, Config),
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
LinkFileName = filename:join(PrivDir, ?'link_test.txt'),
ok = ssh_sftp:make_symlink(Sftp, LinkFileName, FileName),
{ok, FileName} = ssh_sftp:read_link(Sftp, LinkFileName)
end.
retrieve_attributes() ->
[{doc, "Test API function read_file_info/3"}].
retrieve_attributes(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, FileInfo} = ssh_sftp:read_file_info(Sftp, FileName),
{ok, NewFileInfo} = file:read_file_info(FileName),
ct:pal("SFTP: ~p~nFILE: ~p~n", [FileInfo, NewFileInfo]).
set_attributes() ->
[{doc,"Test API function write_file_info/3"}].
set_attributes(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok,Fd} = file:open(FileName, write),
io:put_chars(Fd,"foo"),
ok = ssh_sftp:write_file_info(Sftp, FileName, #file_info{mode=8#400}),
{error, eacces} = file:write_file(FileName, "hello again"),
ssh_sftp:write_file_info(Sftp, FileName, #file_info{mode=8#600}),
ok = file:write_file(FileName, "hello again").
async_read() ->
[{doc,"Test API aread/3"}].
async_read(Config) when is_list(Config) ->
do_async_read(Config, false).
async_read_bin() ->
[{doc,"Test API aread/3"}].
async_read_bin(Config) when is_list(Config) ->
do_async_read(Config, true).
do_async_read(Config, BinaryFlag) ->
{Sftp, _} = ?config(sftp, Config),
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'sftp.txt'),
{ok,ExpDataBin} = file:read_file(FileName),
ExpData = case BinaryFlag of
true -> ExpDataBin;
false -> binary_to_list(ExpDataBin)
end,
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [read|case BinaryFlag of
true -> [binary];
false -> []
end]),
{async, Ref} = ssh_sftp:aread(Sftp, Handle, 20),
?receive_chk(Ref, {ok,ExpData}).
async_write() ->
[{doc,"Test API awrite/3"}].
async_write(Config) when is_list(Config) ->
{Sftp, _} = ?config(sftp, Config),
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [write]),
Expected = ?bindata,
{async, Ref} = ssh_sftp:awrite(Sftp, Handle, Expected),
receive
{async_reply, Ref, ok} ->
{ok, Data} = file:read_file(FileName),
?chk_expected(Data, Expected);
Msg ->
ct:fail(Msg)
end.
position() ->
[{doc, "Test API functions position/3"}].
position(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
Data = list_to_binary("1234567890"),
ssh_sftp:write_file(Sftp, FileName, [Data]),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [read]),
{ok, 3} = ssh_sftp:position(Sftp, Handle, {bof, 3}),
{ok, "4"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 10} = ssh_sftp:position(Sftp, Handle, eof),
eof = ssh_sftp:read(Sftp, Handle, 1),
{ok, 6} = ssh_sftp:position(Sftp, Handle, {bof, 6}),
{ok, "7"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 9} = ssh_sftp:position(Sftp, Handle, {cur, 2}),
{ok, "0"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 0} = ssh_sftp:position(Sftp, Handle, bof),
{ok, "1"} = ssh_sftp:read(Sftp, Handle, 1),
{ok, 1} = ssh_sftp:position(Sftp, Handle, cur),
{ok, "2"} = ssh_sftp:read(Sftp, Handle, 1).
pos_read() ->
[{doc,"Test API functions pread/3 and apread/3"}].
pos_read(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
Data = ?bindata,
ssh_sftp:write_file(Sftp, FileName, [Data]),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [read]),
{async, Ref} = ssh_sftp:apread(Sftp, Handle, {bof,5}, 4),
?receive_chk(Ref, {ok,binary_part(Data,5,4)}),
?chk_expected(ssh_sftp:pread(Sftp,Handle,{bof,4},4), {ok,binary_part(Data,4,4)}).
pos_write() ->
[{doc,"Test API functions pwrite/4 and apwrite/4"}].
pos_write(Config) when is_list(Config) ->
PrivDir = ?config(priv_dir, Config),
FileName = filename:join(PrivDir, ?'test.txt'),
{Sftp, _} = ?config(sftp, Config),
{ok, Handle} = ssh_sftp:open(Sftp, FileName, [write]),
Data = unicode:characters_to_list("再见"),
ssh_sftp:write_file(Sftp, FileName, [Data]),
NewData = unicode:characters_to_list(" さようなら"),
{async, Ref} = ssh_sftp:apwrite(Sftp, Handle, {bof, 2}, NewData),
?receive_chk(Ref, ok),
ok = ssh_sftp:pwrite(Sftp, Handle, eof, unicode:characters_to_list(" adjö ")),
?chk_expected(ssh_sftp:read_file(Sftp,FileName),
{ok,unicode:characters_to_binary("再见 さようなら adjö ")}).
sftp_nonexistent_subsystem() ->
[{doc, "Try to execute sftp subsystem on a server that does not support it"}].
sftp_nonexistent_subsystem(Config) when is_list(Config) ->
{_,Host, Port} = ?config(sftpd, Config),
{error,"server failed to start sftp subsystem"} =
ssh_sftp:start_channel(Host, Port,
[{user_interaction, false},
{user, ?USER},
{password, ?PASSWD},
{silently_accept_hosts, true}]).
shell_no_unicode(Config) ->
do_shell(?config(io,Config),
[new_prompt,
{type,"io:format(\"hej ~p~n\",[42])."},
{expect,"hej 42"}
]).
shell_unicode_string(Config) ->
do_shell(?config(io,Config),
[new_prompt,
{type,"io:format(\"こにちわ~ts~n\",[\"四二\"])."},
{expect,"こにちわ四二"},
{expect,"ok"}
]).
Internal functions ------------------------------------------------
prep(Config) ->
PrivDir = ?config(priv_dir, Config),
TestFile = filename:join(PrivDir, ?'sftp.txt'),
TestFile1 = filename:join(PrivDir, ?'test.txt'),
TestLink = filename:join(PrivDir, ?'link_test.txt'),
file:delete(TestFile),
file:delete(TestFile1),
file:delete(TestLink),
DataDir = ?config(data_dir, Config),
FileName = filename:join(DataDir, ?'sftp.txt'),
{ok,_BytesCopied} = file:copy(FileName, TestFile),
{ok, FileInfo} = file:read_file_info(TestFile),
ok = file:write_file_info(TestFile,
FileInfo#file_info{mode = Mode}).
do_shell(IO, List) -> do_shell(IO, 0, List).
do_shell(IO, N, [new_prompt|More]) ->
do_shell(IO, N+1, More);
do_shell(IO, N, Ops=[{Order,Arg}|More]) ->
receive
X = <<"\r\n">> ->
do_shell(IO, N, Ops);
<<P1,"> ">> when (P1-$0)==N ->
do_shell_prompt(IO, N, Order, Arg, More);
<<P1,P2,"> ">> when (P1-$0)*10 + (P2-$0) == N ->
do_shell_prompt(IO, N, Order, Arg, More);
Err when element(1,Err)==error ->
ct:fail("do_shell error: ~p~n",[Err]);
RecBin when Order==expect ; Order==expect_echo ->
RecStr = string:strip(unicode:characters_to_list(RecBin)),
ExpStr = string:strip(Arg),
case lists:prefix(ExpStr, RecStr) of
true when Order==expect ->
ct:pal("Matched ~ts",[RecStr]),
do_shell(IO, N, More);
true when Order==expect_echo ->
ct:pal("Matched echo ~ts",[RecStr]),
do_shell(IO, N, More);
false ->
ct:fail("*** Expected ~p, but got ~p",[string:strip(ExpStr),RecStr])
end
after 10000 ->
case Order of
expect -> ct:fail("timeout, expected ~p",[string:strip(Arg)]);
type -> ct:fail("timeout, no prompt")
end
end;
do_shell(_, _, []) ->
ok.
do_shell_prompt(IO, N, type, Str, More) ->
IO ! {input, self(), Str++"\r\n"},
ct:pal("Promt '~p> ', Sent ~ts",[N,Str++"\r\n"]),
do_shell_prompt(IO, N, Op, Str, More) ->
do_shell(IO, N, [{Op,Str}|More]).
|
a857be2f5782f2149dfef0c0e48be30d095cff2a490119d3367e0577ea7680d1 | TheLortex/mirage-monorepo | s.ml | { { { Copyright ( C ) 2012 - 2014 Anil Madhavapeddy < >
* Copyright ( c ) 2014
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
* Copyright (c) 2014 Rudi Grinberg
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
* Module type signatures for Cohttp components
(** The [IO] module defines the blocking interface for reading and writing to
Cohttp streams *)
module type IO = sig
type +'a t
(** ['a t] represents a blocking monad state *)
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
(** [a >>= b] will pass the result of [a] to the [b] function. This is a
monadic [bind]. *)
val return : 'a -> 'a t
(** [return a] will construct a constant IO value. *)
type ic
(** [ic] represents an input channel *)
type oc
(** [oc] represents an output channel *)
type conn
(** [conn] represents the underlying network flow *)
val refill : ic -> [ `Ok | `Eof ] t
val with_input_buffer :
ic -> f:(string -> pos:int -> len:int -> 'a * int) -> 'a
val read_line : ic -> string option t
* [ read_line ic ] will read a single line terminated by or CRLF from the
input channel [ ic ] . It returns { ! None } if EOF or other error condition is
reached .
input channel [ic]. It returns {!None} if EOF or other error condition is
reached. *)
val read : ic -> int -> string t
* [ read ic len ] will block until a maximum of [ len ] characters are read from
the input channel [ ic ] . It returns an empty string if EOF or some other
error condition occurs on the input channel , and can also return fewer
than [ len ] characters if input buffering is not sufficient to satisfy the
request .
the input channel [ic]. It returns an empty string if EOF or some other
error condition occurs on the input channel, and can also return fewer
than [len] characters if input buffering is not sufficient to satisfy the
request. *)
val write : oc -> string -> unit t
(** [write oc s] will block until the complete [s] string is written to the
output channel [oc]. *)
val flush : oc -> unit t
(** [flush oc] will return when all previously buffered content from calling
{!write} have been written to the output channel [oc]. *)
end
module type Http_io = sig
type t
type reader
type writer
module IO : IO
val read : IO.ic -> [ `Eof | `Invalid of string | `Ok of t ] IO.t
val make_body_writer : ?flush:bool -> t -> IO.oc -> writer
val make_body_reader : t -> IO.ic -> reader
val read_body_chunk : reader -> Transfer.chunk IO.t
val write_header : t -> IO.oc -> unit IO.t
val write_body : writer -> string -> unit IO.t
val write : ?flush:bool -> (writer -> unit IO.t) -> t -> IO.oc -> unit IO.t
end
module type Request = sig
type t = {
headers : Header.t; (** HTTP request headers *)
meth : Code.meth; (** HTTP request method *)
scheme : string option; (** URI scheme (http or https) *)
resource : string; (** Request path and query *)
* HTTP version , usually 1.1
encoding : Transfer.encoding;
[@deprecated "this field will be removed in the future"]
}
[@@deriving sexp]
val headers : t -> Header.t
val meth : t -> Code.meth
val scheme : t -> string option
val resource : t -> string
val version : t -> Code.version
val encoding : t -> Transfer.encoding
val compare : t -> t -> int
val make :
?meth:Code.meth ->
?version:Code.version ->
?encoding:Transfer.encoding ->
?headers:Header.t ->
Uri.t ->
t
* [ make ( ) ] is a value of { ! type : t } . The default values for the request , if
not specified , are : [ status ] is [ ` Ok ] , [ version ] is [ ` HTTP_1_1 ] , [ flush ]
is [ false ] and [ headers ] is [ Header.empty ] . The request encoding value is
determined via the [ Header.get_transfer_encoding ] function and , if not
found , uses the default value [ Transfer . Fixed 0 ] .
not specified, are: [status] is [`Ok], [version] is [`HTTP_1_1], [flush]
is [false] and [headers] is [Header.empty]. The request encoding value is
determined via the [Header.get_transfer_encoding] function and, if not
found, uses the default value [Transfer.Fixed 0]. *)
val is_keep_alive : t -> bool
(** Return true whether the connection should be reused *)
val uri : t -> Uri.t
val make_for_client :
?headers:Header.t ->
?chunked:bool ->
?body_length:int64 ->
Code.meth ->
Uri.t ->
t
end
module type Response = sig
type t = {
encoding : Transfer.encoding;
[@deprecated "this field will be removed in the future"]
headers : Header.t; (** response HTTP headers *)
* ( * * HTTP version , usually 1.1
status : Code.status_code; (** HTTP status code of the response *)
flush : bool; [@deprecated "this field will be removed in the future"]
}
[@@deriving sexp]
val encoding : t -> Transfer.encoding
val headers : t -> Header.t
val version : t -> Code.version
val status : t -> Code.status_code
val flush :
(t -> bool[@deprecated "this field will be removed in the future"])
val compare : t -> t -> int
val make :
?version:Code.version ->
?status:Code.status_code ->
?flush:bool ->
?encoding:Transfer.encoding ->
?headers:Header.t ->
unit ->
t
* [ make ( ) ] is a value of { ! type : t } . The default values for the request , if
not specified , are : [ status ] is [ ` Ok ] , [ version ] is [ ` HTTP_1_1 ] , [ flush ]
is [ false ] and [ headers ] is [ Header.empty ] . The request encoding value is
determined via the [ Header.get_transfer_encoding ] function and , if not
found , uses the default value [ Transfer . Chunked ] .
not specified, are: [status] is [`Ok], [version] is [`HTTP_1_1], [flush]
is [false] and [headers] is [Header.empty]. The request encoding value is
determined via the [Header.get_transfer_encoding] function and, if not
found, uses the default value [Transfer.Chunked]. *)
end
module type Body = sig
type t
val to_string : t -> string
val to_string_list : t -> string list
val to_form : t -> (string * string list) list
val empty : t
val is_empty : t -> bool
val of_string : string -> t
val of_string_list : string list -> t
val of_form : ?scheme:string -> (string * string list) list -> t
val map : (string -> string) -> t -> t
val transfer_encoding : t -> Transfer.encoding
end
| null | https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/ocaml-cohttp/cohttp/src/s.ml | ocaml | * The [IO] module defines the blocking interface for reading and writing to
Cohttp streams
* ['a t] represents a blocking monad state
* [a >>= b] will pass the result of [a] to the [b] function. This is a
monadic [bind].
* [return a] will construct a constant IO value.
* [ic] represents an input channel
* [oc] represents an output channel
* [conn] represents the underlying network flow
* [write oc s] will block until the complete [s] string is written to the
output channel [oc].
* [flush oc] will return when all previously buffered content from calling
{!write} have been written to the output channel [oc].
* HTTP request headers
* HTTP request method
* URI scheme (http or https)
* Request path and query
* Return true whether the connection should be reused
* response HTTP headers
* HTTP status code of the response | { { { Copyright ( C ) 2012 - 2014 Anil Madhavapeddy < >
* Copyright ( c ) 2014
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
* Copyright (c) 2014 Rudi Grinberg
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
* Module type signatures for Cohttp components
module type IO = sig
type +'a t
val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
type ic
type oc
type conn
val refill : ic -> [ `Ok | `Eof ] t
val with_input_buffer :
ic -> f:(string -> pos:int -> len:int -> 'a * int) -> 'a
val read_line : ic -> string option t
* [ read_line ic ] will read a single line terminated by or CRLF from the
input channel [ ic ] . It returns { ! None } if EOF or other error condition is
reached .
input channel [ic]. It returns {!None} if EOF or other error condition is
reached. *)
val read : ic -> int -> string t
* [ read ic len ] will block until a maximum of [ len ] characters are read from
the input channel [ ic ] . It returns an empty string if EOF or some other
error condition occurs on the input channel , and can also return fewer
than [ len ] characters if input buffering is not sufficient to satisfy the
request .
the input channel [ic]. It returns an empty string if EOF or some other
error condition occurs on the input channel, and can also return fewer
than [len] characters if input buffering is not sufficient to satisfy the
request. *)
val write : oc -> string -> unit t
val flush : oc -> unit t
end
module type Http_io = sig
type t
type reader
type writer
module IO : IO
val read : IO.ic -> [ `Eof | `Invalid of string | `Ok of t ] IO.t
val make_body_writer : ?flush:bool -> t -> IO.oc -> writer
val make_body_reader : t -> IO.ic -> reader
val read_body_chunk : reader -> Transfer.chunk IO.t
val write_header : t -> IO.oc -> unit IO.t
val write_body : writer -> string -> unit IO.t
val write : ?flush:bool -> (writer -> unit IO.t) -> t -> IO.oc -> unit IO.t
end
module type Request = sig
type t = {
* HTTP version , usually 1.1
encoding : Transfer.encoding;
[@deprecated "this field will be removed in the future"]
}
[@@deriving sexp]
val headers : t -> Header.t
val meth : t -> Code.meth
val scheme : t -> string option
val resource : t -> string
val version : t -> Code.version
val encoding : t -> Transfer.encoding
val compare : t -> t -> int
val make :
?meth:Code.meth ->
?version:Code.version ->
?encoding:Transfer.encoding ->
?headers:Header.t ->
Uri.t ->
t
* [ make ( ) ] is a value of { ! type : t } . The default values for the request , if
not specified , are : [ status ] is [ ` Ok ] , [ version ] is [ ` HTTP_1_1 ] , [ flush ]
is [ false ] and [ headers ] is [ Header.empty ] . The request encoding value is
determined via the [ Header.get_transfer_encoding ] function and , if not
found , uses the default value [ Transfer . Fixed 0 ] .
not specified, are: [status] is [`Ok], [version] is [`HTTP_1_1], [flush]
is [false] and [headers] is [Header.empty]. The request encoding value is
determined via the [Header.get_transfer_encoding] function and, if not
found, uses the default value [Transfer.Fixed 0]. *)
val is_keep_alive : t -> bool
val uri : t -> Uri.t
val make_for_client :
?headers:Header.t ->
?chunked:bool ->
?body_length:int64 ->
Code.meth ->
Uri.t ->
t
end
module type Response = sig
type t = {
encoding : Transfer.encoding;
[@deprecated "this field will be removed in the future"]
* ( * * HTTP version , usually 1.1
flush : bool; [@deprecated "this field will be removed in the future"]
}
[@@deriving sexp]
val encoding : t -> Transfer.encoding
val headers : t -> Header.t
val version : t -> Code.version
val status : t -> Code.status_code
val flush :
(t -> bool[@deprecated "this field will be removed in the future"])
val compare : t -> t -> int
val make :
?version:Code.version ->
?status:Code.status_code ->
?flush:bool ->
?encoding:Transfer.encoding ->
?headers:Header.t ->
unit ->
t
* [ make ( ) ] is a value of { ! type : t } . The default values for the request , if
not specified , are : [ status ] is [ ` Ok ] , [ version ] is [ ` HTTP_1_1 ] , [ flush ]
is [ false ] and [ headers ] is [ Header.empty ] . The request encoding value is
determined via the [ Header.get_transfer_encoding ] function and , if not
found , uses the default value [ Transfer . Chunked ] .
not specified, are: [status] is [`Ok], [version] is [`HTTP_1_1], [flush]
is [false] and [headers] is [Header.empty]. The request encoding value is
determined via the [Header.get_transfer_encoding] function and, if not
found, uses the default value [Transfer.Chunked]. *)
end
module type Body = sig
type t
val to_string : t -> string
val to_string_list : t -> string list
val to_form : t -> (string * string list) list
val empty : t
val is_empty : t -> bool
val of_string : string -> t
val of_string_list : string list -> t
val of_form : ?scheme:string -> (string * string list) list -> t
val map : (string -> string) -> t -> t
val transfer_encoding : t -> Transfer.encoding
end
|
5c1c870e3f066a3ad38ff0466291b9bcb1b3082f9e1b84527c16b41ad9cf7126 | madjestic/Haskell-OpenGL-Tutorial | Rendering.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE InstanceSigs #
module NGL.Rendering where
import Graphics.Rendering.OpenGL as GL hiding (Color, Constant)
import Graphics.UI.GLFW as GLFW
import Control.Monad
import Control.Applicative
import System.Exit ( exitWith, ExitCode(..) )
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.Storable
import NGL.LoadShaders
import NGL.Shape
import Graphics.GLUtil
data Descriptor = Descriptor VertexArrayObject ArrayIndex NumArrayIndices
draw :: GLFW.Window -> Drawable -> IO ()
draw win xs = do
descriptor <- initResources xs
onDisplay win descriptor
bufferOffset :: Integral a => a -> Ptr b
bufferOffset = plusPtr nullPtr . fromIntegral
loadTex :: FilePath -> IO TextureObject
loadTex f = do t <- either error id <$> readTexture f
textureFilter Texture2D $= ((Linear', Nothing), Linear')
texture2DWrap $= (Repeated, ClampToEdge)
return t
initResources :: ([Vertex4 Float],[TexCoord2 Float],String) -> IO Descriptor
initResources (vs, uv, tex) = do
triangles <- genObjectName
bindVertexArrayObject $= Just triangles
--
-- Declaring VBO: vertices
--
let vertices = vs
numVertices = length vertices
vertexBuffer <- genObjectName
bindBuffer ArrayBuffer $= Just vertexBuffer
withArray vs $ \ptr -> do
let size = fromIntegral (numVertices * sizeOf (head vs))
bufferData ArrayBuffer $= (size, ptr, StaticDraw)
let firstIndex = 0
vPosition = AttribLocation 0
vertexAttribPointer vPosition $=
(ToFloat, VertexArrayDescriptor 4 Float 0 (bufferOffset firstIndex))
vertexAttribArray vPosition $= Enabled
--
-- Declaring VBO: UVs
--
let uv = toUV Planar
textureBuffer <- genObjectName
bindBuffer ArrayBuffer $= Just textureBuffer
withArray uv $ \ptr -> do
let size = fromIntegral (numVertices * sizeOf (head uv))
bufferData ArrayBuffer $= (size, ptr, StaticDraw)
let firstIndex = 0
uvCoords = AttribLocation 2
vertexAttribPointer uvCoords $=
(ToFloat, VertexArrayDescriptor 2 Float 0 (bufferOffset firstIndex))
vertexAttribArray uvCoords $= Enabled
tx <- loadTex tex
texture Texture2D $= Enabled
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just tx
program <- loadShaders [
ShaderInfo VertexShader (FileSource "Shaders/shader.vert"),
ShaderInfo FragmentShader (FileSource "Shaders/shader.frag")]
currentProgram $= Just program
return $ Descriptor triangles firstIndex (fromIntegral numVertices)
keyPressed :: GLFW.KeyCallback
keyPressed win GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = shutdown win
keyPressed _ _ _ _ _ = return ()
shutdown :: GLFW.WindowCloseCallback
shutdown win = do
GLFW.destroyWindow win
GLFW.terminate
_ <- exitWith ExitSuccess
return ()
resizeWindow :: GLFW.WindowSizeCallback
resizeWindow win w h =
do
GL.viewport $= (GL.Position 0 0, GL.Size (fromIntegral w) (fromIntegral h))
GL.matrixMode $= GL.Projection
GL.loadIdentity
GL.ortho2D 0 (realToFrac w) (realToFrac h) 0
createWindow :: String -> (Int, Int) -> IO GLFW.Window
createWindow title (sizex,sizey) = do
GLFW.init
GLFW.defaultWindowHints
Just win <- GLFW.createWindow sizex sizey title Nothing Nothing
GLFW.makeContextCurrent (Just win)
GLFW.setWindowSizeCallback win (Just resizeWindow)
GLFW.setKeyCallback win (Just keyPressed)
GLFW.setWindowCloseCallback win (Just shutdown)
return win
closeWindow :: GLFW.Window -> IO ()
closeWindow win = do
GLFW.destroyWindow win
GLFW.terminate
onDisplay :: GLFW.Window -> Descriptor -> IO ()
onDisplay win descriptor@(Descriptor triangles firstIndex numVertices) = do
GL.clearColor $= Color4 0 0 0 1
GL.clear [ColorBuffer]
bindVertexArrayObject $= Just triangles
drawArrays Triangles firstIndex numVertices
GLFW.swapBuffers win
forever $ do
GLFW.pollEvents
onDisplay win descriptor
| null | https://raw.githubusercontent.com/madjestic/Haskell-OpenGL-Tutorial/9f685ddde9d6c5d2cc9c2c62f214ca0d43e717c7/rectangle_with_texture_blending/NGL/Rendering.hs | haskell |
Declaring VBO: vertices
Declaring VBO: UVs
| # LANGUAGE FlexibleInstances #
# LANGUAGE InstanceSigs #
module NGL.Rendering where
import Graphics.Rendering.OpenGL as GL hiding (Color, Constant)
import Graphics.UI.GLFW as GLFW
import Control.Monad
import Control.Applicative
import System.Exit ( exitWith, ExitCode(..) )
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.Storable
import NGL.LoadShaders
import NGL.Shape
import Graphics.GLUtil
data Descriptor = Descriptor VertexArrayObject ArrayIndex NumArrayIndices
draw :: GLFW.Window -> Drawable -> IO ()
draw win xs = do
descriptor <- initResources xs
onDisplay win descriptor
bufferOffset :: Integral a => a -> Ptr b
bufferOffset = plusPtr nullPtr . fromIntegral
loadTex :: FilePath -> IO TextureObject
loadTex f = do t <- either error id <$> readTexture f
textureFilter Texture2D $= ((Linear', Nothing), Linear')
texture2DWrap $= (Repeated, ClampToEdge)
return t
initResources :: ([Vertex4 Float],[TexCoord2 Float],String) -> IO Descriptor
initResources (vs, uv, tex) = do
triangles <- genObjectName
bindVertexArrayObject $= Just triangles
let vertices = vs
numVertices = length vertices
vertexBuffer <- genObjectName
bindBuffer ArrayBuffer $= Just vertexBuffer
withArray vs $ \ptr -> do
let size = fromIntegral (numVertices * sizeOf (head vs))
bufferData ArrayBuffer $= (size, ptr, StaticDraw)
let firstIndex = 0
vPosition = AttribLocation 0
vertexAttribPointer vPosition $=
(ToFloat, VertexArrayDescriptor 4 Float 0 (bufferOffset firstIndex))
vertexAttribArray vPosition $= Enabled
let uv = toUV Planar
textureBuffer <- genObjectName
bindBuffer ArrayBuffer $= Just textureBuffer
withArray uv $ \ptr -> do
let size = fromIntegral (numVertices * sizeOf (head uv))
bufferData ArrayBuffer $= (size, ptr, StaticDraw)
let firstIndex = 0
uvCoords = AttribLocation 2
vertexAttribPointer uvCoords $=
(ToFloat, VertexArrayDescriptor 2 Float 0 (bufferOffset firstIndex))
vertexAttribArray uvCoords $= Enabled
tx <- loadTex tex
texture Texture2D $= Enabled
activeTexture $= TextureUnit 0
textureBinding Texture2D $= Just tx
program <- loadShaders [
ShaderInfo VertexShader (FileSource "Shaders/shader.vert"),
ShaderInfo FragmentShader (FileSource "Shaders/shader.frag")]
currentProgram $= Just program
return $ Descriptor triangles firstIndex (fromIntegral numVertices)
keyPressed :: GLFW.KeyCallback
keyPressed win GLFW.Key'Escape _ GLFW.KeyState'Pressed _ = shutdown win
keyPressed _ _ _ _ _ = return ()
shutdown :: GLFW.WindowCloseCallback
shutdown win = do
GLFW.destroyWindow win
GLFW.terminate
_ <- exitWith ExitSuccess
return ()
resizeWindow :: GLFW.WindowSizeCallback
resizeWindow win w h =
do
GL.viewport $= (GL.Position 0 0, GL.Size (fromIntegral w) (fromIntegral h))
GL.matrixMode $= GL.Projection
GL.loadIdentity
GL.ortho2D 0 (realToFrac w) (realToFrac h) 0
createWindow :: String -> (Int, Int) -> IO GLFW.Window
createWindow title (sizex,sizey) = do
GLFW.init
GLFW.defaultWindowHints
Just win <- GLFW.createWindow sizex sizey title Nothing Nothing
GLFW.makeContextCurrent (Just win)
GLFW.setWindowSizeCallback win (Just resizeWindow)
GLFW.setKeyCallback win (Just keyPressed)
GLFW.setWindowCloseCallback win (Just shutdown)
return win
closeWindow :: GLFW.Window -> IO ()
closeWindow win = do
GLFW.destroyWindow win
GLFW.terminate
onDisplay :: GLFW.Window -> Descriptor -> IO ()
onDisplay win descriptor@(Descriptor triangles firstIndex numVertices) = do
GL.clearColor $= Color4 0 0 0 1
GL.clear [ColorBuffer]
bindVertexArrayObject $= Just triangles
drawArrays Triangles firstIndex numVertices
GLFW.swapBuffers win
forever $ do
GLFW.pollEvents
onDisplay win descriptor
|
bb5b5f2dbe96088ff387aaf296b23cc95dc2140f9f70c621d585d942e308addd | xapi-project/xenvm | lvdisplay.ml | LVM compatible bits and pieces
open Cmdliner
open Xenvm_common
open Lwt
let print_verbose vg lv =
let read_write =
let all =
(if List.mem Lvm.Lv.Status.Read lv.Lvm.Lv.status
then [ "read" ] else []) @
(if List.mem Lvm.Lv.Status.Write lv.Lvm.Lv.status
then [ "write" ] else []) in
String.concat "/" all in
let size = Int64.mul vg.Lvm.Vg.extent_size (Lvm.Lv.size_in_extents lv) in
let creation_time =
let open Unix in
let tm = gmtime (Int64.to_float lv.Lvm.Lv.creation_time) in
Printf.sprintf "%d-%02d-%02d %02d:%02d:%02d +0000"
(tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday
tm.tm_hour tm.tm_min tm.tm_sec in
let device =
let module Devmapper = (val !dm: S.RETRYMAPPER) in
let name = Mapper.name_of vg.Lvm.Vg.name lv.Lvm.Lv.name in
Devmapper.stat name >>= fun s ->
match s with
| Some info ->
Lwt.return (Some (Printf.sprintf "%ld:%ld" info.Devmapper.major info.Devmapper.minor))
| None ->
Lwt.return (None) in
device >>= fun device ->
let lines = [
"--- Logical volume ---";
Printf.sprintf "LV Path /dev/%s/%s" vg.Lvm.Vg.name lv.Lvm.Lv.name;
Printf.sprintf "LV Name %s" lv.Lvm.Lv.name;
Printf.sprintf "VG Name %s" vg.Lvm.Vg.name;
Printf.sprintf "LV UUID %s" (Lvm.Uuid.to_string lv.Lvm.Lv.id);
Printf.sprintf "LV Write Access %s" read_write;
Printf.sprintf "LV Creation host, time %s, %s" lv.Lvm.Lv.creation_host creation_time;
Printf.sprintf "LV Status %s" (if List.mem Lvm.Lv.Status.Visible lv.Lvm.Lv.status then "available" else "");
Printf.sprintf "# open uknown";
Printf.sprintf "LV Size %Lds" size;
Printf.sprintf "Current LE %Ld" (Lvm.Lv.size_in_extents lv);
Printf.sprintf "Segments %d" (List.length lv.Lvm.Lv.segments);
Printf.sprintf "Allocation inherit";
Printf.sprintf "Read ahead sectors auto";
- currently set to 256
- currently set to 256
*)
] @ (match device with
| Some device -> [ Printf.sprintf "Block device %s" device ]
| None -> []) @ [
"";
] in
Lwt_list.iter_s (fun line -> stdout " %s" line) lines
(* Example output:
/dev/packer-virtualbox-iso-vg/root:packer-virtualbox-iso-vg:3:1:-1:1:132661248:16194:-1:0:-1:252:0
*)
let print_colon vg lv =
let sectors = Int64.mul vg.Lvm.Vg.extent_size (Lvm.Lv.size_in_extents lv) in
let majorminor =
let module Devmapper = (val !dm: S.RETRYMAPPER) in
let name = Mapper.name_of vg.Lvm.Vg.name lv.Lvm.Lv.name in
Devmapper.stat name >>= fun s ->
match s with
| Some info ->
Lwt.return (Int32.to_string info.Devmapper.major, Int32.to_string info.Devmapper.minor)
| None ->
Lwt.return ("-1", "-1") in
majorminor >>= fun (major,minor) ->
let parts = [
Printf.sprintf "/dev/%s/%s" vg.Lvm.Vg.name lv.Lvm.Lv.name;
vg.Lvm.Vg.name;
"?"; (* access *)
"?"; (* volume status *)
"?"; (* internal logical volume number *)
"?"; (* open count *)
Int64.to_string sectors; (* size in sectors *)
"?"; (* current size in extents *)
"?"; (* allocated extents *)
"?"; (* allocation policy *)
"?"; (* read ahead sectors *)
major;
minor;
] in
stdout " %s" (String.concat ":" parts)
let lvdisplay copts colon (vg_name,lv_display_opt) =
let open Xenvm_common in
let t =
get_vg_info_t copts vg_name >>= fun info ->
set_uri copts info;
Client.get () >>= fun vg ->
let print = if colon then print_colon else print_verbose in
let to_print =
Lvm.Vg.LVs.bindings vg.Lvm.Vg.lvs
only interested in the LV , not the i d
|> List.filter (function { Lvm.Lv.name } -> match lv_display_opt with
| None -> true
| Some lv' when lv' = name -> true
| _ -> false
) in
Lwt_list.iter_s (print vg) to_print
>>= fun () ->
if to_print = [] then failwith "Failed to find any matching logical volumes";
Lwt.return () in
Lwt_main.run t
let lvdisplay_cmd =
let doc = "report information about logical volumes" in
let man = [
`S "DESCRIPTION";
`P "lvdisplay produces formatted output about logical volumes";
] in
let colon_arg =
let doc = "Print in terse colon-separated form" in
Arg.(value & flag & info ["colon";"c"] ~doc) in
Term.(pure lvdisplay $ Xenvm_common.copts_t $ colon_arg $ Xenvm_common.name_arg),
Term.info "lvdisplay" ~sdocs:"COMMON OPTIONS" ~doc ~man
| null | https://raw.githubusercontent.com/xapi-project/xenvm/401754dfb05376b5fc78c9290453b006f6f38aa1/xenvm/lvdisplay.ml | ocaml | Example output:
/dev/packer-virtualbox-iso-vg/root:packer-virtualbox-iso-vg:3:1:-1:1:132661248:16194:-1:0:-1:252:0
access
volume status
internal logical volume number
open count
size in sectors
current size in extents
allocated extents
allocation policy
read ahead sectors | LVM compatible bits and pieces
open Cmdliner
open Xenvm_common
open Lwt
let print_verbose vg lv =
let read_write =
let all =
(if List.mem Lvm.Lv.Status.Read lv.Lvm.Lv.status
then [ "read" ] else []) @
(if List.mem Lvm.Lv.Status.Write lv.Lvm.Lv.status
then [ "write" ] else []) in
String.concat "/" all in
let size = Int64.mul vg.Lvm.Vg.extent_size (Lvm.Lv.size_in_extents lv) in
let creation_time =
let open Unix in
let tm = gmtime (Int64.to_float lv.Lvm.Lv.creation_time) in
Printf.sprintf "%d-%02d-%02d %02d:%02d:%02d +0000"
(tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday
tm.tm_hour tm.tm_min tm.tm_sec in
let device =
let module Devmapper = (val !dm: S.RETRYMAPPER) in
let name = Mapper.name_of vg.Lvm.Vg.name lv.Lvm.Lv.name in
Devmapper.stat name >>= fun s ->
match s with
| Some info ->
Lwt.return (Some (Printf.sprintf "%ld:%ld" info.Devmapper.major info.Devmapper.minor))
| None ->
Lwt.return (None) in
device >>= fun device ->
let lines = [
"--- Logical volume ---";
Printf.sprintf "LV Path /dev/%s/%s" vg.Lvm.Vg.name lv.Lvm.Lv.name;
Printf.sprintf "LV Name %s" lv.Lvm.Lv.name;
Printf.sprintf "VG Name %s" vg.Lvm.Vg.name;
Printf.sprintf "LV UUID %s" (Lvm.Uuid.to_string lv.Lvm.Lv.id);
Printf.sprintf "LV Write Access %s" read_write;
Printf.sprintf "LV Creation host, time %s, %s" lv.Lvm.Lv.creation_host creation_time;
Printf.sprintf "LV Status %s" (if List.mem Lvm.Lv.Status.Visible lv.Lvm.Lv.status then "available" else "");
Printf.sprintf "# open uknown";
Printf.sprintf "LV Size %Lds" size;
Printf.sprintf "Current LE %Ld" (Lvm.Lv.size_in_extents lv);
Printf.sprintf "Segments %d" (List.length lv.Lvm.Lv.segments);
Printf.sprintf "Allocation inherit";
Printf.sprintf "Read ahead sectors auto";
- currently set to 256
- currently set to 256
*)
] @ (match device with
| Some device -> [ Printf.sprintf "Block device %s" device ]
| None -> []) @ [
"";
] in
Lwt_list.iter_s (fun line -> stdout " %s" line) lines
let print_colon vg lv =
let sectors = Int64.mul vg.Lvm.Vg.extent_size (Lvm.Lv.size_in_extents lv) in
let majorminor =
let module Devmapper = (val !dm: S.RETRYMAPPER) in
let name = Mapper.name_of vg.Lvm.Vg.name lv.Lvm.Lv.name in
Devmapper.stat name >>= fun s ->
match s with
| Some info ->
Lwt.return (Int32.to_string info.Devmapper.major, Int32.to_string info.Devmapper.minor)
| None ->
Lwt.return ("-1", "-1") in
majorminor >>= fun (major,minor) ->
let parts = [
Printf.sprintf "/dev/%s/%s" vg.Lvm.Vg.name lv.Lvm.Lv.name;
vg.Lvm.Vg.name;
major;
minor;
] in
stdout " %s" (String.concat ":" parts)
let lvdisplay copts colon (vg_name,lv_display_opt) =
let open Xenvm_common in
let t =
get_vg_info_t copts vg_name >>= fun info ->
set_uri copts info;
Client.get () >>= fun vg ->
let print = if colon then print_colon else print_verbose in
let to_print =
Lvm.Vg.LVs.bindings vg.Lvm.Vg.lvs
only interested in the LV , not the i d
|> List.filter (function { Lvm.Lv.name } -> match lv_display_opt with
| None -> true
| Some lv' when lv' = name -> true
| _ -> false
) in
Lwt_list.iter_s (print vg) to_print
>>= fun () ->
if to_print = [] then failwith "Failed to find any matching logical volumes";
Lwt.return () in
Lwt_main.run t
let lvdisplay_cmd =
let doc = "report information about logical volumes" in
let man = [
`S "DESCRIPTION";
`P "lvdisplay produces formatted output about logical volumes";
] in
let colon_arg =
let doc = "Print in terse colon-separated form" in
Arg.(value & flag & info ["colon";"c"] ~doc) in
Term.(pure lvdisplay $ Xenvm_common.copts_t $ colon_arg $ Xenvm_common.name_arg),
Term.info "lvdisplay" ~sdocs:"COMMON OPTIONS" ~doc ~man
|
504152a546bff4b1bf1d6e32334ccc167d85b24aaa820272e2bcff4236083897 | chordify/HarmTrace-Base | General.hs | {-# OPTIONS_GHC -Wall #-}
# LANGUAGE FlexibleContexts #
--------------------------------------------------------------------------------
-- |
Module : HarmTrace . Base . . General
Copyright : ( c ) 2012 - -2016 , Chordify BV
License : LGPL-3
--
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- Summary: Some general parsing utilities used for parsing textual chord
-- representations.
--------------------------------------------------------------------------------
module HarmTrace.Base.Parse.General ( -- * Top level parsers
parseData
, parseDataWithErrors
, parseDataSafe
-- * Some general parsers
, pString
, pLineEnd
, pManyTill
-- Re-exporting the uu-parsinglib
, module Text.ParserCombinators.UU
, module Text.ParserCombinators.UU.Utils
, module Text.ParserCombinators.UU.BasicInstances
, module Data . ListLike . Base
) where
import Text.ParserCombinators.UU
import Text.ParserCombinators.UU.Utils hiding ( pSpaces )
import Text.ParserCombinators.UU.BasicInstances hiding ( IsLocationUpdatedBy )
import Data.ListLike.Base ( ListLike )
import Data.List ( intersperse )
--------------------------------------------------------------------------------
-- A collection of parsing functions used by parsers throughout the project
--------------------------------------------------------------------------------
-- | This is identical to 'parseData' however it will throw an 'error' when
-- the the list with parsing errors is not empty. No, this will not make your
-- program more \safe\. However, in certain cases you really want to be sure
-- that parsing has finished without errors. In those cases you should use
-- 'parseDataSafe'.
parseDataSafe :: (ListLike s a, Show a, Show s) =>
P (Str a s LineColPos) b -> s -> b
parseDataSafe p inp = case parseDataWithErrors p inp of
(dat, [] ) -> dat
(_ , err) -> error ("HarmTrace.Base.Parsing: a parsing"
++ " function did not finish without errors. While"
++ " parsing the data starting with:\n"
++ (take 80 $ show inp)
++ "\nThe following errors were encountered:\n"
++ (concat . intersperse "\n" . take 50
. map show $ err))
-- | Top-level parser that ignores error-reporting, regardless of there were
-- error in the parse
parseData :: (ListLike s a, Show a) => P (Str a s LineColPos) b -> s -> b
parseData p inp = fst ( parseDataWithErrors p inp )
-- | Top-level parser that returns both the result as well as a (possibly empty)
-- list of error-corrections.
parseDataWithErrors :: (ListLike s a, Show a)
=> P (Str a s LineColPos) b -> s -> (b, [Error LineColPos])
parseDataWithErrors p inp = (parse ( (,) <$> p <*> pEnd)
(createStr (LineColPos 0 0 0) inp))
-- | Parses a specific string
pString :: (ListLike state a, IsLocationUpdatedBy loc a, Show a, Eq a)
=> [a] -> P (Str a state loc) [a]
# INLINABLE pString #
pString s = foldr (\a b -> (:) <$> a <*> b) (pure []) (map pSym s)
-- | Parses UNIX and DOS/WINDOWS line endings including trailing whitespace
pLineEnd :: Parser String
pLineEnd = pString "\n" <|> pString "\r\n" <|> pString " " <|> pString "\t"
| Parses an arbitrary times the first parsing combinator until the parsing
second parsing combinator is encountered . The result of the second parsing
-- combinator is ignored.
pManyTill :: P st a -> P st b -> P st [a]
pManyTill p end = [] <$ end
<<|>
(:) <$> p <*> pManyTill p end
| null | https://raw.githubusercontent.com/chordify/HarmTrace-Base/cd1a0651ec29f08b1d8328f20e8569cb358587d8/src/HarmTrace/Base/Parse/General.hs | haskell | # OPTIONS_GHC -Wall #
------------------------------------------------------------------------------
|
Maintainer :
Stability : experimental
Portability : non-portable
Summary: Some general parsing utilities used for parsing textual chord
representations.
------------------------------------------------------------------------------
* Top level parsers
* Some general parsers
Re-exporting the uu-parsinglib
------------------------------------------------------------------------------
A collection of parsing functions used by parsers throughout the project
------------------------------------------------------------------------------
| This is identical to 'parseData' however it will throw an 'error' when
the the list with parsing errors is not empty. No, this will not make your
program more \safe\. However, in certain cases you really want to be sure
that parsing has finished without errors. In those cases you should use
'parseDataSafe'.
| Top-level parser that ignores error-reporting, regardless of there were
error in the parse
| Top-level parser that returns both the result as well as a (possibly empty)
list of error-corrections.
| Parses a specific string
| Parses UNIX and DOS/WINDOWS line endings including trailing whitespace
combinator is ignored. | # LANGUAGE FlexibleContexts #
Module : HarmTrace . Base . . General
Copyright : ( c ) 2012 - -2016 , Chordify BV
License : LGPL-3
parseData
, parseDataWithErrors
, parseDataSafe
, pString
, pLineEnd
, pManyTill
, module Text.ParserCombinators.UU
, module Text.ParserCombinators.UU.Utils
, module Text.ParserCombinators.UU.BasicInstances
, module Data . ListLike . Base
) where
import Text.ParserCombinators.UU
import Text.ParserCombinators.UU.Utils hiding ( pSpaces )
import Text.ParserCombinators.UU.BasicInstances hiding ( IsLocationUpdatedBy )
import Data.ListLike.Base ( ListLike )
import Data.List ( intersperse )
parseDataSafe :: (ListLike s a, Show a, Show s) =>
P (Str a s LineColPos) b -> s -> b
parseDataSafe p inp = case parseDataWithErrors p inp of
(dat, [] ) -> dat
(_ , err) -> error ("HarmTrace.Base.Parsing: a parsing"
++ " function did not finish without errors. While"
++ " parsing the data starting with:\n"
++ (take 80 $ show inp)
++ "\nThe following errors were encountered:\n"
++ (concat . intersperse "\n" . take 50
. map show $ err))
parseData :: (ListLike s a, Show a) => P (Str a s LineColPos) b -> s -> b
parseData p inp = fst ( parseDataWithErrors p inp )
parseDataWithErrors :: (ListLike s a, Show a)
=> P (Str a s LineColPos) b -> s -> (b, [Error LineColPos])
parseDataWithErrors p inp = (parse ( (,) <$> p <*> pEnd)
(createStr (LineColPos 0 0 0) inp))
pString :: (ListLike state a, IsLocationUpdatedBy loc a, Show a, Eq a)
=> [a] -> P (Str a state loc) [a]
# INLINABLE pString #
pString s = foldr (\a b -> (:) <$> a <*> b) (pure []) (map pSym s)
pLineEnd :: Parser String
pLineEnd = pString "\n" <|> pString "\r\n" <|> pString " " <|> pString "\t"
| Parses an arbitrary times the first parsing combinator until the parsing
second parsing combinator is encountered . The result of the second parsing
pManyTill :: P st a -> P st b -> P st [a]
pManyTill p end = [] <$ end
<<|>
(:) <$> p <*> pManyTill p end
|
32446b423960194547372042020038ea368bbf01e99424f487424c41aad1bb73 | levex/haskell-doom | Language.hs | # LANGUAGE KindSignatures #
# LANGUAGE ExistentialQuantification #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
module Graphics.Shader.Language where
import Graphics.Shader.Types
import Data.List (intercalate)
import GHC.TypeLits
import Data.Proxy
data Exp
= Var String
| EScalar Double
| forall t. Expression t => EIndex t Int
| forall t1 t2. (Expression t1, Expression t2) => Combine t1 t2
| forall t. (Expression t) => Wrap t
| FuncApp String [Exp]
| Mul Exp Exp
| Add Exp Exp
| Negate Exp
| Abs Exp
| Signum Exp
| forall t. (Expression t) => Assign Exp t
| forall t. (Expression t, ShowType t) => Define t
instance Num Exp where
(*) = Mul
(+) = Add
abs = Abs
signum = Signum
fromInteger = EScalar . fromInteger
negate (Negate n) = n
negate n = Negate n
instance Show Exp where
show (Var name)
= name
show (EIndex e i)
= show e ++ "[" ++ show i ++ "]"
show (Combine e1 e2)
= e1s ++ ", " ++ e2s
where e1s = case toExpression e1 of
Combine e1' e1''
-> show e1' ++ ", " ++ show e1''
_ -> show e1
e2s = case toExpression e2 of
Combine e2' e2''
-> show e2' ++ ", " ++ show e2''
_ -> show e2
show (FuncApp funcname es)
= funcname ++ "(" ++ intercalate ", " (map show es) ++ ")"
show (Wrap e)
= show e
show (Mul e1 e2)
= show e1 ++ " * " ++ show e2
show (Add e1 e2)
= show e1 ++ " + " ++ show e2
show (Assign e1 e2)
= show e1 ++ " = " ++ show e2
show (Define e)
= showType e ++ " " ++ show e
show (EScalar s)
= show s
show (Abs e)
= "abs(" ++ show e ++ ")"
show (Signum e)
= "signum(" ++ show e ++ ")"
show (Negate s)
= "-" ++ show s
class Show a => Expression a where
fromExpression :: Exp -> a
toExpression :: a -> Exp
class ShowType a where
showType :: a -> String
data Scalar
= Scalar Exp
instance ShowType Scalar where
showType _
= "float"
instance Show Scalar where
show (Scalar e)
= show e
data Vec (dim :: Nat)
= Vec Exp
instance (KnownNat n) => ShowType (Vec n) where
showType (Vec _)
= "vec" ++ dim
where dim = show $ natVal (Proxy :: Proxy n)
instance KnownNat n => Show (Vec n) where
show vec@(Vec expr)
= case expr of
expr'@Combine{} -> w expr'
_ -> show expr
where dim = natVal (Proxy :: Proxy n)
w e = case dim of
1 -> show e
_ -> showType vec ++ "(" ++ show e ++ ")"
data Mat (rows :: Nat) (cols :: Nat)
= Mat Exp
instance (KnownNat r, KnownNat c) => ShowType (Mat r c) where
showType (Mat _)
= "mat" ++ rdim ++ "x" ++ cdim
where rdim = show $ natVal (Proxy :: Proxy r)
cdim = show $ natVal (Proxy :: Proxy r)
instance (KnownNat r, KnownNat c) => Show (Mat r c) where
show mat@(Mat expr)
= case expr of
expr'@Combine{} -> w expr'
_ -> show expr
where w e = showType mat ++ "(" ++ show e ++ ")"
data Sampler (d :: Nat)
= Sampler Exp
deriving Show
instance Expression Scalar where
fromExpression = Scalar
toExpression (Scalar p) = p
instance (Show (Vec d), KnownNat d) => Expression (Vec d) where
fromExpression = Vec
toExpression (Vec e) = e
instance (Show (Mat r c), KnownNat r, KnownNat c) => Expression (Mat r c) where
fromExpression = Mat
toExpression (Mat e) = e
instance (Show (Sampler n), KnownNat n) => Expression (Sampler n) where
fromExpression = Sampler
toExpression (Sampler e) = e
-- ARGUMENT TYPES
type family FromArg a where
FromArg 'Float = Scalar
FromArg 'Vec2 = Vec 2
FromArg 'Vec3 = Vec 3
FromArg 'Vec4 = Vec 4
FromArg 'Mat1 = Mat 1 1
FromArg 'Mat2 = Mat 2 2
FromArg 'Mat3 = Mat 3 3
FromArg 'Mat4 = Mat 4 4
FromArg 'Sampler2D = Sampler 2
| null | https://raw.githubusercontent.com/levex/haskell-doom/30ec4e0c5fa6bf10cbce99e27e3d7027afbdb980/src/Graphics/Shader/Language.hs | haskell | ARGUMENT TYPES | # LANGUAGE KindSignatures #
# LANGUAGE ExistentialQuantification #
# LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
module Graphics.Shader.Language where
import Graphics.Shader.Types
import Data.List (intercalate)
import GHC.TypeLits
import Data.Proxy
data Exp
= Var String
| EScalar Double
| forall t. Expression t => EIndex t Int
| forall t1 t2. (Expression t1, Expression t2) => Combine t1 t2
| forall t. (Expression t) => Wrap t
| FuncApp String [Exp]
| Mul Exp Exp
| Add Exp Exp
| Negate Exp
| Abs Exp
| Signum Exp
| forall t. (Expression t) => Assign Exp t
| forall t. (Expression t, ShowType t) => Define t
instance Num Exp where
(*) = Mul
(+) = Add
abs = Abs
signum = Signum
fromInteger = EScalar . fromInteger
negate (Negate n) = n
negate n = Negate n
instance Show Exp where
show (Var name)
= name
show (EIndex e i)
= show e ++ "[" ++ show i ++ "]"
show (Combine e1 e2)
= e1s ++ ", " ++ e2s
where e1s = case toExpression e1 of
Combine e1' e1''
-> show e1' ++ ", " ++ show e1''
_ -> show e1
e2s = case toExpression e2 of
Combine e2' e2''
-> show e2' ++ ", " ++ show e2''
_ -> show e2
show (FuncApp funcname es)
= funcname ++ "(" ++ intercalate ", " (map show es) ++ ")"
show (Wrap e)
= show e
show (Mul e1 e2)
= show e1 ++ " * " ++ show e2
show (Add e1 e2)
= show e1 ++ " + " ++ show e2
show (Assign e1 e2)
= show e1 ++ " = " ++ show e2
show (Define e)
= showType e ++ " " ++ show e
show (EScalar s)
= show s
show (Abs e)
= "abs(" ++ show e ++ ")"
show (Signum e)
= "signum(" ++ show e ++ ")"
show (Negate s)
= "-" ++ show s
class Show a => Expression a where
fromExpression :: Exp -> a
toExpression :: a -> Exp
class ShowType a where
showType :: a -> String
data Scalar
= Scalar Exp
instance ShowType Scalar where
showType _
= "float"
instance Show Scalar where
show (Scalar e)
= show e
data Vec (dim :: Nat)
= Vec Exp
instance (KnownNat n) => ShowType (Vec n) where
showType (Vec _)
= "vec" ++ dim
where dim = show $ natVal (Proxy :: Proxy n)
instance KnownNat n => Show (Vec n) where
show vec@(Vec expr)
= case expr of
expr'@Combine{} -> w expr'
_ -> show expr
where dim = natVal (Proxy :: Proxy n)
w e = case dim of
1 -> show e
_ -> showType vec ++ "(" ++ show e ++ ")"
data Mat (rows :: Nat) (cols :: Nat)
= Mat Exp
instance (KnownNat r, KnownNat c) => ShowType (Mat r c) where
showType (Mat _)
= "mat" ++ rdim ++ "x" ++ cdim
where rdim = show $ natVal (Proxy :: Proxy r)
cdim = show $ natVal (Proxy :: Proxy r)
instance (KnownNat r, KnownNat c) => Show (Mat r c) where
show mat@(Mat expr)
= case expr of
expr'@Combine{} -> w expr'
_ -> show expr
where w e = showType mat ++ "(" ++ show e ++ ")"
data Sampler (d :: Nat)
= Sampler Exp
deriving Show
instance Expression Scalar where
fromExpression = Scalar
toExpression (Scalar p) = p
instance (Show (Vec d), KnownNat d) => Expression (Vec d) where
fromExpression = Vec
toExpression (Vec e) = e
instance (Show (Mat r c), KnownNat r, KnownNat c) => Expression (Mat r c) where
fromExpression = Mat
toExpression (Mat e) = e
instance (Show (Sampler n), KnownNat n) => Expression (Sampler n) where
fromExpression = Sampler
toExpression (Sampler e) = e
type family FromArg a where
FromArg 'Float = Scalar
FromArg 'Vec2 = Vec 2
FromArg 'Vec3 = Vec 3
FromArg 'Vec4 = Vec 4
FromArg 'Mat1 = Mat 1 1
FromArg 'Mat2 = Mat 2 2
FromArg 'Mat3 = Mat 3 3
FromArg 'Mat4 = Mat 4 4
FromArg 'Sampler2D = Sampler 2
|
fc105bb6310361f63c14f40037e0d0596e8d1b68e8c84fea21fcbc3918665c34 | synduce/Synduce | maxcount.ml | * @synduce -s 2 -NB
type 'a clist =
| Single of 'a
| Concat of 'a clist * 'a clist
type 'a list =
| Elt of 'a
| Cons of 'a * 'a list
let rec maxcount = function
| Elt a -> a, 1
| Cons (hd, tl) ->
let amax, acnt = maxcount tl in
max amax hd, if hd > amax then 1 else acnt + if hd = amax then 1 else 0
;;
let rec clist_to_list = function
| Single a -> Elt a
| Concat (x, y) -> dec y x
and dec l1 = function
| Single a -> Cons (a, clist_to_list l1)
| Concat (x, y) -> dec (Concat (y, l1)) x
;;
let rec hom = function
| Single a -> [%synt f0]
| Concat (x, y) -> [%synt join]
;;
assert (hom = clist_to_list @@ maxcount)
| null | https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/list/maxcount.ml | ocaml | * @synduce -s 2 -NB
type 'a clist =
| Single of 'a
| Concat of 'a clist * 'a clist
type 'a list =
| Elt of 'a
| Cons of 'a * 'a list
let rec maxcount = function
| Elt a -> a, 1
| Cons (hd, tl) ->
let amax, acnt = maxcount tl in
max amax hd, if hd > amax then 1 else acnt + if hd = amax then 1 else 0
;;
let rec clist_to_list = function
| Single a -> Elt a
| Concat (x, y) -> dec y x
and dec l1 = function
| Single a -> Cons (a, clist_to_list l1)
| Concat (x, y) -> dec (Concat (y, l1)) x
;;
let rec hom = function
| Single a -> [%synt f0]
| Concat (x, y) -> [%synt join]
;;
assert (hom = clist_to_list @@ maxcount)
| |
5cc98c1f49f79763f26c1dee00ff0bc8630d70852b2930afa54c0f9c8563f262 | herbelin/coq-hh | libnames.mli | (************************************************************************)
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 *)
(************************************************************************)
open Pp
open Util
open Names
open Term
open Mod_subst
* { 6 Global reference is a kernel side type for all references together }
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val isConstRef : global_reference -> bool
val isIndRef : global_reference -> bool
val isConstructRef : global_reference -> bool
val eq_gr : global_reference -> global_reference -> bool
val canonical_gr : global_reference -> global_reference
val destVarRef : global_reference -> variable
val destConstRef : global_reference -> constant
val destIndRef : global_reference -> inductive
val destConstructRef : global_reference -> constructor
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
(** Turn a global reference into a construction *)
val constr_of_global : global_reference -> constr
(** Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference *)
val global_of_constr : constr -> global_reference
* Obsolete synonyms for constr_of_global and global_of_constr
val constr_of_reference : global_reference -> constr
val reference_of_constr : constr -> global_reference
module RefOrdered : sig
type t = global_reference
val compare : global_reference -> global_reference -> int
end
module Refset : Set.S with type elt = global_reference
module Refmap : Map.S with type key = global_reference
* { 6 Extended global references }
type syndef_name = kernel_name
type extended_global_reference =
| TrueGlobal of global_reference
| SynDef of syndef_name
* { 6 Dirpaths }
val pr_dirpath : dir_path -> Pp.std_ppcmds
val dirpath_of_string : string -> dir_path
val string_of_dirpath : dir_path -> string
(** Pop the suffix of a [dir_path] *)
val pop_dirpath : dir_path -> dir_path
(** Pop the suffix n times *)
val pop_dirpath_n : int -> dir_path -> dir_path
(** Give the immediate prefix and basename of a [dir_path] *)
val split_dirpath : dir_path -> dir_path * identifier
val add_dirpath_suffix : dir_path -> module_ident -> dir_path
val add_dirpath_prefix : module_ident -> dir_path -> dir_path
val chop_dirpath : int -> dir_path -> dir_path * dir_path
val append_dirpath : dir_path -> dir_path -> dir_path
val drop_dirpath_prefix : dir_path -> dir_path -> dir_path
val is_dirpath_prefix_of : dir_path -> dir_path -> bool
module Dirset : Set.S with type elt = dir_path
module Dirmap : Map.S with type key = dir_path
* { 6 Full paths are { e absolute } paths of declarations }
type full_path
(** Constructors of [full_path] *)
val make_path : dir_path -> identifier -> full_path
(** Destructors of [full_path] *)
val repr_path : full_path -> dir_path * identifier
val dirpath : full_path -> dir_path
val basename : full_path -> identifier
(** Parsing and printing of section path as ["coq_root.module.id"] *)
val path_of_string : string -> full_path
val string_of_path : full_path -> string
val pr_path : full_path -> std_ppcmds
module Spmap : Map.S with type key = full_path
val restrict_path : int -> full_path -> full_path
* { 6 Temporary function to brutally form kernel names from section paths }
val encode_mind : dir_path -> identifier -> mutual_inductive
val decode_mind : mutual_inductive -> dir_path * identifier
val encode_con : dir_path -> identifier -> constant
val decode_con : constant -> dir_path * identifier
* { 6 ... }
(** A [qualid] is a partially qualified ident; it includes fully
qualified names (= absolute names) and all intermediate partial
qualifications of absolute names, including single identifiers.
The [qualid] are used to access the name table. *)
type qualid
val make_qualid : dir_path -> identifier -> qualid
val repr_qualid : qualid -> dir_path * identifier
val pr_qualid : qualid -> std_ppcmds
val string_of_qualid : qualid -> string
val qualid_of_string : string -> qualid
(** Turns an absolute name, a dirpath, or an identifier into a
qualified name denoting the same name *)
val qualid_of_path : full_path -> qualid
val qualid_of_dirpath : dir_path -> qualid
val qualid_of_ident : identifier -> qualid
(** Both names are passed to objects: a "semantic" [kernel_name], which
can be substituted and a "syntactic" [full_path] which can be printed
*)
type object_name = full_path * kernel_name
type object_prefix = dir_path * (module_path * dir_path)
val make_oname : object_prefix -> identifier -> object_name
* to this type are mapped [ dir_path ] 's in the nametab
type global_dir_reference =
| DirOpenModule of object_prefix
| DirOpenModtype of object_prefix
| DirOpenSection of object_prefix
| DirModule of object_prefix
| DirClosedSection of dir_path
(** this won't last long I hope! *)
* { 6 ... }
(** A [reference] is the user-level notion of name. It denotes either a
global name (referred either by a qualified name or by a single
name) or a variable *)
type reference =
| Qualid of qualid located
| Ident of identifier located
val qualid_of_reference : reference -> qualid located
val string_of_reference : reference -> string
val pr_reference : reference -> std_ppcmds
val loc_of_reference : reference -> loc
* { 6 Popping one level of section in global names }
val pop_con : constant -> constant
val pop_kn : mutual_inductive-> mutual_inductive
val pop_global_reference : global_reference -> global_reference
(** Deprecated synonyms *)
val make_short_qualid : identifier -> qualid (** = qualid_of_ident *)
val qualid_of_sp : full_path -> qualid (** = qualid_of_path *)
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/library/libnames.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* Turn a global reference into a construction
* Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference
* Pop the suffix of a [dir_path]
* Pop the suffix n times
* Give the immediate prefix and basename of a [dir_path]
* Constructors of [full_path]
* Destructors of [full_path]
* Parsing and printing of section path as ["coq_root.module.id"]
* A [qualid] is a partially qualified ident; it includes fully
qualified names (= absolute names) and all intermediate partial
qualifications of absolute names, including single identifiers.
The [qualid] are used to access the name table.
* Turns an absolute name, a dirpath, or an identifier into a
qualified name denoting the same name
* Both names are passed to objects: a "semantic" [kernel_name], which
can be substituted and a "syntactic" [full_path] which can be printed
* this won't last long I hope!
* A [reference] is the user-level notion of name. It denotes either a
global name (referred either by a qualified name or by a single
name) or a variable
* Deprecated synonyms
* = qualid_of_ident
* = qualid_of_path | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Util
open Names
open Term
open Mod_subst
* { 6 Global reference is a kernel side type for all references together }
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val isConstRef : global_reference -> bool
val isIndRef : global_reference -> bool
val isConstructRef : global_reference -> bool
val eq_gr : global_reference -> global_reference -> bool
val canonical_gr : global_reference -> global_reference
val destVarRef : global_reference -> variable
val destConstRef : global_reference -> constant
val destIndRef : global_reference -> inductive
val destConstructRef : global_reference -> constructor
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
val constr_of_global : global_reference -> constr
val global_of_constr : constr -> global_reference
* Obsolete synonyms for constr_of_global and global_of_constr
val constr_of_reference : global_reference -> constr
val reference_of_constr : constr -> global_reference
module RefOrdered : sig
type t = global_reference
val compare : global_reference -> global_reference -> int
end
module Refset : Set.S with type elt = global_reference
module Refmap : Map.S with type key = global_reference
* { 6 Extended global references }
type syndef_name = kernel_name
type extended_global_reference =
| TrueGlobal of global_reference
| SynDef of syndef_name
* { 6 Dirpaths }
val pr_dirpath : dir_path -> Pp.std_ppcmds
val dirpath_of_string : string -> dir_path
val string_of_dirpath : dir_path -> string
val pop_dirpath : dir_path -> dir_path
val pop_dirpath_n : int -> dir_path -> dir_path
val split_dirpath : dir_path -> dir_path * identifier
val add_dirpath_suffix : dir_path -> module_ident -> dir_path
val add_dirpath_prefix : module_ident -> dir_path -> dir_path
val chop_dirpath : int -> dir_path -> dir_path * dir_path
val append_dirpath : dir_path -> dir_path -> dir_path
val drop_dirpath_prefix : dir_path -> dir_path -> dir_path
val is_dirpath_prefix_of : dir_path -> dir_path -> bool
module Dirset : Set.S with type elt = dir_path
module Dirmap : Map.S with type key = dir_path
* { 6 Full paths are { e absolute } paths of declarations }
type full_path
val make_path : dir_path -> identifier -> full_path
val repr_path : full_path -> dir_path * identifier
val dirpath : full_path -> dir_path
val basename : full_path -> identifier
val path_of_string : string -> full_path
val string_of_path : full_path -> string
val pr_path : full_path -> std_ppcmds
module Spmap : Map.S with type key = full_path
val restrict_path : int -> full_path -> full_path
* { 6 Temporary function to brutally form kernel names from section paths }
val encode_mind : dir_path -> identifier -> mutual_inductive
val decode_mind : mutual_inductive -> dir_path * identifier
val encode_con : dir_path -> identifier -> constant
val decode_con : constant -> dir_path * identifier
* { 6 ... }
type qualid
val make_qualid : dir_path -> identifier -> qualid
val repr_qualid : qualid -> dir_path * identifier
val pr_qualid : qualid -> std_ppcmds
val string_of_qualid : qualid -> string
val qualid_of_string : string -> qualid
val qualid_of_path : full_path -> qualid
val qualid_of_dirpath : dir_path -> qualid
val qualid_of_ident : identifier -> qualid
type object_name = full_path * kernel_name
type object_prefix = dir_path * (module_path * dir_path)
val make_oname : object_prefix -> identifier -> object_name
* to this type are mapped [ dir_path ] 's in the nametab
type global_dir_reference =
| DirOpenModule of object_prefix
| DirOpenModtype of object_prefix
| DirOpenSection of object_prefix
| DirModule of object_prefix
| DirClosedSection of dir_path
* { 6 ... }
type reference =
| Qualid of qualid located
| Ident of identifier located
val qualid_of_reference : reference -> qualid located
val string_of_reference : reference -> string
val pr_reference : reference -> std_ppcmds
val loc_of_reference : reference -> loc
* { 6 Popping one level of section in global names }
val pop_con : constant -> constant
val pop_kn : mutual_inductive-> mutual_inductive
val pop_global_reference : global_reference -> global_reference
|
300a01bbe5274d5356b3c45be861edab69e2c4a2fb8ba0c7f8f99e1103202baa | prepor/condo | system_test.ml | open! Core.Std
open! Async.Std
open! Import
module S = System
let%expect_test "place snapshot" =
let snapshot = Instance.init_snaphot () |> Instance.snapshot_to_yojson in
let%bind s = system () in
let%bind () = S.place_snapshot s ~name:"nginx" ~snapshot in
print_endline (In_channel.read_all "/tmp/condo_state");
[%expect {|
Can't read state file, initialized the new one
{"nginx":["Init"]} |}]
| null | https://raw.githubusercontent.com/prepor/condo/b9a16829e6ffef10df2fefdadf143b56d33f0b97/test/system_test.ml | ocaml | open! Core.Std
open! Async.Std
open! Import
module S = System
let%expect_test "place snapshot" =
let snapshot = Instance.init_snaphot () |> Instance.snapshot_to_yojson in
let%bind s = system () in
let%bind () = S.place_snapshot s ~name:"nginx" ~snapshot in
print_endline (In_channel.read_all "/tmp/condo_state");
[%expect {|
Can't read state file, initialized the new one
{"nginx":["Init"]} |}]
| |
98da21e0647e1e18cb3445de009de334c00c324ed0e495ec0a3608cf5c7af250 | aryx/fork-efuns | scroll.ml | (*s: features/scroll.ml *)
(*s: copyright header2 *)
(***********************************************************************)
(* *)
xlib for
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
(*e: copyright header2 *)
open Efuns
open Move
(*****************************************************************************)
(* Screen *)
(*****************************************************************************)
(*s: function [[Simple.forward_screen]] *)
let forward_screen frame =
frame.frm_force_start <- true;
frame.frm_redraw <- true;
frame.frm_y_offset <- frame.frm_y_offset + frame.frm_height - 2
(*e: function [[Simple.forward_screen]] *)
(*s: function [[Simple.backward_screen]] *)
let backward_screen frame =
frame.frm_force_start <- true;
frame.frm_redraw <- true;
frame.frm_y_offset <- frame.frm_y_offset - frame.frm_height + 2
(*e: function [[Simple.backward_screen]] *)
(*****************************************************************************)
Scroll
(*****************************************************************************)
(*s: function [[Simple.scroll_line]] *)
let scroll_line frame n =
frame.frm_force_start <- true;
frame.frm_redraw <- true;
frame.frm_y_offset <- frame.frm_y_offset + n
(*e: function [[Simple.scroll_line]] *)
s : function [ [ ] ]
let scroll_down frame =
scroll_line frame 1;
forward_line frame
[@@interactive]
e : function [ [ ] ]
s : function [ [ Simple.scroll_up ] ]
let scroll_up frame =
scroll_line frame (-1);
backward_line frame
[@@interactive]
e : function [ [ Simple.scroll_up ] ]
s : function [ [ Simple.scroll_other_up ] ]
let scroll_other_up frame =
Window.next scroll_up frame.frm_window
[@@interactive]
e : function [ [ Simple.scroll_other_up ] ]
s : function [ [ Simple.scroll_other_down ] ]
let scroll_other_down frame =
Window.next scroll_down frame.frm_window
[@@interactive]
e : function [ [ Simple.scroll_other_down ] ]
(*s: function [[Simple.recenter]] *)
let recenter frame =
let (_, text, point) = Frame.buf_text_point frame in
frame.frm_force_start <- true;
frame.frm_redraw <- true;
Text.goto_point text frame.frm_start point;
frame.frm_y_offset <- - frame.frm_height/2
[@@interactive]
(*e: function [[Simple.recenter]] *)
(*e: features/scroll.ml *)
| null | https://raw.githubusercontent.com/aryx/fork-efuns/8f2f8f66879d45e26ecdca0033f9c92aec2b783d/features/scroll.ml | ocaml | s: features/scroll.ml
s: copyright header2
*********************************************************************
*********************************************************************
e: copyright header2
***************************************************************************
Screen
***************************************************************************
s: function [[Simple.forward_screen]]
e: function [[Simple.forward_screen]]
s: function [[Simple.backward_screen]]
e: function [[Simple.backward_screen]]
***************************************************************************
***************************************************************************
s: function [[Simple.scroll_line]]
e: function [[Simple.scroll_line]]
s: function [[Simple.recenter]]
e: function [[Simple.recenter]]
e: features/scroll.ml | xlib for
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Efuns
open Move
let forward_screen frame =
frame.frm_force_start <- true;
frame.frm_redraw <- true;
frame.frm_y_offset <- frame.frm_y_offset + frame.frm_height - 2
let backward_screen frame =
frame.frm_force_start <- true;
frame.frm_redraw <- true;
frame.frm_y_offset <- frame.frm_y_offset - frame.frm_height + 2
Scroll
let scroll_line frame n =
frame.frm_force_start <- true;
frame.frm_redraw <- true;
frame.frm_y_offset <- frame.frm_y_offset + n
s : function [ [ ] ]
let scroll_down frame =
scroll_line frame 1;
forward_line frame
[@@interactive]
e : function [ [ ] ]
s : function [ [ Simple.scroll_up ] ]
let scroll_up frame =
scroll_line frame (-1);
backward_line frame
[@@interactive]
e : function [ [ Simple.scroll_up ] ]
s : function [ [ Simple.scroll_other_up ] ]
let scroll_other_up frame =
Window.next scroll_up frame.frm_window
[@@interactive]
e : function [ [ Simple.scroll_other_up ] ]
s : function [ [ Simple.scroll_other_down ] ]
let scroll_other_down frame =
Window.next scroll_down frame.frm_window
[@@interactive]
e : function [ [ Simple.scroll_other_down ] ]
let recenter frame =
let (_, text, point) = Frame.buf_text_point frame in
frame.frm_force_start <- true;
frame.frm_redraw <- true;
Text.goto_point text frame.frm_start point;
frame.frm_y_offset <- - frame.frm_height/2
[@@interactive]
|
8c28a1bdb95ae7a943523577200dba72184f278e7eaf3f65cdb31a629fb6e63f | clash-lang/ghc-tcplugins-extra | Constraint.hs | module Internal.Constraint (newGiven, flatToCt, overEvidencePredType) where
import GhcApi.GhcPlugins
import GhcApi.Constraint
(Ct(..), CtEvidence(..), CtLoc, ctLoc, ctEvId, mkNonCanonical)
import Panic (panicDoc)
import TcType (TcType)
import Constraint (QCInst(..))
import TcEvidence (EvTerm(..))
import TcPluginM (TcPluginM)
import qualified TcPluginM (newGiven)
-- | Create a new [G]iven constraint, with the supplied evidence. This must not
-- be invoked from 'tcPluginInit' or 'tcPluginStop', or it will panic.
newGiven :: CtLoc -> PredType -> EvTerm -> TcPluginM CtEvidence
newGiven loc pty (EvExpr ev) = TcPluginM.newGiven loc pty ev
newGiven _ _ ev = panicDoc "newGiven: not an EvExpr: " (ppr ev)
flatToCt :: [((TcTyVar,TcType),Ct)] -> Maybe Ct
flatToCt [((_,lhs),ct),((_,rhs),_)]
= Just
$ mkNonCanonical
$ CtGiven (mkPrimEqPred lhs rhs)
(ctEvId ct)
(ctLoc ct)
flatToCt _ = Nothing
-- | Modify the predicate type of the evidence term of a constraint
overEvidencePredType :: (TcType -> TcType) -> Ct -> Ct
overEvidencePredType f (CQuantCan qci) =
let
ev :: CtEvidence
ev = qci_ev qci
in CQuantCan ( qci { qci_ev = ev { ctev_pred = f (ctev_pred ev) } } )
overEvidencePredType f ct =
let
ev :: CtEvidence
ev = cc_ev ct
in ct { cc_ev = ev { ctev_pred = f (ctev_pred ev) } } | null | https://raw.githubusercontent.com/clash-lang/ghc-tcplugins-extra/20a6cc71b6fef6e92bca4eda0abdb776403ceb31/src-ghc-8.8/Internal/Constraint.hs | haskell | | Create a new [G]iven constraint, with the supplied evidence. This must not
be invoked from 'tcPluginInit' or 'tcPluginStop', or it will panic.
| Modify the predicate type of the evidence term of a constraint | module Internal.Constraint (newGiven, flatToCt, overEvidencePredType) where
import GhcApi.GhcPlugins
import GhcApi.Constraint
(Ct(..), CtEvidence(..), CtLoc, ctLoc, ctEvId, mkNonCanonical)
import Panic (panicDoc)
import TcType (TcType)
import Constraint (QCInst(..))
import TcEvidence (EvTerm(..))
import TcPluginM (TcPluginM)
import qualified TcPluginM (newGiven)
newGiven :: CtLoc -> PredType -> EvTerm -> TcPluginM CtEvidence
newGiven loc pty (EvExpr ev) = TcPluginM.newGiven loc pty ev
newGiven _ _ ev = panicDoc "newGiven: not an EvExpr: " (ppr ev)
flatToCt :: [((TcTyVar,TcType),Ct)] -> Maybe Ct
flatToCt [((_,lhs),ct),((_,rhs),_)]
= Just
$ mkNonCanonical
$ CtGiven (mkPrimEqPred lhs rhs)
(ctEvId ct)
(ctLoc ct)
flatToCt _ = Nothing
overEvidencePredType :: (TcType -> TcType) -> Ct -> Ct
overEvidencePredType f (CQuantCan qci) =
let
ev :: CtEvidence
ev = qci_ev qci
in CQuantCan ( qci { qci_ev = ev { ctev_pred = f (ctev_pred ev) } } )
overEvidencePredType f ct =
let
ev :: CtEvidence
ev = cc_ev ct
in ct { cc_ev = ev { ctev_pred = f (ctev_pred ev) } } |
022b43d2950437b13a63e7d08727a43b7a92231e45ce159c4001761dec8ba6a2 | trevorbernard/cljzmq-examples | project.clj | (defproject cljzmq-examples "0.1.0-SNAPSHOT"
:description "zguide examples ported to cljzmq"
:url "-examples"
:license {:name "LGPLv3+"
:url ""}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.zeromq/cljzmq "0.1.4"]])
| null | https://raw.githubusercontent.com/trevorbernard/cljzmq-examples/d76df4b1f07749efa566c4bf8bdd4ec3ca0b26a6/project.clj | clojure | (defproject cljzmq-examples "0.1.0-SNAPSHOT"
:description "zguide examples ported to cljzmq"
:url "-examples"
:license {:name "LGPLv3+"
:url ""}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.zeromq/cljzmq "0.1.4"]])
| |
924d550c17b87260051ab36b4b874cb7f58280adef988a28335828a187cb96ae | AbstractMachinesLab/caramel | ast_helper.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, LexiFi
(* *)
Copyright 2012 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. *)
(* *)
(**************************************************************************)
* Helpers to produce Parsetree fragments
open Asttypes
open Parsetree
open Docstrings
type lid = Longident.t loc
type str = string loc
type loc = Location.t
type attrs = attribute list
let default_loc = ref Location.none
let with_default_loc l f =
let old = !default_loc in
default_loc := l;
try let r = f () in default_loc := old; r
with exn -> default_loc := old; raise exn
module Const = struct
let integer ?suffix i = Pconst_integer (i, suffix)
let int ?suffix i = integer ?suffix (string_of_int i)
let int32 ?(suffix='l') i = integer ~suffix (Int32.to_string i)
let int64 ?(suffix='L') i = integer ~suffix (Int64.to_string i)
let nativeint ?(suffix='n') i = integer ~suffix (Nativeint.to_string i)
let float ?suffix f = Pconst_float (f, suffix)
let char c = Pconst_char c
let string ?quotation_delimiter s = Pconst_string (s, quotation_delimiter)
end
module Typ = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ptyp_desc = d; ptyp_loc = loc; ptyp_attributes = attrs}
let attr d a = {d with ptyp_attributes = d.ptyp_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ptyp_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ptyp_var a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_arrow (a, b, c))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ptyp_tuple a)
let constr ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_constr (a, b))
let object_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_object (a, b))
let class_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_class (a, b))
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_alias (a, b))
let variant ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_variant (a, b, c))
let poly ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_poly (a, b))
let package ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_package (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Ptyp_extension a)
let force_poly t =
match t.ptyp_desc with
| Ptyp_poly _ -> t
| _ -> poly ~loc:t.ptyp_loc [] t (* -> ghost? *)
end
module Pat = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ppat_desc = d; ppat_loc = loc; ppat_attributes = attrs}
let attr d a = {d with ppat_attributes = d.ppat_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ppat_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ppat_var a)
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ppat_alias (a, b))
let constant ?loc ?attrs a = mk ?loc ?attrs (Ppat_constant a)
let interval ?loc ?attrs a b = mk ?loc ?attrs (Ppat_interval (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ppat_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Ppat_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Ppat_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Ppat_record (a, b))
let array ?loc ?attrs a = mk ?loc ?attrs (Ppat_array a)
let or_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_or (a, b))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_constraint (a, b))
let type_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_type a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_lazy a)
let unpack ?loc ?attrs a = mk ?loc ?attrs (Ppat_unpack a)
let exception_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_exception a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Ppat_extension a)
end
module Exp = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pexp_desc = d; pexp_loc = loc; pexp_attributes = attrs}
let attr d a = {d with pexp_attributes = d.pexp_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pexp_ident a)
let constant ?loc ?attrs a = mk ?loc ?attrs (Pexp_constant a)
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_let (a, b, c))
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pexp_fun (a, b, c, d))
let function_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_function a)
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pexp_apply (a, b))
let match_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_match (a, b))
let try_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_try (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Pexp_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Pexp_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Pexp_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Pexp_record (a, b))
let field ?loc ?attrs a b = mk ?loc ?attrs (Pexp_field (a, b))
let setfield ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_setfield (a, b, c))
let array ?loc ?attrs a = mk ?loc ?attrs (Pexp_array a)
let ifthenelse ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_ifthenelse (a, b, c))
let sequence ?loc ?attrs a b = mk ?loc ?attrs (Pexp_sequence (a, b))
let while_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_while (a, b))
let for_ ?loc ?attrs a b c d e = mk ?loc ?attrs (Pexp_for (a, b, c, d, e))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_constraint (a, b))
let coerce ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_coerce (a, b, c))
let send ?loc ?attrs a b = mk ?loc ?attrs (Pexp_send (a, b))
let new_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_new a)
let setinstvar ?loc ?attrs a b = mk ?loc ?attrs (Pexp_setinstvar (a, b))
let override ?loc ?attrs a = mk ?loc ?attrs (Pexp_override a)
let letmodule ?loc ?attrs a b c= mk ?loc ?attrs (Pexp_letmodule (a, b, c))
let assert_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_assert a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_lazy a)
let poly ?loc ?attrs a b = mk ?loc ?attrs (Pexp_poly (a, b))
let object_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_object a)
let newtype ?loc ?attrs a b = mk ?loc ?attrs (Pexp_newtype (a, b))
let pack ?loc ?attrs a = mk ?loc ?attrs (Pexp_pack a)
let open_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_open (a, b, c))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pexp_extension a)
let unreachable ?loc ?attrs () = mk ?loc ?attrs Pexp_unreachable
let case lhs ?guard rhs =
{
pc_lhs = lhs;
pc_guard = guard;
pc_rhs = rhs;
}
end
module Mty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmty_desc = d; pmty_loc = loc; pmty_attributes = attrs}
let attr d a = {d with pmty_attributes = d.pmty_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pmty_ident a)
let alias ?loc ?attrs a = mk ?loc ?attrs (Pmty_alias a)
let signature ?loc ?attrs a = mk ?loc ?attrs (Pmty_signature a)
let functor_ ?loc ?attrs a b c = mk ?loc ?attrs (Pmty_functor (a, b, c))
let with_ ?loc ?attrs a b = mk ?loc ?attrs (Pmty_with (a, b))
let typeof_ ?loc ?attrs a = mk ?loc ?attrs (Pmty_typeof a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmty_extension a)
end
module Mod = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmod_desc = d; pmod_loc = loc; pmod_attributes = attrs}
let attr d a = {d with pmod_attributes = d.pmod_attributes @ [a]}
let ident ?loc ?attrs x = mk ?loc ?attrs (Pmod_ident x)
let structure ?loc ?attrs x = mk ?loc ?attrs (Pmod_structure x)
let functor_ ?loc ?attrs arg arg_ty body =
mk ?loc ?attrs (Pmod_functor (arg, arg_ty, body))
let apply ?loc ?attrs m1 m2 = mk ?loc ?attrs (Pmod_apply (m1, m2))
let constraint_ ?loc ?attrs m mty = mk ?loc ?attrs (Pmod_constraint (m, mty))
let unpack ?loc ?attrs e = mk ?loc ?attrs (Pmod_unpack e)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmod_extension a)
end
module Sig = struct
let mk ?(loc = !default_loc) d = {psig_desc = d; psig_loc = loc}
let value ?loc a = mk ?loc (Psig_value a)
let type_ ?loc rec_flag a = mk ?loc (Psig_type (rec_flag, a))
let type_extension ?loc a = mk ?loc (Psig_typext a)
let exception_ ?loc a = mk ?loc (Psig_exception a)
let module_ ?loc a = mk ?loc (Psig_module a)
let rec_module ?loc a = mk ?loc (Psig_recmodule a)
let modtype ?loc a = mk ?loc (Psig_modtype a)
let open_ ?loc a = mk ?loc (Psig_open a)
let include_ ?loc a = mk ?loc (Psig_include a)
let class_ ?loc a = mk ?loc (Psig_class a)
let class_type ?loc a = mk ?loc (Psig_class_type a)
let extension ?loc ?(attrs = []) a = mk ?loc (Psig_extension (a, attrs))
let attribute ?loc a = mk ?loc (Psig_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
end
module Str = struct
let mk ?(loc = !default_loc) d = {pstr_desc = d; pstr_loc = loc}
let eval ?loc ?(attrs = []) a = mk ?loc (Pstr_eval (a, attrs))
let value ?loc a b = mk ?loc (Pstr_value (a, b))
let primitive ?loc a = mk ?loc (Pstr_primitive a)
let type_ ?loc rec_flag a = mk ?loc (Pstr_type (rec_flag, a))
let type_extension ?loc a = mk ?loc (Pstr_typext a)
let exception_ ?loc a = mk ?loc (Pstr_exception a)
let module_ ?loc a = mk ?loc (Pstr_module a)
let rec_module ?loc a = mk ?loc (Pstr_recmodule a)
let modtype ?loc a = mk ?loc (Pstr_modtype a)
let open_ ?loc a = mk ?loc (Pstr_open a)
let class_ ?loc a = mk ?loc (Pstr_class a)
let class_type ?loc a = mk ?loc (Pstr_class_type a)
let include_ ?loc a = mk ?loc (Pstr_include a)
let extension ?loc ?(attrs = []) a = mk ?loc (Pstr_extension (a, attrs))
let attribute ?loc a = mk ?loc (Pstr_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
end
module Cl = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcl_desc = d;
pcl_loc = loc;
pcl_attributes = attrs;
}
let attr d a = {d with pcl_attributes = d.pcl_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constr (a, b))
let structure ?loc ?attrs a = mk ?loc ?attrs (Pcl_structure a)
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pcl_fun (a, b, c, d))
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pcl_apply (a, b))
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcl_let (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcl_extension a)
end
module Cty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcty_desc = d;
pcty_loc = loc;
pcty_attributes = attrs;
}
let attr d a = {d with pcty_attributes = d.pcty_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcty_constr (a, b))
let signature ?loc ?attrs a = mk ?loc ?attrs (Pcty_signature a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Pcty_arrow (a, b, c))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcty_extension a)
end
module Ctf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pctf_desc = d;
pctf_loc = loc;
pctf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a = mk ?loc ?attrs (Pctf_inherit a)
let val_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_val (a, b, c, d))
let method_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_method (a, b, c, d))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pctf_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pctf_extension a)
let attribute ?loc a = mk ?loc (Pctf_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
let attr d a = {d with pctf_attributes = d.pctf_attributes @ [a]}
end
module Cf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pcf_desc = d;
pcf_loc = loc;
pcf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_inherit (a, b, c))
let val_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_val (a, b, c))
let method_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_method (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcf_constraint (a, b))
let initializer_ ?loc ?attrs a = mk ?loc ?attrs (Pcf_initializer a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcf_extension a)
let attribute ?loc a = mk ?loc (Pcf_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
let virtual_ ct = Cfk_virtual ct
let concrete o e = Cfk_concrete (o, e)
let attr d a = {d with pcf_attributes = d.pcf_attributes @ [a]}
end
module Val = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(prim = []) name typ =
{
pval_name = name;
pval_type = typ;
pval_attributes = add_docs_attrs docs attrs;
pval_loc = loc;
pval_prim = prim;
}
end
module Md = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name typ =
{
pmd_name = name;
pmd_type = typ;
pmd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmd_loc = loc;
}
end
module Mtd = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) ?typ name =
{
pmtd_name = name;
pmtd_type = typ;
pmtd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmtd_loc = loc;
}
end
module Mb = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name expr =
{
pmb_name = name;
pmb_expr = expr;
pmb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmb_loc = loc;
}
end
module Opn = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(override = Fresh) lid =
{
popen_lid = lid;
popen_override = override;
popen_loc = loc;
popen_attributes = add_docs_attrs docs attrs;
}
end
module Incl = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs) mexpr =
{
pincl_mod = mexpr;
pincl_loc = loc;
pincl_attributes = add_docs_attrs docs attrs;
}
end
module Vb = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(text = []) pat expr =
{
pvb_pat = pat;
pvb_expr = expr;
pvb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pvb_loc = loc;
}
end
module Ci = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(virt = Concrete) ?(params = []) name expr =
{
pci_virt = virt;
pci_params = params;
pci_name = name;
pci_expr = expr;
pci_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pci_loc = loc;
}
end
module Type = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(params = [])
?(cstrs = [])
?(kind = Ptype_abstract)
?(priv = Public)
?manifest
name =
{
ptype_name = name;
ptype_params = params;
ptype_cstrs = cstrs;
ptype_kind = kind;
ptype_private = priv;
ptype_manifest = manifest;
ptype_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
ptype_loc = loc;
}
let constructor ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(args = Pcstr_tuple []) ?res name =
{
pcd_name = name;
pcd_args = args;
pcd_res = res;
pcd_loc = loc;
pcd_attributes = add_info_attrs info attrs;
}
let field ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(mut = Immutable) name typ =
{
pld_name = name;
pld_mutable = mut;
pld_type = typ;
pld_loc = loc;
pld_attributes = add_info_attrs info attrs;
}
end
(** Type extensions *)
module Te = struct
let mk ?(attrs = []) ?(docs = empty_docs)
?(params = []) ?(priv = Public) path constructors =
{
ptyext_path = path;
ptyext_params = params;
ptyext_constructors = constructors;
ptyext_private = priv;
ptyext_attributes = add_docs_attrs docs attrs;
}
let constructor ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name kind =
{
pext_name = name;
pext_kind = kind;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let decl ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(info = empty_info) ?(args = Pcstr_tuple []) ?res name =
{
pext_name = name;
pext_kind = Pext_decl(args, res);
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let rebind ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name lid =
{
pext_name = name;
pext_kind = Pext_rebind lid;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
end
module Csig = struct
let mk self fields =
{
pcsig_self = self;
pcsig_fields = fields;
}
end
module Cstr = struct
let mk self fields =
{
pcstr_self = self;
pcstr_fields = fields;
}
end
| null | https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/upstream/ocaml_403/parsing/ast_helper.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.
************************************************************************
-> ghost?
* Type extensions | , LexiFi
Copyright 2012 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* Helpers to produce Parsetree fragments
open Asttypes
open Parsetree
open Docstrings
type lid = Longident.t loc
type str = string loc
type loc = Location.t
type attrs = attribute list
let default_loc = ref Location.none
let with_default_loc l f =
let old = !default_loc in
default_loc := l;
try let r = f () in default_loc := old; r
with exn -> default_loc := old; raise exn
module Const = struct
let integer ?suffix i = Pconst_integer (i, suffix)
let int ?suffix i = integer ?suffix (string_of_int i)
let int32 ?(suffix='l') i = integer ~suffix (Int32.to_string i)
let int64 ?(suffix='L') i = integer ~suffix (Int64.to_string i)
let nativeint ?(suffix='n') i = integer ~suffix (Nativeint.to_string i)
let float ?suffix f = Pconst_float (f, suffix)
let char c = Pconst_char c
let string ?quotation_delimiter s = Pconst_string (s, quotation_delimiter)
end
module Typ = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ptyp_desc = d; ptyp_loc = loc; ptyp_attributes = attrs}
let attr d a = {d with ptyp_attributes = d.ptyp_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ptyp_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ptyp_var a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_arrow (a, b, c))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ptyp_tuple a)
let constr ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_constr (a, b))
let object_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_object (a, b))
let class_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_class (a, b))
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_alias (a, b))
let variant ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_variant (a, b, c))
let poly ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_poly (a, b))
let package ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_package (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Ptyp_extension a)
let force_poly t =
match t.ptyp_desc with
| Ptyp_poly _ -> t
end
module Pat = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ppat_desc = d; ppat_loc = loc; ppat_attributes = attrs}
let attr d a = {d with ppat_attributes = d.ppat_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ppat_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ppat_var a)
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ppat_alias (a, b))
let constant ?loc ?attrs a = mk ?loc ?attrs (Ppat_constant a)
let interval ?loc ?attrs a b = mk ?loc ?attrs (Ppat_interval (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ppat_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Ppat_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Ppat_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Ppat_record (a, b))
let array ?loc ?attrs a = mk ?loc ?attrs (Ppat_array a)
let or_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_or (a, b))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_constraint (a, b))
let type_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_type a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_lazy a)
let unpack ?loc ?attrs a = mk ?loc ?attrs (Ppat_unpack a)
let exception_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_exception a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Ppat_extension a)
end
module Exp = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pexp_desc = d; pexp_loc = loc; pexp_attributes = attrs}
let attr d a = {d with pexp_attributes = d.pexp_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pexp_ident a)
let constant ?loc ?attrs a = mk ?loc ?attrs (Pexp_constant a)
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_let (a, b, c))
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pexp_fun (a, b, c, d))
let function_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_function a)
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pexp_apply (a, b))
let match_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_match (a, b))
let try_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_try (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Pexp_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Pexp_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Pexp_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Pexp_record (a, b))
let field ?loc ?attrs a b = mk ?loc ?attrs (Pexp_field (a, b))
let setfield ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_setfield (a, b, c))
let array ?loc ?attrs a = mk ?loc ?attrs (Pexp_array a)
let ifthenelse ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_ifthenelse (a, b, c))
let sequence ?loc ?attrs a b = mk ?loc ?attrs (Pexp_sequence (a, b))
let while_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_while (a, b))
let for_ ?loc ?attrs a b c d e = mk ?loc ?attrs (Pexp_for (a, b, c, d, e))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_constraint (a, b))
let coerce ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_coerce (a, b, c))
let send ?loc ?attrs a b = mk ?loc ?attrs (Pexp_send (a, b))
let new_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_new a)
let setinstvar ?loc ?attrs a b = mk ?loc ?attrs (Pexp_setinstvar (a, b))
let override ?loc ?attrs a = mk ?loc ?attrs (Pexp_override a)
let letmodule ?loc ?attrs a b c= mk ?loc ?attrs (Pexp_letmodule (a, b, c))
let assert_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_assert a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_lazy a)
let poly ?loc ?attrs a b = mk ?loc ?attrs (Pexp_poly (a, b))
let object_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_object a)
let newtype ?loc ?attrs a b = mk ?loc ?attrs (Pexp_newtype (a, b))
let pack ?loc ?attrs a = mk ?loc ?attrs (Pexp_pack a)
let open_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_open (a, b, c))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pexp_extension a)
let unreachable ?loc ?attrs () = mk ?loc ?attrs Pexp_unreachable
let case lhs ?guard rhs =
{
pc_lhs = lhs;
pc_guard = guard;
pc_rhs = rhs;
}
end
module Mty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmty_desc = d; pmty_loc = loc; pmty_attributes = attrs}
let attr d a = {d with pmty_attributes = d.pmty_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pmty_ident a)
let alias ?loc ?attrs a = mk ?loc ?attrs (Pmty_alias a)
let signature ?loc ?attrs a = mk ?loc ?attrs (Pmty_signature a)
let functor_ ?loc ?attrs a b c = mk ?loc ?attrs (Pmty_functor (a, b, c))
let with_ ?loc ?attrs a b = mk ?loc ?attrs (Pmty_with (a, b))
let typeof_ ?loc ?attrs a = mk ?loc ?attrs (Pmty_typeof a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmty_extension a)
end
module Mod = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmod_desc = d; pmod_loc = loc; pmod_attributes = attrs}
let attr d a = {d with pmod_attributes = d.pmod_attributes @ [a]}
let ident ?loc ?attrs x = mk ?loc ?attrs (Pmod_ident x)
let structure ?loc ?attrs x = mk ?loc ?attrs (Pmod_structure x)
let functor_ ?loc ?attrs arg arg_ty body =
mk ?loc ?attrs (Pmod_functor (arg, arg_ty, body))
let apply ?loc ?attrs m1 m2 = mk ?loc ?attrs (Pmod_apply (m1, m2))
let constraint_ ?loc ?attrs m mty = mk ?loc ?attrs (Pmod_constraint (m, mty))
let unpack ?loc ?attrs e = mk ?loc ?attrs (Pmod_unpack e)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmod_extension a)
end
module Sig = struct
let mk ?(loc = !default_loc) d = {psig_desc = d; psig_loc = loc}
let value ?loc a = mk ?loc (Psig_value a)
let type_ ?loc rec_flag a = mk ?loc (Psig_type (rec_flag, a))
let type_extension ?loc a = mk ?loc (Psig_typext a)
let exception_ ?loc a = mk ?loc (Psig_exception a)
let module_ ?loc a = mk ?loc (Psig_module a)
let rec_module ?loc a = mk ?loc (Psig_recmodule a)
let modtype ?loc a = mk ?loc (Psig_modtype a)
let open_ ?loc a = mk ?loc (Psig_open a)
let include_ ?loc a = mk ?loc (Psig_include a)
let class_ ?loc a = mk ?loc (Psig_class a)
let class_type ?loc a = mk ?loc (Psig_class_type a)
let extension ?loc ?(attrs = []) a = mk ?loc (Psig_extension (a, attrs))
let attribute ?loc a = mk ?loc (Psig_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
end
module Str = struct
let mk ?(loc = !default_loc) d = {pstr_desc = d; pstr_loc = loc}
let eval ?loc ?(attrs = []) a = mk ?loc (Pstr_eval (a, attrs))
let value ?loc a b = mk ?loc (Pstr_value (a, b))
let primitive ?loc a = mk ?loc (Pstr_primitive a)
let type_ ?loc rec_flag a = mk ?loc (Pstr_type (rec_flag, a))
let type_extension ?loc a = mk ?loc (Pstr_typext a)
let exception_ ?loc a = mk ?loc (Pstr_exception a)
let module_ ?loc a = mk ?loc (Pstr_module a)
let rec_module ?loc a = mk ?loc (Pstr_recmodule a)
let modtype ?loc a = mk ?loc (Pstr_modtype a)
let open_ ?loc a = mk ?loc (Pstr_open a)
let class_ ?loc a = mk ?loc (Pstr_class a)
let class_type ?loc a = mk ?loc (Pstr_class_type a)
let include_ ?loc a = mk ?loc (Pstr_include a)
let extension ?loc ?(attrs = []) a = mk ?loc (Pstr_extension (a, attrs))
let attribute ?loc a = mk ?loc (Pstr_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
end
module Cl = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcl_desc = d;
pcl_loc = loc;
pcl_attributes = attrs;
}
let attr d a = {d with pcl_attributes = d.pcl_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constr (a, b))
let structure ?loc ?attrs a = mk ?loc ?attrs (Pcl_structure a)
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pcl_fun (a, b, c, d))
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pcl_apply (a, b))
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcl_let (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcl_extension a)
end
module Cty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcty_desc = d;
pcty_loc = loc;
pcty_attributes = attrs;
}
let attr d a = {d with pcty_attributes = d.pcty_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcty_constr (a, b))
let signature ?loc ?attrs a = mk ?loc ?attrs (Pcty_signature a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Pcty_arrow (a, b, c))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcty_extension a)
end
module Ctf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pctf_desc = d;
pctf_loc = loc;
pctf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a = mk ?loc ?attrs (Pctf_inherit a)
let val_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_val (a, b, c, d))
let method_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_method (a, b, c, d))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pctf_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pctf_extension a)
let attribute ?loc a = mk ?loc (Pctf_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
let attr d a = {d with pctf_attributes = d.pctf_attributes @ [a]}
end
module Cf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pcf_desc = d;
pcf_loc = loc;
pcf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_inherit (a, b, c))
let val_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_val (a, b, c))
let method_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_method (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcf_constraint (a, b))
let initializer_ ?loc ?attrs a = mk ?loc ?attrs (Pcf_initializer a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcf_extension a)
let attribute ?loc a = mk ?loc (Pcf_attribute a)
let text txt =
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
txt
let virtual_ ct = Cfk_virtual ct
let concrete o e = Cfk_concrete (o, e)
let attr d a = {d with pcf_attributes = d.pcf_attributes @ [a]}
end
module Val = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(prim = []) name typ =
{
pval_name = name;
pval_type = typ;
pval_attributes = add_docs_attrs docs attrs;
pval_loc = loc;
pval_prim = prim;
}
end
module Md = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name typ =
{
pmd_name = name;
pmd_type = typ;
pmd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmd_loc = loc;
}
end
module Mtd = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) ?typ name =
{
pmtd_name = name;
pmtd_type = typ;
pmtd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmtd_loc = loc;
}
end
module Mb = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name expr =
{
pmb_name = name;
pmb_expr = expr;
pmb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmb_loc = loc;
}
end
module Opn = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(override = Fresh) lid =
{
popen_lid = lid;
popen_override = override;
popen_loc = loc;
popen_attributes = add_docs_attrs docs attrs;
}
end
module Incl = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs) mexpr =
{
pincl_mod = mexpr;
pincl_loc = loc;
pincl_attributes = add_docs_attrs docs attrs;
}
end
module Vb = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(text = []) pat expr =
{
pvb_pat = pat;
pvb_expr = expr;
pvb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pvb_loc = loc;
}
end
module Ci = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(virt = Concrete) ?(params = []) name expr =
{
pci_virt = virt;
pci_params = params;
pci_name = name;
pci_expr = expr;
pci_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pci_loc = loc;
}
end
module Type = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(params = [])
?(cstrs = [])
?(kind = Ptype_abstract)
?(priv = Public)
?manifest
name =
{
ptype_name = name;
ptype_params = params;
ptype_cstrs = cstrs;
ptype_kind = kind;
ptype_private = priv;
ptype_manifest = manifest;
ptype_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
ptype_loc = loc;
}
let constructor ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(args = Pcstr_tuple []) ?res name =
{
pcd_name = name;
pcd_args = args;
pcd_res = res;
pcd_loc = loc;
pcd_attributes = add_info_attrs info attrs;
}
let field ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(mut = Immutable) name typ =
{
pld_name = name;
pld_mutable = mut;
pld_type = typ;
pld_loc = loc;
pld_attributes = add_info_attrs info attrs;
}
end
module Te = struct
let mk ?(attrs = []) ?(docs = empty_docs)
?(params = []) ?(priv = Public) path constructors =
{
ptyext_path = path;
ptyext_params = params;
ptyext_constructors = constructors;
ptyext_private = priv;
ptyext_attributes = add_docs_attrs docs attrs;
}
let constructor ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name kind =
{
pext_name = name;
pext_kind = kind;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let decl ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(info = empty_info) ?(args = Pcstr_tuple []) ?res name =
{
pext_name = name;
pext_kind = Pext_decl(args, res);
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let rebind ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name lid =
{
pext_name = name;
pext_kind = Pext_rebind lid;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
end
module Csig = struct
let mk self fields =
{
pcsig_self = self;
pcsig_fields = fields;
}
end
module Cstr = struct
let mk self fields =
{
pcstr_self = self;
pcstr_fields = fields;
}
end
|
333a16fb1a4de0a54e77f4fdcf004579bc17ada3955172f2994deabd19ab263c | chaoxu/mgccl-haskell | chbp.hs | import System.IO
import Data.Graph.Inductive
import Data.Maybe
import Newick
import Data.Tree
import Data.List
import Rosalind
import Data.Set hiding (map, filter, null, foldl)
main :: IO ()
main = do c <- getLine
t' <-loop []
let w = words c
t = fromJust $ normalCharacterTable t'
o = g w $ map (toSet w) t
p = build o $ head $ topsort o
putStrLn $ printNewickTree $ rootedToUnrooted p
toSet l t = fromList [ x | (x,y) <-zip l t , y=='1']
g l t = grev $ gmap (sub gr) gr
where gr = mkGraph v e :: Gr (Set String) ()
v = zip [0..length t - 1] t
n = length l
e = map (\(x,y)->(x,y,())) $ filter (multi e2) e2
e2 = [(y,x)|(x,a)<-v,(y,b)<-v, b `isProperSubsetOf` a, a/=b]
sub g (p,i,a,s)
| null pp = (p,i,a,s)
| otherwise = (p,i,a `difference` t,s)
where t = unions $ map (fromJust . lab g ) pp
pp = pre g i
multi t (x,y) = null $ startx `intersect` endy
where startx = map snd $ filter ((== x).fst) t
endy = map fst $ filter ((== y).snd) t
build g i
| null s = buildLeaf a
| length s == 1 = Node "" [buildLeaf a, build g (head s)]
| length s == 2 = Node "" [build g (head s),build g (last s)]
where s = suc g i
a = toList $ fromJust $ lab g i
buildLeaf [a,b] = Node "" [Node a [], Node b []]
buildLeaf [a] = Node a []
rootedToUnrooted (Node a [Node b x,y]) = Node b (y:x)
loop xs = do end <- isEOF
if end
then return $ reverse xs
else do c <- getLine
loop (c:xs)
| null | https://raw.githubusercontent.com/chaoxu/mgccl-haskell/bb03e39ae43f410bd2a673ac2b438929ab8ef7a1/rosalind/chbp.hs | haskell | import System.IO
import Data.Graph.Inductive
import Data.Maybe
import Newick
import Data.Tree
import Data.List
import Rosalind
import Data.Set hiding (map, filter, null, foldl)
main :: IO ()
main = do c <- getLine
t' <-loop []
let w = words c
t = fromJust $ normalCharacterTable t'
o = g w $ map (toSet w) t
p = build o $ head $ topsort o
putStrLn $ printNewickTree $ rootedToUnrooted p
toSet l t = fromList [ x | (x,y) <-zip l t , y=='1']
g l t = grev $ gmap (sub gr) gr
where gr = mkGraph v e :: Gr (Set String) ()
v = zip [0..length t - 1] t
n = length l
e = map (\(x,y)->(x,y,())) $ filter (multi e2) e2
e2 = [(y,x)|(x,a)<-v,(y,b)<-v, b `isProperSubsetOf` a, a/=b]
sub g (p,i,a,s)
| null pp = (p,i,a,s)
| otherwise = (p,i,a `difference` t,s)
where t = unions $ map (fromJust . lab g ) pp
pp = pre g i
multi t (x,y) = null $ startx `intersect` endy
where startx = map snd $ filter ((== x).fst) t
endy = map fst $ filter ((== y).snd) t
build g i
| null s = buildLeaf a
| length s == 1 = Node "" [buildLeaf a, build g (head s)]
| length s == 2 = Node "" [build g (head s),build g (last s)]
where s = suc g i
a = toList $ fromJust $ lab g i
buildLeaf [a,b] = Node "" [Node a [], Node b []]
buildLeaf [a] = Node a []
rootedToUnrooted (Node a [Node b x,y]) = Node b (y:x)
loop xs = do end <- isEOF
if end
then return $ reverse xs
else do c <- getLine
loop (c:xs)
| |
f4b2e53a489e536a19e5b8870b09d69abcf48c97b8106cf355fda92162df8718 | OpenC2-org/ocas | act_distill.erl | @author
( C ) 2017 , sFractal Consulting LLC
-module(act_distill).
%%%-------------------------------------------------------------------
%%%
%%% All rights reserved.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions are
%%% met:
%%%
%%% * Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
%%%
%%% * Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in the
%%% documentation and/or other materials provided with the distribution.
%%%
%%% * The names of its contributors may not be used to endorse or promote
%%% products derived from this software without specific prior written
%%% permission.
%%%
%%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
%%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
%%% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES . LOSS OF USE ,
%%% DATA, OR PROFITS. OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
%%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
%%% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%%-------------------------------------------------------------------
-behaviour(gen_server).
-behaviour(oc_env). % for calling start modules
-author("Duncan Sparrell").
-license("Apache 2.0").
%% gen_server callbacks
-export([ init/1
, handle_call/3
, handle_cast/2
, handle_info/2
, terminate/2
, code_change/3
]).
%% interface calls
-export([ start/1
, stop/0
, keepalive/0
]).
-ignore_xref({start, 1}). % to keep xref happy
-ignore_xref({keepalive, 0}). % to keep xref happy
%% This routine API handles all the actions that can be taken
start(State) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [State], []).
stop() ->
gen_server:cast(?MODULE, shutdown).
keepalive() ->
gen_server:call(?MODULE, keepalive).
%% initialize server with state
init( [State] ) ->
lager:debug( "starting ~p with ~p", [?MODULE, State] ),
{ ok, State }.
%% synchronous calls
handle_call( keepalive, From, State ) ->
lager:debug( "~p got keepalive from ~p", [?MODULE, From] ),
reply to
Response = {keepalive_received, act_distill},
{reply, Response, State};
%% handle unknown call messages
handle_call(Message, From, State) ->
lager:info( "~p got unknown ~p from ~p", [?MODULE, Message, From] ),
{reply, error, State}.
%% async calls
handle_cast(shutdown, State) ->
lager:info( "~p got shutdown", [?MODULE] ),
{stop, normal, State};
%% handle unknown cast messages
handle_cast(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
%% handle unknown info messages
handle_info(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
%% handle terminate
terminate(normal, _State) ->
ok.
%% don't really handle code change yet
code_change(_OldVsn, State, _Extra) ->
%% No change planned. The function is there for behaviour sanity,
%% but will not be used. Only a version on the next
{ok, State}.
| null | https://raw.githubusercontent.com/OpenC2-org/ocas/c15132d9f37b1e0e29884456a520557c25b22f38/apps/ocas/src/action_servers/act_distill.erl | erlang | -------------------------------------------------------------------
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS. OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------
for calling start modules
gen_server callbacks
interface calls
to keep xref happy
to keep xref happy
This routine API handles all the actions that can be taken
initialize server with state
synchronous calls
handle unknown call messages
async calls
handle unknown cast messages
handle unknown info messages
handle terminate
don't really handle code change yet
No change planned. The function is there for behaviour sanity,
but will not be used. Only a version on the next | @author
( C ) 2017 , sFractal Consulting LLC
-module(act_distill).
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES . LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-behaviour(gen_server).
-author("Duncan Sparrell").
-license("Apache 2.0").
-export([ init/1
, handle_call/3
, handle_cast/2
, handle_info/2
, terminate/2
, code_change/3
]).
-export([ start/1
, stop/0
, keepalive/0
]).
start(State) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [State], []).
stop() ->
gen_server:cast(?MODULE, shutdown).
keepalive() ->
gen_server:call(?MODULE, keepalive).
init( [State] ) ->
lager:debug( "starting ~p with ~p", [?MODULE, State] ),
{ ok, State }.
handle_call( keepalive, From, State ) ->
lager:debug( "~p got keepalive from ~p", [?MODULE, From] ),
reply to
Response = {keepalive_received, act_distill},
{reply, Response, State};
handle_call(Message, From, State) ->
lager:info( "~p got unknown ~p from ~p", [?MODULE, Message, From] ),
{reply, error, State}.
handle_cast(shutdown, State) ->
lager:info( "~p got shutdown", [?MODULE] ),
{stop, normal, State};
handle_cast(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
handle_info(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
terminate(normal, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
d935d93478776a50d2bcda3ca41ee0cbd4e125aff4ba35adef8e79d433bd7344 | fgalassi/cs61a-sp11 | 3.16.scm | (define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(count-pairs (cdr x))
1)))
returns 3
- > [ 1| * ] - > [ 2| * ] - > [ 3|/ ]
(define a1 (list 1 2 3))
returns 4
- > [ 1| * ] - > [ * | * ]
; | |
; v v
[ 3|/ ]
(define b2 (cons 3 nil))
(define a2 (cons 1 (cons b2 b2)))
returns 7
; -> [*|*]
; | |
; v v
; [*|*]
; | |
; v v
[ 3|/ ]
(define c3 (cons 3 nil))
(define b3 (cons c3 c3))
(define a3 (cons b3 b3))
; never returns
- > [ 1| * ] - > [ 2| * ] - > [ * |/ ]
; ^ |
; | |
; -------------------
(define a4 (list 1 2 3))
(set-car! (cddr a4) a4)
| null | https://raw.githubusercontent.com/fgalassi/cs61a-sp11/66df3b54b03ee27f368c716ae314fd7ed85c4dba/homework/3.16.scm | scheme | | |
v v
-> [*|*]
| |
v v
[*|*]
| |
v v
never returns
^ |
| |
------------------- | (define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(count-pairs (cdr x))
1)))
returns 3
- > [ 1| * ] - > [ 2| * ] - > [ 3|/ ]
(define a1 (list 1 2 3))
returns 4
- > [ 1| * ] - > [ * | * ]
[ 3|/ ]
(define b2 (cons 3 nil))
(define a2 (cons 1 (cons b2 b2)))
returns 7
[ 3|/ ]
(define c3 (cons 3 nil))
(define b3 (cons c3 c3))
(define a3 (cons b3 b3))
- > [ 1| * ] - > [ 2| * ] - > [ * |/ ]
(define a4 (list 1 2 3))
(set-car! (cddr a4) a4)
|
8304070aa0069a2992e5792a91b2b0984cc5df97c8f4bbc773665fad06f382f3 | amir343/avlang | avl_port.erl | Copyright ( c ) 2016 - 2017
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(avl_port).
-behaviour(type_interface).
-include("type_macros.hrl").
-export([ abs_form/0
, lub/0
, name/0
]).
abs_form() -> {avl_type, 'Port'}.
lub() -> 'Any'.
name() -> 'Port'.
| null | https://raw.githubusercontent.com/amir343/avlang/36b14f476327c38d7fb75a787e1e8fd89f25919e/src/avl_port.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright ( c ) 2016 - 2017
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(avl_port).
-behaviour(type_interface).
-include("type_macros.hrl").
-export([ abs_form/0
, lub/0
, name/0
]).
abs_form() -> {avl_type, 'Port'}.
lub() -> 'Any'.
name() -> 'Port'.
|
030d0491e85d7ec3d5306cf27d18926a311b176a817db301b142daed7e5fa04f | Incanus3/ExiL | fe-rules.lisp | (in-package :exil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; strategies
;; TODO: this shouldn't take function, instead it should seem more like
;; a function definition - it should take name and body, pass the body to parser
;; to create the strategy (which will probably still be just a function)
;; and then store the strategy in the environment under given name
(defun defstrategyf (name function)
(add-strategy *current-environment* name function
(format nil "(defstrategy ~A ~A)" name function))
nil)
;; public
(defmacro defstrategy (name function)
"define new strategy"
`(defstrategyf ',name ,function))
(defun undefstrategyf (name)
(rem-strategy *current-environment* name
(format nil "(undefstrategy ~A)" name))
nil)
;; public
(defmacro undefstrategy (name)
"define new strategy"
`(undefstrategyf ',name))
(defun setstrategyf (name)
"set strategy to use"
(set-strategy *current-environment* name
(format nil "(setstrategy ~A)" name))
nil)
; public
(defmacro setstrategy (name)
"set strategy to use"
`(setstrategyf ',name))
(defun current-strategy ()
(current-strategy-name *current-environment*))
(defun strategies ()
(strategy-names *current-environment*))
(defun find-strategy (name)
(eenv:find-strategy *current-environment* name))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; rules
(defun defrulef (name body)
(add-rule *current-environment*
(parse-rule *current-environment* name body)
(format nil "(defrule ~A ~A)" name body)))
;; public
(defmacro defrule (name &body body)
"define rule"
`(defrulef ',name ',body))
(defun undefrulef (name)
(rem-rule *current-environment* name
(format nil "(undefrule ~A)" name)))
;; public
(defmacro undefrule (name)
"undefine rule"
`(undefrulef ',name))
(defun rules ()
(rule-names *current-environment*))
(defun find-rulef (name)
(external (exil-env:find-rule *current-environment* name)))
(defmacro find-rule (name)
`(find-rulef ',name))
(defun rule-docf (name)
(exil-core:doc (exil-env:find-rule *current-environment* name)))
(defmacro rule-doc (name)
`(rule-docf ',name))
(defun ppdefrulef (name)
(fresh-princ (exil-env:find-rule *current-environment* name)))
;; public
(defmacro ppdefrule (name)
"pretty-print rule definition"
`(ppdefrulef ',name))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; agenda
(defun agenda ()
(print-agenda *current-environment*)
nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; backward chaining
(defun defgoalf (goal-spec)
(add-goal *current-environment* (parse-pattern *current-environment* goal-spec)
(format nil "(defgoal ~A)" goal-spec))
nil)
(defmacro defgoal (goal-spec)
`(defgoalf ',goal-spec))
(defun undefgoalf (goal-spec)
(rem-goal *current-environment* (parse-pattern *current-environment* goal-spec)
(format nil "(undefgoal ~A)" goal-spec))
nil)
(defmacro undefgoal (goal-spec)
`(undefgoalf ',goal-spec))
(defun goals ()
(mapcar #'external (exil-env:goals *current-environment*)))
| null | https://raw.githubusercontent.com/Incanus3/ExiL/de0f7c37538cecb7032cc1f2aa070524b0bc048d/src/front-end/fe-rules.lisp | lisp |
strategies
TODO: this shouldn't take function, instead it should seem more like
a function definition - it should take name and body, pass the body to parser
to create the strategy (which will probably still be just a function)
and then store the strategy in the environment under given name
public
public
public
rules
public
public
public
agenda
backward chaining | (in-package :exil)
(defun defstrategyf (name function)
(add-strategy *current-environment* name function
(format nil "(defstrategy ~A ~A)" name function))
nil)
(defmacro defstrategy (name function)
"define new strategy"
`(defstrategyf ',name ,function))
(defun undefstrategyf (name)
(rem-strategy *current-environment* name
(format nil "(undefstrategy ~A)" name))
nil)
(defmacro undefstrategy (name)
"define new strategy"
`(undefstrategyf ',name))
(defun setstrategyf (name)
"set strategy to use"
(set-strategy *current-environment* name
(format nil "(setstrategy ~A)" name))
nil)
(defmacro setstrategy (name)
"set strategy to use"
`(setstrategyf ',name))
(defun current-strategy ()
(current-strategy-name *current-environment*))
(defun strategies ()
(strategy-names *current-environment*))
(defun find-strategy (name)
(eenv:find-strategy *current-environment* name))
(defun defrulef (name body)
(add-rule *current-environment*
(parse-rule *current-environment* name body)
(format nil "(defrule ~A ~A)" name body)))
(defmacro defrule (name &body body)
"define rule"
`(defrulef ',name ',body))
(defun undefrulef (name)
(rem-rule *current-environment* name
(format nil "(undefrule ~A)" name)))
(defmacro undefrule (name)
"undefine rule"
`(undefrulef ',name))
(defun rules ()
(rule-names *current-environment*))
(defun find-rulef (name)
(external (exil-env:find-rule *current-environment* name)))
(defmacro find-rule (name)
`(find-rulef ',name))
(defun rule-docf (name)
(exil-core:doc (exil-env:find-rule *current-environment* name)))
(defmacro rule-doc (name)
`(rule-docf ',name))
(defun ppdefrulef (name)
(fresh-princ (exil-env:find-rule *current-environment* name)))
(defmacro ppdefrule (name)
"pretty-print rule definition"
`(ppdefrulef ',name))
(defun agenda ()
(print-agenda *current-environment*)
nil)
(defun defgoalf (goal-spec)
(add-goal *current-environment* (parse-pattern *current-environment* goal-spec)
(format nil "(defgoal ~A)" goal-spec))
nil)
(defmacro defgoal (goal-spec)
`(defgoalf ',goal-spec))
(defun undefgoalf (goal-spec)
(rem-goal *current-environment* (parse-pattern *current-environment* goal-spec)
(format nil "(undefgoal ~A)" goal-spec))
nil)
(defmacro undefgoal (goal-spec)
`(undefgoalf ',goal-spec))
(defun goals ()
(mapcar #'external (exil-env:goals *current-environment*)))
|
dfa785f8f2a3727533f319c226d430b1760c4bba25fc097a10b5a2bae7542728 | walck/learn-physics | SimpleVec.hs | # OPTIONS_GHC -Wall #
{-# LANGUAGE Safe #-}
|
Module : Physics . Learn .
Copyright : ( c ) 2012 - 2019
License : BSD3 ( see LICENSE )
Maintainer : < >
Stability : experimental
Basic operations on the vector type ' ' , such as vector addition
and scalar multiplication .
This module is simple in the sense that the operations
on vectors all have simple , concrete types ,
without the need for type classes .
This makes using and reasoning about vector operations
easier for a person just learning .
Module : Physics.Learn.SimpleVec
Copyright : (c) Scott N. Walck 2012-2019
License : BSD3 (see LICENSE)
Maintainer : Scott N. Walck <>
Stability : experimental
Basic operations on the vector type 'Vec', such as vector addition
and scalar multiplication.
This module is simple in the sense that the operations
on vectors all have simple, concrete types,
without the need for type classes.
This makes using and reasoning about vector operations
easier for a person just learning Haskell.
-}
module Physics.Learn.SimpleVec
( Vec
, R
, xComp
, yComp
, zComp
, vec
, (^+^)
, (^-^)
, (*^)
, (^*)
, (^/)
, (<.>)
, (><)
, magnitude
, zeroV
, negateV
, sumV
, iHat
, jHat
, kHat
)
where
import Physics.Learn.CommonVec
( Vec(..)
, R
, vec
, iHat
, jHat
, kHat
, (><)
)
infixl 6 ^+^
infixl 6 ^-^
infixl 7 *^
infixl 7 ^*
infixl 7 ^/
infixl 7 <.>
| The zero vector .
zeroV :: Vec
zeroV = vec 0 0 0
-- | The additive inverse of a vector.
negateV :: Vec -> Vec
negateV (Vec ax ay az) = Vec (-ax) (-ay) (-az)
-- | Sum of a list of vectors.
sumV :: [Vec] -> Vec
sumV = foldr (^+^) zeroV
-- | Vector addition.
(^+^) :: Vec -> Vec -> Vec
Vec ax ay az ^+^ Vec bx by bz
= Vec (ax+bx) (ay+by) (az+bz)
-- | Vector subtraction.
(^-^) :: Vec -> Vec -> Vec
Vec ax ay az ^-^ Vec bx by bz = Vec (ax-bx) (ay-by) (az-bz)
-- | Scalar multiplication, where the scalar is on the left
-- and the vector is on the right.
(*^) :: R -> Vec -> Vec
c *^ Vec ax ay az = Vec (c*ax) (c*ay) (c*az)
-- | Scalar multiplication, where the scalar is on the right
-- and the vector is on the left.
(^*) :: Vec -> R -> Vec
Vec ax ay az ^* c = Vec (c*ax) (c*ay) (c*az)
-- | Division of a vector by a scalar.
(^/) :: Vec -> R -> Vec
Vec ax ay az ^/ c = Vec (ax/c) (ay/c) (az/c)
| Dot product of two vectors .
(<.>) :: Vec -> Vec -> R
Vec ax ay az <.> Vec bx by bz = ax*bx + ay*by + az*bz
-- | Magnitude of a vector.
magnitude :: Vec -> R
magnitude v = sqrt(v <.> v)
| null | https://raw.githubusercontent.com/walck/learn-physics/99611ca49940b78a0e13402f35082805cc7db294/src/Physics/Learn/SimpleVec.hs | haskell | # LANGUAGE Safe #
| The additive inverse of a vector.
| Sum of a list of vectors.
| Vector addition.
| Vector subtraction.
| Scalar multiplication, where the scalar is on the left
and the vector is on the right.
| Scalar multiplication, where the scalar is on the right
and the vector is on the left.
| Division of a vector by a scalar.
| Magnitude of a vector. | # OPTIONS_GHC -Wall #
|
Module : Physics . Learn .
Copyright : ( c ) 2012 - 2019
License : BSD3 ( see LICENSE )
Maintainer : < >
Stability : experimental
Basic operations on the vector type ' ' , such as vector addition
and scalar multiplication .
This module is simple in the sense that the operations
on vectors all have simple , concrete types ,
without the need for type classes .
This makes using and reasoning about vector operations
easier for a person just learning .
Module : Physics.Learn.SimpleVec
Copyright : (c) Scott N. Walck 2012-2019
License : BSD3 (see LICENSE)
Maintainer : Scott N. Walck <>
Stability : experimental
Basic operations on the vector type 'Vec', such as vector addition
and scalar multiplication.
This module is simple in the sense that the operations
on vectors all have simple, concrete types,
without the need for type classes.
This makes using and reasoning about vector operations
easier for a person just learning Haskell.
-}
module Physics.Learn.SimpleVec
( Vec
, R
, xComp
, yComp
, zComp
, vec
, (^+^)
, (^-^)
, (*^)
, (^*)
, (^/)
, (<.>)
, (><)
, magnitude
, zeroV
, negateV
, sumV
, iHat
, jHat
, kHat
)
where
import Physics.Learn.CommonVec
( Vec(..)
, R
, vec
, iHat
, jHat
, kHat
, (><)
)
infixl 6 ^+^
infixl 6 ^-^
infixl 7 *^
infixl 7 ^*
infixl 7 ^/
infixl 7 <.>
| The zero vector .
zeroV :: Vec
zeroV = vec 0 0 0
negateV :: Vec -> Vec
negateV (Vec ax ay az) = Vec (-ax) (-ay) (-az)
sumV :: [Vec] -> Vec
sumV = foldr (^+^) zeroV
(^+^) :: Vec -> Vec -> Vec
Vec ax ay az ^+^ Vec bx by bz
= Vec (ax+bx) (ay+by) (az+bz)
(^-^) :: Vec -> Vec -> Vec
Vec ax ay az ^-^ Vec bx by bz = Vec (ax-bx) (ay-by) (az-bz)
(*^) :: R -> Vec -> Vec
c *^ Vec ax ay az = Vec (c*ax) (c*ay) (c*az)
(^*) :: Vec -> R -> Vec
Vec ax ay az ^* c = Vec (c*ax) (c*ay) (c*az)
(^/) :: Vec -> R -> Vec
Vec ax ay az ^/ c = Vec (ax/c) (ay/c) (az/c)
| Dot product of two vectors .
(<.>) :: Vec -> Vec -> R
Vec ax ay az <.> Vec bx by bz = ax*bx + ay*by + az*bz
magnitude :: Vec -> R
magnitude v = sqrt(v <.> v)
|
2ddaf091ffdcfbb211b0010e8e848925069e375a7ef6fabc4212ffe1d2f1e9c4 | LesleyLai/ocamlpt | sphere.ml | open Base
open Vec3
type t = {center: Vec3.t; radius: float; material: Material.t}
let create center radius material =
{center; radius; material}
void get_sphere_uv(const vec3 & p , double & u , double & v ) {
= ( ) , p.x ( ) ) ;
auto theta = asin(p.y ( ) ) ;
u = 1-(phi + pi ) / ( 2*pi ) ;
v = ( theta + pi/2 ) / pi ;
}
void get_sphere_uv(const vec3& p, double& u, double& v) {
auto phi = atan2(p.z(), p.x());
auto theta = asin(p.y());
u = 1-(phi + pi) / (2*pi);
v = (theta + pi/2) / pi;
}
*)
let get_sphere_uv (p: Vec3.t) =
let open Float in
let phi = atan2 p.z p.x
and theta = asin p.y in
let u = 1. - (phi + pi) / (2. * pi)
and v = (theta + pi/2.) / pi in
(u, v)
let hit (r: Ray.t) ({center; radius; material}: t): Material.hit_record option =
let open Float in
let t_min = 0.00001 in
let oc = r.origin -| center in
let a = Vec3.dot r.direction r.direction
and half_b = Vec3.dot oc r.direction
and c = (Vec3.dot oc oc) -. radius *. radius in
let hit_record_from_t t face_direction: Material.hit_record option =
if (t > t_min) then
let p = Ray.at t r in
let outward_normal = ((p -| center) /| radius) in
let normal =
match face_direction with
| Material.FrontFace -> outward_normal
| Material.BackFace -> (negate outward_normal)
in
let (u, v) = get_sphere_uv p in
Some {t; p; normal; material; u; v; face_direction}
else
None
in
let quater_discriminant = half_b *. half_b -. a *. c in
if quater_discriminant > 0. then
let root = sqrt quater_discriminant in
let t1 = (-.half_b -. root)/. a in
hit_record_from_t t1 Material.FrontFace |>
Option_ext.or_else ~f:(
fun () ->
let t2 = (-.half_b +. root)/. a in
hit_record_from_t t2 Material.BackFace)
else
None
let bounding_box (sphere: t): Aabb.t =
let open Vec3 in
let r = (Vec3.create sphere.radius sphere.radius sphere.radius) in
{min=sphere.center -| r; max=sphere.center +| r}
| null | https://raw.githubusercontent.com/LesleyLai/ocamlpt/65c72fc473e98e1fe802b25807dc74a19a6a3d3e/lib/sphere.ml | ocaml | open Base
open Vec3
type t = {center: Vec3.t; radius: float; material: Material.t}
let create center radius material =
{center; radius; material}
void get_sphere_uv(const vec3 & p , double & u , double & v ) {
= ( ) , p.x ( ) ) ;
auto theta = asin(p.y ( ) ) ;
u = 1-(phi + pi ) / ( 2*pi ) ;
v = ( theta + pi/2 ) / pi ;
}
void get_sphere_uv(const vec3& p, double& u, double& v) {
auto phi = atan2(p.z(), p.x());
auto theta = asin(p.y());
u = 1-(phi + pi) / (2*pi);
v = (theta + pi/2) / pi;
}
*)
let get_sphere_uv (p: Vec3.t) =
let open Float in
let phi = atan2 p.z p.x
and theta = asin p.y in
let u = 1. - (phi + pi) / (2. * pi)
and v = (theta + pi/2.) / pi in
(u, v)
let hit (r: Ray.t) ({center; radius; material}: t): Material.hit_record option =
let open Float in
let t_min = 0.00001 in
let oc = r.origin -| center in
let a = Vec3.dot r.direction r.direction
and half_b = Vec3.dot oc r.direction
and c = (Vec3.dot oc oc) -. radius *. radius in
let hit_record_from_t t face_direction: Material.hit_record option =
if (t > t_min) then
let p = Ray.at t r in
let outward_normal = ((p -| center) /| radius) in
let normal =
match face_direction with
| Material.FrontFace -> outward_normal
| Material.BackFace -> (negate outward_normal)
in
let (u, v) = get_sphere_uv p in
Some {t; p; normal; material; u; v; face_direction}
else
None
in
let quater_discriminant = half_b *. half_b -. a *. c in
if quater_discriminant > 0. then
let root = sqrt quater_discriminant in
let t1 = (-.half_b -. root)/. a in
hit_record_from_t t1 Material.FrontFace |>
Option_ext.or_else ~f:(
fun () ->
let t2 = (-.half_b +. root)/. a in
hit_record_from_t t2 Material.BackFace)
else
None
let bounding_box (sphere: t): Aabb.t =
let open Vec3 in
let r = (Vec3.create sphere.radius sphere.radius sphere.radius) in
{min=sphere.center -| r; max=sphere.center +| r}
| |
4cd823a15f24c080abfad5d1b28a7a0d8373667cd203586774f778f3d642e998 | spl/ivy | dcheckdef.mli |
*
* Copyright ( c ) 2006 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2006,
* Jeremy Condit <>
* Matthew Harren <>
* George C. Necula <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
type check =
CNonNull of Cil.exp
| CEq of Cil.exp * Cil.exp * string * Pretty.doc list
| CMult of Cil.exp * Cil.exp
| CPtrArith of Cil.exp * Cil.exp * Cil.exp * Cil.exp * int
| CPtrArithNT of Cil.exp * Cil.exp * Cil.exp * Cil.exp * int
| CPtrArithAccess of Cil.exp * Cil.exp * Cil.exp * Cil.exp * int
| CLeqInt of Cil.exp * Cil.exp * string
| CLeq of Cil.exp * Cil.exp * string
| CLeqNT of Cil.exp * Cil.exp * int * string
| CNullOrLeq of Cil.exp * Cil.exp * Cil.exp * string
| CNullOrLeqNT of Cil.exp * Cil.exp * Cil.exp * int * string
| CWriteNT of Cil.exp * Cil.exp * Cil.exp * int
| CNullUnionOrSelected of Cil.lval * Cil.exp
| CSelected of Cil.exp
| CNotSelected of Cil.exp
val checks_equal : check -> check -> bool
val mkFun : string -> Cil.typ -> Cil.typ list -> Cil.attributes -> Cil.exp
val checkWhy : check -> string
val checkText : check -> Pretty.doc list
val instrToCheck : Cil.instr -> check option
val checkToInstr : check -> Cil.instr
val isDeputyFunctionLval : Cil.exp -> bool
val isDeputyFunctionInstr : Cil.instr -> bool
val is_check_instr : Cil.instr -> bool
val is_deputy_instr : Cil.instr -> bool
val is_deputy_fun : Cil.instr -> bool
val is_alloc_fun : Cil.instr -> bool
val isLibcNoSideEffects : Cil.instr -> bool
val lvNoSideEffects : Cil.exp -> bool
| null | https://raw.githubusercontent.com/spl/ivy/b1b516484fba637eb24e83d27555d273495e622b/src/deputy/dcheckdef.mli | ocaml |
*
* Copyright ( c ) 2006 ,
* < >
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2006,
* Jeremy Condit <>
* Matthew Harren <>
* George C. Necula <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
type check =
CNonNull of Cil.exp
| CEq of Cil.exp * Cil.exp * string * Pretty.doc list
| CMult of Cil.exp * Cil.exp
| CPtrArith of Cil.exp * Cil.exp * Cil.exp * Cil.exp * int
| CPtrArithNT of Cil.exp * Cil.exp * Cil.exp * Cil.exp * int
| CPtrArithAccess of Cil.exp * Cil.exp * Cil.exp * Cil.exp * int
| CLeqInt of Cil.exp * Cil.exp * string
| CLeq of Cil.exp * Cil.exp * string
| CLeqNT of Cil.exp * Cil.exp * int * string
| CNullOrLeq of Cil.exp * Cil.exp * Cil.exp * string
| CNullOrLeqNT of Cil.exp * Cil.exp * Cil.exp * int * string
| CWriteNT of Cil.exp * Cil.exp * Cil.exp * int
| CNullUnionOrSelected of Cil.lval * Cil.exp
| CSelected of Cil.exp
| CNotSelected of Cil.exp
val checks_equal : check -> check -> bool
val mkFun : string -> Cil.typ -> Cil.typ list -> Cil.attributes -> Cil.exp
val checkWhy : check -> string
val checkText : check -> Pretty.doc list
val instrToCheck : Cil.instr -> check option
val checkToInstr : check -> Cil.instr
val isDeputyFunctionLval : Cil.exp -> bool
val isDeputyFunctionInstr : Cil.instr -> bool
val is_check_instr : Cil.instr -> bool
val is_deputy_instr : Cil.instr -> bool
val is_deputy_fun : Cil.instr -> bool
val is_alloc_fun : Cil.instr -> bool
val isLibcNoSideEffects : Cil.instr -> bool
val lvNoSideEffects : Cil.exp -> bool
| |
7bf5e73c124796c84ec3a53815bb12b3376cd30192fe2b32b47e97b4f6adbf58 | achirkin/vulkan | DeclaredNames.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Strict #-}
module Write.Util.DeclaredNames
( DeclaredNames, baseDeclaredNames
, DeclaredIdent (..), DIThingMembers (..)
, diToImportSpec, diToExportSpec
, combineExportSpecs, importToExportSpec
) where
import Control.DeepSeq
import Data.List (unionBy)
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import Data.Semigroup
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Language.Haskell.Exts.Syntax
-- | I want to have unambiguous set of haskell identifiers globally for
-- the library. Thus, it should be possible to lookup module names
-- (for export or import) by identifiers.
type DeclaredNames = Map DeclaredIdent (ModuleName (), [ImportSpec ()])
-- | I limit number of ways to express imports and exports to
-- simplify further processing.
-- I think, this is a good compromise.
data DeclaredIdent
= DIVar { diName :: Text }
-- ^ variable or function (starts with lower case)
| DIPat { diName :: Text }
-- ^ pattern synonyms
| DIThing { diName :: Text, diWithMembers :: DIThingMembers}
-- ^ Class or data or type (starts with upper case)
deriving (Eq, Ord, Show, Generic, NFData)
data DIThingMembers = DITNo | DITEmpty | DITAll
deriving (Eq, Ord, Show, Generic, NFData)
diToImportSpec :: DeclaredIdent -> ImportSpec ()
diToImportSpec (DIVar n)
| T.length n >= 2 && T.head n == '(' && T.last n == ')'
= IVar () (Symbol () . T.unpack . T.init $ T.tail n)
| otherwise
= IVar () (Ident () $ T.unpack n)
diToImportSpec (DIPat n)
= IAbs () (PatternNamespace ()) (Ident () $ T.unpack n)
diToImportSpec (DIThing n DITNo)
= IAbs () (NoNamespace ()) (Ident () $ T.unpack n)
diToImportSpec (DIThing n DITEmpty)
= IThingWith () (Ident () $ T.unpack n) []
diToImportSpec (DIThing n DITAll)
= IThingAll () (Ident () $ T.unpack n)
diToExportSpec :: DeclaredIdent -> ExportSpec ()
diToExportSpec (DIVar n)
| T.length n >= 2 && T.head n == '(' && T.last n == ')'
= EVar () (UnQual () . Symbol () . T.unpack . T.init $ T.tail n)
| otherwise
= EVar () (UnQual () $ Ident () $ T.unpack n)
diToExportSpec (DIPat n)
= EAbs () (PatternNamespace ())
(UnQual () $ Ident () $ T.unpack n)
diToExportSpec (DIThing n DITNo)
= EAbs () (NoNamespace ())
(UnQual () $ Ident () $ T.unpack n)
diToExportSpec (DIThing n DITEmpty)
= EThingWith () (NoWildcard ())
(UnQual () $ Ident () $ T.unpack n) []
diToExportSpec (DIThing n DITAll)
= EThingWith () (EWildcard () 0)
(UnQual () $ Ident () $ T.unpack n) []
| Make a union of two export specs if it is possible ,
-- otherwise return nothing.
combineExportSpecs :: ExportSpec a -> ExportSpec a -> Maybe (ExportSpec a)
combineExportSpecs a@EVar {} b@EThingWith{} = combineExportSpecs b a
combineExportSpecs a@EAbs {} b@EThingWith{} = combineExportSpecs b a
combineExportSpecs (EVar l a) (EVar _ b)
| a `eq'` b = Just $ EVar l a
combineExportSpecs (EAbs l n a) (EAbs _ m b)
| n `eq'` m && a `eq'` b = Just $ EAbs l n a
combineExportSpecs (EThingWith l wcA nA csA) (EThingWith _ wcB nB csB)
| nA `eq'` nB = Just $ EThingWith l (combineWildCards wcA wcB) nA (unionBy eq' csA csB)
combineExportSpecs a@(EThingWith _ _ _ csA) (EVar _ b)
| any (eq' (eVarName b)) csA = Just a
where
eVarName (Qual l _ n) = VarName l n
eVarName (UnQual l n) = VarName l n
eVarName (Special l _) = VarName l (Symbol l "invalid!")
combineExportSpecs a@(EThingWith _ _ nA csA) (EAbs _ ns b)
| PatternNamespace _ <- ns
, any (eq' (eConName b)) csA = Just a
| nA `eq'` b = Just a
where
eConName (Qual l _ n) = ConName l n
eConName (UnQual l n) = ConName l n
eConName (Special l _) = ConName l (Symbol l "invalid!")
combineExportSpecs a b
| a `eq'` b = Just a
combineExportSpecs _ _ = Nothing
eq' :: (Eq (c ()), Functor c) => c a -> c b -> Bool
eq' a b = (() <$ a) == (() <$ b)
combineWildCards :: EWildcard l -> EWildcard l -> EWildcard l
combineWildCards (NoWildcard _) w = w
combineWildCards w (NoWildcard _) = w
combineWildCards (EWildcard l a) (EWildcard _ b) = EWildcard l (max a b)
importToExportSpec :: ImportSpec () -> ExportSpec ()
importToExportSpec (IVar l a) = EVar l (UnQual () a)
importToExportSpec (IAbs l s a) = EAbs l s (UnQual () a)
importToExportSpec (IThingAll l a) = EThingWith l (EWildcard () 0) (UnQual () a) []
importToExportSpec (IThingWith l a cs) = EThingWith l (NoWildcard ()) (UnQual () a) cs
baseDeclaredNames :: DeclaredNames
baseDeclaredNames
= ida "Graphics.Vulkan.Marshal.Internal" "VulkanMarshalPrim"
<> ida "Graphics.Vulkan.Marshal" "FlagType"
<> id0 "Graphics.Vulkan.Marshal" "FlagMask"
<> id0 "Graphics.Vulkan.Marshal" "FlagBit"
<> ida "Graphics.Vulkan.Marshal" "VulkanMarshal"
<> id0 "Graphics.Vulkan.Marshal" "VulkanMarshalPrim"
<> ida "Graphics.Vulkan.Marshal" "VulkanPtr"
<> ida "Graphics.Vulkan.Marshal" "VkPtr"
<> ipa "Graphics.Vulkan.Marshal" "VK_NULL_HANDLE"
<> ipa "Graphics.Vulkan.Marshal" "VK_NULL"
<> ipa "Graphics.Vulkan.Marshal" "VK_ZERO_FLAGS"
<> iva "Graphics.Vulkan.Marshal" "clearStorable"
<> iva "Graphics.Vulkan.Marshal" "withPtr"
<> ida "Graphics.Vulkan.Marshal" "HasField"
<> ida "Graphics.Vulkan.Marshal" "CanReadField"
<> ida "Graphics.Vulkan.Marshal" "CanWriteField"
<> ida "Graphics.Vulkan.Marshal" "CanReadFieldArray"
<> ida "Graphics.Vulkan.Marshal" "CanWriteFieldArray"
<> id0 "Graphics.Vulkan.Marshal" "IndexInBounds"
<> iva "Graphics.Vulkan.Marshal" "mallocForeignPtr"
<> iva "Graphics.Vulkan.Marshal" "withForeignPtr"
<> iva "Graphics.Vulkan.Marshal" "addForeignPtrFinalizer"
<> id0 "Graphics.Vulkan.Marshal" "Int8"
<> id0 "Graphics.Vulkan.Marshal" "Int16"
<> id0 "Graphics.Vulkan.Marshal" "Int32"
<> id0 "Graphics.Vulkan.Marshal" "Int64"
<> id0 "Graphics.Vulkan.Marshal" "Word8"
<> id0 "Graphics.Vulkan.Marshal" "Word16"
<> id0 "Graphics.Vulkan.Marshal" "Word32"
<> id0 "Graphics.Vulkan.Marshal" "Word64"
<> id0 "Graphics.Vulkan.Marshal" "Ptr"
<> id0 "Graphics.Vulkan.Marshal" "FunPtr"
<> id0 "Graphics.Vulkan.Marshal" "Void"
<> id0 "Graphics.Vulkan.Marshal" "CString"
<> ida "Graphics.Vulkan.Marshal" "CInt"
<> ida "Graphics.Vulkan.Marshal" "CSize"
<> ida "Graphics.Vulkan.Marshal" "CChar"
<> ida "Graphics.Vulkan.Marshal" "CWchar"
<> ida "Graphics.Vulkan.Marshal" "CULong"
<> iva "Graphics.Vulkan.Marshal" "withCStringField"
<> iva "Graphics.Vulkan.Marshal" "unsafeCStringField"
<> iva "Graphics.Vulkan.Marshal" "getStringField"
<> iva "Graphics.Vulkan.Marshal" "readStringField"
<> iva "Graphics.Vulkan.Marshal" "writeStringField"
<> iva "Graphics.Vulkan.Marshal" "eqCStrings"
<> ida "Graphics.Vulkan.Marshal.Proc" "VulkanProc"
<> ida "Foreign.C.Types" "CFloat"
<> iva "Foreign.Ptr" "nullPtr"
<> id1 "GHC.Ptr" "Ptr"
<> id0 "GHC.Generics" "Generic"
<> id0 "Data.Data" "Data"
<> ida "Data.Bits" "Bits"
<> ida "Data.Bits" "FiniteBits"
<> ida "Foreign.Storable" "Storable"
<> iva "Text.ParserCombinators.ReadPrec" "(+++)"
<> iva "Text.ParserCombinators.ReadPrec" "step"
<> iva "Text.ParserCombinators.ReadPrec" "prec"
<> iva "Text.Read" "parens"
<> ida "Text.Read" "Read"
<> iva "GHC.Read" "choose"
<> iva "GHC.Read" "expectP"
<> ida "Text.Read.Lex" "Lexeme"
<> iva "Data.Coerce" "coerce"
<> id1 "GHC.Base" "IO"
<> id1 "GHC.Base" "Int"
<> id1 "GHC.Base" "Word"
<> id0 "GHC.Base" "Addr#"
<> id0 "GHC.Base" "Proxy#"
<> id0 "GHC.Base" "ByteArray#"
<> iva "GHC.Base" "plusAddr#"
<> iva "GHC.Base" "proxy#"
<> iva "GHC.Base" "byteArrayContents#"
<> ida "GHC.ForeignPtr" "ForeignPtr"
<> ida "GHC.ForeignPtr" "ForeignPtrContents"
<> iva "GHC.ForeignPtr" "newForeignPtr_"
<> iva "System.IO.Unsafe" "unsafeDupablePerformIO"
<> ida "GHC.TypeLits" "ErrorMessage"
<> id0 "GHC.TypeLits" "TypeError"
<> id0 "GHC.TypeLits" "KnownNat"
<> id0 "GHC.TypeLits" "CmpNat"
<> iva "GHC.TypeLits" "natVal'"
where
ida m t = Map.fromList $ withISpec
[ (DIThing t DITAll , ModuleName () m)
, (DIThing t DITEmpty, ModuleName () m)
, (DIThing t DITNo, ModuleName () m)
]
id0 m t = Map.fromList $ withISpec
[ (DIThing t DITEmpty, ModuleName () m)
, (DIThing t DITNo, ModuleName () m)
]
id1 m t = Map.fromList $ withISpec
[ (DIThing t DITAll, ModuleName () m)
]
ity m t x = Map.fromList [ ( DIThing t x , ModuleName ( ) m ) ]
iva m t = Map.fromList $ withISpec
[ (DIVar t, ModuleName () m) ]
ipa m t = Map.fromList $ withISpec
[ (DIPat t, ModuleName () m) ]
withISpec = map withISpec'
withISpec' (di,m) = (di, (m, [diToImportSpec di]))
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/genvulkan/src/Write/Util/DeclaredNames.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
# LANGUAGE Strict #
| I want to have unambiguous set of haskell identifiers globally for
the library. Thus, it should be possible to lookup module names
(for export or import) by identifiers.
| I limit number of ways to express imports and exports to
simplify further processing.
I think, this is a good compromise.
^ variable or function (starts with lower case)
^ pattern synonyms
^ Class or data or type (starts with upper case)
otherwise return nothing. | # LANGUAGE DeriveGeneric #
module Write.Util.DeclaredNames
( DeclaredNames, baseDeclaredNames
, DeclaredIdent (..), DIThingMembers (..)
, diToImportSpec, diToExportSpec
, combineExportSpecs, importToExportSpec
) where
import Control.DeepSeq
import Data.List (unionBy)
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import Data.Semigroup
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Generics (Generic)
import Language.Haskell.Exts.Syntax
type DeclaredNames = Map DeclaredIdent (ModuleName (), [ImportSpec ()])
data DeclaredIdent
= DIVar { diName :: Text }
| DIPat { diName :: Text }
| DIThing { diName :: Text, diWithMembers :: DIThingMembers}
deriving (Eq, Ord, Show, Generic, NFData)
data DIThingMembers = DITNo | DITEmpty | DITAll
deriving (Eq, Ord, Show, Generic, NFData)
diToImportSpec :: DeclaredIdent -> ImportSpec ()
diToImportSpec (DIVar n)
| T.length n >= 2 && T.head n == '(' && T.last n == ')'
= IVar () (Symbol () . T.unpack . T.init $ T.tail n)
| otherwise
= IVar () (Ident () $ T.unpack n)
diToImportSpec (DIPat n)
= IAbs () (PatternNamespace ()) (Ident () $ T.unpack n)
diToImportSpec (DIThing n DITNo)
= IAbs () (NoNamespace ()) (Ident () $ T.unpack n)
diToImportSpec (DIThing n DITEmpty)
= IThingWith () (Ident () $ T.unpack n) []
diToImportSpec (DIThing n DITAll)
= IThingAll () (Ident () $ T.unpack n)
diToExportSpec :: DeclaredIdent -> ExportSpec ()
diToExportSpec (DIVar n)
| T.length n >= 2 && T.head n == '(' && T.last n == ')'
= EVar () (UnQual () . Symbol () . T.unpack . T.init $ T.tail n)
| otherwise
= EVar () (UnQual () $ Ident () $ T.unpack n)
diToExportSpec (DIPat n)
= EAbs () (PatternNamespace ())
(UnQual () $ Ident () $ T.unpack n)
diToExportSpec (DIThing n DITNo)
= EAbs () (NoNamespace ())
(UnQual () $ Ident () $ T.unpack n)
diToExportSpec (DIThing n DITEmpty)
= EThingWith () (NoWildcard ())
(UnQual () $ Ident () $ T.unpack n) []
diToExportSpec (DIThing n DITAll)
= EThingWith () (EWildcard () 0)
(UnQual () $ Ident () $ T.unpack n) []
| Make a union of two export specs if it is possible ,
combineExportSpecs :: ExportSpec a -> ExportSpec a -> Maybe (ExportSpec a)
combineExportSpecs a@EVar {} b@EThingWith{} = combineExportSpecs b a
combineExportSpecs a@EAbs {} b@EThingWith{} = combineExportSpecs b a
combineExportSpecs (EVar l a) (EVar _ b)
| a `eq'` b = Just $ EVar l a
combineExportSpecs (EAbs l n a) (EAbs _ m b)
| n `eq'` m && a `eq'` b = Just $ EAbs l n a
combineExportSpecs (EThingWith l wcA nA csA) (EThingWith _ wcB nB csB)
| nA `eq'` nB = Just $ EThingWith l (combineWildCards wcA wcB) nA (unionBy eq' csA csB)
combineExportSpecs a@(EThingWith _ _ _ csA) (EVar _ b)
| any (eq' (eVarName b)) csA = Just a
where
eVarName (Qual l _ n) = VarName l n
eVarName (UnQual l n) = VarName l n
eVarName (Special l _) = VarName l (Symbol l "invalid!")
combineExportSpecs a@(EThingWith _ _ nA csA) (EAbs _ ns b)
| PatternNamespace _ <- ns
, any (eq' (eConName b)) csA = Just a
| nA `eq'` b = Just a
where
eConName (Qual l _ n) = ConName l n
eConName (UnQual l n) = ConName l n
eConName (Special l _) = ConName l (Symbol l "invalid!")
combineExportSpecs a b
| a `eq'` b = Just a
combineExportSpecs _ _ = Nothing
eq' :: (Eq (c ()), Functor c) => c a -> c b -> Bool
eq' a b = (() <$ a) == (() <$ b)
combineWildCards :: EWildcard l -> EWildcard l -> EWildcard l
combineWildCards (NoWildcard _) w = w
combineWildCards w (NoWildcard _) = w
combineWildCards (EWildcard l a) (EWildcard _ b) = EWildcard l (max a b)
importToExportSpec :: ImportSpec () -> ExportSpec ()
importToExportSpec (IVar l a) = EVar l (UnQual () a)
importToExportSpec (IAbs l s a) = EAbs l s (UnQual () a)
importToExportSpec (IThingAll l a) = EThingWith l (EWildcard () 0) (UnQual () a) []
importToExportSpec (IThingWith l a cs) = EThingWith l (NoWildcard ()) (UnQual () a) cs
baseDeclaredNames :: DeclaredNames
baseDeclaredNames
= ida "Graphics.Vulkan.Marshal.Internal" "VulkanMarshalPrim"
<> ida "Graphics.Vulkan.Marshal" "FlagType"
<> id0 "Graphics.Vulkan.Marshal" "FlagMask"
<> id0 "Graphics.Vulkan.Marshal" "FlagBit"
<> ida "Graphics.Vulkan.Marshal" "VulkanMarshal"
<> id0 "Graphics.Vulkan.Marshal" "VulkanMarshalPrim"
<> ida "Graphics.Vulkan.Marshal" "VulkanPtr"
<> ida "Graphics.Vulkan.Marshal" "VkPtr"
<> ipa "Graphics.Vulkan.Marshal" "VK_NULL_HANDLE"
<> ipa "Graphics.Vulkan.Marshal" "VK_NULL"
<> ipa "Graphics.Vulkan.Marshal" "VK_ZERO_FLAGS"
<> iva "Graphics.Vulkan.Marshal" "clearStorable"
<> iva "Graphics.Vulkan.Marshal" "withPtr"
<> ida "Graphics.Vulkan.Marshal" "HasField"
<> ida "Graphics.Vulkan.Marshal" "CanReadField"
<> ida "Graphics.Vulkan.Marshal" "CanWriteField"
<> ida "Graphics.Vulkan.Marshal" "CanReadFieldArray"
<> ida "Graphics.Vulkan.Marshal" "CanWriteFieldArray"
<> id0 "Graphics.Vulkan.Marshal" "IndexInBounds"
<> iva "Graphics.Vulkan.Marshal" "mallocForeignPtr"
<> iva "Graphics.Vulkan.Marshal" "withForeignPtr"
<> iva "Graphics.Vulkan.Marshal" "addForeignPtrFinalizer"
<> id0 "Graphics.Vulkan.Marshal" "Int8"
<> id0 "Graphics.Vulkan.Marshal" "Int16"
<> id0 "Graphics.Vulkan.Marshal" "Int32"
<> id0 "Graphics.Vulkan.Marshal" "Int64"
<> id0 "Graphics.Vulkan.Marshal" "Word8"
<> id0 "Graphics.Vulkan.Marshal" "Word16"
<> id0 "Graphics.Vulkan.Marshal" "Word32"
<> id0 "Graphics.Vulkan.Marshal" "Word64"
<> id0 "Graphics.Vulkan.Marshal" "Ptr"
<> id0 "Graphics.Vulkan.Marshal" "FunPtr"
<> id0 "Graphics.Vulkan.Marshal" "Void"
<> id0 "Graphics.Vulkan.Marshal" "CString"
<> ida "Graphics.Vulkan.Marshal" "CInt"
<> ida "Graphics.Vulkan.Marshal" "CSize"
<> ida "Graphics.Vulkan.Marshal" "CChar"
<> ida "Graphics.Vulkan.Marshal" "CWchar"
<> ida "Graphics.Vulkan.Marshal" "CULong"
<> iva "Graphics.Vulkan.Marshal" "withCStringField"
<> iva "Graphics.Vulkan.Marshal" "unsafeCStringField"
<> iva "Graphics.Vulkan.Marshal" "getStringField"
<> iva "Graphics.Vulkan.Marshal" "readStringField"
<> iva "Graphics.Vulkan.Marshal" "writeStringField"
<> iva "Graphics.Vulkan.Marshal" "eqCStrings"
<> ida "Graphics.Vulkan.Marshal.Proc" "VulkanProc"
<> ida "Foreign.C.Types" "CFloat"
<> iva "Foreign.Ptr" "nullPtr"
<> id1 "GHC.Ptr" "Ptr"
<> id0 "GHC.Generics" "Generic"
<> id0 "Data.Data" "Data"
<> ida "Data.Bits" "Bits"
<> ida "Data.Bits" "FiniteBits"
<> ida "Foreign.Storable" "Storable"
<> iva "Text.ParserCombinators.ReadPrec" "(+++)"
<> iva "Text.ParserCombinators.ReadPrec" "step"
<> iva "Text.ParserCombinators.ReadPrec" "prec"
<> iva "Text.Read" "parens"
<> ida "Text.Read" "Read"
<> iva "GHC.Read" "choose"
<> iva "GHC.Read" "expectP"
<> ida "Text.Read.Lex" "Lexeme"
<> iva "Data.Coerce" "coerce"
<> id1 "GHC.Base" "IO"
<> id1 "GHC.Base" "Int"
<> id1 "GHC.Base" "Word"
<> id0 "GHC.Base" "Addr#"
<> id0 "GHC.Base" "Proxy#"
<> id0 "GHC.Base" "ByteArray#"
<> iva "GHC.Base" "plusAddr#"
<> iva "GHC.Base" "proxy#"
<> iva "GHC.Base" "byteArrayContents#"
<> ida "GHC.ForeignPtr" "ForeignPtr"
<> ida "GHC.ForeignPtr" "ForeignPtrContents"
<> iva "GHC.ForeignPtr" "newForeignPtr_"
<> iva "System.IO.Unsafe" "unsafeDupablePerformIO"
<> ida "GHC.TypeLits" "ErrorMessage"
<> id0 "GHC.TypeLits" "TypeError"
<> id0 "GHC.TypeLits" "KnownNat"
<> id0 "GHC.TypeLits" "CmpNat"
<> iva "GHC.TypeLits" "natVal'"
where
ida m t = Map.fromList $ withISpec
[ (DIThing t DITAll , ModuleName () m)
, (DIThing t DITEmpty, ModuleName () m)
, (DIThing t DITNo, ModuleName () m)
]
id0 m t = Map.fromList $ withISpec
[ (DIThing t DITEmpty, ModuleName () m)
, (DIThing t DITNo, ModuleName () m)
]
id1 m t = Map.fromList $ withISpec
[ (DIThing t DITAll, ModuleName () m)
]
ity m t x = Map.fromList [ ( DIThing t x , ModuleName ( ) m ) ]
iva m t = Map.fromList $ withISpec
[ (DIVar t, ModuleName () m) ]
ipa m t = Map.fromList $ withISpec
[ (DIPat t, ModuleName () m) ]
withISpec = map withISpec'
withISpec' (di,m) = (di, (m, [diToImportSpec di]))
|
c9e335f8ff964eaedb0c206683468107b275e79c1be5ddcb77c061fe6b20a8c0 | nikita-volkov/rebase | Scientific.hs | module Rebase.Data.Text.Lazy.Builder.Scientific
(
module Data.Text.Lazy.Builder.Scientific
)
where
import Data.Text.Lazy.Builder.Scientific
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Data/Text/Lazy/Builder/Scientific.hs | haskell | module Rebase.Data.Text.Lazy.Builder.Scientific
(
module Data.Text.Lazy.Builder.Scientific
)
where
import Data.Text.Lazy.Builder.Scientific
| |
5f9613c2fba957b33c45127a6847602badd0b5cba4f6b092ca58d95939f0ff39 | formal-land/coq-of-ocaml | disabled_list.ml | let l1 : int list = []
let l2 = [1; 2; 3; 4]
let l3 = [1, "one"; 2, "two"]
let s1 = List.length l1
let s2 = List.length l2
let h _ = List.hd l2
let t _ = List.tl l2
let x _ = List.nth l2 1
let rl = List.rev l2
let ll = List.append l2 l2
let rll = List.rev_append l2 l2
let lc = List.concat [l1; l2; l1; l2]
let lf = List.flatten [l1; l2; l1; l2]
(* Iterators *)
let m = List.map (fun x -> x + 1) l2
let mi = List.mapi (fun i x -> x + i) l2
let rm = List.rev_map (fun x -> x + 1) l2
let fl = List.fold_left (fun s x -> s + x) 0 l2
let fr = List.fold_right (fun x s -> s + x) l2 0
(* List scanning *)
let all = List.for_all (fun x -> x = 2) l2
let ex = List.exists (fun x -> x = 2) l2
(* List searching *)
let fin _ = List.find (fun x -> x = 1) l2
let fil = List.filter (fun x -> x >= 2) l2
let fina = List.find_all (fun x -> x >= 2) l2
let par = List.partition (fun x -> x > 2) l2
(* Association lists *)
let asso _ = List.assoc 2 l3
let masso _ = List.mem_assoc 2 l3
let rasso _ = List.remove_assoc 2 l3
(* Lists of pairs *)
let sp = List.split l3
let com _ = List.combine l2 l2
(* Sorting *)
let so _ = List.sort (fun x y -> y - x) l2
let sso _ = List.stable_sort (fun x y -> y - x) l2
let fso _ = List.fast_sort (fun x y -> y - x) l2
let mer = List.merge (fun x y -> y - x) l2 [2; -1; 5]
| null | https://raw.githubusercontent.com/formal-land/coq-of-ocaml/c9c86b08eb19d7fd023f48029cc5f9bf53f6a11c/tests/disabled_list.ml | ocaml | Iterators
List scanning
List searching
Association lists
Lists of pairs
Sorting | let l1 : int list = []
let l2 = [1; 2; 3; 4]
let l3 = [1, "one"; 2, "two"]
let s1 = List.length l1
let s2 = List.length l2
let h _ = List.hd l2
let t _ = List.tl l2
let x _ = List.nth l2 1
let rl = List.rev l2
let ll = List.append l2 l2
let rll = List.rev_append l2 l2
let lc = List.concat [l1; l2; l1; l2]
let lf = List.flatten [l1; l2; l1; l2]
let m = List.map (fun x -> x + 1) l2
let mi = List.mapi (fun i x -> x + i) l2
let rm = List.rev_map (fun x -> x + 1) l2
let fl = List.fold_left (fun s x -> s + x) 0 l2
let fr = List.fold_right (fun x s -> s + x) l2 0
let all = List.for_all (fun x -> x = 2) l2
let ex = List.exists (fun x -> x = 2) l2
let fin _ = List.find (fun x -> x = 1) l2
let fil = List.filter (fun x -> x >= 2) l2
let fina = List.find_all (fun x -> x >= 2) l2
let par = List.partition (fun x -> x > 2) l2
let asso _ = List.assoc 2 l3
let masso _ = List.mem_assoc 2 l3
let rasso _ = List.remove_assoc 2 l3
let sp = List.split l3
let com _ = List.combine l2 l2
let so _ = List.sort (fun x y -> y - x) l2
let sso _ = List.stable_sort (fun x y -> y - x) l2
let fso _ = List.fast_sort (fun x y -> y - x) l2
let mer = List.merge (fun x y -> y - x) l2 [2; -1; 5]
|
b45c6438e7938b21bf010d4c993fa1f795bf6f93367379355e381e45ee5f0e9f | processone/ejabberd | mod_push_mnesia.erl | %%%----------------------------------------------------------------------
%%% File : mod_push_mnesia.erl
Author : < >
%%% Purpose : Mnesia backend for Push Notifications (XEP-0357)
Created : 15 Jul 2017 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2017 - 2023 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(mod_push_mnesia).
-author('').
-behaviour(mod_push).
%% API
-export([init/2, store_session/6, lookup_session/4, lookup_session/3,
lookup_sessions/3, lookup_sessions/2, lookup_sessions/1,
delete_session/3, delete_old_sessions/2, transform/1]).
-include_lib("stdlib/include/ms_transform.hrl").
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("mod_push.hrl").
%%%-------------------------------------------------------------------
%%% API
%%%-------------------------------------------------------------------
init(_Host, _Opts) ->
ejabberd_mnesia:create(?MODULE, push_session,
[{disc_only_copies, [node()]},
{type, bag},
{attributes, record_info(fields, push_session)}]).
store_session(LUser, LServer, TS, PushJID, Node, XData) ->
US = {LUser, LServer},
PushLJID = jid:tolower(PushJID),
MaxSessions = ejabberd_sm:get_max_user_sessions(LUser, LServer),
F = fun() ->
enforce_max_sessions(US, MaxSessions),
mnesia:write(#push_session{us = US,
timestamp = TS,
service = PushLJID,
node = Node,
xml = encode_xdata(XData)})
end,
case mnesia:transaction(F) of
{atomic, ok} ->
{ok, {TS, PushLJID, Node, XData}};
{aborted, E} ->
?ERROR_MSG("Cannot store push session for ~ts@~ts: ~p",
[LUser, LServer, E]),
{error, db_failure}
end.
lookup_session(LUser, LServer, PushJID, Node) ->
PushLJID = jid:tolower(PushJID),
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, service = P, node = N} = Rec)
when U == LUser,
S == LServer,
P == PushLJID,
N == Node ->
Rec
end),
case mnesia:dirty_select(push_session, MatchSpec) of
[#push_session{timestamp = TS, xml = El}] ->
{ok, {TS, PushLJID, Node, decode_xdata(El)}};
[] ->
?DEBUG("No push session found for ~ts@~ts (~p, ~ts)",
[LUser, LServer, PushJID, Node]),
{error, notfound}
end.
lookup_session(LUser, LServer, TS) ->
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, timestamp = T} = Rec)
when U == LUser,
S == LServer,
T == TS ->
Rec
end),
case mnesia:dirty_select(push_session, MatchSpec) of
[#push_session{service = PushLJID, node = Node, xml = El}] ->
{ok, {TS, PushLJID, Node, decode_xdata(El)}};
[] ->
?DEBUG("No push session found for ~ts@~ts (~p)",
[LUser, LServer, TS]),
{error, notfound}
end.
lookup_sessions(LUser, LServer, PushJID) ->
PushLJID = jid:tolower(PushJID),
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, service = P} = Rec)
when U == LUser,
S == LServer,
P == PushLJID ->
Rec
end),
Records = mnesia:dirty_select(push_session, MatchSpec),
{ok, records_to_sessions(Records)}.
lookup_sessions(LUser, LServer) ->
Records = mnesia:dirty_read(push_session, {LUser, LServer}),
{ok, records_to_sessions(Records)}.
lookup_sessions(LServer) ->
MatchSpec = ets:fun2ms(
fun(#push_session{us = {_U, S}} = Rec)
when S == LServer ->
Rec
end),
Records = mnesia:dirty_select(push_session, MatchSpec),
{ok, records_to_sessions(Records)}.
delete_session(LUser, LServer, TS) ->
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, timestamp = T} = Rec)
when U == LUser,
S == LServer,
T == TS ->
Rec
end),
F = fun() ->
Recs = mnesia:select(push_session, MatchSpec),
lists:foreach(fun mnesia:delete_object/1, Recs)
end,
case mnesia:transaction(F) of
{atomic, ok} ->
ok;
{aborted, E} ->
?ERROR_MSG("Cannot delete push session of ~ts@~ts: ~p",
[LUser, LServer, E]),
{error, db_failure}
end.
delete_old_sessions(_LServer, Time) ->
DelIfOld = fun(#push_session{timestamp = T} = Rec, ok) when T < Time ->
mnesia:delete_object(Rec);
(_Rec, ok) ->
ok
end,
F = fun() ->
mnesia:foldl(DelIfOld, ok, push_session)
end,
case mnesia:transaction(F) of
{atomic, ok} ->
ok;
{aborted, E} ->
?ERROR_MSG("Cannot delete old push sessions: ~p", [E]),
{error, db_failure}
end.
transform({push_session, US, TS, Service, Node, XData}) ->
?INFO_MSG("Transforming push_session Mnesia table", []),
#push_session{us = US, timestamp = TS, service = Service,
node = Node, xml = encode_xdata(XData)}.
%%--------------------------------------------------------------------
Internal functions .
%%--------------------------------------------------------------------
-spec enforce_max_sessions({binary(), binary()}, non_neg_integer() | infinity)
-> ok.
enforce_max_sessions(_US, infinity) ->
ok;
enforce_max_sessions({U, S} = US, MaxSessions) ->
case mnesia:wread({push_session, US}) of
Recs when length(Recs) >= MaxSessions ->
Recs1 = lists:sort(fun(#push_session{timestamp = TS1},
#push_session{timestamp = TS2}) ->
TS1 >= TS2
end, Recs),
OldRecs = lists:nthtail(MaxSessions - 1, Recs1),
?INFO_MSG("Disabling old push session(s) of ~ts@~ts", [U, S]),
lists:foreach(fun(Rec) -> mnesia:delete_object(Rec) end, OldRecs);
_ ->
ok
end.
decode_xdata(undefined) ->
undefined;
decode_xdata(El) ->
xmpp:decode(El).
encode_xdata(undefined) ->
undefined;
encode_xdata(XData) ->
xmpp:encode(XData).
records_to_sessions(Records) ->
[{TS, PushLJID, Node, decode_xdata(El)}
|| #push_session{timestamp = TS,
service = PushLJID,
node = Node,
xml = El} <- Records].
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/mod_push_mnesia.erl | erlang | ----------------------------------------------------------------------
File : mod_push_mnesia.erl
Purpose : Mnesia backend for Push Notifications (XEP-0357)
This program is free software; you can redistribute it and/or
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.
----------------------------------------------------------------------
API
-------------------------------------------------------------------
API
-------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | Author : < >
Created : 15 Jul 2017 by < >
ejabberd , Copyright ( C ) 2017 - 2023 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(mod_push_mnesia).
-author('').
-behaviour(mod_push).
-export([init/2, store_session/6, lookup_session/4, lookup_session/3,
lookup_sessions/3, lookup_sessions/2, lookup_sessions/1,
delete_session/3, delete_old_sessions/2, transform/1]).
-include_lib("stdlib/include/ms_transform.hrl").
-include("logger.hrl").
-include_lib("xmpp/include/xmpp.hrl").
-include("mod_push.hrl").
init(_Host, _Opts) ->
ejabberd_mnesia:create(?MODULE, push_session,
[{disc_only_copies, [node()]},
{type, bag},
{attributes, record_info(fields, push_session)}]).
store_session(LUser, LServer, TS, PushJID, Node, XData) ->
US = {LUser, LServer},
PushLJID = jid:tolower(PushJID),
MaxSessions = ejabberd_sm:get_max_user_sessions(LUser, LServer),
F = fun() ->
enforce_max_sessions(US, MaxSessions),
mnesia:write(#push_session{us = US,
timestamp = TS,
service = PushLJID,
node = Node,
xml = encode_xdata(XData)})
end,
case mnesia:transaction(F) of
{atomic, ok} ->
{ok, {TS, PushLJID, Node, XData}};
{aborted, E} ->
?ERROR_MSG("Cannot store push session for ~ts@~ts: ~p",
[LUser, LServer, E]),
{error, db_failure}
end.
lookup_session(LUser, LServer, PushJID, Node) ->
PushLJID = jid:tolower(PushJID),
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, service = P, node = N} = Rec)
when U == LUser,
S == LServer,
P == PushLJID,
N == Node ->
Rec
end),
case mnesia:dirty_select(push_session, MatchSpec) of
[#push_session{timestamp = TS, xml = El}] ->
{ok, {TS, PushLJID, Node, decode_xdata(El)}};
[] ->
?DEBUG("No push session found for ~ts@~ts (~p, ~ts)",
[LUser, LServer, PushJID, Node]),
{error, notfound}
end.
lookup_session(LUser, LServer, TS) ->
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, timestamp = T} = Rec)
when U == LUser,
S == LServer,
T == TS ->
Rec
end),
case mnesia:dirty_select(push_session, MatchSpec) of
[#push_session{service = PushLJID, node = Node, xml = El}] ->
{ok, {TS, PushLJID, Node, decode_xdata(El)}};
[] ->
?DEBUG("No push session found for ~ts@~ts (~p)",
[LUser, LServer, TS]),
{error, notfound}
end.
lookup_sessions(LUser, LServer, PushJID) ->
PushLJID = jid:tolower(PushJID),
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, service = P} = Rec)
when U == LUser,
S == LServer,
P == PushLJID ->
Rec
end),
Records = mnesia:dirty_select(push_session, MatchSpec),
{ok, records_to_sessions(Records)}.
lookup_sessions(LUser, LServer) ->
Records = mnesia:dirty_read(push_session, {LUser, LServer}),
{ok, records_to_sessions(Records)}.
lookup_sessions(LServer) ->
MatchSpec = ets:fun2ms(
fun(#push_session{us = {_U, S}} = Rec)
when S == LServer ->
Rec
end),
Records = mnesia:dirty_select(push_session, MatchSpec),
{ok, records_to_sessions(Records)}.
delete_session(LUser, LServer, TS) ->
MatchSpec = ets:fun2ms(
fun(#push_session{us = {U, S}, timestamp = T} = Rec)
when U == LUser,
S == LServer,
T == TS ->
Rec
end),
F = fun() ->
Recs = mnesia:select(push_session, MatchSpec),
lists:foreach(fun mnesia:delete_object/1, Recs)
end,
case mnesia:transaction(F) of
{atomic, ok} ->
ok;
{aborted, E} ->
?ERROR_MSG("Cannot delete push session of ~ts@~ts: ~p",
[LUser, LServer, E]),
{error, db_failure}
end.
delete_old_sessions(_LServer, Time) ->
DelIfOld = fun(#push_session{timestamp = T} = Rec, ok) when T < Time ->
mnesia:delete_object(Rec);
(_Rec, ok) ->
ok
end,
F = fun() ->
mnesia:foldl(DelIfOld, ok, push_session)
end,
case mnesia:transaction(F) of
{atomic, ok} ->
ok;
{aborted, E} ->
?ERROR_MSG("Cannot delete old push sessions: ~p", [E]),
{error, db_failure}
end.
transform({push_session, US, TS, Service, Node, XData}) ->
?INFO_MSG("Transforming push_session Mnesia table", []),
#push_session{us = US, timestamp = TS, service = Service,
node = Node, xml = encode_xdata(XData)}.
Internal functions .
-spec enforce_max_sessions({binary(), binary()}, non_neg_integer() | infinity)
-> ok.
enforce_max_sessions(_US, infinity) ->
ok;
enforce_max_sessions({U, S} = US, MaxSessions) ->
case mnesia:wread({push_session, US}) of
Recs when length(Recs) >= MaxSessions ->
Recs1 = lists:sort(fun(#push_session{timestamp = TS1},
#push_session{timestamp = TS2}) ->
TS1 >= TS2
end, Recs),
OldRecs = lists:nthtail(MaxSessions - 1, Recs1),
?INFO_MSG("Disabling old push session(s) of ~ts@~ts", [U, S]),
lists:foreach(fun(Rec) -> mnesia:delete_object(Rec) end, OldRecs);
_ ->
ok
end.
decode_xdata(undefined) ->
undefined;
decode_xdata(El) ->
xmpp:decode(El).
encode_xdata(undefined) ->
undefined;
encode_xdata(XData) ->
xmpp:encode(XData).
records_to_sessions(Records) ->
[{TS, PushLJID, Node, decode_xdata(El)}
|| #push_session{timestamp = TS,
service = PushLJID,
node = Node,
xml = El} <- Records].
|
724728407a493e5e813095d966cdefa918e0d11db67151cc136ee86f616968f0 | ahrefs/monorobot | github.ml | open Base
open Devkit
open Printf
open Github_j
type t =
| Push of commit_pushed_notification
| Pull_request of pr_notification
| PR_review of pr_review_notification
| PR_review_comment of pr_review_comment_notification
| Issue of issue_notification
| Issue_comment of issue_comment_notification
| Commit_comment of commit_comment_notification
| Status of status_notification
(* all other events *)
| Event of event_notification
let repo_of_notification = function
| Push n -> n.repository
| Pull_request n -> n.repository
| PR_review n -> n.repository
| PR_review_comment n -> n.repository
| Issue n -> n.repository
| Issue_comment n -> n.repository
| Commit_comment n -> n.repository
| Status n -> n.repository
| Event n -> n.repository
let commits_branch_of_ref ref =
match String.split ~on:'/' ref with
| "refs" :: "heads" :: l -> String.concat ~sep:"/" l
| _ -> ref
let event_of_filename filename =
match String.split_on_chars ~on:[ '.' ] filename with
| [ kind; _; "json" ] -> Some kind
| _ -> None
let merge_commit_re = Re2.create_exn {|^Merge(?: remote-tracking)? branch '(?:origin/)?.+'(?: of .+)? into (.+)$|}
let is_merge_commit_to_ignore ~(cfg : Config_t.config) ~branch commit =
match cfg.main_branch_name with
| Some main_branch when String.equal branch main_branch ->
(*
handle "Merge <any branch> into <feature branch>" commits when they are merged into main branch
we should have already seen these commits on the feature branch but for some reason they are distinct:true
*)
let title = Common.first_line commit.message in
begin
try
let receiving_branch = Re2.find_first_exn ~sub:(`Index 1) merge_commit_re title in
not @@ String.equal branch receiving_branch
with Re2.Exceptions.Regex_match_failed _ -> false
end
| Some _ | None -> false
let modified_files_of_commit commit = List.concat [ commit.added; commit.removed; commit.modified ]
let is_valid_signature ~secret headers_sig body =
let request_hash =
let key = Cstruct.of_string secret in
Cstruct.to_string @@ Nocrypto.Hash.SHA1.hmac ~key (Cstruct.of_string body)
in
let (`Hex request_hash) = Hex.of_string request_hash in
String.equal headers_sig (sprintf "sha1=%s" request_hash)
let validate_signature ?signing_key ~headers body =
match signing_key with
| None -> Ok ()
| Some secret ->
match List.Assoc.find headers "x-hub-signature" ~equal:String.equal with
| None -> Error "unable to find header x-hub-signature"
| Some signature -> if is_valid_signature ~secret signature body then Ok () else Error "signatures don't match"
(* Parse a payload. The type of the payload is detected from the headers. *)
let parse_exn headers body =
match List.Assoc.find_exn headers "x-github-event" ~equal:String.equal with
| exception exn -> Exn.fail ~exn "unable to read x-github-event"
| "push" -> Push (commit_pushed_notification_of_string body)
| "pull_request" -> Pull_request (pr_notification_of_string body)
| "pull_request_review" -> PR_review (pr_review_notification_of_string body)
| "pull_request_review_comment" -> PR_review_comment (pr_review_comment_notification_of_string body)
| "issues" -> Issue (issue_notification_of_string body)
| "issue_comment" -> Issue_comment (issue_comment_notification_of_string body)
| "status" -> Status (status_notification_of_string body)
| "commit_comment" -> Commit_comment (commit_comment_notification_of_string body)
| "member" | "create" | "delete" | "release" -> Event (event_notification_of_string body)
| event -> failwith @@ sprintf "unsupported event : %s" event
type basehead = string * string
type gh_link =
| Pull_request of repository * int
| Issue of repository * int
| Commit of repository * commit_hash
| Compare of repository * basehead
let gh_link_re = Re2.create_exn {|^(.*)/(.+)/(.+)/(commit|pull|issues|compare)/([a-zA-Z0-9/:\-_.~\^%]+)$|}
let commit_sha_re = Re2.create_exn {|[a-f0-9]{4,40}|}
let comparer_re = {|([a-zA-Z0-9/:\-_.~\^]+)|}
let compare_basehead_re = Re2.create_exn (sprintf {|%s([.]{3})%s|} comparer_re comparer_re)
let gh_org_team_re = Re2.create_exn {|[a-zA-Z0-9\-]+/([a-zA-Z0-9\-]+)|}
(** [gh_link_of_string s] parses a URL string [s] to try to match a supported
GitHub link type, generating repository endpoints if necessary *)
let gh_link_of_string url_str =
let url = Uri.of_string url_str in
let path = Uri.path url in
let gh_com_html_base owner name = sprintf "" owner name in
let gh_com_api_base owner name = sprintf "" owner name in
let custom_html_base ?(scheme = "https") base owner name = sprintf "%s" scheme base owner name in
let custom_api_base ?(scheme = "https") base owner name =
sprintf "%s" scheme base owner name
in
match Uri.host url with
| None -> None
| Some host ->
match Re2.find_submatches_exn gh_link_re path with
| [| _; prefix; Some owner; Some name; Some link_type; Some item |] ->
let item = Base.String.chop_suffix_if_exists item ~suffix:"/" in
let repo =
let base = Option.value_map prefix ~default:host ~f:(fun p -> String.concat [ host; p ]) in
let scheme = Uri.scheme url in
let html_base, api_base =
if String.is_suffix base ~suffix:"github.com" then gh_com_html_base owner name, gh_com_api_base owner name
else custom_html_base ?scheme base owner name, custom_api_base ?scheme base owner name
in
{
name;
full_name = sprintf "%s/%s" owner name;
url = html_base;
commits_url = sprintf "%s/commits{/sha}" api_base;
contents_url = sprintf "%s/contents/{+path}" api_base;
pulls_url = sprintf "%s/pulls{/number}" api_base;
issues_url = sprintf "%s/issues{/number}" api_base;
compare_url = sprintf "%s/compare{/basehead}" api_base;
}
in
let verify_commit_sha repo item =
try
match Re2.find_submatches_exn commit_sha_re item with
| [| Some sha |] -> Some (Commit (repo, sha))
| _ -> None
with _ -> None
in
let verify_compare_basehead repo basehead =
match Re2.find_submatches_exn compare_basehead_re basehead with
| [| _; Some base; _; Some merge |] -> Some (Compare (repo, (base, merge)))
| _ | (exception Re2.Exceptions.Regex_match_failed _) -> None
in
begin
try
match link_type with
| "pull" -> Some (Pull_request (repo, Int.of_string item))
| "issues" -> Some (Issue (repo, Int.of_string item))
| "commit" -> verify_commit_sha repo item
| "compare" ->
let item = Uri.pct_decode item in
verify_compare_basehead repo item
| _ -> None
with _ -> None
end
| _ | (exception Re2.Exceptions.Regex_match_failed _) -> None
let get_project_owners (pr : pull_request) ({ rules } : Config_t.project_owners) =
Rule.Project_owners.match_rules pr.labels rules
|> List.dedup_and_sort ~compare:String.compare
|> List.partition_map ~f:(fun reviewer ->
try
let team = Re2.find_first_exn ~sub:(`Index 1) gh_org_team_re reviewer in
Second team
with Re2.Exceptions.Regex_match_failed _ -> First reviewer
)
|> fun (reviewers, team_reviewers) ->
let already_requested_or_author = pr.user.login :: List.map ~f:(fun r -> r.login) pr.requested_reviewers in
let already_requested_team = List.map ~f:(fun r -> r.slug) pr.requested_teams in
let reviewers = List.filter ~f:(not $ List.mem already_requested_or_author ~equal:String.equal) reviewers in
let team_reviewers = List.filter ~f:(not $ List.mem already_requested_team ~equal:String.equal) team_reviewers in
if List.is_empty reviewers && List.is_empty team_reviewers then None else Some { reviewers; team_reviewers }
| null | https://raw.githubusercontent.com/ahrefs/monorobot/3be7fa1c78bd01f15ef1aebf0cbfae8faa060f64/lib/github.ml | ocaml | all other events
handle "Merge <any branch> into <feature branch>" commits when they are merged into main branch
we should have already seen these commits on the feature branch but for some reason they are distinct:true
Parse a payload. The type of the payload is detected from the headers.
* [gh_link_of_string s] parses a URL string [s] to try to match a supported
GitHub link type, generating repository endpoints if necessary | open Base
open Devkit
open Printf
open Github_j
type t =
| Push of commit_pushed_notification
| Pull_request of pr_notification
| PR_review of pr_review_notification
| PR_review_comment of pr_review_comment_notification
| Issue of issue_notification
| Issue_comment of issue_comment_notification
| Commit_comment of commit_comment_notification
| Status of status_notification
| Event of event_notification
let repo_of_notification = function
| Push n -> n.repository
| Pull_request n -> n.repository
| PR_review n -> n.repository
| PR_review_comment n -> n.repository
| Issue n -> n.repository
| Issue_comment n -> n.repository
| Commit_comment n -> n.repository
| Status n -> n.repository
| Event n -> n.repository
let commits_branch_of_ref ref =
match String.split ~on:'/' ref with
| "refs" :: "heads" :: l -> String.concat ~sep:"/" l
| _ -> ref
let event_of_filename filename =
match String.split_on_chars ~on:[ '.' ] filename with
| [ kind; _; "json" ] -> Some kind
| _ -> None
let merge_commit_re = Re2.create_exn {|^Merge(?: remote-tracking)? branch '(?:origin/)?.+'(?: of .+)? into (.+)$|}
let is_merge_commit_to_ignore ~(cfg : Config_t.config) ~branch commit =
match cfg.main_branch_name with
| Some main_branch when String.equal branch main_branch ->
let title = Common.first_line commit.message in
begin
try
let receiving_branch = Re2.find_first_exn ~sub:(`Index 1) merge_commit_re title in
not @@ String.equal branch receiving_branch
with Re2.Exceptions.Regex_match_failed _ -> false
end
| Some _ | None -> false
let modified_files_of_commit commit = List.concat [ commit.added; commit.removed; commit.modified ]
let is_valid_signature ~secret headers_sig body =
let request_hash =
let key = Cstruct.of_string secret in
Cstruct.to_string @@ Nocrypto.Hash.SHA1.hmac ~key (Cstruct.of_string body)
in
let (`Hex request_hash) = Hex.of_string request_hash in
String.equal headers_sig (sprintf "sha1=%s" request_hash)
let validate_signature ?signing_key ~headers body =
match signing_key with
| None -> Ok ()
| Some secret ->
match List.Assoc.find headers "x-hub-signature" ~equal:String.equal with
| None -> Error "unable to find header x-hub-signature"
| Some signature -> if is_valid_signature ~secret signature body then Ok () else Error "signatures don't match"
let parse_exn headers body =
match List.Assoc.find_exn headers "x-github-event" ~equal:String.equal with
| exception exn -> Exn.fail ~exn "unable to read x-github-event"
| "push" -> Push (commit_pushed_notification_of_string body)
| "pull_request" -> Pull_request (pr_notification_of_string body)
| "pull_request_review" -> PR_review (pr_review_notification_of_string body)
| "pull_request_review_comment" -> PR_review_comment (pr_review_comment_notification_of_string body)
| "issues" -> Issue (issue_notification_of_string body)
| "issue_comment" -> Issue_comment (issue_comment_notification_of_string body)
| "status" -> Status (status_notification_of_string body)
| "commit_comment" -> Commit_comment (commit_comment_notification_of_string body)
| "member" | "create" | "delete" | "release" -> Event (event_notification_of_string body)
| event -> failwith @@ sprintf "unsupported event : %s" event
type basehead = string * string
type gh_link =
| Pull_request of repository * int
| Issue of repository * int
| Commit of repository * commit_hash
| Compare of repository * basehead
let gh_link_re = Re2.create_exn {|^(.*)/(.+)/(.+)/(commit|pull|issues|compare)/([a-zA-Z0-9/:\-_.~\^%]+)$|}
let commit_sha_re = Re2.create_exn {|[a-f0-9]{4,40}|}
let comparer_re = {|([a-zA-Z0-9/:\-_.~\^]+)|}
let compare_basehead_re = Re2.create_exn (sprintf {|%s([.]{3})%s|} comparer_re comparer_re)
let gh_org_team_re = Re2.create_exn {|[a-zA-Z0-9\-]+/([a-zA-Z0-9\-]+)|}
let gh_link_of_string url_str =
let url = Uri.of_string url_str in
let path = Uri.path url in
let gh_com_html_base owner name = sprintf "" owner name in
let gh_com_api_base owner name = sprintf "" owner name in
let custom_html_base ?(scheme = "https") base owner name = sprintf "%s" scheme base owner name in
let custom_api_base ?(scheme = "https") base owner name =
sprintf "%s" scheme base owner name
in
match Uri.host url with
| None -> None
| Some host ->
match Re2.find_submatches_exn gh_link_re path with
| [| _; prefix; Some owner; Some name; Some link_type; Some item |] ->
let item = Base.String.chop_suffix_if_exists item ~suffix:"/" in
let repo =
let base = Option.value_map prefix ~default:host ~f:(fun p -> String.concat [ host; p ]) in
let scheme = Uri.scheme url in
let html_base, api_base =
if String.is_suffix base ~suffix:"github.com" then gh_com_html_base owner name, gh_com_api_base owner name
else custom_html_base ?scheme base owner name, custom_api_base ?scheme base owner name
in
{
name;
full_name = sprintf "%s/%s" owner name;
url = html_base;
commits_url = sprintf "%s/commits{/sha}" api_base;
contents_url = sprintf "%s/contents/{+path}" api_base;
pulls_url = sprintf "%s/pulls{/number}" api_base;
issues_url = sprintf "%s/issues{/number}" api_base;
compare_url = sprintf "%s/compare{/basehead}" api_base;
}
in
let verify_commit_sha repo item =
try
match Re2.find_submatches_exn commit_sha_re item with
| [| Some sha |] -> Some (Commit (repo, sha))
| _ -> None
with _ -> None
in
let verify_compare_basehead repo basehead =
match Re2.find_submatches_exn compare_basehead_re basehead with
| [| _; Some base; _; Some merge |] -> Some (Compare (repo, (base, merge)))
| _ | (exception Re2.Exceptions.Regex_match_failed _) -> None
in
begin
try
match link_type with
| "pull" -> Some (Pull_request (repo, Int.of_string item))
| "issues" -> Some (Issue (repo, Int.of_string item))
| "commit" -> verify_commit_sha repo item
| "compare" ->
let item = Uri.pct_decode item in
verify_compare_basehead repo item
| _ -> None
with _ -> None
end
| _ | (exception Re2.Exceptions.Regex_match_failed _) -> None
let get_project_owners (pr : pull_request) ({ rules } : Config_t.project_owners) =
Rule.Project_owners.match_rules pr.labels rules
|> List.dedup_and_sort ~compare:String.compare
|> List.partition_map ~f:(fun reviewer ->
try
let team = Re2.find_first_exn ~sub:(`Index 1) gh_org_team_re reviewer in
Second team
with Re2.Exceptions.Regex_match_failed _ -> First reviewer
)
|> fun (reviewers, team_reviewers) ->
let already_requested_or_author = pr.user.login :: List.map ~f:(fun r -> r.login) pr.requested_reviewers in
let already_requested_team = List.map ~f:(fun r -> r.slug) pr.requested_teams in
let reviewers = List.filter ~f:(not $ List.mem already_requested_or_author ~equal:String.equal) reviewers in
let team_reviewers = List.filter ~f:(not $ List.mem already_requested_team ~equal:String.equal) team_reviewers in
if List.is_empty reviewers && List.is_empty team_reviewers then None else Some { reviewers; team_reviewers }
|
74387dc680e35ea25aeed30830f58664bf0eb2c491d379f8cd72511ec64435f6 | lamdu/momentu | MRUMemo.hs | Copied & modified from the public - domain uglymemo package by
- Lennart Augustsson
- Lennart Augustsson
-}
module Data.MRUMemo
( memoIO, memoIOPure, memo
) where
import Control.Concurrent.MVar
import Control.Lens.Operators ((<&>))
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import Prelude
memoIO :: Eq a => (a -> IO b) -> IO (a -> IO b)
memoIO act =
memoized <$> newMVar Nothing
where
memoized var key = modifyMVar var onMVar
where
onMVar j@(Just (oldKey, oldvalue))
| oldKey == key = pure (j, oldvalue)
| otherwise = callOrig
onMVar Nothing = callOrig
callOrig = act key <&> \res -> (Just (key, res), res)
-- | Memoize the given function with a single most-recently-used value
memoIOPure
:: Eq a
=> (a -> b) -- ^Function to memoize
-> IO (a -> IO b)
memoIOPure f =
newIORef Nothing <&>
\lastResultRef x ->
atomicModifyIORef lastResultRef $ \m ->
let r = f x
callOrig = (Just (x, r), r)
in case m of
Nothing -> callOrig
Just (key, val)
| key == x -> (m, val)
| otherwise -> callOrig
| The pure version of ' ' .
memo
:: Eq a
=> (a -> b) -- ^Function to memoize
-> a -> b
memo f = let f' = unsafePerformIO (memoIOPure f)
in unsafePerformIO . f'
| null | https://raw.githubusercontent.com/lamdu/momentu/7ba3c75469cfbad521d446e2bbefee1ed69d4406/src/Data/MRUMemo.hs | haskell | | Memoize the given function with a single most-recently-used value
^Function to memoize
^Function to memoize | Copied & modified from the public - domain uglymemo package by
- Lennart Augustsson
- Lennart Augustsson
-}
module Data.MRUMemo
( memoIO, memoIOPure, memo
) where
import Control.Concurrent.MVar
import Control.Lens.Operators ((<&>))
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import Prelude
memoIO :: Eq a => (a -> IO b) -> IO (a -> IO b)
memoIO act =
memoized <$> newMVar Nothing
where
memoized var key = modifyMVar var onMVar
where
onMVar j@(Just (oldKey, oldvalue))
| oldKey == key = pure (j, oldvalue)
| otherwise = callOrig
onMVar Nothing = callOrig
callOrig = act key <&> \res -> (Just (key, res), res)
memoIOPure
:: Eq a
-> IO (a -> IO b)
memoIOPure f =
newIORef Nothing <&>
\lastResultRef x ->
atomicModifyIORef lastResultRef $ \m ->
let r = f x
callOrig = (Just (x, r), r)
in case m of
Nothing -> callOrig
Just (key, val)
| key == x -> (m, val)
| otherwise -> callOrig
| The pure version of ' ' .
memo
:: Eq a
-> a -> b
memo f = let f' = unsafePerformIO (memoIOPure f)
in unsafePerformIO . f'
|
b753bc168aa2812a7822287de22653cd0d2f18c7e6e69a5e20c8b3ef93238420 | ericnormand/lispcast-clojure-core-async | chapter11.clj | Exercise 1
(defn work-session []
(go
(let [t (async/timeout 10000)]
(loop []
(let [[val ch] (alts! [t
telephone-chan
email-chan
todo-chan] :priority true)]
(if (= ch t)
(println "Break time!")
(do
(do-task val ch)
(recur))))))))
(defn pomodoro []
(go
(work-session)
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Pushup!")
(recur))))))
(work-session)
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Jump!")
(recur))))))
(work-session)
(<! (async/timeout 10000))
(println "Work is done!")))
;; Example
(defn pomodoro []
(go
(<! (work-session))
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Pushup!")
(recur))))))
(<! (work-session))
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Jump!")
(recur))))))
(<! (work-session))
(<! (async/timeout 10000))
(println "Work is done!")))
Exercise 2
(defn break-session [do-exercise]
(go
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(do-exercise)
(recur))))))))
(defn pomodoro []
(go
(<! (work-session))
(<! (break-session (fn [] (println "Pushup!"))))
(<! (work-session))
(<! (break-session (fn [] (println "Jump!"))))
(<! (work-session))
(<! (async/timeout 10000))
(println "Work is done!")))
Exercise 3
(defn work-day []
(go
(<! (pomodoro))
(<! (pomodoro))
(<! (pomodoro))))
| null | https://raw.githubusercontent.com/ericnormand/lispcast-clojure-core-async/ac1140be188a261155eb353928aa03f9f8048eb1/exercises/chapter11.clj | clojure | Example | Exercise 1
(defn work-session []
(go
(let [t (async/timeout 10000)]
(loop []
(let [[val ch] (alts! [t
telephone-chan
email-chan
todo-chan] :priority true)]
(if (= ch t)
(println "Break time!")
(do
(do-task val ch)
(recur))))))))
(defn pomodoro []
(go
(work-session)
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Pushup!")
(recur))))))
(work-session)
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Jump!")
(recur))))))
(work-session)
(<! (async/timeout 10000))
(println "Work is done!")))
(defn pomodoro []
(go
(<! (work-session))
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Pushup!")
(recur))))))
(<! (work-session))
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(println "Jump!")
(recur))))))
(<! (work-session))
(<! (async/timeout 10000))
(println "Work is done!")))
Exercise 2
(defn break-session [do-exercise]
(go
(let [t (async/timeout 5000)]
(loop []
(let [[v c] (alts! [t reps-chan] :priority true)]
(if (= c t)
(println "Work time!")
(do
(do-exercise)
(recur))))))))
(defn pomodoro []
(go
(<! (work-session))
(<! (break-session (fn [] (println "Pushup!"))))
(<! (work-session))
(<! (break-session (fn [] (println "Jump!"))))
(<! (work-session))
(<! (async/timeout 10000))
(println "Work is done!")))
Exercise 3
(defn work-day []
(go
(<! (pomodoro))
(<! (pomodoro))
(<! (pomodoro))))
|
0251a33eee87b09b4cd3e56638f073dc73eeb132ad15269d51f465fb238a6c9b | finnishtransportagency/harja | erilliskustannus_kyselyt.clj | (ns harja.kyselyt.erilliskustannus-kyselyt
"Erilliskustannuksiin liittyvät tietokantakyselyt"
(:require [jeesql.core :refer [defqueries]]
[harja.kyselyt.konversio :as konv]))
(defqueries "harja/kyselyt/erilliskustannus_kyselyt.sql"
{:positional? true})
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/587654c25f7ce458ef87078b2d3a4edd7c7f6159/src/clj/harja/kyselyt/erilliskustannus_kyselyt.clj | clojure | (ns harja.kyselyt.erilliskustannus-kyselyt
"Erilliskustannuksiin liittyvät tietokantakyselyt"
(:require [jeesql.core :refer [defqueries]]
[harja.kyselyt.konversio :as konv]))
(defqueries "harja/kyselyt/erilliskustannus_kyselyt.sql"
{:positional? true})
| |
ebf8995bb1e0be1d4184575dc3b1cecd7808e72b4b10cd79ef9e72f7e2243400 | bsaleil/lc | peval.scm.scm | ;;------------------------------------------------------------------------------
Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
;;------------------------------------------------------------------------------
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
;;------------------------------------------------------------------------------
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
; Gabriel benchmarks
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
; C benchmarks
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
; Other benchmarks
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
PEVAL -- A simple partial evaluator for Scheme , written by .
;------------------------------------------------------------------------------
Utilities
(define (every? pred? l)
(let loop ((l l))
(or (null? l) (and (pred? (car l)) (loop (cdr l))))))
(define (some? pred? l)
(let loop ((l l))
(if (null? l) #f (or (pred? (car l)) (loop (cdr l))))))
(define (map2 f l1 l2)
(let loop ((l1 l1) (l2 l2))
(if (pair? l1)
(cons (f (car l1) (car l2)) (loop (cdr l1) (cdr l2)))
'())))
(define (get-last-pair l)
(let loop ((l l))
(let ((x (cdr l))) (if (pair? x) (loop x) l))))
;------------------------------------------------------------------------------
;
; The partial evaluator.
(define (partial-evaluate proc args)
(peval (alphatize proc '()) args))
(define (alphatize exp env) ; return a copy of 'exp' where each bound var has
(define (alpha exp) ; been renamed (to prevent aliasing problems)
(cond ((const-expr? exp)
(quot (const-value exp)))
((symbol? exp)
(let ((x (assq exp env))) (if x (cdr x) exp)))
((or (eq? (car exp) 'if) (eq? (car exp) 'begin))
(cons (car exp) (map alpha (cdr exp))))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(let ((new-env (new-variables (map car (cadr exp)) env)))
(list (car exp)
(map (lambda (x)
(list (cdr (assq (car x) new-env))
(if (eq? (car exp) 'let)
(alpha (cadr x))
(alphatize (cadr x) new-env))))
(cadr exp))
(alphatize (caddr exp) new-env))))
((eq? (car exp) 'lambda)
(let ((new-env (new-variables (cadr exp) env)))
(list 'lambda
(map (lambda (x) (cdr (assq x new-env))) (cadr exp))
(alphatize (caddr exp) new-env))))
(else
(map alpha exp))))
(alpha exp))
(define (const-expr? expr) ; is 'expr' a constant expression?
(and (not (symbol? expr))
(or (not (pair? expr))
(eq? (car expr) 'quote))))
(define (const-value expr) ; return the value of a constant expression
(if (pair? expr) ; then it must be a quoted constant
(cadr expr)
expr))
(define (quot val) ; make a quoted constant whose value is 'val'
(list 'quote val))
(define (new-variables parms env)
(append (map (lambda (x) (cons x (new-variable x))) parms) env))
(define *current-num* 0)
(define (new-variable name)
(set! *current-num* (+ *current-num* 1))
(string->symbol
(string-append (symbol->string name)
"_"
(number->string *current-num*))))
;------------------------------------------------------------------------------
;
; (peval proc args) will transform a procedure that is known to be called
; with constants as some of its arguments into a specialized procedure that
; is 'equivalent' but accepts only the non-constant parameters. 'proc' is the
; list representation of a lambda-expression and 'args' is a list of values,
; one for each parameter of the lambda-expression. A special value (i.e.
; 'not-constant') is used to indicate an argument that is not a constant.
; The returned procedure is one that has as parameters the parameters of the
; original procedure which are NOT passed constants. Constants will have been
; substituted for the constant parameters that are referenced in the body
; of the procedure.
;
; For example:
;
; (peval
; '(lambda (x y z) (f z x y)) ; the procedure
( list 1 not - constant # t ) ) ; the knowledge about x , y and z
;
; will return: (lambda (y) (f '#t '1 y))
(define (peval proc args)
(simplify!
(let ((parms (cadr proc)) ; get the parameter list
(body (caddr proc))) ; get the body of the procedure
(list 'lambda
(remove-constant parms args) ; remove the constant parameters
(beta-subst ; in the body, replace variable refs to the constant
body ; parameters by the corresponding constant
(map2 (lambda (x y) (if (not-constant? y) '(()) (cons x (quot y))))
parms
args))))))
(define not-constant (list '?)) ; special value indicating non-constant parms.
(define (not-constant? x) (eq? x not-constant))
(define (remove-constant l a) ; remove from list 'l' all elements whose
(cond ((null? l) ; corresponding element in 'a' is a constant
'())
((not-constant? (car a))
(cons (car l) (remove-constant (cdr l) (cdr a))))
(else
(remove-constant (cdr l) (cdr a)))))
(define (extract-constant l a) ; extract from list 'l' all elements whose
(cond ((null? l) ; corresponding element in 'a' is a constant
'())
((not-constant? (car a))
(extract-constant (cdr l) (cdr a)))
(else
(cons (car l) (extract-constant (cdr l) (cdr a))))))
(define (beta-subst exp env) ; return a modified 'exp' where each var named in
(define (bs exp) ; 'env' is replaced by the corresponding expr (it
(cond ((const-expr? exp) ; is assumed that the code has been alphatized)
(quot (const-value exp)))
((symbol? exp)
(let ((x (assq exp env)))
(if x (cdr x) exp)))
((or (eq? (car exp) 'if) (eq? (car exp) 'begin))
(cons (car exp) (map bs (cdr exp))))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(list (car exp)
(map (lambda (x) (list (car x) (bs (cadr x)))) (cadr exp))
(bs (caddr exp))))
((eq? (car exp) 'lambda)
(list 'lambda
(cadr exp)
(bs (caddr exp))))
(else
(map bs exp))))
(bs exp))
;------------------------------------------------------------------------------
;
; The expression simplifier.
(define (simplify! exp) ; simplify the expression 'exp' destructively (it
; is assumed that the code has been alphatized)
(define (simp! where env)
(define (s! where)
(let ((exp (car where)))
(cond ((const-expr? exp)) ; leave constants the way they are
((symbol? exp)) ; leave variable references the way they are
((eq? (car exp) 'if) ; dead code removal for conditionals
(s! (cdr exp)) ; simplify the predicate
(if (const-expr? (cadr exp)) ; is the predicate a constant?
(begin
(set-car! where
(if (memq (const-value (cadr exp)) '(#f ())) ; false?
(if (= (length exp) 3) ''() (cadddr exp))
(caddr exp)))
(s! where))
(for-each! s! (cddr exp)))) ; simplify consequent and alt.
((eq? (car exp) 'begin)
(for-each! s! (cdr exp))
(let loop ((exps exp)) ; remove all useless expressions
(if (not (null? (cddr exps))) ; not last expression?
(let ((x (cadr exps)))
(loop (if (or (const-expr? x)
(symbol? x)
(and (pair? x) (eq? (car x) 'lambda)))
(begin (set-cdr! exps (cddr exps)) exps)
(cdr exps))))))
only one expression in the begin ?
(set-car! where (cadr exp))))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(let ((new-env (cons exp env)))
(define (keep i)
(if (>= i (length (cadar where)))
'()
(let* ((var (car (list-ref (cadar where) i)))
(val (cadr (assq var (cadar where))))
(refs (ref-count (car where) var))
(self-refs (ref-count val var))
(total-refs (- (car refs) (car self-refs)))
(oper-refs (- (cadr refs) (cadr self-refs))))
(cond ((= total-refs 0)
(keep (+ i 1)))
((or (const-expr? val)
(symbol? val)
(and (pair? val)
(eq? (car val) 'lambda)
(= total-refs 1)
(= oper-refs 1)
(= (car self-refs) 0))
(and (caddr refs)
(= total-refs 1)))
(set-car! where
(beta-subst (car where)
(list (cons var val))))
(keep (+ i 1)))
(else
(cons var (keep (+ i 1))))))))
(simp! (cddr exp) new-env)
(for-each! (lambda (x) (simp! (cdar x) new-env)) (cadr exp))
(let ((to-keep (keep 0)))
(if (< (length to-keep) (length (cadar where)))
(begin
(if (null? to-keep)
(set-car! where (caddar where))
(set-car! (cdar where)
(map (lambda (v) (assq v (cadar where))) to-keep)))
(s! where))
(if (null? to-keep)
(set-car! where (caddar where)))))))
((eq? (car exp) 'lambda)
(simp! (cddr exp) (cons exp env)))
(else
(for-each! s! exp)
(cond ((symbol? (car exp)) ; is the operator position a var ref?
(let ((frame (binding-frame (car exp) env)))
(if frame ; is it a bound variable?
(let ((proc (bound-expr (car exp) frame)))
(if (and (pair? proc)
(eq? (car proc) 'lambda)
(some? const-expr? (cdr exp)))
(let* ((args (arg-pattern (cdr exp)))
(new-proc (peval proc args))
(new-args (remove-constant (cdr exp) args)))
(set-car! where
(cons (add-binding new-proc frame (car exp))
new-args)))))
(set-car! where
(constant-fold-global (car exp) (cdr exp))))))
((not (pair? (car exp))))
((eq? (caar exp) 'lambda)
(set-car! where
(list 'let
(map2 list (cadar exp) (cdr exp))
(caddar exp)))
(s! where)))))))
(s! where))
(define (remove-empty-calls! where env)
(define (rec! where)
(let ((exp (car where)))
(cond ((const-expr? exp))
((symbol? exp))
((eq? (car exp) 'if)
(rec! (cdr exp))
(rec! (cddr exp))
(rec! (cdddr exp)))
((eq? (car exp) 'begin)
(for-each! rec! (cdr exp)))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(let ((new-env (cons exp env)))
(remove-empty-calls! (cddr exp) new-env)
(for-each! (lambda (x) (remove-empty-calls! (cdar x) new-env))
(cadr exp))))
((eq? (car exp) 'lambda)
(rec! (cddr exp)))
(else
(for-each! rec! (cdr exp))
(if (and (null? (cdr exp)) (symbol? (car exp)))
(let ((frame (binding-frame (car exp) env)))
(if frame ; is it a bound variable?
(let ((proc (bound-expr (car exp) frame)))
(if (and (pair? proc)
(eq? (car proc) 'lambda))
(begin
(set! changed? #t)
(set-car! where (caddr proc))))))))))))
(rec! where))
(define changed? #f)
(let ((x (list exp)))
(let loop ()
(set! changed? #f)
(simp! x '())
(remove-empty-calls! x '())
(if changed? (loop) (car x)))))
(define (ref-count exp var) ; compute how many references to variable 'var'
(let ((total 0) ; are contained in 'exp'
(oper 0)
(always-evaled #t))
(define (rc exp ae)
(cond ((const-expr? exp))
((symbol? exp)
(if (eq? exp var)
(begin
(set! total (+ total 1))
(set! always-evaled (and ae always-evaled)))))
((eq? (car exp) 'if)
(rc (cadr exp) ae)
(for-each (lambda (x) (rc x #f)) (cddr exp)))
((eq? (car exp) 'begin)
(for-each (lambda (x) (rc x ae)) (cdr exp)))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(for-each (lambda (x) (rc (cadr x) ae)) (cadr exp))
(rc (caddr exp) ae))
((eq? (car exp) 'lambda)
(rc (caddr exp) #f))
(else
(for-each (lambda (x) (rc x ae)) exp)
(if (symbol? (car exp))
(if (eq? (car exp) var) (set! oper (+ oper 1)))))))
(rc exp #t)
(list total oper always-evaled)))
(define (binding-frame var env)
(cond ((null? env) #f)
((or (eq? (caar env) 'let) (eq? (caar env) 'letrec))
(if (assq var (cadar env)) (car env) (binding-frame var (cdr env))))
((eq? (caar env) 'lambda)
(if (memq var (cadar env)) (car env) (binding-frame var (cdr env))))
(else
(fatal-error "ill-formed environment"))))
(define (bound-expr var frame)
(cond ((or (eq? (car frame) 'let) (eq? (car frame) 'letrec))
(cadr (assq var (cadr frame))))
((eq? (car frame) 'lambda)
not-constant)
(else
(fatal-error "ill-formed frame"))))
(define (add-binding val frame name)
(define (find-val val bindings)
(cond ((null? bindings) #f)
((equal? val (cadar bindings)) ; *kludge* equal? is not exactly what
(caar bindings)) ; we want...
(else
(find-val val (cdr bindings)))))
(or (find-val val (cadr frame))
(let ((var (new-variable name)))
(set-cdr! (get-last-pair (cadr frame)) (list (list var val)))
var)))
(define (for-each! proc! l) ; call proc! on each CONS CELL in the list 'l'
(if (not (null? l))
(begin (proc! l) (for-each! proc! (cdr l)))))
(define (arg-pattern exps) ; return the argument pattern (i.e. the list of
(if (null? exps) ; constants in 'exps' but with the not-constant
'() ; value wherever the corresponding expression in
(cons (if (const-expr? (car exps)) ; 'exps' is not a constant)
(const-value (car exps))
not-constant)
(arg-pattern (cdr exps)))))
;------------------------------------------------------------------------------
;
; Knowledge about primitive procedures.
(define *primitives*
(list
(cons 'car (lambda (args)
(and (= (length args) 1)
(pair? (car args))
(quot (car (car args))))))
(cons 'cdr (lambda (args)
(and (= (length args) 1)
(pair? (car args))
(quot (cdr (car args))))))
(cons '+ (lambda (args)
(and (every? number? args)
(quot (sum args 0)))))
(cons '* (lambda (args)
(and (every? number? args)
(quot (product args 1)))))
(cons '- (lambda (args)
(and (> (length args) 0)
(every? number? args)
(quot (if (null? (cdr args))
(- (car args))
(- (car args) (sum (cdr args) 0)))))))
(cons '/ (lambda (args)
(and (> (length args) 1)
(every? number? args)
(quot (if (null? (cdr args))
(/ (car args))
(/ (car args) (product (cdr args) 1)))))))
(cons '< (lambda (args)
(and (= (length args) 2)
(every? number? args)
(quot (< (car args) (cadr args))))))
(cons '= (lambda (args)
(and (= (length args) 2)
(every? number? args)
(quot (= (car args) (cadr args))))))
(cons '> (lambda (args)
(and (= (length args) 2)
(every? number? args)
(quot (> (car args) (cadr args))))))
(cons 'eq? (lambda (args)
(and (= (length args) 2)
(quot (eq? (car args) (cadr args))))))
(cons 'not (lambda (args)
(and (= (length args) 1)
(quot (not (car args))))))
(cons 'null? (lambda (args)
(and (= (length args) 1)
(quot (null? (car args))))))
(cons 'pair? (lambda (args)
(and (= (length args) 1)
(quot (pair? (car args))))))
(cons 'symbol? (lambda (args)
(and (= (length args) 1)
(quot (symbol? (car args))))))
)
)
(define (sum lst n)
(if (null? lst)
n
(sum (cdr lst) (+ n (car lst)))))
(define (product lst n)
(if (null? lst)
n
(product (cdr lst) (* n (car lst)))))
(define (reduce-global name args)
(let ((x (assq name *primitives*)))
(and x ((cdr x) args))))
(define (constant-fold-global name exprs)
(define (flatten args op)
(cond ((null? args)
'())
((and (pair? (car args)) (eq? (caar args) op))
(append (flatten (cdar args) op) (flatten (cdr args) op)))
(else
(cons (car args) (flatten (cdr args) op)))))
(let ((args (if (or (eq? name '+) (eq? name '*)) ; associative ops
(flatten exprs name)
exprs)))
(or (and (every? const-expr? args)
(reduce-global name (map const-value args)))
(let ((pattern (arg-pattern args)))
(let ((non-const (remove-constant args pattern))
(const (map const-value (extract-constant args pattern))))
(cond ((eq? name '+) ; + is commutative
(let ((x (reduce-global '+ const)))
(if x
(let ((y (const-value x)))
(cons '+
(if (= y 0) non-const (cons x non-const))))
(cons name args))))
((eq? name '*) ; * is commutative
(let ((x (reduce-global '* const)))
(if x
(let ((y (const-value x)))
(cons '*
(if (= y 1) non-const (cons x non-const))))
(cons name args))))
((eq? name 'cons)
(cond ((and (const-expr? (cadr args))
(null? (const-value (cadr args))))
(list 'list (car args)))
((and (pair? (cadr args))
(eq? (car (cadr args)) 'list))
(cons 'list (cons (car args) (cdr (cadr args)))))
(else
(cons name args))))
(else
(cons name args))))))))
;------------------------------------------------------------------------------
;
; Examples:
(define (try-peval proc args)
(partial-evaluate proc args))
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example1
'(lambda (a b c)
(if (null? a) b (+ (car a) c))))
( try - peval example1 ( list ' ( 10 11 ) not - constant ' 1 ) )
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example2
'(lambda (x y)
(let ((q (lambda (a b) (if (< a 0) b (- 10 b)))))
(if (< x 0) (q (- y) (- x)) (q y x)))))
;(try-peval example2 (list not-constant '1))
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example3
'(lambda (l n)
(letrec ((add-list
(lambda (l n)
(if (null? l)
'()
(cons (+ (car l) n) (add-list (cdr l) n))))))
(add-list l n))))
( try - peval example3 ( list not - constant ' 1 ) )
;(try-peval example3 (list '(1 2 3) not-constant))
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example4
'(lambda (exp env)
(letrec ((eval
(lambda (exp env)
(letrec ((eval-list
(lambda (l env)
(if (null? l)
'()
(cons (eval (car l) env)
(eval-list (cdr l) env))))))
(if (symbol? exp) (lookup exp env)
(if (not (pair? exp)) exp
(if (eq? (car exp) 'quote) (car (cdr exp))
(apply (eval (car exp) env)
(eval-list (cdr exp) env)))))))))
(eval exp env))))
;(try-peval example4 (list 'x not-constant))
;(try-peval example4 (list '(f 1 2 3) not-constant))
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example5
'(lambda (a b)
(letrec ((funct
(lambda (x)
(+ x b (if (< x 1) 0 (funct (- x 1)))))))
(funct a))))
( try - peval example5 ( list ' 5 not - constant ) )
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example6
'(lambda ()
(letrec ((fib
(lambda (x)
(if (< x 2) x (+ (fib (- x 1)) (fib (- x 2)))))))
(fib 10))))
;(try-peval example6 '())
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example7
'(lambda (input)
(letrec ((copy (lambda (in)
(if (pair? in)
(cons (copy (car in))
(copy (cdr in)))
in))))
(copy input))))
;(try-peval example7 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z)))
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define example8
'(lambda (input)
(letrec ((reverse (lambda (in result)
(if (pair? in)
(reverse (cdr in) (cons (car in) result))
result))))
(reverse input '()))))
( try - peval example8 ( list ' ( a b c d e f g h i j k l m n o p q r s t u v w x y z ) ) )
; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(define (test)
(set! *current-num* 0)
(list (try-peval example1 (list '(10 11) not-constant '1))
(try-peval example2 (list not-constant '1))
(try-peval example3 (list not-constant '1))
(try-peval example3 (list '(1 2 3) not-constant))
(try-peval example4 (list 'x not-constant))
(try-peval example4 (list '(f 1 2 3) not-constant))
(try-peval example5 (list '5 not-constant))
(try-peval example6 '())
(try-peval
example7
(list '(a b c d e f g h i j k l m n o p q r s t u v w x y z)))
(try-peval
example8
(list '(a b c d e f g h i j k l m n o p q r s t u v w x y z)))))
(define (main . args)
(run-benchmark
"peval"
peval-iters
(lambda (result)
(and (list? result)
(= (length result) 10)
(equal? (list-ref result 9)
'(lambda ()
(list 'z 'y 'x 'w 'v 'u 't 's 'r 'q 'p 'o 'n
'm 'l 'k 'j 'i 'h 'g 'f 'e 'd 'c 'b 'a)))))
(lambda () (lambda () (test)))))
(main)
| null | https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultVMIL-lc-gsc-lc/LCnaive/peval.scm.scm | scheme | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Gabriel benchmarks
C benchmarks
Other benchmarks
------------------------------------------------------------------------------
------------------------------------------------------------------------------
The partial evaluator.
return a copy of 'exp' where each bound var has
been renamed (to prevent aliasing problems)
is 'expr' a constant expression?
return the value of a constant expression
then it must be a quoted constant
make a quoted constant whose value is 'val'
------------------------------------------------------------------------------
(peval proc args) will transform a procedure that is known to be called
with constants as some of its arguments into a specialized procedure that
is 'equivalent' but accepts only the non-constant parameters. 'proc' is the
list representation of a lambda-expression and 'args' is a list of values,
one for each parameter of the lambda-expression. A special value (i.e.
'not-constant') is used to indicate an argument that is not a constant.
The returned procedure is one that has as parameters the parameters of the
original procedure which are NOT passed constants. Constants will have been
substituted for the constant parameters that are referenced in the body
of the procedure.
For example:
(peval
'(lambda (x y z) (f z x y)) ; the procedure
the knowledge about x , y and z
will return: (lambda (y) (f '#t '1 y))
get the parameter list
get the body of the procedure
remove the constant parameters
in the body, replace variable refs to the constant
parameters by the corresponding constant
special value indicating non-constant parms.
remove from list 'l' all elements whose
corresponding element in 'a' is a constant
extract from list 'l' all elements whose
corresponding element in 'a' is a constant
return a modified 'exp' where each var named in
'env' is replaced by the corresponding expr (it
is assumed that the code has been alphatized)
------------------------------------------------------------------------------
The expression simplifier.
simplify the expression 'exp' destructively (it
is assumed that the code has been alphatized)
leave constants the way they are
leave variable references the way they are
dead code removal for conditionals
simplify the predicate
is the predicate a constant?
false?
simplify consequent and alt.
remove all useless expressions
not last expression?
is the operator position a var ref?
is it a bound variable?
is it a bound variable?
compute how many references to variable 'var'
are contained in 'exp'
*kludge* equal? is not exactly what
we want...
call proc! on each CONS CELL in the list 'l'
return the argument pattern (i.e. the list of
constants in 'exps' but with the not-constant
value wherever the corresponding expression in
'exps' is not a constant)
------------------------------------------------------------------------------
Knowledge about primitive procedures.
associative ops
+ is commutative
* is commutative
------------------------------------------------------------------------------
Examples:
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(try-peval example2 (list not-constant '1))
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(try-peval example3 (list '(1 2 3) not-constant))
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(try-peval example4 (list 'x not-constant))
(try-peval example4 (list '(f 1 2 3) not-constant))
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(try-peval example6 '())
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
(try-peval example7 (list '(a b c d e f g h i j k l m n o p q r s t u v w x y z)))
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
PEVAL -- A simple partial evaluator for Scheme , written by .
Utilities
(define (every? pred? l)
(let loop ((l l))
(or (null? l) (and (pred? (car l)) (loop (cdr l))))))
(define (some? pred? l)
(let loop ((l l))
(if (null? l) #f (or (pred? (car l)) (loop (cdr l))))))
(define (map2 f l1 l2)
(let loop ((l1 l1) (l2 l2))
(if (pair? l1)
(cons (f (car l1) (car l2)) (loop (cdr l1) (cdr l2)))
'())))
(define (get-last-pair l)
(let loop ((l l))
(let ((x (cdr l))) (if (pair? x) (loop x) l))))
(define (partial-evaluate proc args)
(peval (alphatize proc '()) args))
(cond ((const-expr? exp)
(quot (const-value exp)))
((symbol? exp)
(let ((x (assq exp env))) (if x (cdr x) exp)))
((or (eq? (car exp) 'if) (eq? (car exp) 'begin))
(cons (car exp) (map alpha (cdr exp))))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(let ((new-env (new-variables (map car (cadr exp)) env)))
(list (car exp)
(map (lambda (x)
(list (cdr (assq (car x) new-env))
(if (eq? (car exp) 'let)
(alpha (cadr x))
(alphatize (cadr x) new-env))))
(cadr exp))
(alphatize (caddr exp) new-env))))
((eq? (car exp) 'lambda)
(let ((new-env (new-variables (cadr exp) env)))
(list 'lambda
(map (lambda (x) (cdr (assq x new-env))) (cadr exp))
(alphatize (caddr exp) new-env))))
(else
(map alpha exp))))
(alpha exp))
(and (not (symbol? expr))
(or (not (pair? expr))
(eq? (car expr) 'quote))))
(cadr expr)
expr))
(list 'quote val))
(define (new-variables parms env)
(append (map (lambda (x) (cons x (new-variable x))) parms) env))
(define *current-num* 0)
(define (new-variable name)
(set! *current-num* (+ *current-num* 1))
(string->symbol
(string-append (symbol->string name)
"_"
(number->string *current-num*))))
(define (peval proc args)
(simplify!
(list 'lambda
(map2 (lambda (x y) (if (not-constant? y) '(()) (cons x (quot y))))
parms
args))))))
(define (not-constant? x) (eq? x not-constant))
'())
((not-constant? (car a))
(cons (car l) (remove-constant (cdr l) (cdr a))))
(else
(remove-constant (cdr l) (cdr a)))))
'())
((not-constant? (car a))
(extract-constant (cdr l) (cdr a)))
(else
(cons (car l) (extract-constant (cdr l) (cdr a))))))
(quot (const-value exp)))
((symbol? exp)
(let ((x (assq exp env)))
(if x (cdr x) exp)))
((or (eq? (car exp) 'if) (eq? (car exp) 'begin))
(cons (car exp) (map bs (cdr exp))))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(list (car exp)
(map (lambda (x) (list (car x) (bs (cadr x)))) (cadr exp))
(bs (caddr exp))))
((eq? (car exp) 'lambda)
(list 'lambda
(cadr exp)
(bs (caddr exp))))
(else
(map bs exp))))
(bs exp))
(define (simp! where env)
(define (s! where)
(let ((exp (car where)))
(begin
(set-car! where
(if (= (length exp) 3) ''() (cadddr exp))
(caddr exp)))
(s! where))
((eq? (car exp) 'begin)
(for-each! s! (cdr exp))
(let ((x (cadr exps)))
(loop (if (or (const-expr? x)
(symbol? x)
(and (pair? x) (eq? (car x) 'lambda)))
(begin (set-cdr! exps (cddr exps)) exps)
(cdr exps))))))
only one expression in the begin ?
(set-car! where (cadr exp))))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(let ((new-env (cons exp env)))
(define (keep i)
(if (>= i (length (cadar where)))
'()
(let* ((var (car (list-ref (cadar where) i)))
(val (cadr (assq var (cadar where))))
(refs (ref-count (car where) var))
(self-refs (ref-count val var))
(total-refs (- (car refs) (car self-refs)))
(oper-refs (- (cadr refs) (cadr self-refs))))
(cond ((= total-refs 0)
(keep (+ i 1)))
((or (const-expr? val)
(symbol? val)
(and (pair? val)
(eq? (car val) 'lambda)
(= total-refs 1)
(= oper-refs 1)
(= (car self-refs) 0))
(and (caddr refs)
(= total-refs 1)))
(set-car! where
(beta-subst (car where)
(list (cons var val))))
(keep (+ i 1)))
(else
(cons var (keep (+ i 1))))))))
(simp! (cddr exp) new-env)
(for-each! (lambda (x) (simp! (cdar x) new-env)) (cadr exp))
(let ((to-keep (keep 0)))
(if (< (length to-keep) (length (cadar where)))
(begin
(if (null? to-keep)
(set-car! where (caddar where))
(set-car! (cdar where)
(map (lambda (v) (assq v (cadar where))) to-keep)))
(s! where))
(if (null? to-keep)
(set-car! where (caddar where)))))))
((eq? (car exp) 'lambda)
(simp! (cddr exp) (cons exp env)))
(else
(for-each! s! exp)
(let ((frame (binding-frame (car exp) env)))
(let ((proc (bound-expr (car exp) frame)))
(if (and (pair? proc)
(eq? (car proc) 'lambda)
(some? const-expr? (cdr exp)))
(let* ((args (arg-pattern (cdr exp)))
(new-proc (peval proc args))
(new-args (remove-constant (cdr exp) args)))
(set-car! where
(cons (add-binding new-proc frame (car exp))
new-args)))))
(set-car! where
(constant-fold-global (car exp) (cdr exp))))))
((not (pair? (car exp))))
((eq? (caar exp) 'lambda)
(set-car! where
(list 'let
(map2 list (cadar exp) (cdr exp))
(caddar exp)))
(s! where)))))))
(s! where))
(define (remove-empty-calls! where env)
(define (rec! where)
(let ((exp (car where)))
(cond ((const-expr? exp))
((symbol? exp))
((eq? (car exp) 'if)
(rec! (cdr exp))
(rec! (cddr exp))
(rec! (cdddr exp)))
((eq? (car exp) 'begin)
(for-each! rec! (cdr exp)))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(let ((new-env (cons exp env)))
(remove-empty-calls! (cddr exp) new-env)
(for-each! (lambda (x) (remove-empty-calls! (cdar x) new-env))
(cadr exp))))
((eq? (car exp) 'lambda)
(rec! (cddr exp)))
(else
(for-each! rec! (cdr exp))
(if (and (null? (cdr exp)) (symbol? (car exp)))
(let ((frame (binding-frame (car exp) env)))
(let ((proc (bound-expr (car exp) frame)))
(if (and (pair? proc)
(eq? (car proc) 'lambda))
(begin
(set! changed? #t)
(set-car! where (caddr proc))))))))))))
(rec! where))
(define changed? #f)
(let ((x (list exp)))
(let loop ()
(set! changed? #f)
(simp! x '())
(remove-empty-calls! x '())
(if changed? (loop) (car x)))))
(oper 0)
(always-evaled #t))
(define (rc exp ae)
(cond ((const-expr? exp))
((symbol? exp)
(if (eq? exp var)
(begin
(set! total (+ total 1))
(set! always-evaled (and ae always-evaled)))))
((eq? (car exp) 'if)
(rc (cadr exp) ae)
(for-each (lambda (x) (rc x #f)) (cddr exp)))
((eq? (car exp) 'begin)
(for-each (lambda (x) (rc x ae)) (cdr exp)))
((or (eq? (car exp) 'let) (eq? (car exp) 'letrec))
(for-each (lambda (x) (rc (cadr x) ae)) (cadr exp))
(rc (caddr exp) ae))
((eq? (car exp) 'lambda)
(rc (caddr exp) #f))
(else
(for-each (lambda (x) (rc x ae)) exp)
(if (symbol? (car exp))
(if (eq? (car exp) var) (set! oper (+ oper 1)))))))
(rc exp #t)
(list total oper always-evaled)))
(define (binding-frame var env)
(cond ((null? env) #f)
((or (eq? (caar env) 'let) (eq? (caar env) 'letrec))
(if (assq var (cadar env)) (car env) (binding-frame var (cdr env))))
((eq? (caar env) 'lambda)
(if (memq var (cadar env)) (car env) (binding-frame var (cdr env))))
(else
(fatal-error "ill-formed environment"))))
(define (bound-expr var frame)
(cond ((or (eq? (car frame) 'let) (eq? (car frame) 'letrec))
(cadr (assq var (cadr frame))))
((eq? (car frame) 'lambda)
not-constant)
(else
(fatal-error "ill-formed frame"))))
(define (add-binding val frame name)
(define (find-val val bindings)
(cond ((null? bindings) #f)
(else
(find-val val (cdr bindings)))))
(or (find-val val (cadr frame))
(let ((var (new-variable name)))
(set-cdr! (get-last-pair (cadr frame)) (list (list var val)))
var)))
(if (not (null? l))
(begin (proc! l) (for-each! proc! (cdr l)))))
(const-value (car exps))
not-constant)
(arg-pattern (cdr exps)))))
(define *primitives*
(list
(cons 'car (lambda (args)
(and (= (length args) 1)
(pair? (car args))
(quot (car (car args))))))
(cons 'cdr (lambda (args)
(and (= (length args) 1)
(pair? (car args))
(quot (cdr (car args))))))
(cons '+ (lambda (args)
(and (every? number? args)
(quot (sum args 0)))))
(cons '* (lambda (args)
(and (every? number? args)
(quot (product args 1)))))
(cons '- (lambda (args)
(and (> (length args) 0)
(every? number? args)
(quot (if (null? (cdr args))
(- (car args))
(- (car args) (sum (cdr args) 0)))))))
(cons '/ (lambda (args)
(and (> (length args) 1)
(every? number? args)
(quot (if (null? (cdr args))
(/ (car args))
(/ (car args) (product (cdr args) 1)))))))
(cons '< (lambda (args)
(and (= (length args) 2)
(every? number? args)
(quot (< (car args) (cadr args))))))
(cons '= (lambda (args)
(and (= (length args) 2)
(every? number? args)
(quot (= (car args) (cadr args))))))
(cons '> (lambda (args)
(and (= (length args) 2)
(every? number? args)
(quot (> (car args) (cadr args))))))
(cons 'eq? (lambda (args)
(and (= (length args) 2)
(quot (eq? (car args) (cadr args))))))
(cons 'not (lambda (args)
(and (= (length args) 1)
(quot (not (car args))))))
(cons 'null? (lambda (args)
(and (= (length args) 1)
(quot (null? (car args))))))
(cons 'pair? (lambda (args)
(and (= (length args) 1)
(quot (pair? (car args))))))
(cons 'symbol? (lambda (args)
(and (= (length args) 1)
(quot (symbol? (car args))))))
)
)
(define (sum lst n)
(if (null? lst)
n
(sum (cdr lst) (+ n (car lst)))))
(define (product lst n)
(if (null? lst)
n
(product (cdr lst) (* n (car lst)))))
(define (reduce-global name args)
(let ((x (assq name *primitives*)))
(and x ((cdr x) args))))
(define (constant-fold-global name exprs)
(define (flatten args op)
(cond ((null? args)
'())
((and (pair? (car args)) (eq? (caar args) op))
(append (flatten (cdar args) op) (flatten (cdr args) op)))
(else
(cons (car args) (flatten (cdr args) op)))))
(flatten exprs name)
exprs)))
(or (and (every? const-expr? args)
(reduce-global name (map const-value args)))
(let ((pattern (arg-pattern args)))
(let ((non-const (remove-constant args pattern))
(const (map const-value (extract-constant args pattern))))
(let ((x (reduce-global '+ const)))
(if x
(let ((y (const-value x)))
(cons '+
(if (= y 0) non-const (cons x non-const))))
(cons name args))))
(let ((x (reduce-global '* const)))
(if x
(let ((y (const-value x)))
(cons '*
(if (= y 1) non-const (cons x non-const))))
(cons name args))))
((eq? name 'cons)
(cond ((and (const-expr? (cadr args))
(null? (const-value (cadr args))))
(list 'list (car args)))
((and (pair? (cadr args))
(eq? (car (cadr args)) 'list))
(cons 'list (cons (car args) (cdr (cadr args)))))
(else
(cons name args))))
(else
(cons name args))))))))
(define (try-peval proc args)
(partial-evaluate proc args))
(define example1
'(lambda (a b c)
(if (null? a) b (+ (car a) c))))
( try - peval example1 ( list ' ( 10 11 ) not - constant ' 1 ) )
(define example2
'(lambda (x y)
(let ((q (lambda (a b) (if (< a 0) b (- 10 b)))))
(if (< x 0) (q (- y) (- x)) (q y x)))))
(define example3
'(lambda (l n)
(letrec ((add-list
(lambda (l n)
(if (null? l)
'()
(cons (+ (car l) n) (add-list (cdr l) n))))))
(add-list l n))))
( try - peval example3 ( list not - constant ' 1 ) )
(define example4
'(lambda (exp env)
(letrec ((eval
(lambda (exp env)
(letrec ((eval-list
(lambda (l env)
(if (null? l)
'()
(cons (eval (car l) env)
(eval-list (cdr l) env))))))
(if (symbol? exp) (lookup exp env)
(if (not (pair? exp)) exp
(if (eq? (car exp) 'quote) (car (cdr exp))
(apply (eval (car exp) env)
(eval-list (cdr exp) env)))))))))
(eval exp env))))
(define example5
'(lambda (a b)
(letrec ((funct
(lambda (x)
(+ x b (if (< x 1) 0 (funct (- x 1)))))))
(funct a))))
( try - peval example5 ( list ' 5 not - constant ) )
(define example6
'(lambda ()
(letrec ((fib
(lambda (x)
(if (< x 2) x (+ (fib (- x 1)) (fib (- x 2)))))))
(fib 10))))
(define example7
'(lambda (input)
(letrec ((copy (lambda (in)
(if (pair? in)
(cons (copy (car in))
(copy (cdr in)))
in))))
(copy input))))
(define example8
'(lambda (input)
(letrec ((reverse (lambda (in result)
(if (pair? in)
(reverse (cdr in) (cons (car in) result))
result))))
(reverse input '()))))
( try - peval example8 ( list ' ( a b c d e f g h i j k l m n o p q r s t u v w x y z ) ) )
(define (test)
(set! *current-num* 0)
(list (try-peval example1 (list '(10 11) not-constant '1))
(try-peval example2 (list not-constant '1))
(try-peval example3 (list not-constant '1))
(try-peval example3 (list '(1 2 3) not-constant))
(try-peval example4 (list 'x not-constant))
(try-peval example4 (list '(f 1 2 3) not-constant))
(try-peval example5 (list '5 not-constant))
(try-peval example6 '())
(try-peval
example7
(list '(a b c d e f g h i j k l m n o p q r s t u v w x y z)))
(try-peval
example8
(list '(a b c d e f g h i j k l m n o p q r s t u v w x y z)))))
(define (main . args)
(run-benchmark
"peval"
peval-iters
(lambda (result)
(and (list? result)
(= (length result) 10)
(equal? (list-ref result 9)
'(lambda ()
(list 'z 'y 'x 'w 'v 'u 't 's 'r 'q 'p 'o 'n
'm 'l 'k 'j 'i 'h 'g 'f 'e 'd 'c 'b 'a)))))
(lambda () (lambda () (test)))))
(main)
|
22dec2238047d446c8b6041ff01130854df7a0b4d2ca0cb8dd525654f3c4c2ec | crategus/cl-cffi-gtk | application-menu.lisp | ;;; Example Application Menu - 2021-10-10
(in-package :gtk-application)
(defparameter *menu-ui*
"<interface>
<menu id='menubar'>
<submenu>
<attribute name='label'>File</attribute>
</submenu>
<submenu>
<attribute name='label'>Edit</attribute>
</submenu>
<submenu>
<attribute name='label'>View</attribute>
<section>
<item>
<attribute name='label'>Toolbar</attribute>
<attribute name='action'>win.toolbar</attribute>
</item>
<item>
<attribute name='label'>Statusbar</attribute>
<attribute name='action'>win.statusbar</attribute>
</item>
</section>
<section>
<item>
<attribute name='label'>Fullscreen</attribute>
<attribute name='action'>win.fullscreen</attribute>
</item>
</section>
<section>
<submenu>
<attribute name='label'>Highlight Mode</attribute>
<section>
<attribute name='label'>Sources</attribute>
<item>
<attribute name='label'>Vala</attribute>
<attribute name='action'>win.sources</attribute>
<attribute name='target'>vala</attribute>
</item>
<item>
<attribute name='label'>Python</attribute>
<attribute name='action'>win.sources</attribute>
<attribute name='target'>phyton</attribute>
</item>
</section>
<section>
<attribute name='label'>Markup</attribute>
<item>
<attribute name='label'>asciidoc</attribute>
<attribute name='action'>win.markup</attribute>
<attribute name='target'>asciidoc</attribute>
</item>
<item>
<attribute name='label'>HTML</attribute>
<attribute name='action'>win.markup</attribute>
<attribute name='target'>html</attribute>
</item>
</section>
</submenu>
</section>
</submenu>
<submenu>
<attribute name='label'>Help</attribute>
</submenu>
</menu>
</interface>")
(defun change-state (action parameter)
(format t "~%in CHANGE-STATE~%")
(format t " action : ~a~%" (g-action-name action))
(format t " parameter : ~a~%" (g-variant-boolean parameter))
(setf (g-action-state action) parameter))
(defun change-radio-state (action parameter)
(format t "~%in CHANGE-RADIO-STATE~%")
(format t " action : ~a~%" (g-action-name action))
(format t " parameter : ~a~%" (g-variant-string parameter))
(setf (g-action-state action) parameter))
(defun application-menu (&rest argv)
(let (;; Create an application
(app (make-instance 'gtk-application
:application-id "com.crategus.application-menu"
:flags :none)))
Connect signal " startup " to the application
(g-signal-connect app "startup"
(lambda (application)
Intitialize the application menu and the menubar
(let ((builder (make-instance 'gtk-builder)))
;; Read the menus from a string
(gtk-builder-add-from-string builder *menu-ui*)
;; Set the application menu
(setf (gtk-application-app-menu application)
(gtk-builder-object builder "app-menu"))
;; Set the menubar
(setf (gtk-application-menubar application)
(gtk-builder-object builder "menubar")))))
Connect signal " activate " to the application
(g-signal-connect app "activate"
(lambda (application)
;; Create an application window
(let (;; Define action entries for the menu items
(entries (list
(list "toolbar" nil nil "true" #'change-state)
(list "statusbar" nil nil "false" #'change-state)
(list "fullscreen" nil nil "false" #'change-state)
(list "sources"
nil
"s"
"'vala'"
#'change-radio-state)
(list "markup"
nil
"s"
"'html'"
#'change-radio-state)))
(window (make-instance 'gtk-application-window
:application application
:title "Application Menu"
:default-width 480
:default-height 300)))
;; Add the action entries to the application window
(g-action-map-add-action-entries window entries)
;; Show the application window
(gtk-widget-show-all window))))
;; Run the application
(g-application-run app argv)))
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/7f5a09f78d8004a71efa82794265f2587fff98ab/demo/gtk-application/application-menu.lisp | lisp | Example Application Menu - 2021-10-10
Create an application
Read the menus from a string
Set the application menu
Set the menubar
Create an application window
Define action entries for the menu items
Add the action entries to the application window
Show the application window
Run the application |
(in-package :gtk-application)
(defparameter *menu-ui*
"<interface>
<menu id='menubar'>
<submenu>
<attribute name='label'>File</attribute>
</submenu>
<submenu>
<attribute name='label'>Edit</attribute>
</submenu>
<submenu>
<attribute name='label'>View</attribute>
<section>
<item>
<attribute name='label'>Toolbar</attribute>
<attribute name='action'>win.toolbar</attribute>
</item>
<item>
<attribute name='label'>Statusbar</attribute>
<attribute name='action'>win.statusbar</attribute>
</item>
</section>
<section>
<item>
<attribute name='label'>Fullscreen</attribute>
<attribute name='action'>win.fullscreen</attribute>
</item>
</section>
<section>
<submenu>
<attribute name='label'>Highlight Mode</attribute>
<section>
<attribute name='label'>Sources</attribute>
<item>
<attribute name='label'>Vala</attribute>
<attribute name='action'>win.sources</attribute>
<attribute name='target'>vala</attribute>
</item>
<item>
<attribute name='label'>Python</attribute>
<attribute name='action'>win.sources</attribute>
<attribute name='target'>phyton</attribute>
</item>
</section>
<section>
<attribute name='label'>Markup</attribute>
<item>
<attribute name='label'>asciidoc</attribute>
<attribute name='action'>win.markup</attribute>
<attribute name='target'>asciidoc</attribute>
</item>
<item>
<attribute name='label'>HTML</attribute>
<attribute name='action'>win.markup</attribute>
<attribute name='target'>html</attribute>
</item>
</section>
</submenu>
</section>
</submenu>
<submenu>
<attribute name='label'>Help</attribute>
</submenu>
</menu>
</interface>")
(defun change-state (action parameter)
(format t "~%in CHANGE-STATE~%")
(format t " action : ~a~%" (g-action-name action))
(format t " parameter : ~a~%" (g-variant-boolean parameter))
(setf (g-action-state action) parameter))
(defun change-radio-state (action parameter)
(format t "~%in CHANGE-RADIO-STATE~%")
(format t " action : ~a~%" (g-action-name action))
(format t " parameter : ~a~%" (g-variant-string parameter))
(setf (g-action-state action) parameter))
(defun application-menu (&rest argv)
(app (make-instance 'gtk-application
:application-id "com.crategus.application-menu"
:flags :none)))
Connect signal " startup " to the application
(g-signal-connect app "startup"
(lambda (application)
Intitialize the application menu and the menubar
(let ((builder (make-instance 'gtk-builder)))
(gtk-builder-add-from-string builder *menu-ui*)
(setf (gtk-application-app-menu application)
(gtk-builder-object builder "app-menu"))
(setf (gtk-application-menubar application)
(gtk-builder-object builder "menubar")))))
Connect signal " activate " to the application
(g-signal-connect app "activate"
(lambda (application)
(entries (list
(list "toolbar" nil nil "true" #'change-state)
(list "statusbar" nil nil "false" #'change-state)
(list "fullscreen" nil nil "false" #'change-state)
(list "sources"
nil
"s"
"'vala'"
#'change-radio-state)
(list "markup"
nil
"s"
"'html'"
#'change-radio-state)))
(window (make-instance 'gtk-application-window
:application application
:title "Application Menu"
:default-width 480
:default-height 300)))
(g-action-map-add-action-entries window entries)
(gtk-widget-show-all window))))
(g-application-run app argv)))
|
28fbf394c3eacd270259037c98ccda9aef68fbf5e2a1398e41e841c67b93b56a | edicl/cl-interpol | util.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - INTERPOL ; Base : 10 -*-
$ Header : /usr / local / cvsrep / cl - interpol / util.lisp , v 1.12 2008/07/23 14:41:37 edi Exp $
Copyright ( c ) 2003 - 2008 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-interpol)
(define-condition simple-reader-error (simple-condition reader-error)
()
(:documentation "A reader error which can be signalled by ERROR."))
(defmacro signal-reader-error (format-control &rest format-arguments)
"Like ERROR but signals a SIMPLE-READER-ERROR for the stream
*STREAM*."
`(error 'simple-reader-error
:stream *stream*
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
(defun string-list-to-string (string-list)
"Concatenates a list of strings to one string."
this function was originally provided by JP Massar for CL - PPCRE ;
;; note that we can't use APPLY with CONCATENATE here because of
;; CALL-ARGUMENTS-LIMIT
(let ((total-size 0))
(dolist (string string-list)
(incf total-size (length string)))
(let ((result-string (make-array total-size :element-type 'character))
(curr-pos 0))
(dolist (string string-list)
(replace result-string string :start1 curr-pos)
(incf curr-pos (length string)))
result-string)))
(defun get-end-delimiter (start-delimiter delimiters &key errorp)
"Find the closing delimiter corresponding to the opening delimiter
START-DELIMITER in a list DELIMITERS which is formatted like
*OUTER-DELIMITERS*. If ERRORP is true, signal an error if none was
found, otherwise return NIL."
(loop for element in delimiters
if (eql start-delimiter element)
do (return-from get-end-delimiter start-delimiter)
else if (and (consp element)
(char= start-delimiter (car element)))
do (return-from get-end-delimiter (cdr element)))
(when errorp
(signal-reader-error "~S not allowed as a delimiter here" start-delimiter)))
(declaim (inline make-collector))
(defun make-collector ()
"Create an empty string which can be extended by
VECTOR-PUSH-EXTEND."
(make-array 0
:element-type 'character
:fill-pointer t
:adjustable t))
(declaim (inline make-char-from-code))
(defun make-char-from-code (number)
"Create character from char-code NUMBER. NUMBER can be NIL which is
interpreted as 0."
Only look at rightmost eight bits in compliance with Perl
(let ((code (logand #o377 (or number 0))))
(or (and (< code char-code-limit)
(code-char code))
(signal-reader-error "No character for char-code #x~X"
number))))
(declaim (inline lower-case-p*))
(defun lower-case-p* (char)
"Whether CHAR is a character which has case and is lowercase."
(or (not (both-case-p char))
(lower-case-p char)))
(defmacro read-char* ()
"Convenience macro because we always read from the same string with
the same arguments."
`(read-char *stream* t nil t))
(defmacro peek-char* ()
"Convenience macro because we always peek at the same string with
the same arguments."
`(peek-char nil *stream* t nil t))
(declaim (inline copy-readtable*))
(defun copy-readtable* ()
"Returns a copy of the readtable which was current when
INTERPOL-READER was invoked. Memoizes its result."
(or *readtable-copy*
(setq *readtable-copy* (copy-readtable))))
(declaim (inline nsubvec))
(defun nsubvec (sequence start &optional (end (length sequence)))
"Return a subvector by pointing to location in original vector."
(make-array (- end start)
:element-type (array-element-type sequence)
:displaced-to sequence
:displaced-index-offset start))
| null | https://raw.githubusercontent.com/edicl/cl-interpol/70a1137f41dd8889004dbab9536b1adeac2497aa/util.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - INTERPOL ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
note that we can't use APPLY with CONCATENATE here because of
CALL-ARGUMENTS-LIMIT | $ Header : /usr / local / cvsrep / cl - interpol / util.lisp , v 1.12 2008/07/23 14:41:37 edi Exp $
Copyright ( c ) 2003 - 2008 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :cl-interpol)
(define-condition simple-reader-error (simple-condition reader-error)
()
(:documentation "A reader error which can be signalled by ERROR."))
(defmacro signal-reader-error (format-control &rest format-arguments)
"Like ERROR but signals a SIMPLE-READER-ERROR for the stream
*STREAM*."
`(error 'simple-reader-error
:stream *stream*
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
(defun string-list-to-string (string-list)
"Concatenates a list of strings to one string."
(let ((total-size 0))
(dolist (string string-list)
(incf total-size (length string)))
(let ((result-string (make-array total-size :element-type 'character))
(curr-pos 0))
(dolist (string string-list)
(replace result-string string :start1 curr-pos)
(incf curr-pos (length string)))
result-string)))
(defun get-end-delimiter (start-delimiter delimiters &key errorp)
"Find the closing delimiter corresponding to the opening delimiter
START-DELIMITER in a list DELIMITERS which is formatted like
*OUTER-DELIMITERS*. If ERRORP is true, signal an error if none was
found, otherwise return NIL."
(loop for element in delimiters
if (eql start-delimiter element)
do (return-from get-end-delimiter start-delimiter)
else if (and (consp element)
(char= start-delimiter (car element)))
do (return-from get-end-delimiter (cdr element)))
(when errorp
(signal-reader-error "~S not allowed as a delimiter here" start-delimiter)))
(declaim (inline make-collector))
(defun make-collector ()
"Create an empty string which can be extended by
VECTOR-PUSH-EXTEND."
(make-array 0
:element-type 'character
:fill-pointer t
:adjustable t))
(declaim (inline make-char-from-code))
(defun make-char-from-code (number)
"Create character from char-code NUMBER. NUMBER can be NIL which is
interpreted as 0."
Only look at rightmost eight bits in compliance with Perl
(let ((code (logand #o377 (or number 0))))
(or (and (< code char-code-limit)
(code-char code))
(signal-reader-error "No character for char-code #x~X"
number))))
(declaim (inline lower-case-p*))
(defun lower-case-p* (char)
"Whether CHAR is a character which has case and is lowercase."
(or (not (both-case-p char))
(lower-case-p char)))
(defmacro read-char* ()
"Convenience macro because we always read from the same string with
the same arguments."
`(read-char *stream* t nil t))
(defmacro peek-char* ()
"Convenience macro because we always peek at the same string with
the same arguments."
`(peek-char nil *stream* t nil t))
(declaim (inline copy-readtable*))
(defun copy-readtable* ()
"Returns a copy of the readtable which was current when
INTERPOL-READER was invoked. Memoizes its result."
(or *readtable-copy*
(setq *readtable-copy* (copy-readtable))))
(declaim (inline nsubvec))
(defun nsubvec (sequence start &optional (end (length sequence)))
"Return a subvector by pointing to location in original vector."
(make-array (- end start)
:element-type (array-element-type sequence)
:displaced-to sequence
:displaced-index-offset start))
|
2648530482bcc78c8ca232deebda3b601682cf33076b5b9f73f2c65b4d24c19c | mbj/stratosphere | DimensionProperty.hs | module Stratosphere.NetworkFirewall.RuleGroup.DimensionProperty (
DimensionProperty(..), mkDimensionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data DimensionProperty
= DimensionProperty {value :: (Value Prelude.Text)}
mkDimensionProperty :: Value Prelude.Text -> DimensionProperty
mkDimensionProperty value = DimensionProperty {value = value}
instance ToResourceProperties DimensionProperty where
toResourceProperties DimensionProperty {..}
= ResourceProperties
{awsType = "AWS::NetworkFirewall::RuleGroup.Dimension",
supportsTags = Prelude.False, properties = ["Value" JSON..= value]}
instance JSON.ToJSON DimensionProperty where
toJSON DimensionProperty {..} = JSON.object ["Value" JSON..= value]
instance Property "Value" DimensionProperty where
type PropertyType "Value" DimensionProperty = Value Prelude.Text
set newValue DimensionProperty {}
= DimensionProperty {value = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/networkfirewall/gen/Stratosphere/NetworkFirewall/RuleGroup/DimensionProperty.hs | haskell | module Stratosphere.NetworkFirewall.RuleGroup.DimensionProperty (
DimensionProperty(..), mkDimensionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data DimensionProperty
= DimensionProperty {value :: (Value Prelude.Text)}
mkDimensionProperty :: Value Prelude.Text -> DimensionProperty
mkDimensionProperty value = DimensionProperty {value = value}
instance ToResourceProperties DimensionProperty where
toResourceProperties DimensionProperty {..}
= ResourceProperties
{awsType = "AWS::NetworkFirewall::RuleGroup.Dimension",
supportsTags = Prelude.False, properties = ["Value" JSON..= value]}
instance JSON.ToJSON DimensionProperty where
toJSON DimensionProperty {..} = JSON.object ["Value" JSON..= value]
instance Property "Value" DimensionProperty where
type PropertyType "Value" DimensionProperty = Value Prelude.Text
set newValue DimensionProperty {}
= DimensionProperty {value = newValue, ..} | |
f61f0fae4ced8082f15810ad5615c22f95288a8174a4306ff56951184a065268 | tolysz/ghcjs-stack | Main.hs | module Main where
import Foo
main :: IO ()
main = return ()
| null | https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal/Cabal/tests/PackageTests/PreProcess/Main.hs | haskell | module Main where
import Foo
main :: IO ()
main = return ()
| |
02d98b3d473599485995307811a360ea7a8155bae08ac1373d810705dc2e83df | reanimate/reanimate | 09_Camera.hs | animation :: Animation
animation = docEnv $ mapA (withFillOpacity 1) $ scene $ do
cam <- newObject Camera
txt <- newObject $ center $ latex "Fixed (non-cam)"
oModifyS txt $ do
oTopY .= screenTop
oZIndex .= 2
circle <- newObject $ withFillColor "blue" $ mkCircle 1
cameraAttach cam circle
circleRight <- oRead circle oRightX
box <- newObject $ withFillColor "green" $ mkRect 2 2
cameraAttach cam box
oModify box $ oLeftX .~ circleRight
boxCenter <- oRead box oCenterXY
small <- newObject $ center $ latex "This text is very small"
cameraAttach cam small
oModifyS small $ do
oCenterXY .= boxCenter
oScale .= 0.1
oShow txt
oShow small
oShow circle
oShow box
wait 1
cameraFocus cam boxCenter
waitOn $ do
fork $ cameraPan cam 3 boxCenter
fork $ cameraZoom cam 3 15
wait 2
cameraZoom cam 3 1
cameraPan cam 1 (V2 0 0)
| null | https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/playground/snippets/09_Camera.hs | haskell | animation :: Animation
animation = docEnv $ mapA (withFillOpacity 1) $ scene $ do
cam <- newObject Camera
txt <- newObject $ center $ latex "Fixed (non-cam)"
oModifyS txt $ do
oTopY .= screenTop
oZIndex .= 2
circle <- newObject $ withFillColor "blue" $ mkCircle 1
cameraAttach cam circle
circleRight <- oRead circle oRightX
box <- newObject $ withFillColor "green" $ mkRect 2 2
cameraAttach cam box
oModify box $ oLeftX .~ circleRight
boxCenter <- oRead box oCenterXY
small <- newObject $ center $ latex "This text is very small"
cameraAttach cam small
oModifyS small $ do
oCenterXY .= boxCenter
oScale .= 0.1
oShow txt
oShow small
oShow circle
oShow box
wait 1
cameraFocus cam boxCenter
waitOn $ do
fork $ cameraPan cam 3 boxCenter
fork $ cameraZoom cam 3 15
wait 2
cameraZoom cam 3 1
cameraPan cam 1 (V2 0 0)
| |
9d2a03f00f62660b196bf4eed4951db9fbb1b713daf5d2d6649a32bbd0b52923 | krajj7/BotHack | item.clj | (ns bothack.item
(:require [clojure.tools.logging :as log]
[clojure.string :as string]
[bothack.itemtype :refer :all]
[bothack.delegator :refer :all]
[bothack.itemid :refer :all]
[bothack.util :refer :all]))
(def ^:private item-fields
[:slot :qty :buc :grease :poison :erosion1 :erosion2 :proof :used :eaten
:diluted :enchantment :name :generic :specific :recharges :charges :candles
:lit-candelabrum :lit :laid :chained :quivered :offhand :offhand-wielded
:wielded :worn :cost1 :cost2 :cost3])
(defn- erosion [s]
(if (and s (some #(.contains s %) ["burnt" "rusty" "rotted" "corroded"]))
(condp #(.contains %2 %1) s
"very" 2
"thoroughly" 3
1)))
(def ^:private item-re #"^(?:([\w\#\$])\s[+-]\s)?\s*([Aa]n?|[Tt]he|\d+)?\s*(blessed|(?:un)?cursed|(?:un)?holy)?\s*(greased)?\s*(poisoned)?\s*((?:(?:very|thoroughly) )?(?:burnt|rusty))?\s*((?:(?:very|thoroughly) )?(?:rotted|corroded))?\s*(fixed|(?:fire|rust|corrode)proof)?\s*(partly used)?\s*(partly eaten)?\s*(diluted)?\s*([+-]\d+)?\s*(?:(?:pair|set) of)?\s*\b(.*?)\s*(?:called (.*?))?\s*(?:named (.*?))?\s*(?:\((\d+):(-?\d+)\))?\s*(?:\((no|[1-7]) candles?(, lit| attached)\))?\s*(\(lit\))?\s*(\(laid by you\))?\s*(\(chained to you\))?\s*(\(in quiver\))?\s*(\(altern.*?\)?)?\s*(\(wielded i.*?\))?\s*(\((?:weapo?n?|wield?e?d?).*?\)?)?\s*(\((?:bei?n?g?|emb?e?d?d?e?d?|on?).*?\)?)?\s*(?:\(unpaid, (\d+) zorkmids?\)|\((\d+) zorkmids?\)|, no charge(?:, .*)?|, (?:price )?(\d+) zorkmids( each)?(?:, .*)?)?\.?\s*$")
(defn parse-label [label]
for uniques ( " Lord 's partly eaten corpse " = > " partly eaten Lord 's corpse "
#"(?:the )?(.*) partly eaten corpse$"
"partly eaten $1 corpse")
raw (zipmap item-fields (re-first-groups item-re norm-label))]
;(log/debug raw)
(as-> raw res
(if-let [buc (re-first-group #"^potions? of ((?:un)?holy) water$"
(:name res))]
(assoc res
:name "potion of water"
:buc (if (= buc "holy") "blessed" "cursed"))
res)
(update res :name (partial re-first-group #"([^(]*)( \(.*)?$"))
(update res :name #(get jap->eng % %))
(update res :name #(get plural->singular % %))
(assoc res :lit (or (:lit res)
(and (:lit-candelabrum res)
(.contains (:lit-candelabrum res) "lit"))))
(assoc res :in-use (first (keep res [:wielded :worn])))
(assoc res :cost (first (keep res [:cost1 :cost2 :cost3])))
(update res :qty #(if (and % (re-seq #"[0-9]+" %))
(parse-int %)
1))
(if (:candles raw)
(update res :candles #(if (= % "no") 0 (parse-int %)))
res)
(reduce #(update %1 %2 str->kw) res [:buc :proof])
(if (and (not (:buc res))
(or (:charges raw)
(:enchantment raw)
(= "Amulet of Yendor" (:name res))))
(assoc res :buc :uncursed)
res)
(reduce #(update %1 %2 parse-int) res
(filter (comp seq res) [:cost :enchantment :charges :recharges]))
(assoc res :erosion ((fnil max 0 0) (erosion (:erosion1 res))
(erosion (:erosion2 res))))
(dissoc res :cost1 :cost2 :cost3 :lit-candelabrum :erosion1 :erosion2 :slot)
(into {:label label} (filter (comp some? val) res)))))
(defn safe-buc?
"Known not to be cursed?"
[item]
(#{:uncursed :blessed} (:buc item)))
(defn cursed? [item]
(= :cursed (:buc item)))
(defn uncursed? [item]
(= :uncursed (:buc item)))
(defn noncursed? [item]
(not= :cursed (:buc item)))
(defn blessed? [item]
(= :blessed (:buc item)))
(defn single? [item]
(= 1 (:qty item)))
(defn corpse? [item]
(re-seq #" corpses?\b" (:name item)))
(defn corpse->monster [item]
(:monster (name->item (:name item))))
(defn can-take? [item]
(not (:cost item)))
(defn candle? [item]
(.contains (:name item) "candle"))
(defmacro ^:private def-itemtype-pred [kw]
`(defn ~(symbol (str (subs (str kw) 1) \?)) [~'item]
(= ~kw (item-type ~'item))))
#_(pprint (macroexpand-1 '(def-itemtype-pred :food)))
(defmacro ^:private def-itemtype-preds
"defines item type predicates: food? armor? tool? etc."
[]
`(do ~@(for [kw (keys item-kinds)]
`(def-itemtype-pred ~kw))))
(def-itemtype-preds)
(defn tin? [item]
(and (food? item)
(re-seq #"\btins?\b" (:name item))))
(defn shield? [item]
(= :shield (item-subtype item)))
(defn gloves? [item]
(= :gloves (item-subtype item)))
(defn boots? [item]
(= :boots (item-subtype item)))
(defn container? [item]
(some? (re-seq #"^bag\b|sack$|chest$|box$" (:name item))))
(defn bag? [item]
(some? (re-seq #"^bag\b|sack$" (:name item))))
(defn know-contents? [item]
(or (not (container? item))
(= "bag of tricks" (:name item))
(some? (:items item))))
(defn boh?
([item]
(= "bag of holding" (:name item)))
([game item]
(= "bag of holding" (item-name game item))))
(defn water? [item]
(= "potion of water" (:name item)))
(defn holy-water? [item]
(and (water? item) (= :blessed (:buc item))))
(def explorable-container? (every-pred (complement know-contents?)
(complement :locked)
(some-fn noncursed?
(complement boh?))))
(def candelabrum "Candelabrum of Invocation")
(def bell "Bell of Opening")
(def book "Book of the Dead")
(defn dagger? [item]
(.contains (:name item) "dagger"))
(def daggers (->> (:weapon item-kinds)
(filter dagger?)
(map :name)
set))
(defn ammo? [item]
(or (.contains (:name item) "arrow")
(.contains (:name item) "bolt")))
(defn dart? [item]
(.contains (:name item) "dart"))
(def ammo (->> (:weapon item-kinds)
(filter (some-fn ammo? dart?))
(map :name)
set))
(defn short-sword? [item]
(.contains (:name item) "short sword"))
(defn rocks? [item]
(= "rock" (:name item)))
(defn egg? [item]
(re-seq #"\begg\b" (:name item)))
(defn artifact? [item]
(:artifact (or (name->item (:specific item))
(name->item (:name item)))))
(defn nw-ratio
"Nutrition/weight ratio of item"
[item]
(let [id (item-id item)]
(if (not= :food (typekw id))
0
((fnil / 0) (:nutrition id) (:weight id)))))
(defn gold? [item]
(= "gold piece" (:name item)))
(defn key? [item]
(.contains (:name item) "key"))
(defn price-id?
([game item]
(and (price-id? item)
(not (know-price? game item))))
([item]
(and (not (artifact? item))
(not (candle? item))
(not (container? item))
(knowable-appearance? (appearance-of item))
((some-fn tool? ring? scroll? wand? potion? armor?) item))))
(defn wished? [item]
(= "wish" (:specific item)))
(defn safe? [game item]
(or (weapon? item)
(tool? item)
(and (or (safe-buc? item) (:in-use item) (wished? item))
(:safe (item-id game item)))))
(defn shops-taking [item]
(-> (case (item-type item)
:armor #{:armor :weapon}
:weapon #{:armor :weapon}
:scroll #{:book}
:spellbook #{:book}
:amulet #{:gem}
:ring #{:gem}
#{(item-type item)})
(conj :general)))
(defn enchantment [item]
(or (:enchantment item) 0))
(defn charged? [item]
(and (not= "empty" (:specific item))
(not ((fnil zero? 1) (:charges item)))))
(defn recharged? [item]
(or (= "recharged" (:specific item))
(not ((fnil zero? 0) (:recharges item)))))
(defn pick? [item]
(#{"pick-axe" "dwarvish mattock"} (:name item)))
(defn safe-enchant? [item]
(and (some? (:enchantment item))
(case (item-type item)
:weapon (> 6 (enchantment item))
:armor (> 4 (enchantment item))
nil)))
(defn two-handed? [item]
(= 2 (:hands (item-id item))))
(defrecord Item
[label
name
generic ; called
specific ; named
qty
buc ; nil :uncursed :cursed :blessed
0 - 3
proof ; :fixed :rustproof :fireproof ...
enchantment ; nil or number
charges
recharges
in-use ; worn / wielded
not to be confused with ItemType price
bothack.bot.items.IItem
(quantity [item] (:qty item))
(label [item] (:label item))
(name [item] (:name item))
(buc [item] (kw->enum bothack.bot.items.BUC (:buc item)))
(erosion [item] (:erosion item))
(isFixed [item] (boolean (:proof item)))
(enchantment [item] (:enchantment item))
(charges [item] (:charges item))
(recharges [item] (:recharges item))
(isRecharged [item] (boolean (recharged? item)))
(isCharged [item] (boolean (charged? item)))
(isTwohanded [item] (boolean (two-handed? item)))
(isSafeToEnchant [item] (boolean (safe-enchant? item)))
(isArtifact [item] (boolean (artifact? item)))
(type [item] (item-id item))
(possibilities [item] (initial-ids item))
(cost [item] (:cost item))
(isInUse [item] (boolean (:in-use item)))
(isWorn [item] (boolean (:worn item)))
(isContainer [item] (container? item))
(knowContents [item] (know-contents? item))
(contents [item] (:items item))
(isCorpse [item] (boolean (corpse? item)))
(isWielded [item] (boolean (:wielded item))))
(defn label->item [label]
(map->Item (parse-label label)))
(defn slot-item
"Turns a string 'h - an octagonal amulet (being worn)' or [char String] pair
into a [char Item] pair"
([s]
(if-let [[slot label] (re-first-groups #"\s*(.) ?[-+#] (.*)\s*$" s)]
(slot-item (.charAt slot 0) label)))
([chr label]
[chr (label->item label)]))
| null | https://raw.githubusercontent.com/krajj7/BotHack/70226b3c8ed12d29c64068aec0acc0ca71d57adf/src/bothack/item.clj | clojure | (log/debug raw)
called
named
nil :uncursed :cursed :blessed
:fixed :rustproof :fireproof ...
nil or number
worn / wielded | (ns bothack.item
(:require [clojure.tools.logging :as log]
[clojure.string :as string]
[bothack.itemtype :refer :all]
[bothack.delegator :refer :all]
[bothack.itemid :refer :all]
[bothack.util :refer :all]))
(def ^:private item-fields
[:slot :qty :buc :grease :poison :erosion1 :erosion2 :proof :used :eaten
:diluted :enchantment :name :generic :specific :recharges :charges :candles
:lit-candelabrum :lit :laid :chained :quivered :offhand :offhand-wielded
:wielded :worn :cost1 :cost2 :cost3])
(defn- erosion [s]
(if (and s (some #(.contains s %) ["burnt" "rusty" "rotted" "corroded"]))
(condp #(.contains %2 %1) s
"very" 2
"thoroughly" 3
1)))
(def ^:private item-re #"^(?:([\w\#\$])\s[+-]\s)?\s*([Aa]n?|[Tt]he|\d+)?\s*(blessed|(?:un)?cursed|(?:un)?holy)?\s*(greased)?\s*(poisoned)?\s*((?:(?:very|thoroughly) )?(?:burnt|rusty))?\s*((?:(?:very|thoroughly) )?(?:rotted|corroded))?\s*(fixed|(?:fire|rust|corrode)proof)?\s*(partly used)?\s*(partly eaten)?\s*(diluted)?\s*([+-]\d+)?\s*(?:(?:pair|set) of)?\s*\b(.*?)\s*(?:called (.*?))?\s*(?:named (.*?))?\s*(?:\((\d+):(-?\d+)\))?\s*(?:\((no|[1-7]) candles?(, lit| attached)\))?\s*(\(lit\))?\s*(\(laid by you\))?\s*(\(chained to you\))?\s*(\(in quiver\))?\s*(\(altern.*?\)?)?\s*(\(wielded i.*?\))?\s*(\((?:weapo?n?|wield?e?d?).*?\)?)?\s*(\((?:bei?n?g?|emb?e?d?d?e?d?|on?).*?\)?)?\s*(?:\(unpaid, (\d+) zorkmids?\)|\((\d+) zorkmids?\)|, no charge(?:, .*)?|, (?:price )?(\d+) zorkmids( each)?(?:, .*)?)?\.?\s*$")
(defn parse-label [label]
for uniques ( " Lord 's partly eaten corpse " = > " partly eaten Lord 's corpse "
#"(?:the )?(.*) partly eaten corpse$"
"partly eaten $1 corpse")
raw (zipmap item-fields (re-first-groups item-re norm-label))]
(as-> raw res
(if-let [buc (re-first-group #"^potions? of ((?:un)?holy) water$"
(:name res))]
(assoc res
:name "potion of water"
:buc (if (= buc "holy") "blessed" "cursed"))
res)
(update res :name (partial re-first-group #"([^(]*)( \(.*)?$"))
(update res :name #(get jap->eng % %))
(update res :name #(get plural->singular % %))
(assoc res :lit (or (:lit res)
(and (:lit-candelabrum res)
(.contains (:lit-candelabrum res) "lit"))))
(assoc res :in-use (first (keep res [:wielded :worn])))
(assoc res :cost (first (keep res [:cost1 :cost2 :cost3])))
(update res :qty #(if (and % (re-seq #"[0-9]+" %))
(parse-int %)
1))
(if (:candles raw)
(update res :candles #(if (= % "no") 0 (parse-int %)))
res)
(reduce #(update %1 %2 str->kw) res [:buc :proof])
(if (and (not (:buc res))
(or (:charges raw)
(:enchantment raw)
(= "Amulet of Yendor" (:name res))))
(assoc res :buc :uncursed)
res)
(reduce #(update %1 %2 parse-int) res
(filter (comp seq res) [:cost :enchantment :charges :recharges]))
(assoc res :erosion ((fnil max 0 0) (erosion (:erosion1 res))
(erosion (:erosion2 res))))
(dissoc res :cost1 :cost2 :cost3 :lit-candelabrum :erosion1 :erosion2 :slot)
(into {:label label} (filter (comp some? val) res)))))
(defn safe-buc?
"Known not to be cursed?"
[item]
(#{:uncursed :blessed} (:buc item)))
(defn cursed? [item]
(= :cursed (:buc item)))
(defn uncursed? [item]
(= :uncursed (:buc item)))
(defn noncursed? [item]
(not= :cursed (:buc item)))
(defn blessed? [item]
(= :blessed (:buc item)))
(defn single? [item]
(= 1 (:qty item)))
(defn corpse? [item]
(re-seq #" corpses?\b" (:name item)))
(defn corpse->monster [item]
(:monster (name->item (:name item))))
(defn can-take? [item]
(not (:cost item)))
(defn candle? [item]
(.contains (:name item) "candle"))
(defmacro ^:private def-itemtype-pred [kw]
`(defn ~(symbol (str (subs (str kw) 1) \?)) [~'item]
(= ~kw (item-type ~'item))))
#_(pprint (macroexpand-1 '(def-itemtype-pred :food)))
(defmacro ^:private def-itemtype-preds
"defines item type predicates: food? armor? tool? etc."
[]
`(do ~@(for [kw (keys item-kinds)]
`(def-itemtype-pred ~kw))))
(def-itemtype-preds)
(defn tin? [item]
(and (food? item)
(re-seq #"\btins?\b" (:name item))))
(defn shield? [item]
(= :shield (item-subtype item)))
(defn gloves? [item]
(= :gloves (item-subtype item)))
(defn boots? [item]
(= :boots (item-subtype item)))
(defn container? [item]
(some? (re-seq #"^bag\b|sack$|chest$|box$" (:name item))))
(defn bag? [item]
(some? (re-seq #"^bag\b|sack$" (:name item))))
(defn know-contents? [item]
(or (not (container? item))
(= "bag of tricks" (:name item))
(some? (:items item))))
(defn boh?
([item]
(= "bag of holding" (:name item)))
([game item]
(= "bag of holding" (item-name game item))))
(defn water? [item]
(= "potion of water" (:name item)))
(defn holy-water? [item]
(and (water? item) (= :blessed (:buc item))))
(def explorable-container? (every-pred (complement know-contents?)
(complement :locked)
(some-fn noncursed?
(complement boh?))))
(def candelabrum "Candelabrum of Invocation")
(def bell "Bell of Opening")
(def book "Book of the Dead")
(defn dagger? [item]
(.contains (:name item) "dagger"))
(def daggers (->> (:weapon item-kinds)
(filter dagger?)
(map :name)
set))
(defn ammo? [item]
(or (.contains (:name item) "arrow")
(.contains (:name item) "bolt")))
(defn dart? [item]
(.contains (:name item) "dart"))
(def ammo (->> (:weapon item-kinds)
(filter (some-fn ammo? dart?))
(map :name)
set))
(defn short-sword? [item]
(.contains (:name item) "short sword"))
(defn rocks? [item]
(= "rock" (:name item)))
(defn egg? [item]
(re-seq #"\begg\b" (:name item)))
(defn artifact? [item]
(:artifact (or (name->item (:specific item))
(name->item (:name item)))))
(defn nw-ratio
"Nutrition/weight ratio of item"
[item]
(let [id (item-id item)]
(if (not= :food (typekw id))
0
((fnil / 0) (:nutrition id) (:weight id)))))
(defn gold? [item]
(= "gold piece" (:name item)))
(defn key? [item]
(.contains (:name item) "key"))
(defn price-id?
([game item]
(and (price-id? item)
(not (know-price? game item))))
([item]
(and (not (artifact? item))
(not (candle? item))
(not (container? item))
(knowable-appearance? (appearance-of item))
((some-fn tool? ring? scroll? wand? potion? armor?) item))))
(defn wished? [item]
(= "wish" (:specific item)))
(defn safe? [game item]
(or (weapon? item)
(tool? item)
(and (or (safe-buc? item) (:in-use item) (wished? item))
(:safe (item-id game item)))))
(defn shops-taking [item]
(-> (case (item-type item)
:armor #{:armor :weapon}
:weapon #{:armor :weapon}
:scroll #{:book}
:spellbook #{:book}
:amulet #{:gem}
:ring #{:gem}
#{(item-type item)})
(conj :general)))
(defn enchantment [item]
(or (:enchantment item) 0))
(defn charged? [item]
(and (not= "empty" (:specific item))
(not ((fnil zero? 1) (:charges item)))))
(defn recharged? [item]
(or (= "recharged" (:specific item))
(not ((fnil zero? 0) (:recharges item)))))
(defn pick? [item]
(#{"pick-axe" "dwarvish mattock"} (:name item)))
(defn safe-enchant? [item]
(and (some? (:enchantment item))
(case (item-type item)
:weapon (> 6 (enchantment item))
:armor (> 4 (enchantment item))
nil)))
(defn two-handed? [item]
(= 2 (:hands (item-id item))))
(defrecord Item
[label
name
qty
0 - 3
charges
recharges
not to be confused with ItemType price
bothack.bot.items.IItem
(quantity [item] (:qty item))
(label [item] (:label item))
(name [item] (:name item))
(buc [item] (kw->enum bothack.bot.items.BUC (:buc item)))
(erosion [item] (:erosion item))
(isFixed [item] (boolean (:proof item)))
(enchantment [item] (:enchantment item))
(charges [item] (:charges item))
(recharges [item] (:recharges item))
(isRecharged [item] (boolean (recharged? item)))
(isCharged [item] (boolean (charged? item)))
(isTwohanded [item] (boolean (two-handed? item)))
(isSafeToEnchant [item] (boolean (safe-enchant? item)))
(isArtifact [item] (boolean (artifact? item)))
(type [item] (item-id item))
(possibilities [item] (initial-ids item))
(cost [item] (:cost item))
(isInUse [item] (boolean (:in-use item)))
(isWorn [item] (boolean (:worn item)))
(isContainer [item] (container? item))
(knowContents [item] (know-contents? item))
(contents [item] (:items item))
(isCorpse [item] (boolean (corpse? item)))
(isWielded [item] (boolean (:wielded item))))
(defn label->item [label]
(map->Item (parse-label label)))
(defn slot-item
"Turns a string 'h - an octagonal amulet (being worn)' or [char String] pair
into a [char Item] pair"
([s]
(if-let [[slot label] (re-first-groups #"\s*(.) ?[-+#] (.*)\s*$" s)]
(slot-item (.charAt slot 0) label)))
([chr label]
[chr (label->item label)]))
|
97220344a17591bfb10ceafb8b85f1fe69028d2ac7529afb116a09ab9de48db6 | alanz/ghc-exactprint | Issue91.hs | module Issue91 where
Based on -exactprint/issues/91
foo = case hi of
_ -> hi
_ -> hi
_ -> hi
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc88/Issue91.hs | haskell | module Issue91 where
Based on -exactprint/issues/91
foo = case hi of
_ -> hi
_ -> hi
_ -> hi
| |
c1d9112b37373450431c94e579306872e47cff83ce39f81b8ec281387cc4b58f | mirage/ptt | relay_map.ml | let src = Logs.Src.create "ptt.relay-map"
module Log = (val Logs.src_log src)
type t = {
postmaster: Emile.mailbox
; domain: [ `host ] Domain_name.t
; map: (Emile.local, Colombe.Forward_path.t list) Hashtbl.t
}
let postmaster {postmaster; _} = postmaster
let domain {domain; _} = domain
let empty ~postmaster ~domain = {postmaster; domain; map= Hashtbl.create 256}
let add ~local mailbox t =
match Colombe_emile.to_forward_path mailbox with
| Error (`Msg err) -> invalid_arg err
| Ok mailbox -> (
Log.debug (fun m ->
m "Add %a with %a." Emile.pp_local local Colombe.Forward_path.pp mailbox)
; try
let rest = Hashtbl.find t.map local in
if not (List.exists (Colombe.Forward_path.equal mailbox) rest) then
Hashtbl.add t.map local (mailbox :: rest)
; t
with Not_found ->
Hashtbl.add t.map local [mailbox]
; t)
let exists reverse_path t =
match reverse_path with
| None -> false
| Some {Colombe.Path.local; domain= Domain vs; _} ->
let domain' = Domain_name.(host_exn (of_strings_exn vs)) in
Domain_name.equal t.domain domain'
&& Hashtbl.mem t.map (Colombe_emile.of_local local)
| _ -> false
let recipients ~local {map; _} =
match Hashtbl.find map local with
| recipients -> recipients
| exception Not_found ->
Log.err (fun m -> m "%a not found into our local map." Emile.pp_local local)
; []
let all t = Hashtbl.fold (fun _ vs a -> vs @ a) t.map []
let ( <.> ) f g x = f (g x)
let expand t unresolved resolved =
let open Aggregate in
let fold domain elt (unresolved, resolved) =
if not (Domain_name.equal domain t.domain) then
By_domain.add domain elt unresolved, resolved
else
let open Colombe in
let open Forward_path in
let fold (unresolved, resolved) = function
| Postmaster -> (
let local = t.postmaster.Emile.local in
let domain, _ = t.postmaster.Emile.domain in
match domain with
| `Domain vs ->
let domain = Domain_name.(host_exn <.> of_strings_exn) vs in
add_unresolved ~domain `Postmaster unresolved, resolved
| `Addr (Emile.IPv4 v4) ->
unresolved, add_resolved (Ipaddr.V4 v4) (`Local local) resolved
| `Addr (Emile.IPv6 v6) ->
unresolved, add_resolved (Ipaddr.V6 v6) (`Local local) resolved
| `Addr (Emile.Ext _) | `Literal _ -> unresolved, resolved)
| Domain (Domain.Domain v) ->
let domain = Domain_name.(host_exn <.> of_strings_exn) v in
add_unresolved ~domain `All unresolved, resolved
| Forward_path {Path.domain= Domain.Domain v; Path.local; _} ->
let domain = Domain_name.(host_exn <.> of_strings_exn) v in
let local = Colombe_emile.of_local local in
add_unresolved ~domain (`Local local) unresolved, resolved
| Forward_path {Path.domain= Domain.IPv4 v4; Path.local; _} ->
let local = Colombe_emile.of_local local in
unresolved, add_resolved (Ipaddr.V4 v4) (`Local local) resolved
| Forward_path {Path.domain= Domain.IPv6 v6; Path.local; _} ->
let local = Colombe_emile.of_local local in
unresolved, add_resolved (Ipaddr.V6 v6) (`Local local) resolved
| Domain (Domain.IPv4 v4) ->
unresolved, add_resolved (Ipaddr.V4 v4) `All resolved
| Domain (Domain.IPv6 v6) ->
unresolved, add_resolved (Ipaddr.V6 v6) `All resolved
| Forward_path {Path.domain= Domain.Extension _; _} ->
unresolved, resolved
| Domain (Domain.Extension _) -> unresolved, resolved in
match elt with
| `Postmaster -> List.fold_left fold (unresolved, resolved) [Postmaster]
| `All -> List.fold_left fold (unresolved, resolved) (all t)
| `Local vs ->
Log.debug (fun m ->
m "Replace locals %a by their destinations."
Fmt.(Dump.list Emile.pp_local)
vs)
; let vs =
List.fold_left (fun a local -> recipients ~local t @ a) [] vs in
List.fold_left fold (unresolved, resolved) vs in
By_domain.fold fold unresolved (By_domain.empty, resolved)
| null | https://raw.githubusercontent.com/mirage/ptt/80411d4e1eedc989fe4f092d60ed9d56bfd2dbcf/lib/relay_map.ml | ocaml | let src = Logs.Src.create "ptt.relay-map"
module Log = (val Logs.src_log src)
type t = {
postmaster: Emile.mailbox
; domain: [ `host ] Domain_name.t
; map: (Emile.local, Colombe.Forward_path.t list) Hashtbl.t
}
let postmaster {postmaster; _} = postmaster
let domain {domain; _} = domain
let empty ~postmaster ~domain = {postmaster; domain; map= Hashtbl.create 256}
let add ~local mailbox t =
match Colombe_emile.to_forward_path mailbox with
| Error (`Msg err) -> invalid_arg err
| Ok mailbox -> (
Log.debug (fun m ->
m "Add %a with %a." Emile.pp_local local Colombe.Forward_path.pp mailbox)
; try
let rest = Hashtbl.find t.map local in
if not (List.exists (Colombe.Forward_path.equal mailbox) rest) then
Hashtbl.add t.map local (mailbox :: rest)
; t
with Not_found ->
Hashtbl.add t.map local [mailbox]
; t)
let exists reverse_path t =
match reverse_path with
| None -> false
| Some {Colombe.Path.local; domain= Domain vs; _} ->
let domain' = Domain_name.(host_exn (of_strings_exn vs)) in
Domain_name.equal t.domain domain'
&& Hashtbl.mem t.map (Colombe_emile.of_local local)
| _ -> false
let recipients ~local {map; _} =
match Hashtbl.find map local with
| recipients -> recipients
| exception Not_found ->
Log.err (fun m -> m "%a not found into our local map." Emile.pp_local local)
; []
let all t = Hashtbl.fold (fun _ vs a -> vs @ a) t.map []
let ( <.> ) f g x = f (g x)
let expand t unresolved resolved =
let open Aggregate in
let fold domain elt (unresolved, resolved) =
if not (Domain_name.equal domain t.domain) then
By_domain.add domain elt unresolved, resolved
else
let open Colombe in
let open Forward_path in
let fold (unresolved, resolved) = function
| Postmaster -> (
let local = t.postmaster.Emile.local in
let domain, _ = t.postmaster.Emile.domain in
match domain with
| `Domain vs ->
let domain = Domain_name.(host_exn <.> of_strings_exn) vs in
add_unresolved ~domain `Postmaster unresolved, resolved
| `Addr (Emile.IPv4 v4) ->
unresolved, add_resolved (Ipaddr.V4 v4) (`Local local) resolved
| `Addr (Emile.IPv6 v6) ->
unresolved, add_resolved (Ipaddr.V6 v6) (`Local local) resolved
| `Addr (Emile.Ext _) | `Literal _ -> unresolved, resolved)
| Domain (Domain.Domain v) ->
let domain = Domain_name.(host_exn <.> of_strings_exn) v in
add_unresolved ~domain `All unresolved, resolved
| Forward_path {Path.domain= Domain.Domain v; Path.local; _} ->
let domain = Domain_name.(host_exn <.> of_strings_exn) v in
let local = Colombe_emile.of_local local in
add_unresolved ~domain (`Local local) unresolved, resolved
| Forward_path {Path.domain= Domain.IPv4 v4; Path.local; _} ->
let local = Colombe_emile.of_local local in
unresolved, add_resolved (Ipaddr.V4 v4) (`Local local) resolved
| Forward_path {Path.domain= Domain.IPv6 v6; Path.local; _} ->
let local = Colombe_emile.of_local local in
unresolved, add_resolved (Ipaddr.V6 v6) (`Local local) resolved
| Domain (Domain.IPv4 v4) ->
unresolved, add_resolved (Ipaddr.V4 v4) `All resolved
| Domain (Domain.IPv6 v6) ->
unresolved, add_resolved (Ipaddr.V6 v6) `All resolved
| Forward_path {Path.domain= Domain.Extension _; _} ->
unresolved, resolved
| Domain (Domain.Extension _) -> unresolved, resolved in
match elt with
| `Postmaster -> List.fold_left fold (unresolved, resolved) [Postmaster]
| `All -> List.fold_left fold (unresolved, resolved) (all t)
| `Local vs ->
Log.debug (fun m ->
m "Replace locals %a by their destinations."
Fmt.(Dump.list Emile.pp_local)
vs)
; let vs =
List.fold_left (fun a local -> recipients ~local t @ a) [] vs in
List.fold_left fold (unresolved, resolved) vs in
By_domain.fold fold unresolved (By_domain.empty, resolved)
| |
8fd850eab1d0f63d3d5ca28be5c76d94c6cea7a6b0b8e54a18649ca6eb0494dd | semilin/layoup | evtest4.lisp |
(MAKE-LAYOUT :NAME "evtest4" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX
NIL :KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/evtest4.lisp | lisp |
(MAKE-LAYOUT :NAME "evtest4" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX
NIL :KEYBOARD NIL) | |
6b80604d65538845091187830809910f3e6b04942b136bad589fd69ff9196372 | CodyReichert/qi | package.lisp | ;;;
Copyright ( c ) 2007 , All Rights Reserved
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(defpackage #:salza2
(:use #:cl)
(:export
;; misc
#:reset
;; compressor
#:deflate-compressor
#:callback
#:write-bits
#:write-octet
#:write-octet-vector
#:start-data-format
#:compress-octet
#:compress-octet-vector
#:process-input
#:finish-data-format
#:finish-compression
#:with-compressor
;; zlib
#:zlib-compressor
;; gzip
#:gzip-compressor
;; checksum
#:update
#:result
#:result-octets
#:adler32-checksum
#:crc32-checksum
;; user
#:make-stream-output-callback
#:gzip-stream
#:gzip-file
#:compress-data))
| null | https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/salza2/package.lisp | lisp |
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
misc
compressor
zlib
gzip
checksum
user | Copyright ( c ) 2007 , All Rights Reserved
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(defpackage #:salza2
(:use #:cl)
(:export
#:reset
#:deflate-compressor
#:callback
#:write-bits
#:write-octet
#:write-octet-vector
#:start-data-format
#:compress-octet
#:compress-octet-vector
#:process-input
#:finish-data-format
#:finish-compression
#:with-compressor
#:zlib-compressor
#:gzip-compressor
#:update
#:result
#:result-octets
#:adler32-checksum
#:crc32-checksum
#:make-stream-output-callback
#:gzip-stream
#:gzip-file
#:compress-data))
|
dff9be2d81a17269b41030888bed7676421e83e1a14a4929ea692ae81a96067d | altenwald/rdbms | rdbms_table_test.erl | -module(rdbms_table_test).
-include_lib("eunit/include/eunit.hrl").
setup() ->
rdbms_cluster:start_master(),
ok.
teardown(_) ->
rdbms_cluster:leave(rdbms),
ok.
all_test_() ->
{foreach,
local,
fun setup/0,
fun teardown/1,
[
fun create_table_test/1
]
}.
create_table_test(_) ->
[
?_assertEqual(ok, rdbms_table:create_table(<<"users500">>, [<<"id">>, <<"name">>])),
?_assertEqual([<<"id">>, <<"name">>], rdbms_table:attrib_names(<<"users500">>))
].
| null | https://raw.githubusercontent.com/altenwald/rdbms/2972173281ae1ac3bcce836c5fda4751395f7c23/test/rdbms_table_test.erl | erlang | -module(rdbms_table_test).
-include_lib("eunit/include/eunit.hrl").
setup() ->
rdbms_cluster:start_master(),
ok.
teardown(_) ->
rdbms_cluster:leave(rdbms),
ok.
all_test_() ->
{foreach,
local,
fun setup/0,
fun teardown/1,
[
fun create_table_test/1
]
}.
create_table_test(_) ->
[
?_assertEqual(ok, rdbms_table:create_table(<<"users500">>, [<<"id">>, <<"name">>])),
?_assertEqual([<<"id">>, <<"name">>], rdbms_table:attrib_names(<<"users500">>))
].
| |
68550c59b82e4a6b262cdc7b80fd9f10e56ef19e89a6485dcb7da823e35280e2 | stchang/macrotypes | stlc+reco+var-tests.rkt | #lang s-exp macrotypes/examples/stlc+reco+var
(require "rackunit-typechecking.rkt")
(check-type (λ ([n : Int]) (var b = (tup [c = n]) as (∨ [b : (× [c : Int])])))
: (→ Int (∨ [b : (× [c : Int])])))
;; define-type-alias
(define-type-alias Integer Int)
(define-type-alias ArithBinOp (→ Int Int Int))
( define - type - alias C Complex ) ; error , Complex undefined
(check-type ((λ ([x : Int]) (+ x 2)) 3) : Integer)
(check-type ((λ ([x : Integer]) (+ x 2)) 3) : Int)
(check-type ((λ ([x : Integer]) (+ x 2)) 3) : Integer)
(check-type + : ArithBinOp)
(check-type (λ ([f : ArithBinOp]) (f 1 2)) : (→ (→ Int Int Int) Int))
; records (ie labeled tuples)
(check-type "Stephen" : String)
(check-type (tup) : (×))
(check-type (tup [name = "Stephen"]) : (× [name : String]))
(check-type (proj (tup [name = "Stephen"]) name) : String ⇒ "Stephen")
(check-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [name : String] [phone : Int] [male? : Bool]))
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) name)
: String ⇒ "Stephen")
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) name)
: String ⇒ "Stephen")
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) phone)
: Int ⇒ 781)
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) male?)
: Bool ⇒ #t)
(check-not-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [my-name : String] [phone : Int] [male? : Bool]))
(check-not-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [name : String] [my-phone : Int] [male? : Bool]))
(check-not-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [name : String] [phone : Int] [is-male? : Bool]))
;; record errors
(typecheck-fail
(proj 1 "a")
#:with-msg
"expected identifier")
(typecheck-fail
(proj 1 a)
#:with-msg
"Expected expression 1 to have × type, got: Int")
;; variants
(check-type (var coffee = (void) as (∨ [coffee : Unit])) : (∨ [coffee : Unit]))
(check-not-type (var coffee = (void) as (∨ [coffee : Unit])) : (∨ [coffee : Unit] [tea : Unit]))
(typecheck-fail ((λ ([x : (∨ [coffee : Unit] [tea : Unit])]) x)
(var coffee = (void) as (∨ [coffee : Unit])))
#:with-msg
"expected: +\\(∨ \\(coffee : Unit\\) \\(tea : Unit\\)\\)\n *given: +\\(∨ \\(coffee : Unit\\)\\)")
(check-type (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit])) :
(∨ [coffee : Unit] [tea : Unit]))
(check-type (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit] [coke : Unit]))
: (∨ [coffee : Unit] [tea : Unit] [coke : Unit]))
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => 1])
#:with-msg "wrong number of case clauses")
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => 1]
[teaaaaaa x => 2])
#:with-msg "case clauses not exhaustive")
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => 1]
[tea x => 2]
[coke x => 3])
#:with-msg "wrong number of case clauses")
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => "1"]
[tea x => 2])
#:with-msg "branches have incompatible types: String and Int")
(check-type
(case (var coffee = 1 as (∨ [coffee : Int] [tea : Unit]))
[coffee x => x]
[tea x => 2]) : Int ⇒ 1)
(define-type-alias Drink (∨ [coffee : Int] [tea : Unit] [coke : Bool]))
(check-type ((λ ([x : Int]) (+ x x)) 10) : Int ⇒ 20)
(check-type (λ ([x : Int]) (+ (+ x x) (+ x x))) : (→ Int Int))
(check-type
(case ((λ ([d : Drink]) d)
(var coffee = 1 as (∨ [coffee : Int] [tea : Unit] [coke : Bool])))
[coffee x => (+ (+ x x) (+ x x))]
[tea x => 2]
[coke y => 3])
: Int ⇒ 4)
(check-type
(case ((λ ([d : Drink]) d) (var coffee = 1 as Drink))
[coffee x => (+ (+ x x) (+ x x))]
[tea x => 2]
[coke y => 3])
: Int ⇒ 4)
;; variant errors
(typecheck-fail
(var name = "Steve" as Int)
#:with-msg
"Expected the expected type to be a ∨ type, got: Int")
(typecheck-fail
(case 1 [racket x => 1])
#:with-msg
"Expected ∨ type, got: Int")
(typecheck-fail
(λ ([x : (∨)]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ 1)]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ 1\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [1 2])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(1 2\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [a 2])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(a 2\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [a Int])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(a Int\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [1 : Int])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(1 : Int\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [a : 1])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(a : 1\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
;; previous tuple tests: ------------------------------------------------------------
;; wont work anymore
;;(check-type (tup 1 2 3) : (× Int Int Int))
;;(check-type (tup 1 "1" #f +) : (× Int String Bool (→ Int Int Int)))
( check - not - type ( tup 1 " 1 " # f + ) : ( × Unit ( → Int Int Int ) ) )
;;(check-not-type (tup 1 "1" #f +) : (× Int Unit Bool (→ Int Int Int)))
;;(check-not-type (tup 1 "1" #f +) : (× Int String Unit (→ Int Int Int)))
;;(check-not-type (tup 1 "1" #f +) : (× Int String Bool (→ Int Int Unit)))
;;
( check - type ( proj ( tup 1 " 2 " # f ) 0 ) : Int ⇒ 1 )
( check - type ( proj ( tup 1 " 2 " # f ) 1 ) : String ⇒ " 2 " )
( check - type ( proj ( tup 1 " 2 " # f ) 2 ) : ⇒ # f )
( typecheck - fail ( proj ( tup 1 " 2 " # f ) 3 ) ) ; index too large
( typecheck - fail ( proj 1 2 ) ) ; not tuple
;; ext-stlc.rkt tests ---------------------------------------------------------
;; should still pass
;; new literals and base types
(check-type "one" : String) ; literal now supported
(check-type #f : Bool) ; literal now supported
(check-type (λ ([x : Bool]) x) : (→ Bool Bool)) ; Bool is now valid type
;; Unit
(check-type (void) : Unit)
(check-type void : (→ Unit))
(typecheck-fail ((λ ([x : Unit]) x) 2))
(typecheck-fail ((λ ([x : Unit])) void))
(check-type ((λ ([x : Unit]) x) (void)) : Unit)
;; begin
(typecheck-fail (begin))
(check-type (begin 1) : Int)
( typecheck - fail ( begin 1 2 3 ) )
(check-type (begin (void) 1) : Int ⇒ 1)
;;ascription
(typecheck-fail (ann 1 : Bool))
(check-type (ann 1 : Int) : Int ⇒ 1)
(check-type ((λ ([x : Int]) (ann x : Int)) 10) : Int ⇒ 10)
;; let
(check-type (let () (+ 1 1)) : Int ⇒ 2)
(check-type (let ([x 10]) (+ 1 2)) : Int)
(typecheck-fail (let ([x #f]) (+ x 1)))
(check-type (let ([x 10] [y 20]) ((λ ([z : Int] [a : Int]) (+ a z)) x y)) : Int ⇒ 30)
(typecheck-fail (let ([x 10] [y (+ x 1)]) (+ x y))) ; unbound identifier
(check-type (let* ([x 10] [y (+ x 1)]) (+ x y)) : Int ⇒ 21)
(typecheck-fail (let* ([x #t] [y (+ x 1)]) 1))
;; letrec
(typecheck-fail (letrec ([(x : Int) #f] [(y : Int) 1]) y))
(typecheck-fail (letrec ([(y : Int) 1] [(x : Int) #f]) x))
(check-type (letrec ([(x : Int) 1] [(y : Int) (+ x 1)]) (+ x y)) : Int ⇒ 3)
;; recursive
(check-type
(letrec ([(countdown : (→ Int String))
(λ ([i : Int])
(if (= i 0)
"liftoff"
(countdown (- i 1))))])
(countdown 10)) : String ⇒ "liftoff")
;; mutually recursive
(check-type
(letrec ([(is-even? : (→ Int Bool))
(λ ([n : Int])
(or (zero? n)
(is-odd? (sub1 n))))]
[(is-odd? : (→ Int Bool))
(λ ([n : Int])
(and (not (zero? n))
(is-even? (sub1 n))))])
(is-odd? 11)) : Bool ⇒ #t)
tests from stlc+lit - tests.rkt --------------------------
;; most should pass, some failing may now pass due to added types/forms
(check-type 1 : Int)
(check-not-type 1 : (→ Int Int))
;(typecheck-fail "one") ; literal now supported
;(typecheck-fail #f) ; literal now supported
(check-type (λ ([x : Int] [y : Int]) x) : (→ Int Int Int))
(check-not-type (λ ([x : Int]) x) : Int)
(check-type (λ ([x : Int]) x) : (→ Int Int))
(check-type (λ ([f : (→ Int Int)]) 1) : (→ (→ Int Int) Int))
(check-type ((λ ([x : Int]) x) 1) : Int ⇒ 1)
( typecheck - fail ( ( λ ( [ x : Bool ] ) x ) 1 ) ) ; now valid type , but arg has wrong type
( typecheck - fail ( λ ( [ x : Bool ] ) x ) ) ; is now valid type
(typecheck-fail (λ ([f : Int]) (f 1 2))) ; applying f with non-fn type
(check-type (λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y))
: (→ (→ Int Int Int) Int Int Int))
(check-type ((λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y)) + 1 2) : Int ⇒ 3)
adding non - Int
(typecheck-fail (λ ([x : (→ Int Int)]) (+ x x))) ; x should be Int
(typecheck-fail ((λ ([x : Int] [y : Int]) y) 1)) ; wrong number of args
(check-type ((λ ([x : Int]) (+ x x)) 10) : Int ⇒ 20)
| null | https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/macrotypes-test/tests/macrotypes/stlc%2Breco%2Bvar-tests.rkt | racket | define-type-alias
error , Complex undefined
records (ie labeled tuples)
record errors
variants
variant errors
previous tuple tests: ------------------------------------------------------------
wont work anymore
(check-type (tup 1 2 3) : (× Int Int Int))
(check-type (tup 1 "1" #f +) : (× Int String Bool (→ Int Int Int)))
(check-not-type (tup 1 "1" #f +) : (× Int Unit Bool (→ Int Int Int)))
(check-not-type (tup 1 "1" #f +) : (× Int String Unit (→ Int Int Int)))
(check-not-type (tup 1 "1" #f +) : (× Int String Bool (→ Int Int Unit)))
index too large
not tuple
ext-stlc.rkt tests ---------------------------------------------------------
should still pass
new literals and base types
literal now supported
literal now supported
Bool is now valid type
Unit
begin
ascription
let
unbound identifier
letrec
recursive
mutually recursive
most should pass, some failing may now pass due to added types/forms
(typecheck-fail "one") ; literal now supported
(typecheck-fail #f) ; literal now supported
now valid type , but arg has wrong type
is now valid type
applying f with non-fn type
x should be Int
wrong number of args | #lang s-exp macrotypes/examples/stlc+reco+var
(require "rackunit-typechecking.rkt")
(check-type (λ ([n : Int]) (var b = (tup [c = n]) as (∨ [b : (× [c : Int])])))
: (→ Int (∨ [b : (× [c : Int])])))
(define-type-alias Integer Int)
(define-type-alias ArithBinOp (→ Int Int Int))
(check-type ((λ ([x : Int]) (+ x 2)) 3) : Integer)
(check-type ((λ ([x : Integer]) (+ x 2)) 3) : Int)
(check-type ((λ ([x : Integer]) (+ x 2)) 3) : Integer)
(check-type + : ArithBinOp)
(check-type (λ ([f : ArithBinOp]) (f 1 2)) : (→ (→ Int Int Int) Int))
(check-type "Stephen" : String)
(check-type (tup) : (×))
(check-type (tup [name = "Stephen"]) : (× [name : String]))
(check-type (proj (tup [name = "Stephen"]) name) : String ⇒ "Stephen")
(check-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [name : String] [phone : Int] [male? : Bool]))
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) name)
: String ⇒ "Stephen")
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) name)
: String ⇒ "Stephen")
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) phone)
: Int ⇒ 781)
(check-type (proj (tup [name = "Stephen"] [phone = 781] [male? = #t]) male?)
: Bool ⇒ #t)
(check-not-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [my-name : String] [phone : Int] [male? : Bool]))
(check-not-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [name : String] [my-phone : Int] [male? : Bool]))
(check-not-type (tup [name = "Stephen"] [phone = 781] [male? = #t]) :
(× [name : String] [phone : Int] [is-male? : Bool]))
(typecheck-fail
(proj 1 "a")
#:with-msg
"expected identifier")
(typecheck-fail
(proj 1 a)
#:with-msg
"Expected expression 1 to have × type, got: Int")
(check-type (var coffee = (void) as (∨ [coffee : Unit])) : (∨ [coffee : Unit]))
(check-not-type (var coffee = (void) as (∨ [coffee : Unit])) : (∨ [coffee : Unit] [tea : Unit]))
(typecheck-fail ((λ ([x : (∨ [coffee : Unit] [tea : Unit])]) x)
(var coffee = (void) as (∨ [coffee : Unit])))
#:with-msg
"expected: +\\(∨ \\(coffee : Unit\\) \\(tea : Unit\\)\\)\n *given: +\\(∨ \\(coffee : Unit\\)\\)")
(check-type (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit])) :
(∨ [coffee : Unit] [tea : Unit]))
(check-type (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit] [coke : Unit]))
: (∨ [coffee : Unit] [tea : Unit] [coke : Unit]))
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => 1])
#:with-msg "wrong number of case clauses")
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => 1]
[teaaaaaa x => 2])
#:with-msg "case clauses not exhaustive")
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => 1]
[tea x => 2]
[coke x => 3])
#:with-msg "wrong number of case clauses")
(typecheck-fail
(case (var coffee = (void) as (∨ [coffee : Unit] [tea : Unit]))
[coffee x => "1"]
[tea x => 2])
#:with-msg "branches have incompatible types: String and Int")
(check-type
(case (var coffee = 1 as (∨ [coffee : Int] [tea : Unit]))
[coffee x => x]
[tea x => 2]) : Int ⇒ 1)
(define-type-alias Drink (∨ [coffee : Int] [tea : Unit] [coke : Bool]))
(check-type ((λ ([x : Int]) (+ x x)) 10) : Int ⇒ 20)
(check-type (λ ([x : Int]) (+ (+ x x) (+ x x))) : (→ Int Int))
(check-type
(case ((λ ([d : Drink]) d)
(var coffee = 1 as (∨ [coffee : Int] [tea : Unit] [coke : Bool])))
[coffee x => (+ (+ x x) (+ x x))]
[tea x => 2]
[coke y => 3])
: Int ⇒ 4)
(check-type
(case ((λ ([d : Drink]) d) (var coffee = 1 as Drink))
[coffee x => (+ (+ x x) (+ x x))]
[tea x => 2]
[coke y => 3])
: Int ⇒ 4)
(typecheck-fail
(var name = "Steve" as Int)
#:with-msg
"Expected the expected type to be a ∨ type, got: Int")
(typecheck-fail
(case 1 [racket x => 1])
#:with-msg
"Expected ∨ type, got: Int")
(typecheck-fail
(λ ([x : (∨)]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ 1)]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ 1\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [1 2])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(1 2\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [a 2])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(a 2\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [a Int])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(a Int\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [1 : Int])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(1 : Int\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
(typecheck-fail
(λ ([x : (∨ [a : 1])]) x)
#:with-msg "Improper usage of type constructor ∨: \\(∨ \\(a : 1\\)\\), expected \\(∨ \\[label:id : τ:type\\] ...+\\)")
( check - not - type ( tup 1 " 1 " # f + ) : ( × Unit ( → Int Int Int ) ) )
( check - type ( proj ( tup 1 " 2 " # f ) 0 ) : Int ⇒ 1 )
( check - type ( proj ( tup 1 " 2 " # f ) 1 ) : String ⇒ " 2 " )
( check - type ( proj ( tup 1 " 2 " # f ) 2 ) : ⇒ # f )
(check-type (void) : Unit)
(check-type void : (→ Unit))
(typecheck-fail ((λ ([x : Unit]) x) 2))
(typecheck-fail ((λ ([x : Unit])) void))
(check-type ((λ ([x : Unit]) x) (void)) : Unit)
(typecheck-fail (begin))
(check-type (begin 1) : Int)
( typecheck - fail ( begin 1 2 3 ) )
(check-type (begin (void) 1) : Int ⇒ 1)
(typecheck-fail (ann 1 : Bool))
(check-type (ann 1 : Int) : Int ⇒ 1)
(check-type ((λ ([x : Int]) (ann x : Int)) 10) : Int ⇒ 10)
(check-type (let () (+ 1 1)) : Int ⇒ 2)
(check-type (let ([x 10]) (+ 1 2)) : Int)
(typecheck-fail (let ([x #f]) (+ x 1)))
(check-type (let ([x 10] [y 20]) ((λ ([z : Int] [a : Int]) (+ a z)) x y)) : Int ⇒ 30)
(check-type (let* ([x 10] [y (+ x 1)]) (+ x y)) : Int ⇒ 21)
(typecheck-fail (let* ([x #t] [y (+ x 1)]) 1))
(typecheck-fail (letrec ([(x : Int) #f] [(y : Int) 1]) y))
(typecheck-fail (letrec ([(y : Int) 1] [(x : Int) #f]) x))
(check-type (letrec ([(x : Int) 1] [(y : Int) (+ x 1)]) (+ x y)) : Int ⇒ 3)
(check-type
(letrec ([(countdown : (→ Int String))
(λ ([i : Int])
(if (= i 0)
"liftoff"
(countdown (- i 1))))])
(countdown 10)) : String ⇒ "liftoff")
(check-type
(letrec ([(is-even? : (→ Int Bool))
(λ ([n : Int])
(or (zero? n)
(is-odd? (sub1 n))))]
[(is-odd? : (→ Int Bool))
(λ ([n : Int])
(and (not (zero? n))
(is-even? (sub1 n))))])
(is-odd? 11)) : Bool ⇒ #t)
tests from stlc+lit - tests.rkt --------------------------
(check-type 1 : Int)
(check-not-type 1 : (→ Int Int))
(check-type (λ ([x : Int] [y : Int]) x) : (→ Int Int Int))
(check-not-type (λ ([x : Int]) x) : Int)
(check-type (λ ([x : Int]) x) : (→ Int Int))
(check-type (λ ([f : (→ Int Int)]) 1) : (→ (→ Int Int) Int))
(check-type ((λ ([x : Int]) x) 1) : Int ⇒ 1)
(check-type (λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y))
: (→ (→ Int Int Int) Int Int Int))
(check-type ((λ ([f : (→ Int Int Int)] [x : Int] [y : Int]) (f x y)) + 1 2) : Int ⇒ 3)
adding non - Int
(check-type ((λ ([x : Int]) (+ x x)) 10) : Int ⇒ 20)
|
5dbd5c8334b39b69b5b4d8ae59e3c4e100904ec897d8533506245968126e6c82 | Kalimehtar/gtk-cffi | file-chooser-dialog.lisp | (in-package :gtk-cffi)
(defclass file-chooser-dialog (dialog file-chooser)
())
(defcfun "gtk_file_chooser_dialog_new" :pointer
(title :string) (parent pobject) (action file-chooser-action)
(but1-text :string) (but1-response dialog-response)
(but2-text :string) (but2-response dialog-response)
(null :pointer))
(defmethod gconstructor ((file-chooser-dialog file-chooser-dialog)
&key (title "") dialog-parent action &allow-other-keys)
(gtk-file-chooser-dialog-new
title dialog-parent action
"gtk-cancel" :cancel
(case action
((:open :select-folder) "gtk-open")
((:save :create-folder) "gtk-save")) :accept (null-pointer)))
| null | https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/gtk/file-chooser-dialog.lisp | lisp | (in-package :gtk-cffi)
(defclass file-chooser-dialog (dialog file-chooser)
())
(defcfun "gtk_file_chooser_dialog_new" :pointer
(title :string) (parent pobject) (action file-chooser-action)
(but1-text :string) (but1-response dialog-response)
(but2-text :string) (but2-response dialog-response)
(null :pointer))
(defmethod gconstructor ((file-chooser-dialog file-chooser-dialog)
&key (title "") dialog-parent action &allow-other-keys)
(gtk-file-chooser-dialog-new
title dialog-parent action
"gtk-cancel" :cancel
(case action
((:open :select-folder) "gtk-open")
((:save :create-folder) "gtk-save")) :accept (null-pointer)))
| |
8be3678c524557a416062ecc1f073fbbf87249e02aec201cf8da096331881961 | fredrikt/yxa | sipsocket_blacklist.erl | %%%-------------------------------------------------------------------
%%% File : sipsocket_blacklist.erl
@author < >
%%% @doc Sipsocket blacklist gen_server and interface functions.
%%% Keeps track of destinations that recently has failed to
respond to SIP messages . Read more in RFC3263 and 4321 .
%%%
@since 19 Feb 2006 by < >
%%% @end
@private
%%%-------------------------------------------------------------------
-module(sipsocket_blacklist).
%%-compile(export_all).
-behaviour(gen_server).
%%--------------------------------------------------------------------
%% External exports
%%--------------------------------------------------------------------
-export([start_link/0
]).
%%--------------------------------------------------------------------
%% External interface exports
%%--------------------------------------------------------------------
-export([report_unreachable/3,
report_unreachable/4,
remove_blacklisting/1,
remove_blacklisting/2,
is_blacklisted/1,
test/0
]).
%%--------------------------------------------------------------------
%% Internal exports - for local.erl use only
%%--------------------------------------------------------------------
-export([lookup_sipsocket_blacklist/1
]).
%%--------------------------------------------------------------------
%% Internal exports - for sipsocket supervisor only
%%--------------------------------------------------------------------
-export([get_blacklist_name/0
]).
%%--------------------------------------------------------------------
%% Internal exports - gen_server callbacks
%%--------------------------------------------------------------------
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("sipsocket.hrl").
%%--------------------------------------------------------------------
Records
%%--------------------------------------------------------------------
%% @type state() = #state{}.
%% no description
-record(state, {bl %% blacklist ETS table name/reference
}).
-record(blacklist_entry, {pid, %% pid(), who reported this destination unreachable?
reason, %% string(), reason behind blacklisting
ts, %% integer(), util:timestamp() time of blacklisting
probe_t, %% integer(), util:timestamp() of when to probe this destination
duration %% integer(), suggested penalty duration
}).
%%--------------------------------------------------------------------
Macros
%%--------------------------------------------------------------------
-define(SERVER, sipsocket_blacklist).
-define(SIPSOCKET_BLACKLIST, yxa_sipsocket_blacklist).
%% Our standard wakeup interval - how often we should look for expired
%% entrys in the blacklist ETS table
-define(TIMEOUT, 89 * 1000).
-define(PROBE_TIMEOUT, 32).
%%====================================================================
%% External functions
%%====================================================================
%%--------------------------------------------------------------------
%% @spec () -> term()
%%
%% @doc Starts the server
%% @end
%%--------------------------------------------------------------------
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [?SIPSOCKET_BLACKLIST], []).
%%====================================================================
%% External interface functions
%%====================================================================
%%--------------------------------------------------------------------
@spec ( SipDst , SipSocket , Msg ) - > ok
%%
SipDst = # sipdst { }
SipSocket = # sipsocket { } | none
= string ( ) " reason for blacklisting "
%%
%% @doc Blacklist a destination.
@equiv report_unreachable(SipDst , SipSocket , Msg , undefined )
%% @end
%%--------------------------------------------------------------------
report_unreachable(SipDst, SipSocket, Msg) when is_record(SipDst, sipdst),
(is_record(SipSocket, sipsocket) orelse SipSocket == none),
is_list(Msg) ->
report_unreachable(SipDst, SipSocket, Msg, undefined).
%%--------------------------------------------------------------------
@spec ( SipDst , SipSocket , Msg , RetryAfter ) - > ok
%%
SipDst = # sipdst { }
%% SipSocket = #sipsocket{} | none
Msg = string ( ) " reason for blacklisting "
RetryAfter = undefined | integer ( ) " seconds to blacklist "
%%
%% @doc Blacklist a destination.
%% @end
%%--------------------------------------------------------------------
report_unreachable(SipDst, SipSocket, Msg, RetryAfter) when is_record(SipDst, sipdst), is_list(Msg),
(is_integer(RetryAfter) orelse RetryAfter == undefined) ->
case yxa_config:get_env(sipsocket_blacklisting) of
{ok, true} ->
%% Figure out how long time to blacklist this destination this time
{ok, StdDuration} = yxa_config:get_env(sipsocket_blacklist_duration),
{ok, MaxPenalty} = yxa_config:get_env(sipsocket_blacklist_max),
Now = util:timestamp(),
ProbeTS =
case RetryAfter of
undefined ->
{ok, ProbeDelay} = yxa_config:get_env(sipsocket_blacklist_probe_delay),
Now + ProbeDelay;
_ ->
undefined
end,
do_report_unreachable(SipDst, SipSocket, lists:flatten(Msg), RetryAfter,
StdDuration, MaxPenalty, ProbeTS, Now, ?SIPSOCKET_BLACKLIST);
{ok, false} ->
ok
end.
%%--------------------------------------------------------------------
@spec ( SipDst ) - > ok
%%
SipDst = # sipdst { }
%%
%% @doc Remove a destination from the blacklist, if it is present
%% there.
%% @end
%%--------------------------------------------------------------------
remove_blacklisting(SipDst) when is_record(SipDst, sipdst) ->
do_remove_blacklisting(SipDst, ?SIPSOCKET_BLACKLIST).
remove_blacklisting(SipDst, EtsRef) when is_record(SipDst, sipdst) ->
do_remove_blacklisting(SipDst, EtsRef).
%%--------------------------------------------------------------------
@spec ( SipDst ) - > true | false
%%
SipDst = # sipdst { }
%%
%% @doc Check if a destination is currently blacklisted.
%% @end
%%--------------------------------------------------------------------
is_blacklisted(SipDst) when is_record(SipDst, sipdst) ->
case yxa_config:get_env(sipsocket_blacklisting) of
{ok, true} ->
do_is_blacklisted(SipDst, util:timestamp(), ?SIPSOCKET_BLACKLIST);
{ok, false} ->
false
end.
%%--------------------------------------------------------------------
%% @spec (Dst) ->
%% {ok, Entry} |
%% {ok, whitelisted} |
%% {ok, blacklisted} |
%% undefined
%%
Dst = { Proto , Addr , Port } " ets table lookup key "
%% Proto = term()
term ( )
%% Port = term()
%%
%% @doc Part of lookup_dst, unless 'local' had an opinion about a
%% destination. NOTE: Not implemented yet.
%% @end
%%--------------------------------------------------------------------
lookup_sipsocket_blacklist({_Proto, _Addr, _Port} = _Dst) ->
%% XXX check for configured lists of black/whitelisted destinations here
undefined.
%%====================================================================
%% External functions - for sipsocket supervisor only
%%====================================================================
%%--------------------------------------------------------------------
%% @spec () ->
%% EtsRef
%%
%% EtsRef = term()
%%
%% @doc Return the name of the blacklisting ets table. For use
%% from sipsocket supervisor only!
%% @hidden
%% @end
%%--------------------------------------------------------------------
get_blacklist_name() ->
?SIPSOCKET_BLACKLIST.
%%====================================================================
%% Behaviour callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% @spec ([TableName]) ->
%% {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%%
%% TableName = term() "ETS table name/reference"
%%
%% @doc Initiates the server
%% @hidden
%% @end
%%--------------------------------------------------------------------
init([TableName]) ->
{ok, #state{bl = TableName}, ?TIMEOUT}.
%%--------------------------------------------------------------------
@spec handle_call(Msg , From , State ) - >
%% {reply, Reply, State} |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%%
%% @doc Handling call messages
%% @hidden
%% @end
%%--------------------------------------------------------------------
%% @clear
%%--------------------------------------------------------------------
@spec ( Unknown , From , State ) - >
{ reply , { error , not_implemented } , State , Timeout::integer ( ) }
%%
%% @doc Unknown call.
%% @hidden
%% @end
%%--------------------------------------------------------------------
handle_call(Unknown, _From, State) ->
logger:log(error, "Sipsocket blacklist: Received unknown gen_server call : ~p", [Unknown]),
{reply, {error, not_implemented}, State, ?TIMEOUT}.
%%--------------------------------------------------------------------
@spec handle_cast(Msg , State ) - >
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%%
%% @doc Handling cast messages
%% @hidden
%% @end
%%--------------------------------------------------------------------
%% @clear
%%--------------------------------------------------------------------
@spec ( Unknown , State ) - > { noreply , State , Timeout::integer ( ) }
%%
%% @doc Unknown cast.
%% @hidden
%% @end
%%--------------------------------------------------------------------
handle_cast(Unknown, State) ->
logger:log(error, "Sipsocket blacklist: Received unknown gen_server cast : ~p", [Unknown]),
{noreply, State, ?TIMEOUT}.
%%--------------------------------------------------------------------
@spec handle_info(Msg , State ) - >
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%%
%% @doc Handling all non call/cast messages
%% @hidden
%% @end
%%--------------------------------------------------------------------
%% @clear
%%--------------------------------------------------------------------
@spec ( timeout , State ) - > { noreply , State , Timeout::integer ( ) }
%%
%% @doc Wake up and delete expired sockets from our list.
%% @hidden
%% @end
%%--------------------------------------------------------------------
handle_info(timeout, State) ->
AllEntrys = ets:tab2list(State#state.bl),
case AllEntrys of
[] -> ok;
_ ->
logger:log(debug, "Sipsocket blacklist: Extra debug: Contents of blacklist table is :~n~p",
[AllEntrys]),
delete_expired_entrys(AllEntrys, util:timestamp(), State#state.bl)
end,
{noreply, State, ?TIMEOUT}.
%%--------------------------------------------------------------------
@spec ( Reason , State ) - > term ( ) " ignored by gen_server "
%%
%% @doc Shutdown the server
%% @hidden
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
@spec ( OldVsn , State , Extra ) - > { ok , NewState }
%%
@doc Convert process state when code is changed
%% @hidden
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
%%--------------------------------------------------------------------
@spec ( SipDst , SipSocket , Msg , , StdDuration ,
MaxPenalty , ProbeTS , Now , ) - > ok
%%
SipDst = # sipdst { }
%% SipSocket = #sipsocket{}
Msg = string ( ) " reason for blacklisting ( only for debug / diagnostic use ) "
= integer ( ) | undefined " seconds requested by upper layers ( through an Retry - After header in a 503 response for example ) "
StdDuration = integer ( ) " configured default duration - used if is ' undefined ' "
MaxPenalty = integer ( ) " configured duration "
%% ProbeTS = undefined() | integer() "util:timestamp() notion of when we should start probing this destination, if it is requested again"
%% Now = integer() "util:timestamp() notion of present time"
%% EtsRef = term() "ETS table reference"
%%
%% @doc Part of the exported report_unreachable function. Made
%% this way in order to be testable.
%% @end
%%--------------------------------------------------------------------
do_report_unreachable(SipDst, SipSocket, Msg, SecondsIn, StdDuration, MaxPenalty, ProbeTS, Now, EtsRef) ->
Dst = make_dst(SipDst),
case get_blacklist_time(Dst, SecondsIn, EtsRef, StdDuration, MaxPenalty) of
Seconds when is_integer(Seconds) ->
logger:log(debug, "Sipsocket blacklist: Blacklisting destination ~s for ~p seconds",
[sipdst:dst2str(SipDst), Seconds]),
Entry =
#blacklist_entry{pid = self(),
reason = Msg,
ts = Now,
probe_t = ProbeTS,
duration = Seconds
},
ets:insert(EtsRef, {Dst, Entry}),
case is_record(SipSocket, sipsocket) of
true ->
case sipsocket:close_socket(SipSocket) of
ok -> ok;
{error, not_applicable} -> ok;
{error, Reason} ->
logger:log(error, "Sipsocket blacklist: Failed closing sipsocket ~p : ~p",
[SipSocket, Reason])
end,
ok;
false ->
ok
end;
ignore ->
ok
end,
ok.
%%--------------------------------------------------------------------
@spec ( Dst , , , StdDuration , MaxDuration ) - >
%% Seconds |
%% ignore
%%
Dst = term ( ) " ETS table key "
= integer ( ) | undefined " seconds requested by upper layers ( through an Retry - After header in a 503 response for example ) "
%% EtsRef = term() "ETS table reference"
StdDuration = integer ( ) " configured default duration - used if is ' undefined ' "
MaxDuration = integer ( ) " configured duration "
%%
%% Seconds = integer()
%%
%% @doc Decide how long a host should be blacklisted, or if the
%% blacklisting request should be ignored completely
%% (because the destination is black/whitelisted through
%% configuration).
%% @end
%%--------------------------------------------------------------------
get_blacklist_time(Dst, SecondsIn, EtsRef, StdDuration, MaxDuration) ->
case lookup_dst(Dst, EtsRef) of
{ok, blacklisted} ->
ignore;
{ok, whitelisted} ->
ignore;
{ok, OldEntry} when is_record(OldEntry, blacklist_entry) ->
get_blacklist_time_res(SecondsIn, StdDuration, MaxDuration);
none ->
get_blacklist_time_res(SecondsIn, StdDuration, MaxDuration)
end.
part of get_blacklist_time/5
get_blacklist_time_res(undefined, StdDur, Max) ->
lists:min([StdDur, Max]);
get_blacklist_time_res(N, _StdDur, Max) when is_integer(N) ->
lists:min([N, Max]).
%%--------------------------------------------------------------------
@spec ( SipDst , ) - > ok
%%
SipDst = # sipdst { }
%% EtsRef = term() "ETS table reference"
%%
%% @doc Part of the exported remove_blacklisting function. Made
%% this way in order to be testable. NOTE : Currently, the
exported function is not used by the YXA stack or
%% applications. Things get blacklisted, and the only part
%% removing blacklists are this modules gen_server or probes
%% that notice the destination is now reachable again.
%% Having an API function to do it seems reasonable though.
%% @end
%%--------------------------------------------------------------------
do_remove_blacklisting(SipDst, EtsRef) when is_record(SipDst, sipdst) ->
Dst = make_dst(SipDst),
case lookup_dst(Dst, EtsRef) of
{ok, Entry} when is_record(Entry, blacklist_entry) ->
logger:log(debug, "Sipsocket blacklist: Removing blacklisting of ~s", [sipdst:dst2str(SipDst)]),
ets:delete(EtsRef, Dst);
{ok, blacklisted} ->
logger:log(debug, "Sipsocket blacklist: NOT removing (static) blacklisting of ~s",
[sipdst:dst2str(SipDst)]),
ok;
{ok, whitelisted} ->
ok;
none ->
ok
end,
ok.
%%--------------------------------------------------------------------
@spec ( SipDst , Now , ) - >
NewDstList
%%
SipDst = # sipdst { }
%% Now = integer() "util:timestamp() notion of present time"
%% EtsRef = term() "ETS table reference"
%%
= [ # sipdst { } ]
%%
%% @doc Filter out all currently blacklisted destinations from a
%% list of sipdst records. Starts background probes where
%% appropriate. Part of the exported
%% blacklist_filter_dstlist/1 function - written this way to
%% be testable.
%% @end
%%--------------------------------------------------------------------
do_is_blacklisted(SipDst, Now, EtsRef) ->
Dst = make_dst(SipDst),
case lookup_dst(Dst, EtsRef) of
{ok, #blacklist_entry{duration = Duration} = Entry} when is_integer(Duration) ->
case (Entry#blacklist_entry.ts + Duration) - Now of
Remaining when Remaining > 0 ->
DstStr = sipdst:dst2str(SipDst),
logger:log(debug, "Sipsocket blacklist: Skipping destination ~s, blacklisted for ~p more seconds",
[DstStr, Remaining]),
start_background_probe(SipDst, Dst, DstStr, Entry#blacklist_entry.probe_t, Now, EtsRef),
true;
_ ->
%% Entry is expired, treat like no entry was present
false
end;
{ok, blacklisted} ->
logger:log(debug, "Sipsocket blacklist: Skipping destination ~s, blacklisted statically",
[sipdst:dst2str(SipDst)]),
true;
{ok, whitelisted} ->
false;
none ->
false
end.
start_background_probe(SipDst, Dst, DstStr, ProbeT, Now, EtsRef) when is_integer(ProbeT), Now >= ProbeT ->
%% check that we don't have a probe for this destination running already
ProbeId = {probe, Dst},
case ets:insert_new(EtsRef, {ProbeId, self()}) of
true ->
case (SipDst#sipdst.proto == yxa_test) of
true ->
self() ! {start_background_probe, ProbeId};
false ->
{ok, ProbePid} = sipsocket_blacklist_probe:start(SipDst, EtsRef, ProbeId, ?PROBE_TIMEOUT),
logger:log(debug, "Sipsocket blacklist: Started background probe for destination ~s : ~p",
[DstStr, ProbePid])
end;
false ->
logger:log(debug, "Sipsocket blacklist: Extra debug: NOT starting background probe for "
"destination ~s since one is already running", [DstStr])
end,
ok;
start_background_probe(_SipDst, _Dst, DstStr, ProbeT, Now, _EtsRef) when is_integer(ProbeT) ->
logger:log(debug, "Sipsocket blacklist: Extra debug: NOT starting background probe for "
"destination ~s for another ~p seconds",
[DstStr, ProbeT - Now]),
ok;
start_background_probe(_SipDst, _Dst, DstStr, undefined, _Now, _EtsRef) ->
logger:log(debug, "Sipsocket blacklist: Extra debug: NOT starting background probe for "
"destination ~s",
[DstStr]),
ok.
%%--------------------------------------------------------------------
@spec ( Dst , ) - >
%% {ok, Entry} |
%% none
%%
%% Dst = term() "database lookup key"
%% EtsRef = term() "ETS table reference"
%%
%% Entry = blacklist_entry() |
%% whitelisted |
%% blacklisted
%%
@doc Returns the latest entry for Dst . Note well that the entry
%% might be expired!
%% @end
%%--------------------------------------------------------------------
lookup_dst({_Proto, _Addr, _Port} = Dst, EtsRef) ->
case local:lookup_sipsocket_blacklist(Dst) of
{ok, Res} ->
{ok, Res};
undefined ->
case ets:lookup(EtsRef, Dst) of
[] ->
none;
Entrys when is_list(Entrys) ->
{Dst, LatestEntry} = hd(lists:reverse(Entrys)),
{ok, LatestEntry}
end
end.
%%--------------------------------------------------------------------
@spec ( In , Now , ) - > ok
%%
%% In = [{Dst, Entry}]
Dst = term ( ) " lookup key ( { Proto , Addr , Port } ) "
%% Entry = #blacklist_entry{}
%% Now = integer() "util:timestamp() value of present time"
%% EtsRef = term() "ETS table reference"
%%
%% @doc Delete all entrys that have a ts+duration less than Now.
%% Called periodically by the sipsocket_blacklist
%% gen_server.
%% @end
%%--------------------------------------------------------------------
delete_expired_entrys([{Dst, H} | T], Now, EtsRef) when is_record(H, blacklist_entry) ->
case (H#blacklist_entry.ts + H#blacklist_entry.duration) - Now of
Remaining when Remaining =< 0 ->
logger:log(debug, "Sipsocket blacklist: Extra debug: Removing expired entry for ~p : ~p",
[Dst, H]),
ets:delete_object(EtsRef, {Dst, H});
_ ->
ok
end,
delete_expired_entrys(T, Now, EtsRef);
delete_expired_entrys([{{probe, _Dst}, _ProbePid} | T], Now, EtsRef) ->
delete_expired_entrys(T, Now, EtsRef);
delete_expired_entrys([], _Now, _EtsRef) ->
ok.
%%--------------------------------------------------------------------
@spec ( SipDst ) - >
%% Dst
%%
SipDst = # sipdst { }
%%
%% Dst = term()
%%
%% @doc Make database key from a sipdst record.
%% @end
%%--------------------------------------------------------------------
make_dst(SipDst) when is_record(SipDst, sipdst) ->
{SipDst#sipdst.proto, SipDst#sipdst.addr, SipDst#sipdst.port}.
%%====================================================================
%% Test functions
%%====================================================================
%%--------------------------------------------------------------------
%% @spec () -> ok
%%
%% @doc autotest callback
%% @hidden
%% @end
%%--------------------------------------------------------------------
-ifdef( YXA_NO_UNITTEST ).
test() ->
{error, "Unit test code disabled at compile time"}.
-else.
test() ->
Self = self(),
TestEtsRef = ets:new(yxa_blacklist_test, [bag]),
TestSipDst1 = #sipdst{proto = yxa_test,
addr = "192.0.2.1",
port = 6050
},
TestDst1 = make_dst(TestSipDst1),
TestSipSocket1 = #sipsocket{proto = yxa_test,
module = sipsocket_test
},
TestSipDst2 = #sipdst{proto = yxa_test,
addr = "192.0.2.2",
port = 6050
},
%%TestDst2 = make_dst(TestSipDst2),
test # 1 , add , read and delete
%%--------------------------------------------------------------------
autotest:mark(?LINE, "blacklisting test 1 - 1"),
TestNow1 = 10000000,
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test", undefined, 90, 120, 1234, TestNow1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 2"),
%% verify result of insert
TestBLEntry1 = #blacklist_entry{pid = Self,
reason = "test",
ts = TestNow1,
probe_t = 1234,
duration = 90
},
[{TestDst1, TestBLEntry1}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 3"),
{ok, TestBLEntry1} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 4"),
%% insert again, with specified blacklist time
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test", 100, 90, 120, 1234, TestNow1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 5"),
%% verify result of insert, both entrys should be there
TestBLEntry5 = TestBLEntry1#blacklist_entry{duration = 100},
[{TestDst1, TestBLEntry1}, {TestDst1, TestBLEntry5}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 6"),
%% verify that we only get the most recent entry back
{ok, TestBLEntry5} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 7"),
%% verify result of insert, both entrys should be there
TableContents8 = [{TestDst1, TestBLEntry1}, {TestDst1, TestBLEntry5}],
TableContents8 = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 8"),
%% verify that we only get the most recent entry back
{ok, TestBLEntry5} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 9"),
%% delete _wrong_ destination
ok = do_remove_blacklisting(TestSipDst2, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 10"),
%% verify that the table still looks the same
TableContents8 = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 11"),
%% delete right destination
ok = do_remove_blacklisting(TestSipDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 12"),
%% verify that the table is now empty again
[] = ets:tab2list(TestEtsRef),
test # 2 , two expired entrys
%%--------------------------------------------------------------------
autotest:mark(?LINE, "blacklisting test 2 - 1"),
TestNow2 = 10000000,
simulate inserting entry 100 seconds ago , with expire time 60 seconds
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test 2", 60, 30, 120,
undefined, TestNow2 - 100, TestEtsRef),
simulate inserting entry 90 seconds ago , with expire time 30 seconds
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test 2", undefined, 30, 120,
undefined, TestNow2 - 90, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 2"),
[{_, _}, {_, _}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 3"),
TestBLEntry2 = #blacklist_entry{pid = Self,
reason = "test 2",
ts = TestNow2 - 90,
probe_t = undefined,
duration = 30
},
{ok, TestBLEntry2} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 4"),
%% add non-expired entry
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test 2", 60, 30, 120,
undefined, TestNow2, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 5"),
%% delete expired entrys
ok = delete_expired_entrys(ets:tab2list(TestEtsRef), TestNow2, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 6"),
%% verify table now only contains the non-expired entry
TestBLEntry2_1 = TestBLEntry2#blacklist_entry{ts = TestNow2,
duration = 60
},
[{TestDst1, TestBLEntry2_1}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 7"),
%% delete destination
ok = do_remove_blacklisting(TestSipDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 8"),
%% verify that the table is now empty again
[] = ets:tab2list(TestEtsRef),
do_is_blacklisted(SipDst , Now , )
%%--------------------------------------------------------------------
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.0"),
TestISBL_Now = util:timestamp(),
TestISBL_Penalty = 100,
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test", TestISBL_Penalty, 90, 120,
undefined, TestISBL_Now, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.1"),
other SipDst
false = do_is_blacklisted(TestSipDst2, TestISBL_Now, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.2"),
blacklisted for one more second
true = do_is_blacklisted(TestSipDst1, TestISBL_Now + TestISBL_Penalty - 1, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.3"),
blacklisting expires this very second
false = do_is_blacklisted(TestSipDst1, TestISBL_Now + TestISBL_Penalty, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.0"),
TestISBL_ProbeT = TestISBL_Now + 5,
TestISBL_Expire = 120,
ok = do_report_unreachable(TestSipDst2, TestSipSocket1, "test", TestISBL_Penalty,
90, 120, TestISBL_ProbeT, TestISBL_Now, TestEtsRef),
%% make sure there are no signals in our process mailbox
receive
TestISBL_M1 ->
throw({error, test_received_unknown_signal, TestISBL_M1})
after 0 ->
ok
end,
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.1"),
blacklisted , but no probe for one more second
true = do_is_blacklisted(TestSipDst2, TestISBL_ProbeT - 1, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.2"),
%% make sure there are no signals in our process mailbox
receive
TestISBL_M2 ->
throw({error, test_received_unknown_signal, TestISBL_M2})
after 0 ->
ok
end,
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.3"),
%% expired entry, don't start probe
false = do_is_blacklisted(TestSipDst2, TestISBL_Now + TestISBL_Expire, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.4"),
%% blacklisted, and time to probe
true = do_is_blacklisted(TestSipDst2, TestISBL_ProbeT, TestEtsRef),
%% make sure the expected signal is in our process mailbox
receive
{start_background_probe, {probe, TestDst2}} ->
ets:delete(TestEtsRef, {probe, TestDst2}),
ok
after 0 ->
throw({error, "background probe did not start"})
end,
autotest:mark(?LINE, "do_is_blacklisted/3 - 3.0"),
%% delete destinations
ok = do_remove_blacklisting(TestSipDst1, TestEtsRef),
ok = do_remove_blacklisting(TestSipDst2, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 3.1"),
%% verify that the table is now empty again
[] = ets:tab2list(TestEtsRef),
ok.
-endif.
| null | https://raw.githubusercontent.com/fredrikt/yxa/85da46a999d083e6f00b5f156a634ca9be65645b/src/transportlayer/sipsocket_blacklist.erl | erlang | -------------------------------------------------------------------
File : sipsocket_blacklist.erl
@doc Sipsocket blacklist gen_server and interface functions.
Keeps track of destinations that recently has failed to
@end
-------------------------------------------------------------------
-compile(export_all).
--------------------------------------------------------------------
External exports
--------------------------------------------------------------------
--------------------------------------------------------------------
External interface exports
--------------------------------------------------------------------
--------------------------------------------------------------------
Internal exports - for local.erl use only
--------------------------------------------------------------------
--------------------------------------------------------------------
Internal exports - for sipsocket supervisor only
--------------------------------------------------------------------
--------------------------------------------------------------------
Internal exports - gen_server callbacks
--------------------------------------------------------------------
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
@type state() = #state{}.
no description
blacklist ETS table name/reference
pid(), who reported this destination unreachable?
string(), reason behind blacklisting
integer(), util:timestamp() time of blacklisting
integer(), util:timestamp() of when to probe this destination
integer(), suggested penalty duration
--------------------------------------------------------------------
--------------------------------------------------------------------
Our standard wakeup interval - how often we should look for expired
entrys in the blacklist ETS table
====================================================================
External functions
====================================================================
--------------------------------------------------------------------
@spec () -> term()
@doc Starts the server
@end
--------------------------------------------------------------------
====================================================================
External interface functions
====================================================================
--------------------------------------------------------------------
@doc Blacklist a destination.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
SipSocket = #sipsocket{} | none
@doc Blacklist a destination.
@end
--------------------------------------------------------------------
Figure out how long time to blacklist this destination this time
--------------------------------------------------------------------
@doc Remove a destination from the blacklist, if it is present
there.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Check if a destination is currently blacklisted.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Dst) ->
{ok, Entry} |
{ok, whitelisted} |
{ok, blacklisted} |
undefined
Proto = term()
Port = term()
@doc Part of lookup_dst, unless 'local' had an opinion about a
destination. NOTE: Not implemented yet.
@end
--------------------------------------------------------------------
XXX check for configured lists of black/whitelisted destinations here
====================================================================
External functions - for sipsocket supervisor only
====================================================================
--------------------------------------------------------------------
@spec () ->
EtsRef
EtsRef = term()
@doc Return the name of the blacklisting ets table. For use
from sipsocket supervisor only!
@hidden
@end
--------------------------------------------------------------------
====================================================================
Behaviour callbacks
====================================================================
--------------------------------------------------------------------
@spec ([TableName]) ->
{ok, State} |
ignore |
{stop, Reason}
TableName = term() "ETS table name/reference"
@doc Initiates the server
@hidden
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
{reply, Reply, State} |
{stop, Reason, Reply, State} |
{stop, Reason, State}
@doc Handling call messages
@hidden
@end
--------------------------------------------------------------------
@clear
--------------------------------------------------------------------
@doc Unknown call.
@hidden
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
@doc Handling cast messages
@hidden
@end
--------------------------------------------------------------------
@clear
--------------------------------------------------------------------
@doc Unknown cast.
@hidden
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
@doc Handling all non call/cast messages
@hidden
@end
--------------------------------------------------------------------
@clear
--------------------------------------------------------------------
@doc Wake up and delete expired sockets from our list.
@hidden
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Shutdown the server
@hidden
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@hidden
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
SipSocket = #sipsocket{}
ProbeTS = undefined() | integer() "util:timestamp() notion of when we should start probing this destination, if it is requested again"
Now = integer() "util:timestamp() notion of present time"
EtsRef = term() "ETS table reference"
@doc Part of the exported report_unreachable function. Made
this way in order to be testable.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Seconds |
ignore
EtsRef = term() "ETS table reference"
Seconds = integer()
@doc Decide how long a host should be blacklisted, or if the
blacklisting request should be ignored completely
(because the destination is black/whitelisted through
configuration).
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
EtsRef = term() "ETS table reference"
@doc Part of the exported remove_blacklisting function. Made
this way in order to be testable. NOTE : Currently, the
applications. Things get blacklisted, and the only part
removing blacklists are this modules gen_server or probes
that notice the destination is now reachable again.
Having an API function to do it seems reasonable though.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Now = integer() "util:timestamp() notion of present time"
EtsRef = term() "ETS table reference"
@doc Filter out all currently blacklisted destinations from a
list of sipdst records. Starts background probes where
appropriate. Part of the exported
blacklist_filter_dstlist/1 function - written this way to
be testable.
@end
--------------------------------------------------------------------
Entry is expired, treat like no entry was present
check that we don't have a probe for this destination running already
--------------------------------------------------------------------
{ok, Entry} |
none
Dst = term() "database lookup key"
EtsRef = term() "ETS table reference"
Entry = blacklist_entry() |
whitelisted |
blacklisted
might be expired!
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
In = [{Dst, Entry}]
Entry = #blacklist_entry{}
Now = integer() "util:timestamp() value of present time"
EtsRef = term() "ETS table reference"
@doc Delete all entrys that have a ts+duration less than Now.
Called periodically by the sipsocket_blacklist
gen_server.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Dst
Dst = term()
@doc Make database key from a sipdst record.
@end
--------------------------------------------------------------------
====================================================================
Test functions
====================================================================
--------------------------------------------------------------------
@spec () -> ok
@doc autotest callback
@hidden
@end
--------------------------------------------------------------------
TestDst2 = make_dst(TestSipDst2),
--------------------------------------------------------------------
verify result of insert
insert again, with specified blacklist time
verify result of insert, both entrys should be there
verify that we only get the most recent entry back
verify result of insert, both entrys should be there
verify that we only get the most recent entry back
delete _wrong_ destination
verify that the table still looks the same
delete right destination
verify that the table is now empty again
--------------------------------------------------------------------
add non-expired entry
delete expired entrys
verify table now only contains the non-expired entry
delete destination
verify that the table is now empty again
--------------------------------------------------------------------
make sure there are no signals in our process mailbox
make sure there are no signals in our process mailbox
expired entry, don't start probe
blacklisted, and time to probe
make sure the expected signal is in our process mailbox
delete destinations
verify that the table is now empty again | @author < >
respond to SIP messages . Read more in RFC3263 and 4321 .
@since 19 Feb 2006 by < >
@private
-module(sipsocket_blacklist).
-behaviour(gen_server).
-export([start_link/0
]).
-export([report_unreachable/3,
report_unreachable/4,
remove_blacklisting/1,
remove_blacklisting/2,
is_blacklisted/1,
test/0
]).
-export([lookup_sipsocket_blacklist/1
]).
-export([get_blacklist_name/0
]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3
]).
-include("sipsocket.hrl").
Records
}).
}).
Macros
-define(SERVER, sipsocket_blacklist).
-define(SIPSOCKET_BLACKLIST, yxa_sipsocket_blacklist).
-define(TIMEOUT, 89 * 1000).
-define(PROBE_TIMEOUT, 32).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [?SIPSOCKET_BLACKLIST], []).
@spec ( SipDst , SipSocket , Msg ) - > ok
SipDst = # sipdst { }
SipSocket = # sipsocket { } | none
= string ( ) " reason for blacklisting "
@equiv report_unreachable(SipDst , SipSocket , Msg , undefined )
report_unreachable(SipDst, SipSocket, Msg) when is_record(SipDst, sipdst),
(is_record(SipSocket, sipsocket) orelse SipSocket == none),
is_list(Msg) ->
report_unreachable(SipDst, SipSocket, Msg, undefined).
@spec ( SipDst , SipSocket , Msg , RetryAfter ) - > ok
SipDst = # sipdst { }
Msg = string ( ) " reason for blacklisting "
RetryAfter = undefined | integer ( ) " seconds to blacklist "
report_unreachable(SipDst, SipSocket, Msg, RetryAfter) when is_record(SipDst, sipdst), is_list(Msg),
(is_integer(RetryAfter) orelse RetryAfter == undefined) ->
case yxa_config:get_env(sipsocket_blacklisting) of
{ok, true} ->
{ok, StdDuration} = yxa_config:get_env(sipsocket_blacklist_duration),
{ok, MaxPenalty} = yxa_config:get_env(sipsocket_blacklist_max),
Now = util:timestamp(),
ProbeTS =
case RetryAfter of
undefined ->
{ok, ProbeDelay} = yxa_config:get_env(sipsocket_blacklist_probe_delay),
Now + ProbeDelay;
_ ->
undefined
end,
do_report_unreachable(SipDst, SipSocket, lists:flatten(Msg), RetryAfter,
StdDuration, MaxPenalty, ProbeTS, Now, ?SIPSOCKET_BLACKLIST);
{ok, false} ->
ok
end.
@spec ( SipDst ) - > ok
SipDst = # sipdst { }
remove_blacklisting(SipDst) when is_record(SipDst, sipdst) ->
do_remove_blacklisting(SipDst, ?SIPSOCKET_BLACKLIST).
remove_blacklisting(SipDst, EtsRef) when is_record(SipDst, sipdst) ->
do_remove_blacklisting(SipDst, EtsRef).
@spec ( SipDst ) - > true | false
SipDst = # sipdst { }
is_blacklisted(SipDst) when is_record(SipDst, sipdst) ->
case yxa_config:get_env(sipsocket_blacklisting) of
{ok, true} ->
do_is_blacklisted(SipDst, util:timestamp(), ?SIPSOCKET_BLACKLIST);
{ok, false} ->
false
end.
Dst = { Proto , Addr , Port } " ets table lookup key "
term ( )
lookup_sipsocket_blacklist({_Proto, _Addr, _Port} = _Dst) ->
undefined.
get_blacklist_name() ->
?SIPSOCKET_BLACKLIST.
{ ok , State , Timeout } |
init([TableName]) ->
{ok, #state{bl = TableName}, ?TIMEOUT}.
@spec handle_call(Msg , From , State ) - >
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
@spec ( Unknown , From , State ) - >
{ reply , { error , not_implemented } , State , Timeout::integer ( ) }
handle_call(Unknown, _From, State) ->
logger:log(error, "Sipsocket blacklist: Received unknown gen_server call : ~p", [Unknown]),
{reply, {error, not_implemented}, State, ?TIMEOUT}.
@spec handle_cast(Msg , State ) - >
{ noreply , State } |
{ noreply , State , Timeout } |
@spec ( Unknown , State ) - > { noreply , State , Timeout::integer ( ) }
handle_cast(Unknown, State) ->
logger:log(error, "Sipsocket blacklist: Received unknown gen_server cast : ~p", [Unknown]),
{noreply, State, ?TIMEOUT}.
@spec handle_info(Msg , State ) - >
{ noreply , State } |
{ noreply , State , Timeout } |
@spec ( timeout , State ) - > { noreply , State , Timeout::integer ( ) }
handle_info(timeout, State) ->
AllEntrys = ets:tab2list(State#state.bl),
case AllEntrys of
[] -> ok;
_ ->
logger:log(debug, "Sipsocket blacklist: Extra debug: Contents of blacklist table is :~n~p",
[AllEntrys]),
delete_expired_entrys(AllEntrys, util:timestamp(), State#state.bl)
end,
{noreply, State, ?TIMEOUT}.
@spec ( Reason , State ) - > term ( ) " ignored by gen_server "
terminate(_Reason, _State) ->
ok.
@spec ( OldVsn , State , Extra ) - > { ok , NewState }
@doc Convert process state when code is changed
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
@spec ( SipDst , SipSocket , Msg , , StdDuration ,
MaxPenalty , ProbeTS , Now , ) - > ok
SipDst = # sipdst { }
Msg = string ( ) " reason for blacklisting ( only for debug / diagnostic use ) "
= integer ( ) | undefined " seconds requested by upper layers ( through an Retry - After header in a 503 response for example ) "
StdDuration = integer ( ) " configured default duration - used if is ' undefined ' "
MaxPenalty = integer ( ) " configured duration "
do_report_unreachable(SipDst, SipSocket, Msg, SecondsIn, StdDuration, MaxPenalty, ProbeTS, Now, EtsRef) ->
Dst = make_dst(SipDst),
case get_blacklist_time(Dst, SecondsIn, EtsRef, StdDuration, MaxPenalty) of
Seconds when is_integer(Seconds) ->
logger:log(debug, "Sipsocket blacklist: Blacklisting destination ~s for ~p seconds",
[sipdst:dst2str(SipDst), Seconds]),
Entry =
#blacklist_entry{pid = self(),
reason = Msg,
ts = Now,
probe_t = ProbeTS,
duration = Seconds
},
ets:insert(EtsRef, {Dst, Entry}),
case is_record(SipSocket, sipsocket) of
true ->
case sipsocket:close_socket(SipSocket) of
ok -> ok;
{error, not_applicable} -> ok;
{error, Reason} ->
logger:log(error, "Sipsocket blacklist: Failed closing sipsocket ~p : ~p",
[SipSocket, Reason])
end,
ok;
false ->
ok
end;
ignore ->
ok
end,
ok.
@spec ( Dst , , , StdDuration , MaxDuration ) - >
Dst = term ( ) " ETS table key "
= integer ( ) | undefined " seconds requested by upper layers ( through an Retry - After header in a 503 response for example ) "
StdDuration = integer ( ) " configured default duration - used if is ' undefined ' "
MaxDuration = integer ( ) " configured duration "
get_blacklist_time(Dst, SecondsIn, EtsRef, StdDuration, MaxDuration) ->
case lookup_dst(Dst, EtsRef) of
{ok, blacklisted} ->
ignore;
{ok, whitelisted} ->
ignore;
{ok, OldEntry} when is_record(OldEntry, blacklist_entry) ->
get_blacklist_time_res(SecondsIn, StdDuration, MaxDuration);
none ->
get_blacklist_time_res(SecondsIn, StdDuration, MaxDuration)
end.
part of get_blacklist_time/5
get_blacklist_time_res(undefined, StdDur, Max) ->
lists:min([StdDur, Max]);
get_blacklist_time_res(N, _StdDur, Max) when is_integer(N) ->
lists:min([N, Max]).
@spec ( SipDst , ) - > ok
SipDst = # sipdst { }
exported function is not used by the YXA stack or
do_remove_blacklisting(SipDst, EtsRef) when is_record(SipDst, sipdst) ->
Dst = make_dst(SipDst),
case lookup_dst(Dst, EtsRef) of
{ok, Entry} when is_record(Entry, blacklist_entry) ->
logger:log(debug, "Sipsocket blacklist: Removing blacklisting of ~s", [sipdst:dst2str(SipDst)]),
ets:delete(EtsRef, Dst);
{ok, blacklisted} ->
logger:log(debug, "Sipsocket blacklist: NOT removing (static) blacklisting of ~s",
[sipdst:dst2str(SipDst)]),
ok;
{ok, whitelisted} ->
ok;
none ->
ok
end,
ok.
@spec ( SipDst , Now , ) - >
NewDstList
SipDst = # sipdst { }
= [ # sipdst { } ]
do_is_blacklisted(SipDst, Now, EtsRef) ->
Dst = make_dst(SipDst),
case lookup_dst(Dst, EtsRef) of
{ok, #blacklist_entry{duration = Duration} = Entry} when is_integer(Duration) ->
case (Entry#blacklist_entry.ts + Duration) - Now of
Remaining when Remaining > 0 ->
DstStr = sipdst:dst2str(SipDst),
logger:log(debug, "Sipsocket blacklist: Skipping destination ~s, blacklisted for ~p more seconds",
[DstStr, Remaining]),
start_background_probe(SipDst, Dst, DstStr, Entry#blacklist_entry.probe_t, Now, EtsRef),
true;
_ ->
false
end;
{ok, blacklisted} ->
logger:log(debug, "Sipsocket blacklist: Skipping destination ~s, blacklisted statically",
[sipdst:dst2str(SipDst)]),
true;
{ok, whitelisted} ->
false;
none ->
false
end.
start_background_probe(SipDst, Dst, DstStr, ProbeT, Now, EtsRef) when is_integer(ProbeT), Now >= ProbeT ->
ProbeId = {probe, Dst},
case ets:insert_new(EtsRef, {ProbeId, self()}) of
true ->
case (SipDst#sipdst.proto == yxa_test) of
true ->
self() ! {start_background_probe, ProbeId};
false ->
{ok, ProbePid} = sipsocket_blacklist_probe:start(SipDst, EtsRef, ProbeId, ?PROBE_TIMEOUT),
logger:log(debug, "Sipsocket blacklist: Started background probe for destination ~s : ~p",
[DstStr, ProbePid])
end;
false ->
logger:log(debug, "Sipsocket blacklist: Extra debug: NOT starting background probe for "
"destination ~s since one is already running", [DstStr])
end,
ok;
start_background_probe(_SipDst, _Dst, DstStr, ProbeT, Now, _EtsRef) when is_integer(ProbeT) ->
logger:log(debug, "Sipsocket blacklist: Extra debug: NOT starting background probe for "
"destination ~s for another ~p seconds",
[DstStr, ProbeT - Now]),
ok;
start_background_probe(_SipDst, _Dst, DstStr, undefined, _Now, _EtsRef) ->
logger:log(debug, "Sipsocket blacklist: Extra debug: NOT starting background probe for "
"destination ~s",
[DstStr]),
ok.
@spec ( Dst , ) - >
@doc Returns the latest entry for Dst . Note well that the entry
lookup_dst({_Proto, _Addr, _Port} = Dst, EtsRef) ->
case local:lookup_sipsocket_blacklist(Dst) of
{ok, Res} ->
{ok, Res};
undefined ->
case ets:lookup(EtsRef, Dst) of
[] ->
none;
Entrys when is_list(Entrys) ->
{Dst, LatestEntry} = hd(lists:reverse(Entrys)),
{ok, LatestEntry}
end
end.
@spec ( In , Now , ) - > ok
Dst = term ( ) " lookup key ( { Proto , Addr , Port } ) "
delete_expired_entrys([{Dst, H} | T], Now, EtsRef) when is_record(H, blacklist_entry) ->
case (H#blacklist_entry.ts + H#blacklist_entry.duration) - Now of
Remaining when Remaining =< 0 ->
logger:log(debug, "Sipsocket blacklist: Extra debug: Removing expired entry for ~p : ~p",
[Dst, H]),
ets:delete_object(EtsRef, {Dst, H});
_ ->
ok
end,
delete_expired_entrys(T, Now, EtsRef);
delete_expired_entrys([{{probe, _Dst}, _ProbePid} | T], Now, EtsRef) ->
delete_expired_entrys(T, Now, EtsRef);
delete_expired_entrys([], _Now, _EtsRef) ->
ok.
@spec ( SipDst ) - >
SipDst = # sipdst { }
make_dst(SipDst) when is_record(SipDst, sipdst) ->
{SipDst#sipdst.proto, SipDst#sipdst.addr, SipDst#sipdst.port}.
-ifdef( YXA_NO_UNITTEST ).
test() ->
{error, "Unit test code disabled at compile time"}.
-else.
test() ->
Self = self(),
TestEtsRef = ets:new(yxa_blacklist_test, [bag]),
TestSipDst1 = #sipdst{proto = yxa_test,
addr = "192.0.2.1",
port = 6050
},
TestDst1 = make_dst(TestSipDst1),
TestSipSocket1 = #sipsocket{proto = yxa_test,
module = sipsocket_test
},
TestSipDst2 = #sipdst{proto = yxa_test,
addr = "192.0.2.2",
port = 6050
},
test # 1 , add , read and delete
autotest:mark(?LINE, "blacklisting test 1 - 1"),
TestNow1 = 10000000,
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test", undefined, 90, 120, 1234, TestNow1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 2"),
TestBLEntry1 = #blacklist_entry{pid = Self,
reason = "test",
ts = TestNow1,
probe_t = 1234,
duration = 90
},
[{TestDst1, TestBLEntry1}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 3"),
{ok, TestBLEntry1} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 4"),
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test", 100, 90, 120, 1234, TestNow1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 5"),
TestBLEntry5 = TestBLEntry1#blacklist_entry{duration = 100},
[{TestDst1, TestBLEntry1}, {TestDst1, TestBLEntry5}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 6"),
{ok, TestBLEntry5} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 7"),
TableContents8 = [{TestDst1, TestBLEntry1}, {TestDst1, TestBLEntry5}],
TableContents8 = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 8"),
{ok, TestBLEntry5} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 9"),
ok = do_remove_blacklisting(TestSipDst2, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 10"),
TableContents8 = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 11"),
ok = do_remove_blacklisting(TestSipDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 1 - 12"),
[] = ets:tab2list(TestEtsRef),
test # 2 , two expired entrys
autotest:mark(?LINE, "blacklisting test 2 - 1"),
TestNow2 = 10000000,
simulate inserting entry 100 seconds ago , with expire time 60 seconds
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test 2", 60, 30, 120,
undefined, TestNow2 - 100, TestEtsRef),
simulate inserting entry 90 seconds ago , with expire time 30 seconds
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test 2", undefined, 30, 120,
undefined, TestNow2 - 90, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 2"),
[{_, _}, {_, _}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 3"),
TestBLEntry2 = #blacklist_entry{pid = Self,
reason = "test 2",
ts = TestNow2 - 90,
probe_t = undefined,
duration = 30
},
{ok, TestBLEntry2} = lookup_dst(TestDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 4"),
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test 2", 60, 30, 120,
undefined, TestNow2, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 5"),
ok = delete_expired_entrys(ets:tab2list(TestEtsRef), TestNow2, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 6"),
TestBLEntry2_1 = TestBLEntry2#blacklist_entry{ts = TestNow2,
duration = 60
},
[{TestDst1, TestBLEntry2_1}] = ets:tab2list(TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 7"),
ok = do_remove_blacklisting(TestSipDst1, TestEtsRef),
autotest:mark(?LINE, "blacklisting test 2 - 8"),
[] = ets:tab2list(TestEtsRef),
do_is_blacklisted(SipDst , Now , )
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.0"),
TestISBL_Now = util:timestamp(),
TestISBL_Penalty = 100,
ok = do_report_unreachable(TestSipDst1, TestSipSocket1, "test", TestISBL_Penalty, 90, 120,
undefined, TestISBL_Now, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.1"),
other SipDst
false = do_is_blacklisted(TestSipDst2, TestISBL_Now, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.2"),
blacklisted for one more second
true = do_is_blacklisted(TestSipDst1, TestISBL_Now + TestISBL_Penalty - 1, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 1.3"),
blacklisting expires this very second
false = do_is_blacklisted(TestSipDst1, TestISBL_Now + TestISBL_Penalty, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.0"),
TestISBL_ProbeT = TestISBL_Now + 5,
TestISBL_Expire = 120,
ok = do_report_unreachable(TestSipDst2, TestSipSocket1, "test", TestISBL_Penalty,
90, 120, TestISBL_ProbeT, TestISBL_Now, TestEtsRef),
receive
TestISBL_M1 ->
throw({error, test_received_unknown_signal, TestISBL_M1})
after 0 ->
ok
end,
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.1"),
blacklisted , but no probe for one more second
true = do_is_blacklisted(TestSipDst2, TestISBL_ProbeT - 1, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.2"),
receive
TestISBL_M2 ->
throw({error, test_received_unknown_signal, TestISBL_M2})
after 0 ->
ok
end,
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.3"),
false = do_is_blacklisted(TestSipDst2, TestISBL_Now + TestISBL_Expire, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 2.4"),
true = do_is_blacklisted(TestSipDst2, TestISBL_ProbeT, TestEtsRef),
receive
{start_background_probe, {probe, TestDst2}} ->
ets:delete(TestEtsRef, {probe, TestDst2}),
ok
after 0 ->
throw({error, "background probe did not start"})
end,
autotest:mark(?LINE, "do_is_blacklisted/3 - 3.0"),
ok = do_remove_blacklisting(TestSipDst1, TestEtsRef),
ok = do_remove_blacklisting(TestSipDst2, TestEtsRef),
autotest:mark(?LINE, "do_is_blacklisted/3 - 3.1"),
[] = ets:tab2list(TestEtsRef),
ok.
-endif.
|
0f9dae7f5c13f7ebbcf5e5fbef335bd7138388626860ae311b8934fa39b880a8 | apinf/proxy42 | proxy42_plugins.erl | -module(proxy42_plugins).
-export([]).
-compile(export_all).
-behaviour(gen_server).
-define(SERVER, ?MODULE).
-define(APP, proxy42_core).
start() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], [{hibernate_after, 5000}]).
init(_opts) ->
{ok, Plugins} = application:get_env(proxy42_core, plugins),
State = lists:map(fun(Plugin) -> register_plugin_i(Plugin) end, Plugins),
{ok, State}.
terminate(_Reason, _State) ->
ok.
handle_call({register_plugin, Plugin}, _From, State) ->
NewState = [register_plugin_i(Plugin) | State],
{reply, ok, NewState, hibernate};
handle_call(get_registered_plugins, _From, State) ->
{reply, State, State, hibernate}.
handle_cast(_Whatever, State) ->
{noreply, State, hibernate}.
create_tables([]) ->
[];
create_tables([Tab| Rest]) ->
create_table(Tab),
create_tables(Rest).
% TODO: Detect failures and crash
create_table({Name, Attrs}) ->
% TODO: Distributiion. Handle table locations and othe props.
ok = proxy42_storage:ensure_table(Name, [{attributes, Attrs}, {disc_copies, [node()]}]).
register_plugin(Plugin) ->
gen_server:call(?SERVER, {register_plugin, Plugin}).
register_plugin_i(Plugin) ->
{ok, Opts} = Plugin:init(),
%% TODO: Check slug for duplicates
%% TODO: Then create tables
%% TODO: Then add to ets/mnesia
handle_opts(Opts),
{Plugin, Opts}.
-type plugin() :: atom().
-type opts() :: [{atom(), term()}].
-spec get_registered_plugins() -> [{plugin(), opts()}].
get_registered_plugins() ->
gen_server:call(?SERVER, get_registered_plugins).
handle_opts([]) ->
[];
handle_opts([{tables, Tabs}| Rest]) ->
create_tables(Tabs),
[{tables, Tabs} | handle_opts(Rest)];
handle_opts([_ | X]) ->
handle_opts(X).
% TODO: Register slug, register strategies, get rid of catch all.
% Unknown opts must cause a crash.
| null | https://raw.githubusercontent.com/apinf/proxy42/01b483b711881391e8306bf64b83b4df9d0bc832/apps/proxy42_core/src/proxy42_plugins.erl | erlang | TODO: Detect failures and crash
TODO: Distributiion. Handle table locations and othe props.
TODO: Check slug for duplicates
TODO: Then create tables
TODO: Then add to ets/mnesia
TODO: Register slug, register strategies, get rid of catch all.
Unknown opts must cause a crash. | -module(proxy42_plugins).
-export([]).
-compile(export_all).
-behaviour(gen_server).
-define(SERVER, ?MODULE).
-define(APP, proxy42_core).
start() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], [{hibernate_after, 5000}]).
init(_opts) ->
{ok, Plugins} = application:get_env(proxy42_core, plugins),
State = lists:map(fun(Plugin) -> register_plugin_i(Plugin) end, Plugins),
{ok, State}.
terminate(_Reason, _State) ->
ok.
handle_call({register_plugin, Plugin}, _From, State) ->
NewState = [register_plugin_i(Plugin) | State],
{reply, ok, NewState, hibernate};
handle_call(get_registered_plugins, _From, State) ->
{reply, State, State, hibernate}.
handle_cast(_Whatever, State) ->
{noreply, State, hibernate}.
create_tables([]) ->
[];
create_tables([Tab| Rest]) ->
create_table(Tab),
create_tables(Rest).
create_table({Name, Attrs}) ->
ok = proxy42_storage:ensure_table(Name, [{attributes, Attrs}, {disc_copies, [node()]}]).
register_plugin(Plugin) ->
gen_server:call(?SERVER, {register_plugin, Plugin}).
register_plugin_i(Plugin) ->
{ok, Opts} = Plugin:init(),
handle_opts(Opts),
{Plugin, Opts}.
-type plugin() :: atom().
-type opts() :: [{atom(), term()}].
-spec get_registered_plugins() -> [{plugin(), opts()}].
get_registered_plugins() ->
gen_server:call(?SERVER, get_registered_plugins).
handle_opts([]) ->
[];
handle_opts([{tables, Tabs}| Rest]) ->
create_tables(Tabs),
[{tables, Tabs} | handle_opts(Rest)];
handle_opts([_ | X]) ->
handle_opts(X).
|
0f5d9c33f7e1cf283a423c3de5749894ce6903c3b8f0e939099808d293ece251 | mjstewart/rejig | Main.hs | module Main
where
--------------------------------------------------------------------------------
-- standard imports
import Text.Megaparsec
import Text.PrettyPrint
( render
)
import qualified Data.Text.IO as TIO
import qualified Options.Applicative as O
imports by Rejig *
import Rejig.Parser
import Rejig.Settings
import Rejig.Sorter
import Rejig.Pretty
( showPretty
)
--------------------------------------------------------------------------------
fileInput :: O.Parser Input
fileInput =
FileInput <$>
(O.strOption $
O.long "file"
<> O.metavar "FILEPATH"
<> O.help "input file path")
stdInput :: O.Parser Input
stdInput =
StdInput <$>
(O.strOption $
O.long "stdin"
<> O.metavar "DESCRIPTION"
<> O.help "read using stdin including an input source description")
inputP :: O.Parser Input
inputP = fileInput <|> stdInput
srcLangP :: O.Parser SourceLang
srcLangP =
haskellLang <|> damlLang
where
haskellLang =
O.flag' Haskell $
O.long "haskell"
<> O.help "format haskell source"
damlLang =
O.flag' Daml $
O.long "daml"
<> O.help "format daml source"
prefixP :: O.Parser [Text]
prefixP =
words <$>
(O.strOption $
O.long "prefixes"
<> O.value ""
<> O.metavar "ARG1 ARG2 ..."
<> O.help "import names beginning with matching prefixes are grouped together. Provide from least to most specific order")
importTitleP :: O.Parser Bool
importTitleP =
O.switch $
O.long "titles"
<> O.help "Display import group titles"
importBorderTopP :: O.Parser Bool
importBorderTopP =
O.switch $
O.long "border-top"
<> O.help "Display border at the start of import declarations"
importBorderBottomP :: O.Parser Bool
importBorderBottomP =
O.switch $
O.long "border-bottom"
<> O.help "Display border at the end of import declarations"
settingsP :: O.Parser Settings
settingsP = Settings
<$> inputP
<*> srcLangP
<*> prefixP
<*> importTitleP
<*> importBorderTopP
<*> importBorderBottomP
opts :: O.ParserInfo Settings
opts = O.info (settingsP <**> O.helper)
$ O.fullDesc
<> O.progDesc "Sort and format module header declarations"
<> O.header "Rejig"
main :: IO ()
main = do
settings <- O.execParser opts
case _sInput settings of
FileInput path -> do
runFormatter path settings =<< TIO.readFile path
StdInput description ->
runFormatter description settings =<< TIO.getContents
runFormatter :: String -> Settings -> Text -> IO ()
runFormatter description settings content = do
putStrLn $
case runParser parseSourceP description content of
Left bundle -> toResponse "error" $ errorBundlePretty bundle
Right res ->
toResponse "ok" $ render $
runReader (showPretty $ runReader (sortParsedSource res) settings) settings
toResponse :: String -> String -> String
toResponse status body =
"{ \"status\": " <> show status <> ", \"data\": " <> show body <> "}"
mkDefaultSettings :: IO Settings
mkDefaultSettings =
pure $
Settings
{ _sInput = StdInput "demo"
, _ssrcLang = Daml
, _sPrefixGroups = ["Daml", "DA", "DA.Next", "DA.Finance", "Test.MyApp", "Main.MyApp"]
, _sDisplayGroupTitle = True
, _sImportBorderTop = True
, _sImportBorderBottom = True
}
-- For testing
parseFile :: FilePath -> IO ()
parseFile path = do
txt <- TIO.readFile path
settings <- mkDefaultSettings
case runParser parseSourceP "test" txt of
Left bundle -> writeFile "test/snippets/result.txt" (errorBundlePretty bundle)
Right res ->
writeFile "test/snippets/result.txt" $
render $
runReader (showPretty $ runReader (sortParsedSource res) settings) settings
| null | https://raw.githubusercontent.com/mjstewart/rejig/f359cfba44196671df5210da714e07a5ba64263c/src/Main.hs | haskell | ------------------------------------------------------------------------------
standard imports
------------------------------------------------------------------------------
For testing | module Main
where
import Text.Megaparsec
import Text.PrettyPrint
( render
)
import qualified Data.Text.IO as TIO
import qualified Options.Applicative as O
imports by Rejig *
import Rejig.Parser
import Rejig.Settings
import Rejig.Sorter
import Rejig.Pretty
( showPretty
)
fileInput :: O.Parser Input
fileInput =
FileInput <$>
(O.strOption $
O.long "file"
<> O.metavar "FILEPATH"
<> O.help "input file path")
stdInput :: O.Parser Input
stdInput =
StdInput <$>
(O.strOption $
O.long "stdin"
<> O.metavar "DESCRIPTION"
<> O.help "read using stdin including an input source description")
inputP :: O.Parser Input
inputP = fileInput <|> stdInput
srcLangP :: O.Parser SourceLang
srcLangP =
haskellLang <|> damlLang
where
haskellLang =
O.flag' Haskell $
O.long "haskell"
<> O.help "format haskell source"
damlLang =
O.flag' Daml $
O.long "daml"
<> O.help "format daml source"
prefixP :: O.Parser [Text]
prefixP =
words <$>
(O.strOption $
O.long "prefixes"
<> O.value ""
<> O.metavar "ARG1 ARG2 ..."
<> O.help "import names beginning with matching prefixes are grouped together. Provide from least to most specific order")
importTitleP :: O.Parser Bool
importTitleP =
O.switch $
O.long "titles"
<> O.help "Display import group titles"
importBorderTopP :: O.Parser Bool
importBorderTopP =
O.switch $
O.long "border-top"
<> O.help "Display border at the start of import declarations"
importBorderBottomP :: O.Parser Bool
importBorderBottomP =
O.switch $
O.long "border-bottom"
<> O.help "Display border at the end of import declarations"
settingsP :: O.Parser Settings
settingsP = Settings
<$> inputP
<*> srcLangP
<*> prefixP
<*> importTitleP
<*> importBorderTopP
<*> importBorderBottomP
opts :: O.ParserInfo Settings
opts = O.info (settingsP <**> O.helper)
$ O.fullDesc
<> O.progDesc "Sort and format module header declarations"
<> O.header "Rejig"
main :: IO ()
main = do
settings <- O.execParser opts
case _sInput settings of
FileInput path -> do
runFormatter path settings =<< TIO.readFile path
StdInput description ->
runFormatter description settings =<< TIO.getContents
runFormatter :: String -> Settings -> Text -> IO ()
runFormatter description settings content = do
putStrLn $
case runParser parseSourceP description content of
Left bundle -> toResponse "error" $ errorBundlePretty bundle
Right res ->
toResponse "ok" $ render $
runReader (showPretty $ runReader (sortParsedSource res) settings) settings
toResponse :: String -> String -> String
toResponse status body =
"{ \"status\": " <> show status <> ", \"data\": " <> show body <> "}"
mkDefaultSettings :: IO Settings
mkDefaultSettings =
pure $
Settings
{ _sInput = StdInput "demo"
, _ssrcLang = Daml
, _sPrefixGroups = ["Daml", "DA", "DA.Next", "DA.Finance", "Test.MyApp", "Main.MyApp"]
, _sDisplayGroupTitle = True
, _sImportBorderTop = True
, _sImportBorderBottom = True
}
parseFile :: FilePath -> IO ()
parseFile path = do
txt <- TIO.readFile path
settings <- mkDefaultSettings
case runParser parseSourceP "test" txt of
Left bundle -> writeFile "test/snippets/result.txt" (errorBundlePretty bundle)
Right res ->
writeFile "test/snippets/result.txt" $
render $
runReader (showPretty $ runReader (sortParsedSource res) settings) settings
|
bbbd739ecfca2e60888b578ddbfa584e5be9e9087e7a7c95a0fb50cc6a77051c | samuelrivas/moka | mok_internal_functions_aux.erl | Copyright ( c ) 2012 , < >
%%% All rights reserved.
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions are met:
%%% * Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
%%% * Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in the
%%% documentation and/or other materials provided with the distribution.
%%% * Neither the name the author nor the names of its contributors may
%%% be used to endorse or promote products derived from this software
%%% without specific prior written permission.
%%%
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
%%% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%%% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
%%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
%%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%%% THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%% @doc This file is used by {@link mok_internal_functions} tests
-module(mok_internal_functions_aux).
-export([call/1]).
call(X) -> internal(X).
internal(X) -> {not_moked, X}.
%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
erlang - indent - level : 4
%%% End:
| null | https://raw.githubusercontent.com/samuelrivas/moka/92521e43d1d685794f462ed49403c99baeae0226/test/acceptance/mok_internal_functions_aux.erl | erlang | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name the author nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@doc This file is used by {@link mok_internal_functions} tests
_* Emacs ============================================================
Local Variables:
allout-layout: t
End: | Copyright ( c ) 2012 , < >
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-module(mok_internal_functions_aux).
-export([call/1]).
call(X) -> internal(X).
internal(X) -> {not_moked, X}.
erlang - indent - level : 4
|
2390281232a968ea7ebd3cd96bea8c0d5796971a2df2dcd9863e81f541e5f7e8 | basho/riak_test | replication_upgrade.erl | -module(replication_upgrade).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
OrigDelay = rt_config:get(rt_retry_delay, 1000),
lager:info("Original rt_retry_delay is ~p", [OrigDelay]),
rt_config:set(rt_retry_delay, OrigDelay*5),
NewDelay = rt_config:get(rt_retry_delay),
lager:info("New rt_retry_delay is ~p", [NewDelay]),
TestMetaData = riak_test_runner:metadata(),
FromVersion = proplists:get_value(upgrade_version, TestMetaData, previous),
lager:info("Doing rolling replication upgrade test from ~p to ~p",
[FromVersion, "current"]),
NumNodes = rt_config:get(num_nodes, 6),
UpgradeOrder = rt_config:get(repl_upgrade_order, "forwards"),
lager:info("Deploy ~p nodes", [NumNodes]),
Conf = [
{riak_repl,
[
{fullsync_on_connect, false},
{fullsync_interval, disabled}
]}
],
NodeConfig = [{FromVersion, Conf} || _ <- lists:seq(1, NumNodes)],
Nodes = rt:deploy_nodes(NodeConfig, [riak_kv, riak_repl]),
NodeUpgrades = case UpgradeOrder of
"forwards" ->
Nodes;
"backwards" ->
lists:reverse(Nodes);
"alternate" ->
eg 1 , 4 , 2 , 5 , 3 , 6
lists:flatten(lists:foldl(fun(E, [A,B,C]) -> [B, C, A ++ [E]] end,
[[],[],[]], Nodes));
"random" ->
%% halfass randomization
lists:sort(fun(_, _) -> random:uniform(100) < 50 end, Nodes);
Other ->
lager:error("Invalid upgrade ordering ~p", [Other]),
erlang:exit()
end,
ClusterASize = rt_config:get(cluster_a_size, 3),
{ANodes, BNodes} = lists:split(ClusterASize, Nodes),
lager:info("ANodes: ~p", [ANodes]),
lager:info("BNodes: ~p", [BNodes]),
lager:info("Build cluster A"),
repl_util:make_cluster(ANodes),
lager:info("Build cluster B"),
repl_util:make_cluster(BNodes),
lager:info("Replication First pass...homogenous cluster"),
%% initial replication run, homogeneous cluster
replication:replication(ANodes, BNodes, false),
lager:info("Upgrading nodes in order: ~p", [NodeUpgrades]),
rt:log_to_nodes(Nodes, "Upgrading nodes in order: ~p", [NodeUpgrades]),
%% upgrade the nodes, one at a time
ok = lists:foreach(fun(Node) ->
lager:info("Upgrade node: ~p", [Node]),
rt:log_to_nodes(Nodes, "Upgrade node: ~p", [Node]),
rt:upgrade(Node, current),
rt:wait_until_pingable(Node),
rt:wait_for_service(Node, [riak_kv, riak_pipe, riak_repl]),
[rt:wait_until_ring_converged(N) || N <- [ANodes, BNodes]],
%% Prior to 1.4.8 riak_repl registered
%% as a service before completing all
%% initialization including establishing
%% realtime connections.
%%
@TODO Ideally the test would only wait
%% for the connection in the case of the
%% node version being < 1.4.8, but currently
the rt API does not provide a
%% harness-agnostic method do get the node
%% version. For now the test waits for all
%% source cluster nodes to establish a
%% connection before proceeding.
case lists:member(Node, ANodes) of
true ->
replication:wait_until_connection(Node);
false ->
ok
end,
lager:info("Replication with upgraded node: ~p", [Node]),
rt:log_to_nodes(Nodes, "Replication with upgraded node: ~p", [Node]),
replication:replication(ANodes, BNodes, true)
end, NodeUpgrades),
lager:info("Resetting rt_retry_delay to ~p", [OrigDelay]),
rt_config:set(rt_retry_delay, OrigDelay),
pass.
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/replication_upgrade.erl | erlang | halfass randomization
initial replication run, homogeneous cluster
upgrade the nodes, one at a time
Prior to 1.4.8 riak_repl registered
as a service before completing all
initialization including establishing
realtime connections.
for the connection in the case of the
node version being < 1.4.8, but currently
harness-agnostic method do get the node
version. For now the test waits for all
source cluster nodes to establish a
connection before proceeding. | -module(replication_upgrade).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
OrigDelay = rt_config:get(rt_retry_delay, 1000),
lager:info("Original rt_retry_delay is ~p", [OrigDelay]),
rt_config:set(rt_retry_delay, OrigDelay*5),
NewDelay = rt_config:get(rt_retry_delay),
lager:info("New rt_retry_delay is ~p", [NewDelay]),
TestMetaData = riak_test_runner:metadata(),
FromVersion = proplists:get_value(upgrade_version, TestMetaData, previous),
lager:info("Doing rolling replication upgrade test from ~p to ~p",
[FromVersion, "current"]),
NumNodes = rt_config:get(num_nodes, 6),
UpgradeOrder = rt_config:get(repl_upgrade_order, "forwards"),
lager:info("Deploy ~p nodes", [NumNodes]),
Conf = [
{riak_repl,
[
{fullsync_on_connect, false},
{fullsync_interval, disabled}
]}
],
NodeConfig = [{FromVersion, Conf} || _ <- lists:seq(1, NumNodes)],
Nodes = rt:deploy_nodes(NodeConfig, [riak_kv, riak_repl]),
NodeUpgrades = case UpgradeOrder of
"forwards" ->
Nodes;
"backwards" ->
lists:reverse(Nodes);
"alternate" ->
eg 1 , 4 , 2 , 5 , 3 , 6
lists:flatten(lists:foldl(fun(E, [A,B,C]) -> [B, C, A ++ [E]] end,
[[],[],[]], Nodes));
"random" ->
lists:sort(fun(_, _) -> random:uniform(100) < 50 end, Nodes);
Other ->
lager:error("Invalid upgrade ordering ~p", [Other]),
erlang:exit()
end,
ClusterASize = rt_config:get(cluster_a_size, 3),
{ANodes, BNodes} = lists:split(ClusterASize, Nodes),
lager:info("ANodes: ~p", [ANodes]),
lager:info("BNodes: ~p", [BNodes]),
lager:info("Build cluster A"),
repl_util:make_cluster(ANodes),
lager:info("Build cluster B"),
repl_util:make_cluster(BNodes),
lager:info("Replication First pass...homogenous cluster"),
replication:replication(ANodes, BNodes, false),
lager:info("Upgrading nodes in order: ~p", [NodeUpgrades]),
rt:log_to_nodes(Nodes, "Upgrading nodes in order: ~p", [NodeUpgrades]),
ok = lists:foreach(fun(Node) ->
lager:info("Upgrade node: ~p", [Node]),
rt:log_to_nodes(Nodes, "Upgrade node: ~p", [Node]),
rt:upgrade(Node, current),
rt:wait_until_pingable(Node),
rt:wait_for_service(Node, [riak_kv, riak_pipe, riak_repl]),
[rt:wait_until_ring_converged(N) || N <- [ANodes, BNodes]],
@TODO Ideally the test would only wait
the rt API does not provide a
case lists:member(Node, ANodes) of
true ->
replication:wait_until_connection(Node);
false ->
ok
end,
lager:info("Replication with upgraded node: ~p", [Node]),
rt:log_to_nodes(Nodes, "Replication with upgraded node: ~p", [Node]),
replication:replication(ANodes, BNodes, true)
end, NodeUpgrades),
lager:info("Resetting rt_retry_delay to ~p", [OrigDelay]),
rt_config:set(rt_retry_delay, OrigDelay),
pass.
|
e3d65e1803bd48fd4bc54beb79f1b81e19f717992785b01db3105775d05e6aa5 | wireapp/wire-server | RPC.hs | -- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
-- | General RPC utilities.
module Brig.RPC where
import Bilge
import Bilge.RPC
import Bilge.Retry
import Brig.App
import Control.Lens
import Control.Monad.Catch
import Control.Retry
import Data.Aeson
import Data.ByteString.Conversion
import qualified Data.ByteString.Lazy as BL
import Data.Id
import qualified Data.Text as Text
import qualified Data.Text.Lazy as LT
import Imports
import Network.HTTP.Client (HttpExceptionContent (..), checkResponse)
import Network.HTTP.Types.Method
import Network.HTTP.Types.Status
import System.Logger.Class hiding (name, (.=))
x3 :: RetryPolicy
x3 = limitRetries 3 <> exponentialBackoff 100000
zUser :: UserId -> Request -> Request
zUser = header "Z-User" . toByteString'
remote :: ByteString -> Msg -> Msg
remote = field "remote"
decodeBody :: (Typeable a, FromJSON a, MonadThrow m) => Text -> Response (Maybe BL.ByteString) -> m a
decodeBody ctx = responseJsonThrow (ParseException ctx)
expect :: [Status] -> Request -> Request
expect ss rq = rq {checkResponse = check}
where
check rq' rs = do
let s = responseStatus rs
rs' = rs {responseBody = ()}
when (statusIsServerError s || s `notElem` ss) $
throwM $
HttpExceptionRequest rq' (StatusCodeException rs' mempty)
cargoholdRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
cargoholdRequest = serviceRequest "cargohold" cargohold
galleyRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
galleyRequest = serviceRequest "galley" galley
gundeckRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
gundeckRequest = serviceRequest "gundeck" gundeck
serviceRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
LT.Text ->
Control.Lens.Getting Request Env Request ->
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
serviceRequest nm svc m r = do
service <- view svc
serviceRequestImpl nm service m r
serviceRequestImpl ::
(MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
LT.Text ->
Request ->
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
serviceRequestImpl nm service m r = do
recovering x3 rpcHandlers $
const $
rpc' nm service (method m . r)
-- | Failed to parse a response from another service.
data ParseException = ParseException
{ _parseExceptionRemote :: !Text,
_parseExceptionMsg :: String
}
instance Show ParseException where
show (ParseException r m) =
"Failed to parse response from remote "
++ Text.unpack r
++ " with message: "
++ m
instance Exception ParseException
| null | https://raw.githubusercontent.com/wireapp/wire-server/090e762ec0a2026a266c1fd2a288301b3759d92f/services/brig/src/Brig/RPC.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>.
| General RPC utilities.
| Failed to parse a response from another service. | Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Brig.RPC where
import Bilge
import Bilge.RPC
import Bilge.Retry
import Brig.App
import Control.Lens
import Control.Monad.Catch
import Control.Retry
import Data.Aeson
import Data.ByteString.Conversion
import qualified Data.ByteString.Lazy as BL
import Data.Id
import qualified Data.Text as Text
import qualified Data.Text.Lazy as LT
import Imports
import Network.HTTP.Client (HttpExceptionContent (..), checkResponse)
import Network.HTTP.Types.Method
import Network.HTTP.Types.Status
import System.Logger.Class hiding (name, (.=))
x3 :: RetryPolicy
x3 = limitRetries 3 <> exponentialBackoff 100000
zUser :: UserId -> Request -> Request
zUser = header "Z-User" . toByteString'
remote :: ByteString -> Msg -> Msg
remote = field "remote"
decodeBody :: (Typeable a, FromJSON a, MonadThrow m) => Text -> Response (Maybe BL.ByteString) -> m a
decodeBody ctx = responseJsonThrow (ParseException ctx)
expect :: [Status] -> Request -> Request
expect ss rq = rq {checkResponse = check}
where
check rq' rs = do
let s = responseStatus rs
rs' = rs {responseBody = ()}
when (statusIsServerError s || s `notElem` ss) $
throwM $
HttpExceptionRequest rq' (StatusCodeException rs' mempty)
cargoholdRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
cargoholdRequest = serviceRequest "cargohold" cargohold
galleyRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
galleyRequest = serviceRequest "galley" galley
gundeckRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
gundeckRequest = serviceRequest "gundeck" gundeck
serviceRequest ::
(MonadReader Env m, MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
LT.Text ->
Control.Lens.Getting Request Env Request ->
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
serviceRequest nm svc m r = do
service <- view svc
serviceRequestImpl nm service m r
serviceRequestImpl ::
(MonadIO m, MonadMask m, MonadHttp m, HasRequestId m) =>
LT.Text ->
Request ->
StdMethod ->
(Request -> Request) ->
m (Response (Maybe BL.ByteString))
serviceRequestImpl nm service m r = do
recovering x3 rpcHandlers $
const $
rpc' nm service (method m . r)
data ParseException = ParseException
{ _parseExceptionRemote :: !Text,
_parseExceptionMsg :: String
}
instance Show ParseException where
show (ParseException r m) =
"Failed to parse response from remote "
++ Text.unpack r
++ " with message: "
++ m
instance Exception ParseException
|
34e654a6d2e3c3a8dc2aefa915316548b333f7956348de68396370e513ae6fdf | ocaml-multicore/ocaml-tsan | odoc_latex.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cambium , INRIA Paris
(* *)
Copyright 2022 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. *)
(* *)
(**************************************************************************)
(** Generation of LaTeX documentation. *)
val separate_files : bool ref
val latex_titles : (int * string) list ref
val latex_value_prefix : string ref
val latex_type_prefix : string ref
val latex_type_elt_prefix : string ref
val latex_extension_prefix : string ref
val latex_exception_prefix : string ref
val latex_module_prefix : string ref
val latex_module_type_prefix : string ref
val latex_class_prefix : string ref
val latex_class_type_prefix : string ref
val latex_attribute_prefix : string ref
val latex_method_prefix : string ref
module Generator :
sig
class latex :
object
val subst_strings : (Str.regexp * string) list
val subst_strings_code : (Str.regexp * string) list
val subst_strings_simple : (Str.regexp * string) list
val mutable tag_functions :
(string * (Odoc_info.text -> Odoc_info.text)) list
method attribute_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method const_label : ?no_:bool -> Odoc_info.Name.t -> string
method entry_comment :
Format.formatter * (unit -> string) ->
Odoc_info.info option -> Odoc_info.text_element list
method escape : string -> string
method escape_code : string -> string
method escape_simple : string -> string
method exception_label : ?no_:bool -> Odoc_info.Name.t -> string
method extension_label : ?no_:bool -> Odoc_info.Name.t -> string
method first_and_rest_of_info :
Odoc_info.info option -> Odoc_info.text * Odoc_info.text
method generate : Odoc_info.Module.t_module list -> unit
method generate_class_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class -> unit
method generate_class_type_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method generate_for_top_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method generate_inheritance_info :
Format.formatter -> Odoc_info.Class.inherited_class list -> unit
method generate_style_file : unit
method label : ?no_:bool -> Odoc_info.Name.t -> string
method latex_for_class_index :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_label :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_type_index :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_class_type_label :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_module_index :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_label :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_type_index :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_for_module_type_label :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_header :
Format.formatter -> Odoc_info.Module.t_module list -> unit
method latex_of_Block : Format.formatter -> Odoc_info.text -> unit
method latex_of_Bold : Format.formatter -> Odoc_info.text -> unit
method latex_of_Center : Format.formatter -> Odoc_info.text -> unit
method latex_of_Code : Format.formatter -> string -> unit
method latex_of_CodePre : Format.formatter -> string -> unit
method latex_of_Emphasize :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Enum :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Italic : Format.formatter -> Odoc_info.text -> unit
method latex_of_Latex : Format.formatter -> string -> unit
method latex_of_Left : Format.formatter -> Odoc_info.text -> unit
method latex_of_Link :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_List :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Newline : Format.formatter -> unit
method latex_of_Raw : Format.formatter -> string -> unit
method latex_of_Ref :
Format.formatter ->
Odoc_info.Name.t ->
Odoc_info.ref_kind option -> Odoc_info.text option -> unit
method latex_of_Right : Format.formatter -> Odoc_info.text -> unit
method latex_of_Subscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Superscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Target :
Format.formatter -> target:string -> code:string -> unit
method latex_of_Title :
Format.formatter ->
int -> Odoc_info.Name.t option -> Odoc_info.text -> unit
method latex_of_Verbatim : Format.formatter -> string -> unit
method latex_of_attribute :
Format.formatter -> Odoc_info.Value.t_attribute -> unit
method latex_of_class :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_of_class_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_element -> unit
method latex_of_class_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_kind -> unit
method latex_of_class_parameter_list :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit
method latex_of_class_type :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_of_class_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_type_kind -> unit
method latex_of_cstr_args :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.constructor_args * Types.type_expr option ->
Odoc_info.text_element list
method latex_of_custom_text :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_exception :
Format.formatter -> Odoc_info.Exception.t_exception -> unit
method latex_of_included_module :
Format.formatter -> Odoc_info.Module.included_module -> unit
method latex_of_info :
Format.formatter -> ?block:bool -> Odoc_info.info option -> unit
method latex_of_method :
Format.formatter -> Odoc_info.Value.t_method -> unit
method latex_of_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_of_module_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit
method latex_of_module_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_kind -> unit
method latex_of_module_parameter :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit
method latex_of_module_type :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_of_module_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_type_kind -> unit
method latex_of_record :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.record_field list -> Odoc_info.text_element list
method latex_of_text : Format.formatter -> Odoc_info.text -> unit
method latex_of_text_element :
Format.formatter -> Odoc_info.text_element -> unit
method latex_of_type :
Format.formatter -> Odoc_info.Type.t_type -> unit
method latex_of_type_extension :
Odoc_info.Name.t ->
Format.formatter -> Odoc_info.Extension.t_type_extension -> unit
method latex_of_type_params :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit
method latex_of_value :
Format.formatter -> Odoc_info.Value.t_value -> unit
method make_label : string -> string
method make_ref : string -> string
method method_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method normal_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> string
method normal_class_type :
Odoc_info.Name.t -> Types.class_type -> string
method normal_class_type_param_list :
Odoc_info.Name.t -> Types.type_expr list -> string
method normal_cstr_args :
?par:bool ->
Odoc_info.Name.t -> Odoc_info.Type.constructor_args -> string
method normal_module_type :
?code:string -> Odoc_info.Name.t -> Types.module_type -> string
method normal_type : Odoc_info.Name.t -> Types.type_expr -> string
method normal_type_list :
?par:bool ->
Odoc_info.Name.t -> string -> Types.type_expr list -> string
method recfield_label : ?no_:bool -> Odoc_info.Name.t -> string
method relative_idents : Odoc_info.Name.t -> string -> string
method relative_module_idents : Odoc_info.Name.t -> string -> string
method section_style : int -> string -> string
method subst : (Str.regexp * string) list -> string -> string
method text_of_alerts :
Odoc_info.alert list -> Odoc_info.text_element list
method text_of_attribute :
Odoc_info.Value.t_attribute -> Odoc_info.text_element list
method text_of_author_list :
string list -> Odoc_info.text_element list
method text_of_before :
(string * Odoc_info.text) list -> Odoc_info.text_element list
method text_of_class_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_kind -> Odoc_info.text_element list
method text_of_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> Odoc_types.text
method text_of_class_type_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_type_kind -> Odoc_info.text_element list
method text_of_class_type_param_expr_list :
Odoc_info.Name.t ->
Types.type_expr list -> Odoc_info.text_element list
method text_of_custom :
(string * Odoc_info.text) list -> Odoc_info.text
method text_of_exception :
Odoc_info.Exception.t_exception -> Odoc_info.text_element list
method text_of_info :
?block:bool -> Odoc_info.info option -> Odoc_info.text
method text_of_method :
Odoc_info.Value.t_method -> Odoc_info.text_element list
method text_of_module_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_kind -> Odoc_info.text_element list
method text_of_module_parameter_list :
(Odoc_info.Module.module_parameter *
Odoc_info.text_element list option)
list -> Odoc_info.text_element list
method text_of_module_type :
Types.module_type -> Odoc_info.text_element list
method text_of_module_type_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_type_kind -> Odoc_info.text_element list
method text_of_parameter_description :
Odoc_info.Parameter.parameter -> Odoc_info.text
method text_of_parameter_list :
Odoc_info.Name.t ->
Odoc_info.Parameter.parameter list -> Odoc_info.text_element list
method text_of_raised_exceptions :
Odoc_info.raised_exception list -> Odoc_info.text_element list
method text_of_return_opt :
Odoc_info.text option -> Odoc_info.text_element list
method text_of_see : Odoc_info.see -> Odoc_info.text
method text_of_sees :
Odoc_info.see list -> Odoc_info.text_element list
method text_of_short_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_since_opt :
string option -> Odoc_info.text_element list
method text_of_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_type_expr_list :
Odoc_info.Name.t ->
string -> Types.type_expr list -> Odoc_info.text_element list
method text_of_value :
Odoc_info.Value.t_value -> Odoc_info.text_element list
method text_of_version_opt :
string option -> Odoc_info.text_element list
method type_label : ?no_:bool -> Odoc_info.Name.t -> string
method value_label : ?no_:bool -> Odoc_info.Name.t -> string
end
end
module type Latex_generator =
sig
class latex :
object
val subst_strings : (Str.regexp * string) list
val subst_strings_code : (Str.regexp * string) list
val subst_strings_simple : (Str.regexp * string) list
val mutable tag_functions :
(string * (Odoc_info.text -> Odoc_info.text)) list
method attribute_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method const_label : ?no_:bool -> Odoc_info.Name.t -> string
method entry_comment :
Format.formatter * (unit -> string) ->
Odoc_info.info option -> Odoc_info.text_element list
method escape : string -> string
method escape_code : string -> string
method escape_simple : string -> string
method exception_label : ?no_:bool -> Odoc_info.Name.t -> string
method extension_label : ?no_:bool -> Odoc_info.Name.t -> string
method first_and_rest_of_info :
Odoc_info.info option -> Odoc_info.text * Odoc_info.text
method generate : Odoc_info.Module.t_module list -> unit
method generate_class_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class -> unit
method generate_class_type_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method generate_for_top_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method generate_inheritance_info :
Format.formatter -> Odoc_info.Class.inherited_class list -> unit
method generate_style_file : unit
method label : ?no_:bool -> Odoc_info.Name.t -> string
method latex_for_class_index :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_label :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_type_index :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_class_type_label :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_module_index :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_label :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_type_index :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_for_module_type_label :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_header :
Format.formatter -> Odoc_info.Module.t_module list -> unit
method latex_of_Block : Format.formatter -> Odoc_info.text -> unit
method latex_of_Bold : Format.formatter -> Odoc_info.text -> unit
method latex_of_Center : Format.formatter -> Odoc_info.text -> unit
method latex_of_Code : Format.formatter -> string -> unit
method latex_of_CodePre : Format.formatter -> string -> unit
method latex_of_Emphasize :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Enum :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Italic : Format.formatter -> Odoc_info.text -> unit
method latex_of_Latex : Format.formatter -> string -> unit
method latex_of_Left : Format.formatter -> Odoc_info.text -> unit
method latex_of_Link :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_List :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Newline : Format.formatter -> unit
method latex_of_Raw : Format.formatter -> string -> unit
method latex_of_Ref :
Format.formatter ->
Odoc_info.Name.t ->
Odoc_info.ref_kind option -> Odoc_info.text option -> unit
method latex_of_Right : Format.formatter -> Odoc_info.text -> unit
method latex_of_Subscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Superscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Target :
Format.formatter -> target:string -> code:string -> unit
method latex_of_Title :
Format.formatter ->
int -> Odoc_info.Name.t option -> Odoc_info.text -> unit
method latex_of_Verbatim : Format.formatter -> string -> unit
method latex_of_attribute :
Format.formatter -> Odoc_info.Value.t_attribute -> unit
method latex_of_class :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_of_class_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_element -> unit
method latex_of_class_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_kind -> unit
method latex_of_class_parameter_list :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit
method latex_of_class_type :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_of_class_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_type_kind -> unit
method latex_of_cstr_args :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.constructor_args * Types.type_expr option ->
Odoc_info.text_element list
method latex_of_custom_text :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_exception :
Format.formatter -> Odoc_info.Exception.t_exception -> unit
method latex_of_included_module :
Format.formatter -> Odoc_info.Module.included_module -> unit
method latex_of_info :
Format.formatter -> ?block:bool -> Odoc_info.info option -> unit
method latex_of_method :
Format.formatter -> Odoc_info.Value.t_method -> unit
method latex_of_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_of_module_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit
method latex_of_module_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_kind -> unit
method latex_of_module_parameter :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit
method latex_of_module_type :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_of_module_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_type_kind -> unit
method latex_of_record :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.record_field list -> Odoc_info.text_element list
method latex_of_text : Format.formatter -> Odoc_info.text -> unit
method latex_of_text_element :
Format.formatter -> Odoc_info.text_element -> unit
method latex_of_type :
Format.formatter -> Odoc_info.Type.t_type -> unit
method latex_of_type_extension :
Odoc_info.Name.t ->
Format.formatter -> Odoc_info.Extension.t_type_extension -> unit
method latex_of_type_params :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit
method latex_of_value :
Format.formatter -> Odoc_info.Value.t_value -> unit
method make_label : string -> string
method make_ref : string -> string
method method_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method normal_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> string
method normal_class_type :
Odoc_info.Name.t -> Types.class_type -> string
method normal_class_type_param_list :
Odoc_info.Name.t -> Types.type_expr list -> string
method normal_cstr_args :
?par:bool ->
Odoc_info.Name.t -> Odoc_info.Type.constructor_args -> string
method normal_module_type :
?code:string -> Odoc_info.Name.t -> Types.module_type -> string
method normal_type : Odoc_info.Name.t -> Types.type_expr -> string
method normal_type_list :
?par:bool ->
Odoc_info.Name.t -> string -> Types.type_expr list -> string
method recfield_label : ?no_:bool -> Odoc_info.Name.t -> string
method relative_idents : Odoc_info.Name.t -> string -> string
method relative_module_idents : Odoc_info.Name.t -> string -> string
method section_style : int -> string -> string
method subst : (Str.regexp * string) list -> string -> string
method text_of_alerts :
Odoc_info.alert list -> Odoc_info.text_element list
method text_of_attribute :
Odoc_info.Value.t_attribute -> Odoc_info.text_element list
method text_of_author_list :
string list -> Odoc_info.text_element list
method text_of_before :
(string * Odoc_info.text) list -> Odoc_info.text_element list
method text_of_class_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_kind -> Odoc_info.text_element list
method text_of_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> Odoc_types.text
method text_of_class_type_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_type_kind -> Odoc_info.text_element list
method text_of_class_type_param_expr_list :
Odoc_info.Name.t ->
Types.type_expr list -> Odoc_info.text_element list
method text_of_custom :
(string * Odoc_info.text) list -> Odoc_info.text
method text_of_exception :
Odoc_info.Exception.t_exception -> Odoc_info.text_element list
method text_of_info :
?block:bool -> Odoc_info.info option -> Odoc_info.text
method text_of_method :
Odoc_info.Value.t_method -> Odoc_info.text_element list
method text_of_module_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_kind -> Odoc_info.text_element list
method text_of_module_parameter_list :
(Odoc_info.Module.module_parameter *
Odoc_info.text_element list option)
list -> Odoc_info.text_element list
method text_of_module_type :
Types.module_type -> Odoc_info.text_element list
method text_of_module_type_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_type_kind -> Odoc_info.text_element list
method text_of_parameter_description :
Odoc_info.Parameter.parameter -> Odoc_info.text
method text_of_parameter_list :
Odoc_info.Name.t ->
Odoc_info.Parameter.parameter list -> Odoc_info.text_element list
method text_of_raised_exceptions :
Odoc_info.raised_exception list -> Odoc_info.text_element list
method text_of_return_opt :
Odoc_info.text option -> Odoc_info.text_element list
method text_of_see : Odoc_info.see -> Odoc_info.text
method text_of_sees :
Odoc_info.see list -> Odoc_info.text_element list
method text_of_short_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_since_opt :
string option -> Odoc_info.text_element list
method text_of_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_type_expr_list :
Odoc_info.Name.t ->
string -> Types.type_expr list -> Odoc_info.text_element list
method text_of_value :
Odoc_info.Value.t_value -> Odoc_info.text_element list
method text_of_version_opt :
string option -> Odoc_info.text_element list
method type_label : ?no_:bool -> Odoc_info.Name.t -> string
method value_label : ?no_:bool -> Odoc_info.Name.t -> string
end
end
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/ocamldoc/odoc_latex.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.
************************************************************************
* Generation of LaTeX documentation. | , projet Cambium , INRIA Paris
Copyright 2022 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
val separate_files : bool ref
val latex_titles : (int * string) list ref
val latex_value_prefix : string ref
val latex_type_prefix : string ref
val latex_type_elt_prefix : string ref
val latex_extension_prefix : string ref
val latex_exception_prefix : string ref
val latex_module_prefix : string ref
val latex_module_type_prefix : string ref
val latex_class_prefix : string ref
val latex_class_type_prefix : string ref
val latex_attribute_prefix : string ref
val latex_method_prefix : string ref
module Generator :
sig
class latex :
object
val subst_strings : (Str.regexp * string) list
val subst_strings_code : (Str.regexp * string) list
val subst_strings_simple : (Str.regexp * string) list
val mutable tag_functions :
(string * (Odoc_info.text -> Odoc_info.text)) list
method attribute_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method const_label : ?no_:bool -> Odoc_info.Name.t -> string
method entry_comment :
Format.formatter * (unit -> string) ->
Odoc_info.info option -> Odoc_info.text_element list
method escape : string -> string
method escape_code : string -> string
method escape_simple : string -> string
method exception_label : ?no_:bool -> Odoc_info.Name.t -> string
method extension_label : ?no_:bool -> Odoc_info.Name.t -> string
method first_and_rest_of_info :
Odoc_info.info option -> Odoc_info.text * Odoc_info.text
method generate : Odoc_info.Module.t_module list -> unit
method generate_class_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class -> unit
method generate_class_type_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method generate_for_top_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method generate_inheritance_info :
Format.formatter -> Odoc_info.Class.inherited_class list -> unit
method generate_style_file : unit
method label : ?no_:bool -> Odoc_info.Name.t -> string
method latex_for_class_index :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_label :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_type_index :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_class_type_label :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_module_index :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_label :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_type_index :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_for_module_type_label :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_header :
Format.formatter -> Odoc_info.Module.t_module list -> unit
method latex_of_Block : Format.formatter -> Odoc_info.text -> unit
method latex_of_Bold : Format.formatter -> Odoc_info.text -> unit
method latex_of_Center : Format.formatter -> Odoc_info.text -> unit
method latex_of_Code : Format.formatter -> string -> unit
method latex_of_CodePre : Format.formatter -> string -> unit
method latex_of_Emphasize :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Enum :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Italic : Format.formatter -> Odoc_info.text -> unit
method latex_of_Latex : Format.formatter -> string -> unit
method latex_of_Left : Format.formatter -> Odoc_info.text -> unit
method latex_of_Link :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_List :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Newline : Format.formatter -> unit
method latex_of_Raw : Format.formatter -> string -> unit
method latex_of_Ref :
Format.formatter ->
Odoc_info.Name.t ->
Odoc_info.ref_kind option -> Odoc_info.text option -> unit
method latex_of_Right : Format.formatter -> Odoc_info.text -> unit
method latex_of_Subscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Superscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Target :
Format.formatter -> target:string -> code:string -> unit
method latex_of_Title :
Format.formatter ->
int -> Odoc_info.Name.t option -> Odoc_info.text -> unit
method latex_of_Verbatim : Format.formatter -> string -> unit
method latex_of_attribute :
Format.formatter -> Odoc_info.Value.t_attribute -> unit
method latex_of_class :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_of_class_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_element -> unit
method latex_of_class_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_kind -> unit
method latex_of_class_parameter_list :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit
method latex_of_class_type :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_of_class_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_type_kind -> unit
method latex_of_cstr_args :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.constructor_args * Types.type_expr option ->
Odoc_info.text_element list
method latex_of_custom_text :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_exception :
Format.formatter -> Odoc_info.Exception.t_exception -> unit
method latex_of_included_module :
Format.formatter -> Odoc_info.Module.included_module -> unit
method latex_of_info :
Format.formatter -> ?block:bool -> Odoc_info.info option -> unit
method latex_of_method :
Format.formatter -> Odoc_info.Value.t_method -> unit
method latex_of_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_of_module_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit
method latex_of_module_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_kind -> unit
method latex_of_module_parameter :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit
method latex_of_module_type :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_of_module_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_type_kind -> unit
method latex_of_record :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.record_field list -> Odoc_info.text_element list
method latex_of_text : Format.formatter -> Odoc_info.text -> unit
method latex_of_text_element :
Format.formatter -> Odoc_info.text_element -> unit
method latex_of_type :
Format.formatter -> Odoc_info.Type.t_type -> unit
method latex_of_type_extension :
Odoc_info.Name.t ->
Format.formatter -> Odoc_info.Extension.t_type_extension -> unit
method latex_of_type_params :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit
method latex_of_value :
Format.formatter -> Odoc_info.Value.t_value -> unit
method make_label : string -> string
method make_ref : string -> string
method method_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method normal_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> string
method normal_class_type :
Odoc_info.Name.t -> Types.class_type -> string
method normal_class_type_param_list :
Odoc_info.Name.t -> Types.type_expr list -> string
method normal_cstr_args :
?par:bool ->
Odoc_info.Name.t -> Odoc_info.Type.constructor_args -> string
method normal_module_type :
?code:string -> Odoc_info.Name.t -> Types.module_type -> string
method normal_type : Odoc_info.Name.t -> Types.type_expr -> string
method normal_type_list :
?par:bool ->
Odoc_info.Name.t -> string -> Types.type_expr list -> string
method recfield_label : ?no_:bool -> Odoc_info.Name.t -> string
method relative_idents : Odoc_info.Name.t -> string -> string
method relative_module_idents : Odoc_info.Name.t -> string -> string
method section_style : int -> string -> string
method subst : (Str.regexp * string) list -> string -> string
method text_of_alerts :
Odoc_info.alert list -> Odoc_info.text_element list
method text_of_attribute :
Odoc_info.Value.t_attribute -> Odoc_info.text_element list
method text_of_author_list :
string list -> Odoc_info.text_element list
method text_of_before :
(string * Odoc_info.text) list -> Odoc_info.text_element list
method text_of_class_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_kind -> Odoc_info.text_element list
method text_of_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> Odoc_types.text
method text_of_class_type_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_type_kind -> Odoc_info.text_element list
method text_of_class_type_param_expr_list :
Odoc_info.Name.t ->
Types.type_expr list -> Odoc_info.text_element list
method text_of_custom :
(string * Odoc_info.text) list -> Odoc_info.text
method text_of_exception :
Odoc_info.Exception.t_exception -> Odoc_info.text_element list
method text_of_info :
?block:bool -> Odoc_info.info option -> Odoc_info.text
method text_of_method :
Odoc_info.Value.t_method -> Odoc_info.text_element list
method text_of_module_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_kind -> Odoc_info.text_element list
method text_of_module_parameter_list :
(Odoc_info.Module.module_parameter *
Odoc_info.text_element list option)
list -> Odoc_info.text_element list
method text_of_module_type :
Types.module_type -> Odoc_info.text_element list
method text_of_module_type_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_type_kind -> Odoc_info.text_element list
method text_of_parameter_description :
Odoc_info.Parameter.parameter -> Odoc_info.text
method text_of_parameter_list :
Odoc_info.Name.t ->
Odoc_info.Parameter.parameter list -> Odoc_info.text_element list
method text_of_raised_exceptions :
Odoc_info.raised_exception list -> Odoc_info.text_element list
method text_of_return_opt :
Odoc_info.text option -> Odoc_info.text_element list
method text_of_see : Odoc_info.see -> Odoc_info.text
method text_of_sees :
Odoc_info.see list -> Odoc_info.text_element list
method text_of_short_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_since_opt :
string option -> Odoc_info.text_element list
method text_of_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_type_expr_list :
Odoc_info.Name.t ->
string -> Types.type_expr list -> Odoc_info.text_element list
method text_of_value :
Odoc_info.Value.t_value -> Odoc_info.text_element list
method text_of_version_opt :
string option -> Odoc_info.text_element list
method type_label : ?no_:bool -> Odoc_info.Name.t -> string
method value_label : ?no_:bool -> Odoc_info.Name.t -> string
end
end
module type Latex_generator =
sig
class latex :
object
val subst_strings : (Str.regexp * string) list
val subst_strings_code : (Str.regexp * string) list
val subst_strings_simple : (Str.regexp * string) list
val mutable tag_functions :
(string * (Odoc_info.text -> Odoc_info.text)) list
method attribute_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_label : ?no_:bool -> Odoc_info.Name.t -> string
method class_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method const_label : ?no_:bool -> Odoc_info.Name.t -> string
method entry_comment :
Format.formatter * (unit -> string) ->
Odoc_info.info option -> Odoc_info.text_element list
method escape : string -> string
method escape_code : string -> string
method escape_simple : string -> string
method exception_label : ?no_:bool -> Odoc_info.Name.t -> string
method extension_label : ?no_:bool -> Odoc_info.Name.t -> string
method first_and_rest_of_info :
Odoc_info.info option -> Odoc_info.text * Odoc_info.text
method generate : Odoc_info.Module.t_module list -> unit
method generate_class_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class -> unit
method generate_class_type_inheritance_info :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method generate_for_top_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method generate_inheritance_info :
Format.formatter -> Odoc_info.Class.inherited_class list -> unit
method generate_style_file : unit
method label : ?no_:bool -> Odoc_info.Name.t -> string
method latex_for_class_index :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_label :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_for_class_type_index :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_class_type_label :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_for_module_index :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_label :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_for_module_type_index :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_for_module_type_label :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_header :
Format.formatter -> Odoc_info.Module.t_module list -> unit
method latex_of_Block : Format.formatter -> Odoc_info.text -> unit
method latex_of_Bold : Format.formatter -> Odoc_info.text -> unit
method latex_of_Center : Format.formatter -> Odoc_info.text -> unit
method latex_of_Code : Format.formatter -> string -> unit
method latex_of_CodePre : Format.formatter -> string -> unit
method latex_of_Emphasize :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Enum :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Italic : Format.formatter -> Odoc_info.text -> unit
method latex_of_Latex : Format.formatter -> string -> unit
method latex_of_Left : Format.formatter -> Odoc_info.text -> unit
method latex_of_Link :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_List :
Format.formatter -> Odoc_info.text list -> unit
method latex_of_Newline : Format.formatter -> unit
method latex_of_Raw : Format.formatter -> string -> unit
method latex_of_Ref :
Format.formatter ->
Odoc_info.Name.t ->
Odoc_info.ref_kind option -> Odoc_info.text option -> unit
method latex_of_Right : Format.formatter -> Odoc_info.text -> unit
method latex_of_Subscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Superscript :
Format.formatter -> Odoc_info.text -> unit
method latex_of_Target :
Format.formatter -> target:string -> code:string -> unit
method latex_of_Title :
Format.formatter ->
int -> Odoc_info.Name.t option -> Odoc_info.text -> unit
method latex_of_Verbatim : Format.formatter -> string -> unit
method latex_of_attribute :
Format.formatter -> Odoc_info.Value.t_attribute -> unit
method latex_of_class :
Format.formatter -> Odoc_info.Class.t_class -> unit
method latex_of_class_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_element -> unit
method latex_of_class_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_kind -> unit
method latex_of_class_parameter_list :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.t_class -> unit
method latex_of_class_type :
Format.formatter -> Odoc_info.Class.t_class_type -> unit
method latex_of_class_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Class.class_type_kind -> unit
method latex_of_cstr_args :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.constructor_args * Types.type_expr option ->
Odoc_info.text_element list
method latex_of_custom_text :
Format.formatter -> string -> Odoc_info.text -> unit
method latex_of_exception :
Format.formatter -> Odoc_info.Exception.t_exception -> unit
method latex_of_included_module :
Format.formatter -> Odoc_info.Module.included_module -> unit
method latex_of_info :
Format.formatter -> ?block:bool -> Odoc_info.info option -> unit
method latex_of_method :
Format.formatter -> Odoc_info.Value.t_method -> unit
method latex_of_module :
Format.formatter -> Odoc_info.Module.t_module -> unit
method latex_of_module_element :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_element -> unit
method latex_of_module_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_kind -> unit
method latex_of_module_parameter :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_parameter -> unit
method latex_of_module_type :
Format.formatter -> Odoc_info.Module.t_module_type -> unit
method latex_of_module_type_kind :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Module.module_type_kind -> unit
method latex_of_record :
Format.formatter * (unit -> string) ->
Odoc_info.Name.t ->
Odoc_info.Type.record_field list -> Odoc_info.text_element list
method latex_of_text : Format.formatter -> Odoc_info.text -> unit
method latex_of_text_element :
Format.formatter -> Odoc_info.text_element -> unit
method latex_of_type :
Format.formatter -> Odoc_info.Type.t_type -> unit
method latex_of_type_extension :
Odoc_info.Name.t ->
Format.formatter -> Odoc_info.Extension.t_type_extension -> unit
method latex_of_type_params :
Format.formatter ->
Odoc_info.Name.t -> Odoc_info.Type.t_type -> unit
method latex_of_value :
Format.formatter -> Odoc_info.Value.t_value -> unit
method make_label : string -> string
method make_ref : string -> string
method method_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_label : ?no_:bool -> Odoc_info.Name.t -> string
method module_type_label : ?no_:bool -> Odoc_info.Name.t -> string
method normal_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> string
method normal_class_type :
Odoc_info.Name.t -> Types.class_type -> string
method normal_class_type_param_list :
Odoc_info.Name.t -> Types.type_expr list -> string
method normal_cstr_args :
?par:bool ->
Odoc_info.Name.t -> Odoc_info.Type.constructor_args -> string
method normal_module_type :
?code:string -> Odoc_info.Name.t -> Types.module_type -> string
method normal_type : Odoc_info.Name.t -> Types.type_expr -> string
method normal_type_list :
?par:bool ->
Odoc_info.Name.t -> string -> Types.type_expr list -> string
method recfield_label : ?no_:bool -> Odoc_info.Name.t -> string
method relative_idents : Odoc_info.Name.t -> string -> string
method relative_module_idents : Odoc_info.Name.t -> string -> string
method section_style : int -> string -> string
method subst : (Str.regexp * string) list -> string -> string
method text_of_alerts :
Odoc_info.alert list -> Odoc_info.text_element list
method text_of_attribute :
Odoc_info.Value.t_attribute -> Odoc_info.text_element list
method text_of_author_list :
string list -> Odoc_info.text_element list
method text_of_before :
(string * Odoc_info.text) list -> Odoc_info.text_element list
method text_of_class_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_kind -> Odoc_info.text_element list
method text_of_class_params :
Odoc_info.Name.t -> Odoc_info.Class.t_class -> Odoc_types.text
method text_of_class_type_kind :
Odoc_info.Name.t ->
Odoc_info.Class.class_type_kind -> Odoc_info.text_element list
method text_of_class_type_param_expr_list :
Odoc_info.Name.t ->
Types.type_expr list -> Odoc_info.text_element list
method text_of_custom :
(string * Odoc_info.text) list -> Odoc_info.text
method text_of_exception :
Odoc_info.Exception.t_exception -> Odoc_info.text_element list
method text_of_info :
?block:bool -> Odoc_info.info option -> Odoc_info.text
method text_of_method :
Odoc_info.Value.t_method -> Odoc_info.text_element list
method text_of_module_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_kind -> Odoc_info.text_element list
method text_of_module_parameter_list :
(Odoc_info.Module.module_parameter *
Odoc_info.text_element list option)
list -> Odoc_info.text_element list
method text_of_module_type :
Types.module_type -> Odoc_info.text_element list
method text_of_module_type_kind :
?with_def_syntax:bool ->
Odoc_info.Module.module_type_kind -> Odoc_info.text_element list
method text_of_parameter_description :
Odoc_info.Parameter.parameter -> Odoc_info.text
method text_of_parameter_list :
Odoc_info.Name.t ->
Odoc_info.Parameter.parameter list -> Odoc_info.text_element list
method text_of_raised_exceptions :
Odoc_info.raised_exception list -> Odoc_info.text_element list
method text_of_return_opt :
Odoc_info.text option -> Odoc_info.text_element list
method text_of_see : Odoc_info.see -> Odoc_info.text
method text_of_sees :
Odoc_info.see list -> Odoc_info.text_element list
method text_of_short_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_since_opt :
string option -> Odoc_info.text_element list
method text_of_type_expr :
Odoc_info.Name.t -> Types.type_expr -> Odoc_info.text_element list
method text_of_type_expr_list :
Odoc_info.Name.t ->
string -> Types.type_expr list -> Odoc_info.text_element list
method text_of_value :
Odoc_info.Value.t_value -> Odoc_info.text_element list
method text_of_version_opt :
string option -> Odoc_info.text_element list
method type_label : ?no_:bool -> Odoc_info.Name.t -> string
method value_label : ?no_:bool -> Odoc_info.Name.t -> string
end
end
|
d97e72768a62088cc12537885c232faf9d09d627b99e111993b0237b6e1e81d8 | mario-goulart/spock | driver.scm | ;;;; driver.scm - compiler-invocation
(define dropped '())
(define defined '())
(define assigned '())
(define referenced '())
(define undefined '())
(define used-sections '())
(define default-xref-mode #f)
(define (spock-help)
(display "(spock OPTION | FILENAME-OR-PORT ...)\n\n")
(display " Available options:\n\n")
(display " 'source show source forms\n")
(display " 'expand show forms after macro-expansion\n")
(display " 'canonicalized show forms after canonicalization\n")
(display " 'optimized show forms after optimization\n")
(display " 'cps show forms after CPS-conversion\n")
(display " 'strict enable strict mode\n")
(display " 'optimize enable optimizations\n")
(display " 'block enable block-compilation\n")
(display " 'library-path [DIR] add DIR to library path or return library path\n")
(display " 'namespace VAR put globals into module\n")
(display " 'xref show cross-reference\n")
(display " 'runtime include runtime-system in generated code\n")
(display " 'library compile runtime library\n")
(display " 'seal wrap toplevel definitions into local scope\n")
(display " 'debug enable debug-mode\n")
(display " 'usage PROC invoke PROC on usage-errors\n")
(display " 'fail PROC invoke PROC on compiler-errors\n")
(display " 'import FILENAME expand FILENAME\n")
(display " 'environment STORE provide syntactic environment\n")
(display " 'debug-syntax show debug-output during expansion\n")
(display " 'verbose show diagnostic messages\n")
(display " 'prepare just prepare state without compiling\n")
(display " 'code EXP code to be compiled instead of file\n")
(display " 'bind FILENAME generate bindings from specifications\n")
(display " 'output-file FILENAME specify output-file\n"))
(define (spock . args)
(let ((output-file #f)
(include-runtime #f)
(extract-library #f)
(seal-toplevel #f)
(files '())
(mstore #f)
(code #f)
(prepare #f)
(optimize-mode #f)
(mstore-given #f)
(strict-mode #f)
(block-mode #f)
(debug-mode #f)
(xref-mode default-xref-mode)
(verbose-mode #f)
(debug-syntax #f)
(bindings '())
(fail error)
(namespace #f)
(imports '())
(show '()))
(define (usage opts)
(fail "unrecgnized option or missing argument" opts))
(define (sexpand exp dbg)
(match-let (((exp . store)
(expand-syntax exp fail mstore (and dbg debug-syntax))))
(set! mstore store)
exp))
(define (compile-files state files show)
(let ((forms
(or code
`(begin
,@(map
read-forms
(note #f state files "reading source"))))))
(if (memq 'source show)
(pp forms)
(let ((forms
(sexpand
(note #f state forms "expanding syntax")
#t)))
(if (memq 'expand show)
(pp forms)
(let ((forms
(canonicalize
forms
(note #f state state "canonicalizing"))))
(cond ((memq 'canonicalized show)
(pp forms))
((and block-mode (report-undefined)))
((memq 'xref show)
(xref #t (note #f state #t "cross-referencing")))
(else
(let ((forms (if optimize-mode
(optimize
forms
(note #f state state "optimizing"))
forms)))
(if (and optimize-mode (memq 'optimized show))
(pp forms)
;;XXX if "-runtime" + "-library":
;; xref and add compiled library.scm
;; of used definitions (sort sections topologically
;; to determine order)
(let ((toplambdas
(cps
(note #f state forms "performing CPS conversion"))))
(if (memq 'cps show)
(for-each pp toplambdas)
(begin
(note
#f state
(generate-header state)
"generating code")
(generate-code toplambdas state)
(generate-trailer state)))
mstore)))))))))))
(call-with-current-continuation
(lambda (return)
(let loop ((args args))
(match args
(() (let ((files (reverse files))
(state `((strict . ,strict-mode)
(debug . ,debug-mode)
(xref . ,xref-mode)
(seal . ,seal-toplevel)
(block . ,block-mode)
(optimize . ,optimize-mode)
(verbose . ,verbose-mode)
(fail . ,fail)
(runtime . ,include-runtime)
(library-path . ,library-path)
(namespace . ,namespace))))
(when (and (not mstore-given) extract-library)
(set! files
(cons
(read-library state "library.scm" (lambda (x) x))
files)))
(when (and (not prepare) (null? files) (not code) (null? bindings))
(fail "nothing to compile"))
(when (not mstore-given)
(sexpand
(let ((m (cond (strict-mode '(default strict))
(debug-mode '(default debug))
(else '(default)))))
`(define-syntax define-library-section
(letrec-syntax
((walk
(syntax-rules ,m
((_ ()) (%void))
,@(map (lambda (m)
`((_ ((,m def ...) . more))
(begin def ...)))
m)
((_ (clause . more))
(walk more)))))
(syntax-rules ()
((_ sec clause ...)
(begin
(walk (clause ...))))))))
#f)
(let ((features '(spock alexpander srfi-0 srfi-46)))
(when debug-mode (set! features (cons 'debug features)))
(when strict-mode (set! features (cons 'strict features)))
;;XXX do this in a modular and extensible manner
(sexpand
`(define-syntax cond-expand
(syntax-rules (and or not else ,@features)
((cond-expand) (syntax-error "no matching `cond-expand' clause"))
,@(map (lambda (f)
`((cond-expand (,f body ...) . more-clauses)
(begin body ...)))
features)
((cond-expand (else body ...)) (begin body ...))
((cond-expand ((and) body ...) more-clauses ...) (begin body ...))
((cond-expand ((and req1 req2 ...) body ...) more-clauses ...)
(cond-expand
(req1 (cond-expand
((and req2 ...) body ...)
more-clauses ...))
more-clauses ...))
((cond-expand ((or) body ...) more-clauses ...)
(cond-expand more-clauses ...))
((cond-expand ((or req1 req2 ...) body ...) more-clauses ...)
(cond-expand
(req1 (begin body ...))
(else
(cond-expand
((or req2 ...) body ...)
more-clauses ...))))
((cond-expand ((not req) body ...) more-clauses ...)
(cond-expand
(req (cond-expand more-clauses ...))
(else body ...)))
((cond-expand (feature-id body ...) more-clauses ...)
(cond-expand more-clauses ...))))
#f))
(sexpand (read-library state "syntax.scm") #f)
(sexpand (read-library state "library.scm") #f))
(for-each
(lambda (bound)
(let ((bs (parse-bindings (read-contents bound))))
(if (and (null? files) (not code))
(pp bs)
(sexpand bs #t))
bs))
(reverse bindings))
(for-each
(lambda (file) (sexpand (read-forms file) #t))
(reverse imports))
(cond (prepare mstore)
(output-file
(with-output-to-file output-file
(cut compile-files state files show)))
((and (pair? bindings) (not code) (null? files)) #f)
(else (compile-files state files show)))))
(('help . _)
(spock-help))
(('output-file out . more)
(set! output-file out)
(loop more))
(('source . more)
(set! show (cons 'source show))
(loop more))
(('expand . more)
(set! show (cons 'expand show))
(loop more))
(('canonicalized . more)
(set! show (cons 'canonicalized show))
(loop more))
(('optimize . more)
(set! optimize-mode #t)
(loop more))
(('optimized . more)
(set! optimize-mode #t)
(set! show (cons 'optimized show))
(loop more))
(('cps . more)
(set! show (cons 'cps show))
(loop more))
(('strict . more)
(set! strict-mode #t)
(loop more))
(('block . more)
(set! block-mode #t)
(set! xref-mode #t)
(loop more))
(('import filename . more)
(set! imports (cons filename imports))
(loop more))
(('bind arg . more)
(set! bindings (cons arg bindings))
(loop more))
(('library-path)
(return library-path))
(('library-path dir . more)
(set! library-path (cons dir library-path))
(loop more))
(('namespace ns . more)
(set! namespace ns)
(loop more))
(('xref . more)
(set! show (cons 'xref show))
(set! xref-mode #t)
(loop more))
(('runtime . more)
(set! include-runtime #t)
(set! extract-library #t)
(loop more))
(('library . more)
(set! extract-library #t)
(loop more))
(('seal . more)
(set! seal-toplevel #t)
(loop more))
(('fail proc . more)
(set! fail proc)
(loop more))
(('usage proc . more)
(set! usage proc)
(loop more))
(('prepare . more)
(set! prepare #t)
(loop more))
(('debug . more)
(set! debug-mode #t)
(loop more))
(('environment store . more)
(set! mstore store)
(set! mstore-given #t)
(loop more))
(('verbose . more)
(set! verbose-mode #t)
(loop more))
(('debug-syntax . more)
(set! debug-syntax #t)
(loop more))
(('code exp . more)
(set! code exp)
(loop more))
(((or (? string? file) (? input-port? file)) . more)
(set! files (cons file files))
(loop more))
((opts ...) (usage))))))))
| null | https://raw.githubusercontent.com/mario-goulart/spock/b88f08f8bc689babc433ad8288559ce5c28c52d5/driver.scm | scheme | driver.scm - compiler-invocation
XXX if "-runtime" + "-library":
xref and add compiled library.scm
of used definitions (sort sections topologically
to determine order)
XXX do this in a modular and extensible manner |
(define dropped '())
(define defined '())
(define assigned '())
(define referenced '())
(define undefined '())
(define used-sections '())
(define default-xref-mode #f)
(define (spock-help)
(display "(spock OPTION | FILENAME-OR-PORT ...)\n\n")
(display " Available options:\n\n")
(display " 'source show source forms\n")
(display " 'expand show forms after macro-expansion\n")
(display " 'canonicalized show forms after canonicalization\n")
(display " 'optimized show forms after optimization\n")
(display " 'cps show forms after CPS-conversion\n")
(display " 'strict enable strict mode\n")
(display " 'optimize enable optimizations\n")
(display " 'block enable block-compilation\n")
(display " 'library-path [DIR] add DIR to library path or return library path\n")
(display " 'namespace VAR put globals into module\n")
(display " 'xref show cross-reference\n")
(display " 'runtime include runtime-system in generated code\n")
(display " 'library compile runtime library\n")
(display " 'seal wrap toplevel definitions into local scope\n")
(display " 'debug enable debug-mode\n")
(display " 'usage PROC invoke PROC on usage-errors\n")
(display " 'fail PROC invoke PROC on compiler-errors\n")
(display " 'import FILENAME expand FILENAME\n")
(display " 'environment STORE provide syntactic environment\n")
(display " 'debug-syntax show debug-output during expansion\n")
(display " 'verbose show diagnostic messages\n")
(display " 'prepare just prepare state without compiling\n")
(display " 'code EXP code to be compiled instead of file\n")
(display " 'bind FILENAME generate bindings from specifications\n")
(display " 'output-file FILENAME specify output-file\n"))
(define (spock . args)
(let ((output-file #f)
(include-runtime #f)
(extract-library #f)
(seal-toplevel #f)
(files '())
(mstore #f)
(code #f)
(prepare #f)
(optimize-mode #f)
(mstore-given #f)
(strict-mode #f)
(block-mode #f)
(debug-mode #f)
(xref-mode default-xref-mode)
(verbose-mode #f)
(debug-syntax #f)
(bindings '())
(fail error)
(namespace #f)
(imports '())
(show '()))
(define (usage opts)
(fail "unrecgnized option or missing argument" opts))
(define (sexpand exp dbg)
(match-let (((exp . store)
(expand-syntax exp fail mstore (and dbg debug-syntax))))
(set! mstore store)
exp))
(define (compile-files state files show)
(let ((forms
(or code
`(begin
,@(map
read-forms
(note #f state files "reading source"))))))
(if (memq 'source show)
(pp forms)
(let ((forms
(sexpand
(note #f state forms "expanding syntax")
#t)))
(if (memq 'expand show)
(pp forms)
(let ((forms
(canonicalize
forms
(note #f state state "canonicalizing"))))
(cond ((memq 'canonicalized show)
(pp forms))
((and block-mode (report-undefined)))
((memq 'xref show)
(xref #t (note #f state #t "cross-referencing")))
(else
(let ((forms (if optimize-mode
(optimize
forms
(note #f state state "optimizing"))
forms)))
(if (and optimize-mode (memq 'optimized show))
(pp forms)
(let ((toplambdas
(cps
(note #f state forms "performing CPS conversion"))))
(if (memq 'cps show)
(for-each pp toplambdas)
(begin
(note
#f state
(generate-header state)
"generating code")
(generate-code toplambdas state)
(generate-trailer state)))
mstore)))))))))))
(call-with-current-continuation
(lambda (return)
(let loop ((args args))
(match args
(() (let ((files (reverse files))
(state `((strict . ,strict-mode)
(debug . ,debug-mode)
(xref . ,xref-mode)
(seal . ,seal-toplevel)
(block . ,block-mode)
(optimize . ,optimize-mode)
(verbose . ,verbose-mode)
(fail . ,fail)
(runtime . ,include-runtime)
(library-path . ,library-path)
(namespace . ,namespace))))
(when (and (not mstore-given) extract-library)
(set! files
(cons
(read-library state "library.scm" (lambda (x) x))
files)))
(when (and (not prepare) (null? files) (not code) (null? bindings))
(fail "nothing to compile"))
(when (not mstore-given)
(sexpand
(let ((m (cond (strict-mode '(default strict))
(debug-mode '(default debug))
(else '(default)))))
`(define-syntax define-library-section
(letrec-syntax
((walk
(syntax-rules ,m
((_ ()) (%void))
,@(map (lambda (m)
`((_ ((,m def ...) . more))
(begin def ...)))
m)
((_ (clause . more))
(walk more)))))
(syntax-rules ()
((_ sec clause ...)
(begin
(walk (clause ...))))))))
#f)
(let ((features '(spock alexpander srfi-0 srfi-46)))
(when debug-mode (set! features (cons 'debug features)))
(when strict-mode (set! features (cons 'strict features)))
(sexpand
`(define-syntax cond-expand
(syntax-rules (and or not else ,@features)
((cond-expand) (syntax-error "no matching `cond-expand' clause"))
,@(map (lambda (f)
`((cond-expand (,f body ...) . more-clauses)
(begin body ...)))
features)
((cond-expand (else body ...)) (begin body ...))
((cond-expand ((and) body ...) more-clauses ...) (begin body ...))
((cond-expand ((and req1 req2 ...) body ...) more-clauses ...)
(cond-expand
(req1 (cond-expand
((and req2 ...) body ...)
more-clauses ...))
more-clauses ...))
((cond-expand ((or) body ...) more-clauses ...)
(cond-expand more-clauses ...))
((cond-expand ((or req1 req2 ...) body ...) more-clauses ...)
(cond-expand
(req1 (begin body ...))
(else
(cond-expand
((or req2 ...) body ...)
more-clauses ...))))
((cond-expand ((not req) body ...) more-clauses ...)
(cond-expand
(req (cond-expand more-clauses ...))
(else body ...)))
((cond-expand (feature-id body ...) more-clauses ...)
(cond-expand more-clauses ...))))
#f))
(sexpand (read-library state "syntax.scm") #f)
(sexpand (read-library state "library.scm") #f))
(for-each
(lambda (bound)
(let ((bs (parse-bindings (read-contents bound))))
(if (and (null? files) (not code))
(pp bs)
(sexpand bs #t))
bs))
(reverse bindings))
(for-each
(lambda (file) (sexpand (read-forms file) #t))
(reverse imports))
(cond (prepare mstore)
(output-file
(with-output-to-file output-file
(cut compile-files state files show)))
((and (pair? bindings) (not code) (null? files)) #f)
(else (compile-files state files show)))))
(('help . _)
(spock-help))
(('output-file out . more)
(set! output-file out)
(loop more))
(('source . more)
(set! show (cons 'source show))
(loop more))
(('expand . more)
(set! show (cons 'expand show))
(loop more))
(('canonicalized . more)
(set! show (cons 'canonicalized show))
(loop more))
(('optimize . more)
(set! optimize-mode #t)
(loop more))
(('optimized . more)
(set! optimize-mode #t)
(set! show (cons 'optimized show))
(loop more))
(('cps . more)
(set! show (cons 'cps show))
(loop more))
(('strict . more)
(set! strict-mode #t)
(loop more))
(('block . more)
(set! block-mode #t)
(set! xref-mode #t)
(loop more))
(('import filename . more)
(set! imports (cons filename imports))
(loop more))
(('bind arg . more)
(set! bindings (cons arg bindings))
(loop more))
(('library-path)
(return library-path))
(('library-path dir . more)
(set! library-path (cons dir library-path))
(loop more))
(('namespace ns . more)
(set! namespace ns)
(loop more))
(('xref . more)
(set! show (cons 'xref show))
(set! xref-mode #t)
(loop more))
(('runtime . more)
(set! include-runtime #t)
(set! extract-library #t)
(loop more))
(('library . more)
(set! extract-library #t)
(loop more))
(('seal . more)
(set! seal-toplevel #t)
(loop more))
(('fail proc . more)
(set! fail proc)
(loop more))
(('usage proc . more)
(set! usage proc)
(loop more))
(('prepare . more)
(set! prepare #t)
(loop more))
(('debug . more)
(set! debug-mode #t)
(loop more))
(('environment store . more)
(set! mstore store)
(set! mstore-given #t)
(loop more))
(('verbose . more)
(set! verbose-mode #t)
(loop more))
(('debug-syntax . more)
(set! debug-syntax #t)
(loop more))
(('code exp . more)
(set! code exp)
(loop more))
(((or (? string? file) (? input-port? file)) . more)
(set! files (cons file files))
(loop more))
((opts ...) (usage))))))))
|
f1124daafdbf4b421b52fa6647184e3d303355c022c8793ee778188bb1b31e45 | Twinside/FontyFruity | fontytest.hs | import Data.Maybe( fromJust )
import Data.Monoid( mempty )
import Control . ( forM _ )
import Data.Binary( decodeFile )
import qualified Data.Vector as V
import System.Environment( getArgs )
import Graphics.Text.TrueType
import Graphics.Text.TrueType.Internal
dumpFont :: Font -> IO ()
dumpFont font = do
putStrLn . show $ font
{ _fontGlyph = Nothing
, _fontTables = [(t, mempty) | (t, _) <- _fontTables font] }
V.mapM_ (putStrLn . show) . fromJust $ _fontGlyph font
dumpFontName :: FilePath -> IO ()
dumpFontName fontname = do
font <- loadFontFile fontname
case font of
Left err -> putStrLn err
Right font -> dumpFont font
main :: IO ()
main = do
args <- getArgs
o <- findFontOfFamily "Consolas" $ FontStyle False False
case o of
Nothing -> putStrLn "not found"
Just v -> putStrLn v
case args of
[] -> putStrLn "missing font filename"
(fontname:_) -> dumpFontName fontname
| null | https://raw.githubusercontent.com/Twinside/FontyFruity/636eeff6547478ba304cdd7b85ecaa24acc65062/test-src/fontytest.hs | haskell | import Data.Maybe( fromJust )
import Data.Monoid( mempty )
import Control . ( forM _ )
import Data.Binary( decodeFile )
import qualified Data.Vector as V
import System.Environment( getArgs )
import Graphics.Text.TrueType
import Graphics.Text.TrueType.Internal
dumpFont :: Font -> IO ()
dumpFont font = do
putStrLn . show $ font
{ _fontGlyph = Nothing
, _fontTables = [(t, mempty) | (t, _) <- _fontTables font] }
V.mapM_ (putStrLn . show) . fromJust $ _fontGlyph font
dumpFontName :: FilePath -> IO ()
dumpFontName fontname = do
font <- loadFontFile fontname
case font of
Left err -> putStrLn err
Right font -> dumpFont font
main :: IO ()
main = do
args <- getArgs
o <- findFontOfFamily "Consolas" $ FontStyle False False
case o of
Nothing -> putStrLn "not found"
Just v -> putStrLn v
case args of
[] -> putStrLn "missing font filename"
(fontname:_) -> dumpFontName fontname
| |
7650796d67cec61cef88fc888141d3ddfddcf86cc6a74509d13c8c44118926c3 | YoshikuniJujo/test_haskell | try-no-dynamic-dsc-sets.hs | # LANGUAGE QuasiQuotes #
# , LambdaCase , OverloadedStrings #
# LANGUAGE ScopedTypeVariables , RankNTypes , TypeApplications #
# LANGUAGE GADTs , TypeFamilies #
# LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleContexts , FlexibleInstances , UndecidableInstances #
{-# LANGUAGE PatternSynonyms, ViewPatterns #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE StandaloneDeriving #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Main where
import Foreign.Storable
import Data.Kind
import Data.Kind.Object
import Data.Default
import Data.Bits
import Data.Bits.Utils
import Data.List.Length
import Data.TypeLevel.Uncurry
import qualified Data.HeteroParList as HeteroParList
import Data.HeteroParList (pattern (:*), pattern (:**))
import Data.Word
import System.Environment
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Utils as V
import Shaderc.TH
import Shaderc.EnumAuto
import Gpu.Vulkan.Misc
import qualified Gpu.Vulkan as Vk
import qualified Gpu.Vulkan.Enum as Vk
import qualified Gpu.Vulkan.Instance as Vk.Inst
import qualified Gpu.Vulkan.PhysicalDevice as Vk.PhDvc
import qualified Gpu.Vulkan.PhysicalDevice.Struct as Vk.PhDvc
import qualified Gpu.Vulkan.Queue as Vk.Queue
import qualified Gpu.Vulkan.Queue.Enum as Vk.Queue
import qualified Gpu.Vulkan.QueueFamily as Vk.QFam
import qualified Gpu.Vulkan.QueueFamily.Middle as Vk.QFam
import qualified Gpu.Vulkan.Device as Vk.Dvc
import qualified Gpu.Vulkan.CommandPool as Vk.CmdPl
import qualified Gpu.Vulkan.Buffer.Enum as Vk.Bffr
import qualified Gpu.Vulkan.Memory.Enum as Vk.Mem
import qualified Gpu.Vulkan.Memory.Middle as Vk.Mem.M
import qualified Gpu.Vulkan.Descriptor as Vk.Dsc
import qualified Gpu.Vulkan.DescriptorPool as Vk.DscPool
import qualified Gpu.Vulkan.ShaderModule as Vk.ShaderMod
import qualified Gpu.Vulkan.Pipeline.Enum as Vk.Ppl
import qualified Gpu.Vulkan.Pipeline.Layout as Vk.Ppl.Lyt
import qualified Gpu.Vulkan.Pipeline.Layout.Type as Vk.Ppl.Lyt
import qualified Gpu.Vulkan.Pipeline.ShaderStage as Vk.Ppl.ShaderSt
import qualified Gpu.Vulkan.Pipeline.Compute as Vk.Ppl.Cmpt
import qualified Gpu.Vulkan.DescriptorSet as Vk.DscSet
import qualified Gpu.Vulkan.CommandBuffer as Vk.CmdBuf
import qualified Gpu.Vulkan.Command as Vk.Cmd
import qualified Gpu.Vulkan.Buffer as Vk.Bffr
import qualified Gpu.Vulkan.Memory.AllocateInfo as Vk.Dvc.Mem.Buffer
import qualified Gpu.Vulkan.Memory as Vk.Dvc.Mem.ImgBffr
import qualified Gpu.Vulkan.Memory.Kind as Vk.Dvc.Mem.ImgBffr.K
import qualified Gpu.Vulkan.DescriptorSetLayout as Vk.DscSetLyt
import qualified Gpu.Vulkan.DescriptorSetLayout.Type as Vk.DscSetLyt
import qualified Gpu.Vulkan.Khr as Vk.Khr
import qualified Gpu.Vulkan.PushConstant as Vk.PushConstant
main :: IO ()
main = do
args <- getArgs
case args of
[arg] -> do
(r1, r2, r3) <- crtDevice \phdvc qFam dvc mxX ->
let (da, db, dc) = mkData mxX in
Vk.DscSetLyt.create dvc dscSetLayoutInfo
nil nil \dslyt ->
prepDscSets arg phdvc dvc dslyt da db dc
$ calc dvc qFam dslyt mxX
print . take 20 $ unW1 <$> r1
print . take 20 $ unW2 <$> r2
print . take 20 $ unW3 <$> r3
_ -> error "bad args"
newtype W1 = W1 { unW1 :: Word32 } deriving (Show, Storable)
newtype W2 = W2 { unW2 :: Word32 } deriving (Show, Storable)
newtype W3 = W3 { unW3 :: Word32 } deriving (Show, Storable)
type ListW1 = List 256 W1 ""
type ListW2 = List 256 W2 ""
type ListW3 = List 256 W3 ""
crtDevice :: (forall sd .
Vk.PhDvc.P -> Vk.QFam.Index -> Vk.Dvc.D sd -> Word32 -> IO a) -> IO a
crtDevice f = Vk.Inst.create @() @() instInfo nil nil \inst -> do
phdvc <- head <$> Vk.PhDvc.enumerate inst
qf <- findQueueFamily phdvc Vk.Queue.ComputeBit
lmts <- Vk.PhDvc.propertiesLimits <$> Vk.PhDvc.getProperties phdvc
let mxX :. _ = Vk.PhDvc.limitsMaxComputeWorkGroupCount lmts
Vk.Dvc.create @() @'[()] phdvc (dvcInfo qf) nil nil $ \dvc ->
f phdvc qf dvc mxX
where
instInfo = def {
Vk.Inst.createInfoEnabledLayerNames =
[Vk.Khr.validationLayerName] }
dvcInfo qf = Vk.Dvc.CreateInfo {
Vk.Dvc.createInfoNext = Nothing,
Vk.Dvc.createInfoFlags = zeroBits,
Vk.Dvc.createInfoQueueCreateInfos = HeteroParList.Singleton $ queueInfo qf,
Vk.Dvc.createInfoEnabledLayerNames =
[Vk.Khr.validationLayerName],
Vk.Dvc.createInfoEnabledExtensionNames = [],
Vk.Dvc.createInfoEnabledFeatures = Nothing }
queueInfo qf = Vk.Dvc.QueueCreateInfo {
Vk.Dvc.queueCreateInfoNext = Nothing,
Vk.Dvc.queueCreateInfoFlags = zeroBits,
Vk.Dvc.queueCreateInfoQueueFamilyIndex = qf,
Vk.Dvc.queueCreateInfoQueuePriorities = [0] }
findQueueFamily :: Vk.PhDvc.P -> Vk.Queue.FlagBits -> IO Vk.QFam.Index
findQueueFamily phdvc qb = (<$> Vk.PhDvc.getQueueFamilyProperties phdvc)
$ fst . head . filter
((/= zeroBits) . (.&. qb) . Vk.QFam.propertiesQueueFlags . snd)
mkData :: Word32 -> (V.Vector W1, V.Vector W2, V.Vector W3)
mkData n = (
V.genericReplicate n $ W1 3,
V.fromList $ W2 <$> [1 .. n],
V.genericReplicate n $ W3 0 )
type DscSetLytLstW123 = '[
'Vk.DscSetLyt.Buffer '[ListW1, ListW2, ListW3],
'Vk.DscSetLyt.Buffer '[ Atom 256 Word32 'Nothing] ]
dscSetLayoutInfo :: Vk.DscSetLyt.CreateInfo () DscSetLytLstW123
dscSetLayoutInfo = Vk.DscSetLyt.CreateInfo {
Vk.DscSetLyt.createInfoNext = Nothing,
Vk.DscSetLyt.createInfoFlags = zeroBits,
Vk.DscSetLyt.createInfoBindings = bdng :** bdng :** HeteroParList.Nil }
where bdng = Vk.DscSetLyt.BindingBuffer {
Vk.DscSetLyt.bindingBufferDescriptorType =
Vk.Dsc.TypeStorageBuffer,
Vk.DscSetLyt.bindingBufferStageFlags =
Vk.ShaderStageComputeBit }
prepDscSets ::
String -> Vk.PhDvc.P -> Vk.Dvc.D sd -> Vk.DscSetLyt.L sl DscSetLytLstW123 ->
V.Vector W1 -> V.Vector W2 -> V.Vector W3 -> (forall s sm1 sm2 sm3 sb1 sb2 sb3 .
Vk.DscSet.S sd s '(sl, DscSetLytLstW123) ->
Vk.Dvc.Mem.ImgBffr.M sm1 '[ '(sb1, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm1 '[ListW1])] ->
Vk.Dvc.Mem.ImgBffr.M sm2 '[ '(sb2, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm2 '[ListW2])] ->
Vk.Dvc.Mem.ImgBffr.M sm3 '[ '(sb3, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm3 '[ListW3])] -> IO a) -> IO a
prepDscSets arg phdvc dvc dslyt da db dc f =
Vk.DscPool.create dvc dscPoolInfo nil nil \dp ->
Vk.DscSet.allocateSs dvc (dscSetInfo dp dslyt) >>= \(HeteroParList.Singleton ds) ->
storageBufferNew3 phdvc dvc da db dc \(ba, ma) (bb, mb) (bc, mc) ->
storageBufferNew3Objs @Word32
@(Atom 256 Word32 ('Just "x0"))
@(Atom 256 Word32 ('Just "x1"))
@(Atom 256 Word32 ('Just "x2"))
phdvc dvc 3 5 7 \bx mx -> case arg of
"0" -> do
Vk.DscSet.updateDs @_ @() dvc (
Vk.DscSet.Write_ (writeDscSet ds ba bb bc) :**
Vk.DscSet.Write_ (writeDscSet2 @"x0" ds bx) :**
HeteroParList.Nil
) []
f ds ma mb mc
"1" -> do
Vk.DscSet.updateDs @_ @() dvc (
Vk.DscSet.Write_ (writeDscSet ds ba bb bc) :**
Vk.DscSet.Write_ (writeDscSet2 @"x1" ds bx) :**
HeteroParList.Nil
) []
f ds ma mb mc
"2" -> do
Vk.DscSet.updateDs @_ @() dvc (
Vk.DscSet.Write_ (writeDscSet ds ba bb bc) :**
Vk.DscSet.Write_ (writeDscSet2 @"x2" ds bx) :**
HeteroParList.Nil
) []
f ds ma mb mc
_ -> error "bad arg"
dscPoolInfo :: Vk.DscPool.CreateInfo ()
dscPoolInfo = Vk.DscPool.CreateInfo {
Vk.DscPool.createInfoNext = Nothing,
Vk.DscPool.createInfoFlags = Vk.DscPool.CreateFreeDescriptorSetBit,
Vk.DscPool.createInfoMaxSets = 1,
Vk.DscPool.createInfoPoolSizes = [poolSize] }
where poolSize = Vk.DscPool.Size {
Vk.DscPool.sizeType = Vk.Dsc.TypeStorageBuffer,
Vk.DscPool.sizeDescriptorCount = 10 }
dscSetInfo :: Vk.DscPool.P sp -> Vk.DscSetLyt.L sl DscSetLytLstW123 ->
Vk.DscSet.AllocateInfo () sp '[ '(sl, DscSetLytLstW123)]
dscSetInfo pl lyt = Vk.DscSet.AllocateInfo {
Vk.DscSet.allocateInfoNext = Nothing,
Vk.DscSet.allocateInfoDescriptorPool = pl,
Vk.DscSet.allocateInfoSetLayouts = Vk.DscSet.Layout lyt :** HeteroParList.Nil }
type BffMem sm sb nm w = (
Vk.Bffr.Binded sb sm nm '[ List 256 w ""],
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm '[ List 256 w ""])] )
storageBufferNew3 :: Vk.PhDvc.P -> Vk.Dvc.D sd ->
V.Vector W1 -> V.Vector W2 -> V.Vector W3 -> (
forall sb1 sm1 sb2 sm2 sb3 sm3 .
BffMem sm1 sb1 nm1 W1 ->
BffMem sm2 sb2 nm2 W2 ->
BffMem sm3 sb3 nm3 W3 -> IO a ) -> IO a
storageBufferNew3 phdvc dvc x y z f =
storageBufferNews phdvc dvc (x :** y :** z :** HeteroParList.Nil)
$ Arg \b1 m1 -> Arg \b2 m2 -> Arg \b3 m3 ->
f (b1, m1) (b2, m2) (b3, m3)
class StorageBufferNews f a where
type Vectors f :: [Type]
storageBufferNews :: Vk.PhDvc.P -> Vk.Dvc.D sd ->
HeteroParList.PL V.Vector (Vectors f) -> f -> IO a
data Arg nm w f = Arg (forall sb sm .
Vk.Bffr.Binded sb sm nm '[ List 256 w ""] ->
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm '[ List 256 w ""])] -> f)
instance StorageBufferNews (IO a) a where
type Vectors (IO a) = '[]; storageBufferNews _phdvc _dvc HeteroParList.Nil f = f
instance (Storable w, StorageBufferNews f a) =>
StorageBufferNews (Arg nm w f) a where
type Vectors (Arg nm w f) = w ': Vectors f
storageBufferNews phdvc dvc (vs :** vss) (Arg f) =
storageBufferNew phdvc dvc vs \buf mem ->
storageBufferNews @f @a phdvc dvc vss $ f buf mem
type KBuffer = 'Vk.Dvc.Mem.ImgBffr.K.Buffer
storageBufferNew :: forall {sd} v {nm} obj {a} . (
StoreObject v obj, SizeAlignment obj ) =>
Vk.PhDvc.P -> Vk.Dvc.D sd -> v -> (forall sb sm .
Vk.Bffr.Binded sb sm nm '[obj] ->
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, KBuffer nm '[obj])] ->
IO a) -> IO a
storageBufferNew phdvc dvc xs f =
Vk.Bffr.create dvc (bufferInfo xs) nil nil \bff -> do
mi <- getMemoryInfo phdvc dvc bff
Vk.Dvc.Mem.ImgBffr.allocateBind dvc (HeteroParList.Singleton . U2 $ Vk.Dvc.Mem.ImgBffr.Buffer bff) mi
nil nil \(HeteroParList.Singleton (U2 (Vk.Dvc.Mem.ImgBffr.BufferBinded bnd))) m -> do
Vk.Dvc.Mem.ImgBffr.write @nm @obj dvc m zeroBits xs
f bnd m
storageBufferNew3Objs :: forall {sd} v {nm} obj0 obj1 obj2 {a} . (
StoreObject v obj0, SizeAlignment obj0,
StoreObject v obj1, SizeAlignment obj1,
StoreObject v obj2, SizeAlignment obj2,
Vk.Dvc.Mem.ImgBffr.OffsetSizeObject obj0 '[obj0, obj1, obj2],
Vk.Dvc.Mem.ImgBffr.OffsetSizeObject obj1 '[obj0, obj1, obj2],
Vk.Dvc.Mem.ImgBffr.OffsetSizeObject obj2 '[obj0, obj1, obj2]
) =>
Vk.PhDvc.P -> Vk.Dvc.D sd -> v -> v -> v -> (forall sb sm .
Vk.Bffr.Binded sb sm nm '[obj0, obj1, obj2] ->
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, KBuffer nm '[obj0, obj1, obj2])] ->
IO a) -> IO a
storageBufferNew3Objs phdvc dvc x y z f =
Vk.Bffr.create dvc (bufferInfo' x y z) nil nil \bff -> do
mi <- getMemoryInfo phdvc dvc bff
Vk.Dvc.Mem.ImgBffr.allocateBind dvc (HeteroParList.Singleton . U2 $ Vk.Dvc.Mem.ImgBffr.Buffer bff) mi
nil nil \(HeteroParList.Singleton (U2 (Vk.Dvc.Mem.ImgBffr.BufferBinded bnd))) m -> do
Vk.Dvc.Mem.ImgBffr.write @nm @obj0 dvc m zeroBits x
Vk.Dvc.Mem.ImgBffr.write @nm @obj1 dvc m zeroBits y
Vk.Dvc.Mem.ImgBffr.write @nm @obj2 dvc m zeroBits z
f bnd m
bufferInfo :: StoreObject v obj => v -> Vk.Bffr.CreateInfo () '[obj]
bufferInfo xs = Vk.Bffr.CreateInfo {
Vk.Bffr.createInfoNext = Nothing,
Vk.Bffr.createInfoFlags = def,
Vk.Bffr.createInfoLengths = HeteroParList.Singleton $ objectLength xs,
Vk.Bffr.createInfoUsage = Vk.Bffr.UsageStorageBufferBit,
Vk.Bffr.createInfoSharingMode = Vk.SharingModeExclusive,
Vk.Bffr.createInfoQueueFamilyIndices = [] }
bufferInfo' :: (
StoreObject v obj0, StoreObject v obj1, StoreObject v obj2 ) =>
v -> v -> v -> Vk.Bffr.CreateInfo () '[obj0, obj1, obj2]
bufferInfo' x y z = Vk.Bffr.CreateInfo {
Vk.Bffr.createInfoNext = Nothing,
Vk.Bffr.createInfoFlags = def,
Vk.Bffr.createInfoLengths =
objectLength x :** objectLength y :**
objectLength z :** HeteroParList.Nil,
Vk.Bffr.createInfoUsage = Vk.Bffr.UsageStorageBufferBit,
Vk.Bffr.createInfoSharingMode = Vk.SharingModeExclusive,
Vk.Bffr.createInfoQueueFamilyIndices = [] }
getMemoryInfo :: Vk.PhDvc.P -> Vk.Dvc.D sd -> Vk.Bffr.B sb nm objs ->
IO (Vk.Dvc.Mem.Buffer.AllocateInfo ())
getMemoryInfo phdvc dvc buffer = do
reqs <- Vk.Bffr.getMemoryRequirements dvc buffer
mt <- findMemoryTypeIndex phdvc reqs (
Vk.Mem.PropertyHostVisibleBit .|.
Vk.Mem.PropertyHostCoherentBit )
pure Vk.Dvc.Mem.Buffer.AllocateInfo {
Vk.Dvc.Mem.Buffer.allocateInfoNext = Nothing,
Vk.Dvc.Mem.Buffer.allocateInfoMemoryTypeIndex = mt }
findMemoryTypeIndex ::
Vk.PhDvc.P -> Vk.Mem.M.Requirements -> Vk.Mem.PropertyFlags ->
IO Vk.Mem.M.TypeIndex
findMemoryTypeIndex phdvc reqs mprop = do
mprops <- Vk.PhDvc.getMemoryProperties phdvc
let rqts = Vk.Mem.M.requirementsMemoryTypeBits reqs
mpts = (fst <$>) . filter
(checkBits mprop . Vk.Mem.M.mTypePropertyFlags . snd)
$ Vk.PhDvc.memoryPropertiesMemoryTypes mprops
case filter (`Vk.Mem.M.elemTypeIndex` rqts) mpts of
i : _ -> pure i
[] -> error "No available memory types"
writeDscSet :: forall sd sp sl sm1 sb1 nm1 sm2 sb2 nm2 sm3 sb3 nm3 .
Vk.DscSet.S sd sp '(sl, DscSetLytLstW123) ->
Vk.Bffr.Binded sm1 sb1 nm1 '[ListW1] ->
Vk.Bffr.Binded sm2 sb2 nm2 '[ListW2] ->
Vk.Bffr.Binded sm3 sb3 nm3 '[ListW3] ->
Vk.DscSet.Write () sd sp '(sl, DscSetLytLstW123) (
'Vk.DscSet.WriteSourcesArgBuffer '[
'(sb1, sm1, nm1, '[ListW1], ListW1),
'(sb2, sm2, nm2, '[ListW2], ListW2),
'(sb3, sm3, nm3, '[ListW3], ListW3)
] )
writeDscSet ds ba bb bc = Vk.DscSet.Write {
Vk.DscSet.writeNext = Nothing,
Vk.DscSet.writeDstSet = ds,
Vk.DscSet.writeDescriptorType = Vk.Dsc.TypeStorageBuffer,
Vk.DscSet.writeSources = Vk.DscSet.BufferInfos $
bil @W1 ba :** bil @W2 bb :** bil @W3 bc :** HeteroParList.Nil }
where
bil :: forall t {sb} {sm} {nm} {objs} . Vk.Bffr.Binded sm sb nm objs ->
Vk.Dsc.BufferInfo '(sb, sm, nm, objs, List 256 t "")
bil = Vk.Dsc.BufferInfoList
writeDscSet2 :: forall nm objs sd sp sl sm4 sb4 nm4 .
Vk.DscSet.S sd sp '(sl, DscSetLytLstW123) ->
Vk.Bffr.Binded sm4 sb4 nm4 objs ->
Vk.DscSet.Write () sd sp '(sl, DscSetLytLstW123) (
'Vk.DscSet.WriteSourcesArgBuffer '[
'(sb4, sm4, nm4,
objs,
Atom 256 Word32 ('Just nm))
] )
writeDscSet2 ds bx = Vk.DscSet.Write {
Vk.DscSet.writeNext = Nothing,
Vk.DscSet.writeDstSet = ds,
Vk.DscSet.writeDescriptorType = Vk.Dsc.TypeStorageBuffer,
Vk.DscSet.writeSources = Vk.DscSet.BufferInfos $
Vk.Dsc.BufferInfoAtom bx :** HeteroParList.Nil }
calc :: Vk.Dvc.D sd -> Vk.QFam.Index -> Vk.DscSetLyt.L sl DscSetLytLstW123 ->
Word32 -> Vk.DscSet.S sd sp '(sl, DscSetLytLstW123) ->
Vk.Dvc.Mem.ImgBffr.M sm1 '[ '(sb1, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm1 '[ListW1])] ->
Vk.Dvc.Mem.ImgBffr.M sm2 '[ '(sb2, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm2 '[ListW2])] ->
Vk.Dvc.Mem.ImgBffr.M sm3 '[ '(sb3, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm3 '[ListW3])] -> IO ([W1], [W2], [W3])
calc dvc qFam dslyt ln dss ma mb mc =
Vk.Ppl.Lyt.createNew dvc (pplLayoutInfoNew dslyt) nil nil \plyt ->
Vk.Ppl.Cmpt.createCs
dvc Nothing
(HeteroParList.Singleton . U4 $ computePipelineInfo plyt)
nil nil \(HeteroParList.Singleton (Vk.Ppl.Cmpt.Pipeline ppl)) ->
Vk.CmdPl.create dvc (commandPoolInfo qFam) nil nil \cp ->
Vk.CmdBuf.allocate dvc (commandBufferInfo cp) \case
[cmdBuf] -> run dvc qFam cmdBuf ppl plyt dss ln ma mb mc
_ -> error "never occur"
pplLayoutInfoNew :: Vk.DscSetLyt.L sl DscSetLytLstW123 ->
Vk.Ppl.Lyt.CreateInfoNew () '[ '(sl, DscSetLytLstW123)]
('Vk.PushConstant.PushConstantLayout '[] '[])
pplLayoutInfoNew dslyt = Vk.Ppl.Lyt.CreateInfoNew {
Vk.Ppl.Lyt.createInfoNextNew = Nothing,
Vk.Ppl.Lyt.createInfoFlagsNew = zeroBits,
Vk.Ppl.Lyt.createInfoSetLayoutsNew = HeteroParList.Singleton $ U2 dslyt }
computePipelineInfo :: Vk.Ppl.Lyt.L sl '[ '(sdsl, DscSetLytLstW123)] '[] ->
Vk.Ppl.Cmpt.CreateInfo () '((), (), 'GlslComputeShader, (), (),
'[Word32, Word32]) '(sl, '[ '(sdsl, DscSetLytLstW123)], '[]) sbph
computePipelineInfo pl = Vk.Ppl.Cmpt.CreateInfo {
Vk.Ppl.Cmpt.createInfoNext = Nothing,
Vk.Ppl.Cmpt.createInfoFlags = zeroBits,
Vk.Ppl.Cmpt.createInfoStage = U6 shaderStageInfo,
Vk.Ppl.Cmpt.createInfoLayout = U3 pl,
Vk.Ppl.Cmpt.createInfoBasePipelineHandle = Nothing,
Vk.Ppl.Cmpt.createInfoBasePipelineIndex = Nothing }
shaderStageInfo :: Vk.Ppl.ShaderSt.CreateInfoNew
() () 'GlslComputeShader () () '[Word32, Word32]
shaderStageInfo = Vk.Ppl.ShaderSt.CreateInfoNew {
Vk.Ppl.ShaderSt.createInfoNextNew = Nothing,
Vk.Ppl.ShaderSt.createInfoFlagsNew = zeroBits,
Vk.Ppl.ShaderSt.createInfoStageNew = Vk.ShaderStageComputeBit,
Vk.Ppl.ShaderSt.createInfoModuleNew = Vk.ShaderMod.M shaderModInfo nil nil,
Vk.Ppl.ShaderSt.createInfoNameNew = "main",
Vk.Ppl.ShaderSt.createInfoSpecializationInfoNew =
Just $ HeteroParList.Id 3 :** HeteroParList.Id 10 :** HeteroParList.Nil }
where shaderModInfo = Vk.ShaderMod.CreateInfo {
Vk.ShaderMod.createInfoNext = Nothing,
Vk.ShaderMod.createInfoFlags = zeroBits,
Vk.ShaderMod.createInfoCode = glslComputeShaderMain }
commandPoolInfo :: Vk.QFam.Index -> Vk.CmdPl.CreateInfo ()
commandPoolInfo qFam = Vk.CmdPl.CreateInfo {
Vk.CmdPl.createInfoNext = Nothing,
Vk.CmdPl.createInfoFlags = Vk.CmdPl.CreateResetCommandBufferBit,
Vk.CmdPl.createInfoQueueFamilyIndex = qFam }
commandBufferInfo :: Vk.CmdPl.C s -> Vk.CmdBuf.AllocateInfo () s
commandBufferInfo cmdPool = Vk.CmdBuf.AllocateInfo {
Vk.CmdBuf.allocateInfoNext = Nothing,
Vk.CmdBuf.allocateInfoCommandPool = cmdPool,
Vk.CmdBuf.allocateInfoLevel = Vk.CmdBuf.LevelPrimary,
Vk.CmdBuf.allocateInfoCommandBufferCount = 1 }
run :: forall sd sc vs sg sl sdsl sp sm1 sb1 nm1 sm2 sb2 nm2 sm3 sb3 nm3 .
Vk.Dvc.D sd -> Vk.QFam.Index -> Vk.CmdBuf.C sc vs -> Vk.Ppl.Cmpt.C sg ->
Vk.Ppl.Lyt.L sl '[ '(sdsl, DscSetLytLstW123)] '[] ->
Vk.DscSet.S sd sp '(sdsl, DscSetLytLstW123) -> Word32 ->
Vk.Dvc.Mem.ImgBffr.M sm1 '[ '(sb1, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm1 '[ListW1])] ->
Vk.Dvc.Mem.ImgBffr.M sm2 '[ '(sb2, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm2 '[ListW2])] ->
Vk.Dvc.Mem.ImgBffr.M sm3 '[ '(sb3, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm3 '[ListW3])] ->
IO ([W1], [W2], [W3])
run dvc qf cb ppl plyt dss ln ma mb mc = Vk.Dvc.getQueue dvc qf 0 >>= \q -> do
Vk.CmdBuf.begin @() @() cb def do
Vk.Cmd.bindPipelineCompute cb Vk.Ppl.BindPointCompute ppl
Vk.Cmd.bindDescriptorSetsNew cb Vk.Ppl.BindPointCompute plyt
(HeteroParList.Singleton $ U2 dss) []
Vk.Cmd.dispatch cb ln 1 1
Vk.Queue.submit q (U4 sinfo :** HeteroParList.Nil) Nothing
Vk.Queue.waitIdle q
(,,) <$> Vk.Dvc.Mem.ImgBffr.read @nm1 @ListW1 @[W1] dvc ma zeroBits
<*> Vk.Dvc.Mem.ImgBffr.read @nm2 @ListW2 @[W2] dvc mb zeroBits
<*> Vk.Dvc.Mem.ImgBffr.read @nm3 @ListW3 @[W3] dvc mc zeroBits
where sinfo :: Vk.SubmitInfo () _ _ _
sinfo = Vk.SubmitInfo {
Vk.submitInfoNext = Nothing,
Vk.submitInfoWaitSemaphoreDstStageMasks = HeteroParList.Nil,
Vk.submitInfoCommandBuffers = U2 cb :** HeteroParList.Nil,
Vk.submitInfoSignalSemaphores = HeteroParList.Nil }
[glslComputeShader|
#version 460
layout(local_size_x = 1, local_size_y = 1) in;
layout(binding = 0) buffer Data {
uint val[];
} data[3];
layout(binding = 1) buffer Foo {
uint x;
} x;
layout(constant_id = 0) const uint sc = 2;
layout(constant_id = 1) const uint sc2 = 3;
void
main()
{
int index = int(gl_GlobalInvocationID.x);
data[2].val[index] =
(data[0].val[index] + data[1].val[index]) * sc * sc2 + x.x;
}
|]
| null | https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/37eb9675bf1c0b008c7af4843713c91623c1e7f4/themes/gui/vulkan/try-my-vulkan-snd/app/try-no-dynamic-dsc-sets.hs | haskell | # LANGUAGE PatternSynonyms, ViewPatterns # | # LANGUAGE QuasiQuotes #
# , LambdaCase , OverloadedStrings #
# LANGUAGE ScopedTypeVariables , RankNTypes , TypeApplications #
# LANGUAGE GADTs , TypeFamilies #
# LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleContexts , FlexibleInstances , UndecidableInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE PartialTypeSignatures #
# LANGUAGE StandaloneDeriving #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Main where
import Foreign.Storable
import Data.Kind
import Data.Kind.Object
import Data.Default
import Data.Bits
import Data.Bits.Utils
import Data.List.Length
import Data.TypeLevel.Uncurry
import qualified Data.HeteroParList as HeteroParList
import Data.HeteroParList (pattern (:*), pattern (:**))
import Data.Word
import System.Environment
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Utils as V
import Shaderc.TH
import Shaderc.EnumAuto
import Gpu.Vulkan.Misc
import qualified Gpu.Vulkan as Vk
import qualified Gpu.Vulkan.Enum as Vk
import qualified Gpu.Vulkan.Instance as Vk.Inst
import qualified Gpu.Vulkan.PhysicalDevice as Vk.PhDvc
import qualified Gpu.Vulkan.PhysicalDevice.Struct as Vk.PhDvc
import qualified Gpu.Vulkan.Queue as Vk.Queue
import qualified Gpu.Vulkan.Queue.Enum as Vk.Queue
import qualified Gpu.Vulkan.QueueFamily as Vk.QFam
import qualified Gpu.Vulkan.QueueFamily.Middle as Vk.QFam
import qualified Gpu.Vulkan.Device as Vk.Dvc
import qualified Gpu.Vulkan.CommandPool as Vk.CmdPl
import qualified Gpu.Vulkan.Buffer.Enum as Vk.Bffr
import qualified Gpu.Vulkan.Memory.Enum as Vk.Mem
import qualified Gpu.Vulkan.Memory.Middle as Vk.Mem.M
import qualified Gpu.Vulkan.Descriptor as Vk.Dsc
import qualified Gpu.Vulkan.DescriptorPool as Vk.DscPool
import qualified Gpu.Vulkan.ShaderModule as Vk.ShaderMod
import qualified Gpu.Vulkan.Pipeline.Enum as Vk.Ppl
import qualified Gpu.Vulkan.Pipeline.Layout as Vk.Ppl.Lyt
import qualified Gpu.Vulkan.Pipeline.Layout.Type as Vk.Ppl.Lyt
import qualified Gpu.Vulkan.Pipeline.ShaderStage as Vk.Ppl.ShaderSt
import qualified Gpu.Vulkan.Pipeline.Compute as Vk.Ppl.Cmpt
import qualified Gpu.Vulkan.DescriptorSet as Vk.DscSet
import qualified Gpu.Vulkan.CommandBuffer as Vk.CmdBuf
import qualified Gpu.Vulkan.Command as Vk.Cmd
import qualified Gpu.Vulkan.Buffer as Vk.Bffr
import qualified Gpu.Vulkan.Memory.AllocateInfo as Vk.Dvc.Mem.Buffer
import qualified Gpu.Vulkan.Memory as Vk.Dvc.Mem.ImgBffr
import qualified Gpu.Vulkan.Memory.Kind as Vk.Dvc.Mem.ImgBffr.K
import qualified Gpu.Vulkan.DescriptorSetLayout as Vk.DscSetLyt
import qualified Gpu.Vulkan.DescriptorSetLayout.Type as Vk.DscSetLyt
import qualified Gpu.Vulkan.Khr as Vk.Khr
import qualified Gpu.Vulkan.PushConstant as Vk.PushConstant
main :: IO ()
main = do
args <- getArgs
case args of
[arg] -> do
(r1, r2, r3) <- crtDevice \phdvc qFam dvc mxX ->
let (da, db, dc) = mkData mxX in
Vk.DscSetLyt.create dvc dscSetLayoutInfo
nil nil \dslyt ->
prepDscSets arg phdvc dvc dslyt da db dc
$ calc dvc qFam dslyt mxX
print . take 20 $ unW1 <$> r1
print . take 20 $ unW2 <$> r2
print . take 20 $ unW3 <$> r3
_ -> error "bad args"
newtype W1 = W1 { unW1 :: Word32 } deriving (Show, Storable)
newtype W2 = W2 { unW2 :: Word32 } deriving (Show, Storable)
newtype W3 = W3 { unW3 :: Word32 } deriving (Show, Storable)
type ListW1 = List 256 W1 ""
type ListW2 = List 256 W2 ""
type ListW3 = List 256 W3 ""
crtDevice :: (forall sd .
Vk.PhDvc.P -> Vk.QFam.Index -> Vk.Dvc.D sd -> Word32 -> IO a) -> IO a
crtDevice f = Vk.Inst.create @() @() instInfo nil nil \inst -> do
phdvc <- head <$> Vk.PhDvc.enumerate inst
qf <- findQueueFamily phdvc Vk.Queue.ComputeBit
lmts <- Vk.PhDvc.propertiesLimits <$> Vk.PhDvc.getProperties phdvc
let mxX :. _ = Vk.PhDvc.limitsMaxComputeWorkGroupCount lmts
Vk.Dvc.create @() @'[()] phdvc (dvcInfo qf) nil nil $ \dvc ->
f phdvc qf dvc mxX
where
instInfo = def {
Vk.Inst.createInfoEnabledLayerNames =
[Vk.Khr.validationLayerName] }
dvcInfo qf = Vk.Dvc.CreateInfo {
Vk.Dvc.createInfoNext = Nothing,
Vk.Dvc.createInfoFlags = zeroBits,
Vk.Dvc.createInfoQueueCreateInfos = HeteroParList.Singleton $ queueInfo qf,
Vk.Dvc.createInfoEnabledLayerNames =
[Vk.Khr.validationLayerName],
Vk.Dvc.createInfoEnabledExtensionNames = [],
Vk.Dvc.createInfoEnabledFeatures = Nothing }
queueInfo qf = Vk.Dvc.QueueCreateInfo {
Vk.Dvc.queueCreateInfoNext = Nothing,
Vk.Dvc.queueCreateInfoFlags = zeroBits,
Vk.Dvc.queueCreateInfoQueueFamilyIndex = qf,
Vk.Dvc.queueCreateInfoQueuePriorities = [0] }
findQueueFamily :: Vk.PhDvc.P -> Vk.Queue.FlagBits -> IO Vk.QFam.Index
findQueueFamily phdvc qb = (<$> Vk.PhDvc.getQueueFamilyProperties phdvc)
$ fst . head . filter
((/= zeroBits) . (.&. qb) . Vk.QFam.propertiesQueueFlags . snd)
mkData :: Word32 -> (V.Vector W1, V.Vector W2, V.Vector W3)
mkData n = (
V.genericReplicate n $ W1 3,
V.fromList $ W2 <$> [1 .. n],
V.genericReplicate n $ W3 0 )
type DscSetLytLstW123 = '[
'Vk.DscSetLyt.Buffer '[ListW1, ListW2, ListW3],
'Vk.DscSetLyt.Buffer '[ Atom 256 Word32 'Nothing] ]
dscSetLayoutInfo :: Vk.DscSetLyt.CreateInfo () DscSetLytLstW123
dscSetLayoutInfo = Vk.DscSetLyt.CreateInfo {
Vk.DscSetLyt.createInfoNext = Nothing,
Vk.DscSetLyt.createInfoFlags = zeroBits,
Vk.DscSetLyt.createInfoBindings = bdng :** bdng :** HeteroParList.Nil }
where bdng = Vk.DscSetLyt.BindingBuffer {
Vk.DscSetLyt.bindingBufferDescriptorType =
Vk.Dsc.TypeStorageBuffer,
Vk.DscSetLyt.bindingBufferStageFlags =
Vk.ShaderStageComputeBit }
prepDscSets ::
String -> Vk.PhDvc.P -> Vk.Dvc.D sd -> Vk.DscSetLyt.L sl DscSetLytLstW123 ->
V.Vector W1 -> V.Vector W2 -> V.Vector W3 -> (forall s sm1 sm2 sm3 sb1 sb2 sb3 .
Vk.DscSet.S sd s '(sl, DscSetLytLstW123) ->
Vk.Dvc.Mem.ImgBffr.M sm1 '[ '(sb1, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm1 '[ListW1])] ->
Vk.Dvc.Mem.ImgBffr.M sm2 '[ '(sb2, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm2 '[ListW2])] ->
Vk.Dvc.Mem.ImgBffr.M sm3 '[ '(sb3, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm3 '[ListW3])] -> IO a) -> IO a
prepDscSets arg phdvc dvc dslyt da db dc f =
Vk.DscPool.create dvc dscPoolInfo nil nil \dp ->
Vk.DscSet.allocateSs dvc (dscSetInfo dp dslyt) >>= \(HeteroParList.Singleton ds) ->
storageBufferNew3 phdvc dvc da db dc \(ba, ma) (bb, mb) (bc, mc) ->
storageBufferNew3Objs @Word32
@(Atom 256 Word32 ('Just "x0"))
@(Atom 256 Word32 ('Just "x1"))
@(Atom 256 Word32 ('Just "x2"))
phdvc dvc 3 5 7 \bx mx -> case arg of
"0" -> do
Vk.DscSet.updateDs @_ @() dvc (
Vk.DscSet.Write_ (writeDscSet ds ba bb bc) :**
Vk.DscSet.Write_ (writeDscSet2 @"x0" ds bx) :**
HeteroParList.Nil
) []
f ds ma mb mc
"1" -> do
Vk.DscSet.updateDs @_ @() dvc (
Vk.DscSet.Write_ (writeDscSet ds ba bb bc) :**
Vk.DscSet.Write_ (writeDscSet2 @"x1" ds bx) :**
HeteroParList.Nil
) []
f ds ma mb mc
"2" -> do
Vk.DscSet.updateDs @_ @() dvc (
Vk.DscSet.Write_ (writeDscSet ds ba bb bc) :**
Vk.DscSet.Write_ (writeDscSet2 @"x2" ds bx) :**
HeteroParList.Nil
) []
f ds ma mb mc
_ -> error "bad arg"
dscPoolInfo :: Vk.DscPool.CreateInfo ()
dscPoolInfo = Vk.DscPool.CreateInfo {
Vk.DscPool.createInfoNext = Nothing,
Vk.DscPool.createInfoFlags = Vk.DscPool.CreateFreeDescriptorSetBit,
Vk.DscPool.createInfoMaxSets = 1,
Vk.DscPool.createInfoPoolSizes = [poolSize] }
where poolSize = Vk.DscPool.Size {
Vk.DscPool.sizeType = Vk.Dsc.TypeStorageBuffer,
Vk.DscPool.sizeDescriptorCount = 10 }
dscSetInfo :: Vk.DscPool.P sp -> Vk.DscSetLyt.L sl DscSetLytLstW123 ->
Vk.DscSet.AllocateInfo () sp '[ '(sl, DscSetLytLstW123)]
dscSetInfo pl lyt = Vk.DscSet.AllocateInfo {
Vk.DscSet.allocateInfoNext = Nothing,
Vk.DscSet.allocateInfoDescriptorPool = pl,
Vk.DscSet.allocateInfoSetLayouts = Vk.DscSet.Layout lyt :** HeteroParList.Nil }
type BffMem sm sb nm w = (
Vk.Bffr.Binded sb sm nm '[ List 256 w ""],
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm '[ List 256 w ""])] )
storageBufferNew3 :: Vk.PhDvc.P -> Vk.Dvc.D sd ->
V.Vector W1 -> V.Vector W2 -> V.Vector W3 -> (
forall sb1 sm1 sb2 sm2 sb3 sm3 .
BffMem sm1 sb1 nm1 W1 ->
BffMem sm2 sb2 nm2 W2 ->
BffMem sm3 sb3 nm3 W3 -> IO a ) -> IO a
storageBufferNew3 phdvc dvc x y z f =
storageBufferNews phdvc dvc (x :** y :** z :** HeteroParList.Nil)
$ Arg \b1 m1 -> Arg \b2 m2 -> Arg \b3 m3 ->
f (b1, m1) (b2, m2) (b3, m3)
class StorageBufferNews f a where
type Vectors f :: [Type]
storageBufferNews :: Vk.PhDvc.P -> Vk.Dvc.D sd ->
HeteroParList.PL V.Vector (Vectors f) -> f -> IO a
data Arg nm w f = Arg (forall sb sm .
Vk.Bffr.Binded sb sm nm '[ List 256 w ""] ->
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm '[ List 256 w ""])] -> f)
instance StorageBufferNews (IO a) a where
type Vectors (IO a) = '[]; storageBufferNews _phdvc _dvc HeteroParList.Nil f = f
instance (Storable w, StorageBufferNews f a) =>
StorageBufferNews (Arg nm w f) a where
type Vectors (Arg nm w f) = w ': Vectors f
storageBufferNews phdvc dvc (vs :** vss) (Arg f) =
storageBufferNew phdvc dvc vs \buf mem ->
storageBufferNews @f @a phdvc dvc vss $ f buf mem
type KBuffer = 'Vk.Dvc.Mem.ImgBffr.K.Buffer
storageBufferNew :: forall {sd} v {nm} obj {a} . (
StoreObject v obj, SizeAlignment obj ) =>
Vk.PhDvc.P -> Vk.Dvc.D sd -> v -> (forall sb sm .
Vk.Bffr.Binded sb sm nm '[obj] ->
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, KBuffer nm '[obj])] ->
IO a) -> IO a
storageBufferNew phdvc dvc xs f =
Vk.Bffr.create dvc (bufferInfo xs) nil nil \bff -> do
mi <- getMemoryInfo phdvc dvc bff
Vk.Dvc.Mem.ImgBffr.allocateBind dvc (HeteroParList.Singleton . U2 $ Vk.Dvc.Mem.ImgBffr.Buffer bff) mi
nil nil \(HeteroParList.Singleton (U2 (Vk.Dvc.Mem.ImgBffr.BufferBinded bnd))) m -> do
Vk.Dvc.Mem.ImgBffr.write @nm @obj dvc m zeroBits xs
f bnd m
storageBufferNew3Objs :: forall {sd} v {nm} obj0 obj1 obj2 {a} . (
StoreObject v obj0, SizeAlignment obj0,
StoreObject v obj1, SizeAlignment obj1,
StoreObject v obj2, SizeAlignment obj2,
Vk.Dvc.Mem.ImgBffr.OffsetSizeObject obj0 '[obj0, obj1, obj2],
Vk.Dvc.Mem.ImgBffr.OffsetSizeObject obj1 '[obj0, obj1, obj2],
Vk.Dvc.Mem.ImgBffr.OffsetSizeObject obj2 '[obj0, obj1, obj2]
) =>
Vk.PhDvc.P -> Vk.Dvc.D sd -> v -> v -> v -> (forall sb sm .
Vk.Bffr.Binded sb sm nm '[obj0, obj1, obj2] ->
Vk.Dvc.Mem.ImgBffr.M sm '[ '(sb, KBuffer nm '[obj0, obj1, obj2])] ->
IO a) -> IO a
storageBufferNew3Objs phdvc dvc x y z f =
Vk.Bffr.create dvc (bufferInfo' x y z) nil nil \bff -> do
mi <- getMemoryInfo phdvc dvc bff
Vk.Dvc.Mem.ImgBffr.allocateBind dvc (HeteroParList.Singleton . U2 $ Vk.Dvc.Mem.ImgBffr.Buffer bff) mi
nil nil \(HeteroParList.Singleton (U2 (Vk.Dvc.Mem.ImgBffr.BufferBinded bnd))) m -> do
Vk.Dvc.Mem.ImgBffr.write @nm @obj0 dvc m zeroBits x
Vk.Dvc.Mem.ImgBffr.write @nm @obj1 dvc m zeroBits y
Vk.Dvc.Mem.ImgBffr.write @nm @obj2 dvc m zeroBits z
f bnd m
bufferInfo :: StoreObject v obj => v -> Vk.Bffr.CreateInfo () '[obj]
bufferInfo xs = Vk.Bffr.CreateInfo {
Vk.Bffr.createInfoNext = Nothing,
Vk.Bffr.createInfoFlags = def,
Vk.Bffr.createInfoLengths = HeteroParList.Singleton $ objectLength xs,
Vk.Bffr.createInfoUsage = Vk.Bffr.UsageStorageBufferBit,
Vk.Bffr.createInfoSharingMode = Vk.SharingModeExclusive,
Vk.Bffr.createInfoQueueFamilyIndices = [] }
bufferInfo' :: (
StoreObject v obj0, StoreObject v obj1, StoreObject v obj2 ) =>
v -> v -> v -> Vk.Bffr.CreateInfo () '[obj0, obj1, obj2]
bufferInfo' x y z = Vk.Bffr.CreateInfo {
Vk.Bffr.createInfoNext = Nothing,
Vk.Bffr.createInfoFlags = def,
Vk.Bffr.createInfoLengths =
objectLength x :** objectLength y :**
objectLength z :** HeteroParList.Nil,
Vk.Bffr.createInfoUsage = Vk.Bffr.UsageStorageBufferBit,
Vk.Bffr.createInfoSharingMode = Vk.SharingModeExclusive,
Vk.Bffr.createInfoQueueFamilyIndices = [] }
getMemoryInfo :: Vk.PhDvc.P -> Vk.Dvc.D sd -> Vk.Bffr.B sb nm objs ->
IO (Vk.Dvc.Mem.Buffer.AllocateInfo ())
getMemoryInfo phdvc dvc buffer = do
reqs <- Vk.Bffr.getMemoryRequirements dvc buffer
mt <- findMemoryTypeIndex phdvc reqs (
Vk.Mem.PropertyHostVisibleBit .|.
Vk.Mem.PropertyHostCoherentBit )
pure Vk.Dvc.Mem.Buffer.AllocateInfo {
Vk.Dvc.Mem.Buffer.allocateInfoNext = Nothing,
Vk.Dvc.Mem.Buffer.allocateInfoMemoryTypeIndex = mt }
findMemoryTypeIndex ::
Vk.PhDvc.P -> Vk.Mem.M.Requirements -> Vk.Mem.PropertyFlags ->
IO Vk.Mem.M.TypeIndex
findMemoryTypeIndex phdvc reqs mprop = do
mprops <- Vk.PhDvc.getMemoryProperties phdvc
let rqts = Vk.Mem.M.requirementsMemoryTypeBits reqs
mpts = (fst <$>) . filter
(checkBits mprop . Vk.Mem.M.mTypePropertyFlags . snd)
$ Vk.PhDvc.memoryPropertiesMemoryTypes mprops
case filter (`Vk.Mem.M.elemTypeIndex` rqts) mpts of
i : _ -> pure i
[] -> error "No available memory types"
writeDscSet :: forall sd sp sl sm1 sb1 nm1 sm2 sb2 nm2 sm3 sb3 nm3 .
Vk.DscSet.S sd sp '(sl, DscSetLytLstW123) ->
Vk.Bffr.Binded sm1 sb1 nm1 '[ListW1] ->
Vk.Bffr.Binded sm2 sb2 nm2 '[ListW2] ->
Vk.Bffr.Binded sm3 sb3 nm3 '[ListW3] ->
Vk.DscSet.Write () sd sp '(sl, DscSetLytLstW123) (
'Vk.DscSet.WriteSourcesArgBuffer '[
'(sb1, sm1, nm1, '[ListW1], ListW1),
'(sb2, sm2, nm2, '[ListW2], ListW2),
'(sb3, sm3, nm3, '[ListW3], ListW3)
] )
writeDscSet ds ba bb bc = Vk.DscSet.Write {
Vk.DscSet.writeNext = Nothing,
Vk.DscSet.writeDstSet = ds,
Vk.DscSet.writeDescriptorType = Vk.Dsc.TypeStorageBuffer,
Vk.DscSet.writeSources = Vk.DscSet.BufferInfos $
bil @W1 ba :** bil @W2 bb :** bil @W3 bc :** HeteroParList.Nil }
where
bil :: forall t {sb} {sm} {nm} {objs} . Vk.Bffr.Binded sm sb nm objs ->
Vk.Dsc.BufferInfo '(sb, sm, nm, objs, List 256 t "")
bil = Vk.Dsc.BufferInfoList
writeDscSet2 :: forall nm objs sd sp sl sm4 sb4 nm4 .
Vk.DscSet.S sd sp '(sl, DscSetLytLstW123) ->
Vk.Bffr.Binded sm4 sb4 nm4 objs ->
Vk.DscSet.Write () sd sp '(sl, DscSetLytLstW123) (
'Vk.DscSet.WriteSourcesArgBuffer '[
'(sb4, sm4, nm4,
objs,
Atom 256 Word32 ('Just nm))
] )
writeDscSet2 ds bx = Vk.DscSet.Write {
Vk.DscSet.writeNext = Nothing,
Vk.DscSet.writeDstSet = ds,
Vk.DscSet.writeDescriptorType = Vk.Dsc.TypeStorageBuffer,
Vk.DscSet.writeSources = Vk.DscSet.BufferInfos $
Vk.Dsc.BufferInfoAtom bx :** HeteroParList.Nil }
calc :: Vk.Dvc.D sd -> Vk.QFam.Index -> Vk.DscSetLyt.L sl DscSetLytLstW123 ->
Word32 -> Vk.DscSet.S sd sp '(sl, DscSetLytLstW123) ->
Vk.Dvc.Mem.ImgBffr.M sm1 '[ '(sb1, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm1 '[ListW1])] ->
Vk.Dvc.Mem.ImgBffr.M sm2 '[ '(sb2, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm2 '[ListW2])] ->
Vk.Dvc.Mem.ImgBffr.M sm3 '[ '(sb3, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm3 '[ListW3])] -> IO ([W1], [W2], [W3])
calc dvc qFam dslyt ln dss ma mb mc =
Vk.Ppl.Lyt.createNew dvc (pplLayoutInfoNew dslyt) nil nil \plyt ->
Vk.Ppl.Cmpt.createCs
dvc Nothing
(HeteroParList.Singleton . U4 $ computePipelineInfo plyt)
nil nil \(HeteroParList.Singleton (Vk.Ppl.Cmpt.Pipeline ppl)) ->
Vk.CmdPl.create dvc (commandPoolInfo qFam) nil nil \cp ->
Vk.CmdBuf.allocate dvc (commandBufferInfo cp) \case
[cmdBuf] -> run dvc qFam cmdBuf ppl plyt dss ln ma mb mc
_ -> error "never occur"
pplLayoutInfoNew :: Vk.DscSetLyt.L sl DscSetLytLstW123 ->
Vk.Ppl.Lyt.CreateInfoNew () '[ '(sl, DscSetLytLstW123)]
('Vk.PushConstant.PushConstantLayout '[] '[])
pplLayoutInfoNew dslyt = Vk.Ppl.Lyt.CreateInfoNew {
Vk.Ppl.Lyt.createInfoNextNew = Nothing,
Vk.Ppl.Lyt.createInfoFlagsNew = zeroBits,
Vk.Ppl.Lyt.createInfoSetLayoutsNew = HeteroParList.Singleton $ U2 dslyt }
computePipelineInfo :: Vk.Ppl.Lyt.L sl '[ '(sdsl, DscSetLytLstW123)] '[] ->
Vk.Ppl.Cmpt.CreateInfo () '((), (), 'GlslComputeShader, (), (),
'[Word32, Word32]) '(sl, '[ '(sdsl, DscSetLytLstW123)], '[]) sbph
computePipelineInfo pl = Vk.Ppl.Cmpt.CreateInfo {
Vk.Ppl.Cmpt.createInfoNext = Nothing,
Vk.Ppl.Cmpt.createInfoFlags = zeroBits,
Vk.Ppl.Cmpt.createInfoStage = U6 shaderStageInfo,
Vk.Ppl.Cmpt.createInfoLayout = U3 pl,
Vk.Ppl.Cmpt.createInfoBasePipelineHandle = Nothing,
Vk.Ppl.Cmpt.createInfoBasePipelineIndex = Nothing }
shaderStageInfo :: Vk.Ppl.ShaderSt.CreateInfoNew
() () 'GlslComputeShader () () '[Word32, Word32]
shaderStageInfo = Vk.Ppl.ShaderSt.CreateInfoNew {
Vk.Ppl.ShaderSt.createInfoNextNew = Nothing,
Vk.Ppl.ShaderSt.createInfoFlagsNew = zeroBits,
Vk.Ppl.ShaderSt.createInfoStageNew = Vk.ShaderStageComputeBit,
Vk.Ppl.ShaderSt.createInfoModuleNew = Vk.ShaderMod.M shaderModInfo nil nil,
Vk.Ppl.ShaderSt.createInfoNameNew = "main",
Vk.Ppl.ShaderSt.createInfoSpecializationInfoNew =
Just $ HeteroParList.Id 3 :** HeteroParList.Id 10 :** HeteroParList.Nil }
where shaderModInfo = Vk.ShaderMod.CreateInfo {
Vk.ShaderMod.createInfoNext = Nothing,
Vk.ShaderMod.createInfoFlags = zeroBits,
Vk.ShaderMod.createInfoCode = glslComputeShaderMain }
commandPoolInfo :: Vk.QFam.Index -> Vk.CmdPl.CreateInfo ()
commandPoolInfo qFam = Vk.CmdPl.CreateInfo {
Vk.CmdPl.createInfoNext = Nothing,
Vk.CmdPl.createInfoFlags = Vk.CmdPl.CreateResetCommandBufferBit,
Vk.CmdPl.createInfoQueueFamilyIndex = qFam }
commandBufferInfo :: Vk.CmdPl.C s -> Vk.CmdBuf.AllocateInfo () s
commandBufferInfo cmdPool = Vk.CmdBuf.AllocateInfo {
Vk.CmdBuf.allocateInfoNext = Nothing,
Vk.CmdBuf.allocateInfoCommandPool = cmdPool,
Vk.CmdBuf.allocateInfoLevel = Vk.CmdBuf.LevelPrimary,
Vk.CmdBuf.allocateInfoCommandBufferCount = 1 }
run :: forall sd sc vs sg sl sdsl sp sm1 sb1 nm1 sm2 sb2 nm2 sm3 sb3 nm3 .
Vk.Dvc.D sd -> Vk.QFam.Index -> Vk.CmdBuf.C sc vs -> Vk.Ppl.Cmpt.C sg ->
Vk.Ppl.Lyt.L sl '[ '(sdsl, DscSetLytLstW123)] '[] ->
Vk.DscSet.S sd sp '(sdsl, DscSetLytLstW123) -> Word32 ->
Vk.Dvc.Mem.ImgBffr.M sm1 '[ '(sb1, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm1 '[ListW1])] ->
Vk.Dvc.Mem.ImgBffr.M sm2 '[ '(sb2, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm2 '[ListW2])] ->
Vk.Dvc.Mem.ImgBffr.M sm3 '[ '(sb3, 'Vk.Dvc.Mem.ImgBffr.K.Buffer nm3 '[ListW3])] ->
IO ([W1], [W2], [W3])
run dvc qf cb ppl plyt dss ln ma mb mc = Vk.Dvc.getQueue dvc qf 0 >>= \q -> do
Vk.CmdBuf.begin @() @() cb def do
Vk.Cmd.bindPipelineCompute cb Vk.Ppl.BindPointCompute ppl
Vk.Cmd.bindDescriptorSetsNew cb Vk.Ppl.BindPointCompute plyt
(HeteroParList.Singleton $ U2 dss) []
Vk.Cmd.dispatch cb ln 1 1
Vk.Queue.submit q (U4 sinfo :** HeteroParList.Nil) Nothing
Vk.Queue.waitIdle q
(,,) <$> Vk.Dvc.Mem.ImgBffr.read @nm1 @ListW1 @[W1] dvc ma zeroBits
<*> Vk.Dvc.Mem.ImgBffr.read @nm2 @ListW2 @[W2] dvc mb zeroBits
<*> Vk.Dvc.Mem.ImgBffr.read @nm3 @ListW3 @[W3] dvc mc zeroBits
where sinfo :: Vk.SubmitInfo () _ _ _
sinfo = Vk.SubmitInfo {
Vk.submitInfoNext = Nothing,
Vk.submitInfoWaitSemaphoreDstStageMasks = HeteroParList.Nil,
Vk.submitInfoCommandBuffers = U2 cb :** HeteroParList.Nil,
Vk.submitInfoSignalSemaphores = HeteroParList.Nil }
[glslComputeShader|
#version 460
layout(local_size_x = 1, local_size_y = 1) in;
layout(binding = 0) buffer Data {
uint val[];
} data[3];
layout(binding = 1) buffer Foo {
uint x;
} x;
layout(constant_id = 0) const uint sc = 2;
layout(constant_id = 1) const uint sc2 = 3;
void
main()
{
int index = int(gl_GlobalInvocationID.x);
data[2].val[index] =
(data[0].val[index] + data[1].val[index]) * sc * sc2 + x.x;
}
|]
|
1c461676856ae7fb060eb08973e0e53f097d4ef1f9dcba8ce6af7ec91828416d | softwarelanguageslab/maf | R5RS_ad_list-3.scm | ; Changes:
* removed : 0
* added : 2
* swaps : 2
* negated predicates : 1
; * swapped branches: 0
* calls to i d fun : 3
(letrec ((create-list (lambda size
(<change>
(let* ((list-size (if (null? size) 10 (car size)))
(content (make-vector list-size 0))
(first 0)
(list-length 0))
(letrec ((last (lambda ()
(remainder (+ first list-length) list-size)))
(next-index (lambda (index)
(remainder (+ index 1) list-size)))
(prev-index (lambda (index)
(remainder (+ index -1 list-size) list-size)))
(list-index (lambda (position)
(remainder (+ first position -1) list-size)))
(shift-right (lambda (start end)
(letrec ((shift-iter (lambda (index)
(if (= index start)
(vector-set! content (next-index start) (vector-ref content start))
(begin
(vector-set! content (next-index index) (vector-ref content index))
(shift-iter (prev-index index)))))))
(shift-iter end))))
(shift-left (lambda (start end)
(letrec ((shift-iter (lambda (index)
(if (= index end)
(vector-set! content (prev-index end) (vector-ref content end))
(begin
(vector-set! content (prev-index index) (vector-ref content index))
(shift-iter (next-index index)))))))
(shift-iter start))))
(empty? (lambda ()
(zero? list-length)))
(retrieve (lambda (position)
(if (< list-length position)
#f
(vector-ref content (list-index position)))))
(insert (lambda (position element)
(if (< position 1)
#f
(if (>= list-length list-size)
#f
(if (> position (+ list-length 1))
#f
(begin
(set! list-length (+ 1 list-length))
(if (< position (- list-length position))
(begin
(set! first (prev-index first))
(shift-left first (list-index position)))
(shift-right (list-index position) (last)))
(vector-set! content (list-index position) element)
#t))))))
(delete (lambda (position)
(if (< list-length position)
#f
(begin
(set! list-length (- list-length 1))
(if (< position (- list-length position))
(begin
(set! first (next-index first))
(shift-right first (list-index position)))
(shift-left (list-index position) (last)))
#t))))
(replace (lambda (position element)
(if (< list-length position)
#f
(begin
(vector-set! content (list-index position) element)
#t))))
(dispatch (lambda (m . args)
(if (eq? m 'empty?)
(empty?)
(if (eq? m 'insert)
(insert (car args) (cadr args))
(if (eq? m 'delete)
(delete (car args))
(if (eq? m 'retrieve)
(retrieve (car args))
(if (eq? m 'replace)
(replace (car args) (cadr args))
(error "unknown request -- create-list" m)))))))))
dispatch))
((lambda (x) x)
(let* ((list-size (if (null? size) 10 (car size)))
(content (make-vector list-size 0))
(first 0)
(list-length 0))
(letrec ((last (lambda ()
(remainder (+ first list-length) list-size)))
(next-index (lambda (index)
(remainder (+ index 1) list-size)))
(prev-index (lambda (index)
(<change>
()
list-size)
(remainder (+ index -1 list-size) list-size)))
(list-index (lambda (position)
(remainder (+ first position -1) list-size)))
(shift-right (lambda (start end)
(letrec ((shift-iter (lambda (index)
(<change>
(if (= index start)
(vector-set! content (next-index start) (vector-ref content start))
(begin
(vector-set! content (next-index index) (vector-ref content index))
(shift-iter (prev-index index))))
((lambda (x) x)
(if (= index start)
(vector-set! content (next-index start) (vector-ref content start))
(begin
(vector-set! content (next-index index) (vector-ref content index))
(shift-iter (prev-index index)))))))))
(shift-iter end))))
(shift-left (lambda (start end)
(letrec ((shift-iter (lambda (index)
(if (= index end)
(vector-set! content (prev-index end) (vector-ref content end))
(begin
(vector-set! content (prev-index index) (vector-ref content index))
(shift-iter (next-index index)))))))
(shift-iter start))))
(empty? (lambda ()
(zero? list-length)))
(retrieve (lambda (position)
(if (< list-length position)
#f
(vector-ref content (list-index position)))))
(insert (lambda (position element)
(if (< position 1)
#f
(if (>= list-length list-size)
#f
(if (> position (+ list-length 1))
#f
(begin
(set! list-length (+ 1 list-length))
(if (<change> (< position (- list-length position)) (not (< position (- list-length position))))
(begin
(set! first (prev-index first))
(shift-left first (list-index position)))
(shift-right (list-index position) (last)))
(<change>
(vector-set! content (list-index position) element)
#t)
(<change>
#t
(vector-set! content (list-index position) element))))))))
(delete (lambda (position)
(if (< list-length position)
#f
(begin
(<change>
(set! list-length (- list-length 1))
((lambda (x) x) (set! list-length (- list-length 1))))
(if (< position (- list-length position))
(begin
(set! first (next-index first))
(shift-right first (list-index position)))
(shift-left (list-index position) (last)))
#t))))
(replace (lambda (position element)
(if (< list-length position)
#f
(begin
(<change>
(vector-set! content (list-index position) element)
#t)
(<change>
#t
(vector-set! content (list-index position) element))))))
(dispatch (lambda (m . args)
(if (eq? m 'empty?)
(empty?)
(if (eq? m 'insert)
(insert (car args) (cadr args))
(if (eq? m 'delete)
(delete (car args))
(if (eq? m 'retrieve)
(retrieve (car args))
(if (eq? m 'replace)
(replace (car args) (cadr args))
(error "unknown request -- create-list" m)))))))))
dispatch))))))
(L (create-list 6)))
(<change>
()
(display 1))
(equal?
(list
(L 'insert 1 7)
(L 'insert 1 99)
(L 'retrieve 1)
(L 'retrieve 2)
(L 'delete 2)
(L 'replace 1 111)
(L 'retrieve 1)
(L 'empty?)
(L 'delete 1)
(L 'empty?))
(__toplevel_cons
#t
(__toplevel_cons
#t
(__toplevel_cons
99
(__toplevel_cons
7
(__toplevel_cons
#t
(__toplevel_cons
#t
(__toplevel_cons 111 (__toplevel_cons #f (__toplevel_cons #t (__toplevel_cons #t ())))))))))))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_ad_list-3.scm | scheme | Changes:
* swapped branches: 0 | * removed : 0
* added : 2
* swaps : 2
* negated predicates : 1
* calls to i d fun : 3
(letrec ((create-list (lambda size
(<change>
(let* ((list-size (if (null? size) 10 (car size)))
(content (make-vector list-size 0))
(first 0)
(list-length 0))
(letrec ((last (lambda ()
(remainder (+ first list-length) list-size)))
(next-index (lambda (index)
(remainder (+ index 1) list-size)))
(prev-index (lambda (index)
(remainder (+ index -1 list-size) list-size)))
(list-index (lambda (position)
(remainder (+ first position -1) list-size)))
(shift-right (lambda (start end)
(letrec ((shift-iter (lambda (index)
(if (= index start)
(vector-set! content (next-index start) (vector-ref content start))
(begin
(vector-set! content (next-index index) (vector-ref content index))
(shift-iter (prev-index index)))))))
(shift-iter end))))
(shift-left (lambda (start end)
(letrec ((shift-iter (lambda (index)
(if (= index end)
(vector-set! content (prev-index end) (vector-ref content end))
(begin
(vector-set! content (prev-index index) (vector-ref content index))
(shift-iter (next-index index)))))))
(shift-iter start))))
(empty? (lambda ()
(zero? list-length)))
(retrieve (lambda (position)
(if (< list-length position)
#f
(vector-ref content (list-index position)))))
(insert (lambda (position element)
(if (< position 1)
#f
(if (>= list-length list-size)
#f
(if (> position (+ list-length 1))
#f
(begin
(set! list-length (+ 1 list-length))
(if (< position (- list-length position))
(begin
(set! first (prev-index first))
(shift-left first (list-index position)))
(shift-right (list-index position) (last)))
(vector-set! content (list-index position) element)
#t))))))
(delete (lambda (position)
(if (< list-length position)
#f
(begin
(set! list-length (- list-length 1))
(if (< position (- list-length position))
(begin
(set! first (next-index first))
(shift-right first (list-index position)))
(shift-left (list-index position) (last)))
#t))))
(replace (lambda (position element)
(if (< list-length position)
#f
(begin
(vector-set! content (list-index position) element)
#t))))
(dispatch (lambda (m . args)
(if (eq? m 'empty?)
(empty?)
(if (eq? m 'insert)
(insert (car args) (cadr args))
(if (eq? m 'delete)
(delete (car args))
(if (eq? m 'retrieve)
(retrieve (car args))
(if (eq? m 'replace)
(replace (car args) (cadr args))
(error "unknown request -- create-list" m)))))))))
dispatch))
((lambda (x) x)
(let* ((list-size (if (null? size) 10 (car size)))
(content (make-vector list-size 0))
(first 0)
(list-length 0))
(letrec ((last (lambda ()
(remainder (+ first list-length) list-size)))
(next-index (lambda (index)
(remainder (+ index 1) list-size)))
(prev-index (lambda (index)
(<change>
()
list-size)
(remainder (+ index -1 list-size) list-size)))
(list-index (lambda (position)
(remainder (+ first position -1) list-size)))
(shift-right (lambda (start end)
(letrec ((shift-iter (lambda (index)
(<change>
(if (= index start)
(vector-set! content (next-index start) (vector-ref content start))
(begin
(vector-set! content (next-index index) (vector-ref content index))
(shift-iter (prev-index index))))
((lambda (x) x)
(if (= index start)
(vector-set! content (next-index start) (vector-ref content start))
(begin
(vector-set! content (next-index index) (vector-ref content index))
(shift-iter (prev-index index)))))))))
(shift-iter end))))
(shift-left (lambda (start end)
(letrec ((shift-iter (lambda (index)
(if (= index end)
(vector-set! content (prev-index end) (vector-ref content end))
(begin
(vector-set! content (prev-index index) (vector-ref content index))
(shift-iter (next-index index)))))))
(shift-iter start))))
(empty? (lambda ()
(zero? list-length)))
(retrieve (lambda (position)
(if (< list-length position)
#f
(vector-ref content (list-index position)))))
(insert (lambda (position element)
(if (< position 1)
#f
(if (>= list-length list-size)
#f
(if (> position (+ list-length 1))
#f
(begin
(set! list-length (+ 1 list-length))
(if (<change> (< position (- list-length position)) (not (< position (- list-length position))))
(begin
(set! first (prev-index first))
(shift-left first (list-index position)))
(shift-right (list-index position) (last)))
(<change>
(vector-set! content (list-index position) element)
#t)
(<change>
#t
(vector-set! content (list-index position) element))))))))
(delete (lambda (position)
(if (< list-length position)
#f
(begin
(<change>
(set! list-length (- list-length 1))
((lambda (x) x) (set! list-length (- list-length 1))))
(if (< position (- list-length position))
(begin
(set! first (next-index first))
(shift-right first (list-index position)))
(shift-left (list-index position) (last)))
#t))))
(replace (lambda (position element)
(if (< list-length position)
#f
(begin
(<change>
(vector-set! content (list-index position) element)
#t)
(<change>
#t
(vector-set! content (list-index position) element))))))
(dispatch (lambda (m . args)
(if (eq? m 'empty?)
(empty?)
(if (eq? m 'insert)
(insert (car args) (cadr args))
(if (eq? m 'delete)
(delete (car args))
(if (eq? m 'retrieve)
(retrieve (car args))
(if (eq? m 'replace)
(replace (car args) (cadr args))
(error "unknown request -- create-list" m)))))))))
dispatch))))))
(L (create-list 6)))
(<change>
()
(display 1))
(equal?
(list
(L 'insert 1 7)
(L 'insert 1 99)
(L 'retrieve 1)
(L 'retrieve 2)
(L 'delete 2)
(L 'replace 1 111)
(L 'retrieve 1)
(L 'empty?)
(L 'delete 1)
(L 'empty?))
(__toplevel_cons
#t
(__toplevel_cons
#t
(__toplevel_cons
99
(__toplevel_cons
7
(__toplevel_cons
#t
(__toplevel_cons
#t
(__toplevel_cons 111 (__toplevel_cons #f (__toplevel_cons #t (__toplevel_cons #t ())))))))))))) |
d38c20ca2b750da3cca04f8fad5a788a19223bd3a17f66e80ba11910f3ae3c4b | arnemileswinter/itc | Format.hs | module Data.Clock.IntervalTree.Format where
import Data.Clock.IntervalTree
-- | pretty print a stamp, mathematical notation like in the original paper.
fmtStamp :: Stamp -> String
fmtStamp (Stamp i e) = "(" <> fmtId i <> ", " <> fmtEv e <> ")"
where
fmtId ITCIdOff = "0"
fmtId ITCIdOn = "1"
fmtId (ITCIdBranch l r) = "(" <> fmtId l <> ", " <> fmtId r <> ")"
fmtEv (ITCEventLeaf n) = show n
fmtEv (ITCEventBranch n l r) = "(" <> show n <> ", " <> fmtEv l <> ", " <> fmtEv r <> ")"
| prints a stamp as a tikz picture for latex usage .
This mostly aided me in visual debugging .
This mostly aided me in visual debugging.
-}
fmtStampTikz :: Stamp -> String
fmtStampTikz (Stamp i e) = fmtIdsTikz i ++ "\n" ++ fmtEventsTikz e
where
tikzWidth, tikzLineHeight :: Double
tikzWidth = 5
tikzLineHeight = 0.25
tikzRect :: Maybe String -> (Double, Double) -> (Double, Double) -> String
tikzRect _ _ (w, h)
| w == 0 = ""
| h == 0 = ""
tikzRect m (x, y) (w, h) =
"\\node[rectangle,draw=black,anchor=north west,"
<> (case m of Just s -> "fill=" <> s <> ","; Nothing -> "")
<> "minimum width="
<> show w
<> "cm"
<> ",minimum height="
<> show h
<> "cm] at ("
<> show x
<> "cm,"
<> show y
<> "cm) {};\n"
fmtIdsTikz :: ITCId -> String
fmtIdsTikz i0 = go 0 tikzWidth i0
where
go oh w ITCIdOn = tikzRect (Just "blue!40!white") (oh, - tikzLineHeight) (w, tikzLineHeight)
go oh w (ITCIdBranch l r) = go oh (w / 2) l <> go (oh + w / 2) (w / 2) r
go _ _ _ = ""
fmtEventsTikz :: ITCEvent -> String
fmtEventsTikz e0 = go tikzWidth 0 (- tikzLineHeight) e0
where
go w oh ov (ITCEventLeaf n) = tikzRect Nothing (oh, ov + (fromIntegral n * tikzLineHeight)) (w, fromIntegral n * tikzLineHeight)
go w oh ov (ITCEventBranch n l r) =
go w oh ov (ITCEventLeaf n)
<> go (w / 2) oh (ov + (fromIntegral n * tikzLineHeight)) l
<> go (w / 2) (oh + w / 2) (ov + (fromIntegral n * tikzLineHeight)) r
| null | https://raw.githubusercontent.com/arnemileswinter/itc/539425dfaed2441c5cdf821487ab39ee50ab41c2/src/Data/Clock/IntervalTree/Format.hs | haskell | | pretty print a stamp, mathematical notation like in the original paper. | module Data.Clock.IntervalTree.Format where
import Data.Clock.IntervalTree
fmtStamp :: Stamp -> String
fmtStamp (Stamp i e) = "(" <> fmtId i <> ", " <> fmtEv e <> ")"
where
fmtId ITCIdOff = "0"
fmtId ITCIdOn = "1"
fmtId (ITCIdBranch l r) = "(" <> fmtId l <> ", " <> fmtId r <> ")"
fmtEv (ITCEventLeaf n) = show n
fmtEv (ITCEventBranch n l r) = "(" <> show n <> ", " <> fmtEv l <> ", " <> fmtEv r <> ")"
| prints a stamp as a tikz picture for latex usage .
This mostly aided me in visual debugging .
This mostly aided me in visual debugging.
-}
fmtStampTikz :: Stamp -> String
fmtStampTikz (Stamp i e) = fmtIdsTikz i ++ "\n" ++ fmtEventsTikz e
where
tikzWidth, tikzLineHeight :: Double
tikzWidth = 5
tikzLineHeight = 0.25
tikzRect :: Maybe String -> (Double, Double) -> (Double, Double) -> String
tikzRect _ _ (w, h)
| w == 0 = ""
| h == 0 = ""
tikzRect m (x, y) (w, h) =
"\\node[rectangle,draw=black,anchor=north west,"
<> (case m of Just s -> "fill=" <> s <> ","; Nothing -> "")
<> "minimum width="
<> show w
<> "cm"
<> ",minimum height="
<> show h
<> "cm] at ("
<> show x
<> "cm,"
<> show y
<> "cm) {};\n"
fmtIdsTikz :: ITCId -> String
fmtIdsTikz i0 = go 0 tikzWidth i0
where
go oh w ITCIdOn = tikzRect (Just "blue!40!white") (oh, - tikzLineHeight) (w, tikzLineHeight)
go oh w (ITCIdBranch l r) = go oh (w / 2) l <> go (oh + w / 2) (w / 2) r
go _ _ _ = ""
fmtEventsTikz :: ITCEvent -> String
fmtEventsTikz e0 = go tikzWidth 0 (- tikzLineHeight) e0
where
go w oh ov (ITCEventLeaf n) = tikzRect Nothing (oh, ov + (fromIntegral n * tikzLineHeight)) (w, fromIntegral n * tikzLineHeight)
go w oh ov (ITCEventBranch n l r) =
go w oh ov (ITCEventLeaf n)
<> go (w / 2) oh (ov + (fromIntegral n * tikzLineHeight)) l
<> go (w / 2) (oh + w / 2) (ov + (fromIntegral n * tikzLineHeight)) r
|
47d64c3858f096177ebc6fd7d248b19ae34ae50a211968326b1fb20505483273 | mylesmegyesi/metis | util_spec.clj | (ns metis.util-spec
(:use
[speclj.core]
[metis.util]))
(describe "utility functions"
(context "blank?"
(it "returns true for an empty string"
(should (blank? "")))
(it "returns true for an empty collection"
(should (blank? [])))
(it "returns false for a non-empty string"
(should-not (blank? "here")))
(it "returns false for a non-empty collection"
(should-not (blank? ["here"])))
)
)
| null | https://raw.githubusercontent.com/mylesmegyesi/metis/44127ac75fb6ce6235a516bf6a6f8a9222e5dd67/spec/metis/util_spec.clj | clojure | (ns metis.util-spec
(:use
[speclj.core]
[metis.util]))
(describe "utility functions"
(context "blank?"
(it "returns true for an empty string"
(should (blank? "")))
(it "returns true for an empty collection"
(should (blank? [])))
(it "returns false for a non-empty string"
(should-not (blank? "here")))
(it "returns false for a non-empty collection"
(should-not (blank? ["here"])))
)
)
| |
f181b9277c81a99bc4a3a00fc826ccdbe0606eb632fb015a1e4428abda9ed4f7 | RedPRL/stagedtt | Conversion.ml | open Core
module S = Syntax
module D = Domain
module I = Inner
exception NotConvertible
open struct
type mode =
| Full
(** When in {!const.Full} mode, the conversion checker will unfold
{i all} {!const.Syntax.Global} values before checking convertability. *)
| Rigid
(** When in {!const.Rigid} mode, we will only unfold {!const.Syntax.Global}
values if their heads don't match. *)
| Flex
(** When in {!const.Flex} mode, we don't unfold {!const.Syntax.Globals}
at all *)
type env =
{ mode : mode;
size : int }
module Eff = Algaeff.Reader.Make (struct type nonrec env = env end)
let get_mode () =
(Eff.read()).mode
let with_mode s f =
Eff.scope (fun env -> {env with mode = s}) f
(* [TODO: Reed M, 28/04/2022] Can we use Lazy.force_val here? *)
let unfold (tm : D.t) : D.t =
match get_mode() with
| Full -> Eval.unfold tm
| _ -> tm
let bind_var (f : D.t * I.t -> 'a) : 'a =
let lvl = (Eff.read()).size in
Eff.scope (fun env -> {env with size = env.size + 1}) @@ fun () ->
f (D.local lvl, I.Local lvl)
(*******************************************************************************
* Equating Values *)
let rec equate (v0 : D.t) (v1 : D.t) : unit =
let mode = get_mode() in
match unfold v0, unfold v1 with
(* Straightforward syntactic checks *)
| D.Neu neu0, D.Neu neu1 ->
equate_neu neu0 neu1
| D.Lam (_, clo0), D.Lam (_, clo1) ->
equate_tm_clo clo0 clo1
| D.Quote v0, D.Quote v1 ->
equate v0 v1
| D.Code code0, D.Code code1 ->
equate_code code0 code1
(* We unfold globals when in Rigid mode before attempting eta-expansion *)
| D.Neu { hd = D.Global(`Unstaged (_, unf, _)); _ }, v
| v, D.Neu { hd = D.Global(`Unstaged (_, unf, _)); _ } when mode = Rigid ->
equate (Lazy.force unf) v
(* When we have a neutral, we need to attempt to eta-expand. *)
| D.Neu neu, tm
| tm, D.Neu neu ->
equate_eta neu tm
| _ -> raise NotConvertible
and equate_field (lbl0, v0) (lbl1, v1) =
if lbl0 = lbl1 then
equate v0 v1
else
raise NotConvertible
(*******************************************************************************
* Equating Types *)
and equate_tp (tp0 : D.tp) (tp1 : D.tp) : unit =
match tp0, tp1 with
| D.Pi (base0, _, fam0), D.Pi (base1, _, fam1) ->
equate_tp base0 base1;
equate_tp_clo fam0 fam1
| D.Univ stage0, D.Univ stage1 when stage0 = stage1 ->
()
| D.Expr tp0, D.Expr tp1 ->
equate_tp tp0 tp1
| D.El code0, D.El code1 ->
equate_code code0 code1
| D.ElNeu neu0, D.ElNeu neu1 ->
equate_neu neu0 neu1
| tp0, tp1 -> equate_eta_tp tp0 tp1
(*******************************************************************************
* Equating Codes *)
and equate_code (code0 : D.code) (code1 : D.code) : unit =
match code0, code1 with
| CodePi (base0, fam0), CodePi (base1, fam1) ->
equate base0 base1;
equate fam0 fam1
| CodeUniv stage0, CodeUniv stage1 when stage0 = stage1 ->
()
| _ -> raise NotConvertible
(*******************************************************************************
* Equating Neutrals *)
and equate_neu (neu0 : D.neu) (neu1 : D.neu) : unit =
match neu0.hd, neu1.hd with
| D.Local ix0, D.Local ix1 when ix0 = ix1 -> ()
| D.Global (`Unstaged (nm0, v0, _)), D.Global (`Unstaged (nm1, v1, _)) ->
equate_globals nm0 nm1 v0 v1 neu0.spine neu1.spine
| _ -> raise NotConvertible
and equate_globals nm0 nm1 v0 v1 spine0 spine1 : unit =
match get_mode() with
| Flex ->
Flex Mode : perform any unfolding at all .
if nm0 = nm1 then
equate_spine spine0 spine1
else
raise NotConvertible
| Rigid ->
Rigid Mode : If the heads match , try to equate the spines without performing
any unfolding . If this fails , we switch into full mode to avoid any further
backtracking .
any unfolding. If this fails, we switch into full mode to avoid any further
backtracking. *)
if nm0 = nm1 then
try
with_mode Flex @@ fun () -> equate_spine spine0 spine1
with NotConvertible ->
with_mode Full @@ fun () -> equate (Lazy.force v0) (Lazy.force v1)
else
equate (Lazy.force v0) (Lazy.force v1)
| Full ->
failwith "The impossible happened! We didn't unfold a global when in Full mode."
and equate_spine (spine0 : D.frm list) (spine1 : D.frm list) : unit =
match spine0, spine1 with
| [], [] -> ()
| (frm0 :: spine0, frm1 :: spine1) ->
equate_frm frm0 frm1;
equate_spine spine0 spine1
| _ -> raise NotConvertible
and equate_frm (frm0 : D.frm) (frm1 : D.frm) : unit =
match frm0, frm1 with
| D.Ap v0, D.Ap v1 ->
equate v0 v1
| D.Splice, D.Splice ->
()
| _ -> raise NotConvertible
(** {1 Equating with Eta Expansion} *)
and equate_eta (neu0 : D.neu) (v1 : D.t) =
match unfold v1 with
| D.Neu neu1 ->
if neu0.hd = neu1.hd then
equate_spine neu0.spine neu1.spine
else
raise NotConvertible
| D.Lam (_, clo) ->
bind_var @@ fun (arg, iarg) ->
let unfold vfn = Eval.do_ap vfn arg iarg in
let stage fn_tm = I.Ap (fn_tm, iarg) in
equate_eta (D.push_frm neu0 (D.Ap arg) ~unfold ~stage) (Eval.inst_tm_clo clo arg)
| D.Quote v1 ->
let unfold = Eval.do_splice in
let stage tm = I.Splice tm in
equate_eta (D.push_frm neu0 D.Splice ~unfold ~stage) v1
| _ -> raise NotConvertible
and equate_eta_tp (tp0 : D.tp) (tp1 : D.tp) =
match tp0, tp1 with
Because we are n't using weak tarski universes , we need to unfold
layers of El here .
layers of El here. *)
| D.El code, tp
| tp, D.El code ->
equate_tp tp (Eval.unfold_el code)
[ TODO : Reed M , 29/04/2022 ] What happens when we try to equate an ElNeu with a type ?
| _ -> raise NotConvertible
(** {1 Equating Closures} *)
and equate_tm_clo clo0 clo1 =
bind_var @@ fun (arg, _) ->
equate (Eval.inst_tm_clo clo0 arg) (Eval.inst_tm_clo clo1 arg)
and equate_tp_clo clo0 clo1 =
bind_var @@ fun (arg, _) ->
equate_tp (Eval.inst_tp_clo clo0 arg) (Eval.inst_tp_clo clo1 arg)
end
(*******************************************************************************
* Public Interface *)
let equate ~size v0 v1 =
Eff.run ~env:{mode = Rigid; size} @@ fun () -> equate v0 v1
let equate_tp ~size tp0 tp1 =
Eff.run ~env:{mode = Rigid; size} @@ fun () -> equate_tp tp0 tp1
| null | https://raw.githubusercontent.com/RedPRL/stagedtt/f88538036b51cebb83ebb0b418ec9b089550275d/lib/nbe/Conversion.ml | ocaml | * When in {!const.Full} mode, the conversion checker will unfold
{i all} {!const.Syntax.Global} values before checking convertability.
* When in {!const.Rigid} mode, we will only unfold {!const.Syntax.Global}
values if their heads don't match.
* When in {!const.Flex} mode, we don't unfold {!const.Syntax.Globals}
at all
[TODO: Reed M, 28/04/2022] Can we use Lazy.force_val here?
******************************************************************************
* Equating Values
Straightforward syntactic checks
We unfold globals when in Rigid mode before attempting eta-expansion
When we have a neutral, we need to attempt to eta-expand.
******************************************************************************
* Equating Types
******************************************************************************
* Equating Codes
******************************************************************************
* Equating Neutrals
* {1 Equating with Eta Expansion}
* {1 Equating Closures}
******************************************************************************
* Public Interface | open Core
module S = Syntax
module D = Domain
module I = Inner
exception NotConvertible
open struct
type mode =
| Full
| Rigid
| Flex
type env =
{ mode : mode;
size : int }
module Eff = Algaeff.Reader.Make (struct type nonrec env = env end)
let get_mode () =
(Eff.read()).mode
let with_mode s f =
Eff.scope (fun env -> {env with mode = s}) f
let unfold (tm : D.t) : D.t =
match get_mode() with
| Full -> Eval.unfold tm
| _ -> tm
let bind_var (f : D.t * I.t -> 'a) : 'a =
let lvl = (Eff.read()).size in
Eff.scope (fun env -> {env with size = env.size + 1}) @@ fun () ->
f (D.local lvl, I.Local lvl)
let rec equate (v0 : D.t) (v1 : D.t) : unit =
let mode = get_mode() in
match unfold v0, unfold v1 with
| D.Neu neu0, D.Neu neu1 ->
equate_neu neu0 neu1
| D.Lam (_, clo0), D.Lam (_, clo1) ->
equate_tm_clo clo0 clo1
| D.Quote v0, D.Quote v1 ->
equate v0 v1
| D.Code code0, D.Code code1 ->
equate_code code0 code1
| D.Neu { hd = D.Global(`Unstaged (_, unf, _)); _ }, v
| v, D.Neu { hd = D.Global(`Unstaged (_, unf, _)); _ } when mode = Rigid ->
equate (Lazy.force unf) v
| D.Neu neu, tm
| tm, D.Neu neu ->
equate_eta neu tm
| _ -> raise NotConvertible
and equate_field (lbl0, v0) (lbl1, v1) =
if lbl0 = lbl1 then
equate v0 v1
else
raise NotConvertible
and equate_tp (tp0 : D.tp) (tp1 : D.tp) : unit =
match tp0, tp1 with
| D.Pi (base0, _, fam0), D.Pi (base1, _, fam1) ->
equate_tp base0 base1;
equate_tp_clo fam0 fam1
| D.Univ stage0, D.Univ stage1 when stage0 = stage1 ->
()
| D.Expr tp0, D.Expr tp1 ->
equate_tp tp0 tp1
| D.El code0, D.El code1 ->
equate_code code0 code1
| D.ElNeu neu0, D.ElNeu neu1 ->
equate_neu neu0 neu1
| tp0, tp1 -> equate_eta_tp tp0 tp1
and equate_code (code0 : D.code) (code1 : D.code) : unit =
match code0, code1 with
| CodePi (base0, fam0), CodePi (base1, fam1) ->
equate base0 base1;
equate fam0 fam1
| CodeUniv stage0, CodeUniv stage1 when stage0 = stage1 ->
()
| _ -> raise NotConvertible
and equate_neu (neu0 : D.neu) (neu1 : D.neu) : unit =
match neu0.hd, neu1.hd with
| D.Local ix0, D.Local ix1 when ix0 = ix1 -> ()
| D.Global (`Unstaged (nm0, v0, _)), D.Global (`Unstaged (nm1, v1, _)) ->
equate_globals nm0 nm1 v0 v1 neu0.spine neu1.spine
| _ -> raise NotConvertible
and equate_globals nm0 nm1 v0 v1 spine0 spine1 : unit =
match get_mode() with
| Flex ->
Flex Mode : perform any unfolding at all .
if nm0 = nm1 then
equate_spine spine0 spine1
else
raise NotConvertible
| Rigid ->
Rigid Mode : If the heads match , try to equate the spines without performing
any unfolding . If this fails , we switch into full mode to avoid any further
backtracking .
any unfolding. If this fails, we switch into full mode to avoid any further
backtracking. *)
if nm0 = nm1 then
try
with_mode Flex @@ fun () -> equate_spine spine0 spine1
with NotConvertible ->
with_mode Full @@ fun () -> equate (Lazy.force v0) (Lazy.force v1)
else
equate (Lazy.force v0) (Lazy.force v1)
| Full ->
failwith "The impossible happened! We didn't unfold a global when in Full mode."
and equate_spine (spine0 : D.frm list) (spine1 : D.frm list) : unit =
match spine0, spine1 with
| [], [] -> ()
| (frm0 :: spine0, frm1 :: spine1) ->
equate_frm frm0 frm1;
equate_spine spine0 spine1
| _ -> raise NotConvertible
and equate_frm (frm0 : D.frm) (frm1 : D.frm) : unit =
match frm0, frm1 with
| D.Ap v0, D.Ap v1 ->
equate v0 v1
| D.Splice, D.Splice ->
()
| _ -> raise NotConvertible
and equate_eta (neu0 : D.neu) (v1 : D.t) =
match unfold v1 with
| D.Neu neu1 ->
if neu0.hd = neu1.hd then
equate_spine neu0.spine neu1.spine
else
raise NotConvertible
| D.Lam (_, clo) ->
bind_var @@ fun (arg, iarg) ->
let unfold vfn = Eval.do_ap vfn arg iarg in
let stage fn_tm = I.Ap (fn_tm, iarg) in
equate_eta (D.push_frm neu0 (D.Ap arg) ~unfold ~stage) (Eval.inst_tm_clo clo arg)
| D.Quote v1 ->
let unfold = Eval.do_splice in
let stage tm = I.Splice tm in
equate_eta (D.push_frm neu0 D.Splice ~unfold ~stage) v1
| _ -> raise NotConvertible
and equate_eta_tp (tp0 : D.tp) (tp1 : D.tp) =
match tp0, tp1 with
Because we are n't using weak tarski universes , we need to unfold
layers of El here .
layers of El here. *)
| D.El code, tp
| tp, D.El code ->
equate_tp tp (Eval.unfold_el code)
[ TODO : Reed M , 29/04/2022 ] What happens when we try to equate an ElNeu with a type ?
| _ -> raise NotConvertible
and equate_tm_clo clo0 clo1 =
bind_var @@ fun (arg, _) ->
equate (Eval.inst_tm_clo clo0 arg) (Eval.inst_tm_clo clo1 arg)
and equate_tp_clo clo0 clo1 =
bind_var @@ fun (arg, _) ->
equate_tp (Eval.inst_tp_clo clo0 arg) (Eval.inst_tp_clo clo1 arg)
end
let equate ~size v0 v1 =
Eff.run ~env:{mode = Rigid; size} @@ fun () -> equate v0 v1
let equate_tp ~size tp0 tp1 =
Eff.run ~env:{mode = Rigid; size} @@ fun () -> equate_tp tp0 tp1
|
03afa4b2d170a9487169d793e3c3717fd9868bceead0e3f761fc41b151cb4f2e | mhallin/graphql_ppx | discover.ml | module C = Configurator.V1
let () =
C.main ~name:"graphql_ppx" (fun c ->
let system = C.ocaml_config_var_exn c "system" in
let flags = if system = "linux" then ["-ccopt"; "-static"] else [] in
C.Flags.write_sexp "dune.flags" flags)
| null | https://raw.githubusercontent.com/mhallin/graphql_ppx/5796b3759bdf0d29112f48e43a2f0623f7466e8a/discover/discover.ml | ocaml | module C = Configurator.V1
let () =
C.main ~name:"graphql_ppx" (fun c ->
let system = C.ocaml_config_var_exn c "system" in
let flags = if system = "linux" then ["-ccopt"; "-static"] else [] in
C.Flags.write_sexp "dune.flags" flags)
| |
8d145088e4293b194f662a5c39d1aeddfc0578ab2eba8ecfb67d431d26727a60 | nasa/Common-Metadata-Repository | granule.clj | (ns cmr.sizing.granule
(:require
[clojure.data.xml :as xml]
[cmr.sizing.util :as util]
[xml-in.core :as xml-in]))
(defn extract-size-data
[parsed-xml]
(-> parsed-xml
(xml-in/find-first [:Granule :DataGranule :SizeMBDataGranule])
first
read-string
util/mb->bytes))
(defn file-size
"Returns granule file size in bytes."
[xml-metadata]
(-> xml-metadata
xml/parse-str
extract-size-data))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/ses-plugin/src/cmr/sizing/granule.clj | clojure | (ns cmr.sizing.granule
(:require
[clojure.data.xml :as xml]
[cmr.sizing.util :as util]
[xml-in.core :as xml-in]))
(defn extract-size-data
[parsed-xml]
(-> parsed-xml
(xml-in/find-first [:Granule :DataGranule :SizeMBDataGranule])
first
read-string
util/mb->bytes))
(defn file-size
"Returns granule file size in bytes."
[xml-metadata]
(-> xml-metadata
xml/parse-str
extract-size-data))
| |
ad31203fba1fb4aae61b67138678518f71e2bcbbb867f607bd0afb5918cf1d72 | gedge-platform/gedge-platform | rabbit_error_logger_handler.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_error_logger_handler).
-behaviour(gen_event).
%% API
-export([start_link/0, add_handler/0]).
%% gen_event callbacks
-export([init/1, handle_event/2, handle_call/2,
handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {report = []}).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Creates an event manager
%%
( ) - > { ok , Pid } | { error , Error }
%% @end
%%--------------------------------------------------------------------
start_link() ->
gen_event:start_link({local, ?SERVER}).
%%--------------------------------------------------------------------
%% @doc
%% Adds an event handler
%%
@spec add_handler ( ) - > ok | { ' EXIT ' , Reason } | term ( )
%% @end
%%--------------------------------------------------------------------
add_handler() ->
gen_event:add_handler(?SERVER, ?MODULE, []).
%%%===================================================================
%%% gen_event callbacks
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% Whenever a new event handler is added to an event manager,
%% this function is called to initialize the event handler.
%%
) - > { ok , State }
%% @end
%%--------------------------------------------------------------------
init([]) ->
{ok, #state{}}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Whenever an event manager receives an event sent using
%% gen_event:notify/2 or gen_event:sync_notify/2, this function is
%% called for each installed event handler to handle the event.
%%
@spec handle_event(Event , State ) - >
%% {ok, State} |
{ swap_handler , Args1 , State1 , Mod2 , Args2 } |
%% remove_handler
%% @end
%%--------------------------------------------------------------------
handle_event({info_report, _Gleader, {_Pid, _Type,
{net_kernel, {'EXIT', _, Reason}}}},
#state{report = Report} = State) ->
NewReport = case format(Reason) of
[] -> Report;
Formatted -> [Formatted | Report]
end,
{ok, State#state{report = NewReport}};
handle_event(_Event, State) ->
{ok, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Whenever an event manager receives a request sent using
%% gen_event:call/3,4, this function is called for the specified
%% event handler to handle the request.
%%
, State ) - >
%% {ok, Reply, State} |
{ swap_handler , Reply , Args1 , State1 , Mod2 , Args2 } |
%% {remove_handler, Reply}
%% @end
%%--------------------------------------------------------------------
handle_call(get_connection_report, State) ->
{ok, lists:reverse(State#state.report), State#state{report = []}};
handle_call(_Request, State) ->
Reply = ok,
{ok, Reply, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% This function is called for each installed event handler when
%% an event manager receives any other message than an event or a
%% synchronous request (or a system message).
%%
, State ) - >
%% {ok, State} |
{ swap_handler , Args1 , State1 , Mod2 , Args2 } |
%% remove_handler
%% @end
%%--------------------------------------------------------------------
handle_info(_Info, State) ->
{ok, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Whenever an event handler is deleted from an event manager, this
%% function is called. It should be the opposite of Module:init/1 and
%% do any necessary cleaning up.
%%
, State ) - > void ( )
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
@private
%% @doc
%% Convert process state when code is changed
%%
, State , Extra ) - > { ok , NewState }
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
format({check_dflag_xnc_failed, _What}) ->
{" * Remote node uses an incompatible Erlang version ~n", []};
format({recv_challenge_failed, no_node, Node}) ->
{" * Node name (or hostname) mismatch: node ~p believes its node name is not ~p but something else.~n"
" All nodes and CLI tools must refer to node ~p using the same name the node itself uses (see its logs to find out what it is)~n",
[Node, Node, Node]};
format({recv_challenge_failed, Error}) ->
{" * Distribution failed unexpectedly while waiting for challenge: ~p~n", [Error]};
format({recv_challenge_ack_failed, bad_cookie}) ->
{" * Authentication failed (rejected by the local node), please check the Erlang cookie~n", []};
format({recv_challenge_ack_failed, {error, closed}}) ->
{" * Authentication failed (rejected by the remote node), please check the Erlang cookie~n", []};
format({recv_status_failed, not_allowed}) ->
{" * This node is not on the list of nodes authorised by remote node (see net_kernel:allow/1)~n", []};
format({recv_status_failed, {error, closed}}) ->
{" * Remote host closed TCP connection before completing authentication. Is the Erlang distribution using TLS?~n", []};
format(setup_timer_timeout) ->
{" * TCP connection to remote host has timed out. Is the Erlang distribution using TLS?~n", []};
format(_) ->
[].
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit_common/src/rabbit_error_logger_handler.erl | erlang |
API
gen_event callbacks
===================================================================
API
===================================================================
--------------------------------------------------------------------
@doc
Creates an event manager
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Adds an event handler
@end
--------------------------------------------------------------------
===================================================================
gen_event callbacks
===================================================================
--------------------------------------------------------------------
@doc
Whenever a new event handler is added to an event manager,
this function is called to initialize the event handler.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Whenever an event manager receives an event sent using
gen_event:notify/2 or gen_event:sync_notify/2, this function is
called for each installed event handler to handle the event.
{ok, State} |
remove_handler
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Whenever an event manager receives a request sent using
gen_event:call/3,4, this function is called for the specified
event handler to handle the request.
{ok, Reply, State} |
{remove_handler, Reply}
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
This function is called for each installed event handler when
an event manager receives any other message than an event or a
synchronous request (or a system message).
{ok, State} |
remove_handler
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Whenever an event handler is deleted from an event manager, this
function is called. It should be the opposite of Module:init/1 and
do any necessary cleaning up.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Convert process state when code is changed
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_error_logger_handler).
-behaviour(gen_event).
-export([start_link/0, add_handler/0]).
-export([init/1, handle_event/2, handle_call/2,
handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {report = []}).
( ) - > { ok , Pid } | { error , Error }
start_link() ->
gen_event:start_link({local, ?SERVER}).
@spec add_handler ( ) - > ok | { ' EXIT ' , Reason } | term ( )
add_handler() ->
gen_event:add_handler(?SERVER, ?MODULE, []).
@private
) - > { ok , State }
init([]) ->
{ok, #state{}}.
@private
@spec handle_event(Event , State ) - >
{ swap_handler , Args1 , State1 , Mod2 , Args2 } |
handle_event({info_report, _Gleader, {_Pid, _Type,
{net_kernel, {'EXIT', _, Reason}}}},
#state{report = Report} = State) ->
NewReport = case format(Reason) of
[] -> Report;
Formatted -> [Formatted | Report]
end,
{ok, State#state{report = NewReport}};
handle_event(_Event, State) ->
{ok, State}.
@private
, State ) - >
{ swap_handler , Reply , Args1 , State1 , Mod2 , Args2 } |
handle_call(get_connection_report, State) ->
{ok, lists:reverse(State#state.report), State#state{report = []}};
handle_call(_Request, State) ->
Reply = ok,
{ok, Reply, State}.
@private
, State ) - >
{ swap_handler , Args1 , State1 , Mod2 , Args2 } |
handle_info(_Info, State) ->
{ok, State}.
@private
, State ) - > void ( )
terminate(_Reason, _State) ->
ok.
@private
, State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
format({check_dflag_xnc_failed, _What}) ->
{" * Remote node uses an incompatible Erlang version ~n", []};
format({recv_challenge_failed, no_node, Node}) ->
{" * Node name (or hostname) mismatch: node ~p believes its node name is not ~p but something else.~n"
" All nodes and CLI tools must refer to node ~p using the same name the node itself uses (see its logs to find out what it is)~n",
[Node, Node, Node]};
format({recv_challenge_failed, Error}) ->
{" * Distribution failed unexpectedly while waiting for challenge: ~p~n", [Error]};
format({recv_challenge_ack_failed, bad_cookie}) ->
{" * Authentication failed (rejected by the local node), please check the Erlang cookie~n", []};
format({recv_challenge_ack_failed, {error, closed}}) ->
{" * Authentication failed (rejected by the remote node), please check the Erlang cookie~n", []};
format({recv_status_failed, not_allowed}) ->
{" * This node is not on the list of nodes authorised by remote node (see net_kernel:allow/1)~n", []};
format({recv_status_failed, {error, closed}}) ->
{" * Remote host closed TCP connection before completing authentication. Is the Erlang distribution using TLS?~n", []};
format(setup_timer_timeout) ->
{" * TCP connection to remote host has timed out. Is the Erlang distribution using TLS?~n", []};
format(_) ->
[].
|
314ac5eb8e6b1e34f004d10a53e1cfbea9d549d08d0db0d8ec983d31418cf305 | valpackett/octohipster | link_spec.clj | (ns octohipster.link-spec
(:use [speclj core]
[ring.mock request]
[octohipster.link header]))
(describe "make-link-header"
(it "makes the link header"
(should= (make-link-header []) nil)
(should= (make-link-header [{:href "/hello" :rel "next"}])
"</hello>; rel=\"next\"")
(should= (make-link-header [{:href "/hello" :rel "next"}
{:href "/test" :rel "root" :title "thingy"}])
"</hello>; rel=\"next\", </test>; title=\"thingy\" rel=\"root\"")))
(describe "wrap-link-header"
(it "does not return the header when there are no :links"
(let [app (wrap-link-header (fn [req] {:status 200 :headers {} :links [] :body ""}))]
(should= (get (-> (request :get "/") app :headers) "Link") nil)))
(it "returns the header when there are :links"
(let [app (wrap-link-header (fn [req] {:status 200 :headers {} :links [{:rel "a" :href "b"}] :body ""}))]
(should= (get (-> (request :get "/") app :headers) "Link") "<b>; rel=\"a\""))))
| null | https://raw.githubusercontent.com/valpackett/octohipster/4c1d210643940576eed42a194f810c5c719da63f/spec/octohipster/link_spec.clj | clojure | (ns octohipster.link-spec
(:use [speclj core]
[ring.mock request]
[octohipster.link header]))
(describe "make-link-header"
(it "makes the link header"
(should= (make-link-header []) nil)
(should= (make-link-header [{:href "/hello" :rel "next"}])
"</hello>; rel=\"next\"")
(should= (make-link-header [{:href "/hello" :rel "next"}
{:href "/test" :rel "root" :title "thingy"}])
"</hello>; rel=\"next\", </test>; title=\"thingy\" rel=\"root\"")))
(describe "wrap-link-header"
(it "does not return the header when there are no :links"
(let [app (wrap-link-header (fn [req] {:status 200 :headers {} :links [] :body ""}))]
(should= (get (-> (request :get "/") app :headers) "Link") nil)))
(it "returns the header when there are :links"
(let [app (wrap-link-header (fn [req] {:status 200 :headers {} :links [{:rel "a" :href "b"}] :body ""}))]
(should= (get (-> (request :get "/") app :headers) "Link") "<b>; rel=\"a\""))))
| |
d5f5e7e72ca484d442b6941b9bf11a0f754f361a6b8ba18cbb054cae2b165662 | SchornacklabSLCU/amfinder | imgAnnotations.ml | AMFinder - img / imgAnnotations.ml
*
* MIT License
* Copyright ( c ) 2021
*
* 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 .
*
* MIT License
* Copyright (c) 2021 Edouard Evangelisti
*
* 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 Scanf
open Printf
open Morelib
class type cls = object
method get : r:int -> c:int -> unit -> AmfAnnot.annot
method iter : (r:int -> c:int -> AmfAnnot.annot -> unit) -> unit
method iter_layer : char -> (r:int -> c:int -> AmfAnnot.annot -> unit) -> unit
method statistics : ?level:AmfLevel.level -> unit -> (char * int) list
method has_annot : ?level:AmfLevel.level -> r:int -> c:int -> unit -> bool
method dump : Zip.out_file -> unit
end
module Aux = struct
let of_string data =
String.split_on_char '\n' data
|> List.map (String.split_on_char '\t')
|> Array.of_list
|> Array.map Array.of_list
let to_string level data =
Matrix.map (fun (annot : AmfAnnot.annot) ->
annot#get ~level ()
|> CSet.to_seq
|> String.of_seq
) data
|> Array.map Array.to_list
|> Array.map (String.concat "\t")
|> Array.to_list
|> String.concat "\n"
let to_python level (data : AmfAnnot.annot Matrix.t) =
let rows = Array.length data
and columns = Array.length data.(0) in
let buf = Buffer.create 100 in
for i = 0 to rows * columns - 1 do
let r = i / columns and c = i mod columns in
let mask = data.(r).(c) in
if mask#has_annot ~level () then
bprintf buf "%d\t%d\t%s\n" r c
(mask#hot ~level ()
|> List.map string_of_int
|> String.concat "\t")
done;
let res = Buffer.contents buf in
if String.length res = 0 then None else
let header = sprintf "row\tcol\t%s\n" (
AmfLevel.to_header level
|> List.map (String.make 1)
|> String.concat "\t"
) in Some (String.trim (header ^ res))
end
class annotations (source : ImgSource.cls) root_segm ir_struct =
let table =
match root_segm with
| None -> let r = source#rows and c = source#columns in
Matrix.init ~r ~c (fun ~r:_ ~c:_ -> AmfAnnot.create ())
| Some root_segm -> let seg = Aux.of_string root_segm in
match ir_struct with
| None -> Matrix.map AmfAnnot.of_string seg
| Some myc ->
Matrix.map2 (fun rs is ->
AmfAnnot.of_string (rs ^ is)
) seg (Aux.of_string myc)
in
object (self)
method get ~r ~c () = Matrix.get table ~r ~c
method has_annot ?level ~r ~c () = (self#get ~r ~c ())#has_annot ?level ()
method iter f = Matrix.iteri f table
method iter_layer layer f =
let has_layer = match layer with
| '*' -> (fun (mask : AmfAnnot.annot) -> CSet.cardinal (mask#get ()) > 0)
| chr -> (fun (mask : AmfAnnot.annot) -> CSet.mem chr (mask#get ()))
in
Matrix.iteri (fun ~r ~c annot ->
if has_layer annot then f ~r ~c annot
) table
method statistics ?(level = AmfUI.Levels.current ()) () =
let counters = AmfLevel.to_header level
|> List.map (fun c -> c, ref 0) in
self#iter (fun ~r:_ ~c:_ (mask : AmfAnnot.annot) ->
CSet.iter (fun chr ->
incr (List.assoc chr counters)
) (mask#get ~level ())
);
List.map (fun (c, r) -> c, !r) counters
method dump och =
List.iter (fun level ->
let file = AmfLevel.to_string level
|> sprintf "annotations/%s.caml" in
Zip.add_entry (Aux.to_string level table) och file;
Create Python table for use with Python amf scripts .
match Aux.to_python level table with
| None -> ()
| Some data -> let lvl_string = AmfLevel.to_string level in
Zip.add_entry data och (sprintf "%s.tsv" lvl_string)
) AmfLevel.all
end
let retrieve_annotations ich entries =
let root_segm = ref None and ir_struct = ref None in
List.iter (fun entry ->
let path = entry.Zip.filename in
if Filename.dirname path = "annotations" then
match Filename.basename path with
| "col.caml" -> root_segm := Some (Zip.read_entry ich entry)
| "myc.caml" -> ir_struct := Some (Zip.read_entry ich entry)
| any -> AmfLog.error ~code:Err.Image.unknown_annotation_file
"Unknown annotation file %S" any
) entries;
(!root_segm, !ir_struct)
let create ?zip source =
match zip with
| None -> new annotations source None None
| Some ich -> let entries = Zip.entries ich in
match retrieve_annotations ich entries with
| None, _ -> new annotations source None None
| root_segm, ir_struct -> new annotations source root_segm ir_struct
| null | https://raw.githubusercontent.com/SchornacklabSLCU/amfinder/1053045b431b9e9e85a7bcebea2e38cda92a8dcd/amfbrowser/sources/img/imgAnnotations.ml | ocaml | AMFinder - img / imgAnnotations.ml
*
* MIT License
* Copyright ( c ) 2021
*
* 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 .
*
* MIT License
* Copyright (c) 2021 Edouard Evangelisti
*
* 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 Scanf
open Printf
open Morelib
class type cls = object
method get : r:int -> c:int -> unit -> AmfAnnot.annot
method iter : (r:int -> c:int -> AmfAnnot.annot -> unit) -> unit
method iter_layer : char -> (r:int -> c:int -> AmfAnnot.annot -> unit) -> unit
method statistics : ?level:AmfLevel.level -> unit -> (char * int) list
method has_annot : ?level:AmfLevel.level -> r:int -> c:int -> unit -> bool
method dump : Zip.out_file -> unit
end
module Aux = struct
let of_string data =
String.split_on_char '\n' data
|> List.map (String.split_on_char '\t')
|> Array.of_list
|> Array.map Array.of_list
let to_string level data =
Matrix.map (fun (annot : AmfAnnot.annot) ->
annot#get ~level ()
|> CSet.to_seq
|> String.of_seq
) data
|> Array.map Array.to_list
|> Array.map (String.concat "\t")
|> Array.to_list
|> String.concat "\n"
let to_python level (data : AmfAnnot.annot Matrix.t) =
let rows = Array.length data
and columns = Array.length data.(0) in
let buf = Buffer.create 100 in
for i = 0 to rows * columns - 1 do
let r = i / columns and c = i mod columns in
let mask = data.(r).(c) in
if mask#has_annot ~level () then
bprintf buf "%d\t%d\t%s\n" r c
(mask#hot ~level ()
|> List.map string_of_int
|> String.concat "\t")
done;
let res = Buffer.contents buf in
if String.length res = 0 then None else
let header = sprintf "row\tcol\t%s\n" (
AmfLevel.to_header level
|> List.map (String.make 1)
|> String.concat "\t"
) in Some (String.trim (header ^ res))
end
class annotations (source : ImgSource.cls) root_segm ir_struct =
let table =
match root_segm with
| None -> let r = source#rows and c = source#columns in
Matrix.init ~r ~c (fun ~r:_ ~c:_ -> AmfAnnot.create ())
| Some root_segm -> let seg = Aux.of_string root_segm in
match ir_struct with
| None -> Matrix.map AmfAnnot.of_string seg
| Some myc ->
Matrix.map2 (fun rs is ->
AmfAnnot.of_string (rs ^ is)
) seg (Aux.of_string myc)
in
object (self)
method get ~r ~c () = Matrix.get table ~r ~c
method has_annot ?level ~r ~c () = (self#get ~r ~c ())#has_annot ?level ()
method iter f = Matrix.iteri f table
method iter_layer layer f =
let has_layer = match layer with
| '*' -> (fun (mask : AmfAnnot.annot) -> CSet.cardinal (mask#get ()) > 0)
| chr -> (fun (mask : AmfAnnot.annot) -> CSet.mem chr (mask#get ()))
in
Matrix.iteri (fun ~r ~c annot ->
if has_layer annot then f ~r ~c annot
) table
method statistics ?(level = AmfUI.Levels.current ()) () =
let counters = AmfLevel.to_header level
|> List.map (fun c -> c, ref 0) in
self#iter (fun ~r:_ ~c:_ (mask : AmfAnnot.annot) ->
CSet.iter (fun chr ->
incr (List.assoc chr counters)
) (mask#get ~level ())
);
List.map (fun (c, r) -> c, !r) counters
method dump och =
List.iter (fun level ->
let file = AmfLevel.to_string level
|> sprintf "annotations/%s.caml" in
Zip.add_entry (Aux.to_string level table) och file;
Create Python table for use with Python amf scripts .
match Aux.to_python level table with
| None -> ()
| Some data -> let lvl_string = AmfLevel.to_string level in
Zip.add_entry data och (sprintf "%s.tsv" lvl_string)
) AmfLevel.all
end
let retrieve_annotations ich entries =
let root_segm = ref None and ir_struct = ref None in
List.iter (fun entry ->
let path = entry.Zip.filename in
if Filename.dirname path = "annotations" then
match Filename.basename path with
| "col.caml" -> root_segm := Some (Zip.read_entry ich entry)
| "myc.caml" -> ir_struct := Some (Zip.read_entry ich entry)
| any -> AmfLog.error ~code:Err.Image.unknown_annotation_file
"Unknown annotation file %S" any
) entries;
(!root_segm, !ir_struct)
let create ?zip source =
match zip with
| None -> new annotations source None None
| Some ich -> let entries = Zip.entries ich in
match retrieve_annotations ich entries with
| None, _ -> new annotations source None None
| root_segm, ir_struct -> new annotations source root_segm ir_struct
| |
d6bf87e3c60e665d4d19c0438bbc7741fb8db906b43f898aca86df103e807bff | lukaszcz/coinduction | cNorm.mli | (* Proof normalization *)
(* Proof normalization with beta *)
val norm_beta : Evd.evar_map -> EConstr.t -> EConstr.t
(* Proof normalization with beta-iota-zeta and head-delta *)
val norm : Evd.evar_map -> EConstr.t -> EConstr.t
| null | https://raw.githubusercontent.com/lukaszcz/coinduction/b7437fe155a45f93042a5788dc62512534172dcd/src/cNorm.mli | ocaml | Proof normalization
Proof normalization with beta
Proof normalization with beta-iota-zeta and head-delta |
val norm_beta : Evd.evar_map -> EConstr.t -> EConstr.t
val norm : Evd.evar_map -> EConstr.t -> EConstr.t
|
187f5e9784503439af73cd211f87b10ea300496df58f375973259f730c03edfd | facebook/infer | llvm.ml | = = = -- / llvm.ml - LLVM OCaml Interface -------------------------------=== *
*
* Part of the LLVM Project , under the Apache License v2.0 with LLVM Exceptions .
* See for license information .
* SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception
*
* = = = ----------------------------------------------------------------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
type llcontext
type llmodule
type llmetadata
type lltype
type llvalue
type lluse
type llbasicblock
type llbuilder
type llattrkind
type llattribute
type llmemorybuffer
type llmdkind
exception FeatureDisabled of string
let () = Callback.register_exception "Llvm.FeatureDisabled" (FeatureDisabled "")
module TypeKind = struct
type t =
| Void
| Half
| Float
| Double
| X86fp80
| Fp128
| Ppc_fp128
| Label
| Integer
| Function
| Struct
| Array
| Pointer
| Vector
| Metadata
| X86_mmx
| Token
| ScalableVector
| BFloat
| X86_amx
end
module Linkage = struct
type t =
| External
| Available_externally
| Link_once
| Link_once_odr
| Link_once_odr_auto_hide
| Weak
| Weak_odr
| Appending
| Internal
| Private
| Dllimport
| Dllexport
| External_weak
| Ghost
| Common
| Linker_private
| Linker_private_weak
end
module Visibility = struct
type t =
| Default
| Hidden
| Protected
end
module DLLStorageClass = struct
type t =
| Default
| DLLImport
| DLLExport
end
module CallConv = struct
let c = 0
let fast = 8
let cold = 9
let x86_stdcall = 64
let x86_fastcall = 65
end
module AttrRepr = struct
type t =
| Enum of llattrkind * int64
| String of string * string
end
module AttrIndex = struct
type t =
| Function
| Return
| Param of int
let to_int index =
match index with
| Function -> -1
| Return -> 0
| Param(n) -> 1 + n
end
module Attribute = struct
type t =
| Zext
| Sext
| Noreturn
| Inreg
| Structret
| Nounwind
| Noalias
| Byval
| Nest
| Readnone
| Readonly
| Noinline
| Alwaysinline
| Optsize
| Ssp
| Sspreq
| Alignment of int
| Nocapture
| Noredzone
| Noimplicitfloat
| Naked
| Inlinehint
| Stackalignment of int
| ReturnsTwice
| UWTable
| NonLazyBind
end
module Icmp = struct
type t =
| Eq
| Ne
| Ugt
| Uge
| Ult
| Ule
| Sgt
| Sge
| Slt
| Sle
end
module Fcmp = struct
type t =
| False
| Oeq
| Ogt
| Oge
| Olt
| Ole
| One
| Ord
| Uno
| Ueq
| Ugt
| Uge
| Ult
| Ule
| Une
| True
end
module Opcode = struct
type t =
| Invalid (* not an instruction *)
(* Terminator Instructions *)
| Ret
| Br
| Switch
| IndirectBr
| Invoke
| Invalid2
| Unreachable
Standard Binary Operators
| Add
| FAdd
| Sub
| FSub
| Mul
| FMul
| UDiv
| SDiv
| FDiv
| URem
| SRem
| FRem
(* Logical Operators *)
| Shl
| LShr
| AShr
| And
| Or
| Xor
(* Memory Operators *)
| Alloca
| Load
| Store
| GetElementPtr
Cast Operators
| Trunc
| ZExt
| SExt
| FPToUI
| FPToSI
| UIToFP
| SIToFP
| FPTrunc
| FPExt
| PtrToInt
| IntToPtr
| BitCast
(* Other Operators *)
| ICmp
| FCmp
| PHI
| Call
| Select
| UserOp1
| UserOp2
| VAArg
| ExtractElement
| InsertElement
| ShuffleVector
| ExtractValue
| InsertValue
| Fence
| AtomicCmpXchg
| AtomicRMW
| Resume
| LandingPad
| AddrSpaceCast
| CleanupRet
| CatchRet
| CatchPad
| CleanupPad
| CatchSwitch
| FNeg
| CallBr
| Freeze
end
module LandingPadClauseTy = struct
type t =
| Catch
| Filter
end
module ThreadLocalMode = struct
type t =
| None
| GeneralDynamic
| LocalDynamic
| InitialExec
| LocalExec
end
module AtomicOrdering = struct
type t =
| NotAtomic
| Unordered
| Monotonic
| Invalid
| Acquire
| Release
| AcqiureRelease
| SequentiallyConsistent
end
module AtomicRMWBinOp = struct
type t =
| Xchg
| Add
| Sub
| And
| Nand
| Or
| Xor
| Max
| Min
| UMax
| UMin
| FAdd
| FSub
end
module ValueKind = struct
type t =
| NullValue
| Argument
| BasicBlock
| InlineAsm
| MDNode
| MDString
| BlockAddress
| ConstantAggregateZero
| ConstantArray
| ConstantDataArray
| ConstantDataVector
| ConstantExpr
| ConstantFP
| ConstantInt
| ConstantPointerNull
| ConstantStruct
| ConstantVector
| Function
| GlobalAlias
| GlobalIFunc
| GlobalVariable
| UndefValue
| PoisonValue
| Instruction of Opcode.t
end
module DiagnosticSeverity = struct
type t =
| Error
| Warning
| Remark
| Note
end
module ModuleFlagBehavior = struct
type t =
| Error
| Warning
| Require
| Override
| Append
| AppendUnique
end
exception IoError of string
let () = Callback.register_exception "Llvm.IoError" (IoError "")
external install_fatal_error_handler : (string -> unit) -> unit
= "llvm_install_fatal_error_handler"
external reset_fatal_error_handler : unit -> unit
= "llvm_reset_fatal_error_handler"
external enable_pretty_stacktrace : unit -> unit
= "llvm_enable_pretty_stacktrace"
external parse_command_line_options : ?overview:string -> string array -> unit
= "llvm_parse_command_line_options"
type ('a, 'b) llpos =
| At_end of 'a
| Before of 'b
type ('a, 'b) llrev_pos =
| At_start of 'a
| After of 'b
(*===-- Context error handling --------------------------------------------===*)
module Diagnostic = struct
type t
external description : t -> string = "llvm_get_diagnostic_description"
external severity : t -> DiagnosticSeverity.t
= "llvm_get_diagnostic_severity"
end
external set_diagnostic_handler
: llcontext -> (Diagnostic.t -> unit) option -> unit
= "llvm_set_diagnostic_handler"
(*===-- Contexts ----------------------------------------------------------===*)
external create_context : unit -> llcontext = "llvm_create_context"
external dispose_context : llcontext -> unit = "llvm_dispose_context"
external global_context : unit -> llcontext = "llvm_global_context"
external mdkind_id : llcontext -> string -> llmdkind = "llvm_mdkind_id"
(*===-- Attributes --------------------------------------------------------===*)
exception UnknownAttribute of string
let () = Callback.register_exception "Llvm.UnknownAttribute"
(UnknownAttribute "")
external enum_attr_kind : string -> llattrkind = "llvm_enum_attr_kind"
external llvm_create_enum_attr : llcontext -> llattrkind -> int64 ->
llattribute
= "llvm_create_enum_attr_by_kind"
external is_enum_attr : llattribute -> bool = "llvm_is_enum_attr"
external get_enum_attr_kind : llattribute -> llattrkind
= "llvm_get_enum_attr_kind"
external get_enum_attr_value : llattribute -> int64
= "llvm_get_enum_attr_value"
external llvm_create_string_attr : llcontext -> string -> string ->
llattribute
= "llvm_create_string_attr"
external is_string_attr : llattribute -> bool = "llvm_is_string_attr"
external get_string_attr_kind : llattribute -> string
= "llvm_get_string_attr_kind"
external get_string_attr_value : llattribute -> string
= "llvm_get_string_attr_value"
let create_enum_attr context name value =
llvm_create_enum_attr context (enum_attr_kind name) value
let create_string_attr context kind value =
llvm_create_string_attr context kind value
let attr_of_repr context repr =
match repr with
| AttrRepr.Enum(kind, value) -> llvm_create_enum_attr context kind value
| AttrRepr.String(key, value) -> llvm_create_string_attr context key value
let repr_of_attr attr =
if is_enum_attr attr then
AttrRepr.Enum(get_enum_attr_kind attr, get_enum_attr_value attr)
else if is_string_attr attr then
AttrRepr.String(get_string_attr_kind attr, get_string_attr_value attr)
else assert false
(*===-- Modules -----------------------------------------------------------===*)
external create_module : llcontext -> string -> llmodule = "llvm_create_module"
external dispose_module : llmodule -> unit = "llvm_dispose_module"
external target_triple: llmodule -> string
= "llvm_target_triple"
external set_target_triple: string -> llmodule -> unit
= "llvm_set_target_triple"
external data_layout: llmodule -> string
= "llvm_data_layout"
external set_data_layout: string -> llmodule -> unit
= "llvm_set_data_layout"
external dump_module : llmodule -> unit = "llvm_dump_module"
external print_module : string -> llmodule -> unit = "llvm_print_module"
external string_of_llmodule : llmodule -> string = "llvm_string_of_llmodule"
external set_module_inline_asm : llmodule -> string -> unit
= "llvm_set_module_inline_asm"
external module_context : llmodule -> llcontext = "LLVMGetModuleContext"
external get_module_identifier : llmodule -> string
= "llvm_get_module_identifier"
external set_module_identifer : llmodule -> string -> unit
= "llvm_set_module_identifier"
external get_module_flag : llmodule -> string -> llmetadata option
= "llvm_get_module_flag"
external add_module_flag : llmodule -> ModuleFlagBehavior.t ->
string -> llmetadata -> unit = "llvm_add_module_flag"
(*===-- Types -------------------------------------------------------------===*)
external classify_type : lltype -> TypeKind.t = "llvm_classify_type"
external type_context : lltype -> llcontext = "llvm_type_context"
external type_is_sized : lltype -> bool = "llvm_type_is_sized"
external dump_type : lltype -> unit = "llvm_dump_type"
external string_of_lltype : lltype -> string = "llvm_string_of_lltype"
-- ... Operations on integer types ........................................ --
external i1_type : llcontext -> lltype = "llvm_i1_type"
external i8_type : llcontext -> lltype = "llvm_i8_type"
external i16_type : llcontext -> lltype = "llvm_i16_type"
external i32_type : llcontext -> lltype = "llvm_i32_type"
external i64_type : llcontext -> lltype = "llvm_i64_type"
external integer_type : llcontext -> int -> lltype = "llvm_integer_type"
external integer_bitwidth : lltype -> int = "llvm_integer_bitwidth"
(*--... Operations on real types ...........................................--*)
external float_type : llcontext -> lltype = "llvm_float_type"
external double_type : llcontext -> lltype = "llvm_double_type"
external x86fp80_type : llcontext -> lltype = "llvm_x86fp80_type"
external fp128_type : llcontext -> lltype = "llvm_fp128_type"
external ppc_fp128_type : llcontext -> lltype = "llvm_ppc_fp128_type"
(*--... Operations on function types .......................................--*)
external function_type : lltype -> lltype array -> lltype = "llvm_function_type"
external var_arg_function_type : lltype -> lltype array -> lltype
= "llvm_var_arg_function_type"
external is_var_arg : lltype -> bool = "llvm_is_var_arg"
external return_type : lltype -> lltype = "LLVMGetReturnType"
external param_types : lltype -> lltype array = "llvm_param_types"
(*--... Operations on struct types .........................................--*)
external struct_type : llcontext -> lltype array -> lltype = "llvm_struct_type"
external packed_struct_type : llcontext -> lltype array -> lltype
= "llvm_packed_struct_type"
external struct_name : lltype -> string option = "llvm_struct_name"
external named_struct_type : llcontext -> string -> lltype =
"llvm_named_struct_type"
external struct_set_body : lltype -> lltype array -> bool -> unit =
"llvm_struct_set_body"
external struct_element_types : lltype -> lltype array
= "llvm_struct_element_types"
external is_packed : lltype -> bool = "llvm_is_packed"
external is_opaque : lltype -> bool = "llvm_is_opaque"
external is_literal : lltype -> bool = "llvm_is_literal"
(*--... Operations on pointer, vector, and array types .....................--*)
external subtypes : lltype -> lltype array = "llvm_subtypes"
external array_type : lltype -> int -> lltype = "llvm_array_type"
external pointer_type : lltype -> lltype = "llvm_pointer_type"
external qualified_pointer_type : lltype -> int -> lltype
= "llvm_qualified_pointer_type"
external vector_type : lltype -> int -> lltype = "llvm_vector_type"
external element_type : lltype -> lltype = "LLVMGetElementType"
external array_length : lltype -> int = "llvm_array_length"
external address_space : lltype -> int = "llvm_address_space"
external vector_size : lltype -> int = "llvm_vector_size"
(*--... Operations on other types ..........................................--*)
external void_type : llcontext -> lltype = "llvm_void_type"
external label_type : llcontext -> lltype = "llvm_label_type"
external x86_mmx_type : llcontext -> lltype = "llvm_x86_mmx_type"
external type_by_name : llmodule -> string -> lltype option = "llvm_type_by_name"
external classify_value : llvalue -> ValueKind.t = "llvm_classify_value"
(*===-- Values ------------------------------------------------------------===*)
external type_of : llvalue -> lltype = "llvm_type_of"
external value_name : llvalue -> string = "llvm_value_name"
external set_value_name : string -> llvalue -> unit = "llvm_set_value_name"
external dump_value : llvalue -> unit = "llvm_dump_value"
external string_of_llvalue : llvalue -> string = "llvm_string_of_llvalue"
external replace_all_uses_with : llvalue -> llvalue -> unit
= "llvm_replace_all_uses_with"
(*--... Operations on uses .................................................--*)
external use_begin : llvalue -> lluse option = "llvm_use_begin"
external use_succ : lluse -> lluse option = "llvm_use_succ"
external user : lluse -> llvalue = "llvm_user"
external used_value : lluse -> llvalue = "llvm_used_value"
let iter_uses f v =
let rec aux = function
| None -> ()
| Some u ->
f u;
aux (use_succ u)
in
aux (use_begin v)
let fold_left_uses f init v =
let rec aux init u =
match u with
| None -> init
| Some u -> aux (f init u) (use_succ u)
in
aux init (use_begin v)
let fold_right_uses f v init =
let rec aux u init =
match u with
| None -> init
| Some u -> f u (aux (use_succ u) init)
in
aux (use_begin v) init
(*--... Operations on users ................................................--*)
external operand : llvalue -> int -> llvalue = "llvm_operand"
external operand_use : llvalue -> int -> lluse = "llvm_operand_use"
external set_operand : llvalue -> int -> llvalue -> unit = "llvm_set_operand"
external num_operands : llvalue -> int = "llvm_num_operands"
external indices : llvalue -> int array = "llvm_indices"
(*--... Operations on constants of (mostly) any type .......................--*)
external is_constant : llvalue -> bool = "llvm_is_constant"
external const_null : lltype -> llvalue = "LLVMConstNull"
external const_pointer_null : lltype -> llvalue = "LLVMConstPointerNull"
external undef : lltype -> llvalue = "LLVMGetUndef"
external poison : lltype -> llvalue = "LLVMGetPoison"
external is_null : llvalue -> bool = "llvm_is_null"
external is_undef : llvalue -> bool = "llvm_is_undef"
external is_poison : llvalue -> bool = "llvm_is_poison"
external constexpr_opcode : llvalue -> Opcode.t = "llvm_constexpr_get_opcode"
(*--... Operations on instructions .........................................--*)
external has_metadata : llvalue -> bool = "llvm_has_metadata"
external metadata : llvalue -> llmdkind -> llvalue option = "llvm_metadata"
external set_metadata : llvalue -> llmdkind -> llvalue -> unit = "llvm_set_metadata"
external clear_metadata : llvalue -> llmdkind -> unit = "llvm_clear_metadata"
(*--... Operations on metadata .......,.....................................--*)
external mdstring : llcontext -> string -> llvalue = "llvm_mdstring"
external mdnode : llcontext -> llvalue array -> llvalue = "llvm_mdnode"
external mdnull : llcontext -> llvalue = "llvm_mdnull"
external get_mdstring : llvalue -> string option = "llvm_get_mdstring"
external get_mdnode_operands : llvalue -> llvalue array
= "llvm_get_mdnode_operands"
external get_named_metadata : llmodule -> string -> llvalue array
= "llvm_get_namedmd"
external add_named_metadata_operand : llmodule -> string -> llvalue -> unit
= "llvm_append_namedmd"
external get_debug_loc_directory : llvalue -> string option = "llvm_get_debug_loc_directory"
external get_debug_loc_filename : llvalue -> string option = "llvm_get_debug_loc_filename"
external get_debug_loc_line : llvalue -> int = "llvm_get_debug_loc_line"
external get_debug_loc_column : llvalue -> int = "llvm_get_debug_loc_column"
external value_as_metadata : llvalue -> llmetadata = "llvm_value_as_metadata"
external metadata_as_value : llcontext -> llmetadata -> llvalue
= "llvm_metadata_as_value"
(*--... Operations on scalar constants .....................................--*)
external const_int : lltype -> int -> llvalue = "llvm_const_int"
external const_of_int64 : lltype -> Int64.t -> bool -> llvalue
= "llvm_const_of_int64"
external int64_of_const : llvalue -> Int64.t option
= "llvm_int64_of_const"
external const_int_of_string : lltype -> string -> int -> llvalue
= "llvm_const_int_of_string"
external const_float : lltype -> float -> llvalue = "llvm_const_float"
external float_of_const : llvalue -> float option
= "llvm_float_of_const"
external const_float_of_string : lltype -> string -> llvalue
= "llvm_const_float_of_string"
(*--... Operations on composite constants ..................................--*)
external const_string : llcontext -> string -> llvalue = "llvm_const_string"
external const_stringz : llcontext -> string -> llvalue = "llvm_const_stringz"
external const_array : lltype -> llvalue array -> llvalue = "llvm_const_array"
external const_struct : llcontext -> llvalue array -> llvalue
= "llvm_const_struct"
external const_named_struct : lltype -> llvalue array -> llvalue
= "llvm_const_named_struct"
external const_packed_struct : llcontext -> llvalue array -> llvalue
= "llvm_const_packed_struct"
external const_vector : llvalue array -> llvalue = "llvm_const_vector"
external string_of_const : llvalue -> string option = "llvm_string_of_const"
external const_element : llvalue -> int -> llvalue = "llvm_const_element"
(*--... Constant expressions ...............................................--*)
external align_of : lltype -> llvalue = "LLVMAlignOf"
external size_of : lltype -> llvalue = "LLVMSizeOf"
external const_neg : llvalue -> llvalue = "LLVMConstNeg"
external const_nsw_neg : llvalue -> llvalue = "LLVMConstNSWNeg"
external const_nuw_neg : llvalue -> llvalue = "LLVMConstNUWNeg"
external const_fneg : llvalue -> llvalue = "LLVMConstFNeg"
external const_not : llvalue -> llvalue = "LLVMConstNot"
external const_add : llvalue -> llvalue -> llvalue = "LLVMConstAdd"
external const_nsw_add : llvalue -> llvalue -> llvalue = "LLVMConstNSWAdd"
external const_nuw_add : llvalue -> llvalue -> llvalue = "LLVMConstNUWAdd"
external const_fadd : llvalue -> llvalue -> llvalue = "LLVMConstFAdd"
external const_sub : llvalue -> llvalue -> llvalue = "LLVMConstSub"
external const_nsw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNSWSub"
external const_nuw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNUWSub"
external const_fsub : llvalue -> llvalue -> llvalue = "LLVMConstFSub"
external const_mul : llvalue -> llvalue -> llvalue = "LLVMConstMul"
external const_nsw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNSWMul"
external const_nuw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNUWMul"
external const_fmul : llvalue -> llvalue -> llvalue = "LLVMConstFMul"
external const_udiv : llvalue -> llvalue -> llvalue = "LLVMConstUDiv"
external const_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstSDiv"
external const_exact_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstExactSDiv"
external const_fdiv : llvalue -> llvalue -> llvalue = "LLVMConstFDiv"
external const_urem : llvalue -> llvalue -> llvalue = "LLVMConstURem"
external const_srem : llvalue -> llvalue -> llvalue = "LLVMConstSRem"
external const_frem : llvalue -> llvalue -> llvalue = "LLVMConstFRem"
external const_and : llvalue -> llvalue -> llvalue = "LLVMConstAnd"
external const_or : llvalue -> llvalue -> llvalue = "LLVMConstOr"
external const_xor : llvalue -> llvalue -> llvalue = "LLVMConstXor"
external const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue
= "llvm_const_icmp"
external const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue
= "llvm_const_fcmp"
external const_shl : llvalue -> llvalue -> llvalue = "LLVMConstShl"
external const_lshr : llvalue -> llvalue -> llvalue = "LLVMConstLShr"
external const_ashr : llvalue -> llvalue -> llvalue = "LLVMConstAShr"
external const_gep : llvalue -> llvalue array -> llvalue = "llvm_const_gep"
external const_in_bounds_gep : llvalue -> llvalue array -> llvalue
= "llvm_const_in_bounds_gep"
external const_trunc : llvalue -> lltype -> llvalue = "LLVMConstTrunc"
external const_sext : llvalue -> lltype -> llvalue = "LLVMConstSExt"
external const_zext : llvalue -> lltype -> llvalue = "LLVMConstZExt"
external const_fptrunc : llvalue -> lltype -> llvalue = "LLVMConstFPTrunc"
external const_fpext : llvalue -> lltype -> llvalue = "LLVMConstFPExt"
external const_uitofp : llvalue -> lltype -> llvalue = "LLVMConstUIToFP"
external const_sitofp : llvalue -> lltype -> llvalue = "LLVMConstSIToFP"
external const_fptoui : llvalue -> lltype -> llvalue = "LLVMConstFPToUI"
external const_fptosi : llvalue -> lltype -> llvalue = "LLVMConstFPToSI"
external const_ptrtoint : llvalue -> lltype -> llvalue = "LLVMConstPtrToInt"
external const_inttoptr : llvalue -> lltype -> llvalue = "LLVMConstIntToPtr"
external const_bitcast : llvalue -> lltype -> llvalue = "LLVMConstBitCast"
external const_zext_or_bitcast : llvalue -> lltype -> llvalue
= "LLVMConstZExtOrBitCast"
external const_sext_or_bitcast : llvalue -> lltype -> llvalue
= "LLVMConstSExtOrBitCast"
external const_trunc_or_bitcast : llvalue -> lltype -> llvalue
= "LLVMConstTruncOrBitCast"
external const_pointercast : llvalue -> lltype -> llvalue
= "LLVMConstPointerCast"
external const_intcast : llvalue -> lltype -> is_signed:bool -> llvalue
= "llvm_const_intcast"
external const_fpcast : llvalue -> lltype -> llvalue = "LLVMConstFPCast"
external const_select : llvalue -> llvalue -> llvalue -> llvalue
= "LLVMConstSelect"
external const_extractelement : llvalue -> llvalue -> llvalue
= "LLVMConstExtractElement"
external const_insertelement : llvalue -> llvalue -> llvalue -> llvalue
= "LLVMConstInsertElement"
external const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue
= "LLVMConstShuffleVector"
external const_extractvalue : llvalue -> int array -> llvalue
= "llvm_const_extractvalue"
external const_insertvalue : llvalue -> llvalue -> int array -> llvalue
= "llvm_const_insertvalue"
external const_inline_asm : lltype -> string -> string -> bool -> bool ->
llvalue
= "llvm_const_inline_asm"
external block_address : llvalue -> llbasicblock -> llvalue = "LLVMBlockAddress"
(*--... Operations on global variables, functions, and aliases (globals) ...--*)
external global_parent : llvalue -> llmodule = "LLVMGetGlobalParent"
external is_declaration : llvalue -> bool = "llvm_is_declaration"
external linkage : llvalue -> Linkage.t = "llvm_linkage"
external set_linkage : Linkage.t -> llvalue -> unit = "llvm_set_linkage"
external unnamed_addr : llvalue -> bool = "llvm_unnamed_addr"
external set_unnamed_addr : bool -> llvalue -> unit = "llvm_set_unnamed_addr"
external section : llvalue -> string = "llvm_section"
external set_section : string -> llvalue -> unit = "llvm_set_section"
external visibility : llvalue -> Visibility.t = "llvm_visibility"
external set_visibility : Visibility.t -> llvalue -> unit = "llvm_set_visibility"
external dll_storage_class : llvalue -> DLLStorageClass.t = "llvm_dll_storage_class"
external set_dll_storage_class : DLLStorageClass.t -> llvalue -> unit = "llvm_set_dll_storage_class"
external alignment : llvalue -> int = "llvm_alignment"
external set_alignment : int -> llvalue -> unit = "llvm_set_alignment"
external global_copy_all_metadata : llvalue -> (llmdkind * llmetadata) array
= "llvm_global_copy_all_metadata"
external is_global_constant : llvalue -> bool = "llvm_is_global_constant"
external set_global_constant : bool -> llvalue -> unit
= "llvm_set_global_constant"
(*--... Operations on global variables .....................................--*)
external declare_global : lltype -> string -> llmodule -> llvalue
= "llvm_declare_global"
external declare_qualified_global : lltype -> string -> int -> llmodule ->
llvalue
= "llvm_declare_qualified_global"
external define_global : string -> llvalue -> llmodule -> llvalue
= "llvm_define_global"
external define_qualified_global : string -> llvalue -> int -> llmodule ->
llvalue
= "llvm_define_qualified_global"
external lookup_global : string -> llmodule -> llvalue option
= "llvm_lookup_global"
external delete_global : llvalue -> unit = "llvm_delete_global"
external global_initializer : llvalue -> llvalue option = "llvm_global_initializer"
external set_initializer : llvalue -> llvalue -> unit = "llvm_set_initializer"
external remove_initializer : llvalue -> unit = "llvm_remove_initializer"
external is_thread_local : llvalue -> bool = "llvm_is_thread_local"
external set_thread_local : bool -> llvalue -> unit = "llvm_set_thread_local"
external thread_local_mode : llvalue -> ThreadLocalMode.t
= "llvm_thread_local_mode"
external set_thread_local_mode : ThreadLocalMode.t -> llvalue -> unit
= "llvm_set_thread_local_mode"
external is_externally_initialized : llvalue -> bool
= "llvm_is_externally_initialized"
external set_externally_initialized : bool -> llvalue -> unit
= "llvm_set_externally_initialized"
external global_begin : llmodule -> (llmodule, llvalue) llpos
= "llvm_global_begin"
external global_succ : llvalue -> (llmodule, llvalue) llpos
= "llvm_global_succ"
external global_end : llmodule -> (llmodule, llvalue) llrev_pos
= "llvm_global_end"
external global_pred : llvalue -> (llmodule, llvalue) llrev_pos
= "llvm_global_pred"
let rec iter_global_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid global variable range.")
| Before bb ->
f bb;
iter_global_range f (global_succ bb) e
let iter_globals f m =
iter_global_range f (global_begin m) (At_end m)
let rec fold_left_global_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid global variable range.")
| Before bb -> fold_left_global_range f (f init bb) (global_succ bb) e
let fold_left_globals f init m =
fold_left_global_range f init (global_begin m) (At_end m)
let rec rev_iter_global_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid global variable range.")
| After bb ->
f bb;
rev_iter_global_range f (global_pred bb) e
let rev_iter_globals f m =
rev_iter_global_range f (global_end m) (At_start m)
let rec fold_right_global_range f i e init =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid global variable range.")
| After bb -> fold_right_global_range f (global_pred bb) e (f bb init)
let fold_right_globals f m init =
fold_right_global_range f (global_end m) (At_start m) init
(*--... Operations on aliases ..............................................--*)
external add_alias : llmodule -> lltype -> llvalue -> string -> llvalue
= "llvm_add_alias"
(*--... Operations on functions ............................................--*)
external declare_function : string -> lltype -> llmodule -> llvalue
= "llvm_declare_function"
external define_function : string -> lltype -> llmodule -> llvalue
= "llvm_define_function"
external lookup_function : string -> llmodule -> llvalue option
= "llvm_lookup_function"
external delete_function : llvalue -> unit = "llvm_delete_function"
external is_intrinsic : llvalue -> bool = "llvm_is_intrinsic"
external function_call_conv : llvalue -> int = "llvm_function_call_conv"
external set_function_call_conv : int -> llvalue -> unit
= "llvm_set_function_call_conv"
external gc : llvalue -> string option = "llvm_gc"
external set_gc : string option -> llvalue -> unit = "llvm_set_gc"
external function_begin : llmodule -> (llmodule, llvalue) llpos
= "llvm_function_begin"
external function_succ : llvalue -> (llmodule, llvalue) llpos
= "llvm_function_succ"
external function_end : llmodule -> (llmodule, llvalue) llrev_pos
= "llvm_function_end"
external function_pred : llvalue -> (llmodule, llvalue) llrev_pos
= "llvm_function_pred"
let rec iter_function_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid function range.")
| Before fn ->
f fn;
iter_function_range f (function_succ fn) e
let iter_functions f m =
iter_function_range f (function_begin m) (At_end m)
let rec fold_left_function_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid function range.")
| Before fn -> fold_left_function_range f (f init fn) (function_succ fn) e
let fold_left_functions f init m =
fold_left_function_range f init (function_begin m) (At_end m)
let rec rev_iter_function_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid function range.")
| After fn ->
f fn;
rev_iter_function_range f (function_pred fn) e
let rev_iter_functions f m =
rev_iter_function_range f (function_end m) (At_start m)
let rec fold_right_function_range f i e init =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid function range.")
| After fn -> fold_right_function_range f (function_pred fn) e (f fn init)
let fold_right_functions f m init =
fold_right_function_range f (function_end m) (At_start m) init
external llvm_add_function_attr : llvalue -> llattribute -> int -> unit
= "llvm_add_function_attr"
external llvm_function_attrs : llvalue -> int -> llattribute array
= "llvm_function_attrs"
external llvm_remove_enum_function_attr : llvalue -> llattrkind -> int -> unit
= "llvm_remove_enum_function_attr"
external llvm_remove_string_function_attr : llvalue -> string -> int -> unit
= "llvm_remove_string_function_attr"
let add_function_attr f a i =
llvm_add_function_attr f a (AttrIndex.to_int i)
let function_attrs f i =
llvm_function_attrs f (AttrIndex.to_int i)
let remove_enum_function_attr f k i =
llvm_remove_enum_function_attr f k (AttrIndex.to_int i)
let remove_string_function_attr f k i =
llvm_remove_string_function_attr f k (AttrIndex.to_int i)
(*--... Operations on params ...............................................--*)
external params : llvalue -> llvalue array = "llvm_params"
external param : llvalue -> int -> llvalue = "llvm_param"
external param_parent : llvalue -> llvalue = "LLVMGetParamParent"
external param_begin : llvalue -> (llvalue, llvalue) llpos = "llvm_param_begin"
external param_succ : llvalue -> (llvalue, llvalue) llpos = "llvm_param_succ"
external param_end : llvalue -> (llvalue, llvalue) llrev_pos = "llvm_param_end"
external param_pred : llvalue -> (llvalue, llvalue) llrev_pos ="llvm_param_pred"
let rec iter_param_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid parameter range.")
| Before p ->
f p;
iter_param_range f (param_succ p) e
let iter_params f fn =
iter_param_range f (param_begin fn) (At_end fn)
let rec fold_left_param_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid parameter range.")
| Before p -> fold_left_param_range f (f init p) (param_succ p) e
let fold_left_params f init fn =
fold_left_param_range f init (param_begin fn) (At_end fn)
let rec rev_iter_param_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid parameter range.")
| After p ->
f p;
rev_iter_param_range f (param_pred p) e
let rev_iter_params f fn =
rev_iter_param_range f (param_end fn) (At_start fn)
let rec fold_right_param_range f init i e =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid parameter range.")
| After p -> fold_right_param_range f (f p init) (param_pred p) e
let fold_right_params f fn init =
fold_right_param_range f init (param_end fn) (At_start fn)
(*--... Operations on basic blocks .........................................--*)
external value_of_block : llbasicblock -> llvalue = "LLVMBasicBlockAsValue"
external value_is_block : llvalue -> bool = "llvm_value_is_block"
external block_of_value : llvalue -> llbasicblock = "LLVMValueAsBasicBlock"
external block_parent : llbasicblock -> llvalue = "LLVMGetBasicBlockParent"
external basic_blocks : llvalue -> llbasicblock array = "llvm_basic_blocks"
external entry_block : llvalue -> llbasicblock = "LLVMGetEntryBasicBlock"
external delete_block : llbasicblock -> unit = "llvm_delete_block"
external remove_block : llbasicblock -> unit = "llvm_remove_block"
external move_block_before : llbasicblock -> llbasicblock -> unit
= "llvm_move_block_before"
external move_block_after : llbasicblock -> llbasicblock -> unit
= "llvm_move_block_after"
external append_block : llcontext -> string -> llvalue -> llbasicblock
= "llvm_append_block"
external insert_block : llcontext -> string -> llbasicblock -> llbasicblock
= "llvm_insert_block"
external block_begin : llvalue -> (llvalue, llbasicblock) llpos
= "llvm_block_begin"
external block_succ : llbasicblock -> (llvalue, llbasicblock) llpos
= "llvm_block_succ"
external block_end : llvalue -> (llvalue, llbasicblock) llrev_pos
= "llvm_block_end"
external block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos
= "llvm_block_pred"
external block_terminator : llbasicblock -> llvalue option =
"llvm_block_terminator"
let rec iter_block_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid block range.")
| Before bb ->
f bb;
iter_block_range f (block_succ bb) e
let iter_blocks f fn =
iter_block_range f (block_begin fn) (At_end fn)
let rec fold_left_block_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid block range.")
| Before bb -> fold_left_block_range f (f init bb) (block_succ bb) e
let fold_left_blocks f init fn =
fold_left_block_range f init (block_begin fn) (At_end fn)
let rec rev_iter_block_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid block range.")
| After bb ->
f bb;
rev_iter_block_range f (block_pred bb) e
let rev_iter_blocks f fn =
rev_iter_block_range f (block_end fn) (At_start fn)
let rec fold_right_block_range f init i e =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid block range.")
| After bb -> fold_right_block_range f (f bb init) (block_pred bb) e
let fold_right_blocks f fn init =
fold_right_block_range f init (block_end fn) (At_start fn)
(*--... Operations on instructions .........................................--*)
external instr_parent : llvalue -> llbasicblock = "LLVMGetInstructionParent"
external instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos
= "llvm_instr_begin"
external instr_succ : llvalue -> (llbasicblock, llvalue) llpos
= "llvm_instr_succ"
external instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos
= "llvm_instr_end"
external instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos
= "llvm_instr_pred"
external instr_opcode : llvalue -> Opcode.t = "llvm_instr_get_opcode"
external icmp_predicate : llvalue -> Icmp.t option = "llvm_instr_icmp_predicate"
external fcmp_predicate : llvalue -> Fcmp.t option = "llvm_instr_fcmp_predicate"
external atomicrmw_binop : llvalue -> AtomicRMWBinOp.t = "llvm_instr_get_atomicrmw_binop"
external instr_clone : llvalue -> llvalue = "llvm_instr_clone"
let rec iter_instrs_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid instruction range.")
| Before i ->
f i;
iter_instrs_range f (instr_succ i) e
let iter_instrs f bb =
iter_instrs_range f (instr_begin bb) (At_end bb)
let rec fold_left_instrs_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid instruction range.")
| Before i -> fold_left_instrs_range f (f init i) (instr_succ i) e
let fold_left_instrs f init bb =
fold_left_instrs_range f init (instr_begin bb) (At_end bb)
let rec rev_iter_instrs_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid instruction range.")
| After i ->
f i;
rev_iter_instrs_range f (instr_pred i) e
let rev_iter_instrs f bb =
rev_iter_instrs_range f (instr_end bb) (At_start bb)
let rec fold_right_instr_range f i e init =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid instruction range.")
| After i -> fold_right_instr_range f (instr_pred i) e (f i init)
let fold_right_instrs f bb init =
fold_right_instr_range f (instr_end bb) (At_start bb) init
(*--... Operations on call sites ...........................................--*)
external instruction_call_conv: llvalue -> int
= "llvm_instruction_call_conv"
external set_instruction_call_conv: int -> llvalue -> unit
= "llvm_set_instruction_call_conv"
external llvm_add_call_site_attr : llvalue -> llattribute -> int -> unit
= "llvm_add_call_site_attr"
external llvm_call_site_attrs : llvalue -> int -> llattribute array
= "llvm_call_site_attrs"
external llvm_remove_enum_call_site_attr : llvalue -> llattrkind -> int -> unit
= "llvm_remove_enum_call_site_attr"
external llvm_remove_string_call_site_attr : llvalue -> string -> int -> unit
= "llvm_remove_string_call_site_attr"
let add_call_site_attr f a i =
llvm_add_call_site_attr f a (AttrIndex.to_int i)
let call_site_attrs f i =
llvm_call_site_attrs f (AttrIndex.to_int i)
let remove_enum_call_site_attr f k i =
llvm_remove_enum_call_site_attr f k (AttrIndex.to_int i)
let remove_string_call_site_attr f k i =
llvm_remove_string_call_site_attr f k (AttrIndex.to_int i)
(*--... Operations on call and invoke instructions (only) ..................--*)
external num_arg_operands : llvalue -> int = "llvm_num_arg_operands"
external is_tail_call : llvalue -> bool = "llvm_is_tail_call"
external set_tail_call : bool -> llvalue -> unit = "llvm_set_tail_call"
external get_normal_dest : llvalue -> llbasicblock = "LLVMGetNormalDest"
external get_unwind_dest : llvalue -> llbasicblock = "LLVMGetUnwindDest"
(*--... Operations on load/store instructions (only) .......................--*)
external is_volatile : llvalue -> bool = "llvm_is_volatile"
external set_volatile : bool -> llvalue -> unit = "llvm_set_volatile"
(*--... Operations on terminators ..........................................--*)
let is_terminator llv =
let open ValueKind in
let open Opcode in
match classify_value llv with
| Instruction (Br | IndirectBr | Invoke | Resume | Ret | Switch | Unreachable)
-> true
| _ -> false
external successor : llvalue -> int -> llbasicblock = "llvm_successor"
external set_successor : llvalue -> int -> llbasicblock -> unit
= "llvm_set_successor"
external num_successors : llvalue -> int = "llvm_num_successors"
let successors llv =
if not (is_terminator llv) then
raise (Invalid_argument "Llvm.successors can only be used on terminators")
else
Array.init (num_successors llv) (successor llv)
let iter_successors f llv =
if not (is_terminator llv) then
raise (Invalid_argument "Llvm.iter_successors can only be used on terminators")
else
for i = 0 to num_successors llv - 1 do
f (successor llv i)
done
let fold_successors f llv z =
if not (is_terminator llv) then
raise (Invalid_argument "Llvm.fold_successors can only be used on terminators")
else
let n = num_successors llv in
let rec aux i acc =
if i >= n then acc
else begin
let llb = successor llv i in
aux (i+1) (f llb acc)
end
in aux 0 z
(*--... Operations on branches .............................................--*)
external condition : llvalue -> llvalue = "llvm_condition"
external set_condition : llvalue -> llvalue -> unit
= "llvm_set_condition"
external is_conditional : llvalue -> bool = "llvm_is_conditional"
let get_branch llv =
if classify_value llv <> ValueKind.Instruction Opcode.Br then
None
else if is_conditional llv then
Some (`Conditional (condition llv, successor llv 0, successor llv 1))
else
Some (`Unconditional (successor llv 0))
-- ... Operations on phi nodes ............................................ --
external add_incoming : (llvalue * llbasicblock) -> llvalue -> unit
= "llvm_add_incoming"
external incoming : llvalue -> (llvalue * llbasicblock) list = "llvm_incoming"
external delete_instruction : llvalue -> unit = "llvm_delete_instruction"
(*===-- Instruction builders ----------------------------------------------===*)
external builder : llcontext -> llbuilder = "llvm_builder"
external position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit
= "llvm_position_builder"
external insertion_block : llbuilder -> llbasicblock = "llvm_insertion_block"
external insert_into_builder : llvalue -> string -> llbuilder -> unit
= "llvm_insert_into_builder"
let builder_at context ip =
let b = builder context in
position_builder ip b;
b
let builder_before context i = builder_at context (Before i)
let builder_at_end context bb = builder_at context (At_end bb)
let position_before i = position_builder (Before i)
let position_at_end bb = position_builder (At_end bb)
(*--... Metadata ...........................................................--*)
external set_current_debug_location : llbuilder -> llvalue -> unit
= "llvm_set_current_debug_location"
external clear_current_debug_location : llbuilder -> unit
= "llvm_clear_current_debug_location"
external current_debug_location : llbuilder -> llvalue option
= "llvm_current_debug_location"
external set_inst_debug_location : llbuilder -> llvalue -> unit
= "llvm_set_inst_debug_location"
(*--... Terminators ........................................................--*)
external build_ret_void : llbuilder -> llvalue = "llvm_build_ret_void"
external build_ret : llvalue -> llbuilder -> llvalue = "llvm_build_ret"
external build_aggregate_ret : llvalue array -> llbuilder -> llvalue
= "llvm_build_aggregate_ret"
external build_br : llbasicblock -> llbuilder -> llvalue = "llvm_build_br"
external build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder ->
llvalue = "llvm_build_cond_br"
external build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue
= "llvm_build_switch"
external build_malloc : lltype -> string -> llbuilder -> llvalue =
"llvm_build_malloc"
external build_array_malloc : lltype -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_array_malloc"
external build_free : llvalue -> llbuilder -> llvalue = "llvm_build_free"
external add_case : llvalue -> llvalue -> llbasicblock -> unit
= "llvm_add_case"
external switch_default_dest : llvalue -> llbasicblock =
"LLVMGetSwitchDefaultDest"
external build_indirect_br : llvalue -> int -> llbuilder -> llvalue
= "llvm_build_indirect_br"
external add_destination : llvalue -> llbasicblock -> unit
= "llvm_add_destination"
external build_invoke : llvalue -> llvalue array -> llbasicblock ->
llbasicblock -> string -> llbuilder -> llvalue
= "llvm_build_invoke_bc" "llvm_build_invoke_nat"
external build_landingpad : lltype -> llvalue -> int -> string -> llbuilder ->
llvalue = "llvm_build_landingpad"
external is_cleanup : llvalue -> bool = "llvm_is_cleanup"
external set_cleanup : llvalue -> bool -> unit = "llvm_set_cleanup"
external add_clause : llvalue -> llvalue -> unit = "llvm_add_clause"
external build_resume : llvalue -> llbuilder -> llvalue = "llvm_build_resume"
external build_unreachable : llbuilder -> llvalue = "llvm_build_unreachable"
(*--... Arithmetic .........................................................--*)
external build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_add"
external build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_add"
external build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_add"
external build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fadd"
external build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_sub"
external build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_sub"
external build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_sub"
external build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fsub"
external build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_mul"
external build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_mul"
external build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_mul"
external build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fmul"
external build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_udiv"
external build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_sdiv"
external build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_exact_sdiv"
external build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fdiv"
external build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_urem"
external build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_srem"
external build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_frem"
external build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_shl"
external build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_lshr"
external build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_ashr"
external build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_and"
external build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_or"
external build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_xor"
external build_neg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_neg"
external build_nsw_neg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_neg"
external build_nuw_neg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_neg"
external build_fneg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fneg"
external build_not : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_not"
(*--... Memory .............................................................--*)
external build_alloca : lltype -> string -> llbuilder -> llvalue
= "llvm_build_alloca"
external build_array_alloca : lltype -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_array_alloca"
external build_load : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_load"
external build_store : llvalue -> llvalue -> llbuilder -> llvalue
= "llvm_build_store"
external build_atomicrmw : AtomicRMWBinOp.t -> llvalue -> llvalue ->
AtomicOrdering.t -> bool -> string -> llbuilder ->
llvalue
= "llvm_build_atomicrmw_bytecode"
"llvm_build_atomicrmw_native"
external build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue
= "llvm_build_gep"
external build_in_bounds_gep : llvalue -> llvalue array -> string ->
llbuilder -> llvalue = "llvm_build_in_bounds_gep"
external build_struct_gep : llvalue -> int -> string -> llbuilder -> llvalue
= "llvm_build_struct_gep"
external build_global_string : string -> string -> llbuilder -> llvalue
= "llvm_build_global_string"
external build_global_stringptr : string -> string -> llbuilder -> llvalue
= "llvm_build_global_stringptr"
(*--... Casts ..............................................................--*)
external build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_trunc"
external build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_zext"
external build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_sext"
external build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fptoui"
external build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fptosi"
external build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_uitofp"
external build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_sitofp"
external build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fptrunc"
external build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fpext"
external build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_prttoint"
external build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_inttoptr"
external build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_bitcast"
external build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
llvalue = "llvm_build_zext_or_bitcast"
external build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
llvalue = "llvm_build_sext_or_bitcast"
external build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
llvalue = "llvm_build_trunc_or_bitcast"
external build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_pointercast"
external build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_intcast"
external build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fpcast"
(*--... Comparisons ........................................................--*)
external build_icmp : Icmp.t -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_icmp"
external build_fcmp : Fcmp.t -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_fcmp"
(*--... Miscellaneous instructions .........................................--*)
external build_phi : (llvalue * llbasicblock) list -> string -> llbuilder ->
llvalue = "llvm_build_phi"
external build_empty_phi : lltype -> string -> llbuilder -> llvalue
= "llvm_build_empty_phi"
external build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue
= "llvm_build_call"
external build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_select"
external build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_va_arg"
external build_extractelement : llvalue -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_extractelement"
external build_insertelement : llvalue -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_insertelement"
external build_shufflevector : llvalue -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_shufflevector"
external build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue
= "llvm_build_extractvalue"
external build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder ->
llvalue = "llvm_build_insertvalue"
external build_is_null : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_is_null"
external build_is_not_null : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_is_not_null"
external build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_ptrdiff"
external build_freeze : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_freeze"
(*===-- Memory buffers ----------------------------------------------------===*)
module MemoryBuffer = struct
external of_file : string -> llmemorybuffer = "llvm_memorybuffer_of_file"
external of_stdin : unit -> llmemorybuffer = "llvm_memorybuffer_of_stdin"
external of_string : ?name:string -> string -> llmemorybuffer
= "llvm_memorybuffer_of_string"
external as_string : llmemorybuffer -> string = "llvm_memorybuffer_as_string"
external dispose : llmemorybuffer -> unit = "llvm_memorybuffer_dispose"
end
(*===-- Pass Manager ------------------------------------------------------===*)
module PassManager = struct
type 'a t
type any = [ `Module | `Function ]
external create : unit -> [ `Module ] t = "llvm_passmanager_create"
external create_function : llmodule -> [ `Function ] t
= "LLVMCreateFunctionPassManager"
external run_module : llmodule -> [ `Module ] t -> bool
= "llvm_passmanager_run_module"
external initialize : [ `Function ] t -> bool = "llvm_passmanager_initialize"
external run_function : llvalue -> [ `Function ] t -> bool
= "llvm_passmanager_run_function"
external finalize : [ `Function ] t -> bool = "llvm_passmanager_finalize"
external dispose : [< any ] t -> unit = "llvm_passmanager_dispose"
end
| null | https://raw.githubusercontent.com/facebook/infer/0bebce66a92d1773f34f9c9cd9cf0c4b01c5c85c/sledge/vendor/llvm-dune/llvm-project/llvm/bindings/ocaml/llvm/llvm.ml | ocaml | not an instruction
Terminator Instructions
Logical Operators
Memory Operators
Other Operators
===-- Context error handling --------------------------------------------===
===-- Contexts ----------------------------------------------------------===
===-- Attributes --------------------------------------------------------===
===-- Modules -----------------------------------------------------------===
===-- Types -------------------------------------------------------------===
--... Operations on real types ...........................................--
--... Operations on function types .......................................--
--... Operations on struct types .........................................--
--... Operations on pointer, vector, and array types .....................--
--... Operations on other types ..........................................--
===-- Values ------------------------------------------------------------===
--... Operations on uses .................................................--
--... Operations on users ................................................--
--... Operations on constants of (mostly) any type .......................--
--... Operations on instructions .........................................--
--... Operations on metadata .......,.....................................--
--... Operations on scalar constants .....................................--
--... Operations on composite constants ..................................--
--... Constant expressions ...............................................--
--... Operations on global variables, functions, and aliases (globals) ...--
--... Operations on global variables .....................................--
--... Operations on aliases ..............................................--
--... Operations on functions ............................................--
--... Operations on params ...............................................--
--... Operations on basic blocks .........................................--
--... Operations on instructions .........................................--
--... Operations on call sites ...........................................--
--... Operations on call and invoke instructions (only) ..................--
--... Operations on load/store instructions (only) .......................--
--... Operations on terminators ..........................................--
--... Operations on branches .............................................--
===-- Instruction builders ----------------------------------------------===
--... Metadata ...........................................................--
--... Terminators ........................................................--
--... Arithmetic .........................................................--
--... Memory .............................................................--
--... Casts ..............................................................--
--... Comparisons ........................................................--
--... Miscellaneous instructions .........................................--
===-- Memory buffers ----------------------------------------------------===
===-- Pass Manager ------------------------------------------------------=== | = = = -- / llvm.ml - LLVM OCaml Interface -------------------------------=== *
*
* Part of the LLVM Project , under the Apache License v2.0 with LLVM Exceptions .
* See for license information .
* SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception
*
* = = = ----------------------------------------------------------------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
type llcontext
type llmodule
type llmetadata
type lltype
type llvalue
type lluse
type llbasicblock
type llbuilder
type llattrkind
type llattribute
type llmemorybuffer
type llmdkind
exception FeatureDisabled of string
let () = Callback.register_exception "Llvm.FeatureDisabled" (FeatureDisabled "")
module TypeKind = struct
type t =
| Void
| Half
| Float
| Double
| X86fp80
| Fp128
| Ppc_fp128
| Label
| Integer
| Function
| Struct
| Array
| Pointer
| Vector
| Metadata
| X86_mmx
| Token
| ScalableVector
| BFloat
| X86_amx
end
module Linkage = struct
type t =
| External
| Available_externally
| Link_once
| Link_once_odr
| Link_once_odr_auto_hide
| Weak
| Weak_odr
| Appending
| Internal
| Private
| Dllimport
| Dllexport
| External_weak
| Ghost
| Common
| Linker_private
| Linker_private_weak
end
module Visibility = struct
type t =
| Default
| Hidden
| Protected
end
module DLLStorageClass = struct
type t =
| Default
| DLLImport
| DLLExport
end
module CallConv = struct
let c = 0
let fast = 8
let cold = 9
let x86_stdcall = 64
let x86_fastcall = 65
end
module AttrRepr = struct
type t =
| Enum of llattrkind * int64
| String of string * string
end
module AttrIndex = struct
type t =
| Function
| Return
| Param of int
let to_int index =
match index with
| Function -> -1
| Return -> 0
| Param(n) -> 1 + n
end
module Attribute = struct
type t =
| Zext
| Sext
| Noreturn
| Inreg
| Structret
| Nounwind
| Noalias
| Byval
| Nest
| Readnone
| Readonly
| Noinline
| Alwaysinline
| Optsize
| Ssp
| Sspreq
| Alignment of int
| Nocapture
| Noredzone
| Noimplicitfloat
| Naked
| Inlinehint
| Stackalignment of int
| ReturnsTwice
| UWTable
| NonLazyBind
end
module Icmp = struct
type t =
| Eq
| Ne
| Ugt
| Uge
| Ult
| Ule
| Sgt
| Sge
| Slt
| Sle
end
module Fcmp = struct
type t =
| False
| Oeq
| Ogt
| Oge
| Olt
| Ole
| One
| Ord
| Uno
| Ueq
| Ugt
| Uge
| Ult
| Ule
| Une
| True
end
module Opcode = struct
type t =
| Ret
| Br
| Switch
| IndirectBr
| Invoke
| Invalid2
| Unreachable
Standard Binary Operators
| Add
| FAdd
| Sub
| FSub
| Mul
| FMul
| UDiv
| SDiv
| FDiv
| URem
| SRem
| FRem
| Shl
| LShr
| AShr
| And
| Or
| Xor
| Alloca
| Load
| Store
| GetElementPtr
Cast Operators
| Trunc
| ZExt
| SExt
| FPToUI
| FPToSI
| UIToFP
| SIToFP
| FPTrunc
| FPExt
| PtrToInt
| IntToPtr
| BitCast
| ICmp
| FCmp
| PHI
| Call
| Select
| UserOp1
| UserOp2
| VAArg
| ExtractElement
| InsertElement
| ShuffleVector
| ExtractValue
| InsertValue
| Fence
| AtomicCmpXchg
| AtomicRMW
| Resume
| LandingPad
| AddrSpaceCast
| CleanupRet
| CatchRet
| CatchPad
| CleanupPad
| CatchSwitch
| FNeg
| CallBr
| Freeze
end
module LandingPadClauseTy = struct
type t =
| Catch
| Filter
end
module ThreadLocalMode = struct
type t =
| None
| GeneralDynamic
| LocalDynamic
| InitialExec
| LocalExec
end
module AtomicOrdering = struct
type t =
| NotAtomic
| Unordered
| Monotonic
| Invalid
| Acquire
| Release
| AcqiureRelease
| SequentiallyConsistent
end
module AtomicRMWBinOp = struct
type t =
| Xchg
| Add
| Sub
| And
| Nand
| Or
| Xor
| Max
| Min
| UMax
| UMin
| FAdd
| FSub
end
module ValueKind = struct
type t =
| NullValue
| Argument
| BasicBlock
| InlineAsm
| MDNode
| MDString
| BlockAddress
| ConstantAggregateZero
| ConstantArray
| ConstantDataArray
| ConstantDataVector
| ConstantExpr
| ConstantFP
| ConstantInt
| ConstantPointerNull
| ConstantStruct
| ConstantVector
| Function
| GlobalAlias
| GlobalIFunc
| GlobalVariable
| UndefValue
| PoisonValue
| Instruction of Opcode.t
end
module DiagnosticSeverity = struct
type t =
| Error
| Warning
| Remark
| Note
end
module ModuleFlagBehavior = struct
type t =
| Error
| Warning
| Require
| Override
| Append
| AppendUnique
end
exception IoError of string
let () = Callback.register_exception "Llvm.IoError" (IoError "")
external install_fatal_error_handler : (string -> unit) -> unit
= "llvm_install_fatal_error_handler"
external reset_fatal_error_handler : unit -> unit
= "llvm_reset_fatal_error_handler"
external enable_pretty_stacktrace : unit -> unit
= "llvm_enable_pretty_stacktrace"
external parse_command_line_options : ?overview:string -> string array -> unit
= "llvm_parse_command_line_options"
type ('a, 'b) llpos =
| At_end of 'a
| Before of 'b
type ('a, 'b) llrev_pos =
| At_start of 'a
| After of 'b
module Diagnostic = struct
type t
external description : t -> string = "llvm_get_diagnostic_description"
external severity : t -> DiagnosticSeverity.t
= "llvm_get_diagnostic_severity"
end
external set_diagnostic_handler
: llcontext -> (Diagnostic.t -> unit) option -> unit
= "llvm_set_diagnostic_handler"
external create_context : unit -> llcontext = "llvm_create_context"
external dispose_context : llcontext -> unit = "llvm_dispose_context"
external global_context : unit -> llcontext = "llvm_global_context"
external mdkind_id : llcontext -> string -> llmdkind = "llvm_mdkind_id"
exception UnknownAttribute of string
let () = Callback.register_exception "Llvm.UnknownAttribute"
(UnknownAttribute "")
external enum_attr_kind : string -> llattrkind = "llvm_enum_attr_kind"
external llvm_create_enum_attr : llcontext -> llattrkind -> int64 ->
llattribute
= "llvm_create_enum_attr_by_kind"
external is_enum_attr : llattribute -> bool = "llvm_is_enum_attr"
external get_enum_attr_kind : llattribute -> llattrkind
= "llvm_get_enum_attr_kind"
external get_enum_attr_value : llattribute -> int64
= "llvm_get_enum_attr_value"
external llvm_create_string_attr : llcontext -> string -> string ->
llattribute
= "llvm_create_string_attr"
external is_string_attr : llattribute -> bool = "llvm_is_string_attr"
external get_string_attr_kind : llattribute -> string
= "llvm_get_string_attr_kind"
external get_string_attr_value : llattribute -> string
= "llvm_get_string_attr_value"
let create_enum_attr context name value =
llvm_create_enum_attr context (enum_attr_kind name) value
let create_string_attr context kind value =
llvm_create_string_attr context kind value
let attr_of_repr context repr =
match repr with
| AttrRepr.Enum(kind, value) -> llvm_create_enum_attr context kind value
| AttrRepr.String(key, value) -> llvm_create_string_attr context key value
let repr_of_attr attr =
if is_enum_attr attr then
AttrRepr.Enum(get_enum_attr_kind attr, get_enum_attr_value attr)
else if is_string_attr attr then
AttrRepr.String(get_string_attr_kind attr, get_string_attr_value attr)
else assert false
external create_module : llcontext -> string -> llmodule = "llvm_create_module"
external dispose_module : llmodule -> unit = "llvm_dispose_module"
external target_triple: llmodule -> string
= "llvm_target_triple"
external set_target_triple: string -> llmodule -> unit
= "llvm_set_target_triple"
external data_layout: llmodule -> string
= "llvm_data_layout"
external set_data_layout: string -> llmodule -> unit
= "llvm_set_data_layout"
external dump_module : llmodule -> unit = "llvm_dump_module"
external print_module : string -> llmodule -> unit = "llvm_print_module"
external string_of_llmodule : llmodule -> string = "llvm_string_of_llmodule"
external set_module_inline_asm : llmodule -> string -> unit
= "llvm_set_module_inline_asm"
external module_context : llmodule -> llcontext = "LLVMGetModuleContext"
external get_module_identifier : llmodule -> string
= "llvm_get_module_identifier"
external set_module_identifer : llmodule -> string -> unit
= "llvm_set_module_identifier"
external get_module_flag : llmodule -> string -> llmetadata option
= "llvm_get_module_flag"
external add_module_flag : llmodule -> ModuleFlagBehavior.t ->
string -> llmetadata -> unit = "llvm_add_module_flag"
external classify_type : lltype -> TypeKind.t = "llvm_classify_type"
external type_context : lltype -> llcontext = "llvm_type_context"
external type_is_sized : lltype -> bool = "llvm_type_is_sized"
external dump_type : lltype -> unit = "llvm_dump_type"
external string_of_lltype : lltype -> string = "llvm_string_of_lltype"
-- ... Operations on integer types ........................................ --
external i1_type : llcontext -> lltype = "llvm_i1_type"
external i8_type : llcontext -> lltype = "llvm_i8_type"
external i16_type : llcontext -> lltype = "llvm_i16_type"
external i32_type : llcontext -> lltype = "llvm_i32_type"
external i64_type : llcontext -> lltype = "llvm_i64_type"
external integer_type : llcontext -> int -> lltype = "llvm_integer_type"
external integer_bitwidth : lltype -> int = "llvm_integer_bitwidth"
external float_type : llcontext -> lltype = "llvm_float_type"
external double_type : llcontext -> lltype = "llvm_double_type"
external x86fp80_type : llcontext -> lltype = "llvm_x86fp80_type"
external fp128_type : llcontext -> lltype = "llvm_fp128_type"
external ppc_fp128_type : llcontext -> lltype = "llvm_ppc_fp128_type"
external function_type : lltype -> lltype array -> lltype = "llvm_function_type"
external var_arg_function_type : lltype -> lltype array -> lltype
= "llvm_var_arg_function_type"
external is_var_arg : lltype -> bool = "llvm_is_var_arg"
external return_type : lltype -> lltype = "LLVMGetReturnType"
external param_types : lltype -> lltype array = "llvm_param_types"
external struct_type : llcontext -> lltype array -> lltype = "llvm_struct_type"
external packed_struct_type : llcontext -> lltype array -> lltype
= "llvm_packed_struct_type"
external struct_name : lltype -> string option = "llvm_struct_name"
external named_struct_type : llcontext -> string -> lltype =
"llvm_named_struct_type"
external struct_set_body : lltype -> lltype array -> bool -> unit =
"llvm_struct_set_body"
external struct_element_types : lltype -> lltype array
= "llvm_struct_element_types"
external is_packed : lltype -> bool = "llvm_is_packed"
external is_opaque : lltype -> bool = "llvm_is_opaque"
external is_literal : lltype -> bool = "llvm_is_literal"
external subtypes : lltype -> lltype array = "llvm_subtypes"
external array_type : lltype -> int -> lltype = "llvm_array_type"
external pointer_type : lltype -> lltype = "llvm_pointer_type"
external qualified_pointer_type : lltype -> int -> lltype
= "llvm_qualified_pointer_type"
external vector_type : lltype -> int -> lltype = "llvm_vector_type"
external element_type : lltype -> lltype = "LLVMGetElementType"
external array_length : lltype -> int = "llvm_array_length"
external address_space : lltype -> int = "llvm_address_space"
external vector_size : lltype -> int = "llvm_vector_size"
external void_type : llcontext -> lltype = "llvm_void_type"
external label_type : llcontext -> lltype = "llvm_label_type"
external x86_mmx_type : llcontext -> lltype = "llvm_x86_mmx_type"
external type_by_name : llmodule -> string -> lltype option = "llvm_type_by_name"
external classify_value : llvalue -> ValueKind.t = "llvm_classify_value"
external type_of : llvalue -> lltype = "llvm_type_of"
external value_name : llvalue -> string = "llvm_value_name"
external set_value_name : string -> llvalue -> unit = "llvm_set_value_name"
external dump_value : llvalue -> unit = "llvm_dump_value"
external string_of_llvalue : llvalue -> string = "llvm_string_of_llvalue"
external replace_all_uses_with : llvalue -> llvalue -> unit
= "llvm_replace_all_uses_with"
external use_begin : llvalue -> lluse option = "llvm_use_begin"
external use_succ : lluse -> lluse option = "llvm_use_succ"
external user : lluse -> llvalue = "llvm_user"
external used_value : lluse -> llvalue = "llvm_used_value"
let iter_uses f v =
let rec aux = function
| None -> ()
| Some u ->
f u;
aux (use_succ u)
in
aux (use_begin v)
let fold_left_uses f init v =
let rec aux init u =
match u with
| None -> init
| Some u -> aux (f init u) (use_succ u)
in
aux init (use_begin v)
let fold_right_uses f v init =
let rec aux u init =
match u with
| None -> init
| Some u -> f u (aux (use_succ u) init)
in
aux (use_begin v) init
external operand : llvalue -> int -> llvalue = "llvm_operand"
external operand_use : llvalue -> int -> lluse = "llvm_operand_use"
external set_operand : llvalue -> int -> llvalue -> unit = "llvm_set_operand"
external num_operands : llvalue -> int = "llvm_num_operands"
external indices : llvalue -> int array = "llvm_indices"
external is_constant : llvalue -> bool = "llvm_is_constant"
external const_null : lltype -> llvalue = "LLVMConstNull"
external const_pointer_null : lltype -> llvalue = "LLVMConstPointerNull"
external undef : lltype -> llvalue = "LLVMGetUndef"
external poison : lltype -> llvalue = "LLVMGetPoison"
external is_null : llvalue -> bool = "llvm_is_null"
external is_undef : llvalue -> bool = "llvm_is_undef"
external is_poison : llvalue -> bool = "llvm_is_poison"
external constexpr_opcode : llvalue -> Opcode.t = "llvm_constexpr_get_opcode"
external has_metadata : llvalue -> bool = "llvm_has_metadata"
external metadata : llvalue -> llmdkind -> llvalue option = "llvm_metadata"
external set_metadata : llvalue -> llmdkind -> llvalue -> unit = "llvm_set_metadata"
external clear_metadata : llvalue -> llmdkind -> unit = "llvm_clear_metadata"
external mdstring : llcontext -> string -> llvalue = "llvm_mdstring"
external mdnode : llcontext -> llvalue array -> llvalue = "llvm_mdnode"
external mdnull : llcontext -> llvalue = "llvm_mdnull"
external get_mdstring : llvalue -> string option = "llvm_get_mdstring"
external get_mdnode_operands : llvalue -> llvalue array
= "llvm_get_mdnode_operands"
external get_named_metadata : llmodule -> string -> llvalue array
= "llvm_get_namedmd"
external add_named_metadata_operand : llmodule -> string -> llvalue -> unit
= "llvm_append_namedmd"
external get_debug_loc_directory : llvalue -> string option = "llvm_get_debug_loc_directory"
external get_debug_loc_filename : llvalue -> string option = "llvm_get_debug_loc_filename"
external get_debug_loc_line : llvalue -> int = "llvm_get_debug_loc_line"
external get_debug_loc_column : llvalue -> int = "llvm_get_debug_loc_column"
external value_as_metadata : llvalue -> llmetadata = "llvm_value_as_metadata"
external metadata_as_value : llcontext -> llmetadata -> llvalue
= "llvm_metadata_as_value"
external const_int : lltype -> int -> llvalue = "llvm_const_int"
external const_of_int64 : lltype -> Int64.t -> bool -> llvalue
= "llvm_const_of_int64"
external int64_of_const : llvalue -> Int64.t option
= "llvm_int64_of_const"
external const_int_of_string : lltype -> string -> int -> llvalue
= "llvm_const_int_of_string"
external const_float : lltype -> float -> llvalue = "llvm_const_float"
external float_of_const : llvalue -> float option
= "llvm_float_of_const"
external const_float_of_string : lltype -> string -> llvalue
= "llvm_const_float_of_string"
external const_string : llcontext -> string -> llvalue = "llvm_const_string"
external const_stringz : llcontext -> string -> llvalue = "llvm_const_stringz"
external const_array : lltype -> llvalue array -> llvalue = "llvm_const_array"
external const_struct : llcontext -> llvalue array -> llvalue
= "llvm_const_struct"
external const_named_struct : lltype -> llvalue array -> llvalue
= "llvm_const_named_struct"
external const_packed_struct : llcontext -> llvalue array -> llvalue
= "llvm_const_packed_struct"
external const_vector : llvalue array -> llvalue = "llvm_const_vector"
external string_of_const : llvalue -> string option = "llvm_string_of_const"
external const_element : llvalue -> int -> llvalue = "llvm_const_element"
external align_of : lltype -> llvalue = "LLVMAlignOf"
external size_of : lltype -> llvalue = "LLVMSizeOf"
external const_neg : llvalue -> llvalue = "LLVMConstNeg"
external const_nsw_neg : llvalue -> llvalue = "LLVMConstNSWNeg"
external const_nuw_neg : llvalue -> llvalue = "LLVMConstNUWNeg"
external const_fneg : llvalue -> llvalue = "LLVMConstFNeg"
external const_not : llvalue -> llvalue = "LLVMConstNot"
external const_add : llvalue -> llvalue -> llvalue = "LLVMConstAdd"
external const_nsw_add : llvalue -> llvalue -> llvalue = "LLVMConstNSWAdd"
external const_nuw_add : llvalue -> llvalue -> llvalue = "LLVMConstNUWAdd"
external const_fadd : llvalue -> llvalue -> llvalue = "LLVMConstFAdd"
external const_sub : llvalue -> llvalue -> llvalue = "LLVMConstSub"
external const_nsw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNSWSub"
external const_nuw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNUWSub"
external const_fsub : llvalue -> llvalue -> llvalue = "LLVMConstFSub"
external const_mul : llvalue -> llvalue -> llvalue = "LLVMConstMul"
external const_nsw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNSWMul"
external const_nuw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNUWMul"
external const_fmul : llvalue -> llvalue -> llvalue = "LLVMConstFMul"
external const_udiv : llvalue -> llvalue -> llvalue = "LLVMConstUDiv"
external const_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstSDiv"
external const_exact_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstExactSDiv"
external const_fdiv : llvalue -> llvalue -> llvalue = "LLVMConstFDiv"
external const_urem : llvalue -> llvalue -> llvalue = "LLVMConstURem"
external const_srem : llvalue -> llvalue -> llvalue = "LLVMConstSRem"
external const_frem : llvalue -> llvalue -> llvalue = "LLVMConstFRem"
external const_and : llvalue -> llvalue -> llvalue = "LLVMConstAnd"
external const_or : llvalue -> llvalue -> llvalue = "LLVMConstOr"
external const_xor : llvalue -> llvalue -> llvalue = "LLVMConstXor"
external const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue
= "llvm_const_icmp"
external const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue
= "llvm_const_fcmp"
external const_shl : llvalue -> llvalue -> llvalue = "LLVMConstShl"
external const_lshr : llvalue -> llvalue -> llvalue = "LLVMConstLShr"
external const_ashr : llvalue -> llvalue -> llvalue = "LLVMConstAShr"
external const_gep : llvalue -> llvalue array -> llvalue = "llvm_const_gep"
external const_in_bounds_gep : llvalue -> llvalue array -> llvalue
= "llvm_const_in_bounds_gep"
external const_trunc : llvalue -> lltype -> llvalue = "LLVMConstTrunc"
external const_sext : llvalue -> lltype -> llvalue = "LLVMConstSExt"
external const_zext : llvalue -> lltype -> llvalue = "LLVMConstZExt"
external const_fptrunc : llvalue -> lltype -> llvalue = "LLVMConstFPTrunc"
external const_fpext : llvalue -> lltype -> llvalue = "LLVMConstFPExt"
external const_uitofp : llvalue -> lltype -> llvalue = "LLVMConstUIToFP"
external const_sitofp : llvalue -> lltype -> llvalue = "LLVMConstSIToFP"
external const_fptoui : llvalue -> lltype -> llvalue = "LLVMConstFPToUI"
external const_fptosi : llvalue -> lltype -> llvalue = "LLVMConstFPToSI"
external const_ptrtoint : llvalue -> lltype -> llvalue = "LLVMConstPtrToInt"
external const_inttoptr : llvalue -> lltype -> llvalue = "LLVMConstIntToPtr"
external const_bitcast : llvalue -> lltype -> llvalue = "LLVMConstBitCast"
external const_zext_or_bitcast : llvalue -> lltype -> llvalue
= "LLVMConstZExtOrBitCast"
external const_sext_or_bitcast : llvalue -> lltype -> llvalue
= "LLVMConstSExtOrBitCast"
external const_trunc_or_bitcast : llvalue -> lltype -> llvalue
= "LLVMConstTruncOrBitCast"
external const_pointercast : llvalue -> lltype -> llvalue
= "LLVMConstPointerCast"
external const_intcast : llvalue -> lltype -> is_signed:bool -> llvalue
= "llvm_const_intcast"
external const_fpcast : llvalue -> lltype -> llvalue = "LLVMConstFPCast"
external const_select : llvalue -> llvalue -> llvalue -> llvalue
= "LLVMConstSelect"
external const_extractelement : llvalue -> llvalue -> llvalue
= "LLVMConstExtractElement"
external const_insertelement : llvalue -> llvalue -> llvalue -> llvalue
= "LLVMConstInsertElement"
external const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue
= "LLVMConstShuffleVector"
external const_extractvalue : llvalue -> int array -> llvalue
= "llvm_const_extractvalue"
external const_insertvalue : llvalue -> llvalue -> int array -> llvalue
= "llvm_const_insertvalue"
external const_inline_asm : lltype -> string -> string -> bool -> bool ->
llvalue
= "llvm_const_inline_asm"
external block_address : llvalue -> llbasicblock -> llvalue = "LLVMBlockAddress"
external global_parent : llvalue -> llmodule = "LLVMGetGlobalParent"
external is_declaration : llvalue -> bool = "llvm_is_declaration"
external linkage : llvalue -> Linkage.t = "llvm_linkage"
external set_linkage : Linkage.t -> llvalue -> unit = "llvm_set_linkage"
external unnamed_addr : llvalue -> bool = "llvm_unnamed_addr"
external set_unnamed_addr : bool -> llvalue -> unit = "llvm_set_unnamed_addr"
external section : llvalue -> string = "llvm_section"
external set_section : string -> llvalue -> unit = "llvm_set_section"
external visibility : llvalue -> Visibility.t = "llvm_visibility"
external set_visibility : Visibility.t -> llvalue -> unit = "llvm_set_visibility"
external dll_storage_class : llvalue -> DLLStorageClass.t = "llvm_dll_storage_class"
external set_dll_storage_class : DLLStorageClass.t -> llvalue -> unit = "llvm_set_dll_storage_class"
external alignment : llvalue -> int = "llvm_alignment"
external set_alignment : int -> llvalue -> unit = "llvm_set_alignment"
external global_copy_all_metadata : llvalue -> (llmdkind * llmetadata) array
= "llvm_global_copy_all_metadata"
external is_global_constant : llvalue -> bool = "llvm_is_global_constant"
external set_global_constant : bool -> llvalue -> unit
= "llvm_set_global_constant"
external declare_global : lltype -> string -> llmodule -> llvalue
= "llvm_declare_global"
external declare_qualified_global : lltype -> string -> int -> llmodule ->
llvalue
= "llvm_declare_qualified_global"
external define_global : string -> llvalue -> llmodule -> llvalue
= "llvm_define_global"
external define_qualified_global : string -> llvalue -> int -> llmodule ->
llvalue
= "llvm_define_qualified_global"
external lookup_global : string -> llmodule -> llvalue option
= "llvm_lookup_global"
external delete_global : llvalue -> unit = "llvm_delete_global"
external global_initializer : llvalue -> llvalue option = "llvm_global_initializer"
external set_initializer : llvalue -> llvalue -> unit = "llvm_set_initializer"
external remove_initializer : llvalue -> unit = "llvm_remove_initializer"
external is_thread_local : llvalue -> bool = "llvm_is_thread_local"
external set_thread_local : bool -> llvalue -> unit = "llvm_set_thread_local"
external thread_local_mode : llvalue -> ThreadLocalMode.t
= "llvm_thread_local_mode"
external set_thread_local_mode : ThreadLocalMode.t -> llvalue -> unit
= "llvm_set_thread_local_mode"
external is_externally_initialized : llvalue -> bool
= "llvm_is_externally_initialized"
external set_externally_initialized : bool -> llvalue -> unit
= "llvm_set_externally_initialized"
external global_begin : llmodule -> (llmodule, llvalue) llpos
= "llvm_global_begin"
external global_succ : llvalue -> (llmodule, llvalue) llpos
= "llvm_global_succ"
external global_end : llmodule -> (llmodule, llvalue) llrev_pos
= "llvm_global_end"
external global_pred : llvalue -> (llmodule, llvalue) llrev_pos
= "llvm_global_pred"
let rec iter_global_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid global variable range.")
| Before bb ->
f bb;
iter_global_range f (global_succ bb) e
let iter_globals f m =
iter_global_range f (global_begin m) (At_end m)
let rec fold_left_global_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid global variable range.")
| Before bb -> fold_left_global_range f (f init bb) (global_succ bb) e
let fold_left_globals f init m =
fold_left_global_range f init (global_begin m) (At_end m)
let rec rev_iter_global_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid global variable range.")
| After bb ->
f bb;
rev_iter_global_range f (global_pred bb) e
let rev_iter_globals f m =
rev_iter_global_range f (global_end m) (At_start m)
let rec fold_right_global_range f i e init =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid global variable range.")
| After bb -> fold_right_global_range f (global_pred bb) e (f bb init)
let fold_right_globals f m init =
fold_right_global_range f (global_end m) (At_start m) init
external add_alias : llmodule -> lltype -> llvalue -> string -> llvalue
= "llvm_add_alias"
external declare_function : string -> lltype -> llmodule -> llvalue
= "llvm_declare_function"
external define_function : string -> lltype -> llmodule -> llvalue
= "llvm_define_function"
external lookup_function : string -> llmodule -> llvalue option
= "llvm_lookup_function"
external delete_function : llvalue -> unit = "llvm_delete_function"
external is_intrinsic : llvalue -> bool = "llvm_is_intrinsic"
external function_call_conv : llvalue -> int = "llvm_function_call_conv"
external set_function_call_conv : int -> llvalue -> unit
= "llvm_set_function_call_conv"
external gc : llvalue -> string option = "llvm_gc"
external set_gc : string option -> llvalue -> unit = "llvm_set_gc"
external function_begin : llmodule -> (llmodule, llvalue) llpos
= "llvm_function_begin"
external function_succ : llvalue -> (llmodule, llvalue) llpos
= "llvm_function_succ"
external function_end : llmodule -> (llmodule, llvalue) llrev_pos
= "llvm_function_end"
external function_pred : llvalue -> (llmodule, llvalue) llrev_pos
= "llvm_function_pred"
let rec iter_function_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid function range.")
| Before fn ->
f fn;
iter_function_range f (function_succ fn) e
let iter_functions f m =
iter_function_range f (function_begin m) (At_end m)
let rec fold_left_function_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid function range.")
| Before fn -> fold_left_function_range f (f init fn) (function_succ fn) e
let fold_left_functions f init m =
fold_left_function_range f init (function_begin m) (At_end m)
let rec rev_iter_function_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid function range.")
| After fn ->
f fn;
rev_iter_function_range f (function_pred fn) e
let rev_iter_functions f m =
rev_iter_function_range f (function_end m) (At_start m)
let rec fold_right_function_range f i e init =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid function range.")
| After fn -> fold_right_function_range f (function_pred fn) e (f fn init)
let fold_right_functions f m init =
fold_right_function_range f (function_end m) (At_start m) init
external llvm_add_function_attr : llvalue -> llattribute -> int -> unit
= "llvm_add_function_attr"
external llvm_function_attrs : llvalue -> int -> llattribute array
= "llvm_function_attrs"
external llvm_remove_enum_function_attr : llvalue -> llattrkind -> int -> unit
= "llvm_remove_enum_function_attr"
external llvm_remove_string_function_attr : llvalue -> string -> int -> unit
= "llvm_remove_string_function_attr"
let add_function_attr f a i =
llvm_add_function_attr f a (AttrIndex.to_int i)
let function_attrs f i =
llvm_function_attrs f (AttrIndex.to_int i)
let remove_enum_function_attr f k i =
llvm_remove_enum_function_attr f k (AttrIndex.to_int i)
let remove_string_function_attr f k i =
llvm_remove_string_function_attr f k (AttrIndex.to_int i)
external params : llvalue -> llvalue array = "llvm_params"
external param : llvalue -> int -> llvalue = "llvm_param"
external param_parent : llvalue -> llvalue = "LLVMGetParamParent"
external param_begin : llvalue -> (llvalue, llvalue) llpos = "llvm_param_begin"
external param_succ : llvalue -> (llvalue, llvalue) llpos = "llvm_param_succ"
external param_end : llvalue -> (llvalue, llvalue) llrev_pos = "llvm_param_end"
external param_pred : llvalue -> (llvalue, llvalue) llrev_pos ="llvm_param_pred"
let rec iter_param_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid parameter range.")
| Before p ->
f p;
iter_param_range f (param_succ p) e
let iter_params f fn =
iter_param_range f (param_begin fn) (At_end fn)
let rec fold_left_param_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid parameter range.")
| Before p -> fold_left_param_range f (f init p) (param_succ p) e
let fold_left_params f init fn =
fold_left_param_range f init (param_begin fn) (At_end fn)
let rec rev_iter_param_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid parameter range.")
| After p ->
f p;
rev_iter_param_range f (param_pred p) e
let rev_iter_params f fn =
rev_iter_param_range f (param_end fn) (At_start fn)
let rec fold_right_param_range f init i e =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid parameter range.")
| After p -> fold_right_param_range f (f p init) (param_pred p) e
let fold_right_params f fn init =
fold_right_param_range f init (param_end fn) (At_start fn)
external value_of_block : llbasicblock -> llvalue = "LLVMBasicBlockAsValue"
external value_is_block : llvalue -> bool = "llvm_value_is_block"
external block_of_value : llvalue -> llbasicblock = "LLVMValueAsBasicBlock"
external block_parent : llbasicblock -> llvalue = "LLVMGetBasicBlockParent"
external basic_blocks : llvalue -> llbasicblock array = "llvm_basic_blocks"
external entry_block : llvalue -> llbasicblock = "LLVMGetEntryBasicBlock"
external delete_block : llbasicblock -> unit = "llvm_delete_block"
external remove_block : llbasicblock -> unit = "llvm_remove_block"
external move_block_before : llbasicblock -> llbasicblock -> unit
= "llvm_move_block_before"
external move_block_after : llbasicblock -> llbasicblock -> unit
= "llvm_move_block_after"
external append_block : llcontext -> string -> llvalue -> llbasicblock
= "llvm_append_block"
external insert_block : llcontext -> string -> llbasicblock -> llbasicblock
= "llvm_insert_block"
external block_begin : llvalue -> (llvalue, llbasicblock) llpos
= "llvm_block_begin"
external block_succ : llbasicblock -> (llvalue, llbasicblock) llpos
= "llvm_block_succ"
external block_end : llvalue -> (llvalue, llbasicblock) llrev_pos
= "llvm_block_end"
external block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos
= "llvm_block_pred"
external block_terminator : llbasicblock -> llvalue option =
"llvm_block_terminator"
let rec iter_block_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid block range.")
| Before bb ->
f bb;
iter_block_range f (block_succ bb) e
let iter_blocks f fn =
iter_block_range f (block_begin fn) (At_end fn)
let rec fold_left_block_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid block range.")
| Before bb -> fold_left_block_range f (f init bb) (block_succ bb) e
let fold_left_blocks f init fn =
fold_left_block_range f init (block_begin fn) (At_end fn)
let rec rev_iter_block_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid block range.")
| After bb ->
f bb;
rev_iter_block_range f (block_pred bb) e
let rev_iter_blocks f fn =
rev_iter_block_range f (block_end fn) (At_start fn)
let rec fold_right_block_range f init i e =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid block range.")
| After bb -> fold_right_block_range f (f bb init) (block_pred bb) e
let fold_right_blocks f fn init =
fold_right_block_range f init (block_end fn) (At_start fn)
external instr_parent : llvalue -> llbasicblock = "LLVMGetInstructionParent"
external instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos
= "llvm_instr_begin"
external instr_succ : llvalue -> (llbasicblock, llvalue) llpos
= "llvm_instr_succ"
external instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos
= "llvm_instr_end"
external instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos
= "llvm_instr_pred"
external instr_opcode : llvalue -> Opcode.t = "llvm_instr_get_opcode"
external icmp_predicate : llvalue -> Icmp.t option = "llvm_instr_icmp_predicate"
external fcmp_predicate : llvalue -> Fcmp.t option = "llvm_instr_fcmp_predicate"
external atomicrmw_binop : llvalue -> AtomicRMWBinOp.t = "llvm_instr_get_atomicrmw_binop"
external instr_clone : llvalue -> llvalue = "llvm_instr_clone"
let rec iter_instrs_range f i e =
if i = e then () else
match i with
| At_end _ -> raise (Invalid_argument "Invalid instruction range.")
| Before i ->
f i;
iter_instrs_range f (instr_succ i) e
let iter_instrs f bb =
iter_instrs_range f (instr_begin bb) (At_end bb)
let rec fold_left_instrs_range f init i e =
if i = e then init else
match i with
| At_end _ -> raise (Invalid_argument "Invalid instruction range.")
| Before i -> fold_left_instrs_range f (f init i) (instr_succ i) e
let fold_left_instrs f init bb =
fold_left_instrs_range f init (instr_begin bb) (At_end bb)
let rec rev_iter_instrs_range f i e =
if i = e then () else
match i with
| At_start _ -> raise (Invalid_argument "Invalid instruction range.")
| After i ->
f i;
rev_iter_instrs_range f (instr_pred i) e
let rev_iter_instrs f bb =
rev_iter_instrs_range f (instr_end bb) (At_start bb)
let rec fold_right_instr_range f i e init =
if i = e then init else
match i with
| At_start _ -> raise (Invalid_argument "Invalid instruction range.")
| After i -> fold_right_instr_range f (instr_pred i) e (f i init)
let fold_right_instrs f bb init =
fold_right_instr_range f (instr_end bb) (At_start bb) init
external instruction_call_conv: llvalue -> int
= "llvm_instruction_call_conv"
external set_instruction_call_conv: int -> llvalue -> unit
= "llvm_set_instruction_call_conv"
external llvm_add_call_site_attr : llvalue -> llattribute -> int -> unit
= "llvm_add_call_site_attr"
external llvm_call_site_attrs : llvalue -> int -> llattribute array
= "llvm_call_site_attrs"
external llvm_remove_enum_call_site_attr : llvalue -> llattrkind -> int -> unit
= "llvm_remove_enum_call_site_attr"
external llvm_remove_string_call_site_attr : llvalue -> string -> int -> unit
= "llvm_remove_string_call_site_attr"
let add_call_site_attr f a i =
llvm_add_call_site_attr f a (AttrIndex.to_int i)
let call_site_attrs f i =
llvm_call_site_attrs f (AttrIndex.to_int i)
let remove_enum_call_site_attr f k i =
llvm_remove_enum_call_site_attr f k (AttrIndex.to_int i)
let remove_string_call_site_attr f k i =
llvm_remove_string_call_site_attr f k (AttrIndex.to_int i)
external num_arg_operands : llvalue -> int = "llvm_num_arg_operands"
external is_tail_call : llvalue -> bool = "llvm_is_tail_call"
external set_tail_call : bool -> llvalue -> unit = "llvm_set_tail_call"
external get_normal_dest : llvalue -> llbasicblock = "LLVMGetNormalDest"
external get_unwind_dest : llvalue -> llbasicblock = "LLVMGetUnwindDest"
external is_volatile : llvalue -> bool = "llvm_is_volatile"
external set_volatile : bool -> llvalue -> unit = "llvm_set_volatile"
let is_terminator llv =
let open ValueKind in
let open Opcode in
match classify_value llv with
| Instruction (Br | IndirectBr | Invoke | Resume | Ret | Switch | Unreachable)
-> true
| _ -> false
external successor : llvalue -> int -> llbasicblock = "llvm_successor"
external set_successor : llvalue -> int -> llbasicblock -> unit
= "llvm_set_successor"
external num_successors : llvalue -> int = "llvm_num_successors"
let successors llv =
if not (is_terminator llv) then
raise (Invalid_argument "Llvm.successors can only be used on terminators")
else
Array.init (num_successors llv) (successor llv)
let iter_successors f llv =
if not (is_terminator llv) then
raise (Invalid_argument "Llvm.iter_successors can only be used on terminators")
else
for i = 0 to num_successors llv - 1 do
f (successor llv i)
done
let fold_successors f llv z =
if not (is_terminator llv) then
raise (Invalid_argument "Llvm.fold_successors can only be used on terminators")
else
let n = num_successors llv in
let rec aux i acc =
if i >= n then acc
else begin
let llb = successor llv i in
aux (i+1) (f llb acc)
end
in aux 0 z
external condition : llvalue -> llvalue = "llvm_condition"
external set_condition : llvalue -> llvalue -> unit
= "llvm_set_condition"
external is_conditional : llvalue -> bool = "llvm_is_conditional"
let get_branch llv =
if classify_value llv <> ValueKind.Instruction Opcode.Br then
None
else if is_conditional llv then
Some (`Conditional (condition llv, successor llv 0, successor llv 1))
else
Some (`Unconditional (successor llv 0))
-- ... Operations on phi nodes ............................................ --
external add_incoming : (llvalue * llbasicblock) -> llvalue -> unit
= "llvm_add_incoming"
external incoming : llvalue -> (llvalue * llbasicblock) list = "llvm_incoming"
external delete_instruction : llvalue -> unit = "llvm_delete_instruction"
external builder : llcontext -> llbuilder = "llvm_builder"
external position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit
= "llvm_position_builder"
external insertion_block : llbuilder -> llbasicblock = "llvm_insertion_block"
external insert_into_builder : llvalue -> string -> llbuilder -> unit
= "llvm_insert_into_builder"
let builder_at context ip =
let b = builder context in
position_builder ip b;
b
let builder_before context i = builder_at context (Before i)
let builder_at_end context bb = builder_at context (At_end bb)
let position_before i = position_builder (Before i)
let position_at_end bb = position_builder (At_end bb)
external set_current_debug_location : llbuilder -> llvalue -> unit
= "llvm_set_current_debug_location"
external clear_current_debug_location : llbuilder -> unit
= "llvm_clear_current_debug_location"
external current_debug_location : llbuilder -> llvalue option
= "llvm_current_debug_location"
external set_inst_debug_location : llbuilder -> llvalue -> unit
= "llvm_set_inst_debug_location"
external build_ret_void : llbuilder -> llvalue = "llvm_build_ret_void"
external build_ret : llvalue -> llbuilder -> llvalue = "llvm_build_ret"
external build_aggregate_ret : llvalue array -> llbuilder -> llvalue
= "llvm_build_aggregate_ret"
external build_br : llbasicblock -> llbuilder -> llvalue = "llvm_build_br"
external build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder ->
llvalue = "llvm_build_cond_br"
external build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue
= "llvm_build_switch"
external build_malloc : lltype -> string -> llbuilder -> llvalue =
"llvm_build_malloc"
external build_array_malloc : lltype -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_array_malloc"
external build_free : llvalue -> llbuilder -> llvalue = "llvm_build_free"
external add_case : llvalue -> llvalue -> llbasicblock -> unit
= "llvm_add_case"
external switch_default_dest : llvalue -> llbasicblock =
"LLVMGetSwitchDefaultDest"
external build_indirect_br : llvalue -> int -> llbuilder -> llvalue
= "llvm_build_indirect_br"
external add_destination : llvalue -> llbasicblock -> unit
= "llvm_add_destination"
external build_invoke : llvalue -> llvalue array -> llbasicblock ->
llbasicblock -> string -> llbuilder -> llvalue
= "llvm_build_invoke_bc" "llvm_build_invoke_nat"
external build_landingpad : lltype -> llvalue -> int -> string -> llbuilder ->
llvalue = "llvm_build_landingpad"
external is_cleanup : llvalue -> bool = "llvm_is_cleanup"
external set_cleanup : llvalue -> bool -> unit = "llvm_set_cleanup"
external add_clause : llvalue -> llvalue -> unit = "llvm_add_clause"
external build_resume : llvalue -> llbuilder -> llvalue = "llvm_build_resume"
external build_unreachable : llbuilder -> llvalue = "llvm_build_unreachable"
external build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_add"
external build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_add"
external build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_add"
external build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fadd"
external build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_sub"
external build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_sub"
external build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_sub"
external build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fsub"
external build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_mul"
external build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_mul"
external build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_mul"
external build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fmul"
external build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_udiv"
external build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_sdiv"
external build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_exact_sdiv"
external build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fdiv"
external build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_urem"
external build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_srem"
external build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_frem"
external build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_shl"
external build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_lshr"
external build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_ashr"
external build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_and"
external build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_or"
external build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_xor"
external build_neg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_neg"
external build_nsw_neg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nsw_neg"
external build_nuw_neg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_nuw_neg"
external build_fneg : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_fneg"
external build_not : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_not"
external build_alloca : lltype -> string -> llbuilder -> llvalue
= "llvm_build_alloca"
external build_array_alloca : lltype -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_array_alloca"
external build_load : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_load"
external build_store : llvalue -> llvalue -> llbuilder -> llvalue
= "llvm_build_store"
external build_atomicrmw : AtomicRMWBinOp.t -> llvalue -> llvalue ->
AtomicOrdering.t -> bool -> string -> llbuilder ->
llvalue
= "llvm_build_atomicrmw_bytecode"
"llvm_build_atomicrmw_native"
external build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue
= "llvm_build_gep"
external build_in_bounds_gep : llvalue -> llvalue array -> string ->
llbuilder -> llvalue = "llvm_build_in_bounds_gep"
external build_struct_gep : llvalue -> int -> string -> llbuilder -> llvalue
= "llvm_build_struct_gep"
external build_global_string : string -> string -> llbuilder -> llvalue
= "llvm_build_global_string"
external build_global_stringptr : string -> string -> llbuilder -> llvalue
= "llvm_build_global_stringptr"
external build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_trunc"
external build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_zext"
external build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_sext"
external build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fptoui"
external build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fptosi"
external build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_uitofp"
external build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_sitofp"
external build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fptrunc"
external build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fpext"
external build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_prttoint"
external build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_inttoptr"
external build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_bitcast"
external build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
llvalue = "llvm_build_zext_or_bitcast"
external build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
llvalue = "llvm_build_sext_or_bitcast"
external build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder ->
llvalue = "llvm_build_trunc_or_bitcast"
external build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_pointercast"
external build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_intcast"
external build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_fpcast"
external build_icmp : Icmp.t -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_icmp"
external build_fcmp : Fcmp.t -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_fcmp"
external build_phi : (llvalue * llbasicblock) list -> string -> llbuilder ->
llvalue = "llvm_build_phi"
external build_empty_phi : lltype -> string -> llbuilder -> llvalue
= "llvm_build_empty_phi"
external build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue
= "llvm_build_call"
external build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_select"
external build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue
= "llvm_build_va_arg"
external build_extractelement : llvalue -> llvalue -> string -> llbuilder ->
llvalue = "llvm_build_extractelement"
external build_insertelement : llvalue -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_insertelement"
external build_shufflevector : llvalue -> llvalue -> llvalue -> string ->
llbuilder -> llvalue = "llvm_build_shufflevector"
external build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue
= "llvm_build_extractvalue"
external build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder ->
llvalue = "llvm_build_insertvalue"
external build_is_null : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_is_null"
external build_is_not_null : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_is_not_null"
external build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue
= "llvm_build_ptrdiff"
external build_freeze : llvalue -> string -> llbuilder -> llvalue
= "llvm_build_freeze"
module MemoryBuffer = struct
external of_file : string -> llmemorybuffer = "llvm_memorybuffer_of_file"
external of_stdin : unit -> llmemorybuffer = "llvm_memorybuffer_of_stdin"
external of_string : ?name:string -> string -> llmemorybuffer
= "llvm_memorybuffer_of_string"
external as_string : llmemorybuffer -> string = "llvm_memorybuffer_as_string"
external dispose : llmemorybuffer -> unit = "llvm_memorybuffer_dispose"
end
module PassManager = struct
type 'a t
type any = [ `Module | `Function ]
external create : unit -> [ `Module ] t = "llvm_passmanager_create"
external create_function : llmodule -> [ `Function ] t
= "LLVMCreateFunctionPassManager"
external run_module : llmodule -> [ `Module ] t -> bool
= "llvm_passmanager_run_module"
external initialize : [ `Function ] t -> bool = "llvm_passmanager_initialize"
external run_function : llvalue -> [ `Function ] t -> bool
= "llvm_passmanager_run_function"
external finalize : [ `Function ] t -> bool = "llvm_passmanager_finalize"
external dispose : [< any ] t -> unit = "llvm_passmanager_dispose"
end
|
ad10643d6ddd105868d93b9277887cfdcad798a4828983b657547a81c27a5b4e | RutledgePaulV/datalogger | protos.clj | (ns datalogger.protos
(:require [datalogger.impl.config :as config]
[datalogger.impl.utils :as utils]
[clojure.stacktrace :as stack])
(:import (clojure.lang MapEntry Keyword Delay Atom ISeq Volatile Namespace Symbol)
(java.util Map Set List)
(java.time Instant)
(java.util.function Supplier)))
(set! *warn-on-reflection* true)
(defprotocol LoggableData
:extend-via-metadata true
(as-data [x options]
"Convert x into serializable (as json) data.
Also handle any pruning of sensitive values (defined by options).
Also produce a deterministic ordering of any unordered collections."))
(extend-protocol LoggableData
Object
(as-data [x {:keys [object-mapper]}]
(if (config/serializable? object-mapper x)
x
(.getName (class x))))
StackTraceElement
(as-data [x options]
(as-data
{:class (.getClassName x)
:method (.getMethodName x)
:filename (.getFileName x)
:line (.getLineNumber x)}
options))
Thread
(as-data [x options]
(.getName x))
Instant
(as-data [x options]
(str x))
Symbol
(as-data [x options]
(utils/stringify-key x))
Namespace
(as-data [x options]
(as-data (.getName x) options))
Throwable
(as-data [x options]
(as-data
(if (:root-only options)
(let [root ^Throwable (stack/root-cause x)]
(cond-> {:message (ex-message root) :trace (vec (.getStackTrace root))}
(ex-data root) (assoc :data (ex-data root))))
(cond-> {:message (ex-message x) :trace (vec (.getStackTrace x))}
(ex-data x) (assoc :data (ex-data x))
(.getCause x) (assoc :cause (.getCause x))))
options))
String
(as-data [x {:keys [mask-val? masker]}]
(if (mask-val? x)
(masker x)
x))
Keyword
(as-data [x options]
(utils/stringify-key x))
Number
(as-data [x options] x)
Boolean
(as-data [x options] x)
Atom
(as-data [x options]
(as-data (deref x) options))
Volatile
(as-data [x options]
(as-data (deref x) options))
Delay
(as-data [x options]
(as-data (force x) options))
Supplier
(as-data [x options]
(as-data (.get x) options))
nil
(as-data [x options] x)
MapEntry
(as-data [x {:keys [mask-key? masker elide?] :as options}]
(cond
(or (nil? (key x)) (elide? (key x)))
nil
(mask-key? (key x))
[(as-data (key x) options) (masker (val x))]
:otherwise
[(as-data (key x) options) (as-data (val x) options)]))
Map
(as-data [x options]
(let [entries (keep #(as-data % options) x)]
(try
(into (sorted-map) entries)
(catch Exception e
; in case it includes things that aren't comparable
(into {} entries)))))
Set
(as-data [x options]
(let [entries (map #(as-data % options) x)]
(try
(into (sorted-set) entries)
(catch Exception e
; in case it includes things that aren't comparable
(into #{} entries)))))
ISeq
(as-data [x options]
(mapv #(as-data % options) x))
List
(as-data [x options]
(mapv #(as-data % options) x))) | null | https://raw.githubusercontent.com/RutledgePaulV/datalogger/200c14fc230b9bc64d6dc0150ad2262d22c154af/src/datalogger/protos.clj | clojure | in case it includes things that aren't comparable
in case it includes things that aren't comparable | (ns datalogger.protos
(:require [datalogger.impl.config :as config]
[datalogger.impl.utils :as utils]
[clojure.stacktrace :as stack])
(:import (clojure.lang MapEntry Keyword Delay Atom ISeq Volatile Namespace Symbol)
(java.util Map Set List)
(java.time Instant)
(java.util.function Supplier)))
(set! *warn-on-reflection* true)
(defprotocol LoggableData
:extend-via-metadata true
(as-data [x options]
"Convert x into serializable (as json) data.
Also handle any pruning of sensitive values (defined by options).
Also produce a deterministic ordering of any unordered collections."))
(extend-protocol LoggableData
Object
(as-data [x {:keys [object-mapper]}]
(if (config/serializable? object-mapper x)
x
(.getName (class x))))
StackTraceElement
(as-data [x options]
(as-data
{:class (.getClassName x)
:method (.getMethodName x)
:filename (.getFileName x)
:line (.getLineNumber x)}
options))
Thread
(as-data [x options]
(.getName x))
Instant
(as-data [x options]
(str x))
Symbol
(as-data [x options]
(utils/stringify-key x))
Namespace
(as-data [x options]
(as-data (.getName x) options))
Throwable
(as-data [x options]
(as-data
(if (:root-only options)
(let [root ^Throwable (stack/root-cause x)]
(cond-> {:message (ex-message root) :trace (vec (.getStackTrace root))}
(ex-data root) (assoc :data (ex-data root))))
(cond-> {:message (ex-message x) :trace (vec (.getStackTrace x))}
(ex-data x) (assoc :data (ex-data x))
(.getCause x) (assoc :cause (.getCause x))))
options))
String
(as-data [x {:keys [mask-val? masker]}]
(if (mask-val? x)
(masker x)
x))
Keyword
(as-data [x options]
(utils/stringify-key x))
Number
(as-data [x options] x)
Boolean
(as-data [x options] x)
Atom
(as-data [x options]
(as-data (deref x) options))
Volatile
(as-data [x options]
(as-data (deref x) options))
Delay
(as-data [x options]
(as-data (force x) options))
Supplier
(as-data [x options]
(as-data (.get x) options))
nil
(as-data [x options] x)
MapEntry
(as-data [x {:keys [mask-key? masker elide?] :as options}]
(cond
(or (nil? (key x)) (elide? (key x)))
nil
(mask-key? (key x))
[(as-data (key x) options) (masker (val x))]
:otherwise
[(as-data (key x) options) (as-data (val x) options)]))
Map
(as-data [x options]
(let [entries (keep #(as-data % options) x)]
(try
(into (sorted-map) entries)
(catch Exception e
(into {} entries)))))
Set
(as-data [x options]
(let [entries (map #(as-data % options) x)]
(try
(into (sorted-set) entries)
(catch Exception e
(into #{} entries)))))
ISeq
(as-data [x options]
(mapv #(as-data % options) x))
List
(as-data [x options]
(mapv #(as-data % options) x))) |
374bd66d8b617ad6d752c9b011b835210302ce4adfe6959f264dbd81f7cb525d | deadtrickster/prometheus.cl | package.lisp | (in-package #:cl-user)
(defpackage #:prometheus.sbcl
(:use #:cl #:alexandria)
(:nicknames #:prom.sbcl)
(:export #:make-threads-collector
#:make-memory-collector))
| null | https://raw.githubusercontent.com/deadtrickster/prometheus.cl/60572b793135e8ab5a857d47cc1a5fe0af3a2d53/src/collectors/sbcl/package.lisp | lisp | (in-package #:cl-user)
(defpackage #:prometheus.sbcl
(:use #:cl #:alexandria)
(:nicknames #:prom.sbcl)
(:export #:make-threads-collector
#:make-memory-collector))
| |
b16898e586b2b9ee245ca255362839c44008030946b9343b074635c1c48acc8c | mirage/irmin | tree_intf.ml |
* Copyright ( c ) 2013 - 2022 < >
* Copyright ( c ) 2017 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2022 Thomas Gazagnaire <>
* Copyright (c) 2017 Grégoire Henry <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open! Import
module type S = sig
type path [@@deriving irmin]
type step [@@deriving irmin]
type metadata [@@deriving irmin]
type contents [@@deriving irmin]
type contents_key [@@deriving irmin]
type node [@@deriving irmin]
type hash [@@deriving irmin]
* [ Tree ] provides immutable , in - memory partial mirror of the store , with
lazy reads and delayed writes .
Trees are like staging area in : they are immutable temporary
non - persistent areas ( they disappear if the host crash ) , held in memory
for efficiency , where reads are done lazily and writes are done only when
needed on commit : if you modify a key twice , only the last change will be
written to the store when you commit .
lazy reads and delayed writes.
Trees are like staging area in Git: they are immutable temporary
non-persistent areas (they disappear if the host crash), held in memory
for efficiency, where reads are done lazily and writes are done only when
needed on commit: if you modify a key twice, only the last change will be
written to the store when you commit. *)
type t [@@deriving irmin]
(** The type of trees. *)
(** {1 Constructors} *)
val empty : unit -> t
(** [empty ()] is the empty tree. The empty tree does not have associated
backend configuration values, as they can perform in-memory operation,
independently of any given backend. *)
val singleton : path -> ?metadata:metadata -> contents -> t
(** [singleton k c] is the tree with a single binding mapping the key [k] to
the contents [c]. *)
val of_contents : ?metadata:metadata -> contents -> t
(** [of_contents c] is the subtree built from the contents [c]. *)
val of_node : node -> t
(** [of_node n] is the subtree built from the node [n]. *)
type elt = [ `Node of node | `Contents of contents * metadata ]
(** The type for tree elements. *)
val v : elt -> t
(** General-purpose constructor for trees. *)
type kinded_hash = [ `Contents of hash * metadata | `Node of hash ]
[@@deriving irmin]
val pruned : kinded_hash -> t
* [ pruned h ] is a purely in - memory tree with the hash [ h ] . Such trees can be
used as children of other in - memory tree nodes , for instance in order to
compute the hash of the parent , but they can not be dereferenced .
Any operation that would require loading the contents of a pruned node
( e.g. calling { ! find } on one of its children ) will instead raise a
{ ! Pruned_hash } exception . Attempting to export a tree containing pruned
sub - trees to a repository will fail similarly .
used as children of other in-memory tree nodes, for instance in order to
compute the hash of the parent, but they cannot be dereferenced.
Any operation that would require loading the contents of a pruned node
(e.g. calling {!find} on one of its children) will instead raise a
{!Pruned_hash} exception. Attempting to export a tree containing pruned
sub-trees to a repository will fail similarly. *)
val kind : t -> path -> [ `Contents | `Node ] option Lwt.t
(** [kind t k] is the type of [s] in [t]. It could either be a tree node or
some file contents. It is [None] if [k] is not present in [t]. *)
val is_empty : t -> bool
(** [is_empty t] is true iff [t] is {!empty} (i.e. a tree node with no
children). Trees with {!kind} = [`Contents] are never considered empty. *)
(** {1 Diffs} *)
val diff : t -> t -> (path * (contents * metadata) Diff.t) list Lwt.t
(** [diff x y] is the difference of contents between [x] and [y]. *)
(** {1 Manipulating Contents} *)
exception Dangling_hash of { context : string; hash : hash }
(** The exception raised by functions that can force lazy tree nodes but do
not return an explicit {!or_error}. *)
exception Pruned_hash of { context : string; hash : hash }
(** The exception raised by functions that attempts to load {!pruned} tree
nodes. *)
exception Portable_value of { context : string }
* The exception raised by functions that attemps to perform IO on a portable
tree .
tree. *)
type error =
[ `Dangling_hash of hash | `Pruned_hash of hash | `Portable_value ]
type 'a or_error = ('a, error) result
(** Operations on lazy tree contents. *)
module Contents : sig
type t
(** The type of lazy tree contents. *)
val hash : ?cache:bool -> t -> hash
* [ hash t ] is the hash of the { ! contents } value returned when [ t ] is
{ ! successfully . See { ! caching } for an explanation of the
[ cache ] parameter .
{!val-force}d successfully. See {!caching} for an explanation of the
[cache] parameter. *)
val key : t -> contents_key option
* [ key t ] is the key of the { ! contents } value returned when [ t ] is
{ ! successfully .
{!val-force}d successfully. *)
val force : t -> contents or_error Lwt.t
(** [force t] forces evaluation of the lazy content value [t], or returns an
error if no such value exists in the underlying repository. *)
val force_exn : t -> contents Lwt.t
(** Equivalent to {!val-force}, but raises an exception if the lazy content
value is not present in the underlying repository. *)
val clear : t -> unit
(** [clear t] clears [t]'s cache. *)
* { 2 : caching caching }
[ cache ] regulates the caching behaviour regarding the node 's internal
data which are be lazily loaded from the backend .
[ cache ] defaults to [ true ] which may greatly reduce the IOs and the
runtime but may also grealy increase the memory consumption .
[ cache = false ] does n't replace a call to [ clear ] , it only prevents the
storing of new data , it does n't discard the existing one .
[cache] regulates the caching behaviour regarding the node's internal
data which are be lazily loaded from the backend.
[cache] defaults to [true] which may greatly reduce the IOs and the
runtime but may also grealy increase the memory consumption.
[cache = false] doesn't replace a call to [clear], it only prevents the
storing of new data, it doesn't discard the existing one. *)
end
val mem : t -> path -> bool Lwt.t
(** [mem t k] is true iff [k] is associated to some contents in [t]. *)
val find_all : t -> path -> (contents * metadata) option Lwt.t
(** [find_all t k] is [Some (b, m)] if [k] is associated to the contents [b]
and metadata [m] in [t] and [None] if [k] is not present in [t]. *)
val length : t -> ?cache:bool -> path -> int Lwt.t
* [ length t key ] is the number of files and sub - nodes stored under [ key ] in
[ t ] .
It is equivalent to [ ( list t k ) ] but backends might optimise
this call : for instance it 's a constant time operation in [ irmin - pack ] .
[ cache ] defaults to [ true ] , see { ! caching } for an explanation of the
parameter .
[t].
It is equivalent to [List.length (list t k)] but backends might optimise
this call: for instance it's a constant time operation in [irmin-pack].
[cache] defaults to [true], see {!caching} for an explanation of the
parameter.*)
val find : t -> path -> contents option Lwt.t
(** [find] is similar to {!find_all} but it discards metadata. *)
val get_all : t -> path -> (contents * metadata) Lwt.t
(** Same as {!find_all} but raise [Invalid_arg] if [k] is not present in [t]. *)
val list :
t ->
?offset:int ->
?length:int ->
?cache:bool ->
path ->
(step * t) list Lwt.t
(** [list t key] is the list of files and sub-nodes stored under [k] in [t].
The result order is not specified but is stable.
[offset] and [length] are used for pagination.
[cache] defaults to [true], see {!Contents.caching} for an explanation of
the parameter. *)
val seq :
t ->
?offset:int ->
?length:int ->
?cache:bool ->
path ->
(step * t) Seq.t Lwt.t
(** [seq t key] follows the same behavior as {!list} but returns a sequence. *)
val get : t -> path -> contents Lwt.t
(** Same as {!get_all} but ignore the metadata. *)
val add : t -> path -> ?metadata:metadata -> contents -> t Lwt.t
(** [add t k c] is the tree where the key [k] is bound to the contents [c] but
is similar to [t] for other bindings. *)
val update :
t ->
path ->
?metadata:metadata ->
(contents option -> contents option) ->
t Lwt.t
(** [update t k f] is the tree [t'] that is the same as [t] for all keys
except [k], and whose binding for [k] is determined by [f (find t k)].
If [k] refers to an internal node of [t], [f] is called with [None] to
determine the value with which to replace it. *)
val remove : t -> path -> t Lwt.t
(** [remove t k] is the tree where [k] bindings has been removed but is
similar to [t] for other bindings. *)
* { 1 Manipulating Subtrees }
val mem_tree : t -> path -> bool Lwt.t
(** [mem_tree t k] is false iff [find_tree k = None]. *)
val find_tree : t -> path -> t option Lwt.t
(** [find_tree t k] is [Some v] if [k] is associated to [v] in [t]. It is
[None] if [k] is not present in [t]. *)
val get_tree : t -> path -> t Lwt.t
(** [get_tree t k] is [v] if [k] is associated to [v] in [t]. Raise
[Invalid_arg] if [k] is not present in [t].*)
val add_tree : t -> path -> t -> t Lwt.t
(** [add_tree t k v] is the tree where the key [k] is bound to the non-empty
tree [v] but is similar to [t] for other bindings.
If [v] is empty, this is equivalent to [remove t k]. *)
val update_tree : t -> path -> (t option -> t option) -> t Lwt.t
(** [update_tree t k f] is the tree [t'] that is the same as [t] for all
subtrees except under [k], and whose subtree at [k] is determined by
[f (find_tree t k)].
[f] returning either [None] or [Some empty] causes the subtree at [k] to
be unbound (i.e. it is equivalent to [remove t k]). *)
val merge : t Merge.t
* [ merge ] is the 3 - way merge function for trees .
(** {1 Folds} *)
val destruct : t -> [ `Node of node | `Contents of Contents.t * metadata ]
(** General-purpose destructor for trees. *)
type marks
(** The type for fold marks. *)
val empty_marks : unit -> marks
(** [empty_marks ()] is an empty collection of marks. *)
type 'a force = [ `True | `False of path -> 'a -> 'a Lwt.t ]
(** The type for {!fold}'s [force] parameter. [`True] forces the fold to read
the objects of the lazy nodes and contents. [`False f] is applying [f] on
every lazy node and content value instead. *)
type uniq = [ `False | `True | `Marks of marks ]
(** The type for {!fold}'s [uniq] parameters. [`False] folds over all the
nodes. [`True] does not recurse on nodes already seen. [`Marks m] uses the
collection of marks [m] to store the cache of keys: the fold will modify
[m]. This can be used for incremental folds. *)
type ('a, 'b) folder = path -> 'b -> 'a -> 'a Lwt.t
(** The type for {!fold}'s folders: [pre], [post], [contents], [node], and
[tree], where ['a] is the accumulator and ['b] is the item folded. *)
type depth = [ `Eq of int | `Le of int | `Lt of int | `Ge of int | `Gt of int ]
[@@deriving irmin]
(** The type for fold depths.
- [Eq d] folds over nodes and contents of depth exactly [d].
- [Lt d] folds over nodes and contents of depth strictly less than [d].
- [Gt d] folds over nodes and contents of depth strictly more than [d].
[Le d] is [Eq d] and [Lt d]. [Ge d] is [Eq d] and [Gt d]. *)
val fold :
?order:[ `Sorted | `Undefined | `Random of Random.State.t ] ->
?force:'a force ->
?cache:bool ->
?uniq:uniq ->
?pre:('a, step list) folder ->
?post:('a, step list) folder ->
?depth:depth ->
?contents:('a, contents) folder ->
?node:('a, node) folder ->
?tree:('a, t) folder ->
t ->
'a ->
'a Lwt.t
* [ fold t acc ] folds over [ t ] 's nodes with node - specific folders :
[ contents ] , [ node ] , and [ tree ] , based on a node 's { ! kind } .
The default for all folders is identity .
For every node [ n ] of [ t ] , including itself :
- If [ n ] is a [ ` Contents ] kind , call [ contents path c ] where [ c ] is the
{ ! contents } of [ n ] .
- If [ n ] is a [ ` Node ] kind , ( 1 ) call [ pre path steps ] ; ( 2 ) call
[ node path n ] ; ( 3 ) recursively fold on each child ; ( 4 ) call
[ post path steps ] .
- If [ n ] is any kind , call [ tree path t ' ] where [ t ' ] is the tree of [ n ] .
See { { : }
examples / fold.ml } for a demo of the different { ! folder}s .
See { ! force } for details about the [ force ] parameters . By default it is
[ ` True ] .
See { ! uniq } for details about the [ uniq ] parameters . By default it is
[ ` False ] .
The fold depth is controlled by the [ depth ] parameter .
[ cache ] defaults to [ false ] , see { ! Contents.caching } for an explanation of
the parameter .
If [ order ] is [ ` Sorted ] ( the default ) , the elements are traversed in
lexicographic order of their keys . If [ ` Random state ] , they are traversed
in a random order . For large nodes , these two modes are memory - consuming ,
use [ ` Undefined ] for a more memory efficient [ fold ] .
[contents], [node], and [tree], based on a node's {!kind}.
The default for all folders is identity.
For every node [n] of [t], including itself:
- If [n] is a [`Contents] kind, call [contents path c] where [c] is the
{!contents} of [n].
- If [n] is a [`Node] kind, (1) call [pre path steps]; (2) call
[node path n]; (3) recursively fold on each child; (4) call
[post path steps].
- If [n] is any kind, call [tree path t'] where [t'] is the tree of [n].
See {{:}
examples/fold.ml} for a demo of the different {!folder}s.
See {!force} for details about the [force] parameters. By default it is
[`True].
See {!uniq} for details about the [uniq] parameters. By default it is
[`False].
The fold depth is controlled by the [depth] parameter.
[cache] defaults to [false], see {!Contents.caching} for an explanation of
the parameter.
If [order] is [`Sorted] (the default), the elements are traversed in
lexicographic order of their keys. If [`Random state], they are traversed
in a random order. For large nodes, these two modes are memory-consuming,
use [`Undefined] for a more memory efficient [fold]. *)
(** {1 Stats} *)
type stats = {
nodes : int; (** Number of node. *)
leafs : int; (** Number of leafs. *)
skips : int; (** Number of lazy nodes. *)
depth : int; (** Maximal depth. *)
width : int; (** Maximal width. *)
}
[@@deriving irmin]
(** The type for tree stats. *)
val stats : ?force:bool -> t -> stats Lwt.t
* [ stats ~force t ] are [ t ] 's statistics . If [ force ] is true , this will force
the reading of lazy nodes . By default it is [ false ] .
the reading of lazy nodes. By default it is [false]. *)
(** {1 Concrete Trees} *)
type concrete =
[ `Tree of (step * concrete) list | `Contents of contents * metadata ]
[@@deriving irmin]
(** The type for concrete trees. *)
val of_concrete : concrete -> t
(** [of_concrete c] is the subtree equivalent of the concrete tree [c].
@raise Invalid_argument
if [c] contains duplicate bindings for a given path. *)
val to_concrete : t -> concrete Lwt.t
(** [to_concrete t] is the concrete tree equivalent of the subtree [t]. *)
(** {1 Proofs} *)
module Proof : sig
include
Proof.S
with type contents := contents
and type hash := hash
and type step := step
and type metadata := metadata
type irmin_tree
val to_tree : tree t -> irmin_tree
(** [to_tree p] is the tree [t] representing the tree proof [p]. Blinded
parts of the proof will raise [Dangling_hash] when traversed. *)
end
with type irmin_tree := t
(** {1 Caches} *)
val clear : ?depth:int -> t -> unit
(** [clear ?depth t] clears all caches in the tree [t] for subtrees with a
depth higher than [depth]. If [depth] is not set, all of the subtrees are
cleared.
A call to [clear] doesn't discard the subtrees of [t], only their cache
are discarded. Even the lazily loaded and unmodified subtrees remain. *)
* { 1 Performance counters }
type counters = {
mutable contents_hash : int;
mutable contents_find : int;
mutable contents_add : int;
mutable contents_mem : int;
mutable node_hash : int;
mutable node_mem : int;
mutable node_index : int;
mutable node_add : int;
mutable node_find : int;
mutable node_val_v : int;
mutable node_val_find : int;
mutable node_val_list : int;
}
val counters : unit -> counters
val dump_counters : unit Fmt.t
val reset_counters : unit -> unit
val inspect :
t ->
[ `Contents | `Node of [ `Map | `Key | `Value | `Portable_dirty | `Pruned ] ]
(** [inspect t] is similar to {!kind}, with additional state information for
nodes. It is primarily useful for debugging and testing.
If [t] holds a node, additional information about its state is included:
- [`Map], if [t] is from {!of_concrete}.
- [`Value], if [t]'s node has modifications that have not been persisted
to a store.
- [`Portable_dirty], if [t]'s node has modifications and is
{!Node.Portable}. Currently only used with {!Proof}.
- [`Pruned], if [t] is from {!pruned}.
- Otherwise [`Key], the default state for a node loaded from a store. *)
module Private : sig
module Env : sig
type t [@@deriving irmin]
val is_empty : t -> bool
end
val get_env : t -> Env.t
end
end
module type Sigs = sig
module type S = sig
include S
* @inline
end
module Make (B : Backend.S) : sig
include
S
with type path = B.Node.Path.t
and type step = B.Node.Path.step
and type metadata = B.Node.Metadata.t
and type contents = B.Contents.value
and type contents_key = B.Contents.Key.t
and type hash = B.Hash.t
type kinded_key =
[ `Contents of B.Contents.Key.t * metadata | `Node of B.Node.Key.t ]
[@@deriving irmin]
val import : B.Repo.t -> kinded_key -> t option Lwt.t
val import_no_check : B.Repo.t -> kinded_key -> t
val export :
?clear:bool ->
B.Repo.t ->
[> write ] B.Contents.t ->
[> read_write ] B.Node.t ->
node ->
B.Node.key Lwt.t
val dump : t Fmt.t
val equal : t -> t -> bool
val key : t -> kinded_key option
val hash : ?cache:bool -> t -> kinded_hash
val to_backend_node : node -> B.Node.Val.t Lwt.t
val to_backend_portable_node : node -> B.Node_portable.t Lwt.t
val of_backend_node : B.Repo.t -> B.Node.value -> node
type ('proof, 'result) producer :=
B.Repo.t ->
kinded_key ->
(t -> (t * 'result) Lwt.t) ->
('proof * 'result) Lwt.t
type verifier_error =
[ `Proof_mismatch of string
| `Stream_too_long of string
| `Stream_too_short of string ]
[@@deriving irmin]
type ('proof, 'result) verifier :=
'proof ->
(t -> (t * 'result) Lwt.t) ->
(t * 'result, verifier_error) result Lwt.t
type tree_proof := Proof.tree Proof.t
val produce_proof : (tree_proof, 'a) producer
val verify_proof : (tree_proof, 'a) verifier
val hash_of_proof_state : Proof.tree -> kinded_hash
type stream_proof := Proof.stream Proof.t
val produce_stream : (stream_proof, 'a) producer
val verify_stream : (stream_proof, 'a) verifier
end
end
| null | https://raw.githubusercontent.com/mirage/irmin/4936dec5bb672552c1b9f09d1c6de08ccd762605/src/irmin/tree_intf.ml | ocaml | * The type of trees.
* {1 Constructors}
* [empty ()] is the empty tree. The empty tree does not have associated
backend configuration values, as they can perform in-memory operation,
independently of any given backend.
* [singleton k c] is the tree with a single binding mapping the key [k] to
the contents [c].
* [of_contents c] is the subtree built from the contents [c].
* [of_node n] is the subtree built from the node [n].
* The type for tree elements.
* General-purpose constructor for trees.
* [kind t k] is the type of [s] in [t]. It could either be a tree node or
some file contents. It is [None] if [k] is not present in [t].
* [is_empty t] is true iff [t] is {!empty} (i.e. a tree node with no
children). Trees with {!kind} = [`Contents] are never considered empty.
* {1 Diffs}
* [diff x y] is the difference of contents between [x] and [y].
* {1 Manipulating Contents}
* The exception raised by functions that can force lazy tree nodes but do
not return an explicit {!or_error}.
* The exception raised by functions that attempts to load {!pruned} tree
nodes.
* Operations on lazy tree contents.
* The type of lazy tree contents.
* [force t] forces evaluation of the lazy content value [t], or returns an
error if no such value exists in the underlying repository.
* Equivalent to {!val-force}, but raises an exception if the lazy content
value is not present in the underlying repository.
* [clear t] clears [t]'s cache.
* [mem t k] is true iff [k] is associated to some contents in [t].
* [find_all t k] is [Some (b, m)] if [k] is associated to the contents [b]
and metadata [m] in [t] and [None] if [k] is not present in [t].
* [find] is similar to {!find_all} but it discards metadata.
* Same as {!find_all} but raise [Invalid_arg] if [k] is not present in [t].
* [list t key] is the list of files and sub-nodes stored under [k] in [t].
The result order is not specified but is stable.
[offset] and [length] are used for pagination.
[cache] defaults to [true], see {!Contents.caching} for an explanation of
the parameter.
* [seq t key] follows the same behavior as {!list} but returns a sequence.
* Same as {!get_all} but ignore the metadata.
* [add t k c] is the tree where the key [k] is bound to the contents [c] but
is similar to [t] for other bindings.
* [update t k f] is the tree [t'] that is the same as [t] for all keys
except [k], and whose binding for [k] is determined by [f (find t k)].
If [k] refers to an internal node of [t], [f] is called with [None] to
determine the value with which to replace it.
* [remove t k] is the tree where [k] bindings has been removed but is
similar to [t] for other bindings.
* [mem_tree t k] is false iff [find_tree k = None].
* [find_tree t k] is [Some v] if [k] is associated to [v] in [t]. It is
[None] if [k] is not present in [t].
* [get_tree t k] is [v] if [k] is associated to [v] in [t]. Raise
[Invalid_arg] if [k] is not present in [t].
* [add_tree t k v] is the tree where the key [k] is bound to the non-empty
tree [v] but is similar to [t] for other bindings.
If [v] is empty, this is equivalent to [remove t k].
* [update_tree t k f] is the tree [t'] that is the same as [t] for all
subtrees except under [k], and whose subtree at [k] is determined by
[f (find_tree t k)].
[f] returning either [None] or [Some empty] causes the subtree at [k] to
be unbound (i.e. it is equivalent to [remove t k]).
* {1 Folds}
* General-purpose destructor for trees.
* The type for fold marks.
* [empty_marks ()] is an empty collection of marks.
* The type for {!fold}'s [force] parameter. [`True] forces the fold to read
the objects of the lazy nodes and contents. [`False f] is applying [f] on
every lazy node and content value instead.
* The type for {!fold}'s [uniq] parameters. [`False] folds over all the
nodes. [`True] does not recurse on nodes already seen. [`Marks m] uses the
collection of marks [m] to store the cache of keys: the fold will modify
[m]. This can be used for incremental folds.
* The type for {!fold}'s folders: [pre], [post], [contents], [node], and
[tree], where ['a] is the accumulator and ['b] is the item folded.
* The type for fold depths.
- [Eq d] folds over nodes and contents of depth exactly [d].
- [Lt d] folds over nodes and contents of depth strictly less than [d].
- [Gt d] folds over nodes and contents of depth strictly more than [d].
[Le d] is [Eq d] and [Lt d]. [Ge d] is [Eq d] and [Gt d].
* {1 Stats}
* Number of node.
* Number of leafs.
* Number of lazy nodes.
* Maximal depth.
* Maximal width.
* The type for tree stats.
* {1 Concrete Trees}
* The type for concrete trees.
* [of_concrete c] is the subtree equivalent of the concrete tree [c].
@raise Invalid_argument
if [c] contains duplicate bindings for a given path.
* [to_concrete t] is the concrete tree equivalent of the subtree [t].
* {1 Proofs}
* [to_tree p] is the tree [t] representing the tree proof [p]. Blinded
parts of the proof will raise [Dangling_hash] when traversed.
* {1 Caches}
* [clear ?depth t] clears all caches in the tree [t] for subtrees with a
depth higher than [depth]. If [depth] is not set, all of the subtrees are
cleared.
A call to [clear] doesn't discard the subtrees of [t], only their cache
are discarded. Even the lazily loaded and unmodified subtrees remain.
* [inspect t] is similar to {!kind}, with additional state information for
nodes. It is primarily useful for debugging and testing.
If [t] holds a node, additional information about its state is included:
- [`Map], if [t] is from {!of_concrete}.
- [`Value], if [t]'s node has modifications that have not been persisted
to a store.
- [`Portable_dirty], if [t]'s node has modifications and is
{!Node.Portable}. Currently only used with {!Proof}.
- [`Pruned], if [t] is from {!pruned}.
- Otherwise [`Key], the default state for a node loaded from a store. |
* Copyright ( c ) 2013 - 2022 < >
* Copyright ( c ) 2017 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2022 Thomas Gazagnaire <>
* Copyright (c) 2017 Grégoire Henry <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open! Import
module type S = sig
type path [@@deriving irmin]
type step [@@deriving irmin]
type metadata [@@deriving irmin]
type contents [@@deriving irmin]
type contents_key [@@deriving irmin]
type node [@@deriving irmin]
type hash [@@deriving irmin]
* [ Tree ] provides immutable , in - memory partial mirror of the store , with
lazy reads and delayed writes .
Trees are like staging area in : they are immutable temporary
non - persistent areas ( they disappear if the host crash ) , held in memory
for efficiency , where reads are done lazily and writes are done only when
needed on commit : if you modify a key twice , only the last change will be
written to the store when you commit .
lazy reads and delayed writes.
Trees are like staging area in Git: they are immutable temporary
non-persistent areas (they disappear if the host crash), held in memory
for efficiency, where reads are done lazily and writes are done only when
needed on commit: if you modify a key twice, only the last change will be
written to the store when you commit. *)
type t [@@deriving irmin]
val empty : unit -> t
val singleton : path -> ?metadata:metadata -> contents -> t
val of_contents : ?metadata:metadata -> contents -> t
val of_node : node -> t
type elt = [ `Node of node | `Contents of contents * metadata ]
val v : elt -> t
type kinded_hash = [ `Contents of hash * metadata | `Node of hash ]
[@@deriving irmin]
val pruned : kinded_hash -> t
* [ pruned h ] is a purely in - memory tree with the hash [ h ] . Such trees can be
used as children of other in - memory tree nodes , for instance in order to
compute the hash of the parent , but they can not be dereferenced .
Any operation that would require loading the contents of a pruned node
( e.g. calling { ! find } on one of its children ) will instead raise a
{ ! Pruned_hash } exception . Attempting to export a tree containing pruned
sub - trees to a repository will fail similarly .
used as children of other in-memory tree nodes, for instance in order to
compute the hash of the parent, but they cannot be dereferenced.
Any operation that would require loading the contents of a pruned node
(e.g. calling {!find} on one of its children) will instead raise a
{!Pruned_hash} exception. Attempting to export a tree containing pruned
sub-trees to a repository will fail similarly. *)
val kind : t -> path -> [ `Contents | `Node ] option Lwt.t
val is_empty : t -> bool
val diff : t -> t -> (path * (contents * metadata) Diff.t) list Lwt.t
exception Dangling_hash of { context : string; hash : hash }
exception Pruned_hash of { context : string; hash : hash }
exception Portable_value of { context : string }
* The exception raised by functions that attemps to perform IO on a portable
tree .
tree. *)
type error =
[ `Dangling_hash of hash | `Pruned_hash of hash | `Portable_value ]
type 'a or_error = ('a, error) result
module Contents : sig
type t
val hash : ?cache:bool -> t -> hash
* [ hash t ] is the hash of the { ! contents } value returned when [ t ] is
{ ! successfully . See { ! caching } for an explanation of the
[ cache ] parameter .
{!val-force}d successfully. See {!caching} for an explanation of the
[cache] parameter. *)
val key : t -> contents_key option
* [ key t ] is the key of the { ! contents } value returned when [ t ] is
{ ! successfully .
{!val-force}d successfully. *)
val force : t -> contents or_error Lwt.t
val force_exn : t -> contents Lwt.t
val clear : t -> unit
* { 2 : caching caching }
[ cache ] regulates the caching behaviour regarding the node 's internal
data which are be lazily loaded from the backend .
[ cache ] defaults to [ true ] which may greatly reduce the IOs and the
runtime but may also grealy increase the memory consumption .
[ cache = false ] does n't replace a call to [ clear ] , it only prevents the
storing of new data , it does n't discard the existing one .
[cache] regulates the caching behaviour regarding the node's internal
data which are be lazily loaded from the backend.
[cache] defaults to [true] which may greatly reduce the IOs and the
runtime but may also grealy increase the memory consumption.
[cache = false] doesn't replace a call to [clear], it only prevents the
storing of new data, it doesn't discard the existing one. *)
end
val mem : t -> path -> bool Lwt.t
val find_all : t -> path -> (contents * metadata) option Lwt.t
val length : t -> ?cache:bool -> path -> int Lwt.t
* [ length t key ] is the number of files and sub - nodes stored under [ key ] in
[ t ] .
It is equivalent to [ ( list t k ) ] but backends might optimise
this call : for instance it 's a constant time operation in [ irmin - pack ] .
[ cache ] defaults to [ true ] , see { ! caching } for an explanation of the
parameter .
[t].
It is equivalent to [List.length (list t k)] but backends might optimise
this call: for instance it's a constant time operation in [irmin-pack].
[cache] defaults to [true], see {!caching} for an explanation of the
parameter.*)
val find : t -> path -> contents option Lwt.t
val get_all : t -> path -> (contents * metadata) Lwt.t
val list :
t ->
?offset:int ->
?length:int ->
?cache:bool ->
path ->
(step * t) list Lwt.t
val seq :
t ->
?offset:int ->
?length:int ->
?cache:bool ->
path ->
(step * t) Seq.t Lwt.t
val get : t -> path -> contents Lwt.t
val add : t -> path -> ?metadata:metadata -> contents -> t Lwt.t
val update :
t ->
path ->
?metadata:metadata ->
(contents option -> contents option) ->
t Lwt.t
val remove : t -> path -> t Lwt.t
* { 1 Manipulating Subtrees }
val mem_tree : t -> path -> bool Lwt.t
val find_tree : t -> path -> t option Lwt.t
val get_tree : t -> path -> t Lwt.t
val add_tree : t -> path -> t -> t Lwt.t
val update_tree : t -> path -> (t option -> t option) -> t Lwt.t
val merge : t Merge.t
* [ merge ] is the 3 - way merge function for trees .
val destruct : t -> [ `Node of node | `Contents of Contents.t * metadata ]
type marks
val empty_marks : unit -> marks
type 'a force = [ `True | `False of path -> 'a -> 'a Lwt.t ]
type uniq = [ `False | `True | `Marks of marks ]
type ('a, 'b) folder = path -> 'b -> 'a -> 'a Lwt.t
type depth = [ `Eq of int | `Le of int | `Lt of int | `Ge of int | `Gt of int ]
[@@deriving irmin]
val fold :
?order:[ `Sorted | `Undefined | `Random of Random.State.t ] ->
?force:'a force ->
?cache:bool ->
?uniq:uniq ->
?pre:('a, step list) folder ->
?post:('a, step list) folder ->
?depth:depth ->
?contents:('a, contents) folder ->
?node:('a, node) folder ->
?tree:('a, t) folder ->
t ->
'a ->
'a Lwt.t
* [ fold t acc ] folds over [ t ] 's nodes with node - specific folders :
[ contents ] , [ node ] , and [ tree ] , based on a node 's { ! kind } .
The default for all folders is identity .
For every node [ n ] of [ t ] , including itself :
- If [ n ] is a [ ` Contents ] kind , call [ contents path c ] where [ c ] is the
{ ! contents } of [ n ] .
- If [ n ] is a [ ` Node ] kind , ( 1 ) call [ pre path steps ] ; ( 2 ) call
[ node path n ] ; ( 3 ) recursively fold on each child ; ( 4 ) call
[ post path steps ] .
- If [ n ] is any kind , call [ tree path t ' ] where [ t ' ] is the tree of [ n ] .
See { { : }
examples / fold.ml } for a demo of the different { ! folder}s .
See { ! force } for details about the [ force ] parameters . By default it is
[ ` True ] .
See { ! uniq } for details about the [ uniq ] parameters . By default it is
[ ` False ] .
The fold depth is controlled by the [ depth ] parameter .
[ cache ] defaults to [ false ] , see { ! Contents.caching } for an explanation of
the parameter .
If [ order ] is [ ` Sorted ] ( the default ) , the elements are traversed in
lexicographic order of their keys . If [ ` Random state ] , they are traversed
in a random order . For large nodes , these two modes are memory - consuming ,
use [ ` Undefined ] for a more memory efficient [ fold ] .
[contents], [node], and [tree], based on a node's {!kind}.
The default for all folders is identity.
For every node [n] of [t], including itself:
- If [n] is a [`Contents] kind, call [contents path c] where [c] is the
{!contents} of [n].
- If [n] is a [`Node] kind, (1) call [pre path steps]; (2) call
[node path n]; (3) recursively fold on each child; (4) call
[post path steps].
- If [n] is any kind, call [tree path t'] where [t'] is the tree of [n].
See {{:}
examples/fold.ml} for a demo of the different {!folder}s.
See {!force} for details about the [force] parameters. By default it is
[`True].
See {!uniq} for details about the [uniq] parameters. By default it is
[`False].
The fold depth is controlled by the [depth] parameter.
[cache] defaults to [false], see {!Contents.caching} for an explanation of
the parameter.
If [order] is [`Sorted] (the default), the elements are traversed in
lexicographic order of their keys. If [`Random state], they are traversed
in a random order. For large nodes, these two modes are memory-consuming,
use [`Undefined] for a more memory efficient [fold]. *)
type stats = {
}
[@@deriving irmin]
val stats : ?force:bool -> t -> stats Lwt.t
* [ stats ~force t ] are [ t ] 's statistics . If [ force ] is true , this will force
the reading of lazy nodes . By default it is [ false ] .
the reading of lazy nodes. By default it is [false]. *)
type concrete =
[ `Tree of (step * concrete) list | `Contents of contents * metadata ]
[@@deriving irmin]
val of_concrete : concrete -> t
val to_concrete : t -> concrete Lwt.t
module Proof : sig
include
Proof.S
with type contents := contents
and type hash := hash
and type step := step
and type metadata := metadata
type irmin_tree
val to_tree : tree t -> irmin_tree
end
with type irmin_tree := t
val clear : ?depth:int -> t -> unit
* { 1 Performance counters }
type counters = {
mutable contents_hash : int;
mutable contents_find : int;
mutable contents_add : int;
mutable contents_mem : int;
mutable node_hash : int;
mutable node_mem : int;
mutable node_index : int;
mutable node_add : int;
mutable node_find : int;
mutable node_val_v : int;
mutable node_val_find : int;
mutable node_val_list : int;
}
val counters : unit -> counters
val dump_counters : unit Fmt.t
val reset_counters : unit -> unit
val inspect :
t ->
[ `Contents | `Node of [ `Map | `Key | `Value | `Portable_dirty | `Pruned ] ]
module Private : sig
module Env : sig
type t [@@deriving irmin]
val is_empty : t -> bool
end
val get_env : t -> Env.t
end
end
module type Sigs = sig
module type S = sig
include S
* @inline
end
module Make (B : Backend.S) : sig
include
S
with type path = B.Node.Path.t
and type step = B.Node.Path.step
and type metadata = B.Node.Metadata.t
and type contents = B.Contents.value
and type contents_key = B.Contents.Key.t
and type hash = B.Hash.t
type kinded_key =
[ `Contents of B.Contents.Key.t * metadata | `Node of B.Node.Key.t ]
[@@deriving irmin]
val import : B.Repo.t -> kinded_key -> t option Lwt.t
val import_no_check : B.Repo.t -> kinded_key -> t
val export :
?clear:bool ->
B.Repo.t ->
[> write ] B.Contents.t ->
[> read_write ] B.Node.t ->
node ->
B.Node.key Lwt.t
val dump : t Fmt.t
val equal : t -> t -> bool
val key : t -> kinded_key option
val hash : ?cache:bool -> t -> kinded_hash
val to_backend_node : node -> B.Node.Val.t Lwt.t
val to_backend_portable_node : node -> B.Node_portable.t Lwt.t
val of_backend_node : B.Repo.t -> B.Node.value -> node
type ('proof, 'result) producer :=
B.Repo.t ->
kinded_key ->
(t -> (t * 'result) Lwt.t) ->
('proof * 'result) Lwt.t
type verifier_error =
[ `Proof_mismatch of string
| `Stream_too_long of string
| `Stream_too_short of string ]
[@@deriving irmin]
type ('proof, 'result) verifier :=
'proof ->
(t -> (t * 'result) Lwt.t) ->
(t * 'result, verifier_error) result Lwt.t
type tree_proof := Proof.tree Proof.t
val produce_proof : (tree_proof, 'a) producer
val verify_proof : (tree_proof, 'a) verifier
val hash_of_proof_state : Proof.tree -> kinded_hash
type stream_proof := Proof.stream Proof.t
val produce_stream : (stream_proof, 'a) producer
val verify_stream : (stream_proof, 'a) verifier
end
end
|
4e2986ea42f9e82353ff33d98568eea37cc941c6511a275037aeb59c9a483f80 | jaspervdj/patat | Table.hs | --------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Patat.Presentation.Display.Table
( Table (..)
, prettyTable
, themed
) where
--------------------------------------------------------------------------------
import Data.List (intersperse, transpose)
import Patat.PrettyPrint ((<$$>))
import qualified Patat.PrettyPrint as PP
import Patat.Theme (Theme (..))
import qualified Patat.Theme as Theme
import Prelude
--------------------------------------------------------------------------------
data Table = Table
{ tCaption :: PP.Doc
, tAligns :: [PP.Alignment]
, tHeaders :: [PP.Doc]
, tRows :: [[PP.Doc]]
}
--------------------------------------------------------------------------------
prettyTable
:: Theme -> Table -> PP.Doc
prettyTable theme@Theme {..} Table {..} =
PP.indent (PP.Trimmable " ") (PP.Trimmable " ") $
lineIf (not isHeaderLess) (hcat2 headerHeight
[ themed themeTableHeader (PP.align w a (vpad headerHeight header))
| (w, a, header) <- zip3 columnWidths tAligns tHeaders
]) <>
dashedHeaderSeparator theme columnWidths <$$>
joinRows
[ hcat2 rowHeight
[ PP.align w a (vpad rowHeight cell)
| (w, a, cell) <- zip3 columnWidths tAligns row
]
| (rowHeight, row) <- zip rowHeights tRows
] <$$>
lineIf isHeaderLess (dashedHeaderSeparator theme columnWidths) <>
lineIf
(not $ PP.null tCaption) (PP.hardline <> "Table: " <> tCaption)
where
lineIf cond line = if cond then line <> PP.hardline else mempty
joinRows
| all (all isSimpleCell) tRows = PP.vcat
| otherwise = PP.vcat . intersperse ""
isHeaderLess = all PP.null tHeaders
headerDimensions = map PP.dimensions tHeaders :: [(Int, Int)]
rowDimensions = map (map PP.dimensions) tRows :: [[(Int, Int)]]
columnWidths :: [Int]
columnWidths =
[ safeMax (map snd col)
| col <- transpose (headerDimensions : rowDimensions)
]
rowHeights = map (safeMax . map fst) rowDimensions :: [Int]
headerHeight = safeMax (map fst headerDimensions) :: Int
vpad :: Int -> PP.Doc -> PP.Doc
vpad height doc =
let (actual, _) = PP.dimensions doc in
doc <> mconcat (replicate (height - actual) PP.hardline)
safeMax = foldr max 0
hcat2 :: Int -> [PP.Doc] -> PP.Doc
hcat2 rowHeight = PP.paste . intersperse (spaces2 rowHeight)
spaces2 :: Int -> PP.Doc
spaces2 rowHeight =
mconcat $ intersperse PP.hardline $
replicate rowHeight (PP.string " ")
--------------------------------------------------------------------------------
isSimpleCell :: PP.Doc -> Bool
isSimpleCell = (<= 1) . fst . PP.dimensions
--------------------------------------------------------------------------------
dashedHeaderSeparator :: Theme -> [Int] -> PP.Doc
dashedHeaderSeparator Theme {..} columnWidths =
mconcat $ intersperse (PP.string " ")
[ themed themeTableSeparator (PP.string (replicate w '-'))
| w <- columnWidths
]
--------------------------------------------------------------------------------
-- | This does not really belong in the module.
themed :: Maybe Theme.Style -> PP.Doc -> PP.Doc
themed Nothing = id
themed (Just (Theme.Style [])) = id
themed (Just (Theme.Style codes)) = PP.ansi codes
| null | https://raw.githubusercontent.com/jaspervdj/patat/9e0d0ccde9afee07ea23521546c406033afeb4f9/lib/Patat/Presentation/Display/Table.hs | haskell | ------------------------------------------------------------------------------
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| This does not really belong in the module. | # LANGUAGE RecordWildCards #
module Patat.Presentation.Display.Table
( Table (..)
, prettyTable
, themed
) where
import Data.List (intersperse, transpose)
import Patat.PrettyPrint ((<$$>))
import qualified Patat.PrettyPrint as PP
import Patat.Theme (Theme (..))
import qualified Patat.Theme as Theme
import Prelude
data Table = Table
{ tCaption :: PP.Doc
, tAligns :: [PP.Alignment]
, tHeaders :: [PP.Doc]
, tRows :: [[PP.Doc]]
}
prettyTable
:: Theme -> Table -> PP.Doc
prettyTable theme@Theme {..} Table {..} =
PP.indent (PP.Trimmable " ") (PP.Trimmable " ") $
lineIf (not isHeaderLess) (hcat2 headerHeight
[ themed themeTableHeader (PP.align w a (vpad headerHeight header))
| (w, a, header) <- zip3 columnWidths tAligns tHeaders
]) <>
dashedHeaderSeparator theme columnWidths <$$>
joinRows
[ hcat2 rowHeight
[ PP.align w a (vpad rowHeight cell)
| (w, a, cell) <- zip3 columnWidths tAligns row
]
| (rowHeight, row) <- zip rowHeights tRows
] <$$>
lineIf isHeaderLess (dashedHeaderSeparator theme columnWidths) <>
lineIf
(not $ PP.null tCaption) (PP.hardline <> "Table: " <> tCaption)
where
lineIf cond line = if cond then line <> PP.hardline else mempty
joinRows
| all (all isSimpleCell) tRows = PP.vcat
| otherwise = PP.vcat . intersperse ""
isHeaderLess = all PP.null tHeaders
headerDimensions = map PP.dimensions tHeaders :: [(Int, Int)]
rowDimensions = map (map PP.dimensions) tRows :: [[(Int, Int)]]
columnWidths :: [Int]
columnWidths =
[ safeMax (map snd col)
| col <- transpose (headerDimensions : rowDimensions)
]
rowHeights = map (safeMax . map fst) rowDimensions :: [Int]
headerHeight = safeMax (map fst headerDimensions) :: Int
vpad :: Int -> PP.Doc -> PP.Doc
vpad height doc =
let (actual, _) = PP.dimensions doc in
doc <> mconcat (replicate (height - actual) PP.hardline)
safeMax = foldr max 0
hcat2 :: Int -> [PP.Doc] -> PP.Doc
hcat2 rowHeight = PP.paste . intersperse (spaces2 rowHeight)
spaces2 :: Int -> PP.Doc
spaces2 rowHeight =
mconcat $ intersperse PP.hardline $
replicate rowHeight (PP.string " ")
isSimpleCell :: PP.Doc -> Bool
isSimpleCell = (<= 1) . fst . PP.dimensions
dashedHeaderSeparator :: Theme -> [Int] -> PP.Doc
dashedHeaderSeparator Theme {..} columnWidths =
mconcat $ intersperse (PP.string " ")
[ themed themeTableSeparator (PP.string (replicate w '-'))
| w <- columnWidths
]
themed :: Maybe Theme.Style -> PP.Doc -> PP.Doc
themed Nothing = id
themed (Just (Theme.Style [])) = id
themed (Just (Theme.Style codes)) = PP.ansi codes
|
912165e2d42516411a46995eaa3008a27b18019e3109b4a1491a56ba60e214b9 | gregr/dKanren | dkanren-interp.rkt | #lang racket/base
(provide
evalo
)
(require
"dkanren.rkt"
)
TODO
; profile to see what terms are getting all the attention
; nest all literals under a single match clause to compress their mostly-useless scheduling
; can a weighted match prioritize symbol lookup unraveling?
; additional predicates: procedure?, boolean?
; evalo solver
; tag match statements
; recognize tag groups (confirm via debug printing)
; design partitions and env analysis
; force fresh variable names as needed
; rules
; unshadowed env
; literals
; car/cdr reachables
; pair? before car/cdr when input type is ambiguous in env/partition
; rather, car/cdr only allowed on unambiguous pairs
; conditionals on other type/equality witnesses may create partitions with reduced ambiguity
; never car/cdr a cons result
; never type-witness a literal
never equate two literals
; what about generating lambdas/letrecs?
; (aggressive/permissive) union type system?
; other performance enhancement ideas
; pre-synthesis analysis
; partially evaluate known portions of program
; immediately commit to letrec/begin definitions for unknown procedures
; providing fixed param counts where possible
; generating unique, concrete parameter names
; (if desired, these can be converted to logic variables later)
; type inference and environment analysis of calls to unknown/partially-known procedures
; group applications by procedure
; while comparing argument values across applications:
; identify basic values, then sensible uses of primitives on these
; suggest conditionals that partition applications
; i.e., condition must evaluate to:
` # f ` in at least one env
and to ` not # f ` in at least one other env
; maybe also use return values/types to identify desirable partitions
; also see "evalo solver" notes
; synthesize within post-syntactic-analysis representation to avoid redundant parsing overhead
parse initial program to produce something like a de Bruijn program representation
; maybe also support other streamlining, such as inlined primitive ops
; perform synthesis
; project synthesized program back into surface syntax
; maybe intertwine this projection with synthesis, to get faster feedback
; when playing tricky syntactic constraint games, like quining
; related work
; escher
; myth
; /
; /
; /~bodik/research/pldi07-sketching-stencils.pdf
;
; /~lieber/Lieberary/Mondrian/Mondrian.html
; Chimera?
(define (letrec-eval-term program)
`(let ((closure-tag ',(gensym "#%closure"))
(prim-tag ',(gensym "#%primitive"))
(empty-env '()))
(let ((initial-env
`((cons . (val . (,prim-tag . cons)))
(car . (val . (,prim-tag . car)))
(cdr . (val . (,prim-tag . cdr)))
(null? . (val . (,prim-tag . null?)))
(pair? . (val . (,prim-tag . pair?)))
(symbol? . (val . (,prim-tag . symbol?)))
(not . (val . (,prim-tag . not)))
(equal? . (val . (,prim-tag . equal?)))
(list . (val . (,closure-tag (lambda x x) ,empty-env)))
. ,empty-env))
(closure-tag? (lambda (v) (equal? v closure-tag)))
(prim-tag? (lambda (v) (equal? v prim-tag))))
(letrec
((applicable-tag? (lambda (v) (or (closure-tag? v) (prim-tag? v))))
(quotable? (lambda (v)
(match/lazy v
((? symbol?) (not (applicable-tag? v)))
(`(,a . ,d) (and (quotable? a) (quotable? d)))
(_ #t))))
(not-in-params? (lambda (ps sym)
(match/lazy ps
('() #t)
(`(,a . ,d)
(and (not (equal? a sym))
(not-in-params? d sym))))))
(param-list? (lambda (x)
(match/lazy x
('() #t)
(`(,(? symbol? a) . ,d)
(and (param-list? d) (not-in-params? d a)))
(_ #f))))
(params? (lambda (x)
(match/lazy x
((? param-list?) #t)
(x (symbol? x)))))
(in-env? (lambda (env sym)
(match/lazy env
('() #f)
(`((,a . ,_) . ,d)
(or (equal? a sym) (in-env? d sym))))))
(extend-env*
(lambda (params args env)
(match `(,params . ,args)
(`(() . ()) env)
(`((,x . ,dx*) . (,a . ,da*))
(extend-env* dx* da* `((,x . (val . ,a)) . ,env))))))
(lookup
(lambda (env sym)
(match env
(`((,y . ,b) . ,rest)
(if (equal? sym y)
(match b
(`(val . ,v) v)
(`(rec . ,lam-expr) `(,closure-tag ,lam-expr ,env)))
(lookup rest sym))))))
(term?
(lambda (term env)
(letrec
((term1? (lambda (v) (term? v env)))
(terms? (lambda (ts env)
(match/lazy ts
('() #t)
(`(,t . ,ts)
(and (term? t env) (terms? ts env)))))))
(match/lazy term
(#t #t)
(#f #t)
((number) #t)
((symbol sym) (in-env? env sym))
(`(,(? term1?) . ,rands) (terms? rands env))
(`(quote ,datum) (quotable? datum))
(`(if ,c ,t ,f) (and (term1? c) (term1? t) (term1? f)))
(`(lambda ,params ,body)
(and (params? params)
(let ((res
(match params
((and (not (symbol)) params)
(extend-env* params params env))
(sym `((,sym . (val . ,sym)) . ,env)))))
(term? body res))))
(`(letrec
((,p-name ,(and `(lambda ,params ,body) lam-expr)))
,letrec-body)
(and (params? params)
(let ((res `((,p-name
. (rec . (lambda ,params ,body)))
. ,env)))
(and (term? lam-expr res)
(term? letrec-body res)))))
(_ #f)))))
(eval-prim
(lambda (prim-id args)
(match `(,prim-id . ,args)
(`(cons ,a ,d) `(,a . ,d))
(`(car (,(and (not (? applicable-tag?)) a) . ,d)) a)
(`(cdr (,(and (not (? applicable-tag?)) a) . ,d)) d)
(`(null? ()) #t)
(`(null? ,_) #f)
(`(pair? (,(not (? applicable-tag?)) . ,_)) #t)
(`(pair? ,_) #f)
(`(symbol? ,(symbol)) #t)
(`(symbol? ,_) #f)
(`(number? ,(number)) #t)
(`(number? ,(number)) #f)
(`(not #f) #t)
(`(not #t) #f)
(`(equal? ,v1 ,v1) #t)
(`(equal? ,_ ,_) #f))))
(eval-term-list
(lambda (terms env)
(match terms
('() '())
(`(,term . ,terms)
`(,(eval-term term env) . ,(eval-term-list terms env))))))
(eval-term
(lambda (term env)
(let ((bound? (lambda (sym) (in-env? env sym)))
(term1? (lambda (v) (term? v env))))
(match term
((symbol sym) (lookup env sym))
(#t #t)
(#f #f)
((number num) num)
(`(,(and 'quote (not (? bound?))) ,(? quotable? datum))
datum)
((and `(,op . ,_) operation)
(match operation
(`(,(or (not (symbol)) (? bound?))
. ,rands)
(let ((op (eval-term op env))
(a* (eval-term-list rands env)))
(match op
(`(,(? prim-tag?) . ,prim-id)
(eval-prim prim-id a*))
(`(,(? closure-tag?) (lambda ,x ,body) ,env^)
(let ((res (match x
((and (not (symbol)) params)
(extend-env* params a* env^))
(sym `((,sym . (val . ,a*))
. ,env^)))))
(eval-term body res))))))
(`(if ,condition ,alt-true ,alt-false)
(if (eval-term condition env)
(eval-term alt-true env)
(eval-term alt-false env)))
(`(lambda ,params ,body)
`(,closure-tag (lambda ,params ,body) ,env))
(`(letrec ((,p-name (lambda ,params ,body)))
,letrec-body)
(eval-term
letrec-body
`((,p-name . (rec . (lambda ,params ,body)))
. ,env))))))))))
(let ((program ',program))
(let ((_ (match/lazy (term? program initial-env) (#t #t))))
(eval-term program initial-env)))))))
(define (evalo program result)
(let ((tm (letrec-eval-term program)))
(dk-evalo tm result)))
(module+ test
(require
racket/pretty
rackunit
)
(define-syntax test
(syntax-rules ()
((_ name expr expected)
(let ((actual expr))
(when (not (equal? actual expected))
(display name)
(newline)
(pretty-print actual)
(newline))
(check-equal? actual expected)))))
(define (letrec-append body)
`(letrec ((append
(lambda (xs ys)
(if (null? xs) ys (cons (car xs) (append (cdr xs) ys))))))
,body))
(test "evalo-1"
(run* (q)
(evalo `'(1 2 ,q 4 5) '(1 2 3 4 5)))
'((3)))
(test "evalo-append-0"
(run* (q)
(evalo (letrec-append
'(list (append '() '())
(append '(foo) '(bar))
(append '(1 2) '(3 4))))
q))
'(((() (foo bar) (1 2 3 4)))))
(test "evalo-append-1"
(run* (q)
(evalo (letrec-append `(append '(1 2 3) '(4 5))) q))
'(((1 2 3 4 5))))
(test "evalo-append-2"
(run* (q)
(evalo (letrec-append `(append '(1 2 3) ',q)) '(1 2 3 4 5)))
'(((4 5))))
(test "evalo-append-3"
(run* (q)
(evalo (letrec-append `(append ',q '(4 5))) '(1 2 3 4 5)))
'(((1 2 3))))
(test "evalo-append-4"
(run* (q r)
(evalo (letrec-append `(append ',q ',r)) '(1 2 3 4 5)))
'((() (1 2 3 4 5))
((1) (2 3 4 5))
((1 2) (3 4 5))
((1 2 3) (4 5))
((1 2 3 4) (5))
((1 2 3 4 5) ())))
(test "evalo-append-synthesis-1"
(run 1 (q)
(evalo `(letrec
((append (lambda (xs ys)
(if (null? xs)
ys
(cons (car ,q) (append (cdr xs) ys))))))
(append '(1 2) '(3 4)))
'(1 2 3 4))
)
'((xs)))
(test "evalo-append-synthesis-2"
(run 1 (q)
(evalo `(letrec
((append (lambda (xs ys)
(if (null? xs)
ys
(cons (car xs) (,q (cdr xs) ys))))))
(append '(1 2) '(3 4)))
'(1 2 3 4))
)
'((append)))
(test "evalo-append-synthesis-3"
(run 1 (q)
(evalo `(letrec
((append (lambda (xs ys)
(if (,q xs)
ys
(cons (car xs) (append (cdr xs) ys))))))
(append '(1 2) '(3 4)))
'(1 2 3 4))
)
'((null?)))
;; TODO: run higher order interpreters in the relational interpreter instead.
This wo n't work directly due to dKanren 's first - order restriction .
( define
' ( letrec
;((eval-expr
;(lambda (expr env)
;(match expr
;(`(quote ,datum) datum)
;(`(lambda (,(? symbol? x)) ,body)
;(lambda (a)
;(eval-expr body (lambda (y)
;(if (equal? y x) a (env y))))))
;((? symbol? x) (env x))
;(`(cons ,e1 ,e2) (cons (eval-expr e1 env) (eval-expr e2 env)))
;(`(,rator ,rand) ((eval-expr rator env)
;(eval-expr rand env)))))))
;(list
;(eval-expr '((lambda (y) y) 'g1) 'initial-env)
( eval - expr ' ( ( ( lambda ( z ) z ) ( lambda ( v ) v ) ) ' ) ' initial - env )
;(eval-expr '(((lambda (a) (a a)) (lambda (b) b)) 'g3) 'initial-env)
;(eval-expr '(((lambda (c) (lambda (d) c)) 'g4) 'g5) 'initial-env)
;(eval-expr '(((lambda (f) (lambda (v1) (f (f v1)))) (lambda (e) e)) 'g6) 'initial-env)
;(eval-expr '((lambda (g) ((g g) g)) (lambda (i) (lambda (j) 'g7))) 'initial-env))))
;(test-eval ex-eval-expr '(g1 g2 g3 g4 g6 g7))
( define dneg
' ( letrec
;((eval-expr
;(lambda (expr env)
;(match expr
;(`(,(not (not 'quote)) ,datum) datum)
;(`(lambda (,(? symbol? x)) ,body)
;(lambda (a)
;(eval-expr body (lambda (y)
;(if (equal? y x) a (env y))))))
;((symbol x) (env x))
;(`(cons ,e1 ,e2) (cons (eval-expr e1 env) (eval-expr e2 env)))
;(`(,rator ,rand) ((eval-expr rator env)
;(eval-expr rand env)))))))
;(list
;(eval-expr '((lambda (y) y) 'g1) 'initial-env)
( eval - expr ' ( ( ( lambda ( z ) z ) ( lambda ( v ) v ) ) ' ) ' initial - env )
;(eval-expr '(((lambda (a) (a a)) (lambda (b) b)) 'g3) 'initial-env)
;(eval-expr '(((lambda (c) (lambda (d) c)) 'g4) 'g5) 'initial-env)
;(eval-expr '(((lambda (f) (lambda (v1) (f (f v1)))) (lambda (e) e)) 'g6) 'initial-env)
;(eval-expr '((lambda (g) ((g g) g)) (lambda (i) (lambda (j) 'g7))) 'initial-env))))
;(test-eval ex-eval-expr-dneg '(g1 g2 g3 g4 g6 g7))
)
| null | https://raw.githubusercontent.com/gregr/dKanren/2f05275b00dfba5c2f0ca196a514c377b3b60798/dkanren-interp.rkt | racket | profile to see what terms are getting all the attention
nest all literals under a single match clause to compress their mostly-useless scheduling
can a weighted match prioritize symbol lookup unraveling?
additional predicates: procedure?, boolean?
evalo solver
tag match statements
recognize tag groups (confirm via debug printing)
design partitions and env analysis
force fresh variable names as needed
rules
unshadowed env
literals
car/cdr reachables
pair? before car/cdr when input type is ambiguous in env/partition
rather, car/cdr only allowed on unambiguous pairs
conditionals on other type/equality witnesses may create partitions with reduced ambiguity
never car/cdr a cons result
never type-witness a literal
what about generating lambdas/letrecs?
(aggressive/permissive) union type system?
other performance enhancement ideas
pre-synthesis analysis
partially evaluate known portions of program
immediately commit to letrec/begin definitions for unknown procedures
providing fixed param counts where possible
generating unique, concrete parameter names
(if desired, these can be converted to logic variables later)
type inference and environment analysis of calls to unknown/partially-known procedures
group applications by procedure
while comparing argument values across applications:
identify basic values, then sensible uses of primitives on these
suggest conditionals that partition applications
i.e., condition must evaluate to:
maybe also use return values/types to identify desirable partitions
also see "evalo solver" notes
synthesize within post-syntactic-analysis representation to avoid redundant parsing overhead
maybe also support other streamlining, such as inlined primitive ops
perform synthesis
project synthesized program back into surface syntax
maybe intertwine this projection with synthesis, to get faster feedback
when playing tricky syntactic constraint games, like quining
related work
escher
myth
/
/
/~bodik/research/pldi07-sketching-stencils.pdf
/~lieber/Lieberary/Mondrian/Mondrian.html
Chimera?
TODO: run higher order interpreters in the relational interpreter instead.
((eval-expr
(lambda (expr env)
(match expr
(`(quote ,datum) datum)
(`(lambda (,(? symbol? x)) ,body)
(lambda (a)
(eval-expr body (lambda (y)
(if (equal? y x) a (env y))))))
((? symbol? x) (env x))
(`(cons ,e1 ,e2) (cons (eval-expr e1 env) (eval-expr e2 env)))
(`(,rator ,rand) ((eval-expr rator env)
(eval-expr rand env)))))))
(list
(eval-expr '((lambda (y) y) 'g1) 'initial-env)
(eval-expr '(((lambda (a) (a a)) (lambda (b) b)) 'g3) 'initial-env)
(eval-expr '(((lambda (c) (lambda (d) c)) 'g4) 'g5) 'initial-env)
(eval-expr '(((lambda (f) (lambda (v1) (f (f v1)))) (lambda (e) e)) 'g6) 'initial-env)
(eval-expr '((lambda (g) ((g g) g)) (lambda (i) (lambda (j) 'g7))) 'initial-env))))
(test-eval ex-eval-expr '(g1 g2 g3 g4 g6 g7))
((eval-expr
(lambda (expr env)
(match expr
(`(,(not (not 'quote)) ,datum) datum)
(`(lambda (,(? symbol? x)) ,body)
(lambda (a)
(eval-expr body (lambda (y)
(if (equal? y x) a (env y))))))
((symbol x) (env x))
(`(cons ,e1 ,e2) (cons (eval-expr e1 env) (eval-expr e2 env)))
(`(,rator ,rand) ((eval-expr rator env)
(eval-expr rand env)))))))
(list
(eval-expr '((lambda (y) y) 'g1) 'initial-env)
(eval-expr '(((lambda (a) (a a)) (lambda (b) b)) 'g3) 'initial-env)
(eval-expr '(((lambda (c) (lambda (d) c)) 'g4) 'g5) 'initial-env)
(eval-expr '(((lambda (f) (lambda (v1) (f (f v1)))) (lambda (e) e)) 'g6) 'initial-env)
(eval-expr '((lambda (g) ((g g) g)) (lambda (i) (lambda (j) 'g7))) 'initial-env))))
(test-eval ex-eval-expr-dneg '(g1 g2 g3 g4 g6 g7)) | #lang racket/base
(provide
evalo
)
(require
"dkanren.rkt"
)
TODO
never equate two literals
` # f ` in at least one env
and to ` not # f ` in at least one other env
parse initial program to produce something like a de Bruijn program representation
(define (letrec-eval-term program)
`(let ((closure-tag ',(gensym "#%closure"))
(prim-tag ',(gensym "#%primitive"))
(empty-env '()))
(let ((initial-env
`((cons . (val . (,prim-tag . cons)))
(car . (val . (,prim-tag . car)))
(cdr . (val . (,prim-tag . cdr)))
(null? . (val . (,prim-tag . null?)))
(pair? . (val . (,prim-tag . pair?)))
(symbol? . (val . (,prim-tag . symbol?)))
(not . (val . (,prim-tag . not)))
(equal? . (val . (,prim-tag . equal?)))
(list . (val . (,closure-tag (lambda x x) ,empty-env)))
. ,empty-env))
(closure-tag? (lambda (v) (equal? v closure-tag)))
(prim-tag? (lambda (v) (equal? v prim-tag))))
(letrec
((applicable-tag? (lambda (v) (or (closure-tag? v) (prim-tag? v))))
(quotable? (lambda (v)
(match/lazy v
((? symbol?) (not (applicable-tag? v)))
(`(,a . ,d) (and (quotable? a) (quotable? d)))
(_ #t))))
(not-in-params? (lambda (ps sym)
(match/lazy ps
('() #t)
(`(,a . ,d)
(and (not (equal? a sym))
(not-in-params? d sym))))))
(param-list? (lambda (x)
(match/lazy x
('() #t)
(`(,(? symbol? a) . ,d)
(and (param-list? d) (not-in-params? d a)))
(_ #f))))
(params? (lambda (x)
(match/lazy x
((? param-list?) #t)
(x (symbol? x)))))
(in-env? (lambda (env sym)
(match/lazy env
('() #f)
(`((,a . ,_) . ,d)
(or (equal? a sym) (in-env? d sym))))))
(extend-env*
(lambda (params args env)
(match `(,params . ,args)
(`(() . ()) env)
(`((,x . ,dx*) . (,a . ,da*))
(extend-env* dx* da* `((,x . (val . ,a)) . ,env))))))
(lookup
(lambda (env sym)
(match env
(`((,y . ,b) . ,rest)
(if (equal? sym y)
(match b
(`(val . ,v) v)
(`(rec . ,lam-expr) `(,closure-tag ,lam-expr ,env)))
(lookup rest sym))))))
(term?
(lambda (term env)
(letrec
((term1? (lambda (v) (term? v env)))
(terms? (lambda (ts env)
(match/lazy ts
('() #t)
(`(,t . ,ts)
(and (term? t env) (terms? ts env)))))))
(match/lazy term
(#t #t)
(#f #t)
((number) #t)
((symbol sym) (in-env? env sym))
(`(,(? term1?) . ,rands) (terms? rands env))
(`(quote ,datum) (quotable? datum))
(`(if ,c ,t ,f) (and (term1? c) (term1? t) (term1? f)))
(`(lambda ,params ,body)
(and (params? params)
(let ((res
(match params
((and (not (symbol)) params)
(extend-env* params params env))
(sym `((,sym . (val . ,sym)) . ,env)))))
(term? body res))))
(`(letrec
((,p-name ,(and `(lambda ,params ,body) lam-expr)))
,letrec-body)
(and (params? params)
(let ((res `((,p-name
. (rec . (lambda ,params ,body)))
. ,env)))
(and (term? lam-expr res)
(term? letrec-body res)))))
(_ #f)))))
(eval-prim
(lambda (prim-id args)
(match `(,prim-id . ,args)
(`(cons ,a ,d) `(,a . ,d))
(`(car (,(and (not (? applicable-tag?)) a) . ,d)) a)
(`(cdr (,(and (not (? applicable-tag?)) a) . ,d)) d)
(`(null? ()) #t)
(`(null? ,_) #f)
(`(pair? (,(not (? applicable-tag?)) . ,_)) #t)
(`(pair? ,_) #f)
(`(symbol? ,(symbol)) #t)
(`(symbol? ,_) #f)
(`(number? ,(number)) #t)
(`(number? ,(number)) #f)
(`(not #f) #t)
(`(not #t) #f)
(`(equal? ,v1 ,v1) #t)
(`(equal? ,_ ,_) #f))))
(eval-term-list
(lambda (terms env)
(match terms
('() '())
(`(,term . ,terms)
`(,(eval-term term env) . ,(eval-term-list terms env))))))
(eval-term
(lambda (term env)
(let ((bound? (lambda (sym) (in-env? env sym)))
(term1? (lambda (v) (term? v env))))
(match term
((symbol sym) (lookup env sym))
(#t #t)
(#f #f)
((number num) num)
(`(,(and 'quote (not (? bound?))) ,(? quotable? datum))
datum)
((and `(,op . ,_) operation)
(match operation
(`(,(or (not (symbol)) (? bound?))
. ,rands)
(let ((op (eval-term op env))
(a* (eval-term-list rands env)))
(match op
(`(,(? prim-tag?) . ,prim-id)
(eval-prim prim-id a*))
(`(,(? closure-tag?) (lambda ,x ,body) ,env^)
(let ((res (match x
((and (not (symbol)) params)
(extend-env* params a* env^))
(sym `((,sym . (val . ,a*))
. ,env^)))))
(eval-term body res))))))
(`(if ,condition ,alt-true ,alt-false)
(if (eval-term condition env)
(eval-term alt-true env)
(eval-term alt-false env)))
(`(lambda ,params ,body)
`(,closure-tag (lambda ,params ,body) ,env))
(`(letrec ((,p-name (lambda ,params ,body)))
,letrec-body)
(eval-term
letrec-body
`((,p-name . (rec . (lambda ,params ,body)))
. ,env))))))))))
(let ((program ',program))
(let ((_ (match/lazy (term? program initial-env) (#t #t))))
(eval-term program initial-env)))))))
(define (evalo program result)
(let ((tm (letrec-eval-term program)))
(dk-evalo tm result)))
(module+ test
(require
racket/pretty
rackunit
)
(define-syntax test
(syntax-rules ()
((_ name expr expected)
(let ((actual expr))
(when (not (equal? actual expected))
(display name)
(newline)
(pretty-print actual)
(newline))
(check-equal? actual expected)))))
(define (letrec-append body)
`(letrec ((append
(lambda (xs ys)
(if (null? xs) ys (cons (car xs) (append (cdr xs) ys))))))
,body))
(test "evalo-1"
(run* (q)
(evalo `'(1 2 ,q 4 5) '(1 2 3 4 5)))
'((3)))
(test "evalo-append-0"
(run* (q)
(evalo (letrec-append
'(list (append '() '())
(append '(foo) '(bar))
(append '(1 2) '(3 4))))
q))
'(((() (foo bar) (1 2 3 4)))))
(test "evalo-append-1"
(run* (q)
(evalo (letrec-append `(append '(1 2 3) '(4 5))) q))
'(((1 2 3 4 5))))
(test "evalo-append-2"
(run* (q)
(evalo (letrec-append `(append '(1 2 3) ',q)) '(1 2 3 4 5)))
'(((4 5))))
(test "evalo-append-3"
(run* (q)
(evalo (letrec-append `(append ',q '(4 5))) '(1 2 3 4 5)))
'(((1 2 3))))
(test "evalo-append-4"
(run* (q r)
(evalo (letrec-append `(append ',q ',r)) '(1 2 3 4 5)))
'((() (1 2 3 4 5))
((1) (2 3 4 5))
((1 2) (3 4 5))
((1 2 3) (4 5))
((1 2 3 4) (5))
((1 2 3 4 5) ())))
(test "evalo-append-synthesis-1"
(run 1 (q)
(evalo `(letrec
((append (lambda (xs ys)
(if (null? xs)
ys
(cons (car ,q) (append (cdr xs) ys))))))
(append '(1 2) '(3 4)))
'(1 2 3 4))
)
'((xs)))
(test "evalo-append-synthesis-2"
(run 1 (q)
(evalo `(letrec
((append (lambda (xs ys)
(if (null? xs)
ys
(cons (car xs) (,q (cdr xs) ys))))))
(append '(1 2) '(3 4)))
'(1 2 3 4))
)
'((append)))
(test "evalo-append-synthesis-3"
(run 1 (q)
(evalo `(letrec
((append (lambda (xs ys)
(if (,q xs)
ys
(cons (car xs) (append (cdr xs) ys))))))
(append '(1 2) '(3 4)))
'(1 2 3 4))
)
'((null?)))
This wo n't work directly due to dKanren 's first - order restriction .
( define
' ( letrec
( eval - expr ' ( ( ( lambda ( z ) z ) ( lambda ( v ) v ) ) ' ) ' initial - env )
( define dneg
' ( letrec
( eval - expr ' ( ( ( lambda ( z ) z ) ( lambda ( v ) v ) ) ' ) ' initial - env )
)
|
9503490f12936695226307c5161b8754a5841286d6458b36a35de73176b47b2f | release-project/benchmarks | aco.erl | -module(aco).
-export([run/0, run/1]).
-include ("types.hrl").
%% --------------------------- Read problem specification from file ------------------------------ %%
-spec get_int (string()) -> integer().
get_int(S) ->
{N, _} = string:to_integer(S),
N.
-spec read_input(string()) -> {pos_integer(), inputs()}.
read_input(Fname) ->
util:check_file(Fname),
case file:read_file(Fname) of
{ok,B} ->
[N|Rest] = string:tokens(binary:bin_to_list(B), " \n"),
% Split at space & newline.
Input format : 3N+1 integers . N is the first item in the file ,
then three sequences of N integers , containing durations ,
% weights and due dates respectively.
Num_Jobs = get_int(N),
Rest1 = lists:map(fun get_int/1, Rest),
{Durations, Rest2} = lists:split(Num_Jobs, Rest1),
{Weights, Rest3} = lists:split(Num_Jobs, Rest2),
{Deadlines, _} = lists:split(Num_Jobs, Rest3),
{Num_Jobs, {list_to_tuple(Durations), list_to_tuple(Weights), list_to_tuple(Deadlines)}};
{error, Report} ->
error (Report)
end.
%% --------------------------- Run the colony ------------------------------ %%
-spec best_solution (solution(), solution()|none) -> solution().
best_solution(Solution, none) -> Solution;
best_solution(S1 = {Cost1, _}, S2 = {Cost2, _}) ->
if
Cost1 =< Cost2 -> S1;
true -> S2
end.
-spec collect_ants(non_neg_integer(), solution() | none) -> solution().
collect_ants (0,Best) -> Best;
collect_ants (Num_left, Current_Best) -> % or use lists:foldl.
receive
{ant_done, New_Solution} ->
io : format ( " collect_ants ~p : got solution ~p ~ n " , [ self ( ) , Num_left ] ) ,
collect_ants(Num_left-1, best_solution (New_Solution, Current_Best))
end.
-spec aco_loop (pos_integer(), pos_integer(),
[pid()], numjobs(), inputs(), params(), solution() | none) -> solution().
aco_loop (0, _, _, _, _, _, Best_Solution) ->
Best_Solution;
aco_loop (Num_Iter, Num_Ants, Ants, Num_Jobs, Inputs, Params, Best_Solution) ->
lists:foreach (fun (Pid) -> Pid ! {self(), find_solution} end, Ants),
New_Solution = collect_ants(Num_Ants, Best_Solution),
Improved_Solution = localsearch:vnd_loop(New_Solution, Inputs, Params),
#params{verbose=Verbose} = Params,
case Verbose of
true ->
{Cost, _} = Improved_Solution,
io:format ("Iteration ~p: cost = ~p~n", [Num_Iter, Cost]);
_ -> ok
end,
ok = update:update_pheromones(Num_Jobs, Improved_Solution, Params),
aco_loop (Num_Iter-1, Num_Ants, Ants, Num_Jobs, Inputs, Params, Improved_Solution).
-spec aco(string(), pos_integer(), pos_integer(), params()) -> {pos_integer(), {numjobs(), cost(), schedule()}}.
aco(Fname, Num_Ants, Num_Iter, Params0) ->
{Num_Jobs, Inputs} = read_input(Fname),
% Set up ets table: visible to all ants
case lists:member(tau, ets:all()) of
true -> ok; % Already exists: maybe left over from interrupted run.
false -> ets:new(tau, [set, protected, named_table])
end,
#params{tau0=T0} = Params0,
Tau0 = case T0 of
undefined -> fitness:tau0 (Num_Jobs, Inputs, Num_Ants);
_ -> util:check_positive({tau0, T0}), T0
end,
Params = Params0#params{tau0=Tau0},
Tau = lists:map(fun(I) -> {I, util:make_tuple(Num_Jobs, Tau0)} end, lists:seq(1, Num_Jobs)),
ets:insert(tau, Tau),
Ants = lists:map (fun (_) ->
spawn(ant, start, [Num_Jobs, Inputs, Params]) end,
lists:seq(1,Num_Ants)),
{Time, {Best_Cost, Best_Schedule}} =
timer:tc (
fun() -> aco_loop (Num_Iter, Num_Ants, Ants, Num_Jobs, Inputs, Params, none) end
),
ok = lists:foreach (fun (Pid) -> Pid ! {self(), stop} end, Ants),
ets:delete(tau),
{Time, {Num_Jobs, Best_Cost, Best_Schedule}}.
-spec output_result(pos_integer(), {numjobs(), cost(), schedule()}, pos_integer(), pos_integer()) -> ok.
output_result (Time, {Num_Jobs, Best_Cost, Best_Schedule}, Num_Ants, Num_Iter) ->
case get(output_type) of
default ->
io:format("Best cost = ~p~n", [Best_Cost]),
io:format("Time = ~p~n", [Time]);
schedule ->
io:format("Best cost = ~p~n", [Best_Cost]),
io:format("Best schedule = ~p~n", [Best_Schedule]),
io:format("Time = ~p~n", [Time]);
time_only ->
io:format("~p~n", [Time]);
r_output ->
io:format ("~10p ~10p ~10p ~10p ~10p~n", [Num_Jobs, Num_Ants, Num_Iter, Best_Cost, Time])
end.
--------------------------- Parse arguments etc . ------------------------------ % %
-spec usage() -> ok.
usage() ->
io:format ("Usage: aco [options] <input file> <num_ants> <num_iter>~n"),
io:format (" Input file should contain the number of jobs on the first line,~n"),
io:format (" then three lines containing durations, weights, and deadlines.~n"),
io:format (" Node file contains an Erlang list giving nodes to run colonies on.~n"),
io:format ("~n"),
io:format (" The default output is the total weighted tardiness of the best solution~n"), %
io:format (" found, together with the execution time of the main loop in microseconds.~n"),
io:format (" Time taken for setup and data input is ignored.~n"),
io:format ("~n"),
io:format ("Options:~n"),
io:format (" v: verbose~n"),
io:format (" sched: print schedule, cost and time taken~n"),
io:format (" time: print time only (for benchmarking)~n"),
io:format (" R: produce output for R~n"),
io:format (" N: set random seeds using now(). Use this if you get a crypto link error~n"),
io:format (" cyclic: use a cyclic \"random\" number generator of period 10 (for benchmarking)~n"),
io:format (" ne: don't evaporate pheromone during update~n"),
io:format (" a=<float>: set value of pheromone influence factor alpha (default = 1.0)~n"),
io:format (" b=<float>: set value of heuristic influence factor beta (default = 2.0)~n"),
io:format (" rho=<float>: set value of pheromone evaporation rate rho (default = 0.1)~n"),
io:format (" q0=<float>: set value of random exploration factor q0 (default = 0.9)~n"),
io:format (" tau0=<float>: set initial pheromone strength (default calculated from mdd)~n"),
io:format (" mdd: use MDD heuristic (this is the default)~n"),
io:format (" edd: use EDD heuristic instead of MDD~n"),
io:format (" au: use AU heuristic instead of MDD~n"),
io:format (" o1, o2, o12, o21: local search options (experimental)\n"),
io:format (" o1: interchange search~n"),
io:format (" o2: insertion search~n"),
io:format (" o12: interchange + insertion~n"),
io:format (" o21: insertion + interchange~n"),
io:format ("~n").
-spec run2([string()], params()) -> ok.
run2(Args,Params) ->
case Args of
["v"|Rest] ->
run2(Rest, Params#params{verbose=true});
["vv"|Rest] ->
run2(Rest, Params#params{verbose=true, vverbose=true});
["R"|Rest] ->
put(output_type, r_output),
run2(Rest, Params);
["sched"|Rest] ->
put(output_type, schedule),
run2(Rest, Params);
["time"|Rest] ->
put(output_type, time_only),
run2(Rest, Params);
["ne"|Rest] ->
run2(Rest, Params#params{evaporate=false});
["N"|Rest] ->
run2(Rest, Params#params{rng_type=now});
["cyclic"|Rest] ->
run2(Rest, Params#params{rng_type=cyclic});
["o1"|Rest] ->
run2(Rest, Params#params{search=o1});
["o2"|Rest] ->
run2(Rest, Params#params{search=o2});
["o12"|Rest] ->
run2(Rest, Params#params{search=o12});
["o21"|Rest] ->
run2(Rest, Params#params{search=o21});
[ [$a, $= |V] |Rest] ->
Alpha = util:float_of_string(V),
run2(Rest, Params#params{alpha=Alpha});
[ [$b, $= |V] |Rest] ->
Beta = util:float_of_string(V),
run2(Rest, Params#params{beta=Beta});
[ [$q,$0,$= |V] |Rest] ->
Q0 = util:float_of_string(V),
run2(Rest, Params#params{q0=Q0});
[ [$r, $h, $o, $= |V] |Rest] ->
Rho = util:float_of_string(V),
run2(Rest, Params#params{rho=Rho});
[ [$t, $a, $u, $0, $= |V] |Rest] ->
Tau0 = util:float_of_string(V),
run2(Rest, Params#params{tau0=Tau0});
["mdd"|Rest] ->
run2(Rest, Params#params{heuristic=mdd});
["edd"|Rest] ->
run2(Rest, Params#params{heuristic=edd});
["au"|Rest] ->
run2(Rest, Params#params{heuristic=au});
["mixed"|_Rest] ->
util:quit ("Error: mixed heuristics not available in this version.~n", []);
[Fname, Num_Ants0, Num_Iter0] ->
Num_Ants = util:int_of_string(Num_Ants0),
Num_Iter = util:int_of_string(Num_Iter0),
util:check_positive ({'Num_Ants', Num_Ants}),
util:check_positive ({'Num_Iter', Num_Iter}),
{Time, Result} = aco (Fname, Num_Ants, Num_Iter, Params),
output_result (Time, Result, Num_Ants, Num_Iter);
["h"] -> usage();
[F|_] -> io:format ("Unknown option ~p~n", [F]), usage();
[] -> usage()
end.
-spec run([atom()]) -> ok.
run(Args) ->
Params=#params{}, % program parameters - see types.hrl
put(output_type, default), % What to output at the end.
run2 (lists:map (fun atom_to_list/1, Args), Params).
-spec run() -> ok.
run () -> usage().
| null | https://raw.githubusercontent.com/release-project/benchmarks/55f042dca3a2c680e2967c59edc9636456047bd5/ACO/SMP-ACO/aco.erl | erlang | --------------------------- Read problem specification from file ------------------------------ %%
Split at space & newline.
weights and due dates respectively.
--------------------------- Run the colony ------------------------------ %%
or use lists:foldl.
Set up ets table: visible to all ants
Already exists: maybe left over from interrupted run.
%
program parameters - see types.hrl
What to output at the end. | -module(aco).
-export([run/0, run/1]).
-include ("types.hrl").
-spec get_int (string()) -> integer().
get_int(S) ->
{N, _} = string:to_integer(S),
N.
-spec read_input(string()) -> {pos_integer(), inputs()}.
read_input(Fname) ->
util:check_file(Fname),
case file:read_file(Fname) of
{ok,B} ->
[N|Rest] = string:tokens(binary:bin_to_list(B), " \n"),
Input format : 3N+1 integers . N is the first item in the file ,
then three sequences of N integers , containing durations ,
Num_Jobs = get_int(N),
Rest1 = lists:map(fun get_int/1, Rest),
{Durations, Rest2} = lists:split(Num_Jobs, Rest1),
{Weights, Rest3} = lists:split(Num_Jobs, Rest2),
{Deadlines, _} = lists:split(Num_Jobs, Rest3),
{Num_Jobs, {list_to_tuple(Durations), list_to_tuple(Weights), list_to_tuple(Deadlines)}};
{error, Report} ->
error (Report)
end.
-spec best_solution (solution(), solution()|none) -> solution().
best_solution(Solution, none) -> Solution;
best_solution(S1 = {Cost1, _}, S2 = {Cost2, _}) ->
if
Cost1 =< Cost2 -> S1;
true -> S2
end.
-spec collect_ants(non_neg_integer(), solution() | none) -> solution().
collect_ants (0,Best) -> Best;
receive
{ant_done, New_Solution} ->
io : format ( " collect_ants ~p : got solution ~p ~ n " , [ self ( ) , Num_left ] ) ,
collect_ants(Num_left-1, best_solution (New_Solution, Current_Best))
end.
-spec aco_loop (pos_integer(), pos_integer(),
[pid()], numjobs(), inputs(), params(), solution() | none) -> solution().
aco_loop (0, _, _, _, _, _, Best_Solution) ->
Best_Solution;
aco_loop (Num_Iter, Num_Ants, Ants, Num_Jobs, Inputs, Params, Best_Solution) ->
lists:foreach (fun (Pid) -> Pid ! {self(), find_solution} end, Ants),
New_Solution = collect_ants(Num_Ants, Best_Solution),
Improved_Solution = localsearch:vnd_loop(New_Solution, Inputs, Params),
#params{verbose=Verbose} = Params,
case Verbose of
true ->
{Cost, _} = Improved_Solution,
io:format ("Iteration ~p: cost = ~p~n", [Num_Iter, Cost]);
_ -> ok
end,
ok = update:update_pheromones(Num_Jobs, Improved_Solution, Params),
aco_loop (Num_Iter-1, Num_Ants, Ants, Num_Jobs, Inputs, Params, Improved_Solution).
-spec aco(string(), pos_integer(), pos_integer(), params()) -> {pos_integer(), {numjobs(), cost(), schedule()}}.
aco(Fname, Num_Ants, Num_Iter, Params0) ->
{Num_Jobs, Inputs} = read_input(Fname),
case lists:member(tau, ets:all()) of
false -> ets:new(tau, [set, protected, named_table])
end,
#params{tau0=T0} = Params0,
Tau0 = case T0 of
undefined -> fitness:tau0 (Num_Jobs, Inputs, Num_Ants);
_ -> util:check_positive({tau0, T0}), T0
end,
Params = Params0#params{tau0=Tau0},
Tau = lists:map(fun(I) -> {I, util:make_tuple(Num_Jobs, Tau0)} end, lists:seq(1, Num_Jobs)),
ets:insert(tau, Tau),
Ants = lists:map (fun (_) ->
spawn(ant, start, [Num_Jobs, Inputs, Params]) end,
lists:seq(1,Num_Ants)),
{Time, {Best_Cost, Best_Schedule}} =
timer:tc (
fun() -> aco_loop (Num_Iter, Num_Ants, Ants, Num_Jobs, Inputs, Params, none) end
),
ok = lists:foreach (fun (Pid) -> Pid ! {self(), stop} end, Ants),
ets:delete(tau),
{Time, {Num_Jobs, Best_Cost, Best_Schedule}}.
-spec output_result(pos_integer(), {numjobs(), cost(), schedule()}, pos_integer(), pos_integer()) -> ok.
output_result (Time, {Num_Jobs, Best_Cost, Best_Schedule}, Num_Ants, Num_Iter) ->
case get(output_type) of
default ->
io:format("Best cost = ~p~n", [Best_Cost]),
io:format("Time = ~p~n", [Time]);
schedule ->
io:format("Best cost = ~p~n", [Best_Cost]),
io:format("Best schedule = ~p~n", [Best_Schedule]),
io:format("Time = ~p~n", [Time]);
time_only ->
io:format("~p~n", [Time]);
r_output ->
io:format ("~10p ~10p ~10p ~10p ~10p~n", [Num_Jobs, Num_Ants, Num_Iter, Best_Cost, Time])
end.
-spec usage() -> ok.
usage() ->
io:format ("Usage: aco [options] <input file> <num_ants> <num_iter>~n"),
io:format (" Input file should contain the number of jobs on the first line,~n"),
io:format (" then three lines containing durations, weights, and deadlines.~n"),
io:format (" Node file contains an Erlang list giving nodes to run colonies on.~n"),
io:format ("~n"),
io:format (" found, together with the execution time of the main loop in microseconds.~n"),
io:format (" Time taken for setup and data input is ignored.~n"),
io:format ("~n"),
io:format ("Options:~n"),
io:format (" v: verbose~n"),
io:format (" sched: print schedule, cost and time taken~n"),
io:format (" time: print time only (for benchmarking)~n"),
io:format (" R: produce output for R~n"),
io:format (" N: set random seeds using now(). Use this if you get a crypto link error~n"),
io:format (" cyclic: use a cyclic \"random\" number generator of period 10 (for benchmarking)~n"),
io:format (" ne: don't evaporate pheromone during update~n"),
io:format (" a=<float>: set value of pheromone influence factor alpha (default = 1.0)~n"),
io:format (" b=<float>: set value of heuristic influence factor beta (default = 2.0)~n"),
io:format (" rho=<float>: set value of pheromone evaporation rate rho (default = 0.1)~n"),
io:format (" q0=<float>: set value of random exploration factor q0 (default = 0.9)~n"),
io:format (" tau0=<float>: set initial pheromone strength (default calculated from mdd)~n"),
io:format (" mdd: use MDD heuristic (this is the default)~n"),
io:format (" edd: use EDD heuristic instead of MDD~n"),
io:format (" au: use AU heuristic instead of MDD~n"),
io:format (" o1, o2, o12, o21: local search options (experimental)\n"),
io:format (" o1: interchange search~n"),
io:format (" o2: insertion search~n"),
io:format (" o12: interchange + insertion~n"),
io:format (" o21: insertion + interchange~n"),
io:format ("~n").
-spec run2([string()], params()) -> ok.
run2(Args,Params) ->
case Args of
["v"|Rest] ->
run2(Rest, Params#params{verbose=true});
["vv"|Rest] ->
run2(Rest, Params#params{verbose=true, vverbose=true});
["R"|Rest] ->
put(output_type, r_output),
run2(Rest, Params);
["sched"|Rest] ->
put(output_type, schedule),
run2(Rest, Params);
["time"|Rest] ->
put(output_type, time_only),
run2(Rest, Params);
["ne"|Rest] ->
run2(Rest, Params#params{evaporate=false});
["N"|Rest] ->
run2(Rest, Params#params{rng_type=now});
["cyclic"|Rest] ->
run2(Rest, Params#params{rng_type=cyclic});
["o1"|Rest] ->
run2(Rest, Params#params{search=o1});
["o2"|Rest] ->
run2(Rest, Params#params{search=o2});
["o12"|Rest] ->
run2(Rest, Params#params{search=o12});
["o21"|Rest] ->
run2(Rest, Params#params{search=o21});
[ [$a, $= |V] |Rest] ->
Alpha = util:float_of_string(V),
run2(Rest, Params#params{alpha=Alpha});
[ [$b, $= |V] |Rest] ->
Beta = util:float_of_string(V),
run2(Rest, Params#params{beta=Beta});
[ [$q,$0,$= |V] |Rest] ->
Q0 = util:float_of_string(V),
run2(Rest, Params#params{q0=Q0});
[ [$r, $h, $o, $= |V] |Rest] ->
Rho = util:float_of_string(V),
run2(Rest, Params#params{rho=Rho});
[ [$t, $a, $u, $0, $= |V] |Rest] ->
Tau0 = util:float_of_string(V),
run2(Rest, Params#params{tau0=Tau0});
["mdd"|Rest] ->
run2(Rest, Params#params{heuristic=mdd});
["edd"|Rest] ->
run2(Rest, Params#params{heuristic=edd});
["au"|Rest] ->
run2(Rest, Params#params{heuristic=au});
["mixed"|_Rest] ->
util:quit ("Error: mixed heuristics not available in this version.~n", []);
[Fname, Num_Ants0, Num_Iter0] ->
Num_Ants = util:int_of_string(Num_Ants0),
Num_Iter = util:int_of_string(Num_Iter0),
util:check_positive ({'Num_Ants', Num_Ants}),
util:check_positive ({'Num_Iter', Num_Iter}),
{Time, Result} = aco (Fname, Num_Ants, Num_Iter, Params),
output_result (Time, Result, Num_Ants, Num_Iter);
["h"] -> usage();
[F|_] -> io:format ("Unknown option ~p~n", [F]), usage();
[] -> usage()
end.
-spec run([atom()]) -> ok.
run(Args) ->
run2 (lists:map (fun atom_to_list/1, Args), Params).
-spec run() -> ok.
run () -> usage().
|
25089f19ad9198795e1ce2632cbbed5abf31f6932555c434cc9bfe49e55516b9 | hirokai/PaperServer | Science.hs | # LANGUAGE QuasiQuotes #
-----------------------------------------------------------------------------
--
-- Module : Model.PaperReader.Science
-- Copyright :
-- License : BSD3
--
Maintainer :
-- Stability : Experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
--
-- For Science
--
module Parser.Publisher.Science (
scienceReader,
stkeReader
) where
import Parser.Import
import Parser.Utils
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Text.Read
import Control.Applicative
import Text.XML.Cursor
_scienceReader = defaultReader{
doi = anyLevel _doi,
journal = anyLevel _journal,
publisher = anyLevel _publisher,
volume = anyLevel _volume,
pageFrom = anyLevel _pageFrom,
year = anyLevel _year,
authors = anyLevel _authors,
articleType = anyLevel _articleType,
figs = onlyFullL _figsS
}
_scienceReader :: PaperReader
scienceReader :: PaperReader
stkeReader :: PaperReader
_supportedUrlSTKE :: PaperReader -> Text -> Maybe SupportLevel
_supportedUrlS :: PaperReader -> Text -> Maybe SupportLevel
_supportedS :: PaperReader -> Text -> Cursor -> Maybe SupportLevel
_titleSTKE, _titleS, _journal, _volume, _articleType
:: ReaderElement' (Maybe Text)
_doi :: ReaderElement' Text
_year :: ReaderElement' (Maybe Int)
_authors :: ReaderElement' [Text]
_publisher :: ReaderElement' (Maybe Text)
_pageFrom, _pageToS :: ReaderElement' (Maybe Text)
_abstractS :: ReaderElement (Maybe Text)
_mainHtmlS :: ReaderElement (Maybe PaperMainText)
scienceReader = _scienceReader {
title=anyLevel _titleS
, supported=_supportedS
, supportedUrl=_supportedUrlS
, pageTo=anyLevel _pageToS
, abstract=_abstractS
, mainHtml=_mainHtmlS
}
stkeReader = _scienceReader {
title=anyLevel _titleSTKE
, supportedUrl=_supportedUrlSTKE
}
_doi _ = fromMaybe "" . headm . getMeta "citation_doi"
_supportedUrlSTKE _ url
= if any (`T.isPrefixOf` url) ["/"] then
Just SCitation
else
Nothing
_supportedUrlS _ url =
if "/" `T.isPrefixOf` url then
if ".full" `T.isSuffixOf` url then
Just SFullText
else if ".abstract" `T.isSuffixOf` url then
Just SAbstract
else
Nothing
else
Nothing
_supportedS r url cur =
case _supportedUrlS r url of
Just SFullText ->
if (not . null $ queryT [jq| div.fulltext-view > p |] cur) then
Just SFullText
else
Just SAbstract
Just SAbstract -> Just SAbstract
s -> s
-- _title :: PaperReader -> Cursor -> Maybe Text
_titleSTKE _ = inner . queryT [jq| h2 |]
_titleS _ = inner . queryT [jq| #article-title-1 |]
_journal _ = headm . getMeta "citation_journal_title"
_publisher _ = headm . getMeta "citation_publisher"
_pageFrom _ = headm . getMeta "citation_firstpage"
_authors _ = getMeta "citation_authors"
_volume _ = headm . getMeta "citation_volume"
_year _ cur = (fmap (T.reverse . T.take 4 . T.reverse) . headm . getMeta "citation_date") cur >>= r
where r a = case decimal a of
Left err -> Nothing
Right (v,t) -> Just v
_articleType _ cur = (fmap ( (:[])) . headm . queryT [jq| h5 |]) cur >>= inner
_pageToS _ = headm . getMeta "citation_lastpage"
_abstractS _ support
| support == SFullText || support == SAbstract = inner . queryT [jq| div.section.abstract > p |]
| otherwise = const Nothing
_mainHtmlS _ SFullText c = fmap FlatHtml $ maybeText $ TL.toStrict $ toHtml $ queryT [jq| div.fulltext-view > p |] c
_mainHtmlS _ _ c = Nothing
_figsS _ c =
let
cs = queryT [jq| div.fig |] c
mkFig d =
let
id_ = eid $ node d
imgdiv = headm $ queryT [jq| div.fig-inline img |] d
name = imgdiv >>= (headMay . attribute "alt")
cap = imgdiv >>= (inner . queryT [jq| div.fig-caption |])
img = imgdiv >>= (headMay . attribute "src")
in
Figure <$> id_ <*> name <*> cap <*> img
in
catMaybes $ map mkFig cs
| null | https://raw.githubusercontent.com/hirokai/PaperServer/b577955af08660253d0cd11282cf141d1c174bc0/Parser/Publisher/Science.hs | haskell | ---------------------------------------------------------------------------
Module : Model.PaperReader.Science
Copyright :
License : BSD3
Stability : Experimental
Portability :
|
---------------------------------------------------------------------------
For Science
_title :: PaperReader -> Cursor -> Maybe Text | # LANGUAGE QuasiQuotes #
Maintainer :
module Parser.Publisher.Science (
scienceReader,
stkeReader
) where
import Parser.Import
import Parser.Utils
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Text.Read
import Control.Applicative
import Text.XML.Cursor
_scienceReader = defaultReader{
doi = anyLevel _doi,
journal = anyLevel _journal,
publisher = anyLevel _publisher,
volume = anyLevel _volume,
pageFrom = anyLevel _pageFrom,
year = anyLevel _year,
authors = anyLevel _authors,
articleType = anyLevel _articleType,
figs = onlyFullL _figsS
}
_scienceReader :: PaperReader
scienceReader :: PaperReader
stkeReader :: PaperReader
_supportedUrlSTKE :: PaperReader -> Text -> Maybe SupportLevel
_supportedUrlS :: PaperReader -> Text -> Maybe SupportLevel
_supportedS :: PaperReader -> Text -> Cursor -> Maybe SupportLevel
_titleSTKE, _titleS, _journal, _volume, _articleType
:: ReaderElement' (Maybe Text)
_doi :: ReaderElement' Text
_year :: ReaderElement' (Maybe Int)
_authors :: ReaderElement' [Text]
_publisher :: ReaderElement' (Maybe Text)
_pageFrom, _pageToS :: ReaderElement' (Maybe Text)
_abstractS :: ReaderElement (Maybe Text)
_mainHtmlS :: ReaderElement (Maybe PaperMainText)
scienceReader = _scienceReader {
title=anyLevel _titleS
, supported=_supportedS
, supportedUrl=_supportedUrlS
, pageTo=anyLevel _pageToS
, abstract=_abstractS
, mainHtml=_mainHtmlS
}
stkeReader = _scienceReader {
title=anyLevel _titleSTKE
, supportedUrl=_supportedUrlSTKE
}
_doi _ = fromMaybe "" . headm . getMeta "citation_doi"
_supportedUrlSTKE _ url
= if any (`T.isPrefixOf` url) ["/"] then
Just SCitation
else
Nothing
_supportedUrlS _ url =
if "/" `T.isPrefixOf` url then
if ".full" `T.isSuffixOf` url then
Just SFullText
else if ".abstract" `T.isSuffixOf` url then
Just SAbstract
else
Nothing
else
Nothing
_supportedS r url cur =
case _supportedUrlS r url of
Just SFullText ->
if (not . null $ queryT [jq| div.fulltext-view > p |] cur) then
Just SFullText
else
Just SAbstract
Just SAbstract -> Just SAbstract
s -> s
_titleSTKE _ = inner . queryT [jq| h2 |]
_titleS _ = inner . queryT [jq| #article-title-1 |]
_journal _ = headm . getMeta "citation_journal_title"
_publisher _ = headm . getMeta "citation_publisher"
_pageFrom _ = headm . getMeta "citation_firstpage"
_authors _ = getMeta "citation_authors"
_volume _ = headm . getMeta "citation_volume"
_year _ cur = (fmap (T.reverse . T.take 4 . T.reverse) . headm . getMeta "citation_date") cur >>= r
where r a = case decimal a of
Left err -> Nothing
Right (v,t) -> Just v
_articleType _ cur = (fmap ( (:[])) . headm . queryT [jq| h5 |]) cur >>= inner
_pageToS _ = headm . getMeta "citation_lastpage"
_abstractS _ support
| support == SFullText || support == SAbstract = inner . queryT [jq| div.section.abstract > p |]
| otherwise = const Nothing
_mainHtmlS _ SFullText c = fmap FlatHtml $ maybeText $ TL.toStrict $ toHtml $ queryT [jq| div.fulltext-view > p |] c
_mainHtmlS _ _ c = Nothing
_figsS _ c =
let
cs = queryT [jq| div.fig |] c
mkFig d =
let
id_ = eid $ node d
imgdiv = headm $ queryT [jq| div.fig-inline img |] d
name = imgdiv >>= (headMay . attribute "alt")
cap = imgdiv >>= (inner . queryT [jq| div.fig-caption |])
img = imgdiv >>= (headMay . attribute "src")
in
Figure <$> id_ <*> name <*> cap <*> img
in
catMaybes $ map mkFig cs
|
61c34720381a14d9164e7ae1f19e68a90c2ffea3a2b6039ae4b03602e2ece99d | luke-clifton/shh | release.hs | #! /usr/bin/env runghc
# LANGUAGE TemplateHaskell #
# LANGUAGE ExtendedDefaultRules #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE LambdaCase #
import System.FilePath.Glob
import Shh
import System.Exit
import Control.Exception
import qualified Data.ByteString.Lazy.Char8 as B
loadEnv SearchPath
hackageVersion :: String -> IO String
hackageVersion pkg =
curl "-fsS" "-H" "Accept: application/json" ("/" ++ pkg ++ "/preferred")
|> jq "-r" ".\"normal-version\"[0]"
|> (B.unpack <$> captureTrim)
localVersion :: String -> IO String
localVersion pkg =
grep "^version:" (pkg ++ "/" ++ pkg ++ ".cabal")
|> tr "-d" "[:space:]"
|> cut "-d:" "-f2"
|> (B.unpack <$> captureTrim)
needsUpload :: String -> IO Bool
needsUpload pkg = do
hv <- hackageVersion pkg
lv <- localVersion pkg
pure (lv /= hv)
upload :: String -> IO ()
upload pkg = do
needsUpload pkg >>= \case
True -> do
sanity pkg >>= \case
True -> do
lv <- localVersion pkg
let toupload = pkg ++ "-" ++ lv
putStrLn $ "Uploading " ++ toupload
putStrLn "continue? (type 'yes')"
getLine >>= \case
"yes" -> pure ()
_ -> exitFailure
bracket
(mktemp "-d" |> captureTrim)
(rm "-Rf" "--")
$ \tmp -> do
cabal "new-sdist" "--verbose=0" "--builddir" tmp pkg
cabal "new-haddock" "--haddock-for-hackage" "--builddir" tmp pkg
cabal "upload" "--publish" (B.unpack tmp ++ "/sdist/" ++ toupload ++ ".tar.gz")
cabal "upload" "--publish" "-d" (B.unpack tmp ++ "/" ++ toupload ++ "-docs.tar.gz")
git "tag" "-a" toupload "-m" ("Releasing " ++ toupload)
git "push" "origin" toupload
False -> putStrLn $ pkg ++ " has issues, not uploading"
False -> do
putStrLn $ pkg ++ " was not uploaded (versions match)"
codeMatch pkg >>= \case
True -> pure ()
False -> do
putStrLn "... but there is a difference in the tarballs!"
putStrLn "... bump the version number to upload!"
putStrLn "... NB: this might differ because of metadata revisions."
codeMatch :: String -> IO Bool
codeMatch pkg = do
bracket
(mktemp "-d" |> captureTrim)
(rm "-Rf" "--")
$ \tmp -> do
hv <- hackageVersion pkg
cabal "new-sdist" "--verbose=0" "--builddir" tmp pkg
src <- glob (B.unpack tmp ++ "/sdist/*.tar.gz")
gunzip src
src <- glob (B.unpack tmp ++ "/sdist/*.tar")
mkdir "-p" (tmp <> "/local")
mkdir "-p" (tmp <> "/remote")
tar "-C" (tmp <> "/local") "-xf" src
curl "-fsS"
("/" ++ pkg ++ "/" ++ pkg ++ "-" ++ hv ++ ".tar.gz")
|> gunzip
|> tar "-C" (tmp <> "/remote") "-x"
curl "-fsS"
("/" ++ pkg ++ "-" ++ hv ++ "/" ++ pkg ++ ".cabal")
|> ignoreFailure (grep "-v" "x-revision")
&> Truncate (B.pack $ B.unpack tmp ++ "/remote/" ++ pkg ++ "-" ++ hv ++ "/" ++ pkg ++ ".cabal")
translateCode (\case
1 -> Just False
_ -> Nothing
) $ const True <$> diff "--strip-trailing-cr" "-r" (tmp <> "/local") (tmp <> "/remote")
sanity :: String -> IO Bool
sanity pkg = tryFailure (do
git "diff" "--exit-code"
git "diff" "--cached" "--exit-code"
cabal "new-build" pkg
cabal "new-test" pkg
gr <- cabal "new-haddock" "--haddock-for-hackage" pkg |> exitCode (grep "-A" 5 "Missing documentation")
pure (gr == 0)
) >>= either (const $ pure False) pure
main :: IO ()
main = do
upload "shh"
upload "shh-extras"
| null | https://raw.githubusercontent.com/luke-clifton/shh/f2d13b27a1ae86d003deb1d78e79d9a76a0f8882/release.hs | haskell | # LANGUAGE OverloadedStrings # | #! /usr/bin/env runghc
# LANGUAGE TemplateHaskell #
# LANGUAGE ExtendedDefaultRules #
# LANGUAGE LambdaCase #
import System.FilePath.Glob
import Shh
import System.Exit
import Control.Exception
import qualified Data.ByteString.Lazy.Char8 as B
loadEnv SearchPath
hackageVersion :: String -> IO String
hackageVersion pkg =
curl "-fsS" "-H" "Accept: application/json" ("/" ++ pkg ++ "/preferred")
|> jq "-r" ".\"normal-version\"[0]"
|> (B.unpack <$> captureTrim)
localVersion :: String -> IO String
localVersion pkg =
grep "^version:" (pkg ++ "/" ++ pkg ++ ".cabal")
|> tr "-d" "[:space:]"
|> cut "-d:" "-f2"
|> (B.unpack <$> captureTrim)
needsUpload :: String -> IO Bool
needsUpload pkg = do
hv <- hackageVersion pkg
lv <- localVersion pkg
pure (lv /= hv)
upload :: String -> IO ()
upload pkg = do
needsUpload pkg >>= \case
True -> do
sanity pkg >>= \case
True -> do
lv <- localVersion pkg
let toupload = pkg ++ "-" ++ lv
putStrLn $ "Uploading " ++ toupload
putStrLn "continue? (type 'yes')"
getLine >>= \case
"yes" -> pure ()
_ -> exitFailure
bracket
(mktemp "-d" |> captureTrim)
(rm "-Rf" "--")
$ \tmp -> do
cabal "new-sdist" "--verbose=0" "--builddir" tmp pkg
cabal "new-haddock" "--haddock-for-hackage" "--builddir" tmp pkg
cabal "upload" "--publish" (B.unpack tmp ++ "/sdist/" ++ toupload ++ ".tar.gz")
cabal "upload" "--publish" "-d" (B.unpack tmp ++ "/" ++ toupload ++ "-docs.tar.gz")
git "tag" "-a" toupload "-m" ("Releasing " ++ toupload)
git "push" "origin" toupload
False -> putStrLn $ pkg ++ " has issues, not uploading"
False -> do
putStrLn $ pkg ++ " was not uploaded (versions match)"
codeMatch pkg >>= \case
True -> pure ()
False -> do
putStrLn "... but there is a difference in the tarballs!"
putStrLn "... bump the version number to upload!"
putStrLn "... NB: this might differ because of metadata revisions."
codeMatch :: String -> IO Bool
codeMatch pkg = do
bracket
(mktemp "-d" |> captureTrim)
(rm "-Rf" "--")
$ \tmp -> do
hv <- hackageVersion pkg
cabal "new-sdist" "--verbose=0" "--builddir" tmp pkg
src <- glob (B.unpack tmp ++ "/sdist/*.tar.gz")
gunzip src
src <- glob (B.unpack tmp ++ "/sdist/*.tar")
mkdir "-p" (tmp <> "/local")
mkdir "-p" (tmp <> "/remote")
tar "-C" (tmp <> "/local") "-xf" src
curl "-fsS"
("/" ++ pkg ++ "/" ++ pkg ++ "-" ++ hv ++ ".tar.gz")
|> gunzip
|> tar "-C" (tmp <> "/remote") "-x"
curl "-fsS"
("/" ++ pkg ++ "-" ++ hv ++ "/" ++ pkg ++ ".cabal")
|> ignoreFailure (grep "-v" "x-revision")
&> Truncate (B.pack $ B.unpack tmp ++ "/remote/" ++ pkg ++ "-" ++ hv ++ "/" ++ pkg ++ ".cabal")
translateCode (\case
1 -> Just False
_ -> Nothing
) $ const True <$> diff "--strip-trailing-cr" "-r" (tmp <> "/local") (tmp <> "/remote")
sanity :: String -> IO Bool
sanity pkg = tryFailure (do
git "diff" "--exit-code"
git "diff" "--cached" "--exit-code"
cabal "new-build" pkg
cabal "new-test" pkg
gr <- cabal "new-haddock" "--haddock-for-hackage" pkg |> exitCode (grep "-A" 5 "Missing documentation")
pure (gr == 0)
) >>= either (const $ pure False) pure
main :: IO ()
main = do
upload "shh"
upload "shh-extras"
|
72d82ba099d329f09bf953d6a0c6f0ec3b4d5b3eca8e0103ac539e68dae7eb20 | kadena-io/chainweb-node | Create.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
-- |
Module : Chainweb . Cut . Create
Copyright : Copyright © 2020 Kadena LLC .
License : MIT
Maintainer : < >
-- Stability: experimental
--
-- The steps for extending a Cut with a new Block are usually as follows:
--
1 . Select a chain for the new Block header
2 . Call ' getCutExtension ' . If the result is ' Nothing ' the chain is
-- blocked. In which case another chain must be choosen.
3 . Call pact service to create new payload for the new block
4 . Assemble preliminary work header , with preliminary time and nonce value
-- (time should be current time, nonce should be 0) and send work header
-- to the miner.
5 . Receive resolved header ( with final nonce and creation time ) from miner
6 . Create new header by computing the merkle hash for the resolved header
7 . Extend cut with new header by calling ' tryMonotonicCutExtension '
8 . Create new cut hashes with the new header and payload attached .
9 . Submit cut hashes ( along with attached new header and payload ) to cut
-- validation pipeline.
--
module Chainweb.Cut.Create
(
-- * Cut Extension
CutExtension
, _cutExtensionCut
, cutExtensionCut
, _cutExtensionParent
, cutExtensionParent
, _cutExtensionAdjacentHashes
, cutExtensionAdjacentHashes
, getCutExtension
-- * Work
, WorkHeader(..)
, encodeWorkHeader
, decodeWorkHeader
, newWorkHeader
, newWorkHeaderPure
-- * Solved Work
, SolvedWork(..)
, encodeSolvedWork
, decodeSolvedWork
, extend
, InvalidSolvedHeader(..)
, extendCut
) where
import Control.DeepSeq
import Control.Lens
import Control.Monad
import Control.Monad.Catch
import qualified Data.ByteString.Short as SB
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import qualified Data.Text as T
import GHC.Generics
import GHC.Stack
-- internal modules
import Chainweb.BlockCreationTime
import Chainweb.BlockHash
import Chainweb.BlockHeader
import Chainweb.BlockHeader.Validation
import Chainweb.BlockHeight
import Chainweb.ChainValue
import Chainweb.Cut
import Chainweb.Cut.CutHashes
import Chainweb.Difficulty
import Chainweb.Payload
import Chainweb.Time
import Chainweb.Utils
import Chainweb.Utils.Serialization
import Chainweb.Version
import Chainweb.Version.Utils
-- -------------------------------------------------------------------------- --
-- Adjacent Parent Hashes
-- | Witnesses that a cut can be extended for the respective header.
--
data CutExtension = CutExtension
{ _cutExtensionCut' :: !Cut
-- This is overly restrictive, since the same cut extension can be
valid for more than one cut . It 's fine for now .
, _cutExtensionParent' :: !ParentHeader
, _cutExtensionAdjacentHashes' :: !BlockHashRecord
}
deriving (Show, Eq, Generic)
makeLenses ''CutExtension
_cutExtensionCut :: CutExtension -> Cut
_cutExtensionCut = _cutExtensionCut'
cutExtensionCut :: Lens' CutExtension Cut
cutExtensionCut = cutExtensionCut'
_cutExtensionParent :: CutExtension -> ParentHeader
_cutExtensionParent = _cutExtensionParent'
cutExtensionParent :: Lens' CutExtension ParentHeader
cutExtensionParent = cutExtensionParent'
_cutExtensionAdjacentHashes :: CutExtension -> BlockHashRecord
_cutExtensionAdjacentHashes = _cutExtensionAdjacentHashes'
cutExtensionAdjacentHashes :: Lens' CutExtension BlockHashRecord
cutExtensionAdjacentHashes = cutExtensionAdjacentHashes'
instance HasChainId CutExtension where
_chainId = _chainId . _cutExtensionParent
{-# INLINE _chainId #-}
instance HasChainwebVersion CutExtension where
_chainwebVersion = _chainwebVersion . _cutExtensionCut
# INLINE _ chainwebVersion #
-- | Witness that a cut can be extended for the given chain by trying to
-- assemble the adjacent hashes for a new work header.
--
-- Generally, adajacent validation uses the graph of the parent header. This
-- ensures that during a graph transition the current header and all
-- dependencies use the same graph and the inductive validation step works
without special cases . Genesis headers do n't require validation , because they
are hard - coded . Only in the first step after the transition , the dependencies
-- have a different graph. But at this point all dependencies exist.
--
-- A transition cut is a cut where the graph of minimum height header is
-- different than the graph of the header of maximum height. If this is a
-- transition cut, i.e. the cut contains block headers with different graphs, we
-- wait until all chains transitions to the new graph before add the genesis
-- blocks for the new chains and move ahead. So steps in the new graph are not
-- allowed.
--
-- TODO: it is important that the semantics of this function corresponds to the
respective validation in the module " Chainweb . Cut " , in particular
-- 'isMonotonicCutExtension'. It must not happen, that a cut passes validation
-- that can't be further extended.
--
getCutExtension
:: HasCallStack
=> HasChainId cid
=> Cut
-- ^ the cut which is to be extended
-> cid
-- ^ the header onto which the new block is created. It is expected
-- that this header is contained in the cut.
-> Maybe CutExtension
getCutExtension c cid = do
-- In a graph transition we wait for all chains to do the transition to the
-- new graph before moving ahead.
--
guard (not $ isGraphTransitionCut && isGraphTransitionPost)
as <- BlockHashRecord <$> newAdjHashes parentGraph
return CutExtension
{ _cutExtensionCut' = c
, _cutExtensionParent' = ParentHeader p
, _cutExtensionAdjacentHashes' = as
}
where
p = c ^?! ixg (_chainId cid)
v = _chainwebVersion c
parentHeight = _blockHeight p
targetHeight = parentHeight + 1
parentGraph = chainGraphAt_ p parentHeight
isGraphTransitionPost = isGraphChange c parentHeight
isGraphTransitionCut = isTransitionCut c
-- | Try to get all adjacent hashes dependencies for the given graph.
--
newAdjHashes :: ChainGraph -> Maybe (HM.HashMap ChainId BlockHash)
newAdjHashes g =
imapM (\xcid _ -> hashForChain xcid)
converts to ( )
$ adjacentChainIds g p
hashForChain acid
-- existing chain
| Just b <- lookupCutM acid c = tryAdj b
| targetHeight == genesisHeight v acid = error $ T.unpack
$ "getAdjacentParents: invalid cut extension, requested parent of a genesis block for chain "
<> sshow acid
<> ". Parent: " <> encodeToText (ObjectEncoded p)
| otherwise = error $ T.unpack
$ "getAdjacentParents: invalid cut, can't find adjacent hash for chain "
<> sshow acid
<> ". Parent: " <> encodeToText (ObjectEncoded p)
tryAdj :: BlockHeader -> Maybe BlockHash
tryAdj b
-- When the block is behind, we can move ahead
| _blockHeight b == targetHeight = Just $! _blockParent b
-- if the block is ahead it's blocked
| _blockHeight b + 1 == parentHeight = Nothing -- chain is blocked
-- If this is not a graph transition cut we can move ahead
| _blockHeight b == parentHeight = Just $! _blockHash b
-- The cut is invalid
| _blockHeight b > targetHeight = error $ T.unpack
$ "getAdjacentParents: detected invalid cut (adjacent parent too far ahead)."
<> " Parent: " <> encodeToText (ObjectEncoded p)
<> " Conflict: " <> encodeToText (ObjectEncoded b)
| _blockHeight b + 1 < parentHeight = error $ T.unpack
$ "getAdjacentParents: detected invalid cut (adjacent parent too far behind)."
<> " Parent: " <> encodeToText (ObjectEncoded p)
<> " Conflict: " <> encodeToText (ObjectEncoded b)
| otherwise = error
$ "Chainweb.Miner.Coordinator.getAdjacentParents: internal code invariant violation"
-- -------------------------------------------------------------------------- --
-- Mining Work Header
| A work header has a preliminary creation time and an invalid nonce of 0 .
-- It is the job of the miner to update the creation time and find a valid nonce
-- that satisfies the target of the header.
--
-- The updated header has type 'SolvedHeader'.
--
data WorkHeader = WorkHeader
{ _workHeaderChainId :: !ChainId
, _workHeaderTarget :: !HashTarget
, _workHeaderBytes :: !SB.ShortByteString
^ 286 work bytes .
The last 8 bytes are the nonce
The creation time is encoded in bytes 8 - 15
}
deriving (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
encodeWorkHeader :: WorkHeader -> Put
encodeWorkHeader wh = do
encodeChainId $ _workHeaderChainId wh
encodeHashTarget $ _workHeaderTarget wh
putByteString $ SB.fromShort $ _workHeaderBytes wh
-- FIXME: We really want this indepenent of the block height. For production
chainweb version this is actually the case .
--
decodeWorkHeader :: ChainwebVersion -> BlockHeight -> Get WorkHeader
decodeWorkHeader ver h = WorkHeader
<$> decodeChainId
<*> decodeHashTarget
<*> (SB.toShort <$> getByteString (int $ workSizeBytes ver h))
-- | Create work header for cut
--
newWorkHeader
:: ChainValueCasLookup hdb BlockHeader
=> hdb
-> CutExtension
-> BlockPayloadHash
-> IO WorkHeader
newWorkHeader hdb e h = do
creationTime <- BlockCreationTime <$> getCurrentTimeIntegral
newWorkHeaderPure (chainLookupM hdb) creationTime e h
-- | A pure version of 'newWorkHeader' that is useful in testing.
--
newWorkHeaderPure
:: Applicative m
=> (ChainValue BlockHash -> m BlockHeader)
-> BlockCreationTime
-> CutExtension
-> BlockPayloadHash
-> m WorkHeader
newWorkHeaderPure hdb creationTime extension phash = do
-- Collect block headers for adjacent parents, some of which may be
-- available in the cut.
createWithParents <$> getAdjacentParentHeaders hdb extension
where
Assemble a candidate ` BlockHeader ` without a specific ` Nonce `
-- value. `Nonce` manipulation is assumed to occur within the
-- core Mining logic.
--
createWithParents parents =
let nh = newBlockHeader parents phash (Nonce 0) creationTime
$! _cutExtensionParent extension
-- FIXME: check that parents also include hashes on new chains!
in WorkHeader
{ _workHeaderBytes = SB.toShort $ runPutS $ encodeBlockHeaderWithoutHash nh
, _workHeaderTarget = _blockTarget nh
, _workHeaderChainId = _chainId nh
}
-- | Get all adjacent parent headers for a new block header for a given cut.
--
-- This yields the same result as 'blockAdjacentParentHeaders', however, it is
-- more efficent when the cut and the adjacent parent hashes are already known.
-- Also, it works accross graph changes. It is not checked whether the given
-- adjacent parent hashes are consistent with the cut.
--
-- Only those parents are included that are not block parent hashes of genesis
-- blocks. This can occur when new graphs are introduced. The headers are used
-- in 'newBlockHeader' for computing the target. That means that during a graph
-- change the target computation may only use some (or none) adjacent parents to
-- adjust the epoch start, which is fine.
--
-- If the parent header doesn't exist, because the chain is new, only the
-- genesis parent hash is included as 'Left' value.
--
getAdjacentParentHeaders
:: HasCallStack
=> Applicative m
=> (ChainValue BlockHash -> m BlockHeader)
-> CutExtension
-> m (HM.HashMap ChainId ParentHeader)
getAdjacentParentHeaders hdb extension
= itraverse select
. _getBlockHashRecord
$ _cutExtensionAdjacentHashes extension
where
c = _cutExtensionCut extension
select cid h = case c ^? ixg cid of
Just ch -> ParentHeader <$> if _blockHash ch == h
then pure ch
else hdb (ChainValue cid h)
Nothing -> error $ T.unpack
$ "Chainweb.Cut.Create.getAdjacentParentHeaders: inconsistent cut extension detected"
<> ". ChainId: " <> encodeToText cid
<> ". CutHashes: " <> encodeToText (cutToCutHashes Nothing c)
-- -------------------------------------------------------------------------- --
-- Solved Header
--
-- | A solved header is the result of mining. It has the final creation time and
a valid nonce . The binary representation does n't yet contain a Hash .
-- Also, the block header is not yet validated.
--
-- This is an internal data type. On the client/miner side only the serialized
-- representation is used.
--
newtype SolvedWork = SolvedWork BlockHeader
deriving (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
encodeSolvedWork :: SolvedWork -> Put
encodeSolvedWork (SolvedWork hdr) = encodeBlockHeaderWithoutHash hdr
decodeSolvedWork :: Get SolvedWork
decodeSolvedWork = SolvedWork <$> decodeBlockHeaderWithoutHash
data InvalidSolvedHeader = InvalidSolvedHeader BlockHeader T.Text
deriving (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
instance Exception InvalidSolvedHeader
-- | Extend a Cut with a solved work value.
--
-- The function verifies that the solved work actually is a valid extension of
the cut and matches the given payload data . It also checks a few other
-- invariants. It does't do a full validation.
--
The resulting ' CutHashes ' value contains the new header and payload as
-- attachement and can be submitted into a cut pipeline.
--
-- The result is 'Nothing' if the given cut can't be extended with the solved
-- work.
--
extend
:: MonadThrow m
=> Cut
-> PayloadData
-> SolvedWork
-> m (BlockHeader, Maybe CutHashes)
extend c pd s = do
(bh, mc) <- extendCut c (_payloadDataPayloadHash pd) s
return (bh, toCutHashes bh <$> mc)
where
toCutHashes bh c' = cutToCutHashes Nothing c'
& set cutHashesHeaders (HM.singleton (_blockHash bh) bh)
& set cutHashesPayloads (HM.singleton (_blockPayloadHash bh) pd)
-- | For internal use and testing
--
extendCut
:: MonadThrow m
=> Cut
-> BlockPayloadHash
-> SolvedWork
-> m (BlockHeader, Maybe Cut)
extendCut c ph (SolvedWork bh) = do
Fail Early : If a ` BlockHeader ` 's injected ( and thus its POW
-- Hash) is trivially incorrect, reject it.
--
unless (prop_block_pow bh)
$ throwM $ InvalidSolvedHeader bh "Invalid POW hash"
-- Fail Early: check that the given payload matches the new block.
--
unless (_blockPayloadHash bh == ph) $ throwM $ InvalidSolvedHeader bh
$ "Invalid payload hash"
<> ". Expected: " <> sshow (_blockPayloadHash bh)
<> ", Got: " <> sshow ph
If the ` BlockHeader ` is already stale and ca n't be appended to the
-- best `Cut`, Nothing is returned
--
(bh,) <$> tryMonotonicCutExtension c bh
| null | https://raw.githubusercontent.com/kadena-io/chainweb-node/aff594a05096341d01ae50a9f37056b2519025d2/src/Chainweb/Cut/Create.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
|
Stability: experimental
The steps for extending a Cut with a new Block are usually as follows:
blocked. In which case another chain must be choosen.
(time should be current time, nonce should be 0) and send work header
to the miner.
validation pipeline.
* Cut Extension
* Work
* Solved Work
internal modules
-------------------------------------------------------------------------- --
Adjacent Parent Hashes
| Witnesses that a cut can be extended for the respective header.
This is overly restrictive, since the same cut extension can be
# INLINE _chainId #
| Witness that a cut can be extended for the given chain by trying to
assemble the adjacent hashes for a new work header.
Generally, adajacent validation uses the graph of the parent header. This
ensures that during a graph transition the current header and all
dependencies use the same graph and the inductive validation step works
have a different graph. But at this point all dependencies exist.
A transition cut is a cut where the graph of minimum height header is
different than the graph of the header of maximum height. If this is a
transition cut, i.e. the cut contains block headers with different graphs, we
wait until all chains transitions to the new graph before add the genesis
blocks for the new chains and move ahead. So steps in the new graph are not
allowed.
TODO: it is important that the semantics of this function corresponds to the
'isMonotonicCutExtension'. It must not happen, that a cut passes validation
that can't be further extended.
^ the cut which is to be extended
^ the header onto which the new block is created. It is expected
that this header is contained in the cut.
In a graph transition we wait for all chains to do the transition to the
new graph before moving ahead.
| Try to get all adjacent hashes dependencies for the given graph.
existing chain
When the block is behind, we can move ahead
if the block is ahead it's blocked
chain is blocked
If this is not a graph transition cut we can move ahead
The cut is invalid
-------------------------------------------------------------------------- --
Mining Work Header
It is the job of the miner to update the creation time and find a valid nonce
that satisfies the target of the header.
The updated header has type 'SolvedHeader'.
FIXME: We really want this indepenent of the block height. For production
| Create work header for cut
| A pure version of 'newWorkHeader' that is useful in testing.
Collect block headers for adjacent parents, some of which may be
available in the cut.
value. `Nonce` manipulation is assumed to occur within the
core Mining logic.
FIXME: check that parents also include hashes on new chains!
| Get all adjacent parent headers for a new block header for a given cut.
This yields the same result as 'blockAdjacentParentHeaders', however, it is
more efficent when the cut and the adjacent parent hashes are already known.
Also, it works accross graph changes. It is not checked whether the given
adjacent parent hashes are consistent with the cut.
Only those parents are included that are not block parent hashes of genesis
blocks. This can occur when new graphs are introduced. The headers are used
in 'newBlockHeader' for computing the target. That means that during a graph
change the target computation may only use some (or none) adjacent parents to
adjust the epoch start, which is fine.
If the parent header doesn't exist, because the chain is new, only the
genesis parent hash is included as 'Left' value.
-------------------------------------------------------------------------- --
Solved Header
| A solved header is the result of mining. It has the final creation time and
Also, the block header is not yet validated.
This is an internal data type. On the client/miner side only the serialized
representation is used.
| Extend a Cut with a solved work value.
The function verifies that the solved work actually is a valid extension of
invariants. It does't do a full validation.
attachement and can be submitted into a cut pipeline.
The result is 'Nothing' if the given cut can't be extended with the solved
work.
| For internal use and testing
Hash) is trivially incorrect, reject it.
Fail Early: check that the given payload matches the new block.
best `Cut`, Nothing is returned
| # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
Module : Chainweb . Cut . Create
Copyright : Copyright © 2020 Kadena LLC .
License : MIT
Maintainer : < >
1 . Select a chain for the new Block header
2 . Call ' getCutExtension ' . If the result is ' Nothing ' the chain is
3 . Call pact service to create new payload for the new block
4 . Assemble preliminary work header , with preliminary time and nonce value
5 . Receive resolved header ( with final nonce and creation time ) from miner
6 . Create new header by computing the merkle hash for the resolved header
7 . Extend cut with new header by calling ' tryMonotonicCutExtension '
8 . Create new cut hashes with the new header and payload attached .
9 . Submit cut hashes ( along with attached new header and payload ) to cut
module Chainweb.Cut.Create
(
CutExtension
, _cutExtensionCut
, cutExtensionCut
, _cutExtensionParent
, cutExtensionParent
, _cutExtensionAdjacentHashes
, cutExtensionAdjacentHashes
, getCutExtension
, WorkHeader(..)
, encodeWorkHeader
, decodeWorkHeader
, newWorkHeader
, newWorkHeaderPure
, SolvedWork(..)
, encodeSolvedWork
, decodeSolvedWork
, extend
, InvalidSolvedHeader(..)
, extendCut
) where
import Control.DeepSeq
import Control.Lens
import Control.Monad
import Control.Monad.Catch
import qualified Data.ByteString.Short as SB
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import qualified Data.Text as T
import GHC.Generics
import GHC.Stack
import Chainweb.BlockCreationTime
import Chainweb.BlockHash
import Chainweb.BlockHeader
import Chainweb.BlockHeader.Validation
import Chainweb.BlockHeight
import Chainweb.ChainValue
import Chainweb.Cut
import Chainweb.Cut.CutHashes
import Chainweb.Difficulty
import Chainweb.Payload
import Chainweb.Time
import Chainweb.Utils
import Chainweb.Utils.Serialization
import Chainweb.Version
import Chainweb.Version.Utils
data CutExtension = CutExtension
{ _cutExtensionCut' :: !Cut
valid for more than one cut . It 's fine for now .
, _cutExtensionParent' :: !ParentHeader
, _cutExtensionAdjacentHashes' :: !BlockHashRecord
}
deriving (Show, Eq, Generic)
makeLenses ''CutExtension
_cutExtensionCut :: CutExtension -> Cut
_cutExtensionCut = _cutExtensionCut'
cutExtensionCut :: Lens' CutExtension Cut
cutExtensionCut = cutExtensionCut'
_cutExtensionParent :: CutExtension -> ParentHeader
_cutExtensionParent = _cutExtensionParent'
cutExtensionParent :: Lens' CutExtension ParentHeader
cutExtensionParent = cutExtensionParent'
_cutExtensionAdjacentHashes :: CutExtension -> BlockHashRecord
_cutExtensionAdjacentHashes = _cutExtensionAdjacentHashes'
cutExtensionAdjacentHashes :: Lens' CutExtension BlockHashRecord
cutExtensionAdjacentHashes = cutExtensionAdjacentHashes'
instance HasChainId CutExtension where
_chainId = _chainId . _cutExtensionParent
instance HasChainwebVersion CutExtension where
_chainwebVersion = _chainwebVersion . _cutExtensionCut
# INLINE _ chainwebVersion #
without special cases . Genesis headers do n't require validation , because they
are hard - coded . Only in the first step after the transition , the dependencies
respective validation in the module " Chainweb . Cut " , in particular
getCutExtension
:: HasCallStack
=> HasChainId cid
=> Cut
-> cid
-> Maybe CutExtension
getCutExtension c cid = do
guard (not $ isGraphTransitionCut && isGraphTransitionPost)
as <- BlockHashRecord <$> newAdjHashes parentGraph
return CutExtension
{ _cutExtensionCut' = c
, _cutExtensionParent' = ParentHeader p
, _cutExtensionAdjacentHashes' = as
}
where
p = c ^?! ixg (_chainId cid)
v = _chainwebVersion c
parentHeight = _blockHeight p
targetHeight = parentHeight + 1
parentGraph = chainGraphAt_ p parentHeight
isGraphTransitionPost = isGraphChange c parentHeight
isGraphTransitionCut = isTransitionCut c
newAdjHashes :: ChainGraph -> Maybe (HM.HashMap ChainId BlockHash)
newAdjHashes g =
imapM (\xcid _ -> hashForChain xcid)
converts to ( )
$ adjacentChainIds g p
hashForChain acid
| Just b <- lookupCutM acid c = tryAdj b
| targetHeight == genesisHeight v acid = error $ T.unpack
$ "getAdjacentParents: invalid cut extension, requested parent of a genesis block for chain "
<> sshow acid
<> ". Parent: " <> encodeToText (ObjectEncoded p)
| otherwise = error $ T.unpack
$ "getAdjacentParents: invalid cut, can't find adjacent hash for chain "
<> sshow acid
<> ". Parent: " <> encodeToText (ObjectEncoded p)
tryAdj :: BlockHeader -> Maybe BlockHash
tryAdj b
| _blockHeight b == targetHeight = Just $! _blockParent b
| _blockHeight b == parentHeight = Just $! _blockHash b
| _blockHeight b > targetHeight = error $ T.unpack
$ "getAdjacentParents: detected invalid cut (adjacent parent too far ahead)."
<> " Parent: " <> encodeToText (ObjectEncoded p)
<> " Conflict: " <> encodeToText (ObjectEncoded b)
| _blockHeight b + 1 < parentHeight = error $ T.unpack
$ "getAdjacentParents: detected invalid cut (adjacent parent too far behind)."
<> " Parent: " <> encodeToText (ObjectEncoded p)
<> " Conflict: " <> encodeToText (ObjectEncoded b)
| otherwise = error
$ "Chainweb.Miner.Coordinator.getAdjacentParents: internal code invariant violation"
| A work header has a preliminary creation time and an invalid nonce of 0 .
data WorkHeader = WorkHeader
{ _workHeaderChainId :: !ChainId
, _workHeaderTarget :: !HashTarget
, _workHeaderBytes :: !SB.ShortByteString
^ 286 work bytes .
The last 8 bytes are the nonce
The creation time is encoded in bytes 8 - 15
}
deriving (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
encodeWorkHeader :: WorkHeader -> Put
encodeWorkHeader wh = do
encodeChainId $ _workHeaderChainId wh
encodeHashTarget $ _workHeaderTarget wh
putByteString $ SB.fromShort $ _workHeaderBytes wh
chainweb version this is actually the case .
decodeWorkHeader :: ChainwebVersion -> BlockHeight -> Get WorkHeader
decodeWorkHeader ver h = WorkHeader
<$> decodeChainId
<*> decodeHashTarget
<*> (SB.toShort <$> getByteString (int $ workSizeBytes ver h))
newWorkHeader
:: ChainValueCasLookup hdb BlockHeader
=> hdb
-> CutExtension
-> BlockPayloadHash
-> IO WorkHeader
newWorkHeader hdb e h = do
creationTime <- BlockCreationTime <$> getCurrentTimeIntegral
newWorkHeaderPure (chainLookupM hdb) creationTime e h
newWorkHeaderPure
:: Applicative m
=> (ChainValue BlockHash -> m BlockHeader)
-> BlockCreationTime
-> CutExtension
-> BlockPayloadHash
-> m WorkHeader
newWorkHeaderPure hdb creationTime extension phash = do
createWithParents <$> getAdjacentParentHeaders hdb extension
where
Assemble a candidate ` BlockHeader ` without a specific ` Nonce `
createWithParents parents =
let nh = newBlockHeader parents phash (Nonce 0) creationTime
$! _cutExtensionParent extension
in WorkHeader
{ _workHeaderBytes = SB.toShort $ runPutS $ encodeBlockHeaderWithoutHash nh
, _workHeaderTarget = _blockTarget nh
, _workHeaderChainId = _chainId nh
}
getAdjacentParentHeaders
:: HasCallStack
=> Applicative m
=> (ChainValue BlockHash -> m BlockHeader)
-> CutExtension
-> m (HM.HashMap ChainId ParentHeader)
getAdjacentParentHeaders hdb extension
= itraverse select
. _getBlockHashRecord
$ _cutExtensionAdjacentHashes extension
where
c = _cutExtensionCut extension
select cid h = case c ^? ixg cid of
Just ch -> ParentHeader <$> if _blockHash ch == h
then pure ch
else hdb (ChainValue cid h)
Nothing -> error $ T.unpack
$ "Chainweb.Cut.Create.getAdjacentParentHeaders: inconsistent cut extension detected"
<> ". ChainId: " <> encodeToText cid
<> ". CutHashes: " <> encodeToText (cutToCutHashes Nothing c)
a valid nonce . The binary representation does n't yet contain a Hash .
newtype SolvedWork = SolvedWork BlockHeader
deriving (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
encodeSolvedWork :: SolvedWork -> Put
encodeSolvedWork (SolvedWork hdr) = encodeBlockHeaderWithoutHash hdr
decodeSolvedWork :: Get SolvedWork
decodeSolvedWork = SolvedWork <$> decodeBlockHeaderWithoutHash
data InvalidSolvedHeader = InvalidSolvedHeader BlockHeader T.Text
deriving (Show, Eq, Ord, Generic)
deriving anyclass (NFData)
instance Exception InvalidSolvedHeader
the cut and matches the given payload data . It also checks a few other
The resulting ' CutHashes ' value contains the new header and payload as
extend
:: MonadThrow m
=> Cut
-> PayloadData
-> SolvedWork
-> m (BlockHeader, Maybe CutHashes)
extend c pd s = do
(bh, mc) <- extendCut c (_payloadDataPayloadHash pd) s
return (bh, toCutHashes bh <$> mc)
where
toCutHashes bh c' = cutToCutHashes Nothing c'
& set cutHashesHeaders (HM.singleton (_blockHash bh) bh)
& set cutHashesPayloads (HM.singleton (_blockPayloadHash bh) pd)
extendCut
:: MonadThrow m
=> Cut
-> BlockPayloadHash
-> SolvedWork
-> m (BlockHeader, Maybe Cut)
extendCut c ph (SolvedWork bh) = do
Fail Early : If a ` BlockHeader ` 's injected ( and thus its POW
unless (prop_block_pow bh)
$ throwM $ InvalidSolvedHeader bh "Invalid POW hash"
unless (_blockPayloadHash bh == ph) $ throwM $ InvalidSolvedHeader bh
$ "Invalid payload hash"
<> ". Expected: " <> sshow (_blockPayloadHash bh)
<> ", Got: " <> sshow ph
If the ` BlockHeader ` is already stale and ca n't be appended to the
(bh,) <$> tryMonotonicCutExtension c bh
|
08267c162f02d983c64e2bf3ebd3cf5aff0fe677e533d789dbd502125b7ebfbe | ocamllabs/vscode-ocaml-platform | ppx_tools.ml | open Base
module Dumpast = Dumpast
let get_preprocessed_ast path =
match Ppxlib.Ast_io.read_binary path with
| exception Sys_error s -> Error s
| Ok s -> Ok s
| Error e -> Error e
let get_reparsed_code_from_pp_file ~path =
get_preprocessed_ast path
|> Result.map ~f:(fun source ->
match Ppxlib.Ast_io.get_ast source with
| Impl structure ->
let structure =
Ppxlib_ast.Selected_ast.To_ocaml.copy_structure structure
in
Caml.Format.asprintf "%a" Pprintast.structure structure
| Intf signature ->
let signature =
Ppxlib_ast.Selected_ast.To_ocaml.copy_signature signature
in
Caml.Format.asprintf "%a" Pprintast.signature signature)
| null | https://raw.githubusercontent.com/ocamllabs/vscode-ocaml-platform/a7256e8be0fad29c34bfc9a7015cb2d76802fe29/src/ppx_tools/ppx_tools.ml | ocaml | open Base
module Dumpast = Dumpast
let get_preprocessed_ast path =
match Ppxlib.Ast_io.read_binary path with
| exception Sys_error s -> Error s
| Ok s -> Ok s
| Error e -> Error e
let get_reparsed_code_from_pp_file ~path =
get_preprocessed_ast path
|> Result.map ~f:(fun source ->
match Ppxlib.Ast_io.get_ast source with
| Impl structure ->
let structure =
Ppxlib_ast.Selected_ast.To_ocaml.copy_structure structure
in
Caml.Format.asprintf "%a" Pprintast.structure structure
| Intf signature ->
let signature =
Ppxlib_ast.Selected_ast.To_ocaml.copy_signature signature
in
Caml.Format.asprintf "%a" Pprintast.signature signature)
| |
73de24e35c89048eeffb785a2e1ac72d9569d99380c75e4b2af9358864a07f57 | clojure/core.typed | parse_unparse.clj | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^:skip-wiki clojure.core.typed.checker.jvm.parse-unparse
(:require [clojure.core.typed :as t]
[clojure.core.typed.checker.type-rep :as r]
[clojure.core.typed.checker.type-ctors :as c]
[clojure.core.typed.checker.name-env :as nme-env]
[clojure.core.typed.checker.object-rep :as orep]
[clojure.core.typed.checker.path-rep :as pthrep]
[clojure.core.typed.coerce-utils :as coerce]
[clojure.core.typed.contract-utils :as con]
[clojure.core.typed.errors :as err]
[clojure.core.typed.util-vars :as vs]
[clojure.core.typed.checker.dvar-env :as dvar]
[clojure.core.typed.checker.filter-rep :as f]
[clojure.core.typed.checker.filter-ops :as fl]
[clojure.core.typed.checker.jvm.constant-type :as const]
[clojure.core.typed.checker.free-ops :as free-ops]
[clojure.core.typed.checker.indirect-utils :as indu]
[clojure.core.typed.checker.indirect-ops :as ind]
[clojure.core.typed.current-impl :as impl]
[clojure.core.typed.checker.hset-utils :as hset]
[clojure.set :as set]
[clojure.math.combinatorics :as comb])
(:import (clojure.core.typed.checker.type_rep NotType DifferenceType Intersection Union FnIntersection
DottedPretype Function RClass App TApp
PrimitiveArray DataType Protocol TypeFn Poly PolyDots
Mu HeterogeneousMap
CountRange Name Value Top TypeOf Unchecked TopFunction B F Result AnyValue
KwArgsSeq TCError Extends JSNumber JSBoolean SymbolicClosure
CLJSInteger ArrayCLJS JSNominal JSString TCResult AssocType
GetType HSequential HSet JSUndefined JSNull JSSymbol JSObject
JSObj)
(clojure.core.typed.checker.filter_rep TopFilter BotFilter TypeFilter NotTypeFilter AndFilter OrFilter
ImpFilter NoFilter)
(clojure.core.typed.checker.object_rep NoObject EmptyObject Path)
(clojure.core.typed.checker.path_rep KeyPE CountPE ClassPE KeysPE ValsPE NthPE KeywordPE)
(clojure.lang Cons IPersistentList Symbol IPersistentVector)))
(defonce ^:dynamic *parse-type-in-ns* nil)
(set-validator! #'*parse-type-in-ns* (some-fn nil? symbol? con/namespace?))
(declare unparse-type unparse-filter unparse-filter-set unparse-flow-set unparse-object
unparse-path-elem)
; Types print by unparsing them
(do (defmethod print-method clojure.core.typed.checker.impl_protocols.TCType [s writer]
(print-method (unparse-type s) writer))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCType clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCType java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCType clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.impl_protocols.TCAnyType [s writer]
(print-method (unparse-type s) writer))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCAnyType clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCAnyType java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCAnyType clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.impl_protocols.IFilter [s writer]
(cond
(f/FilterSet? s) (print-method (unparse-filter-set s) writer)
(r/FlowSet? s) (print-method (unparse-flow-set s) writer)
:else (print-method (unparse-filter s) writer)))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IFilter clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IFilter java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IFilter clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.impl_protocols.IRObject [s writer]
(print-method (unparse-object s) writer))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IRObject clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IRObject java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IRObject clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.path_rep.IPathElem [s writer]
(print-method (unparse-path-elem s) writer))
(prefer-method print-method clojure.core.typed.checker.path_rep.IPathElem clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.path_rep.IPathElem java.util.Map)
(prefer-method print-method clojure.core.typed.checker.path_rep.IPathElem clojure.lang.IPersistentMap)
)
(defmacro with-parse-ns [sym & body]
`(binding [*parse-type-in-ns* ~sym]
~@body))
(defn with-parse-ns* [sym f]
{:pre [(symbol? sym)]}
(binding [*parse-type-in-ns* sym]
(f)))
(declare parse-type parse-type* resolve-type-clj resolve-type-cljs)
(defn parse-clj [s]
(impl/with-clojure-impl
(parse-type s)))
(defn parse-cljs [s]
(impl/with-cljs-impl
(parse-type s)))
(defn parse-type [s]
(parse-type* s))
(defmulti parse-type* class)
(defmulti parse-type-list
(fn [[n]]
{:post [((some-fn nil? symbol?) %)]}
(when (symbol? n)
(or (impl/impl-case
:clojure (cond
(special-symbol? n) n
:else (let [r (resolve-type-clj n)]
(when (var? r)
(coerce/var->symbol r))))
:cljs (resolve-type-cljs n))
n))))
(def parsed-free-map? (con/hmap-c? :fname symbol?
:bnd r/Bounds?
:variance r/variance?))
parsing TFn , protocol , RClass binders
(defn ^:private parse-free-with-variance [f]
{:post [(parsed-free-map? %)]}
(if (symbol? f)
{:fname f
:bnd r/no-bounds
:variance :invariant}
(let [[n & {:keys [< > variance] :as opts}] f]
(when (contains? opts :kind)
(err/deprecated-warn "Kind annotation for TFn parameters"))
(when-not (r/variance? variance)
(err/int-error (str "Invalid variance " (pr-str variance) " in free binder: " f)))
{:fname n
:bnd (let [upper-or-nil (when (contains? opts :<)
(parse-type <))
lower-or-nil (when (contains? opts :>)
(parse-type >))]
(c/infer-bounds upper-or-nil lower-or-nil))
:variance variance})))
(defn parse-free-binder-with-variance [binder]
{:post [(every? parsed-free-map? %)]}
(reduce (fn [fs fsyn]
{:pre [(every? parsed-free-map? fs)]
:post [(every? parsed-free-map? %)]}
;(prn "parse-free-binder-with-variance" (map :fname fs))
(conj fs
(free-ops/with-bounded-frees
(zipmap (map (comp r/make-F :fname) fs)
(map :bnd fs))
(parse-free-with-variance fsyn))))
[] binder))
; parsing All binders
;return a vector of [name bnds]
(defn parse-free [f]
{:post [((con/hvector-c? symbol? r/Bounds?) %)]}
(let [validate-sym (fn [s]
(when-not (symbol? s)
(err/int-error (str "Type variable must be a symbol, given: " (pr-str s))))
(when (namespace s)
(err/int-error (str "Type variable must not be namespace qualified: " (pr-str s))))
(when (.contains (name s) ".")
(err/int-error (str "Type variable must not contain dots (.): " (pr-str s))))
(when (#{"true" "nil" "false"} (name s))
(err/int-error (str "Type variable must not be named true, false, or nil: " (pr-str s)))))]
(if (symbol? f)
(do (validate-sym f)
[f r/no-bounds])
(let [[n & {:keys [< >] :as opts}] f]
(validate-sym n)
(when (contains? opts :kind)
(err/deprecated-warn "Kind annotation for TFn parameters"))
(when (:variance opts)
(err/int-error "Variance not supported for variables introduced with All"))
[n (let [upper-or-nil (when (contains? opts :<)
(parse-type <))
lower-or-nil (when (contains? opts :>)
(parse-type >))]
(c/infer-bounds upper-or-nil lower-or-nil))]))))
(defn check-forbidden-rec [rec tbody]
(letfn [(well-formed? [t]
(and (not= rec t)
(if ((some-fn r/Intersection? r/Union?) t)
(every? well-formed? (:types t))
true)))]
(when-not (well-formed? tbody)
(err/int-error (str "Recursive type not allowed here")))))
(defn- Mu*-var []
(let [v (ns-resolve (find-ns 'clojure.core.typed.checker.type-ctors) 'Mu*)]
(assert (var? v) "Mu* unbound")
v))
(defn parse-rec-type [[rec & [[free-symbol :as bnder] type
:as args]]]
(when-not (== 1 (count bnder))
(err/int-error "Rec type requires exactly one entry in binder"))
(when-not (== 2 (count args))
(err/int-error "Wrong arguments to Rec"))
(let [Mu* @(Mu*-var)
_ (when-not (= 1 (count bnder))
(err/int-error "Only one variable allowed: Rec"))
f (r/make-F free-symbol)
body (free-ops/with-frees [f]
(parse-type type))
_ (check-forbidden-rec f body)]
(Mu* (:name f) body)))
( defmethod parse - type - list ' DottedPretype
[ [ _ ] ]
( let [ df ( dvar/*dotted - scope * ) ]
; (assert df bsyn)
( r / DottedPretype1 - maker ( free - ops / with - frees [ df ]
( parse - type psyn ) )
(: name ( dvar/*dotted - scope * ) ) ) ) )
(defn parse-CountRange [[_ & [n u :as args]]]
(when-not (#{1 2} (count args))
(err/int-error "Wrong arguments to CountRange"))
(when-not (integer? n)
(err/int-error "First argument to CountRange must be an integer"))
(when-not (or (#{1} (count args))
(integer? u))
(err/int-error "Second argument to CountRange must be an integer"))
(r/make-CountRange n u))
(defmethod parse-type-list 'CountRange [t] (parse-CountRange t))
(defmethod parse-type-list 'clojure.core.typed/CountRange [t] (parse-CountRange t))
(defmethod parse-type-list 'cljs.core.typed/CountRange [t] (parse-CountRange t))
(declare resolve-type-clj)
(defn uniquify-local [sym]
(get-in vs/*current-expr* [:env :clojure.core.typed.analyzer.common.passes.uniquify/locals-frame-val sym]))
(defmethod parse-type-list 'clojure.core.typed/TypeOf [[_ sym :as t]]
(impl/assert-clojure)
(when-not (= 2 (count t))
(err/int-error (str "Wrong number of arguments to TypeOf (" (count t) ")")))
(when-not (symbol? sym)
(err/int-error "Argument to TypeOf must be a symbol."))
(let [uniquified-local (uniquify-local sym)
vsym (let [r (resolve-type-clj sym)]
(when (var? r)
(coerce/var->symbol r)))]
(if uniquified-local
(let [t (ind/type-of-nofail uniquified-local)]
(when-not t
(err/int-error (str "Could not resolve TypeOf for local " sym)))
t)
(do
(when-not vsym
(err/int-error (str "Could not resolve TypeOf for var " sym)))
(r/-type-of vsym)))))
(defn parse-ExactCount [[_ & [n :as args]]]
(when-not (#{1} (count args))
(err/int-error "Wrong arguments to ExactCount"))
(when-not (integer? n)
(err/int-error "First argument to ExactCount must be an integer"))
(r/make-ExactCountRange n))
(defmethod parse-type-list 'ExactCount [t] (parse-ExactCount t))
(defmethod parse-type-list 'clojure.core.typed/ExactCount [t] (parse-ExactCount t))
(defmethod parse-type-list 'cljs.core.typed/ExactCount [t] (parse-ExactCount t))
(defn- RClass-of-var []
(let [v (ns-resolve (find-ns 'clojure.core.typed.checker.type-ctors) 'RClass-of)]
(assert (var? v) "RClass-of unbound")
v))
(defn predicate-for [on-type]
(let [RClass-of @(RClass-of-var)]
(r/make-FnIntersection
(r/make-Function [r/-any] (impl/impl-case
:clojure (RClass-of Boolean)
:cljs (r/JSBoolean-maker))
:filter (fl/-FS (fl/-filter on-type 0)
(fl/-not-filter on-type 0))))))
(defn parse-Pred [[_ & [t-syn :as args]]]
(when-not (== 1 (count args))
(err/int-error "Wrong arguments to predicate"))
(predicate-for (parse-type t-syn)))
; possibly should be called Pred
(defmethod parse-type-list 'predicate [t]
(err/deprecated-plain-op 'predicate 'Pred)
(parse-Pred t))
(defmethod parse-type-list 'clojure.core.typed/Pred [t] (parse-Pred t))
(defmethod parse-type-list 'cljs.core.typed/Pred [t] (parse-Pred t))
FIXME deprecate
(defmethod parse-type-list 'Not
[[_ tsyn :as all]]
(when-not (= (count all) 2)
(err/int-error (str "Wrong arguments to Not (expected 1): " all)))
(r/NotType-maker (parse-type tsyn)))
(defn parse-Difference [[_ tsyn & dsyns :as all]]
(when-not (<= 3 (count all))
(err/int-error (str "Wrong arguments to Difference (expected at least 2): " all)))
(apply r/-difference (parse-type tsyn) (mapv parse-type dsyns)))
(defmethod parse-type-list 'Difference [t]
(err/deprecated-plain-op 'Difference)
(parse-Difference t))
(defmethod parse-type-list 'clojure.core.typed/Difference [t] (parse-Difference t))
(defmethod parse-type-list 'cljs.core.typed/Difference [t] (parse-Difference t))
(defmethod parse-type-list 'Rec [syn]
(err/deprecated-plain-op 'Rec)
(parse-rec-type syn))
(defmethod parse-type-list 'clojure.core.typed/Rec [syn] (parse-rec-type syn))
(defmethod parse-type-list 'cljs.core.typed/Rec [syn] (parse-rec-type syn))
(defn parse-Assoc [[_ tsyn & entries :as all]]
(when-not (<= 1 (count (next all)))
(err/int-error (str "Wrong arguments to Assoc: " all)))
(let [{ellipsis-pos '...}
(zipmap entries (range))
[entries dentries] (split-at (if ellipsis-pos
(dec ellipsis-pos)
(count entries))
entries)
[drest-type _ drest-bnd] (when ellipsis-pos
dentries)
_ (when-not (-> entries count even?)
(err/int-error (str "Incorrect Assoc syntax: " all " , must have even number of key/val pair.")))
_ (when-not (or (not ellipsis-pos)
(= (count dentries) 3))
(err/int-error (str "Incorrect Assoc syntax: " all " , Dotted rest entry must be 3 entries")))
_ (when-not (or (not ellipsis-pos) (symbol? drest-bnd))
(err/int-error "Dotted bound must be symbol"))]
(r/AssocType-maker (parse-type tsyn)
(doall (->> entries
(map parse-type)
(partition 2)
(map vec)))
(when ellipsis-pos
(let [bnd (dvar/*dotted-scope* drest-bnd)
_ (when-not bnd
(err/int-error (str (pr-str drest-bnd) " is not in scope as a dotted variable")))]
(r/DottedPretype1-maker
(free-ops/with-frees [bnd] ;with dotted bound in scope as free
(parse-type drest-type))
(:name bnd)))))))
(defmethod parse-type-list 'Assoc [t] (parse-Assoc t))
(defmethod parse-type-list 'clojure.core.typed/Assoc [t] (parse-Assoc t))
(defmethod parse-type-list 'cljs.core.typed/Assoc [t] (parse-Assoc t))
(defn parse-Get [[_ tsyn keysyn & not-foundsyn :as all]]
(when-not (#{2 3} (count (next all)))
(err/int-error (str "Wrong arguments to Get: " all)))
(r/-get (parse-type tsyn)
(parse-type keysyn)
:not-found
(when (#{3} (count (next all)))
(parse-type not-foundsyn))))
(defmethod parse-type-list 'Get [t] (parse-Get t))
(defmethod parse-type-list 'clojure.core.typed/Get [t] (parse-Get t))
(defmethod parse-type-list 'cljs.core.typed/Get [t] (parse-Get t))
; convert flattened kw arguments to vectors
(defn normalise-binder [bnds]
(loop [bnds bnds
out []]
(cond
(empty? bnds) out
(vector? (first bnds)) (let [[s & rst] bnds]
(recur rst
(conj out s)))
:else
(let [[sym & rst] bnds
[group rst] (loop [bnds rst
out [sym]]
(if (keyword? (second bnds))
(let [_ (when-not (#{2} (count (take 2 bnds)))
(err/int-error (str "Keyword option " (second bnds)
" has no associated value")))
[k v & rst] bnds]
(recur rst
(conj out k v)))
[bnds out]))]
(recur rst
(conj out group))))))
(defn parse-dotted-binder [bnds]
{:pre [(vector? bnds)]}
(let [frees-with-bnds (reduce (fn [fs fsyn]
{:pre [(vector? fs)]
:post [(every? (con/hvector-c? symbol? r/Bounds?) %)]}
(conj fs
(free-ops/with-bounded-frees (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) fs))
(parse-free fsyn))))
[] (-> bnds pop pop))
dvar (parse-free (-> bnds pop peek))]
[frees-with-bnds dvar]))
(defn parse-normal-binder [bnds]
(let [frees-with-bnds
(reduce (fn [fs fsyn]
{:pre [(vector? fs)]
:post [(every? (con/hvector-c? symbol? r/Bounds?) %)]}
(conj fs
(free-ops/with-bounded-frees (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) fs))
(parse-free fsyn))))
[] bnds)]
[frees-with-bnds nil]))
(defn parse-unknown-binder [bnds]
{:pre [((some-fn nil? vector?) bnds)]}
(when bnds
((if (#{'...} (peek bnds))
parse-dotted-binder
parse-normal-binder)
bnds)))
(defn parse-All-binder [bnds]
{:pre [(vector? bnds)]}
(let [[positional kwargs] (split-with (complement keyword?) bnds)
positional (vec positional)
_ (when-not (even? (count kwargs))
(err/int-error (str "Expected an even number of keyword options to All, given: " (vec kwargs))))
_ (when (seq kwargs)
(when-not (apply distinct? (map first (partition 2 kwargs)))
(err/int-error (str "Gave repeated keyword args to All: " (vec kwargs)))))
{:keys [named] :as kwargs} kwargs
_ (let [unsupported (set/difference (set (keys kwargs)) #{:named})]
(when (seq unsupported)
(err/int-error (str "Unsupported keyword argument(s) to All: " unsupported))))
_ (when (contains? kwargs :named)
(when-not (and (vector? named)
(every? symbol? named))
(err/int-error (str ":named keyword argument to All must be a vector of symbols, given: " (pr-str named)))))
dotted? (= '... (peek positional))
bnds* (if named
(let [positional-no-dotted (if dotted?
(pop (pop positional))
positional)
;; fit :named variables between positional and dotted variable, because
;; PolyDots expects the dotted variable last.
bnds* (vec (concat positional-no-dotted named
(when dotted?
(subvec positional (- (count positional) 2)))))]
bnds*)
positional)
no-dots (if dotted?
(pop bnds*)
bnds*)
_ (when (seq no-dots)
(when-not (apply distinct? no-dots)
(err/int-error (str "Variables bound by All must be unique, given: " no-dots))))
named-map (let [sym-to-pos (into {} (map-indexed #(vector %2 %1)) no-dots)]
(select-keys sym-to-pos named))
TODO
;; update usages of parse-unknown-binder to use parse-All-binder
[frees-with-bnds dvar] ((if dotted?
parse-dotted-binder
parse-normal-binder)
bnds*)]
{:frees-with-bnds frees-with-bnds
:dvar dvar
:named named-map}))
;dispatch on last element of syntax in binder
(defn parse-all-type [bnds type]
(let [_ (assert (vector? bnds))
{:keys [frees-with-bnds dvar named]} (parse-All-binder bnds)
bfs (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) frees-with-bnds))]
(if dvar
(free-ops/with-bounded-frees bfs
(c/PolyDots* (map first (concat frees-with-bnds [dvar]))
(map second (concat frees-with-bnds [dvar]))
(dvar/with-dotted [(r/make-F (first dvar))]
(parse-type type))
:named named))
(free-ops/with-bounded-frees bfs
(c/Poly* (map first frees-with-bnds)
(map second frees-with-bnds)
(parse-type type)
:named named)))))
(defmethod parse-type-list 'Extends
[[_ extends & {:keys [without] :as opts} :as syn]]
(when-not (empty? (set/difference (set (keys opts)) #{:without}))
(err/int-error (str "Invalid options to Extends:" (keys opts))))
(when-not (vector? extends)
(err/int-error (str "Extends takes a vector of types: " (pr-str syn))))
(c/-extends (doall (map parse-type extends))
:without (doall (map parse-type without))))
(defn parse-All [[_All_ bnds syn & more :as all]]
;(prn "All syntax" all)
(when more
(err/int-error (str "Bad All syntax: " all)))
(parse-all-type bnds syn))
(defmethod parse-type-list 'All [t]
(err/deprecated-plain-op 'All)
(parse-All t))
(defmethod parse-type-list 'clojure.core.typed/All [t] (parse-All t))
(defmethod parse-type-list 'cljs.core.typed/All [t] (parse-All t))
(defn parse-union-type [[u & types]]
(c/make-Union (doall (map parse-type types))))
(defmethod parse-type-list 'U [syn]
(err/deprecated-plain-op 'U)
(parse-union-type syn))
(defmethod parse-type-list 'clojure.core.typed/U [syn] (parse-union-type syn))
(defmethod parse-type-list 'cljs.core.typed/U [syn] (parse-union-type syn))
; don't do any simplification of the intersection because some types might
; not be resolved
(defn parse-intersection-type [[i & types]]
(c/make-Intersection (doall (map parse-type types))))
(defmethod parse-type-list 'I [syn]
(err/deprecated-plain-op 'I)
(parse-intersection-type syn))
(defmethod parse-type-list 'clojure.core.typed/I [syn] (parse-intersection-type syn))
(defmethod parse-type-list 'cljs.core.typed/I [syn] (parse-intersection-type syn))
(defn parse-Array
[[_ syn & none]]
(when-not (empty? none)
(err/int-error "Expected 1 argument to Array"))
(let [t (parse-type syn)]
(impl/impl-case
:clojure (let [jtype (if (r/RClass? t)
(r/RClass->Class t)
Object)]
(r/PrimitiveArray-maker jtype t t))
:cljs (r/ArrayCLJS-maker t t))))
(defmethod parse-type-list 'Array [syn] (parse-Array syn))
(defmethod parse-type-list 'cljs.core.typed/Array [syn] (parse-Array syn))
(defn parse-ReadOnlyArray
[[_ osyn & none]]
(when-not (empty? none)
(err/int-error "Expected 1 argument to ReadOnlyArray"))
(let [o (parse-type osyn)]
(impl/impl-case
:clojure (r/PrimitiveArray-maker Object (r/Bottom) o)
:cljs (r/ArrayCLJS-maker (r/Bottom) o))))
(defmethod parse-type-list 'ReadOnlyArray [syn] (parse-ReadOnlyArray syn))
(defmethod parse-type-list 'cljs.core.typed/ReadOnlyArray [syn] (parse-ReadOnlyArray syn))
(defmethod parse-type-list 'Array2
[[_ isyn osyn & none]]
(when-not (empty? none)
(err/int-error "Expected 2 arguments to Array2"))
(let [i (parse-type isyn)
o (parse-type osyn)]
(impl/impl-case
:clojure (r/PrimitiveArray-maker Object i o)
:cljs (r/ArrayCLJS-maker i o))))
(defmethod parse-type-list 'Array3
[[_ jsyn isyn osyn & none]]
(impl/assert-clojure)
(when-not (empty? none)
(err/int-error "Expected 3 arguments to Array3"))
(let [jrclass (c/fully-resolve-type (parse-type jsyn))
_ (when-not (r/RClass? jrclass)
(err/int-error "First argument to Array3 must be a Class"))]
(r/PrimitiveArray-maker (r/RClass->Class jrclass) (parse-type isyn) (parse-type osyn))))
(declare parse-function)
(defn parse-fn-intersection-type [[Fn & types]]
(apply r/make-FnIntersection (mapv parse-function types)))
(defn parse-Fn [[_ & types :as syn]]
(when-not (seq types)
(err/int-error (str "Must pass at least one arity to Fn: " (pr-str syn))))
(when-not (every? vector? types)
(err/int-error (str "Fn accepts vectors, given: " (pr-str syn))))
(parse-fn-intersection-type syn))
(defmethod parse-type-list 'Fn [t]
(err/deprecated-plain-op 'Fn 'IFn)
(parse-Fn t))
(defmethod parse-type-list 'clojure.core.typed/IFn [t] (parse-Fn t))
(defmethod parse-type-list 'cljs.core.typed/IFn [t] (parse-Fn t))
(defn parse-free-binder [[nme & {:keys [variance < > kind] :as opts}]]
(when-not (symbol? nme)
(err/int-error "First entry in free binder should be a name symbol"))
{:nme nme :variance (or variance :invariant)
:bound (r/Bounds-maker
;upper
(when-not kind
(if (contains? opts :<)
(parse-type <)
r/-any))
;lower
(when-not kind
(if (contains? opts :>)
(parse-type >)
r/-nothing))
;kind
(when kind
(parse-type kind)))})
(defn parse-tfn-binder [[nme & opts-flat :as all]]
{:pre [(vector? all)]
:post [((con/hmap-c? :nme symbol? :variance r/variance?
:bound r/Bounds?)
%)]}
(let [_ (when-not (even? (count opts-flat))
(err/int-error (str "Uneven arguments passed to TFn binder: "
(pr-str all))))
{:keys [variance < >]
:or {variance :inferred}
:as opts}
(apply hash-map opts-flat)]
(when-not (symbol? nme)
(err/int-error "Must provide a name symbol to TFn"))
(when (contains? opts :kind)
(err/deprecated-warn "Kind annotation for TFn parameters"))
(when-not (r/variance? variance)
(err/int-error (str "Invalid variance: " (pr-str variance))))
{:nme nme :variance variance
:bound (let [upper-or-nil (when (contains? opts :<)
(parse-type <))
lower-or-nil (when (contains? opts :>)
(parse-type >))]
(c/infer-bounds upper-or-nil lower-or-nil))}))
(defn parse-type-fn
[[_ binder bodysyn :as tfn]]
(when-not (= 3 (count tfn))
(err/int-error (str "Wrong number of arguments to TFn: " (pr-str tfn))))
(when-not (every? vector? binder)
(err/int-error (str "TFn binder should be vector of vectors: " (pr-str tfn))))
(let [; don't scope a free in its own bounds. Should review this decision
free-maps (free-ops/with-free-symbols (map (fn [s]
{:pre [(vector? s)]
:post [(symbol? %)]}
(first s))
binder)
(mapv parse-tfn-binder binder))
bodyt (free-ops/with-bounded-frees (into {}
(map (fn [{:keys [nme bound]}] [(r/make-F nme) bound])
free-maps))
(parse-type bodysyn))
; We check variances lazily in TypeFn-body*. This avoids any weird issues with calculating
; variances with potentially partially defined types.
;vs (free-ops/with-bounded-frees (map (fn [{:keys [nme bound]}] [(r/make-F nme) bound])
; free-maps)
( frees / fv - variances bodyt ) )
;_ (doseq [{:keys [nme variance]} free-maps]
; (when-let [actual-v (vs nme)]
; (when-not (= (vs nme) variance)
; (err/int-error (str "Type variable " nme " appears in " (name actual-v) " position "
; "when declared " (name variance))))))
]
(c/TypeFn* (map :nme free-maps) (map :variance free-maps)
(map :bound free-maps) bodyt
{:meta {:env vs/*current-env*}})))
(defmethod parse-type-list 'TFn [syn]
(err/deprecated-plain-op 'TFn)
(parse-type-fn syn))
(defmethod parse-type-list 'clojure.core.typed/TFn [syn] (parse-type-fn syn))
(defmethod parse-type-list 'cljs.core.typed/TFn [syn] (parse-type-fn syn))
(declare parse-quoted-hvec)
(defmethod parse-type-list 'Seq* [syn]
(err/deprecated-plain-op 'Seq* 'HSeq)
(r/-hseq (mapv parse-type (rest syn))))
(defmethod parse-type-list 'List* [syn]
(err/deprecated-plain-op 'List* 'HList)
(r/HeterogeneousList-maker (mapv parse-type (rest syn))))
(defmethod parse-type-list 'Vector* [syn]
(err/deprecated-plain-op 'Vector* 'HVec)
(parse-quoted-hvec (rest syn)))
;; parse-HVec, parse-HSequential and parse-HSeq have many common patterns
;; so we reuse them
(defn parse-types-with-rest-drest [err-msg]
(fn [syns]
(let [rest? (#{'*} (last syns))
dotted? (#{'...} (-> syns butlast last))
_ (when (and rest? dotted?)
(err/int-error (str err-msg syns)))
{:keys [fixed rest drest]}
(cond
rest?
(let [fixed (mapv parse-type (drop-last 2 syns))
rest (parse-type (-> syns butlast last))]
{:fixed fixed
:rest rest})
dotted?
(let [fixed (mapv parse-type (drop-last 3 syns))
[drest-type _dots_ drest-bnd :as dot-syntax] (take-last 3 syns)
; should never fail, if the logic changes above it's probably
; useful to keep around.
_ (when-not (#{3} (count dot-syntax))
(err/int-error (str "Bad vector syntax: " dot-syntax)))
bnd (dvar/*dotted-scope* drest-bnd)
_ (when-not bnd
(err/int-error (str (pr-str drest-bnd) " is not in scope as a dotted variable")))]
{:fixed fixed
:drest (r/DottedPretype1-maker
(free-ops/with-frees [bnd] ;with dotted bound in scope as free
(parse-type drest-type))
(:name bnd))})
:else {:fixed (mapv parse-type syns)})]
{:fixed fixed
:rest rest
:drest drest})))
(def parse-hvec-types (parse-types-with-rest-drest
"Invalid heterogeneous vector syntax:"))
(def parse-hsequential-types (parse-types-with-rest-drest
"Invalid heterogeneous sequential syntax:"))
(def parse-hseq-types (parse-types-with-rest-drest
"Invalid heterogeneous seq syntax:"))
(def parse-hlist-types (parse-types-with-rest-drest
"Invalid heterogeneous list syntax:"))
(declare parse-object parse-filter-set)
(defn parse-heterogeneous* [parse-h*-types constructor]
(fn [[_ syn & {:keys [filter-sets objects repeat]}]]
(let [{:keys [fixed drest rest]} (parse-h*-types syn)]
(constructor fixed
:filters (when filter-sets
(mapv parse-filter-set filter-sets))
:objects (when objects
(mapv parse-object objects))
:drest drest
:rest rest
:repeat (when (true? repeat)
true)))))
(def parse-HVec (parse-heterogeneous* parse-hvec-types r/-hvec))
(def parse-HSequential (parse-heterogeneous* parse-hsequential-types r/-hsequential))
(def parse-HSeq (parse-heterogeneous* parse-hseq-types r/-hseq))
(def parse-HList (parse-heterogeneous* parse-hseq-types (comp #(assoc % :kind :list)
r/-hsequential)))
(defmethod parse-type-list 'HVec [t] (parse-HVec t))
(defmethod parse-type-list 'clojure.core.typed/HVec [t] (parse-HVec t))
(defmethod parse-type-list 'cljs.core.typed/HVec [t] (parse-HVec t))
(defmethod parse-type-list 'HSequential [t] (parse-HSequential t))
(defmethod parse-type-list 'clojure.core.typed/HSequential [t] (parse-HSequential t))
(defmethod parse-type-list 'cljs.core.typed/HSequential [t] (parse-HSequential t))
(defmethod parse-type-list 'HSeq [t]
(err/deprecated-plain-op 'HSeq)
(parse-HSeq t))
(defmethod parse-type-list 'clojure.core.typed/HSeq [t] (parse-HSeq t))
(defmethod parse-type-list 'cljs.core.typed/HSeq [t] (parse-HSeq t))
;; TODO CLJS HList
(defmethod parse-type-list 'clojure.core.typed/HList [t] (parse-HList t))
(defn parse-HSet [[_ ts & {:keys [complete?] :or {complete? true}} :as args]]
(let [bad (seq (remove hset/valid-fixed? ts))]
(when bad
(err/int-error (str "Bad arguments to HSet: " (pr-str bad))))
(r/-hset (set (map r/-val ts)) :complete? complete?)))
(defmethod parse-type-list 'clojure.core.typed/HSet [t] (parse-HSet t))
(defmethod parse-type-list 'cljs.core.typed/HSet [t] (parse-HSet t))
(defn- syn-to-hmap [mandatory optional absent-keys complete?]
(when mandatory
(when-not (map? mandatory)
(err/int-error (str "Mandatory entries to HMap must be a map: " mandatory))))
(when optional
(when-not (map? optional)
(err/int-error (str "Optional entries to HMap must be a map: " optional))))
(letfn [(mapt [m]
(into {} (for [[k v] m]
[(r/-val k)
(parse-type v)])))]
(let [_ (when-not (every? empty? [(set/intersection (set (keys mandatory))
(set (keys optional)))
(set/intersection (set (keys mandatory))
(set absent-keys))
(set/intersection (set (keys optional))
(set absent-keys))])
(err/int-error (str "HMap options contain duplicate key entries: "
"Mandatory: " (into {} mandatory) ", Optional: " (into {} optional)
", Absent: " (set absent-keys))))
_ (when-not (every? keyword? (keys mandatory)) (err/int-error "HMap's mandatory keys must be keywords"))
mandatory (mapt mandatory)
_ (when-not (every? keyword? (keys optional)) (err/int-error "HMap's optional keys must be keywords"))
optional (mapt optional)
_ (when-not (every? keyword? absent-keys) (err/int-error "HMap's absent keys must be keywords"))
absent-keys (set (map r/-val absent-keys))]
(c/make-HMap :mandatory mandatory :optional optional
:complete? complete? :absent-keys absent-keys))))
(defn parse-quoted-hvec [syn]
(let [{:keys [fixed drest rest]} (parse-hvec-types syn)]
(r/-hvec fixed
:drest drest
:rest rest)))
(defmethod parse-type-list 'quote
[[_ syn]]
(cond
((some-fn number? keyword? symbol? string?) syn) (r/-val syn)
(vector? syn) (parse-quoted-hvec syn)
; quoted map is a partial map with mandatory keys
(map? syn) (syn-to-hmap syn nil nil false)
:else (err/int-error (str "Invalid use of quote: " (pr-str syn)))))
(declare parse-in-ns)
(defn multi-frequencies
"Like frequencies, but only returns frequencies greater
than one"
[coll]
(->> coll
frequencies
(filter (fn [[k freq]]
(when (< 1 freq)
true)))
(into {})))
(defn parse-HMap [[_HMap_ & flat-opts :as all]]
(let [supported-options #{:optional :mandatory :absent-keys :complete?}
support deprecated syntax ( HMap { } ) , which is now ( HMap : mandatory { } )
deprecated-mandatory (when (map? (first flat-opts))
(err/deprecated-warn
"(HMap {}) syntax has changed, use (HMap :mandatory {})")
(first flat-opts))
flat-opts (if deprecated-mandatory
(next flat-opts)
flat-opts)
_ (when-not (even? (count flat-opts))
(err/int-error (str "Uneven keyword arguments to HMap: " (pr-str all))))
flat-keys (->> flat-opts
(partition 2)
(map first))
_ (when-not (every? keyword? flat-keys)
(err/int-error (str "HMap requires keyword arguments, given " (pr-str (first flat-keys))
#_#_" in: " (pr-str all))))
_ (let [kf (->> flat-keys
multi-frequencies
(map first)
seq)]
(when-let [[k] kf]
(err/int-error (str "Repeated keyword argument to HMap: " (pr-str k)))))
{:keys [optional mandatory absent-keys complete?]
:or {complete? false}
:as others} (apply hash-map flat-opts)
_ (when-let [[k] (seq (set/difference (set (keys others)) supported-options))]
(err/int-error (str "Unsupported HMap keyword argument: " (pr-str k))))
_ (when (and deprecated-mandatory mandatory)
(err/int-error (str "Cannot provide both deprecated initial map syntax and :mandatory option to HMap")))
mandatory (or deprecated-mandatory mandatory)]
(syn-to-hmap mandatory optional absent-keys complete?)))
(defmethod parse-type-list 'HMap [t] (parse-HMap t))
(defmethod parse-type-list 'clojure.core.typed/HMap [t] (parse-HMap t))
(defmethod parse-type-list 'cljs.core.typed/HMap [t] (parse-HMap t))
(defn parse-JSObj [[_JSObj_ types :as all]]
(let [_ (when-not (= 2 (count all))
(err/int-error (str "Bad syntax to JSObj: " (pr-str all))))
_ (when-not (every? keyword? (keys types))
(err/int-error (str "JSObj requires keyword keys, given " (pr-str (class (first (remove keyword? (keys types))))))))
parsed-types (zipmap (keys types)
(map parse-type (vals types)))]
(r/JSObj-maker parsed-types)))
(defmethod parse-type-list 'cljs.core.typed/JSObj [t] (parse-JSObj t))
(def ^:private cljs-ns (delay (impl/dynaload 'clojure.core.typed.util-cljs/cljs-ns)))
(defn- parse-in-ns []
{:post [(symbol? %)]}
(or *parse-type-in-ns*
(impl/impl-case
:clojure (ns-name *ns*)
:cljs (@cljs-ns))))
(defn- resolve-type-clj
"Returns a var, class or nil"
[sym]
{:pre [(symbol? sym)]
:post [((some-fn var? class? nil?) %)]}
(impl/assert-clojure)
(let [nsym (parse-in-ns)]
(if-let [ns (find-ns nsym)]
(ns-resolve ns sym)
(err/int-error (str "Cannot find namespace: " sym)))))
(defn- resolve-alias-clj
"Returns a symbol if sym maps to a type alias, otherwise nil"
[sym]
{:pre [(symbol? sym)]
:post [((some-fn symbol? nil?) %)]}
(impl/assert-clojure)
(let [nsym (parse-in-ns)
nsp (some-> (namespace sym) symbol)]
(if-let [ns (find-ns nsym)]
(when-let [qual (if nsp
(some-> (or ((ns-aliases ns) nsp)
(find-ns nsp))
ns-name)
(ns-name ns))]
(let [_ (assert (and (symbol? qual)
(not (namespace qual))))
qsym (symbol (name qual) (name sym))]
(when (contains? (nme-env/name-env) qsym)
qsym)))
(err/int-error (str "Cannot find namespace: " sym)))))
(let [cljs-resolve-var (delay (impl/dynaload 'clojure.core.typed.util-cljs/resolve-var))]
(defn- resolve-type-cljs
"Returns a qualified symbol or nil"
[sym]
{:pre [(symbol? sym)]
:post [((some-fn symbol?
nil?)
%)]}
(impl/assert-cljs)
(let [nsym (parse-in-ns)
res (@cljs-resolve-var nsym sym)]
res)))
(defn parse-RClass [cls-sym params-syn]
(impl/assert-clojure)
(let [RClass-of @(RClass-of-var)
cls (resolve-type-clj cls-sym)
_ (when-not (class? cls) (err/int-error (str (pr-str cls-sym) " cannot be resolved")))
tparams (doall (map parse-type params-syn))]
(RClass-of cls tparams)))
(defn parse-Value [[_Value_ syn :as all]]
(when-not (#{2} (count all))
(err/int-error (str "Incorrect number of arguments to Value, " (count all)
", expected 2: " all)))
(impl/impl-case
:clojure (const/constant-type syn)
:cljs (cond
((some-fn symbol? keyword?) syn)
(r/-val syn)
:else (assert nil "FIXME CLJS parse Value"))))
(defmethod parse-type-list 'Value [t] (parse-Value t))
(defmethod parse-type-list 'clojure.core.typed/Val [t] (parse-Value t))
(defmethod parse-type-list 'clojure.core.typed/Value [t] (parse-Value t))
(defmethod parse-type-list 'cljs.core.typed/Val [t] (parse-Value t))
(defmethod parse-type-list 'cljs.core.typed/Value [t] (parse-Value t))
(defmethod parse-type-list 'KeywordArgs
[[_KeywordArgs_ & {:keys [optional mandatory]}]]
(when-not (= #{}
(set/intersection (set (keys optional))
(set (keys mandatory))))
(err/int-error (str "Optional and mandatory keyword arguments should be disjoint: "
(set/intersection (set (keys optional))
(set (keys mandatory))))))
(let [optional (into {} (for [[k v] optional]
(do (when-not (keyword? k) (err/int-error (str "Keyword argument keys must be keywords: " (pr-str k))))
[(r/-val k) (parse-type v)])))
mandatory (into {} (for [[k v] mandatory]
(do (when-not (keyword? k) (err/int-error (str "Keyword argument keys must be keywords: " (pr-str k))))
[(r/-val k) (parse-type v)])))]
(apply c/Un (apply concat
(for [opts (map #(into {} %) (comb/subsets optional))]
(let [m (merge mandatory opts)
kss (comb/permutations (keys m))]
(for [ks kss]
(r/-hseq (mapcat #(find m %) ks)))))))))
(declare unparse-type deprecated-list)
(defn parse-type-list-default
[[n & args :as syn]]
(if-let [d (deprecated-list syn)]
d
(let [op (parse-type n)]
;(prn "tapp op" op)
(when-not ((some-fn r/Name? r/TypeFn? r/F? r/B? r/Poly?) op)
(err/int-error (str "Invalid operator to type application: " syn)))
(with-meta (r/TApp-maker op (mapv parse-type args))
{:syn syn
:env vs/*current-env*}))))
(defmethod parse-type-list :default
[[n & args :as syn]]
(parse-type-list-default syn))
(defmethod parse-type* Cons [l] (parse-type-list l))
(defmethod parse-type* IPersistentList [l]
(parse-type-list l))
(defmulti parse-type-symbol
(fn [n]
{:pre [(symbol? n)]}
(or (impl/impl-case
:clojure (let [r (resolve-type-clj n)]
(when (var? r)
(coerce/var->symbol r)))
TODO
:cljs (resolve-type-cljs n))
n)))
(defn parse-Any [sym]
(if (-> sym meta ::t/infer)
r/-infer-any
r/-any))
(defmethod parse-type-symbol 'Any [_]
(err/deprecated-plain-op 'Any)
r/-any)
(defmethod parse-type-symbol 'clojure.core.typed/Any [s] (parse-Any s))
(defmethod parse-type-symbol 'cljs.core.typed/Any [s] (parse-Any s))
(defmethod parse-type-symbol 'clojure.core.typed/TCError [t] (r/TCError-maker))
(defmethod parse-type-symbol 'Nothing [_]
(err/deprecated-plain-op 'Nothing)
(r/Bottom))
(defmethod parse-type-symbol 'clojure.core.typed/Nothing [_] (r/Bottom))
(defmethod parse-type-symbol 'cljs.core.typed/Nothing [_] (r/Bottom))
(defmethod parse-type-symbol 'AnyFunction [_] (r/TopFunction-maker))
(defmethod parse-type-symbol 'cljs.core.typed/CLJSInteger [_] (r/CLJSInteger-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSNumber [_] (r/JSNumber-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSBoolean [_] (r/JSBoolean-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSObject [_] (r/JSObject-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSString [_] (r/JSString-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSUndefined [_] (r/JSUndefined-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSNull [_] (r/JSNull-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSSymbol [_] (r/JSSymbol-maker))
(defn clj-primitives-fn []
(let [RClass-of @(RClass-of-var)]
{'byte (RClass-of 'byte)
'short (RClass-of 'short)
'int (RClass-of 'int)
'long (RClass-of 'long)
'float (RClass-of 'float)
'double (RClass-of 'double)
'boolean (RClass-of 'boolean)
'char (RClass-of 'char)
'void r/-nil}))
;[Any -> (U nil Type)]
(defmulti deprecated-clj-symbol identity)
(defmethod deprecated-clj-symbol :default [_] nil)
;[Any -> (U nil Type)]
(defn deprecated-symbol [sym]
{:post [((some-fn nil? r/Type?) %)]}
(impl/impl-case
:clojure (deprecated-clj-symbol sym)
:cljs nil))
;[Any -> (U nil Type)]
(defmulti deprecated-clj-list
(fn [[op]]
(when (symbol? op)
((some-fn
(every-pred
class? coerce/Class->symbol)
(every-pred
var? coerce/var->symbol))
(resolve-type-clj op)))))
(defmethod deprecated-clj-list :default [_] nil)
;[Any -> (U nil Type)]
(defn deprecated-list [lst]
{:post [((some-fn nil? r/Type?) %)]}
(impl/impl-case
:clojure (deprecated-clj-list lst)
:cljs nil))
(defn parse-type-symbol-default
[sym]
(let [primitives (impl/impl-case
:clojure (clj-primitives-fn)
:cljs {})
free (when (symbol? sym)
(free-ops/free-in-scope sym))
rsym (when-not free
(impl/impl-case
:clojure (let [res (when (symbol? sym)
(resolve-type-clj sym))]
(cond
(class? res) (coerce/Class->symbol res)
(var? res) (coerce/var->symbol res)
;; name doesn't resolve, try declared protocol or datatype
;; in the current namespace
:else (let [ns (parse-in-ns)
dprotocol (if (namespace sym)
sym
(symbol (str ns) (str sym)))
ddatatype (if (some #{\.} (str sym))
sym
(symbol (str (munge ns)) (str sym)))
nmesym (resolve-alias-clj sym)]
(cond
nmesym nmesym
(nme-env/declared-protocol? dprotocol) dprotocol
(nme-env/declared-datatype? ddatatype) ddatatype))))
:cljs (when (symbol? sym)
(resolve-type-cljs sym))))
_ (assert ((some-fn symbol? nil?) rsym))]
(cond
free free
(primitives sym) (primitives sym)
rsym ((some-fn deprecated-symbol r/Name-maker) rsym)
:else (let [menv (let [m (meta sym)]
(when ((every-pred :line :column :file) m)
m))]
(binding [vs/*current-env* (or menv vs/*current-env*)]
(err/int-error (str "Cannot resolve type: " (pr-str sym)
"\nHint: Is " (pr-str sym) " in scope?")
{:use-current-env true}))))))
(defmethod parse-type-symbol :default
[sym]
(parse-type-symbol-default sym))
(defmethod parse-type* Symbol [l] (parse-type-symbol l))
(defmethod parse-type* Boolean [v] (if v r/-true r/-false))
(defmethod parse-type* nil [_] r/-nil)
(declare parse-path-elem parse-filter*)
(defn parse-filter [f]
(cond
(= 'tt f) f/-top
(= 'ff f) f/-bot
(= 'no-filter f) f/-no-filter
(not ((some-fn seq? list?) f)) (err/int-error (str "Malformed filter expression: " (pr-str f)))
:else (parse-filter* f)))
(defn parse-object-path [{:keys [id path]}]
(when-not (f/name-ref? id)
(err/int-error (str "Must pass natural number or symbol as id: " (pr-str id))))
(orep/-path (when path (mapv parse-path-elem path)) id))
(defn parse-object [obj]
(case obj
empty orep/-empty
no-object orep/-no-object
(parse-object-path obj)))
(defn parse-filter-set [{:keys [then else] :as fsyn}]
(when-not (map? fsyn)
(err/int-error "Filter set must be a map"))
(let [extra (set/difference (set (keys fsyn)) #{:then :else})]
(when-not (empty? extra)
(err/int-error (str "Invalid filter set option: " (first extra)))))
(fl/-FS (if (contains? fsyn :then)
(parse-filter then)
f/-top)
(if (contains? fsyn :else)
(parse-filter else)
f/-top)))
(defmulti parse-filter*
#(when (coll? %)
(first %)))
(defmethod parse-filter* :default
[syn]
(err/int-error (str "Malformed filter expression: " (pr-str syn))))
(defmethod parse-filter* 'is
[[_ & [tsyn nme psyns :as all]]]
(when-not (#{2 3} (count all))
(err/int-error (str "Wrong number of arguments to is")))
(let [t (parse-type tsyn)
p (when (= 3 (count all))
(mapv parse-path-elem psyns))]
(fl/-filter t nme p)))
(defmethod parse-filter* '!
[[_ & [tsyn nme psyns :as all]]]
(when-not (#{2 3} (count all))
(err/int-error (str "Wrong number of arguments to !")))
(let [t (parse-type tsyn)
p (when (= 3 (count all))
(mapv parse-path-elem psyns))]
(fl/-not-filter t nme p)))
(defmethod parse-filter* '|
[[_ & fsyns]]
(apply fl/-or (mapv parse-filter fsyns)))
(defmethod parse-filter* '&
[[_ & fsyns]]
(apply fl/-and (mapv parse-filter fsyns)))
(defmethod parse-filter* 'when
[[_ & [a c :as args] :as all]]
(when-not (#{2} (count args))
(err/int-error (str "Wrong number of arguments to when: " all)))
(fl/-imp (parse-filter a) (parse-filter c)))
FIXME clean up the magic . eg . handle ( Class foo bar ) as an error
(defmulti parse-path-elem
#(cond
(symbol? %) %
(coll? %) (first %)
:else
(err/int-error (str "Malformed path element: " (pr-str %)))))
(defmethod parse-path-elem :default [syn]
(err/int-error (str "Malformed path element: " (pr-str syn))))
(defmethod parse-path-elem 'Class [_] (pthrep/ClassPE-maker))
(defmethod parse-path-elem 'Count [_] (pthrep/CountPE-maker))
(defmethod parse-path-elem 'Keys [_] (pthrep/KeysPE-maker))
(defmethod parse-path-elem 'Vals [_] (pthrep/ValsPE-maker))
(defmethod parse-path-elem 'Key
[[_ & [ksyn :as all]]]
(when-not (= 1 (count all))
(err/int-error "Wrong arguments to Key"))
(pthrep/-kpe ksyn))
(defmethod parse-path-elem 'Nth
[[_ & [idx :as all]]]
(when-not (= 1 (count all))
(err/int-error "Wrong arguments to Nth"))
(pthrep/NthPE-maker idx))
(defmethod parse-path-elem 'Keyword [_] (pthrep/KeywordPE-maker))
(defn- parse-kw-map [m]
{:post [((con/hash-c? r/Value? r/Type?) %)]}
(into {} (for [[k v] m]
[(r/-val k) (parse-type v)])))
(defn parse-function [f]
{:post [(r/Function? %)]}
(let [is-arrow '#{-> :->}
all-dom (take-while (complement is-arrow) f)
[the-arrow rng & opts-flat :as chk] (drop-while (complement is-arrow) f) ;opts aren't used yet
_ (when ('#{->} the-arrow)
TODO deprecate
)
_ (when-not (<= 2 (count chk))
(err/int-error (str "Incorrect function syntax: " f)))
_ (when-not (even? (count opts-flat))
(err/int-error (str "Incorrect function syntax, must have even number of keyword parameters: " f)))
opts (apply hash-map opts-flat)
{ellipsis-pos '...
asterix-pos '*
kw-asterix-pos :*
ampersand-pos '&
push-rest-pos '<*
push-dot-pos '<...}
(zipmap all-dom (range))
_ (when-not (#{0 1} (count (filter identity [asterix-pos ellipsis-pos ampersand-pos
kw-asterix-pos push-rest-pos])))
(err/int-error "Can only provide one rest argument option: & ... * or <*"))
asterix-pos (or asterix-pos kw-asterix-pos)
_ (when-let [ks (seq (remove #{:filters :object :flow} (keys opts)))]
(err/int-error (str "Invalid function keyword option/s: " ks)))
filters (when-let [[_ fsyn] (find opts :filters)]
(parse-filter-set fsyn))
object (when-let [[_ obj] (find opts :object)]
(parse-object obj))
flow (when-let [[_ obj] (find opts :flow)]
(r/-flow (parse-filter obj)))
fixed-dom (cond
asterix-pos (take (dec asterix-pos) all-dom)
ellipsis-pos (take (dec ellipsis-pos) all-dom)
ampersand-pos (take ampersand-pos all-dom)
push-rest-pos (take (dec push-rest-pos) all-dom)
push-dot-pos (take (dec push-dot-pos) all-dom)
:else all-dom)
rest-type (when asterix-pos
(nth all-dom (dec asterix-pos)))
_ (when-not (or (not asterix-pos)
(= (count all-dom) (inc asterix-pos)))
(err/int-error (str "Trailing syntax after rest parameter: " (pr-str (drop (inc asterix-pos) all-dom)))))
[drest-type _ drest-bnd :as drest-seq] (when ellipsis-pos
(drop (dec ellipsis-pos) all-dom))
_ (when-not (or (not ellipsis-pos) (= 3 (count drest-seq)))
(err/int-error "Dotted rest entry must be 3 entries"))
_ (when-not (or (not ellipsis-pos) (symbol? drest-bnd))
(err/int-error "Dotted bound must be symbol"))
[pdot-type _ pdot-bnd :as pdot-seq] (when push-dot-pos
(drop (dec push-dot-pos) all-dom))
_ (when-not (or (not push-dot-pos) (= 3 (count pdot-seq)))
(err/int-error "push dotted rest entry must be 3 entries"))
_ (when-not (or (not push-dot-pos) (symbol? pdot-bnd))
(err/int-error "push dotted bound must be symbol"))
[& {optional-kws :optional mandatory-kws :mandatory} :as kws-seq]
(let [kwsyn (when ampersand-pos
(drop (inc ampersand-pos) all-dom))]
; support deprecated syntax [& {} -> ] to be equivalent to [& :optional {} -> ]
(if (and kwsyn
(map? (first kwsyn)))
(do (err/deprecated-warn "[& {} -> ] function syntax is deprecated. Use [& :optional {} -> ]")
(cons :optional kwsyn))
kwsyn))
_ (when-not (or (not ampersand-pos) (seq kws-seq))
(err/int-error "Must provide syntax after &"))
prest-type (when push-rest-pos
(nth all-dom (dec push-rest-pos)))
_ (when-not (or (not push-rest-pos)
(= (count all-dom) (inc push-rest-pos)))
(err/int-error (str "Trailing syntax after pust-rest parameter: " (pr-str (drop (inc push-rest-pos) all-dom)))))]
(r/make-Function (mapv parse-type fixed-dom)
(parse-type rng)
:rest
(when asterix-pos
(parse-type rest-type))
:drest
(when ellipsis-pos
(let [bnd (dvar/*dotted-scope* drest-bnd)
_ (when-not bnd
(err/int-error (str (pr-str drest-bnd) " is not in scope as a dotted variable")))]
(r/DottedPretype1-maker
(free-ops/with-frees [bnd] ;with dotted bound in scope as free
(parse-type drest-type))
(:name bnd))))
:prest
(when push-rest-pos
(parse-type prest-type))
:pdot
(when push-dot-pos
(let [bnd (dvar/*dotted-scope* pdot-bnd)
_ (when-not bnd
(err/int-error (str (pr-str pdot-bnd) " is not in scope as a dotted variable")))]
(r/DottedPretype1-maker
(free-ops/with-frees [bnd] ;with dotted bound in scope as free
(parse-type pdot-type))
(:name bnd))))
:filter filters
:object object
:flow flow
:optional-kws (when optional-kws
(parse-kw-map optional-kws))
:mandatory-kws (when mandatory-kws
(parse-kw-map mandatory-kws)))))
(defmethod parse-type* IPersistentVector
[f]
(apply r/make-FnIntersection [(parse-function f)]))
(defmethod parse-type* :default
[k]
(err/int-error (str "Bad type syntax: " (pr-str k)
(when ((some-fn symbol? keyword?) k)
(str "\n\nHint: Value types should be preceded by a quote or wrapped in the Value constructor."
" eg. '" (pr-str k) " or (Value " (pr-str k)")")))))
(indu/add-indirection ind/parse-type parse-type)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Unparse
types are generally agnostic to the current implementation .
;; Special types are unparsed under clojure.core.typed in the :unknown
;; implementation. All other types are verbosely printed under :unknown.
(defonce ^:dynamic *unparse-type-in-ns* nil)
(set-validator! #'*unparse-type-in-ns* (some-fn nil? symbol?))
(defn unparse-in-ns []
{:post [((some-fn nil? symbol?) %)]}
(or *unparse-type-in-ns*
(impl/impl-case
:clojure (ns-name *ns*)
:cljs (@cljs-ns)
:unknown nil)))
(defmacro with-unparse-ns [sym & body]
`(binding [*unparse-type-in-ns* ~sym]
~@body))
(defn alias-in-ns
"Returns an alias for namespace sym in ns, or nil if none."
[nsym ns]
{:pre [(string? nsym)
(con/namespace? ns)]
:post [((some-fn nil? symbol?) %)]}
(impl/assert-clojure)
(some (fn [[alias ans]]
(when (= (str nsym) (str (ns-name ans)))
alias))
(ns-aliases ns)))
(defn core-lang-Class-sym [clsym]
{:pre [(symbol? clsym)]
:post [((some-fn nil? symbol?) %)]}
(when (.startsWith (str clsym) "clojure.lang.")
(symbol (.getSimpleName (Class/forName (str clsym))))))
(defn Class-symbol-intern [clsym ns]
{:pre [(con/namespace? ns)]
:post [((some-fn nil? symbol?) %)]}
(some (fn [[isym cls]]
(when (= (str clsym) (str (coerce/Class->symbol cls)))
isym))
(ns-imports ns)))
(defn var-symbol-intern
"Returns a symbol interned in ns for var symbol, or nil if none.
(var-symbol-intern 'symbol (find-ns 'clojure.core))
;=> 'symbol
(var-symbol-intern 'bar (find-ns 'clojure.core))
;=> nil"
[sym ns]
{:pre [(symbol? sym)
(con/namespace? ns)]
:post [((some-fn nil? symbol?) %)]}
(some (fn [[isym var]]
(when (= (str sym) (str (coerce/var->symbol var)))
isym))
(merge (ns-interns ns)
(ns-refers ns))))
(defn unparse-Name-symbol-in-ns [sym]
{:pre [(symbol? sym)]
:post [(symbol? %)]}
( prn " unparse - Name - symbol - in - ns " )
(if-let [ns (and (not vs/*verbose-types*)
(some-> (unparse-in-ns) find-ns))]
(impl/impl-case
:clojure
(or ; use an import name
(Class-symbol-intern sym ns)
; core.lang classes are special
(core-lang-Class-sym sym)
; use unqualified name if interned
(when (namespace sym)
(or (var-symbol-intern sym ns)
; use aliased ns if not interned, but ns is aliased
(when-let [alias (alias-in-ns (namespace sym) ns)]
(symbol (str alias) (name sym)))))
; otherwise use fully qualified name
sym)
:cljs sym
:unknown sym)
sym))
(declare unparse-type*)
(defn unparse-type [t]
; quick way of giving a Name that the user is familiar with
;(prn "unparse-type" (class t))
(if-let [nsym (-> t meta :source-Name)]
nsym
(unparse-type* t)))
(defmulti unparse-type* class)
(defn unp [t] (prn (unparse-type t)))
(defmethod unparse-type* Top [_] (unparse-Name-symbol-in-ns `t/Any))
TODO qualify vsym in current ns
(defmethod unparse-type* TypeOf [{:keys [vsym] :as t}] (list (unparse-Name-symbol-in-ns `t/TypeOf) vsym))
(defmethod unparse-type* Unchecked [{:keys [vsym] :as t}]
(if vsym
(list 'Unchecked vsym)
'Unchecked))
(defmethod unparse-type* TCError [_] (unparse-Name-symbol-in-ns `t/TCError))
(defmethod unparse-type* Name [{:keys [id]}] (unparse-Name-symbol-in-ns id))
(defmethod unparse-type* AnyValue [_] (unparse-Name-symbol-in-ns `t/AnyValue))
(defmethod unparse-type* DottedPretype
[{:keys [pre-type name]}]
(list 'DottedPretype (unparse-type pre-type) (if (symbol? name)
(-> name r/make-F r/F-original-name)
name)))
(defmethod unparse-type* CountRange [{:keys [lower upper]}]
(cond
(= lower upper) (list (unparse-Name-symbol-in-ns `t/ExactCount)
lower)
:else (list* (unparse-Name-symbol-in-ns `t/CountRange)
lower
(when upper [upper]))))
(defmethod unparse-type* App
[{:keys [rator rands]}]
(list* (unparse-type rator) (mapv unparse-type rands)))
(defmethod unparse-type* TApp
[{:keys [rator rands] :as tapp}]
(cond
;perform substitution if obvious
;(TypeFn? rator) (unparse-type (resolve-tapp tapp))
:else
(list* (unparse-type rator) (mapv unparse-type rands))))
(defmethod unparse-type* Result
[{:keys [t]}]
(unparse-type t))
(defmethod unparse-type* F
[{:keys [] :as f}]
; Note: don't print f here, results in infinite recursion
;(prn (-> f :name) (-> f :name meta))
(r/F-original-name f))
(defmethod unparse-type* PrimitiveArray
[{:keys [jtype input-type output-type]}]
(cond
(and (= input-type output-type)
(= Object jtype))
(list 'Array (unparse-type input-type))
(= Object jtype)
(list 'Array2 (unparse-type input-type) (unparse-type output-type))
:else
(list 'Array3 (coerce/Class->symbol jtype)
(unparse-type input-type) (unparse-type output-type))))
(defmethod unparse-type* B
[{:keys [idx]}]
(list 'B idx))
(defmethod unparse-type* Union
[{types :types :as u}]
(cond
; Prefer the user provided Name for this type. Needs more thinking?
;(-> u meta :from-name) (-> u meta :from-name)
(seq types) (list* (unparse-Name-symbol-in-ns `t/U)
(doall (map unparse-type types)))
:else (unparse-Name-symbol-in-ns `t/Nothing)))
(defmethod unparse-type* FnIntersection
[{types :types}]
(cond
; use vector sugar where appropriate
(and (not vs/*verbose-types*)
(== 1 (count types)))
(unparse-type (first types))
:else
(list* (unparse-Name-symbol-in-ns `t/IFn)
(doall (map unparse-type types)))))
(defmethod unparse-type* Intersection
[{types :types}]
(list* (unparse-Name-symbol-in-ns `t/I)
(doall (map unparse-type types))))
(defmethod unparse-type* DifferenceType
[{:keys [type without]}]
(list* (unparse-Name-symbol-in-ns `t/Difference)
(unparse-type* type)
(doall (map unparse-type without))))
(defmethod unparse-type* NotType
[{:keys [type]}]
(list 'Not (unparse-type type)))
(defmethod unparse-type* TopFunction [_] 'AnyFunction)
(defn- unparse-kw-map [m]
{:pre [((con/hash-c? r/Value? r/Type?) m)]}
(into {} (for [[^Value k v] m]
[(.val k) (unparse-type v)])))
(defn unparse-result [{:keys [t fl o flow] :as rng}]
{:pre [(r/Result? rng)]}
(concat [(unparse-type t)]
(when-not (every? (some-fn f/TopFilter? f/NoFilter?) [(:then fl) (:else fl)])
[:filters (unparse-filter-set fl)])
(when-not ((some-fn orep/NoObject? orep/EmptyObject?) o)
[:object (unparse-object o)])
(when-not ((some-fn f/TopFilter? f/NoFilter?) (:normal flow))
[:flow (unparse-flow-set flow)])))
(defn unparse-bound [name]
{:pre [((some-fn symbol? nat-int?) name)]}
(if (symbol? name)
(-> name r/make-F r/F-original-name)
`(~'B ~name)))
(defmethod unparse-type* SymbolicClosure
[{:keys [fexpr env]}]
(list 'SymbolicClosure))
(defmethod unparse-type* Function
[{:keys [dom rng kws rest drest prest pdot]}]
(vec (concat (doall (map unparse-type dom))
(when rest
[(unparse-type rest) '*])
(when drest
(let [{:keys [pre-type name]} drest]
[(unparse-type pre-type)
'...
(unparse-bound name)]))
(when kws
(let [{:keys [optional mandatory]} kws]
(list* '&
(concat
(when (seq mandatory)
[:mandatory (unparse-kw-map mandatory)])
(when (seq optional)
[:optional (unparse-kw-map optional)])))))
(when prest
[(unparse-type prest) '<*])
(when pdot
(let [{:keys [pre-type name]} pdot]
[(unparse-type pre-type)
'<...
(unparse-bound name)]))
['->]
(unparse-result rng))))
(defn unparse-flow-set [flow]
{:pre [(r/FlowSet? flow)]}
(unparse-filter (r/flow-normal flow)))
(defmethod unparse-type* Protocol
[{:keys [the-var poly?]}]
(let [s (unparse-Name-symbol-in-ns the-var)]
(if poly?
(list* s (mapv unparse-type poly?))
s)))
(defmethod unparse-type* DataType
[{:keys [the-class poly?]}]
(if poly?
(list* (unparse-Name-symbol-in-ns the-class) (mapv unparse-type poly?))
(unparse-Name-symbol-in-ns the-class)))
(defmethod unparse-type* RClass
[{:keys [the-class poly?] :as r}]
(if (empty? poly?)
(unparse-Name-symbol-in-ns the-class)
(list* (unparse-Name-symbol-in-ns the-class) (doall (map unparse-type poly?)))))
(defmethod unparse-type* Mu
[m]
(let [nme (-> (c/Mu-fresh-symbol* m) r/make-F r/F-original-name)
body (c/Mu-body* nme m)]
(list (unparse-Name-symbol-in-ns `t/Rec) [nme] (unparse-type body))))
(defn unparse-poly-bounds-entry [name {:keys [upper-bound lower-bound higher-kind] :as bnds}]
(let [name (-> name r/make-F r/F-original-name)
u (when upper-bound
(unparse-type upper-bound))
l (when lower-bound
(unparse-type lower-bound))
h (when higher-kind
(unparse-type higher-kind))]
(or (when higher-kind
[name :kind h])
(when-not (or (r/Top? upper-bound) (r/Bottom? lower-bound))
[name :< u :> l])
(when-not (r/Top? upper-bound)
[name :< u])
(when-not (r/Bottom? lower-bound)
[name :> l])
name)))
(defn unparse-poly-dotted-bounds-entry [free-name bbnd]
; ignore dotted bound for now, not sure what it means yet.
[(-> free-name r/make-F r/F-original-name) '...])
(defn unparse-poly-binder [dotted? free-names bbnds named]
(let [named-remappings (apply sorted-map (interleave (vals named) (keys named)))
{:keys [fixed-inb named-inb]} (group-by (fn [[i]]
(if (named-remappings i)
:named-inb
:fixed-inb))
(map vector
(range)
free-names
bbnds))
[fixed-inb dotted-inb] (if dotted?
((juxt pop peek) fixed-inb)
[fixed-inb nil])
unp-inb (fn [[_ free-name bbnd]]
(unparse-poly-bounds-entry free-name bbnd))
binder (into (mapv unp-inb fixed-inb)
(concat
(when-let [[_ free-name bbnd] dotted-inb]
(unparse-poly-dotted-bounds-entry free-name bbnd))
(when named-inb
[:named (mapv unp-inb named-inb)])))]
binder))
(defmethod unparse-type* PolyDots
[{:keys [nbound named] :as p}]
(let [free-names (vec (c/PolyDots-fresh-symbols* p))
bbnds (c/PolyDots-bbnds* free-names p)
binder (unparse-poly-binder true free-names bbnds named)
body (c/PolyDots-body* free-names p)]
(list (unparse-Name-symbol-in-ns `t/All) binder (unparse-type body))))
(defmethod unparse-type* Extends
[{:keys [extends without]}]
(list* 'Extends
(mapv unparse-type extends)
(when (seq without)
[:without (mapv unparse-type without)])))
(defmethod unparse-type* Poly
[{:keys [nbound named] :as p}]
(let [free-names (c/Poly-fresh-symbols* p)
;_ (prn "Poly unparse" free-names (map meta free-names))
bbnds (c/Poly-bbnds* free-names p)
binder (unparse-poly-binder false free-names bbnds named)
body (c/Poly-body* free-names p)]
(list (unparse-Name-symbol-in-ns `t/All) binder (unparse-type body))))
( - bounds - entry [ t / Sym Bounds Variance - > Any ] )
(defn unparse-typefn-bounds-entry [name {:keys [upper-bound lower-bound higher-kind]} v]
(let [name (-> name r/make-F r/F-original-name)
u (when upper-bound
(unparse-type upper-bound))
l (when lower-bound
(unparse-type lower-bound))
h (when higher-kind
(unparse-type higher-kind))]
(or (when higher-kind
[name :variance v :kind h])
(when-not (or (r/Top? upper-bound) (r/Bottom? lower-bound))
[name :variance v :< u :> l])
(when-not (r/Top? upper-bound)
[name :variance v :< u])
(when-not (r/Bottom? lower-bound)
[name :variance v :> l])
[name :variance v])))
(defmethod unparse-type* TypeFn
[{:keys [nbound] :as p}]
(let [free-names (c/TypeFn-fresh-symbols* p)
bbnds (c/TypeFn-bbnds* free-names p)
binder (mapv unparse-typefn-bounds-entry free-names bbnds (:variances p))
body (c/TypeFn-body* free-names p)]
(list (unparse-Name-symbol-in-ns `t/TFn) binder (unparse-type body))))
(defmethod unparse-type* Value
[v]
(if ((some-fn r/Nil? r/True? r/False?) v)
(:val v)
(list (unparse-Name-symbol-in-ns `t/Val) (:val v))))
(defn- unparse-map-of-types [m]
(into {} (map (fn [[k v]]
(assert (r/Value? k) k)
(vector (:val k) (unparse-type v)))
m)))
(defmethod unparse-type* HeterogeneousMap
[^HeterogeneousMap v]
(list* (unparse-Name-symbol-in-ns `t/HMap)
(concat
; only elide if other information is present
(when (or (seq (:types v))
(not (or (seq (:optional v))
(seq (:absent-keys v))
(c/complete-hmap? v))))
[:mandatory (unparse-map-of-types (.types v))])
(when (seq (:optional v))
[:optional (unparse-map-of-types (:optional v))])
(when-let [ks (and (not (c/complete-hmap? v))
(seq (.absent-keys v)))]
[:absent-keys (set (map :val ks))])
(when (c/complete-hmap? v)
[:complete? true]))))
(defn unparse-heterogeneous* [sym {:keys [types rest drest fs objects repeat] :as v}]
(let [first-part (concat
(map unparse-type (:types v))
(when rest [(unparse-type rest) '*])
(when drest [(unparse-type (:pre-type drest))
'...
(unparse-bound (:name drest))]))]
(list* sym
(vec first-part)
(concat
(when repeat
[:repeat true])
(when-not (every? #{(fl/-FS f/-top f/-top)} fs)
[:filter-sets (mapv unparse-filter-set fs)])
(when-not (every? #{orep/-empty} objects)
[:objects (mapv unparse-object objects)])))))
(defmethod unparse-type* HSequential [v]
(unparse-heterogeneous*
(case (:kind v)
:list (unparse-Name-symbol-in-ns `t/HList)
:vector (unparse-Name-symbol-in-ns `t/HVec)
:seq (unparse-Name-symbol-in-ns `t/HSeq)
:sequential (unparse-Name-symbol-in-ns `t/HSequential))
v))
(defmethod unparse-type* HSet
[{:keys [fixed] :as v}]
{:pre [(every? r/Value? fixed)]}
(list (unparse-Name-symbol-in-ns `t/HSet) (set (map :val fixed))))
(defmethod unparse-type* KwArgsSeq
[^KwArgsSeq v]
(list* 'KwArgsSeq
(concat
(when (seq (.optional v))
[:optional (unparse-map-of-types (.optional v))])
(when (seq (.mandatory v))
[:mandatory (unparse-map-of-types (.mandatory v))])
(when (:complete? v)
[:complete? (:complete? v)])
(when (:nilable-non-empty? v)
[:nilable-non-empty? (:nilable-non-empty? v)]))))
(defmethod unparse-type* AssocType
[{:keys [target entries dentries]}]
(list* (unparse-Name-symbol-in-ns `t/Assoc)
(unparse-type target)
(concat
(doall (map unparse-type (apply concat entries)))
(when dentries [(unparse-type (:pre-type dentries))
'...
(unparse-bound (:name dentries))]))))
(defmethod unparse-type* GetType
[{:keys [target key not-found]}]
(list* (unparse-Name-symbol-in-ns `t/Get)
(unparse-type target)
(unparse-type key)
(when (not= r/-nil not-found)
[(unparse-type not-found)])))
; CLJS Types
(defmethod unparse-type* JSNumber [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSNumber))
(defmethod unparse-type* JSBoolean [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSBoolean))
(defmethod unparse-type* JSObject [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSObject))
(defmethod unparse-type* CLJSInteger [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/CLJSInteger))
(defmethod unparse-type* JSString [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSString))
(defmethod unparse-type* JSSymbol [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSSymbol))
(defmethod unparse-type* JSUndefined [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSUndefined))
(defmethod unparse-type* JSNull [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSNull))
(defmethod unparse-type* JSObj [t] (list (unparse-Name-symbol-in-ns 'cljs.core.typed/JSObj)
(zipmap (keys (:types t))
(map unparse-type (vals (:types t))))))
(defmethod unparse-type* ArrayCLJS
[{:keys [input-type output-type]}]
(cond
(= input-type output-type) (list 'Array (unparse-type input-type))
:else (list 'Array2 (unparse-type input-type) (unparse-type output-type))))
(defmethod unparse-type* JSNominal
[{:keys [name poly?]}]
(let [sym (symbol name)]
(if (seq poly?)
(list* sym (map unparse-type poly?))
sym)))
; Objects
(declare unparse-path-elem)
(defmulti unparse-object class)
(defmethod unparse-object EmptyObject [_] 'empty)
(defmethod unparse-object NoObject [_] 'no-object)
(defmethod unparse-object Path [{:keys [path id]}] (conj {:id id} (when (seq path) [:path (mapv unparse-path-elem path)])))
; Path elems
(defmulti unparse-path-elem class)
(defmethod unparse-path-elem KeyPE [t] (list 'Key (:val t)))
(defmethod unparse-path-elem CountPE [t] 'Count)
(defmethod unparse-path-elem ClassPE [t] 'Class)
(defmethod unparse-path-elem NthPE [t] (list 'Nth (:idx t)))
(defmethod unparse-path-elem KeysPE [t] 'Keys)
(defmethod unparse-path-elem ValsPE [t] 'Vals)
(defmethod unparse-path-elem KeywordPE [t] 'Keyword)
; Filters
(defmulti unparse-filter* class)
(declare unparse-filter)
(defn unparse-filter-set [{:keys [then else] :as fs}]
{:pre [(f/FilterSet? fs)]}
{:then (unparse-filter then)
:else (unparse-filter else)})
(defn unparse-filter [f]
(unparse-filter* f))
(defmethod unparse-filter* TopFilter [f] 'tt)
(defmethod unparse-filter* BotFilter [f] 'ff)
(defmethod unparse-filter* NoFilter [f] 'no-filter)
(declare unparse-type)
(defmethod unparse-filter* TypeFilter
[{:keys [type path id]}]
(concat (list 'is (unparse-type type) id)
(when (seq path)
[(mapv unparse-path-elem path)])))
(defmethod unparse-filter* NotTypeFilter
[{:keys [type path id]}]
(concat (list '! (unparse-type type) id)
(when (seq path)
[(mapv unparse-path-elem path)])))
(defmethod unparse-filter* AndFilter [{:keys [fs]}] (apply list '& (map unparse-filter fs)))
(defmethod unparse-filter* OrFilter [{:keys [fs]}] (apply list '| (map unparse-filter fs)))
(defmethod unparse-filter* ImpFilter
[{:keys [a c]}]
(list 'when (unparse-filter a) (unparse-filter c)))
;[TCResult -> Any]
(defn unparse-TCResult [r]
(let [t (unparse-type (r/ret-t r))
fs (unparse-filter-set (r/ret-f r))
o (unparse-object (r/ret-o r))]
(if (and (= (fl/-FS f/-top f/-top) (r/ret-f r))
(= (r/ret-o r) orep/-empty))
t
(if (= (r/ret-o r) orep/-empty)
[t fs]
[t fs o]))))
(defn unparse-TCResult-in-ns [r ns]
{:pre [((some-fn con/namespace? symbol?) ns)]}
(binding [*unparse-type-in-ns* (if (symbol? ns)
ns
(ns-name ns))]
(unparse-TCResult r)))
(defmethod unparse-type* TCResult
[v]
(unparse-TCResult v))
(indu/add-indirection ind/unparse-type unparse-type)
| null | https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/jvm/parse_unparse.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
Types print by unparsing them
(prn "parse-free-binder-with-variance" (map :fname fs))
parsing All binders
return a vector of [name bnds]
(assert df bsyn)
possibly should be called Pred
with dotted bound in scope as free
convert flattened kw arguments to vectors
fit :named variables between positional and dotted variable, because
PolyDots expects the dotted variable last.
update usages of parse-unknown-binder to use parse-All-binder
dispatch on last element of syntax in binder
(prn "All syntax" all)
don't do any simplification of the intersection because some types might
not be resolved
upper
lower
kind
don't scope a free in its own bounds. Should review this decision
We check variances lazily in TypeFn-body*. This avoids any weird issues with calculating
variances with potentially partially defined types.
vs (free-ops/with-bounded-frees (map (fn [{:keys [nme bound]}] [(r/make-F nme) bound])
free-maps)
_ (doseq [{:keys [nme variance]} free-maps]
(when-let [actual-v (vs nme)]
(when-not (= (vs nme) variance)
(err/int-error (str "Type variable " nme " appears in " (name actual-v) " position "
"when declared " (name variance))))))
parse-HVec, parse-HSequential and parse-HSeq have many common patterns
so we reuse them
should never fail, if the logic changes above it's probably
useful to keep around.
with dotted bound in scope as free
TODO CLJS HList
quoted map is a partial map with mandatory keys
(prn "tapp op" op)
[Any -> (U nil Type)]
[Any -> (U nil Type)]
[Any -> (U nil Type)]
[Any -> (U nil Type)]
name doesn't resolve, try declared protocol or datatype
in the current namespace
opts aren't used yet
support deprecated syntax [& {} -> ] to be equivalent to [& :optional {} -> ]
with dotted bound in scope as free
with dotted bound in scope as free
Special types are unparsed under clojure.core.typed in the :unknown
implementation. All other types are verbosely printed under :unknown.
=> 'symbol
=> nil"
use an import name
core.lang classes are special
use unqualified name if interned
use aliased ns if not interned, but ns is aliased
otherwise use fully qualified name
quick way of giving a Name that the user is familiar with
(prn "unparse-type" (class t))
perform substitution if obvious
(TypeFn? rator) (unparse-type (resolve-tapp tapp))
Note: don't print f here, results in infinite recursion
(prn (-> f :name) (-> f :name meta))
Prefer the user provided Name for this type. Needs more thinking?
(-> u meta :from-name) (-> u meta :from-name)
use vector sugar where appropriate
ignore dotted bound for now, not sure what it means yet.
_ (prn "Poly unparse" free-names (map meta free-names))
only elide if other information is present
CLJS Types
Objects
Path elems
Filters
[TCResult -> Any] | Copyright ( c ) , contributors .
(ns ^:skip-wiki clojure.core.typed.checker.jvm.parse-unparse
(:require [clojure.core.typed :as t]
[clojure.core.typed.checker.type-rep :as r]
[clojure.core.typed.checker.type-ctors :as c]
[clojure.core.typed.checker.name-env :as nme-env]
[clojure.core.typed.checker.object-rep :as orep]
[clojure.core.typed.checker.path-rep :as pthrep]
[clojure.core.typed.coerce-utils :as coerce]
[clojure.core.typed.contract-utils :as con]
[clojure.core.typed.errors :as err]
[clojure.core.typed.util-vars :as vs]
[clojure.core.typed.checker.dvar-env :as dvar]
[clojure.core.typed.checker.filter-rep :as f]
[clojure.core.typed.checker.filter-ops :as fl]
[clojure.core.typed.checker.jvm.constant-type :as const]
[clojure.core.typed.checker.free-ops :as free-ops]
[clojure.core.typed.checker.indirect-utils :as indu]
[clojure.core.typed.checker.indirect-ops :as ind]
[clojure.core.typed.current-impl :as impl]
[clojure.core.typed.checker.hset-utils :as hset]
[clojure.set :as set]
[clojure.math.combinatorics :as comb])
(:import (clojure.core.typed.checker.type_rep NotType DifferenceType Intersection Union FnIntersection
DottedPretype Function RClass App TApp
PrimitiveArray DataType Protocol TypeFn Poly PolyDots
Mu HeterogeneousMap
CountRange Name Value Top TypeOf Unchecked TopFunction B F Result AnyValue
KwArgsSeq TCError Extends JSNumber JSBoolean SymbolicClosure
CLJSInteger ArrayCLJS JSNominal JSString TCResult AssocType
GetType HSequential HSet JSUndefined JSNull JSSymbol JSObject
JSObj)
(clojure.core.typed.checker.filter_rep TopFilter BotFilter TypeFilter NotTypeFilter AndFilter OrFilter
ImpFilter NoFilter)
(clojure.core.typed.checker.object_rep NoObject EmptyObject Path)
(clojure.core.typed.checker.path_rep KeyPE CountPE ClassPE KeysPE ValsPE NthPE KeywordPE)
(clojure.lang Cons IPersistentList Symbol IPersistentVector)))
(defonce ^:dynamic *parse-type-in-ns* nil)
(set-validator! #'*parse-type-in-ns* (some-fn nil? symbol? con/namespace?))
(declare unparse-type unparse-filter unparse-filter-set unparse-flow-set unparse-object
unparse-path-elem)
(do (defmethod print-method clojure.core.typed.checker.impl_protocols.TCType [s writer]
(print-method (unparse-type s) writer))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCType clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCType java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCType clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.impl_protocols.TCAnyType [s writer]
(print-method (unparse-type s) writer))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCAnyType clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCAnyType java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.TCAnyType clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.impl_protocols.IFilter [s writer]
(cond
(f/FilterSet? s) (print-method (unparse-filter-set s) writer)
(r/FlowSet? s) (print-method (unparse-flow-set s) writer)
:else (print-method (unparse-filter s) writer)))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IFilter clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IFilter java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IFilter clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.impl_protocols.IRObject [s writer]
(print-method (unparse-object s) writer))
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IRObject clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IRObject java.util.Map)
(prefer-method print-method clojure.core.typed.checker.impl_protocols.IRObject clojure.lang.IPersistentMap)
(defmethod print-method clojure.core.typed.checker.path_rep.IPathElem [s writer]
(print-method (unparse-path-elem s) writer))
(prefer-method print-method clojure.core.typed.checker.path_rep.IPathElem clojure.lang.IRecord)
(prefer-method print-method clojure.core.typed.checker.path_rep.IPathElem java.util.Map)
(prefer-method print-method clojure.core.typed.checker.path_rep.IPathElem clojure.lang.IPersistentMap)
)
(defmacro with-parse-ns [sym & body]
`(binding [*parse-type-in-ns* ~sym]
~@body))
(defn with-parse-ns* [sym f]
{:pre [(symbol? sym)]}
(binding [*parse-type-in-ns* sym]
(f)))
(declare parse-type parse-type* resolve-type-clj resolve-type-cljs)
(defn parse-clj [s]
(impl/with-clojure-impl
(parse-type s)))
(defn parse-cljs [s]
(impl/with-cljs-impl
(parse-type s)))
(defn parse-type [s]
(parse-type* s))
(defmulti parse-type* class)
(defmulti parse-type-list
(fn [[n]]
{:post [((some-fn nil? symbol?) %)]}
(when (symbol? n)
(or (impl/impl-case
:clojure (cond
(special-symbol? n) n
:else (let [r (resolve-type-clj n)]
(when (var? r)
(coerce/var->symbol r))))
:cljs (resolve-type-cljs n))
n))))
(def parsed-free-map? (con/hmap-c? :fname symbol?
:bnd r/Bounds?
:variance r/variance?))
parsing TFn , protocol , RClass binders
(defn ^:private parse-free-with-variance [f]
{:post [(parsed-free-map? %)]}
(if (symbol? f)
{:fname f
:bnd r/no-bounds
:variance :invariant}
(let [[n & {:keys [< > variance] :as opts}] f]
(when (contains? opts :kind)
(err/deprecated-warn "Kind annotation for TFn parameters"))
(when-not (r/variance? variance)
(err/int-error (str "Invalid variance " (pr-str variance) " in free binder: " f)))
{:fname n
:bnd (let [upper-or-nil (when (contains? opts :<)
(parse-type <))
lower-or-nil (when (contains? opts :>)
(parse-type >))]
(c/infer-bounds upper-or-nil lower-or-nil))
:variance variance})))
(defn parse-free-binder-with-variance [binder]
{:post [(every? parsed-free-map? %)]}
(reduce (fn [fs fsyn]
{:pre [(every? parsed-free-map? fs)]
:post [(every? parsed-free-map? %)]}
(conj fs
(free-ops/with-bounded-frees
(zipmap (map (comp r/make-F :fname) fs)
(map :bnd fs))
(parse-free-with-variance fsyn))))
[] binder))
(defn parse-free [f]
{:post [((con/hvector-c? symbol? r/Bounds?) %)]}
(let [validate-sym (fn [s]
(when-not (symbol? s)
(err/int-error (str "Type variable must be a symbol, given: " (pr-str s))))
(when (namespace s)
(err/int-error (str "Type variable must not be namespace qualified: " (pr-str s))))
(when (.contains (name s) ".")
(err/int-error (str "Type variable must not contain dots (.): " (pr-str s))))
(when (#{"true" "nil" "false"} (name s))
(err/int-error (str "Type variable must not be named true, false, or nil: " (pr-str s)))))]
(if (symbol? f)
(do (validate-sym f)
[f r/no-bounds])
(let [[n & {:keys [< >] :as opts}] f]
(validate-sym n)
(when (contains? opts :kind)
(err/deprecated-warn "Kind annotation for TFn parameters"))
(when (:variance opts)
(err/int-error "Variance not supported for variables introduced with All"))
[n (let [upper-or-nil (when (contains? opts :<)
(parse-type <))
lower-or-nil (when (contains? opts :>)
(parse-type >))]
(c/infer-bounds upper-or-nil lower-or-nil))]))))
(defn check-forbidden-rec [rec tbody]
(letfn [(well-formed? [t]
(and (not= rec t)
(if ((some-fn r/Intersection? r/Union?) t)
(every? well-formed? (:types t))
true)))]
(when-not (well-formed? tbody)
(err/int-error (str "Recursive type not allowed here")))))
(defn- Mu*-var []
(let [v (ns-resolve (find-ns 'clojure.core.typed.checker.type-ctors) 'Mu*)]
(assert (var? v) "Mu* unbound")
v))
(defn parse-rec-type [[rec & [[free-symbol :as bnder] type
:as args]]]
(when-not (== 1 (count bnder))
(err/int-error "Rec type requires exactly one entry in binder"))
(when-not (== 2 (count args))
(err/int-error "Wrong arguments to Rec"))
(let [Mu* @(Mu*-var)
_ (when-not (= 1 (count bnder))
(err/int-error "Only one variable allowed: Rec"))
f (r/make-F free-symbol)
body (free-ops/with-frees [f]
(parse-type type))
_ (check-forbidden-rec f body)]
(Mu* (:name f) body)))
( defmethod parse - type - list ' DottedPretype
[ [ _ ] ]
( let [ df ( dvar/*dotted - scope * ) ]
( r / DottedPretype1 - maker ( free - ops / with - frees [ df ]
( parse - type psyn ) )
(: name ( dvar/*dotted - scope * ) ) ) ) )
(defn parse-CountRange [[_ & [n u :as args]]]
(when-not (#{1 2} (count args))
(err/int-error "Wrong arguments to CountRange"))
(when-not (integer? n)
(err/int-error "First argument to CountRange must be an integer"))
(when-not (or (#{1} (count args))
(integer? u))
(err/int-error "Second argument to CountRange must be an integer"))
(r/make-CountRange n u))
(defmethod parse-type-list 'CountRange [t] (parse-CountRange t))
(defmethod parse-type-list 'clojure.core.typed/CountRange [t] (parse-CountRange t))
(defmethod parse-type-list 'cljs.core.typed/CountRange [t] (parse-CountRange t))
(declare resolve-type-clj)
(defn uniquify-local [sym]
(get-in vs/*current-expr* [:env :clojure.core.typed.analyzer.common.passes.uniquify/locals-frame-val sym]))
(defmethod parse-type-list 'clojure.core.typed/TypeOf [[_ sym :as t]]
(impl/assert-clojure)
(when-not (= 2 (count t))
(err/int-error (str "Wrong number of arguments to TypeOf (" (count t) ")")))
(when-not (symbol? sym)
(err/int-error "Argument to TypeOf must be a symbol."))
(let [uniquified-local (uniquify-local sym)
vsym (let [r (resolve-type-clj sym)]
(when (var? r)
(coerce/var->symbol r)))]
(if uniquified-local
(let [t (ind/type-of-nofail uniquified-local)]
(when-not t
(err/int-error (str "Could not resolve TypeOf for local " sym)))
t)
(do
(when-not vsym
(err/int-error (str "Could not resolve TypeOf for var " sym)))
(r/-type-of vsym)))))
(defn parse-ExactCount [[_ & [n :as args]]]
(when-not (#{1} (count args))
(err/int-error "Wrong arguments to ExactCount"))
(when-not (integer? n)
(err/int-error "First argument to ExactCount must be an integer"))
(r/make-ExactCountRange n))
(defmethod parse-type-list 'ExactCount [t] (parse-ExactCount t))
(defmethod parse-type-list 'clojure.core.typed/ExactCount [t] (parse-ExactCount t))
(defmethod parse-type-list 'cljs.core.typed/ExactCount [t] (parse-ExactCount t))
(defn- RClass-of-var []
(let [v (ns-resolve (find-ns 'clojure.core.typed.checker.type-ctors) 'RClass-of)]
(assert (var? v) "RClass-of unbound")
v))
(defn predicate-for [on-type]
(let [RClass-of @(RClass-of-var)]
(r/make-FnIntersection
(r/make-Function [r/-any] (impl/impl-case
:clojure (RClass-of Boolean)
:cljs (r/JSBoolean-maker))
:filter (fl/-FS (fl/-filter on-type 0)
(fl/-not-filter on-type 0))))))
(defn parse-Pred [[_ & [t-syn :as args]]]
(when-not (== 1 (count args))
(err/int-error "Wrong arguments to predicate"))
(predicate-for (parse-type t-syn)))
(defmethod parse-type-list 'predicate [t]
(err/deprecated-plain-op 'predicate 'Pred)
(parse-Pred t))
(defmethod parse-type-list 'clojure.core.typed/Pred [t] (parse-Pred t))
(defmethod parse-type-list 'cljs.core.typed/Pred [t] (parse-Pred t))
FIXME deprecate
(defmethod parse-type-list 'Not
[[_ tsyn :as all]]
(when-not (= (count all) 2)
(err/int-error (str "Wrong arguments to Not (expected 1): " all)))
(r/NotType-maker (parse-type tsyn)))
(defn parse-Difference [[_ tsyn & dsyns :as all]]
(when-not (<= 3 (count all))
(err/int-error (str "Wrong arguments to Difference (expected at least 2): " all)))
(apply r/-difference (parse-type tsyn) (mapv parse-type dsyns)))
(defmethod parse-type-list 'Difference [t]
(err/deprecated-plain-op 'Difference)
(parse-Difference t))
(defmethod parse-type-list 'clojure.core.typed/Difference [t] (parse-Difference t))
(defmethod parse-type-list 'cljs.core.typed/Difference [t] (parse-Difference t))
(defmethod parse-type-list 'Rec [syn]
(err/deprecated-plain-op 'Rec)
(parse-rec-type syn))
(defmethod parse-type-list 'clojure.core.typed/Rec [syn] (parse-rec-type syn))
(defmethod parse-type-list 'cljs.core.typed/Rec [syn] (parse-rec-type syn))
(defn parse-Assoc [[_ tsyn & entries :as all]]
(when-not (<= 1 (count (next all)))
(err/int-error (str "Wrong arguments to Assoc: " all)))
(let [{ellipsis-pos '...}
(zipmap entries (range))
[entries dentries] (split-at (if ellipsis-pos
(dec ellipsis-pos)
(count entries))
entries)
[drest-type _ drest-bnd] (when ellipsis-pos
dentries)
_ (when-not (-> entries count even?)
(err/int-error (str "Incorrect Assoc syntax: " all " , must have even number of key/val pair.")))
_ (when-not (or (not ellipsis-pos)
(= (count dentries) 3))
(err/int-error (str "Incorrect Assoc syntax: " all " , Dotted rest entry must be 3 entries")))
_ (when-not (or (not ellipsis-pos) (symbol? drest-bnd))
(err/int-error "Dotted bound must be symbol"))]
(r/AssocType-maker (parse-type tsyn)
(doall (->> entries
(map parse-type)
(partition 2)
(map vec)))
(when ellipsis-pos
(let [bnd (dvar/*dotted-scope* drest-bnd)
_ (when-not bnd
(err/int-error (str (pr-str drest-bnd) " is not in scope as a dotted variable")))]
(r/DottedPretype1-maker
(parse-type drest-type))
(:name bnd)))))))
(defmethod parse-type-list 'Assoc [t] (parse-Assoc t))
(defmethod parse-type-list 'clojure.core.typed/Assoc [t] (parse-Assoc t))
(defmethod parse-type-list 'cljs.core.typed/Assoc [t] (parse-Assoc t))
(defn parse-Get [[_ tsyn keysyn & not-foundsyn :as all]]
(when-not (#{2 3} (count (next all)))
(err/int-error (str "Wrong arguments to Get: " all)))
(r/-get (parse-type tsyn)
(parse-type keysyn)
:not-found
(when (#{3} (count (next all)))
(parse-type not-foundsyn))))
(defmethod parse-type-list 'Get [t] (parse-Get t))
(defmethod parse-type-list 'clojure.core.typed/Get [t] (parse-Get t))
(defmethod parse-type-list 'cljs.core.typed/Get [t] (parse-Get t))
(defn normalise-binder [bnds]
(loop [bnds bnds
out []]
(cond
(empty? bnds) out
(vector? (first bnds)) (let [[s & rst] bnds]
(recur rst
(conj out s)))
:else
(let [[sym & rst] bnds
[group rst] (loop [bnds rst
out [sym]]
(if (keyword? (second bnds))
(let [_ (when-not (#{2} (count (take 2 bnds)))
(err/int-error (str "Keyword option " (second bnds)
" has no associated value")))
[k v & rst] bnds]
(recur rst
(conj out k v)))
[bnds out]))]
(recur rst
(conj out group))))))
(defn parse-dotted-binder [bnds]
{:pre [(vector? bnds)]}
(let [frees-with-bnds (reduce (fn [fs fsyn]
{:pre [(vector? fs)]
:post [(every? (con/hvector-c? symbol? r/Bounds?) %)]}
(conj fs
(free-ops/with-bounded-frees (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) fs))
(parse-free fsyn))))
[] (-> bnds pop pop))
dvar (parse-free (-> bnds pop peek))]
[frees-with-bnds dvar]))
(defn parse-normal-binder [bnds]
(let [frees-with-bnds
(reduce (fn [fs fsyn]
{:pre [(vector? fs)]
:post [(every? (con/hvector-c? symbol? r/Bounds?) %)]}
(conj fs
(free-ops/with-bounded-frees (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) fs))
(parse-free fsyn))))
[] bnds)]
[frees-with-bnds nil]))
(defn parse-unknown-binder [bnds]
{:pre [((some-fn nil? vector?) bnds)]}
(when bnds
((if (#{'...} (peek bnds))
parse-dotted-binder
parse-normal-binder)
bnds)))
(defn parse-All-binder [bnds]
{:pre [(vector? bnds)]}
(let [[positional kwargs] (split-with (complement keyword?) bnds)
positional (vec positional)
_ (when-not (even? (count kwargs))
(err/int-error (str "Expected an even number of keyword options to All, given: " (vec kwargs))))
_ (when (seq kwargs)
(when-not (apply distinct? (map first (partition 2 kwargs)))
(err/int-error (str "Gave repeated keyword args to All: " (vec kwargs)))))
{:keys [named] :as kwargs} kwargs
_ (let [unsupported (set/difference (set (keys kwargs)) #{:named})]
(when (seq unsupported)
(err/int-error (str "Unsupported keyword argument(s) to All: " unsupported))))
_ (when (contains? kwargs :named)
(when-not (and (vector? named)
(every? symbol? named))
(err/int-error (str ":named keyword argument to All must be a vector of symbols, given: " (pr-str named)))))
dotted? (= '... (peek positional))
bnds* (if named
(let [positional-no-dotted (if dotted?
(pop (pop positional))
positional)
bnds* (vec (concat positional-no-dotted named
(when dotted?
(subvec positional (- (count positional) 2)))))]
bnds*)
positional)
no-dots (if dotted?
(pop bnds*)
bnds*)
_ (when (seq no-dots)
(when-not (apply distinct? no-dots)
(err/int-error (str "Variables bound by All must be unique, given: " no-dots))))
named-map (let [sym-to-pos (into {} (map-indexed #(vector %2 %1)) no-dots)]
(select-keys sym-to-pos named))
TODO
[frees-with-bnds dvar] ((if dotted?
parse-dotted-binder
parse-normal-binder)
bnds*)]
{:frees-with-bnds frees-with-bnds
:dvar dvar
:named named-map}))
(defn parse-all-type [bnds type]
(let [_ (assert (vector? bnds))
{:keys [frees-with-bnds dvar named]} (parse-All-binder bnds)
bfs (into {} (map (fn [[n bnd]] [(r/make-F n) bnd]) frees-with-bnds))]
(if dvar
(free-ops/with-bounded-frees bfs
(c/PolyDots* (map first (concat frees-with-bnds [dvar]))
(map second (concat frees-with-bnds [dvar]))
(dvar/with-dotted [(r/make-F (first dvar))]
(parse-type type))
:named named))
(free-ops/with-bounded-frees bfs
(c/Poly* (map first frees-with-bnds)
(map second frees-with-bnds)
(parse-type type)
:named named)))))
(defmethod parse-type-list 'Extends
[[_ extends & {:keys [without] :as opts} :as syn]]
(when-not (empty? (set/difference (set (keys opts)) #{:without}))
(err/int-error (str "Invalid options to Extends:" (keys opts))))
(when-not (vector? extends)
(err/int-error (str "Extends takes a vector of types: " (pr-str syn))))
(c/-extends (doall (map parse-type extends))
:without (doall (map parse-type without))))
(defn parse-All [[_All_ bnds syn & more :as all]]
(when more
(err/int-error (str "Bad All syntax: " all)))
(parse-all-type bnds syn))
(defmethod parse-type-list 'All [t]
(err/deprecated-plain-op 'All)
(parse-All t))
(defmethod parse-type-list 'clojure.core.typed/All [t] (parse-All t))
(defmethod parse-type-list 'cljs.core.typed/All [t] (parse-All t))
(defn parse-union-type [[u & types]]
(c/make-Union (doall (map parse-type types))))
(defmethod parse-type-list 'U [syn]
(err/deprecated-plain-op 'U)
(parse-union-type syn))
(defmethod parse-type-list 'clojure.core.typed/U [syn] (parse-union-type syn))
(defmethod parse-type-list 'cljs.core.typed/U [syn] (parse-union-type syn))
(defn parse-intersection-type [[i & types]]
(c/make-Intersection (doall (map parse-type types))))
(defmethod parse-type-list 'I [syn]
(err/deprecated-plain-op 'I)
(parse-intersection-type syn))
(defmethod parse-type-list 'clojure.core.typed/I [syn] (parse-intersection-type syn))
(defmethod parse-type-list 'cljs.core.typed/I [syn] (parse-intersection-type syn))
(defn parse-Array
[[_ syn & none]]
(when-not (empty? none)
(err/int-error "Expected 1 argument to Array"))
(let [t (parse-type syn)]
(impl/impl-case
:clojure (let [jtype (if (r/RClass? t)
(r/RClass->Class t)
Object)]
(r/PrimitiveArray-maker jtype t t))
:cljs (r/ArrayCLJS-maker t t))))
(defmethod parse-type-list 'Array [syn] (parse-Array syn))
(defmethod parse-type-list 'cljs.core.typed/Array [syn] (parse-Array syn))
(defn parse-ReadOnlyArray
[[_ osyn & none]]
(when-not (empty? none)
(err/int-error "Expected 1 argument to ReadOnlyArray"))
(let [o (parse-type osyn)]
(impl/impl-case
:clojure (r/PrimitiveArray-maker Object (r/Bottom) o)
:cljs (r/ArrayCLJS-maker (r/Bottom) o))))
(defmethod parse-type-list 'ReadOnlyArray [syn] (parse-ReadOnlyArray syn))
(defmethod parse-type-list 'cljs.core.typed/ReadOnlyArray [syn] (parse-ReadOnlyArray syn))
(defmethod parse-type-list 'Array2
[[_ isyn osyn & none]]
(when-not (empty? none)
(err/int-error "Expected 2 arguments to Array2"))
(let [i (parse-type isyn)
o (parse-type osyn)]
(impl/impl-case
:clojure (r/PrimitiveArray-maker Object i o)
:cljs (r/ArrayCLJS-maker i o))))
(defmethod parse-type-list 'Array3
[[_ jsyn isyn osyn & none]]
(impl/assert-clojure)
(when-not (empty? none)
(err/int-error "Expected 3 arguments to Array3"))
(let [jrclass (c/fully-resolve-type (parse-type jsyn))
_ (when-not (r/RClass? jrclass)
(err/int-error "First argument to Array3 must be a Class"))]
(r/PrimitiveArray-maker (r/RClass->Class jrclass) (parse-type isyn) (parse-type osyn))))
(declare parse-function)
(defn parse-fn-intersection-type [[Fn & types]]
(apply r/make-FnIntersection (mapv parse-function types)))
(defn parse-Fn [[_ & types :as syn]]
(when-not (seq types)
(err/int-error (str "Must pass at least one arity to Fn: " (pr-str syn))))
(when-not (every? vector? types)
(err/int-error (str "Fn accepts vectors, given: " (pr-str syn))))
(parse-fn-intersection-type syn))
(defmethod parse-type-list 'Fn [t]
(err/deprecated-plain-op 'Fn 'IFn)
(parse-Fn t))
(defmethod parse-type-list 'clojure.core.typed/IFn [t] (parse-Fn t))
(defmethod parse-type-list 'cljs.core.typed/IFn [t] (parse-Fn t))
(defn parse-free-binder [[nme & {:keys [variance < > kind] :as opts}]]
(when-not (symbol? nme)
(err/int-error "First entry in free binder should be a name symbol"))
{:nme nme :variance (or variance :invariant)
:bound (r/Bounds-maker
(when-not kind
(if (contains? opts :<)
(parse-type <)
r/-any))
(when-not kind
(if (contains? opts :>)
(parse-type >)
r/-nothing))
(when kind
(parse-type kind)))})
(defn parse-tfn-binder [[nme & opts-flat :as all]]
{:pre [(vector? all)]
:post [((con/hmap-c? :nme symbol? :variance r/variance?
:bound r/Bounds?)
%)]}
(let [_ (when-not (even? (count opts-flat))
(err/int-error (str "Uneven arguments passed to TFn binder: "
(pr-str all))))
{:keys [variance < >]
:or {variance :inferred}
:as opts}
(apply hash-map opts-flat)]
(when-not (symbol? nme)
(err/int-error "Must provide a name symbol to TFn"))
(when (contains? opts :kind)
(err/deprecated-warn "Kind annotation for TFn parameters"))
(when-not (r/variance? variance)
(err/int-error (str "Invalid variance: " (pr-str variance))))
{:nme nme :variance variance
:bound (let [upper-or-nil (when (contains? opts :<)
(parse-type <))
lower-or-nil (when (contains? opts :>)
(parse-type >))]
(c/infer-bounds upper-or-nil lower-or-nil))}))
(defn parse-type-fn
[[_ binder bodysyn :as tfn]]
(when-not (= 3 (count tfn))
(err/int-error (str "Wrong number of arguments to TFn: " (pr-str tfn))))
(when-not (every? vector? binder)
(err/int-error (str "TFn binder should be vector of vectors: " (pr-str tfn))))
free-maps (free-ops/with-free-symbols (map (fn [s]
{:pre [(vector? s)]
:post [(symbol? %)]}
(first s))
binder)
(mapv parse-tfn-binder binder))
bodyt (free-ops/with-bounded-frees (into {}
(map (fn [{:keys [nme bound]}] [(r/make-F nme) bound])
free-maps))
(parse-type bodysyn))
( frees / fv - variances bodyt ) )
]
(c/TypeFn* (map :nme free-maps) (map :variance free-maps)
(map :bound free-maps) bodyt
{:meta {:env vs/*current-env*}})))
(defmethod parse-type-list 'TFn [syn]
(err/deprecated-plain-op 'TFn)
(parse-type-fn syn))
(defmethod parse-type-list 'clojure.core.typed/TFn [syn] (parse-type-fn syn))
(defmethod parse-type-list 'cljs.core.typed/TFn [syn] (parse-type-fn syn))
(declare parse-quoted-hvec)
(defmethod parse-type-list 'Seq* [syn]
(err/deprecated-plain-op 'Seq* 'HSeq)
(r/-hseq (mapv parse-type (rest syn))))
(defmethod parse-type-list 'List* [syn]
(err/deprecated-plain-op 'List* 'HList)
(r/HeterogeneousList-maker (mapv parse-type (rest syn))))
(defmethod parse-type-list 'Vector* [syn]
(err/deprecated-plain-op 'Vector* 'HVec)
(parse-quoted-hvec (rest syn)))
(defn parse-types-with-rest-drest [err-msg]
(fn [syns]
(let [rest? (#{'*} (last syns))
dotted? (#{'...} (-> syns butlast last))
_ (when (and rest? dotted?)
(err/int-error (str err-msg syns)))
{:keys [fixed rest drest]}
(cond
rest?
(let [fixed (mapv parse-type (drop-last 2 syns))
rest (parse-type (-> syns butlast last))]
{:fixed fixed
:rest rest})
dotted?
(let [fixed (mapv parse-type (drop-last 3 syns))
[drest-type _dots_ drest-bnd :as dot-syntax] (take-last 3 syns)
_ (when-not (#{3} (count dot-syntax))
(err/int-error (str "Bad vector syntax: " dot-syntax)))
bnd (dvar/*dotted-scope* drest-bnd)
_ (when-not bnd
(err/int-error (str (pr-str drest-bnd) " is not in scope as a dotted variable")))]
{:fixed fixed
:drest (r/DottedPretype1-maker
(parse-type drest-type))
(:name bnd))})
:else {:fixed (mapv parse-type syns)})]
{:fixed fixed
:rest rest
:drest drest})))
(def parse-hvec-types (parse-types-with-rest-drest
"Invalid heterogeneous vector syntax:"))
(def parse-hsequential-types (parse-types-with-rest-drest
"Invalid heterogeneous sequential syntax:"))
(def parse-hseq-types (parse-types-with-rest-drest
"Invalid heterogeneous seq syntax:"))
(def parse-hlist-types (parse-types-with-rest-drest
"Invalid heterogeneous list syntax:"))
(declare parse-object parse-filter-set)
(defn parse-heterogeneous* [parse-h*-types constructor]
(fn [[_ syn & {:keys [filter-sets objects repeat]}]]
(let [{:keys [fixed drest rest]} (parse-h*-types syn)]
(constructor fixed
:filters (when filter-sets
(mapv parse-filter-set filter-sets))
:objects (when objects
(mapv parse-object objects))
:drest drest
:rest rest
:repeat (when (true? repeat)
true)))))
(def parse-HVec (parse-heterogeneous* parse-hvec-types r/-hvec))
(def parse-HSequential (parse-heterogeneous* parse-hsequential-types r/-hsequential))
(def parse-HSeq (parse-heterogeneous* parse-hseq-types r/-hseq))
(def parse-HList (parse-heterogeneous* parse-hseq-types (comp #(assoc % :kind :list)
r/-hsequential)))
(defmethod parse-type-list 'HVec [t] (parse-HVec t))
(defmethod parse-type-list 'clojure.core.typed/HVec [t] (parse-HVec t))
(defmethod parse-type-list 'cljs.core.typed/HVec [t] (parse-HVec t))
(defmethod parse-type-list 'HSequential [t] (parse-HSequential t))
(defmethod parse-type-list 'clojure.core.typed/HSequential [t] (parse-HSequential t))
(defmethod parse-type-list 'cljs.core.typed/HSequential [t] (parse-HSequential t))
(defmethod parse-type-list 'HSeq [t]
(err/deprecated-plain-op 'HSeq)
(parse-HSeq t))
(defmethod parse-type-list 'clojure.core.typed/HSeq [t] (parse-HSeq t))
(defmethod parse-type-list 'cljs.core.typed/HSeq [t] (parse-HSeq t))
(defmethod parse-type-list 'clojure.core.typed/HList [t] (parse-HList t))
(defn parse-HSet [[_ ts & {:keys [complete?] :or {complete? true}} :as args]]
(let [bad (seq (remove hset/valid-fixed? ts))]
(when bad
(err/int-error (str "Bad arguments to HSet: " (pr-str bad))))
(r/-hset (set (map r/-val ts)) :complete? complete?)))
(defmethod parse-type-list 'clojure.core.typed/HSet [t] (parse-HSet t))
(defmethod parse-type-list 'cljs.core.typed/HSet [t] (parse-HSet t))
(defn- syn-to-hmap [mandatory optional absent-keys complete?]
(when mandatory
(when-not (map? mandatory)
(err/int-error (str "Mandatory entries to HMap must be a map: " mandatory))))
(when optional
(when-not (map? optional)
(err/int-error (str "Optional entries to HMap must be a map: " optional))))
(letfn [(mapt [m]
(into {} (for [[k v] m]
[(r/-val k)
(parse-type v)])))]
(let [_ (when-not (every? empty? [(set/intersection (set (keys mandatory))
(set (keys optional)))
(set/intersection (set (keys mandatory))
(set absent-keys))
(set/intersection (set (keys optional))
(set absent-keys))])
(err/int-error (str "HMap options contain duplicate key entries: "
"Mandatory: " (into {} mandatory) ", Optional: " (into {} optional)
", Absent: " (set absent-keys))))
_ (when-not (every? keyword? (keys mandatory)) (err/int-error "HMap's mandatory keys must be keywords"))
mandatory (mapt mandatory)
_ (when-not (every? keyword? (keys optional)) (err/int-error "HMap's optional keys must be keywords"))
optional (mapt optional)
_ (when-not (every? keyword? absent-keys) (err/int-error "HMap's absent keys must be keywords"))
absent-keys (set (map r/-val absent-keys))]
(c/make-HMap :mandatory mandatory :optional optional
:complete? complete? :absent-keys absent-keys))))
(defn parse-quoted-hvec [syn]
(let [{:keys [fixed drest rest]} (parse-hvec-types syn)]
(r/-hvec fixed
:drest drest
:rest rest)))
(defmethod parse-type-list 'quote
[[_ syn]]
(cond
((some-fn number? keyword? symbol? string?) syn) (r/-val syn)
(vector? syn) (parse-quoted-hvec syn)
(map? syn) (syn-to-hmap syn nil nil false)
:else (err/int-error (str "Invalid use of quote: " (pr-str syn)))))
(declare parse-in-ns)
(defn multi-frequencies
"Like frequencies, but only returns frequencies greater
than one"
[coll]
(->> coll
frequencies
(filter (fn [[k freq]]
(when (< 1 freq)
true)))
(into {})))
(defn parse-HMap [[_HMap_ & flat-opts :as all]]
(let [supported-options #{:optional :mandatory :absent-keys :complete?}
support deprecated syntax ( HMap { } ) , which is now ( HMap : mandatory { } )
deprecated-mandatory (when (map? (first flat-opts))
(err/deprecated-warn
"(HMap {}) syntax has changed, use (HMap :mandatory {})")
(first flat-opts))
flat-opts (if deprecated-mandatory
(next flat-opts)
flat-opts)
_ (when-not (even? (count flat-opts))
(err/int-error (str "Uneven keyword arguments to HMap: " (pr-str all))))
flat-keys (->> flat-opts
(partition 2)
(map first))
_ (when-not (every? keyword? flat-keys)
(err/int-error (str "HMap requires keyword arguments, given " (pr-str (first flat-keys))
#_#_" in: " (pr-str all))))
_ (let [kf (->> flat-keys
multi-frequencies
(map first)
seq)]
(when-let [[k] kf]
(err/int-error (str "Repeated keyword argument to HMap: " (pr-str k)))))
{:keys [optional mandatory absent-keys complete?]
:or {complete? false}
:as others} (apply hash-map flat-opts)
_ (when-let [[k] (seq (set/difference (set (keys others)) supported-options))]
(err/int-error (str "Unsupported HMap keyword argument: " (pr-str k))))
_ (when (and deprecated-mandatory mandatory)
(err/int-error (str "Cannot provide both deprecated initial map syntax and :mandatory option to HMap")))
mandatory (or deprecated-mandatory mandatory)]
(syn-to-hmap mandatory optional absent-keys complete?)))
(defmethod parse-type-list 'HMap [t] (parse-HMap t))
(defmethod parse-type-list 'clojure.core.typed/HMap [t] (parse-HMap t))
(defmethod parse-type-list 'cljs.core.typed/HMap [t] (parse-HMap t))
(defn parse-JSObj [[_JSObj_ types :as all]]
(let [_ (when-not (= 2 (count all))
(err/int-error (str "Bad syntax to JSObj: " (pr-str all))))
_ (when-not (every? keyword? (keys types))
(err/int-error (str "JSObj requires keyword keys, given " (pr-str (class (first (remove keyword? (keys types))))))))
parsed-types (zipmap (keys types)
(map parse-type (vals types)))]
(r/JSObj-maker parsed-types)))
(defmethod parse-type-list 'cljs.core.typed/JSObj [t] (parse-JSObj t))
(def ^:private cljs-ns (delay (impl/dynaload 'clojure.core.typed.util-cljs/cljs-ns)))
(defn- parse-in-ns []
{:post [(symbol? %)]}
(or *parse-type-in-ns*
(impl/impl-case
:clojure (ns-name *ns*)
:cljs (@cljs-ns))))
(defn- resolve-type-clj
"Returns a var, class or nil"
[sym]
{:pre [(symbol? sym)]
:post [((some-fn var? class? nil?) %)]}
(impl/assert-clojure)
(let [nsym (parse-in-ns)]
(if-let [ns (find-ns nsym)]
(ns-resolve ns sym)
(err/int-error (str "Cannot find namespace: " sym)))))
(defn- resolve-alias-clj
"Returns a symbol if sym maps to a type alias, otherwise nil"
[sym]
{:pre [(symbol? sym)]
:post [((some-fn symbol? nil?) %)]}
(impl/assert-clojure)
(let [nsym (parse-in-ns)
nsp (some-> (namespace sym) symbol)]
(if-let [ns (find-ns nsym)]
(when-let [qual (if nsp
(some-> (or ((ns-aliases ns) nsp)
(find-ns nsp))
ns-name)
(ns-name ns))]
(let [_ (assert (and (symbol? qual)
(not (namespace qual))))
qsym (symbol (name qual) (name sym))]
(when (contains? (nme-env/name-env) qsym)
qsym)))
(err/int-error (str "Cannot find namespace: " sym)))))
(let [cljs-resolve-var (delay (impl/dynaload 'clojure.core.typed.util-cljs/resolve-var))]
(defn- resolve-type-cljs
"Returns a qualified symbol or nil"
[sym]
{:pre [(symbol? sym)]
:post [((some-fn symbol?
nil?)
%)]}
(impl/assert-cljs)
(let [nsym (parse-in-ns)
res (@cljs-resolve-var nsym sym)]
res)))
(defn parse-RClass [cls-sym params-syn]
(impl/assert-clojure)
(let [RClass-of @(RClass-of-var)
cls (resolve-type-clj cls-sym)
_ (when-not (class? cls) (err/int-error (str (pr-str cls-sym) " cannot be resolved")))
tparams (doall (map parse-type params-syn))]
(RClass-of cls tparams)))
(defn parse-Value [[_Value_ syn :as all]]
(when-not (#{2} (count all))
(err/int-error (str "Incorrect number of arguments to Value, " (count all)
", expected 2: " all)))
(impl/impl-case
:clojure (const/constant-type syn)
:cljs (cond
((some-fn symbol? keyword?) syn)
(r/-val syn)
:else (assert nil "FIXME CLJS parse Value"))))
(defmethod parse-type-list 'Value [t] (parse-Value t))
(defmethod parse-type-list 'clojure.core.typed/Val [t] (parse-Value t))
(defmethod parse-type-list 'clojure.core.typed/Value [t] (parse-Value t))
(defmethod parse-type-list 'cljs.core.typed/Val [t] (parse-Value t))
(defmethod parse-type-list 'cljs.core.typed/Value [t] (parse-Value t))
(defmethod parse-type-list 'KeywordArgs
[[_KeywordArgs_ & {:keys [optional mandatory]}]]
(when-not (= #{}
(set/intersection (set (keys optional))
(set (keys mandatory))))
(err/int-error (str "Optional and mandatory keyword arguments should be disjoint: "
(set/intersection (set (keys optional))
(set (keys mandatory))))))
(let [optional (into {} (for [[k v] optional]
(do (when-not (keyword? k) (err/int-error (str "Keyword argument keys must be keywords: " (pr-str k))))
[(r/-val k) (parse-type v)])))
mandatory (into {} (for [[k v] mandatory]
(do (when-not (keyword? k) (err/int-error (str "Keyword argument keys must be keywords: " (pr-str k))))
[(r/-val k) (parse-type v)])))]
(apply c/Un (apply concat
(for [opts (map #(into {} %) (comb/subsets optional))]
(let [m (merge mandatory opts)
kss (comb/permutations (keys m))]
(for [ks kss]
(r/-hseq (mapcat #(find m %) ks)))))))))
(declare unparse-type deprecated-list)
(defn parse-type-list-default
[[n & args :as syn]]
(if-let [d (deprecated-list syn)]
d
(let [op (parse-type n)]
(when-not ((some-fn r/Name? r/TypeFn? r/F? r/B? r/Poly?) op)
(err/int-error (str "Invalid operator to type application: " syn)))
(with-meta (r/TApp-maker op (mapv parse-type args))
{:syn syn
:env vs/*current-env*}))))
(defmethod parse-type-list :default
[[n & args :as syn]]
(parse-type-list-default syn))
(defmethod parse-type* Cons [l] (parse-type-list l))
(defmethod parse-type* IPersistentList [l]
(parse-type-list l))
(defmulti parse-type-symbol
(fn [n]
{:pre [(symbol? n)]}
(or (impl/impl-case
:clojure (let [r (resolve-type-clj n)]
(when (var? r)
(coerce/var->symbol r)))
TODO
:cljs (resolve-type-cljs n))
n)))
(defn parse-Any [sym]
(if (-> sym meta ::t/infer)
r/-infer-any
r/-any))
(defmethod parse-type-symbol 'Any [_]
(err/deprecated-plain-op 'Any)
r/-any)
(defmethod parse-type-symbol 'clojure.core.typed/Any [s] (parse-Any s))
(defmethod parse-type-symbol 'cljs.core.typed/Any [s] (parse-Any s))
(defmethod parse-type-symbol 'clojure.core.typed/TCError [t] (r/TCError-maker))
(defmethod parse-type-symbol 'Nothing [_]
(err/deprecated-plain-op 'Nothing)
(r/Bottom))
(defmethod parse-type-symbol 'clojure.core.typed/Nothing [_] (r/Bottom))
(defmethod parse-type-symbol 'cljs.core.typed/Nothing [_] (r/Bottom))
(defmethod parse-type-symbol 'AnyFunction [_] (r/TopFunction-maker))
(defmethod parse-type-symbol 'cljs.core.typed/CLJSInteger [_] (r/CLJSInteger-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSNumber [_] (r/JSNumber-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSBoolean [_] (r/JSBoolean-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSObject [_] (r/JSObject-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSString [_] (r/JSString-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSUndefined [_] (r/JSUndefined-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSNull [_] (r/JSNull-maker))
(defmethod parse-type-symbol 'cljs.core.typed/JSSymbol [_] (r/JSSymbol-maker))
(defn clj-primitives-fn []
(let [RClass-of @(RClass-of-var)]
{'byte (RClass-of 'byte)
'short (RClass-of 'short)
'int (RClass-of 'int)
'long (RClass-of 'long)
'float (RClass-of 'float)
'double (RClass-of 'double)
'boolean (RClass-of 'boolean)
'char (RClass-of 'char)
'void r/-nil}))
(defmulti deprecated-clj-symbol identity)
(defmethod deprecated-clj-symbol :default [_] nil)
(defn deprecated-symbol [sym]
{:post [((some-fn nil? r/Type?) %)]}
(impl/impl-case
:clojure (deprecated-clj-symbol sym)
:cljs nil))
(defmulti deprecated-clj-list
(fn [[op]]
(when (symbol? op)
((some-fn
(every-pred
class? coerce/Class->symbol)
(every-pred
var? coerce/var->symbol))
(resolve-type-clj op)))))
(defmethod deprecated-clj-list :default [_] nil)
(defn deprecated-list [lst]
{:post [((some-fn nil? r/Type?) %)]}
(impl/impl-case
:clojure (deprecated-clj-list lst)
:cljs nil))
(defn parse-type-symbol-default
[sym]
(let [primitives (impl/impl-case
:clojure (clj-primitives-fn)
:cljs {})
free (when (symbol? sym)
(free-ops/free-in-scope sym))
rsym (when-not free
(impl/impl-case
:clojure (let [res (when (symbol? sym)
(resolve-type-clj sym))]
(cond
(class? res) (coerce/Class->symbol res)
(var? res) (coerce/var->symbol res)
:else (let [ns (parse-in-ns)
dprotocol (if (namespace sym)
sym
(symbol (str ns) (str sym)))
ddatatype (if (some #{\.} (str sym))
sym
(symbol (str (munge ns)) (str sym)))
nmesym (resolve-alias-clj sym)]
(cond
nmesym nmesym
(nme-env/declared-protocol? dprotocol) dprotocol
(nme-env/declared-datatype? ddatatype) ddatatype))))
:cljs (when (symbol? sym)
(resolve-type-cljs sym))))
_ (assert ((some-fn symbol? nil?) rsym))]
(cond
free free
(primitives sym) (primitives sym)
rsym ((some-fn deprecated-symbol r/Name-maker) rsym)
:else (let [menv (let [m (meta sym)]
(when ((every-pred :line :column :file) m)
m))]
(binding [vs/*current-env* (or menv vs/*current-env*)]
(err/int-error (str "Cannot resolve type: " (pr-str sym)
"\nHint: Is " (pr-str sym) " in scope?")
{:use-current-env true}))))))
(defmethod parse-type-symbol :default
[sym]
(parse-type-symbol-default sym))
(defmethod parse-type* Symbol [l] (parse-type-symbol l))
(defmethod parse-type* Boolean [v] (if v r/-true r/-false))
(defmethod parse-type* nil [_] r/-nil)
(declare parse-path-elem parse-filter*)
(defn parse-filter [f]
(cond
(= 'tt f) f/-top
(= 'ff f) f/-bot
(= 'no-filter f) f/-no-filter
(not ((some-fn seq? list?) f)) (err/int-error (str "Malformed filter expression: " (pr-str f)))
:else (parse-filter* f)))
(defn parse-object-path [{:keys [id path]}]
(when-not (f/name-ref? id)
(err/int-error (str "Must pass natural number or symbol as id: " (pr-str id))))
(orep/-path (when path (mapv parse-path-elem path)) id))
(defn parse-object [obj]
(case obj
empty orep/-empty
no-object orep/-no-object
(parse-object-path obj)))
(defn parse-filter-set [{:keys [then else] :as fsyn}]
(when-not (map? fsyn)
(err/int-error "Filter set must be a map"))
(let [extra (set/difference (set (keys fsyn)) #{:then :else})]
(when-not (empty? extra)
(err/int-error (str "Invalid filter set option: " (first extra)))))
(fl/-FS (if (contains? fsyn :then)
(parse-filter then)
f/-top)
(if (contains? fsyn :else)
(parse-filter else)
f/-top)))
(defmulti parse-filter*
#(when (coll? %)
(first %)))
(defmethod parse-filter* :default
[syn]
(err/int-error (str "Malformed filter expression: " (pr-str syn))))
(defmethod parse-filter* 'is
[[_ & [tsyn nme psyns :as all]]]
(when-not (#{2 3} (count all))
(err/int-error (str "Wrong number of arguments to is")))
(let [t (parse-type tsyn)
p (when (= 3 (count all))
(mapv parse-path-elem psyns))]
(fl/-filter t nme p)))
(defmethod parse-filter* '!
[[_ & [tsyn nme psyns :as all]]]
(when-not (#{2 3} (count all))
(err/int-error (str "Wrong number of arguments to !")))
(let [t (parse-type tsyn)
p (when (= 3 (count all))
(mapv parse-path-elem psyns))]
(fl/-not-filter t nme p)))
(defmethod parse-filter* '|
[[_ & fsyns]]
(apply fl/-or (mapv parse-filter fsyns)))
(defmethod parse-filter* '&
[[_ & fsyns]]
(apply fl/-and (mapv parse-filter fsyns)))
(defmethod parse-filter* 'when
[[_ & [a c :as args] :as all]]
(when-not (#{2} (count args))
(err/int-error (str "Wrong number of arguments to when: " all)))
(fl/-imp (parse-filter a) (parse-filter c)))
FIXME clean up the magic . eg . handle ( Class foo bar ) as an error
(defmulti parse-path-elem
#(cond
(symbol? %) %
(coll? %) (first %)
:else
(err/int-error (str "Malformed path element: " (pr-str %)))))
(defmethod parse-path-elem :default [syn]
(err/int-error (str "Malformed path element: " (pr-str syn))))
(defmethod parse-path-elem 'Class [_] (pthrep/ClassPE-maker))
(defmethod parse-path-elem 'Count [_] (pthrep/CountPE-maker))
(defmethod parse-path-elem 'Keys [_] (pthrep/KeysPE-maker))
(defmethod parse-path-elem 'Vals [_] (pthrep/ValsPE-maker))
(defmethod parse-path-elem 'Key
[[_ & [ksyn :as all]]]
(when-not (= 1 (count all))
(err/int-error "Wrong arguments to Key"))
(pthrep/-kpe ksyn))
(defmethod parse-path-elem 'Nth
[[_ & [idx :as all]]]
(when-not (= 1 (count all))
(err/int-error "Wrong arguments to Nth"))
(pthrep/NthPE-maker idx))
(defmethod parse-path-elem 'Keyword [_] (pthrep/KeywordPE-maker))
(defn- parse-kw-map [m]
{:post [((con/hash-c? r/Value? r/Type?) %)]}
(into {} (for [[k v] m]
[(r/-val k) (parse-type v)])))
(defn parse-function [f]
{:post [(r/Function? %)]}
(let [is-arrow '#{-> :->}
all-dom (take-while (complement is-arrow) f)
_ (when ('#{->} the-arrow)
TODO deprecate
)
_ (when-not (<= 2 (count chk))
(err/int-error (str "Incorrect function syntax: " f)))
_ (when-not (even? (count opts-flat))
(err/int-error (str "Incorrect function syntax, must have even number of keyword parameters: " f)))
opts (apply hash-map opts-flat)
{ellipsis-pos '...
asterix-pos '*
kw-asterix-pos :*
ampersand-pos '&
push-rest-pos '<*
push-dot-pos '<...}
(zipmap all-dom (range))
_ (when-not (#{0 1} (count (filter identity [asterix-pos ellipsis-pos ampersand-pos
kw-asterix-pos push-rest-pos])))
(err/int-error "Can only provide one rest argument option: & ... * or <*"))
asterix-pos (or asterix-pos kw-asterix-pos)
_ (when-let [ks (seq (remove #{:filters :object :flow} (keys opts)))]
(err/int-error (str "Invalid function keyword option/s: " ks)))
filters (when-let [[_ fsyn] (find opts :filters)]
(parse-filter-set fsyn))
object (when-let [[_ obj] (find opts :object)]
(parse-object obj))
flow (when-let [[_ obj] (find opts :flow)]
(r/-flow (parse-filter obj)))
fixed-dom (cond
asterix-pos (take (dec asterix-pos) all-dom)
ellipsis-pos (take (dec ellipsis-pos) all-dom)
ampersand-pos (take ampersand-pos all-dom)
push-rest-pos (take (dec push-rest-pos) all-dom)
push-dot-pos (take (dec push-dot-pos) all-dom)
:else all-dom)
rest-type (when asterix-pos
(nth all-dom (dec asterix-pos)))
_ (when-not (or (not asterix-pos)
(= (count all-dom) (inc asterix-pos)))
(err/int-error (str "Trailing syntax after rest parameter: " (pr-str (drop (inc asterix-pos) all-dom)))))
[drest-type _ drest-bnd :as drest-seq] (when ellipsis-pos
(drop (dec ellipsis-pos) all-dom))
_ (when-not (or (not ellipsis-pos) (= 3 (count drest-seq)))
(err/int-error "Dotted rest entry must be 3 entries"))
_ (when-not (or (not ellipsis-pos) (symbol? drest-bnd))
(err/int-error "Dotted bound must be symbol"))
[pdot-type _ pdot-bnd :as pdot-seq] (when push-dot-pos
(drop (dec push-dot-pos) all-dom))
_ (when-not (or (not push-dot-pos) (= 3 (count pdot-seq)))
(err/int-error "push dotted rest entry must be 3 entries"))
_ (when-not (or (not push-dot-pos) (symbol? pdot-bnd))
(err/int-error "push dotted bound must be symbol"))
[& {optional-kws :optional mandatory-kws :mandatory} :as kws-seq]
(let [kwsyn (when ampersand-pos
(drop (inc ampersand-pos) all-dom))]
(if (and kwsyn
(map? (first kwsyn)))
(do (err/deprecated-warn "[& {} -> ] function syntax is deprecated. Use [& :optional {} -> ]")
(cons :optional kwsyn))
kwsyn))
_ (when-not (or (not ampersand-pos) (seq kws-seq))
(err/int-error "Must provide syntax after &"))
prest-type (when push-rest-pos
(nth all-dom (dec push-rest-pos)))
_ (when-not (or (not push-rest-pos)
(= (count all-dom) (inc push-rest-pos)))
(err/int-error (str "Trailing syntax after pust-rest parameter: " (pr-str (drop (inc push-rest-pos) all-dom)))))]
(r/make-Function (mapv parse-type fixed-dom)
(parse-type rng)
:rest
(when asterix-pos
(parse-type rest-type))
:drest
(when ellipsis-pos
(let [bnd (dvar/*dotted-scope* drest-bnd)
_ (when-not bnd
(err/int-error (str (pr-str drest-bnd) " is not in scope as a dotted variable")))]
(r/DottedPretype1-maker
(parse-type drest-type))
(:name bnd))))
:prest
(when push-rest-pos
(parse-type prest-type))
:pdot
(when push-dot-pos
(let [bnd (dvar/*dotted-scope* pdot-bnd)
_ (when-not bnd
(err/int-error (str (pr-str pdot-bnd) " is not in scope as a dotted variable")))]
(r/DottedPretype1-maker
(parse-type pdot-type))
(:name bnd))))
:filter filters
:object object
:flow flow
:optional-kws (when optional-kws
(parse-kw-map optional-kws))
:mandatory-kws (when mandatory-kws
(parse-kw-map mandatory-kws)))))
(defmethod parse-type* IPersistentVector
[f]
(apply r/make-FnIntersection [(parse-function f)]))
(defmethod parse-type* :default
[k]
(err/int-error (str "Bad type syntax: " (pr-str k)
(when ((some-fn symbol? keyword?) k)
(str "\n\nHint: Value types should be preceded by a quote or wrapped in the Value constructor."
" eg. '" (pr-str k) " or (Value " (pr-str k)")")))))
(indu/add-indirection ind/parse-type parse-type)
Unparse
types are generally agnostic to the current implementation .
(defonce ^:dynamic *unparse-type-in-ns* nil)
(set-validator! #'*unparse-type-in-ns* (some-fn nil? symbol?))
(defn unparse-in-ns []
{:post [((some-fn nil? symbol?) %)]}
(or *unparse-type-in-ns*
(impl/impl-case
:clojure (ns-name *ns*)
:cljs (@cljs-ns)
:unknown nil)))
(defmacro with-unparse-ns [sym & body]
`(binding [*unparse-type-in-ns* ~sym]
~@body))
(defn alias-in-ns
"Returns an alias for namespace sym in ns, or nil if none."
[nsym ns]
{:pre [(string? nsym)
(con/namespace? ns)]
:post [((some-fn nil? symbol?) %)]}
(impl/assert-clojure)
(some (fn [[alias ans]]
(when (= (str nsym) (str (ns-name ans)))
alias))
(ns-aliases ns)))
(defn core-lang-Class-sym [clsym]
{:pre [(symbol? clsym)]
:post [((some-fn nil? symbol?) %)]}
(when (.startsWith (str clsym) "clojure.lang.")
(symbol (.getSimpleName (Class/forName (str clsym))))))
(defn Class-symbol-intern [clsym ns]
{:pre [(con/namespace? ns)]
:post [((some-fn nil? symbol?) %)]}
(some (fn [[isym cls]]
(when (= (str clsym) (str (coerce/Class->symbol cls)))
isym))
(ns-imports ns)))
(defn var-symbol-intern
"Returns a symbol interned in ns for var symbol, or nil if none.
(var-symbol-intern 'symbol (find-ns 'clojure.core))
(var-symbol-intern 'bar (find-ns 'clojure.core))
[sym ns]
{:pre [(symbol? sym)
(con/namespace? ns)]
:post [((some-fn nil? symbol?) %)]}
(some (fn [[isym var]]
(when (= (str sym) (str (coerce/var->symbol var)))
isym))
(merge (ns-interns ns)
(ns-refers ns))))
(defn unparse-Name-symbol-in-ns [sym]
{:pre [(symbol? sym)]
:post [(symbol? %)]}
( prn " unparse - Name - symbol - in - ns " )
(if-let [ns (and (not vs/*verbose-types*)
(some-> (unparse-in-ns) find-ns))]
(impl/impl-case
:clojure
(Class-symbol-intern sym ns)
(core-lang-Class-sym sym)
(when (namespace sym)
(or (var-symbol-intern sym ns)
(when-let [alias (alias-in-ns (namespace sym) ns)]
(symbol (str alias) (name sym)))))
sym)
:cljs sym
:unknown sym)
sym))
(declare unparse-type*)
(defn unparse-type [t]
(if-let [nsym (-> t meta :source-Name)]
nsym
(unparse-type* t)))
(defmulti unparse-type* class)
(defn unp [t] (prn (unparse-type t)))
(defmethod unparse-type* Top [_] (unparse-Name-symbol-in-ns `t/Any))
TODO qualify vsym in current ns
(defmethod unparse-type* TypeOf [{:keys [vsym] :as t}] (list (unparse-Name-symbol-in-ns `t/TypeOf) vsym))
(defmethod unparse-type* Unchecked [{:keys [vsym] :as t}]
(if vsym
(list 'Unchecked vsym)
'Unchecked))
(defmethod unparse-type* TCError [_] (unparse-Name-symbol-in-ns `t/TCError))
(defmethod unparse-type* Name [{:keys [id]}] (unparse-Name-symbol-in-ns id))
(defmethod unparse-type* AnyValue [_] (unparse-Name-symbol-in-ns `t/AnyValue))
(defmethod unparse-type* DottedPretype
[{:keys [pre-type name]}]
(list 'DottedPretype (unparse-type pre-type) (if (symbol? name)
(-> name r/make-F r/F-original-name)
name)))
(defmethod unparse-type* CountRange [{:keys [lower upper]}]
(cond
(= lower upper) (list (unparse-Name-symbol-in-ns `t/ExactCount)
lower)
:else (list* (unparse-Name-symbol-in-ns `t/CountRange)
lower
(when upper [upper]))))
(defmethod unparse-type* App
[{:keys [rator rands]}]
(list* (unparse-type rator) (mapv unparse-type rands)))
(defmethod unparse-type* TApp
[{:keys [rator rands] :as tapp}]
(cond
:else
(list* (unparse-type rator) (mapv unparse-type rands))))
(defmethod unparse-type* Result
[{:keys [t]}]
(unparse-type t))
(defmethod unparse-type* F
[{:keys [] :as f}]
(r/F-original-name f))
(defmethod unparse-type* PrimitiveArray
[{:keys [jtype input-type output-type]}]
(cond
(and (= input-type output-type)
(= Object jtype))
(list 'Array (unparse-type input-type))
(= Object jtype)
(list 'Array2 (unparse-type input-type) (unparse-type output-type))
:else
(list 'Array3 (coerce/Class->symbol jtype)
(unparse-type input-type) (unparse-type output-type))))
(defmethod unparse-type* B
[{:keys [idx]}]
(list 'B idx))
(defmethod unparse-type* Union
[{types :types :as u}]
(cond
(seq types) (list* (unparse-Name-symbol-in-ns `t/U)
(doall (map unparse-type types)))
:else (unparse-Name-symbol-in-ns `t/Nothing)))
(defmethod unparse-type* FnIntersection
[{types :types}]
(cond
(and (not vs/*verbose-types*)
(== 1 (count types)))
(unparse-type (first types))
:else
(list* (unparse-Name-symbol-in-ns `t/IFn)
(doall (map unparse-type types)))))
(defmethod unparse-type* Intersection
[{types :types}]
(list* (unparse-Name-symbol-in-ns `t/I)
(doall (map unparse-type types))))
(defmethod unparse-type* DifferenceType
[{:keys [type without]}]
(list* (unparse-Name-symbol-in-ns `t/Difference)
(unparse-type* type)
(doall (map unparse-type without))))
(defmethod unparse-type* NotType
[{:keys [type]}]
(list 'Not (unparse-type type)))
(defmethod unparse-type* TopFunction [_] 'AnyFunction)
(defn- unparse-kw-map [m]
{:pre [((con/hash-c? r/Value? r/Type?) m)]}
(into {} (for [[^Value k v] m]
[(.val k) (unparse-type v)])))
(defn unparse-result [{:keys [t fl o flow] :as rng}]
{:pre [(r/Result? rng)]}
(concat [(unparse-type t)]
(when-not (every? (some-fn f/TopFilter? f/NoFilter?) [(:then fl) (:else fl)])
[:filters (unparse-filter-set fl)])
(when-not ((some-fn orep/NoObject? orep/EmptyObject?) o)
[:object (unparse-object o)])
(when-not ((some-fn f/TopFilter? f/NoFilter?) (:normal flow))
[:flow (unparse-flow-set flow)])))
(defn unparse-bound [name]
{:pre [((some-fn symbol? nat-int?) name)]}
(if (symbol? name)
(-> name r/make-F r/F-original-name)
`(~'B ~name)))
(defmethod unparse-type* SymbolicClosure
[{:keys [fexpr env]}]
(list 'SymbolicClosure))
(defmethod unparse-type* Function
[{:keys [dom rng kws rest drest prest pdot]}]
(vec (concat (doall (map unparse-type dom))
(when rest
[(unparse-type rest) '*])
(when drest
(let [{:keys [pre-type name]} drest]
[(unparse-type pre-type)
'...
(unparse-bound name)]))
(when kws
(let [{:keys [optional mandatory]} kws]
(list* '&
(concat
(when (seq mandatory)
[:mandatory (unparse-kw-map mandatory)])
(when (seq optional)
[:optional (unparse-kw-map optional)])))))
(when prest
[(unparse-type prest) '<*])
(when pdot
(let [{:keys [pre-type name]} pdot]
[(unparse-type pre-type)
'<...
(unparse-bound name)]))
['->]
(unparse-result rng))))
(defn unparse-flow-set [flow]
{:pre [(r/FlowSet? flow)]}
(unparse-filter (r/flow-normal flow)))
(defmethod unparse-type* Protocol
[{:keys [the-var poly?]}]
(let [s (unparse-Name-symbol-in-ns the-var)]
(if poly?
(list* s (mapv unparse-type poly?))
s)))
(defmethod unparse-type* DataType
[{:keys [the-class poly?]}]
(if poly?
(list* (unparse-Name-symbol-in-ns the-class) (mapv unparse-type poly?))
(unparse-Name-symbol-in-ns the-class)))
(defmethod unparse-type* RClass
[{:keys [the-class poly?] :as r}]
(if (empty? poly?)
(unparse-Name-symbol-in-ns the-class)
(list* (unparse-Name-symbol-in-ns the-class) (doall (map unparse-type poly?)))))
(defmethod unparse-type* Mu
[m]
(let [nme (-> (c/Mu-fresh-symbol* m) r/make-F r/F-original-name)
body (c/Mu-body* nme m)]
(list (unparse-Name-symbol-in-ns `t/Rec) [nme] (unparse-type body))))
(defn unparse-poly-bounds-entry [name {:keys [upper-bound lower-bound higher-kind] :as bnds}]
(let [name (-> name r/make-F r/F-original-name)
u (when upper-bound
(unparse-type upper-bound))
l (when lower-bound
(unparse-type lower-bound))
h (when higher-kind
(unparse-type higher-kind))]
(or (when higher-kind
[name :kind h])
(when-not (or (r/Top? upper-bound) (r/Bottom? lower-bound))
[name :< u :> l])
(when-not (r/Top? upper-bound)
[name :< u])
(when-not (r/Bottom? lower-bound)
[name :> l])
name)))
(defn unparse-poly-dotted-bounds-entry [free-name bbnd]
[(-> free-name r/make-F r/F-original-name) '...])
(defn unparse-poly-binder [dotted? free-names bbnds named]
(let [named-remappings (apply sorted-map (interleave (vals named) (keys named)))
{:keys [fixed-inb named-inb]} (group-by (fn [[i]]
(if (named-remappings i)
:named-inb
:fixed-inb))
(map vector
(range)
free-names
bbnds))
[fixed-inb dotted-inb] (if dotted?
((juxt pop peek) fixed-inb)
[fixed-inb nil])
unp-inb (fn [[_ free-name bbnd]]
(unparse-poly-bounds-entry free-name bbnd))
binder (into (mapv unp-inb fixed-inb)
(concat
(when-let [[_ free-name bbnd] dotted-inb]
(unparse-poly-dotted-bounds-entry free-name bbnd))
(when named-inb
[:named (mapv unp-inb named-inb)])))]
binder))
(defmethod unparse-type* PolyDots
[{:keys [nbound named] :as p}]
(let [free-names (vec (c/PolyDots-fresh-symbols* p))
bbnds (c/PolyDots-bbnds* free-names p)
binder (unparse-poly-binder true free-names bbnds named)
body (c/PolyDots-body* free-names p)]
(list (unparse-Name-symbol-in-ns `t/All) binder (unparse-type body))))
(defmethod unparse-type* Extends
[{:keys [extends without]}]
(list* 'Extends
(mapv unparse-type extends)
(when (seq without)
[:without (mapv unparse-type without)])))
(defmethod unparse-type* Poly
[{:keys [nbound named] :as p}]
(let [free-names (c/Poly-fresh-symbols* p)
bbnds (c/Poly-bbnds* free-names p)
binder (unparse-poly-binder false free-names bbnds named)
body (c/Poly-body* free-names p)]
(list (unparse-Name-symbol-in-ns `t/All) binder (unparse-type body))))
( - bounds - entry [ t / Sym Bounds Variance - > Any ] )
(defn unparse-typefn-bounds-entry [name {:keys [upper-bound lower-bound higher-kind]} v]
(let [name (-> name r/make-F r/F-original-name)
u (when upper-bound
(unparse-type upper-bound))
l (when lower-bound
(unparse-type lower-bound))
h (when higher-kind
(unparse-type higher-kind))]
(or (when higher-kind
[name :variance v :kind h])
(when-not (or (r/Top? upper-bound) (r/Bottom? lower-bound))
[name :variance v :< u :> l])
(when-not (r/Top? upper-bound)
[name :variance v :< u])
(when-not (r/Bottom? lower-bound)
[name :variance v :> l])
[name :variance v])))
(defmethod unparse-type* TypeFn
[{:keys [nbound] :as p}]
(let [free-names (c/TypeFn-fresh-symbols* p)
bbnds (c/TypeFn-bbnds* free-names p)
binder (mapv unparse-typefn-bounds-entry free-names bbnds (:variances p))
body (c/TypeFn-body* free-names p)]
(list (unparse-Name-symbol-in-ns `t/TFn) binder (unparse-type body))))
(defmethod unparse-type* Value
[v]
(if ((some-fn r/Nil? r/True? r/False?) v)
(:val v)
(list (unparse-Name-symbol-in-ns `t/Val) (:val v))))
(defn- unparse-map-of-types [m]
(into {} (map (fn [[k v]]
(assert (r/Value? k) k)
(vector (:val k) (unparse-type v)))
m)))
(defmethod unparse-type* HeterogeneousMap
[^HeterogeneousMap v]
(list* (unparse-Name-symbol-in-ns `t/HMap)
(concat
(when (or (seq (:types v))
(not (or (seq (:optional v))
(seq (:absent-keys v))
(c/complete-hmap? v))))
[:mandatory (unparse-map-of-types (.types v))])
(when (seq (:optional v))
[:optional (unparse-map-of-types (:optional v))])
(when-let [ks (and (not (c/complete-hmap? v))
(seq (.absent-keys v)))]
[:absent-keys (set (map :val ks))])
(when (c/complete-hmap? v)
[:complete? true]))))
(defn unparse-heterogeneous* [sym {:keys [types rest drest fs objects repeat] :as v}]
(let [first-part (concat
(map unparse-type (:types v))
(when rest [(unparse-type rest) '*])
(when drest [(unparse-type (:pre-type drest))
'...
(unparse-bound (:name drest))]))]
(list* sym
(vec first-part)
(concat
(when repeat
[:repeat true])
(when-not (every? #{(fl/-FS f/-top f/-top)} fs)
[:filter-sets (mapv unparse-filter-set fs)])
(when-not (every? #{orep/-empty} objects)
[:objects (mapv unparse-object objects)])))))
(defmethod unparse-type* HSequential [v]
(unparse-heterogeneous*
(case (:kind v)
:list (unparse-Name-symbol-in-ns `t/HList)
:vector (unparse-Name-symbol-in-ns `t/HVec)
:seq (unparse-Name-symbol-in-ns `t/HSeq)
:sequential (unparse-Name-symbol-in-ns `t/HSequential))
v))
(defmethod unparse-type* HSet
[{:keys [fixed] :as v}]
{:pre [(every? r/Value? fixed)]}
(list (unparse-Name-symbol-in-ns `t/HSet) (set (map :val fixed))))
(defmethod unparse-type* KwArgsSeq
[^KwArgsSeq v]
(list* 'KwArgsSeq
(concat
(when (seq (.optional v))
[:optional (unparse-map-of-types (.optional v))])
(when (seq (.mandatory v))
[:mandatory (unparse-map-of-types (.mandatory v))])
(when (:complete? v)
[:complete? (:complete? v)])
(when (:nilable-non-empty? v)
[:nilable-non-empty? (:nilable-non-empty? v)]))))
(defmethod unparse-type* AssocType
[{:keys [target entries dentries]}]
(list* (unparse-Name-symbol-in-ns `t/Assoc)
(unparse-type target)
(concat
(doall (map unparse-type (apply concat entries)))
(when dentries [(unparse-type (:pre-type dentries))
'...
(unparse-bound (:name dentries))]))))
(defmethod unparse-type* GetType
[{:keys [target key not-found]}]
(list* (unparse-Name-symbol-in-ns `t/Get)
(unparse-type target)
(unparse-type key)
(when (not= r/-nil not-found)
[(unparse-type not-found)])))
(defmethod unparse-type* JSNumber [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSNumber))
(defmethod unparse-type* JSBoolean [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSBoolean))
(defmethod unparse-type* JSObject [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSObject))
(defmethod unparse-type* CLJSInteger [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/CLJSInteger))
(defmethod unparse-type* JSString [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSString))
(defmethod unparse-type* JSSymbol [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSSymbol))
(defmethod unparse-type* JSUndefined [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSUndefined))
(defmethod unparse-type* JSNull [_] (unparse-Name-symbol-in-ns 'cljs.core.typed/JSNull))
(defmethod unparse-type* JSObj [t] (list (unparse-Name-symbol-in-ns 'cljs.core.typed/JSObj)
(zipmap (keys (:types t))
(map unparse-type (vals (:types t))))))
(defmethod unparse-type* ArrayCLJS
[{:keys [input-type output-type]}]
(cond
(= input-type output-type) (list 'Array (unparse-type input-type))
:else (list 'Array2 (unparse-type input-type) (unparse-type output-type))))
(defmethod unparse-type* JSNominal
[{:keys [name poly?]}]
(let [sym (symbol name)]
(if (seq poly?)
(list* sym (map unparse-type poly?))
sym)))
(declare unparse-path-elem)
(defmulti unparse-object class)
(defmethod unparse-object EmptyObject [_] 'empty)
(defmethod unparse-object NoObject [_] 'no-object)
(defmethod unparse-object Path [{:keys [path id]}] (conj {:id id} (when (seq path) [:path (mapv unparse-path-elem path)])))
(defmulti unparse-path-elem class)
(defmethod unparse-path-elem KeyPE [t] (list 'Key (:val t)))
(defmethod unparse-path-elem CountPE [t] 'Count)
(defmethod unparse-path-elem ClassPE [t] 'Class)
(defmethod unparse-path-elem NthPE [t] (list 'Nth (:idx t)))
(defmethod unparse-path-elem KeysPE [t] 'Keys)
(defmethod unparse-path-elem ValsPE [t] 'Vals)
(defmethod unparse-path-elem KeywordPE [t] 'Keyword)
(defmulti unparse-filter* class)
(declare unparse-filter)
(defn unparse-filter-set [{:keys [then else] :as fs}]
{:pre [(f/FilterSet? fs)]}
{:then (unparse-filter then)
:else (unparse-filter else)})
(defn unparse-filter [f]
(unparse-filter* f))
(defmethod unparse-filter* TopFilter [f] 'tt)
(defmethod unparse-filter* BotFilter [f] 'ff)
(defmethod unparse-filter* NoFilter [f] 'no-filter)
(declare unparse-type)
(defmethod unparse-filter* TypeFilter
[{:keys [type path id]}]
(concat (list 'is (unparse-type type) id)
(when (seq path)
[(mapv unparse-path-elem path)])))
(defmethod unparse-filter* NotTypeFilter
[{:keys [type path id]}]
(concat (list '! (unparse-type type) id)
(when (seq path)
[(mapv unparse-path-elem path)])))
(defmethod unparse-filter* AndFilter [{:keys [fs]}] (apply list '& (map unparse-filter fs)))
(defmethod unparse-filter* OrFilter [{:keys [fs]}] (apply list '| (map unparse-filter fs)))
(defmethod unparse-filter* ImpFilter
[{:keys [a c]}]
(list 'when (unparse-filter a) (unparse-filter c)))
(defn unparse-TCResult [r]
(let [t (unparse-type (r/ret-t r))
fs (unparse-filter-set (r/ret-f r))
o (unparse-object (r/ret-o r))]
(if (and (= (fl/-FS f/-top f/-top) (r/ret-f r))
(= (r/ret-o r) orep/-empty))
t
(if (= (r/ret-o r) orep/-empty)
[t fs]
[t fs o]))))
(defn unparse-TCResult-in-ns [r ns]
{:pre [((some-fn con/namespace? symbol?) ns)]}
(binding [*unparse-type-in-ns* (if (symbol? ns)
ns
(ns-name ns))]
(unparse-TCResult r)))
(defmethod unparse-type* TCResult
[v]
(unparse-TCResult v))
(indu/add-indirection ind/unparse-type unparse-type)
|
2803c565d80e2591e3cc0c183698ac9b262c5d117085cab7fe05d4d91e374514 | schell/odin | NextT.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
{-# LANGUAGE TypeFamilies #-}
module Control.Monad.Trans.NextT
( module Control.Monad.Trans.NextT
, NonEmpty(..)
, MonadMask(..)
) where
import Control.Monad.Catch (MonadCatch (..), MonadMask (..),
MonadThrow (..))
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
--------------------------------------------------------------------------------
-- Class
--------------------------------------------------------------------------------
class Monad m => MonadNext m where
--type Base (m :: * -> *) :: * -> *
-- | Done this loop immediately, returning a value.
done :: a -> m a
-- | Yield a computation to return to later (next frame).
next :: m a -> m a
-- | Run a computation to get either a value (in the case the loop done) or a
-- computation to run later.
runNext :: m a -> m (Either a (m a))
| A concrete implementation of MonadNext .
newtype NextT m b = NextT { runNextT :: m (Either b (NextT m b)) }
instance Monad m => MonadNext (NextT m) where
done = NextT . return . Left
next = NextT . return . Right
runNext = lift . runNextT
--instance OdinReader
--------------------------------------------------------------------------------
-- Instances
--------------------------------------------------------------------------------
instance Monad m => Functor (NextT m) where
fmap f (NextT g) = NextT $ g >>= \case
Right ev -> return $ Right $ fmap f ev
Left c -> return $ Left $ f c
instance Monad m => Applicative (NextT m) where
pure = done
ef <*> ex = do
f <- ef
x <- ex
return $ f x
instance Monad m => Monad (NextT m) where
(NextT g) >>= fev = NextT $ g >>= \case
Right ev -> return $ Right $ ev >>= fev
Left c -> runNextT $ fev c
return = done
instance MonadTrans NextT where
lift f = NextT $ f >>= return . Left
instance MonadIO m => MonadIO (NextT m) where
liftIO = lift . liftIO
instance MonadThrow m => MonadThrow (NextT m) where
throwM = lift . throwM
instance MonadCatch m => MonadCatch (NextT m) where
catch f h = catch f h
instance MonadMask m => MonadMask (NextT m) where
mask = mask
uninterruptibleMask = uninterruptibleMask
--------------------------------------------------------------------------------
-- Combinators
--------------------------------------------------------------------------------
-- | Wait some number of frames.
wait :: MonadNext m => Int -> m ()
wait 0 = done ()
wait n = next $ wait $ n - 1
-- | Runs both evented computations (left and then right) each frame and returns
the first computation that completes .
withEither :: MonadNext m => m a -> m b -> m (Either a b)
withEither ea eb = ((,) <$> runNext ea <*> runNext eb) >>= \case
( Left a, _) -> done $ Left a
( _, Left b) -> done $ Right b
(Right a, Right b) -> next $ withEither a b
-- | Runs all evented computations (left to right) on each frame and returns
the first computation that completes .
withAny :: MonadNext m => NonEmpty (m a) -> m a
withAny ts = go [] ts
where go xs (y :| []) = runNext y >>= \case
Left a -> done a
Right f -> next $ withAny $ NE.fromList $ xs ++ [f]
go xs (y :| (z:zs)) = runNext y >>= \case
Left a -> done a
Right f -> go (xs ++ [f]) (z :| zs)
| null | https://raw.githubusercontent.com/schell/odin/97ae1610a7abd19aa150bc7dfc132082d88ca9ea/odin-engine/src/Control/Monad/Trans/NextT.hs | haskell | # LANGUAGE TypeFamilies #
------------------------------------------------------------------------------
Class
------------------------------------------------------------------------------
type Base (m :: * -> *) :: * -> *
| Done this loop immediately, returning a value.
| Yield a computation to return to later (next frame).
| Run a computation to get either a value (in the case the loop done) or a
computation to run later.
instance OdinReader
------------------------------------------------------------------------------
Instances
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Combinators
------------------------------------------------------------------------------
| Wait some number of frames.
| Runs both evented computations (left and then right) each frame and returns
| Runs all evented computations (left to right) on each frame and returns | # LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
module Control.Monad.Trans.NextT
( module Control.Monad.Trans.NextT
, NonEmpty(..)
, MonadMask(..)
) where
import Control.Monad.Catch (MonadCatch (..), MonadMask (..),
MonadThrow (..))
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
class Monad m => MonadNext m where
done :: a -> m a
next :: m a -> m a
runNext :: m a -> m (Either a (m a))
| A concrete implementation of MonadNext .
newtype NextT m b = NextT { runNextT :: m (Either b (NextT m b)) }
instance Monad m => MonadNext (NextT m) where
done = NextT . return . Left
next = NextT . return . Right
runNext = lift . runNextT
instance Monad m => Functor (NextT m) where
fmap f (NextT g) = NextT $ g >>= \case
Right ev -> return $ Right $ fmap f ev
Left c -> return $ Left $ f c
instance Monad m => Applicative (NextT m) where
pure = done
ef <*> ex = do
f <- ef
x <- ex
return $ f x
instance Monad m => Monad (NextT m) where
(NextT g) >>= fev = NextT $ g >>= \case
Right ev -> return $ Right $ ev >>= fev
Left c -> runNextT $ fev c
return = done
instance MonadTrans NextT where
lift f = NextT $ f >>= return . Left
instance MonadIO m => MonadIO (NextT m) where
liftIO = lift . liftIO
instance MonadThrow m => MonadThrow (NextT m) where
throwM = lift . throwM
instance MonadCatch m => MonadCatch (NextT m) where
catch f h = catch f h
instance MonadMask m => MonadMask (NextT m) where
mask = mask
uninterruptibleMask = uninterruptibleMask
wait :: MonadNext m => Int -> m ()
wait 0 = done ()
wait n = next $ wait $ n - 1
the first computation that completes .
withEither :: MonadNext m => m a -> m b -> m (Either a b)
withEither ea eb = ((,) <$> runNext ea <*> runNext eb) >>= \case
( Left a, _) -> done $ Left a
( _, Left b) -> done $ Right b
(Right a, Right b) -> next $ withEither a b
the first computation that completes .
withAny :: MonadNext m => NonEmpty (m a) -> m a
withAny ts = go [] ts
where go xs (y :| []) = runNext y >>= \case
Left a -> done a
Right f -> next $ withAny $ NE.fromList $ xs ++ [f]
go xs (y :| (z:zs)) = runNext y >>= \case
Left a -> done a
Right f -> go (xs ++ [f]) (z :| zs)
|
30d138ab4bf8f8fb034b10eb30272efc027bb0c965e301de132eaa5ec3c707f0 | S8A/htdp-exercises | ex483.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 ex483) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp")) #f)))
(define QUEENS 8)
A QP is a structure :
; (make-posn CI CI)
A CI is an N in [ 0,QUEENS ) .
; interpretation (make-posn c r) denotes the square at
the r - th row and c - th column
(define-struct sqp [x y threatened])
; A Board is a [List-of Square]
A Square Position ( Sqp ) is a structure : ( make - sqp N N Boolean )
; interpretation the position of a square and whether it is
; threatened or not.
; data examples: QP
(define 0-1 (make-posn 0 1))
(define 1-3 (make-posn 1 3))
(define 2-0 (make-posn 2 0))
(define 3-2 (make-posn 3 2))
; data examples: [List-of QP]
(define 4QUEEN-SOLUTION-1
(list (make-posn 0 1) (make-posn 1 3)
(make-posn 2 0) (make-posn 3 2)))
(define 4QUEEN-SOLUTION-2
(list (make-posn 0 2) (make-posn 1 0)
(make-posn 2 3) (make-posn 3 1)))
(define loq1 (list (make-posn 0 1) (make-posn 0 0)
(make-posn 1 2) (make-posn 3 0)))
; N -> [Maybe [List-of QP]]
; finds a solution to the n queens problem
(define (n-queens n)
(place-queens (board0 n) n))
(check-expect (n-queens 2) #false)
(check-expect (n-queens 3) #false)
(check-satisfied (n-queens 4) (n-queens-solution? 4))
(check-satisfied (n-queens 4) is-queens-result?)
; Board N -> [Maybe [List-of QP]]
; places n queens on board; otherwise, returns #false
(define (place-queens a-board n)
(cond
[(zero? n) '()]
[(positive? n)
(local ((define available (find-open-spots a-board))
(define result (place-queens/list a-board available n)))
result)]))
; Board [List-of QP] N -> [Maybe [List-of QP]]
; places n queens on board starting from a position from the list;
; otherwise, returns false
(define (place-queens/list a-board positions n)
(cond
[(empty? positions) #false]
[(cons? positions)
(local ((define new-board (add-queen a-board (first positions)))
(define next (place-queens new-board (sub1 n))))
(if (false? next)
(place-queens/list a-board (rest positions) n)
(cons (first positions) next)))]))
N - > Board
; creates the initial n by n board
(define (board0 n)
(foldr (lambda (y rest-pairs)
(append (build-list n (lambda (x) (make-sqp x y #false)))
rest-pairs))
'() (build-list n (lambda (y) y))))
(check-expect (board0 0) '())
(check-expect (board0 1) (list (make-sqp 0 0 #false)))
(check-expect (board0 3) (list (make-sqp 0 0 #false)
(make-sqp 1 0 #false)
(make-sqp 2 0 #false)
(make-sqp 0 1 #false)
(make-sqp 1 1 #false)
(make-sqp 2 1 #false)
(make-sqp 0 2 #false)
(make-sqp 1 2 #false)
(make-sqp 2 2 #false)))
Board QP - > Board
; places a queen at qp on a-board
(define (add-queen a-board qp)
(map (lambda (sq)
(make-sqp (sqp-x sq) (sqp-y sq)
(or (sqp-threatened sq) (threatening? qp (sqp-posn sq)))))
a-board))
(check-expect (add-queen (board0 0) (make-posn 0 0)) '())
(check-expect (add-queen (board0 1) (make-posn 0 0))
(list (make-sqp 0 0 #true)))
(check-expect (add-queen (board0 3) (make-posn 2 1))
(list (make-sqp 0 0 #false)
(make-sqp 1 0 #true)
(make-sqp 2 0 #true)
(make-sqp 0 1 #true)
(make-sqp 1 1 #true)
(make-sqp 2 1 #true)
(make-sqp 0 2 #false)
(make-sqp 1 2 #true)
(make-sqp 2 2 #true)))
; Board -> [List-of QP]
; finds spots where it is still safe to place a queen
(define (find-open-spots a-board)
(map sqp-posn
(filter (lambda (sq) (false? (sqp-threatened sq))) a-board)))
(check-expect (find-open-spots (board0 0)) '())
(check-expect (find-open-spots (board0 1)) (list (make-posn 0 0)))
(check-expect (find-open-spots (list (make-sqp 0 0 #false)
(make-sqp 1 0 #true)
(make-sqp 2 0 #true)
(make-sqp 0 1 #true)
(make-sqp 1 1 #true)
(make-sqp 2 1 #true)
(make-sqp 0 2 #false)
(make-sqp 1 2 #true)
(make-sqp 2 2 #true)))
(list (make-posn 0 0) (make-posn 0 2)))
; Square -> GP
; gets the position of the given square
(define (sqp-posn sq)
(make-posn (sqp-x sq) (sqp-y sq)))
(check-expect (sqp-posn (make-sqp 2 1 #false)) (make-posn 2 1))
(check-expect (sqp-posn (make-sqp 3 5 #true)) (make-posn 3 5))
; N -> [[List-of QP] -> Boolean]
; produces a test that determines whether some list of queen positions
; is a valid solution to the puzzle
(define (n-queens-solution? n)
(lambda (loq)
(cond
[(false? loq) #false]
[(cons? loq)
(local ((define pairs
(foldr (lambda (q1 rest-of-pairs)
(append (foldr (lambda (q2 rest)
(if (equal? q1 q2)
rest
(cons (list q1 q2) rest)))
'() loq)
rest-of-pairs))
'() loq)))
(and (= (length loq) n)
(andmap (lambda (pair)
(not (threatening? (first pair) (second pair))))
pairs)))])))
(check-expect ((n-queens-solution? 4) 4QUEEN-SOLUTION-2) #true)
(check-expect ((n-queens-solution? 4) loq1) #false)
(check-expect ((n-queens-solution? 3) loq1) #false)
; [List-of QP] -> Boolean
is the result equal [ as a set ] to one of two lists
(define (is-queens-result? x)
(or (set=? 4QUEEN-SOLUTION-1 x)
(set=? 4QUEEN-SOLUTION-2 x)))
(check-expect (is-queens-result? 4QUEEN-SOLUTION-1) #true)
(check-expect (is-queens-result? 4QUEEN-SOLUTION-2) #true)
(check-expect (is-queens-result? loq1) #false)
; [List-of X] [List-of X] -> Boolean
; determines whether the given lsits contain the same items, regardless
; of order
(define (set=? l1 l2)
(and (= (length l1) (length l2))
(andmap (lambda (i1) (member? i1 l2)) l1)
(andmap (lambda (i2) (member? i2 l1)) l2)))
(check-expect (set=? '(a b c d) '(a b c)) #false)
(check-expect (set=? '(a b c) '(a b c d)) #false)
(check-expect (set=? '(a b c d) '(d b a c)) #true)
; QP QP -> Boolean
determines whether two queens placed on the given squares would
; threaten each other
(define (threatening? qp1 qp2)
(local ((define qp1x (posn-x qp1))
(define qp1y (posn-y qp1))
(define qp2x (posn-x qp2))
(define qp2y (posn-y qp2))
(define same-row? (= qp1y qp2y))
(define same-col? (= qp1x qp2x))
(define same-first-diagonal?
(= (- qp1x qp1y) (- qp2x qp2y)))
(define same-second-diagonal?
(= (+ qp1x qp1y) (+ qp2x qp2y))))
(or same-row? same-col? same-first-diagonal? same-second-diagonal?)))
(check-expect (threatening? (make-posn 0 0) (make-posn 1 2)) #false)
(check-expect (threatening? (make-posn 1 0) (make-posn 1 2)) #true)
(check-expect (threatening? (make-posn 0 2) (make-posn 1 2)) #true)
(check-expect (threatening? (make-posn 3 0) (make-posn 1 2)) #true)
(define SQUARE-SIZE 20) ; side length of each square in pixels
(define HALF-SQUARE-SIZE (/ SQUARE-SIZE 2))
(define WSQ (square SQUARE-SIZE "solid" "white"))
(define BSQ (square SQUARE-SIZE "solid" "black"))
(define OUTER-RADIUS (* 2/5 SQUARE-SIZE))
(define INNER-RADIUS (* 3/4 OUTER-RADIUS))
(define QUEEN
(overlay (radial-star QUEENS INNER-RADIUS OUTER-RADIUS "solid" "black")
(radial-star QUEENS INNER-RADIUS OUTER-RADIUS "outline" "white")))
; N [List-of QP] Image -> Image
; renders the image of a chessboard of size nxn with the given
; image placed according to the given queen positions
(define (render-queens n loq queen-image)
(foldr (lambda (q img)
(place-image queen-image
(queen-px-distance (posn-x q))
(queen-px-distance (posn-y q))
img))
(render-chessboard n WSQ BSQ) loq))
(check-expect
(render-queens 4 (rest loq1) QUEEN)
(place-image QUEEN (queen-px-distance 0) (queen-px-distance 0)
(place-image QUEEN (queen-px-distance 1) (queen-px-distance 2)
(place-image QUEEN
(queen-px-distance 3)
(queen-px-distance 0)
(render-chessboard 4 WSQ BSQ)))))
; N -> Image
; renders a chessboard of size nxn using the given
; square images
(define (render-chessboard n white-square-img black-square-img)
(foldr above empty-image
(build-list n
(lambda (row)
(local ((define white-pos? (if (odd? row) odd? even?)))
(foldr beside empty-image
(build-list n
(lambda (col)
(if (white-pos? col)
white-square-img
black-square-img)))))))))
(check-expect (render-chessboard 0 WSQ BSQ) empty-image)
(check-expect (render-chessboard 2 WSQ BSQ)
(above (beside WSQ BSQ) (beside BSQ WSQ)))
; N -> Number
; converts the given distance in squares to the correct distance in pixels
(define (queen-px-distance d)
(+ HALF-SQUARE-SIZE (* SQUARE-SIZE d)))
(check-expect (queen-px-distance 0) HALF-SQUARE-SIZE)
(check-expect (queen-px-distance 5) (+ HALF-SQUARE-SIZE (* SQUARE-SIZE 5)))
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex483.rkt | racket | about the language level of this file in a form that our tools can easily process.
(make-posn CI CI)
interpretation (make-posn c r) denotes the square at
A Board is a [List-of Square]
interpretation the position of a square and whether it is
threatened or not.
data examples: QP
data examples: [List-of QP]
N -> [Maybe [List-of QP]]
finds a solution to the n queens problem
Board N -> [Maybe [List-of QP]]
places n queens on board; otherwise, returns #false
Board [List-of QP] N -> [Maybe [List-of QP]]
places n queens on board starting from a position from the list;
otherwise, returns false
creates the initial n by n board
places a queen at qp on a-board
Board -> [List-of QP]
finds spots where it is still safe to place a queen
Square -> GP
gets the position of the given square
N -> [[List-of QP] -> Boolean]
produces a test that determines whether some list of queen positions
is a valid solution to the puzzle
[List-of QP] -> Boolean
[List-of X] [List-of X] -> Boolean
determines whether the given lsits contain the same items, regardless
of order
QP QP -> Boolean
threaten each other
side length of each square in pixels
N [List-of QP] Image -> Image
renders the image of a chessboard of size nxn with the given
image placed according to the given queen positions
N -> Image
renders a chessboard of size nxn using the given
square images
N -> Number
converts the given distance in squares to the correct distance in pixels | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex483) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp")) #f)))
(define QUEENS 8)
A QP is a structure :
A CI is an N in [ 0,QUEENS ) .
the r - th row and c - th column
(define-struct sqp [x y threatened])
A Square Position ( Sqp ) is a structure : ( make - sqp N N Boolean )
(define 0-1 (make-posn 0 1))
(define 1-3 (make-posn 1 3))
(define 2-0 (make-posn 2 0))
(define 3-2 (make-posn 3 2))
(define 4QUEEN-SOLUTION-1
(list (make-posn 0 1) (make-posn 1 3)
(make-posn 2 0) (make-posn 3 2)))
(define 4QUEEN-SOLUTION-2
(list (make-posn 0 2) (make-posn 1 0)
(make-posn 2 3) (make-posn 3 1)))
(define loq1 (list (make-posn 0 1) (make-posn 0 0)
(make-posn 1 2) (make-posn 3 0)))
(define (n-queens n)
(place-queens (board0 n) n))
(check-expect (n-queens 2) #false)
(check-expect (n-queens 3) #false)
(check-satisfied (n-queens 4) (n-queens-solution? 4))
(check-satisfied (n-queens 4) is-queens-result?)
(define (place-queens a-board n)
(cond
[(zero? n) '()]
[(positive? n)
(local ((define available (find-open-spots a-board))
(define result (place-queens/list a-board available n)))
result)]))
(define (place-queens/list a-board positions n)
(cond
[(empty? positions) #false]
[(cons? positions)
(local ((define new-board (add-queen a-board (first positions)))
(define next (place-queens new-board (sub1 n))))
(if (false? next)
(place-queens/list a-board (rest positions) n)
(cons (first positions) next)))]))
N - > Board
(define (board0 n)
(foldr (lambda (y rest-pairs)
(append (build-list n (lambda (x) (make-sqp x y #false)))
rest-pairs))
'() (build-list n (lambda (y) y))))
(check-expect (board0 0) '())
(check-expect (board0 1) (list (make-sqp 0 0 #false)))
(check-expect (board0 3) (list (make-sqp 0 0 #false)
(make-sqp 1 0 #false)
(make-sqp 2 0 #false)
(make-sqp 0 1 #false)
(make-sqp 1 1 #false)
(make-sqp 2 1 #false)
(make-sqp 0 2 #false)
(make-sqp 1 2 #false)
(make-sqp 2 2 #false)))
Board QP - > Board
(define (add-queen a-board qp)
(map (lambda (sq)
(make-sqp (sqp-x sq) (sqp-y sq)
(or (sqp-threatened sq) (threatening? qp (sqp-posn sq)))))
a-board))
(check-expect (add-queen (board0 0) (make-posn 0 0)) '())
(check-expect (add-queen (board0 1) (make-posn 0 0))
(list (make-sqp 0 0 #true)))
(check-expect (add-queen (board0 3) (make-posn 2 1))
(list (make-sqp 0 0 #false)
(make-sqp 1 0 #true)
(make-sqp 2 0 #true)
(make-sqp 0 1 #true)
(make-sqp 1 1 #true)
(make-sqp 2 1 #true)
(make-sqp 0 2 #false)
(make-sqp 1 2 #true)
(make-sqp 2 2 #true)))
(define (find-open-spots a-board)
(map sqp-posn
(filter (lambda (sq) (false? (sqp-threatened sq))) a-board)))
(check-expect (find-open-spots (board0 0)) '())
(check-expect (find-open-spots (board0 1)) (list (make-posn 0 0)))
(check-expect (find-open-spots (list (make-sqp 0 0 #false)
(make-sqp 1 0 #true)
(make-sqp 2 0 #true)
(make-sqp 0 1 #true)
(make-sqp 1 1 #true)
(make-sqp 2 1 #true)
(make-sqp 0 2 #false)
(make-sqp 1 2 #true)
(make-sqp 2 2 #true)))
(list (make-posn 0 0) (make-posn 0 2)))
(define (sqp-posn sq)
(make-posn (sqp-x sq) (sqp-y sq)))
(check-expect (sqp-posn (make-sqp 2 1 #false)) (make-posn 2 1))
(check-expect (sqp-posn (make-sqp 3 5 #true)) (make-posn 3 5))
(define (n-queens-solution? n)
(lambda (loq)
(cond
[(false? loq) #false]
[(cons? loq)
(local ((define pairs
(foldr (lambda (q1 rest-of-pairs)
(append (foldr (lambda (q2 rest)
(if (equal? q1 q2)
rest
(cons (list q1 q2) rest)))
'() loq)
rest-of-pairs))
'() loq)))
(and (= (length loq) n)
(andmap (lambda (pair)
(not (threatening? (first pair) (second pair))))
pairs)))])))
(check-expect ((n-queens-solution? 4) 4QUEEN-SOLUTION-2) #true)
(check-expect ((n-queens-solution? 4) loq1) #false)
(check-expect ((n-queens-solution? 3) loq1) #false)
is the result equal [ as a set ] to one of two lists
(define (is-queens-result? x)
(or (set=? 4QUEEN-SOLUTION-1 x)
(set=? 4QUEEN-SOLUTION-2 x)))
(check-expect (is-queens-result? 4QUEEN-SOLUTION-1) #true)
(check-expect (is-queens-result? 4QUEEN-SOLUTION-2) #true)
(check-expect (is-queens-result? loq1) #false)
(define (set=? l1 l2)
(and (= (length l1) (length l2))
(andmap (lambda (i1) (member? i1 l2)) l1)
(andmap (lambda (i2) (member? i2 l1)) l2)))
(check-expect (set=? '(a b c d) '(a b c)) #false)
(check-expect (set=? '(a b c) '(a b c d)) #false)
(check-expect (set=? '(a b c d) '(d b a c)) #true)
determines whether two queens placed on the given squares would
(define (threatening? qp1 qp2)
(local ((define qp1x (posn-x qp1))
(define qp1y (posn-y qp1))
(define qp2x (posn-x qp2))
(define qp2y (posn-y qp2))
(define same-row? (= qp1y qp2y))
(define same-col? (= qp1x qp2x))
(define same-first-diagonal?
(= (- qp1x qp1y) (- qp2x qp2y)))
(define same-second-diagonal?
(= (+ qp1x qp1y) (+ qp2x qp2y))))
(or same-row? same-col? same-first-diagonal? same-second-diagonal?)))
(check-expect (threatening? (make-posn 0 0) (make-posn 1 2)) #false)
(check-expect (threatening? (make-posn 1 0) (make-posn 1 2)) #true)
(check-expect (threatening? (make-posn 0 2) (make-posn 1 2)) #true)
(check-expect (threatening? (make-posn 3 0) (make-posn 1 2)) #true)
(define HALF-SQUARE-SIZE (/ SQUARE-SIZE 2))
(define WSQ (square SQUARE-SIZE "solid" "white"))
(define BSQ (square SQUARE-SIZE "solid" "black"))
(define OUTER-RADIUS (* 2/5 SQUARE-SIZE))
(define INNER-RADIUS (* 3/4 OUTER-RADIUS))
(define QUEEN
(overlay (radial-star QUEENS INNER-RADIUS OUTER-RADIUS "solid" "black")
(radial-star QUEENS INNER-RADIUS OUTER-RADIUS "outline" "white")))
(define (render-queens n loq queen-image)
(foldr (lambda (q img)
(place-image queen-image
(queen-px-distance (posn-x q))
(queen-px-distance (posn-y q))
img))
(render-chessboard n WSQ BSQ) loq))
(check-expect
(render-queens 4 (rest loq1) QUEEN)
(place-image QUEEN (queen-px-distance 0) (queen-px-distance 0)
(place-image QUEEN (queen-px-distance 1) (queen-px-distance 2)
(place-image QUEEN
(queen-px-distance 3)
(queen-px-distance 0)
(render-chessboard 4 WSQ BSQ)))))
(define (render-chessboard n white-square-img black-square-img)
(foldr above empty-image
(build-list n
(lambda (row)
(local ((define white-pos? (if (odd? row) odd? even?)))
(foldr beside empty-image
(build-list n
(lambda (col)
(if (white-pos? col)
white-square-img
black-square-img)))))))))
(check-expect (render-chessboard 0 WSQ BSQ) empty-image)
(check-expect (render-chessboard 2 WSQ BSQ)
(above (beside WSQ BSQ) (beside BSQ WSQ)))
(define (queen-px-distance d)
(+ HALF-SQUARE-SIZE (* SQUARE-SIZE d)))
(check-expect (queen-px-distance 0) HALF-SQUARE-SIZE)
(check-expect (queen-px-distance 5) (+ HALF-SQUARE-SIZE (* SQUARE-SIZE 5)))
|
46a9f688db7f51adb89cc44005fbcd0496095cd7dc15e24e5de6aeda60a603fd | informatimago/lisp | xkcd.lisp | -*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE : xkcd.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; Builds an inverted index of xkcd.
;;;;
< PJB > < >
MODIFICATIONS
2014 - 10 - 22 < PJB > Created .
;;;;
;;;; Note: xmls-tools and parse-html don't agree on the format of
;;;; sexps representing xml/html attributes.
;;;;
;;;;LEGAL
AGPL3
;;;;
Copyright 2014 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details .
;;;;
You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see </>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(require :xmls-tools #P"~/src/public/lisp/future/xmls-tools.lisp")
(defpackage "COM.INFORMATIMAGO.XKCD"
(:use "COMMON-LISP"
"XMLS-TOOLS"
"QL-HTTP"
"COM.INFORMATIMAGO.COMMON-LISP.HTML-PARSER.PARSE-HTML"
"COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML-ENTITIES"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING")
(:export "UPDATE-XKCD-INDEX"
"XKCD")
(:documentation "
Builds an inverted index of xkcd.com comics, and let you search them by keyword.
Use XKCD to perform a keyword search on xkcd.com comics.
The first search will download all the xkcd html pages to build the index,
which is cached in ~/.cache/xkcd/.
The ulterior searches only hit the site once a day.
Example:
the first time ,
(xkcd \"standard\") ; in normal use.
Copyright Pascal J. Bourguignon 2014 - 2014
AGPL3
"))
(in-package "COM.INFORMATIMAGO.XKCD")
(defparameter *verbose* nil
"Print messages while processing.")
(defparameter *utf-8* (character-set-to-lisp-encoding :utf-8)
"The external-format for utf-8.")
(defparameter *last-day* 0
"A monotonically increasing integer representing the day of
publication of the last xkcd.com comic.")
(defparameter *raw-index* '()
"An a-list mapping xkcd indexes to a list of title and alt texts.")
(defparameter *inverted-index* nil
"A hash-table mapping words to xkcd indexes.")
(defun xkcd-url (index)
(format nil "/~D/" index))
(defun entity-text (entity)
(etypecase entity
(null '(""))
(cons (mapcan (function entity-text) (cddr entity)))
(string (list entity))))
(defun fetch-xkcd-raw-index (&optional (min 1) (max))
"Fetches the xkcd pages from min to max (or to the first 404
\(excluding index 404) and push new entires to *RAW-INDEX*."
(flet ((prepare-text (text)
(format nil "~{~A~^ ~}" (mapcar (function melt-entities) (entity-text text)))))
(loop
:with path = #p"/tmp/xkcd"
:for i :from min
:for url = (xkcd-url i)
:while (or (null max) (<= i max))
:do (handler-case
(progn
(fetch url path
:if-exists :supersede
:follow-redirects t
:quietly (not *verbose*))
(let* ((document (find :html (parse-html-file
path
:verbose nil
:external-format *utf-8*)
:key (lambda (item) (and (listp item) (first item)))))
( ctitle ( third ( first ( remove - if - not ( lambda ( entity )
( string= " ctitle " ( getf ( second entity ) : i d ) ) )
;; (find-children-tagged document :div)))))
)
(dolist (element (find-children-tagged document :img))
(let ((title (getf (element-attributes element) :title))
(alt (getf (element-attributes element) :alt)))
(when title
(pushnew (list i
;; (when ctitle (prepare-text ctitle))
(when alt (prepare-text alt))
(when title (prepare-text title)))
*raw-index*
:test (function equal)))))))
(unexpected-http-status (err)
(unless (and (= i 404) (= 404 (unexpected-http-status-code err)))
(error err)))))))
(defun tokenize (text)
"Returns a list of unique downcased words in text"
(remove-duplicates (loop
:with start = 0
:with len = (length text)
:for s = (position-if #'alphanumericp text :start start)
:for e = (and s (position-if-not #'alphanumericp text :start (1+ s)))
:while s
:collect (string-downcase (subseq text s e))
:while (and e (< e len))
:do (setq start e))
:test (function string=)))
(defun xkcd-file (name)
(let ((path (merge-pathnames (format nil ".cache/xkcd/~A.sexp" name) (user-homedir-pathname))))
(ensure-directories-exist path)
path))
(defmacro define-persistent-variable (name pathname &key external-format default-value)
(let ((vval (gensym)))
`(progn
(defun ,name ()
(sexp-file-contents ,pathname :external-format ,external-format
:if-does-not-exist ,default-value))
(defun (setf ,name) (,vval)
(setf (sexp-file-contents ,pathname :external-format ,external-format
:if-does-not-exist :create
:if-exists :supersede) ,vval)))))
(define-persistent-variable last-day (xkcd-file "last-day")
:external-format *utf-8* :default-value 0)
(define-persistent-variable raw-index (xkcd-file "raw-index")
:external-format *utf-8* :default-value nil)
(define-persistent-variable inverted-index (xkcd-file "inverted-index")
:external-format *utf-8* :default-value '(hash-table :test equal))
(defun current-day ()
(multiple-value-bind (se mi ho da mo ye) (decode-universal-time (get-universal-time) 0)
(declare (ignore se mi ho))
(+ (* (+ (* ye 100) mo) 100) da)))
(defun update-inverted-index ()
(let ((index (make-hash-table :test (function equal) :size (length *raw-index*))))
(loop :for (i ctitle title alt) :in *raw-index*
:do (loop :for word :in (nconc (tokenize ctitle) (tokenize title) (tokenize alt))
:do (pushnew i (gethash word index '()))))
(setf (inverted-index) (hash-table-to-sexp (setf *inverted-index* index)))))
(defun update-xkcd-index ()
"
DO: Load the indexes from the .cache; if the last data is older than
current day, then try to fetch a new item, and re-compute the
inverse index.
"
(setf *last-day* (or *last-day* (last-day))
*raw-index* (or *raw-index* (raw-index))
*inverted-index* (or *inverted-index* (sexp-to-hash-table (inverted-index))))
(when (< *last-day* (current-day))
(let ((old-length (length *raw-index*))
(min (1+ (reduce (function max) *raw-index* :initial-value 0 :key (function first)))))
(handler-case (fetch-xkcd-raw-index min)
(unexpected-http-status () nil))
(unless (= (length *raw-index*) old-length)
(setf (raw-index) *raw-index*)
(update-inverted-index)
(setf *last-day* (setf (last-day) (current-day)))))))
(defun raw-search (words)
(sort (remove-duplicates (mapcan (lambda (word) (copy-list (gethash word *inverted-index*))) words))
(function <)))
(defun xkcd-at (index)
(find index *raw-index* :key (function first)))
(defun xkcd (words &key (verbose nil))
"
DO: Prints a list of xkcd.com urls (along with alt text and title),
that contain at least one of the words.
RETURN: The list of urls.
"
(let ((*verbose* verbose))
(update-xkcd-index))
(mapcar (lambda (i)
(destructuring-bind (i alt title) (xkcd-at i)
(let ((url (xkcd-url i)))
(format t "~%~@{~@[- ~A~%~]~}~%"
url
(when alt (nsubseq (string-justify-left alt *print-right-margin* 2) 2))
(when title (nsubseq (string-justify-left title *print-right-margin* 2) 2)))
url)))
(etypecase words
(symbol (raw-search (tokenize (string words))))
(string (raw-search (tokenize words)))
(list (raw-search (mapcan (function tokenize) words))))))
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/future/xkcd.lisp | lisp | coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
Builds an inverted index of xkcd.
Note: xmls-tools and parse-html don't agree on the format of
sexps representing xml/html attributes.
LEGAL
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>.
**************************************************************************
in normal use.
(find-children-tagged document :div)))))
(when ctitle (prepare-text ctitle))
if the last data is older than
THE END ;;;; | FILE : xkcd.lisp
USER - INTERFACE :
< PJB > < >
MODIFICATIONS
2014 - 10 - 22 < PJB > Created .
AGPL3
Copyright 2014 - 2016
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(require :xmls-tools #P"~/src/public/lisp/future/xmls-tools.lisp")
(defpackage "COM.INFORMATIMAGO.XKCD"
(:use "COMMON-LISP"
"XMLS-TOOLS"
"QL-HTTP"
"COM.INFORMATIMAGO.COMMON-LISP.HTML-PARSER.PARSE-HTML"
"COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML-ENTITIES"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING")
(:export "UPDATE-XKCD-INDEX"
"XKCD")
(:documentation "
Builds an inverted index of xkcd.com comics, and let you search them by keyword.
Use XKCD to perform a keyword search on xkcd.com comics.
The first search will download all the xkcd html pages to build the index,
which is cached in ~/.cache/xkcd/.
The ulterior searches only hit the site once a day.
Example:
the first time ,
Copyright Pascal J. Bourguignon 2014 - 2014
AGPL3
"))
(in-package "COM.INFORMATIMAGO.XKCD")
(defparameter *verbose* nil
"Print messages while processing.")
(defparameter *utf-8* (character-set-to-lisp-encoding :utf-8)
"The external-format for utf-8.")
(defparameter *last-day* 0
"A monotonically increasing integer representing the day of
publication of the last xkcd.com comic.")
(defparameter *raw-index* '()
"An a-list mapping xkcd indexes to a list of title and alt texts.")
(defparameter *inverted-index* nil
"A hash-table mapping words to xkcd indexes.")
(defun xkcd-url (index)
(format nil "/~D/" index))
(defun entity-text (entity)
(etypecase entity
(null '(""))
(cons (mapcan (function entity-text) (cddr entity)))
(string (list entity))))
(defun fetch-xkcd-raw-index (&optional (min 1) (max))
"Fetches the xkcd pages from min to max (or to the first 404
\(excluding index 404) and push new entires to *RAW-INDEX*."
(flet ((prepare-text (text)
(format nil "~{~A~^ ~}" (mapcar (function melt-entities) (entity-text text)))))
(loop
:with path = #p"/tmp/xkcd"
:for i :from min
:for url = (xkcd-url i)
:while (or (null max) (<= i max))
:do (handler-case
(progn
(fetch url path
:if-exists :supersede
:follow-redirects t
:quietly (not *verbose*))
(let* ((document (find :html (parse-html-file
path
:verbose nil
:external-format *utf-8*)
:key (lambda (item) (and (listp item) (first item)))))
( ctitle ( third ( first ( remove - if - not ( lambda ( entity )
( string= " ctitle " ( getf ( second entity ) : i d ) ) )
)
(dolist (element (find-children-tagged document :img))
(let ((title (getf (element-attributes element) :title))
(alt (getf (element-attributes element) :alt)))
(when title
(pushnew (list i
(when alt (prepare-text alt))
(when title (prepare-text title)))
*raw-index*
:test (function equal)))))))
(unexpected-http-status (err)
(unless (and (= i 404) (= 404 (unexpected-http-status-code err)))
(error err)))))))
(defun tokenize (text)
"Returns a list of unique downcased words in text"
(remove-duplicates (loop
:with start = 0
:with len = (length text)
:for s = (position-if #'alphanumericp text :start start)
:for e = (and s (position-if-not #'alphanumericp text :start (1+ s)))
:while s
:collect (string-downcase (subseq text s e))
:while (and e (< e len))
:do (setq start e))
:test (function string=)))
(defun xkcd-file (name)
(let ((path (merge-pathnames (format nil ".cache/xkcd/~A.sexp" name) (user-homedir-pathname))))
(ensure-directories-exist path)
path))
(defmacro define-persistent-variable (name pathname &key external-format default-value)
(let ((vval (gensym)))
`(progn
(defun ,name ()
(sexp-file-contents ,pathname :external-format ,external-format
:if-does-not-exist ,default-value))
(defun (setf ,name) (,vval)
(setf (sexp-file-contents ,pathname :external-format ,external-format
:if-does-not-exist :create
:if-exists :supersede) ,vval)))))
(define-persistent-variable last-day (xkcd-file "last-day")
:external-format *utf-8* :default-value 0)
(define-persistent-variable raw-index (xkcd-file "raw-index")
:external-format *utf-8* :default-value nil)
(define-persistent-variable inverted-index (xkcd-file "inverted-index")
:external-format *utf-8* :default-value '(hash-table :test equal))
(defun current-day ()
(multiple-value-bind (se mi ho da mo ye) (decode-universal-time (get-universal-time) 0)
(declare (ignore se mi ho))
(+ (* (+ (* ye 100) mo) 100) da)))
(defun update-inverted-index ()
(let ((index (make-hash-table :test (function equal) :size (length *raw-index*))))
(loop :for (i ctitle title alt) :in *raw-index*
:do (loop :for word :in (nconc (tokenize ctitle) (tokenize title) (tokenize alt))
:do (pushnew i (gethash word index '()))))
(setf (inverted-index) (hash-table-to-sexp (setf *inverted-index* index)))))
(defun update-xkcd-index ()
"
current day, then try to fetch a new item, and re-compute the
inverse index.
"
(setf *last-day* (or *last-day* (last-day))
*raw-index* (or *raw-index* (raw-index))
*inverted-index* (or *inverted-index* (sexp-to-hash-table (inverted-index))))
(when (< *last-day* (current-day))
(let ((old-length (length *raw-index*))
(min (1+ (reduce (function max) *raw-index* :initial-value 0 :key (function first)))))
(handler-case (fetch-xkcd-raw-index min)
(unexpected-http-status () nil))
(unless (= (length *raw-index*) old-length)
(setf (raw-index) *raw-index*)
(update-inverted-index)
(setf *last-day* (setf (last-day) (current-day)))))))
(defun raw-search (words)
(sort (remove-duplicates (mapcan (lambda (word) (copy-list (gethash word *inverted-index*))) words))
(function <)))
(defun xkcd-at (index)
(find index *raw-index* :key (function first)))
(defun xkcd (words &key (verbose nil))
"
DO: Prints a list of xkcd.com urls (along with alt text and title),
that contain at least one of the words.
RETURN: The list of urls.
"
(let ((*verbose* verbose))
(update-xkcd-index))
(mapcar (lambda (i)
(destructuring-bind (i alt title) (xkcd-at i)
(let ((url (xkcd-url i)))
(format t "~%~@{~@[- ~A~%~]~}~%"
url
(when alt (nsubseq (string-justify-left alt *print-right-margin* 2) 2))
(when title (nsubseq (string-justify-left title *print-right-margin* 2) 2)))
url)))
(etypecase words
(symbol (raw-search (tokenize (string words))))
(string (raw-search (tokenize words)))
(list (raw-search (mapcan (function tokenize) words))))))
|
af7d4656d91458f63c6c88cd50a3a3b4cf3e29de7ce9016992d7e3eccb4fc782 | dustin/environ | gen_sup.erl | %%
%%
%%
-module(gen_sup).
-behavior(supervisor).
-export([init/1]).
Generic supervisor initialization
init([Rv|_Args]) -> {ok, Rv}.
| null | https://raw.githubusercontent.com/dustin/environ/a45e714752a38e0b67ebd7e8d0bf8fb0c74d7945/src/gen_sup.erl | erlang |
-module(gen_sup).
-behavior(supervisor).
-export([init/1]).
Generic supervisor initialization
init([Rv|_Args]) -> {ok, Rv}.
| |
6ea2661efc0b0b4637a0f2b12900c7abe01a1b9a615b6348bd712005aa76a4aa | caisah/sicp-exercises-and-examples | ex_2.2.scm | ;; Consider the problem of representing line segments in a plane. Each segment is
;; represented as a pair of points: a starting point and an ending point. Define a
;; constructor make-segment and selectors start-segment and end-segment that define
;; the representation of segments in terms of points. Furthermore, a point can be
;; represented as a pair of numbers: the x coordinate and the y coordinate. Accordingly,
;; specify a constructor make-point and selectors x-point and y-point that define this
;; representation. Finally, using your selectors and constructors, define a procedure
;; midpoint-segment that takes a line segment as argument and returns its midpoint
;; (the point whose coordinates are the average of the coordinates of the endpoints).
;; To try your procedures, you'll need a way to print points:
;; (define (print-point p)
;; (newline)
;; (display "(")
;; (display (x-point p))
;; (display ",")
;; (display (y-point p))
;; (display "("))
(define (new-point x y)
(cons x y))
(define (x-point p)
(car p))
(define (y-point p)
(cdr p))
(define (make-segment p1 p2)
(cons p1 p2))
(define (midpoint-segment s)
(new-point (/ (+ (car (car s)) (car (cdr s))) 2)
(/ (+ (cdr (car s)) (cdr (cdr s))) 2)))
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")"))
(define fpoint (new-point 1 1))
(define spoint (new-point 3 3))
(define seg (make-segment fpoint spoint))
(define mid (midpoint-segment seg))
(print-point mid)
| null | https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/2.1.2-abstraction_barriers/ex_2.2.scm | scheme | Consider the problem of representing line segments in a plane. Each segment is
represented as a pair of points: a starting point and an ending point. Define a
constructor make-segment and selectors start-segment and end-segment that define
the representation of segments in terms of points. Furthermore, a point can be
represented as a pair of numbers: the x coordinate and the y coordinate. Accordingly,
specify a constructor make-point and selectors x-point and y-point that define this
representation. Finally, using your selectors and constructors, define a procedure
midpoint-segment that takes a line segment as argument and returns its midpoint
(the point whose coordinates are the average of the coordinates of the endpoints).
To try your procedures, you'll need a way to print points:
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display "(")) |
(define (new-point x y)
(cons x y))
(define (x-point p)
(car p))
(define (y-point p)
(cdr p))
(define (make-segment p1 p2)
(cons p1 p2))
(define (midpoint-segment s)
(new-point (/ (+ (car (car s)) (car (cdr s))) 2)
(/ (+ (cdr (car s)) (cdr (cdr s))) 2)))
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")"))
(define fpoint (new-point 1 1))
(define spoint (new-point 3 3))
(define seg (make-segment fpoint spoint))
(define mid (midpoint-segment seg))
(print-point mid)
|
98b52a0a98fb990130094a1f39c7851e9affccad3c939c7a867c7201b79e066a | ucsd-progsys/230-wi19-web | Axiomatic.hs | {-@ LIQUID "--reflection" @-}
{-@ LIQUID "--ple" @-}
{-@ LIQUID "--diff" @-}
{- LIQUID "--short-names" @-}
TODO : to have to rewrite this annotation !
TODO : to have to rewrite this annotation !
--------------------------------------------------------------------------------
-- | Inspired by
--
--
--------------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
module Axiomatic where
import Prelude hiding ((++))
import ProofCombinators
import qualified State as S
import Expressions
import Imp
import BigStep hiding (And)
--------------------------------------------------------------------------------
{- | A Floyd-Hoare triple is of the form
{ P } c { Q }
where
- `P` and `Q` are assertions (think `BExp`) and
- `c` is a command (think `Com`)
A Floyd-Hoare triple states that
IF
* The program `c` is starts at a state where the *precondition* `P` is True, and
* The program finishes execution
THEN
* At the final state, the *postcondition* `Q` will also evaluate to True.
-}
| Lets paraphrase the following Hoare triples in English .
1 ) { True } c { X = 5 }
2 ) { X = m } c { X = m + 5 }
3 ) { X < = Y } c { Y < = X }
4 ) { True } c { False }
1) {True} c {X = 5}
2) {X = m} c {X = m + 5}
3) {X <= Y} c {Y <= X}
4) {True} c {False}
-}
--------------------------------------------------------------------------------
-- | The type `Assertion` formalizes the type for the
-- assertions (i.e. pre- and post-conditions) `P`, `Q`
-- appearing in the triples {P} c {Q}
type Assertion = BExp
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| Legitimate Triples
--------------------------------------------------------------------------------
Which of the following triples are " legit " i.e. , the claimed relation between
` pre`condition ` ` P ` , ` com`mand ` C ` , and ` post`condition ` Q ` is true ?
1 ) { True }
X < ~ 5
{ X = 5 }
2 ) { X = 2 }
X < ~ X + 1
{ X = 3 }
3 ) { True }
X < ~ 5 ;
Y < ~ 0
4 ) { True }
X < ~ 5 ;
Y < ~ X
{ Y = 5 }
5 ) { X = 2 & & X = 3 }
X < ~ 5
{ X = 0 }
6 ) { True }
SKIP
{ False }
7 ) { False }
SKIP
{ True }
8) { True }
WHILE True DO
SKIP
{ False }
9 ) { X = 0 }
WHILE X < = 0 DO
X < ~ X + 1
{ X = 1 }
10 ) { X = 1 }
WHILE not ( X < = 0 ) DO
X < ~ X + 1
{ X = 100 }
--------------------------------------------------------------------------------
Which of the following triples are "legit" i.e., the claimed relation between
`pre`condition` `P`, `com`mand `C`, and `post`condition `Q` is true?
1) {True}
X <~ 5
{X = 5}
2) {X = 2}
X <~ X + 1
{X = 3}
3) {True}
X <~ 5;
Y <~ 0
{X = 5}
4) {True}
X <~ 5;
Y <~ X
{Y = 5}
5) {X = 2 && X = 3}
X <~ 5
{X = 0}
6) {True}
SKIP
{False}
7) {False}
SKIP
{True}
8) {True}
WHILE True DO
SKIP
{False}
9) {X = 0}
WHILE X <= 0 DO
X <~ X + 1
{X = 1}
10) {X = 1}
WHILE not (X <= 0) DO
X <~ X + 1
{X = 100}
-}
--------------------------------------------------------------------------------
| ` Legit ` formalizes the notion of when a Floyd - Hoare triple is legitimate
--------------------------------------------------------------------------------
@ type Legit P C Q = s:{State | bval P s }
- > s ' : _ - > Prop ( BStep C s s ' )
- > { bval Q s ' }
@
-> s':_ -> Prop (BStep C s s')
-> {bval Q s'}
@-}
type Legit = State -> State -> BStep -> Proof
| { True } X < ~ 5 { X = 5 } ---------------------------------------------------
@ leg1 : : Legit tt ( Assign { " x " } ( N 5 ) ) ( Equal ( V { " x " } ) ( N 5 ) ) @
leg1 :: Legit
leg1 s s' (BAssign {})
= S.lemma_get_set "x" 5 s
| { True } X < ~ 5 ; y < - X { X = 5 } -------------------------------------------
@ leg3 : : Legit tt ( Seq ( Assign { " x " } ( N 5 ) ) ( Assign { " y " } ( V { " x " } ) ) ) ( Equal ( V { " y " } ) ( N 5 ) ) @
leg3 :: Legit
leg3 s s' (BSeq _ _ _ smid _ (BAssign {}) (BAssign {}))
= S.lemma_get_set "x" 5 s &&& S.lemma_get_set "y" 5 smid
| { False } X < ~ 5 { X = 0 } --------------------------------------------------
@ leg5 : : Legit ff ( Assign { " x " } ( N 5 ) ) ( Equal ( V { " x " } ) ( N 22 ) ) @
leg5 :: Legit
leg5 s s' _ = ()
--------------------------------------------------------------------------------
| Two simple facts about Floyd - Hoare Triples --------------------------------
--------------------------------------------------------------------------------
{-@ lem_post_true :: p:_ -> c:_ -> Legit p c tt @-}
lem_post_true :: Assertion -> Com -> Legit
lem_post_true p c = \s s' c_s_s' -> ()
{-@ lem_pre_false :: c:_ -> q:_ -> Legit ff c q @-}
lem_pre_false :: Com -> Assertion -> Legit
lem_pre_false c q = \s s' c_s_s' -> ()
-- | Assignment
{ Y = 1 } X < ~ Y { X = 1 }
{ X + Y = 1 } X < ~ X + Y { X = 1 }
{ a = 1 } X < ~ a { X = 1 }
| Lets fill in the blanks
{ ? ? ? }
x < ~ 3
{ x = = 3 }
{ ? ? ? }
x < ~ x + 1
{ x < = 5 }
{ ? ? ? }
x < ~ y + 1
{ 0 < = x & & x < = 5 }
{ ??? }
x <~ 3
{ x == 3 }
{ ??? }
x <~ x + 1
{ x <= 5 }
{ ??? }
x <~ y + 1
{ 0 <= x && x <= 5 }
-}
| To conclude that an arbitrary postcondition ` Q ` holds after
` x < ~ a ` , we need to assume that Q holds before ` x < ~ a `
but with all occurrences of ` x ` replaced by ` a ` in ` Q `
Lets revisit the example above :
{ ? ? ? }
x < ~ 3
{ x = = 3 }
{ ? ? ? }
x < ~ x + 1
{ x < = 5 }
{ ? ? ? }
x < ~ y + 1
{ 0 < = x & & x < = 5 }
`x <~ a`, we need to assume that Q holds before `x <~ a`
but with all occurrences of `x` replaced by `a` in `Q`
Lets revisit the example above:
{ ??? }
x <~ 3
{ x == 3 }
{ ??? }
x <~ x + 1
{ x <= 5 }
{ ??? }
x <~ y + 1
{ 0 <= x && x <= 5 }
-}
--------------------------------------------------------------------------------
-- | `Valid`ity of an assertion
--------------------------------------------------------------------------------
forall = = True
{-@ type Valid P = s:State -> { v: Proof | bval P s } @-}
type Valid = State -> Proof
x > = 0 || x < 0
@ : : p : _ - > Valid p - > ( ) @
checkValid :: Assertion -> Valid -> ()
checkValid p v = ()
x < = 0
ex0 = checkValid (e0 `bImp` e1) (\_ -> ())
where
e0 = (V "x") `Leq` (N 0)
e1 = ((V "x") `Minus` (N 1)) `Leq` (N 0)
x < = 0 = > x - 1 < = 0
e1 = e0 ` ` ( ( V " x " ` Minus ` N 1 ) ` Leq ` ( N 0 ) )
--------------------------------------------------------------------------------
-- | When does an assertion `Imply` another
--------------------------------------------------------------------------------
@ type Imply P Q = Valid ( Q ) @
10 < = x = > 5 < = x
@ v1 : : _ - > Imply ( ( N 10 ) ( V { " x " } ) ) ( ( N 5 ) ( V { " x " } ) ) @
v1 :: a -> Valid
v1 _ = \_ -> ()
-- (0 < x && 0 < y) ===> (0 < x + y)
@ v2 : : _ - > Imply ( ( ( N 0 ) ( V { " x " } ) ) ( ( N 0 ) ( V { " y " } ) ) )
( ( N 0 ) ( Plus ( V { " x " } ) ( V { " y " } ) ) )
@
(Leq (N 0) (Plus (V {"x"}) (V {"y"})))
@-}
v2 :: a -> Valid
v2 _ = \_ -> ()
--------------------------------------------------------------------------------
-- | The Floyd-Hoare proof system
--------------------------------------------------------------------------------
data FHP where
FH :: Assertion -> Com -> Assertion -> FHP
data FH where
FHSkip :: Assertion -> FH
FHAssign :: Assertion -> Vname -> AExp -> FH
FHSeq :: Assertion -> Com -> Assertion -> Com -> Assertion -> FH -> FH -> FH
FHIf :: Assertion -> Assertion -> BExp -> Com -> Com -> FH -> FH -> FH
FHWhile :: Assertion -> BExp -> Com -> FH -> FH
FHConPre :: Assertion -> Assertion -> Assertion -> Com -> Valid -> FH -> FH
FHConPost :: Assertion -> Assertion -> Assertion -> Com -> FH -> Valid -> FH
@ data FH where
FHSkip : : p : _
- > Prop ( FH p Skip p )
| FHAssign : : q : _ - > x : _ - > a : _
- > Prop ( FH ( bsubst x a q ) ( Assign x a ) q )
| FHSeq : : p : _ - > c1 : _ - > q : _ - > c2 : _ - > r : _
- > Prop ( FH p c1 q )
- > Prop ( FH q c2 r )
- > Prop ( FH p ( Seq c1 c2 ) r )
| FHIf : : p : _ - > q : _ - > b : _ - > c1 : _ - > c2 : _
- > Prop ( FH ( bAnd p b ) c1 q )
- > Prop ( FH ( bAnd p ( Not b ) ) c2 q )
- > Prop ( FH p ( If b c1 c2 ) q )
| FHWhile : : inv : _ - > b : _ - > c : _
- > Prop ( FH ( b ) c inv )
- > Prop ( FH inv ( While b c ) ( ( Not b ) ) )
| FHConPre : : p ' : _ - > p : _ - > q : _ - > c : _
- > Imply p ' p
- > Prop ( FH p c q )
- > Prop ( FH p ' c q )
| FHConPost : : p : _ - > q : _ - > q ' : _ - > c : _
- > Prop ( FH p c q )
- > Imply q q '
- > Prop ( FH p c q ' )
@
FHSkip :: p:_
-> Prop (FH p Skip p)
| FHAssign :: q:_ -> x:_ -> a:_
-> Prop (FH (bsubst x a q) (Assign x a) q)
| FHSeq :: p:_ -> c1:_ -> q:_ -> c2:_ -> r:_
-> Prop (FH p c1 q)
-> Prop (FH q c2 r)
-> Prop (FH p (Seq c1 c2) r)
| FHIf :: p:_ -> q:_ -> b:_ -> c1:_ -> c2:_
-> Prop (FH (bAnd p b) c1 q)
-> Prop (FH (bAnd p (Not b)) c2 q)
-> Prop (FH p (If b c1 c2) q)
| FHWhile :: inv:_ -> b:_ -> c:_
-> Prop (FH (bAnd inv b) c inv)
-> Prop (FH inv (While b c) (bAnd inv (Not b)))
| FHConPre :: p':_ -> p:_ -> q:_ -> c:_
-> Imply p' p
-> Prop (FH p c q)
-> Prop (FH p' c q)
| FHConPost :: p:_ -> q:_ -> q':_ -> c:_
-> Prop (FH p c q)
-> Imply q q'
-> Prop (FH p c q')
@-}
--------------------------------------------------------------------------------
| THEOREM : Soundness of Floyd - Hoare Logic
--------------------------------------------------------------------------------
: : p : _ - > c : _ - > q : _ - > Prop ( FH p c q ) - > Legit p c q
-- thm_legit_fh :: p:_ -> c:_ -> q:_ -> Legit p c q -> Prop (FH p c q)
--------------------------------------------------------------------------------
-- | Making FH Algorithmic: Verification Conditions
--------------------------------------------------------------------------------
data ICom
= ISkip -- skip
| IAssign Vname AExp -- x := a
| ISeq ICom ICom -- c1; c2
| IIf BExp ICom ICom -- if b then c1 else c2
| IWhile Assertion BExp ICom -- while {I} b c
deriving (Show)
{-@ reflect pre @-}
pre :: ICom -> Assertion -> Assertion
pre ISkip q = q
pre (IAssign x a) q = bsubst x a q
pre (ISeq c1 c2) q = pre c1 (pre c2 q)
pre (IIf b c1 c2) q = bIte b (pre c1 q) (pre c2 q)
pre (IWhile i _ _) _ = i
{-@ reflect vc @-}
vc :: ICom -> Assertion -> Assertion
vc ISkip _ = tt
vc (IAssign {}) _ = tt
vc (ISeq c1 c2) q = (vc c1 (pre c2 q)) `bAnd` (vc c2 q)
vc (IIf _ c1 c2) q = (vc c1 q) `bAnd` (vc c2 q)
{ i & & b } c { i }
((bAnd i (Not b)) `bImp` q ) `bAnd` -- { i & ~b} => Q
vc c i
{-@ reflect erase @-}
erase :: ICom -> Com
erase ISkip = Skip
erase (IAssign x a) = Assign x a
erase (ISeq c1 c2) = Seq (erase c1) (erase c2)
erase (IIf b c1 c2) = If b (erase c1) (erase c2)
erase (IWhile _ b c) = While b (erase c)
-----------------------------------------------------------------------------------
-- | THEOREM: Soundness of VC
-----------------------------------------------------------------------------------
-- thm_vc :: c:_ -> q:_ -> Valid (vc c q) -> Legit (pre c q) (erase c) q
-----------------------------------------------------------------------------------
-- | Extending the above to triples [HW]
-----------------------------------------------------------------------------------
{-@ reflect vc' @-}
vc' :: Assertion -> ICom -> Assertion -> Assertion
vc' p c q = bAnd (bImp p (pre c q)) (vc c q)
-----------------------------------------------------------------------------------
-- | THEOREM: Soundness of VC'
-----------------------------------------------------------------------------------
-- thm_vc' :: p:_ -> c:_ -> q:_ -> Valid (vc' p c q) -> Legit p (erase c) q
| null | https://raw.githubusercontent.com/ucsd-progsys/230-wi19-web/7f5fc5414886fae4e2382cd5a0e48f638be06f0f/src/Week10/Axiomatic.hs | haskell | @ LIQUID "--reflection" @
@ LIQUID "--ple" @
@ LIQUID "--diff" @
LIQUID "--short-names" @
------------------------------------------------------------------------------
| Inspired by
------------------------------------------------------------------------------
# LANGUAGE GADTs #
------------------------------------------------------------------------------
| A Floyd-Hoare triple is of the form
{ P } c { Q }
where
- `P` and `Q` are assertions (think `BExp`) and
- `c` is a command (think `Com`)
A Floyd-Hoare triple states that
IF
* The program `c` is starts at a state where the *precondition* `P` is True, and
* The program finishes execution
THEN
* At the final state, the *postcondition* `Q` will also evaluate to True.
------------------------------------------------------------------------------
| The type `Assertion` formalizes the type for the
assertions (i.e. pre- and post-conditions) `P`, `Q`
appearing in the triples {P} c {Q}
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-------------------------------------------------
-----------------------------------------
------------------------------------------------
------------------------------------------------------------------------------
------------------------------
------------------------------------------------------------------------------
@ lem_post_true :: p:_ -> c:_ -> Legit p c tt @
@ lem_pre_false :: c:_ -> q:_ -> Legit ff c q @
| Assignment
------------------------------------------------------------------------------
| `Valid`ity of an assertion
------------------------------------------------------------------------------
@ type Valid P = s:State -> { v: Proof | bval P s } @
------------------------------------------------------------------------------
| When does an assertion `Imply` another
------------------------------------------------------------------------------
(0 < x && 0 < y) ===> (0 < x + y)
------------------------------------------------------------------------------
| The Floyd-Hoare proof system
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
thm_legit_fh :: p:_ -> c:_ -> q:_ -> Legit p c q -> Prop (FH p c q)
------------------------------------------------------------------------------
| Making FH Algorithmic: Verification Conditions
------------------------------------------------------------------------------
skip
x := a
c1; c2
if b then c1 else c2
while {I} b c
@ reflect pre @
@ reflect vc @
{ i & ~b} => Q
@ reflect erase @
---------------------------------------------------------------------------------
| THEOREM: Soundness of VC
---------------------------------------------------------------------------------
thm_vc :: c:_ -> q:_ -> Valid (vc c q) -> Legit (pre c q) (erase c) q
---------------------------------------------------------------------------------
| Extending the above to triples [HW]
---------------------------------------------------------------------------------
@ reflect vc' @
---------------------------------------------------------------------------------
| THEOREM: Soundness of VC'
---------------------------------------------------------------------------------
thm_vc' :: p:_ -> c:_ -> q:_ -> Valid (vc' p c q) -> Legit p (erase c) q | TODO : to have to rewrite this annotation !
TODO : to have to rewrite this annotation !
module Axiomatic where
import Prelude hiding ((++))
import ProofCombinators
import qualified State as S
import Expressions
import Imp
import BigStep hiding (And)
| Lets paraphrase the following Hoare triples in English .
1 ) { True } c { X = 5 }
2 ) { X = m } c { X = m + 5 }
3 ) { X < = Y } c { Y < = X }
4 ) { True } c { False }
1) {True} c {X = 5}
2) {X = m} c {X = m + 5}
3) {X <= Y} c {Y <= X}
4) {True} c {False}
-}
type Assertion = BExp
| Legitimate Triples
Which of the following triples are " legit " i.e. , the claimed relation between
` pre`condition ` ` P ` , ` com`mand ` C ` , and ` post`condition ` Q ` is true ?
1 ) { True }
X < ~ 5
{ X = 5 }
2 ) { X = 2 }
X < ~ X + 1
{ X = 3 }
3 ) { True }
X < ~ 5 ;
Y < ~ 0
4 ) { True }
X < ~ 5 ;
Y < ~ X
{ Y = 5 }
5 ) { X = 2 & & X = 3 }
X < ~ 5
{ X = 0 }
6 ) { True }
SKIP
{ False }
7 ) { False }
SKIP
{ True }
8) { True }
WHILE True DO
SKIP
{ False }
9 ) { X = 0 }
WHILE X < = 0 DO
X < ~ X + 1
{ X = 1 }
10 ) { X = 1 }
WHILE not ( X < = 0 ) DO
X < ~ X + 1
{ X = 100 }
Which of the following triples are "legit" i.e., the claimed relation between
`pre`condition` `P`, `com`mand `C`, and `post`condition `Q` is true?
1) {True}
X <~ 5
{X = 5}
2) {X = 2}
X <~ X + 1
{X = 3}
3) {True}
X <~ 5;
Y <~ 0
{X = 5}
4) {True}
X <~ 5;
Y <~ X
{Y = 5}
5) {X = 2 && X = 3}
X <~ 5
{X = 0}
6) {True}
SKIP
{False}
7) {False}
SKIP
{True}
8) {True}
WHILE True DO
SKIP
{False}
9) {X = 0}
WHILE X <= 0 DO
X <~ X + 1
{X = 1}
10) {X = 1}
WHILE not (X <= 0) DO
X <~ X + 1
{X = 100}
-}
| ` Legit ` formalizes the notion of when a Floyd - Hoare triple is legitimate
@ type Legit P C Q = s:{State | bval P s }
- > s ' : _ - > Prop ( BStep C s s ' )
- > { bval Q s ' }
@
-> s':_ -> Prop (BStep C s s')
-> {bval Q s'}
@-}
type Legit = State -> State -> BStep -> Proof
@ leg1 : : Legit tt ( Assign { " x " } ( N 5 ) ) ( Equal ( V { " x " } ) ( N 5 ) ) @
leg1 :: Legit
leg1 s s' (BAssign {})
= S.lemma_get_set "x" 5 s
@ leg3 : : Legit tt ( Seq ( Assign { " x " } ( N 5 ) ) ( Assign { " y " } ( V { " x " } ) ) ) ( Equal ( V { " y " } ) ( N 5 ) ) @
leg3 :: Legit
leg3 s s' (BSeq _ _ _ smid _ (BAssign {}) (BAssign {}))
= S.lemma_get_set "x" 5 s &&& S.lemma_get_set "y" 5 smid
@ leg5 : : Legit ff ( Assign { " x " } ( N 5 ) ) ( Equal ( V { " x " } ) ( N 22 ) ) @
leg5 :: Legit
leg5 s s' _ = ()
lem_post_true :: Assertion -> Com -> Legit
lem_post_true p c = \s s' c_s_s' -> ()
lem_pre_false :: Com -> Assertion -> Legit
lem_pre_false c q = \s s' c_s_s' -> ()
{ Y = 1 } X < ~ Y { X = 1 }
{ X + Y = 1 } X < ~ X + Y { X = 1 }
{ a = 1 } X < ~ a { X = 1 }
| Lets fill in the blanks
{ ? ? ? }
x < ~ 3
{ x = = 3 }
{ ? ? ? }
x < ~ x + 1
{ x < = 5 }
{ ? ? ? }
x < ~ y + 1
{ 0 < = x & & x < = 5 }
{ ??? }
x <~ 3
{ x == 3 }
{ ??? }
x <~ x + 1
{ x <= 5 }
{ ??? }
x <~ y + 1
{ 0 <= x && x <= 5 }
-}
| To conclude that an arbitrary postcondition ` Q ` holds after
` x < ~ a ` , we need to assume that Q holds before ` x < ~ a `
but with all occurrences of ` x ` replaced by ` a ` in ` Q `
Lets revisit the example above :
{ ? ? ? }
x < ~ 3
{ x = = 3 }
{ ? ? ? }
x < ~ x + 1
{ x < = 5 }
{ ? ? ? }
x < ~ y + 1
{ 0 < = x & & x < = 5 }
`x <~ a`, we need to assume that Q holds before `x <~ a`
but with all occurrences of `x` replaced by `a` in `Q`
Lets revisit the example above:
{ ??? }
x <~ 3
{ x == 3 }
{ ??? }
x <~ x + 1
{ x <= 5 }
{ ??? }
x <~ y + 1
{ 0 <= x && x <= 5 }
-}
forall = = True
type Valid = State -> Proof
x > = 0 || x < 0
@ : : p : _ - > Valid p - > ( ) @
checkValid :: Assertion -> Valid -> ()
checkValid p v = ()
x < = 0
ex0 = checkValid (e0 `bImp` e1) (\_ -> ())
where
e0 = (V "x") `Leq` (N 0)
e1 = ((V "x") `Minus` (N 1)) `Leq` (N 0)
x < = 0 = > x - 1 < = 0
e1 = e0 ` ` ( ( V " x " ` Minus ` N 1 ) ` Leq ` ( N 0 ) )
@ type Imply P Q = Valid ( Q ) @
10 < = x = > 5 < = x
@ v1 : : _ - > Imply ( ( N 10 ) ( V { " x " } ) ) ( ( N 5 ) ( V { " x " } ) ) @
v1 :: a -> Valid
v1 _ = \_ -> ()
@ v2 : : _ - > Imply ( ( ( N 0 ) ( V { " x " } ) ) ( ( N 0 ) ( V { " y " } ) ) )
( ( N 0 ) ( Plus ( V { " x " } ) ( V { " y " } ) ) )
@
(Leq (N 0) (Plus (V {"x"}) (V {"y"})))
@-}
v2 :: a -> Valid
v2 _ = \_ -> ()
data FHP where
FH :: Assertion -> Com -> Assertion -> FHP
data FH where
FHSkip :: Assertion -> FH
FHAssign :: Assertion -> Vname -> AExp -> FH
FHSeq :: Assertion -> Com -> Assertion -> Com -> Assertion -> FH -> FH -> FH
FHIf :: Assertion -> Assertion -> BExp -> Com -> Com -> FH -> FH -> FH
FHWhile :: Assertion -> BExp -> Com -> FH -> FH
FHConPre :: Assertion -> Assertion -> Assertion -> Com -> Valid -> FH -> FH
FHConPost :: Assertion -> Assertion -> Assertion -> Com -> FH -> Valid -> FH
@ data FH where
FHSkip : : p : _
- > Prop ( FH p Skip p )
| FHAssign : : q : _ - > x : _ - > a : _
- > Prop ( FH ( bsubst x a q ) ( Assign x a ) q )
| FHSeq : : p : _ - > c1 : _ - > q : _ - > c2 : _ - > r : _
- > Prop ( FH p c1 q )
- > Prop ( FH q c2 r )
- > Prop ( FH p ( Seq c1 c2 ) r )
| FHIf : : p : _ - > q : _ - > b : _ - > c1 : _ - > c2 : _
- > Prop ( FH ( bAnd p b ) c1 q )
- > Prop ( FH ( bAnd p ( Not b ) ) c2 q )
- > Prop ( FH p ( If b c1 c2 ) q )
| FHWhile : : inv : _ - > b : _ - > c : _
- > Prop ( FH ( b ) c inv )
- > Prop ( FH inv ( While b c ) ( ( Not b ) ) )
| FHConPre : : p ' : _ - > p : _ - > q : _ - > c : _
- > Imply p ' p
- > Prop ( FH p c q )
- > Prop ( FH p ' c q )
| FHConPost : : p : _ - > q : _ - > q ' : _ - > c : _
- > Prop ( FH p c q )
- > Imply q q '
- > Prop ( FH p c q ' )
@
FHSkip :: p:_
-> Prop (FH p Skip p)
| FHAssign :: q:_ -> x:_ -> a:_
-> Prop (FH (bsubst x a q) (Assign x a) q)
| FHSeq :: p:_ -> c1:_ -> q:_ -> c2:_ -> r:_
-> Prop (FH p c1 q)
-> Prop (FH q c2 r)
-> Prop (FH p (Seq c1 c2) r)
| FHIf :: p:_ -> q:_ -> b:_ -> c1:_ -> c2:_
-> Prop (FH (bAnd p b) c1 q)
-> Prop (FH (bAnd p (Not b)) c2 q)
-> Prop (FH p (If b c1 c2) q)
| FHWhile :: inv:_ -> b:_ -> c:_
-> Prop (FH (bAnd inv b) c inv)
-> Prop (FH inv (While b c) (bAnd inv (Not b)))
| FHConPre :: p':_ -> p:_ -> q:_ -> c:_
-> Imply p' p
-> Prop (FH p c q)
-> Prop (FH p' c q)
| FHConPost :: p:_ -> q:_ -> q':_ -> c:_
-> Prop (FH p c q)
-> Imply q q'
-> Prop (FH p c q')
@-}
| THEOREM : Soundness of Floyd - Hoare Logic
: : p : _ - > c : _ - > q : _ - > Prop ( FH p c q ) - > Legit p c q
data ICom
deriving (Show)
pre :: ICom -> Assertion -> Assertion
pre ISkip q = q
pre (IAssign x a) q = bsubst x a q
pre (ISeq c1 c2) q = pre c1 (pre c2 q)
pre (IIf b c1 c2) q = bIte b (pre c1 q) (pre c2 q)
pre (IWhile i _ _) _ = i
vc :: ICom -> Assertion -> Assertion
vc ISkip _ = tt
vc (IAssign {}) _ = tt
vc (ISeq c1 c2) q = (vc c1 (pre c2 q)) `bAnd` (vc c2 q)
vc (IIf _ c1 c2) q = (vc c1 q) `bAnd` (vc c2 q)
{ i & & b } c { i }
vc c i
erase :: ICom -> Com
erase ISkip = Skip
erase (IAssign x a) = Assign x a
erase (ISeq c1 c2) = Seq (erase c1) (erase c2)
erase (IIf b c1 c2) = If b (erase c1) (erase c2)
erase (IWhile _ b c) = While b (erase c)
vc' :: Assertion -> ICom -> Assertion -> Assertion
vc' p c q = bAnd (bImp p (pre c q)) (vc c q)
|
d2cc747406d89bacd7ab5ca15a25c91cc61515f181d62b9f3dcd87ba6dea93cb | mini-monkey/mini-monkey | prop_user.erl | -module(prop_user).
-include_lib("proper/include/proper.hrl").
-import(mm_test_common, [setup/0,
allow_admin/2,
allow_subscribe/2,
allow_publish/2,
disallow_admin/2,
disallow_subscribe/2,
disallow_publish/2]).
%%%%%%%%%%%%%%%%%%
%%% Properties %%%
%%%%%%%%%%%%%%%%%%
prop_user_minimal_pub_sub_test() ->
?FORALL({Token1, Token2, Room, Content, Tag}, {blob(), blob(), blob(), blob(), blob()},
begin
%% setup the system
setup(),
mm_login:add_token(Token1),
mm_login:add_token(Token2),
%% make the connections
{ok, Sock1} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
{ok, Sock2} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
%% login both
true andalso
login(Sock1, Token1) andalso
login(Sock2, Token2) andalso
%% enter room
enter(Sock1, Room) andalso
enter(Sock2, Room) andalso
%% mock permissions
allow_subscribe(Room, Token1) andalso
allow_publish(Room, Token2) andalso
%% pub / sub
subscribe(Sock1, Tag) andalso
publish(Sock2, Content) andalso
%% receive messaage
receive_content(Sock1, Tag, Content) andalso
%% revoke permissions
disallow_subscribe(Room, Token1) andalso
disallow_publish(Room, Token2) andalso
%% make sure we cannot subscribe and publish
cannot_subscribe(Sock1, Tag) andalso
cannot_publish(Sock2, Content) andalso
%% clean-up
close(Sock1) andalso
close(Sock2)
end).
prop_admin_for_pub() ->
?FORALL({TokenAdmin, TokenPub, Room, Content}, {blob(), blob(), blob(), blob()},
begin
setup(),
mm_login:add_token(TokenAdmin),
mm_login:add_token(TokenPub),
%% make the connections
{ok, Sock1} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
{ok, Sock2} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
%% login both
true andalso
login(Sock1, TokenAdmin) andalso
login(Sock2, TokenPub) andalso
%% enter room
enter(Sock1, Room) andalso
enter(Sock2, Room) andalso
allow admin to admin ( using god_token )
allow_admin(Room, TokenAdmin) andalso
%% publisher cannot publish without permission
cannot_publish(Sock2, Content) andalso
%% allow publisher to publish using admin token
admin_publish(Sock1, TokenPub) andalso
%% publish a message
publish(Sock2, Content) andalso
%% clean-up
close(Sock1) andalso
close(Sock2)
end).
prop_admin_for_sub() ->
?FORALL({TokenAdmin, TokenSub, Room, Tag}, {blob(), blob(), blob(), blob()},
begin
setup(),
mm_login:add_token(TokenAdmin),
mm_login:add_token(TokenSub),
%% make the connections
{ok, Sock1} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
{ok, Sock2} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
%% login both
true andalso
login(Sock1, TokenAdmin) andalso
login(Sock2, TokenSub) andalso
%% enter room
enter(Sock1, Room) andalso
enter(Sock2, Room) andalso
allow admin to admin ( using god_token )
allow_admin(Room, TokenAdmin) andalso
%% publisher cannot publish without permission
cannot_subscribe(Sock2, Tag) andalso
%% allow publisher to publish using admin token
admin_subscribe(Sock1, TokenSub) andalso
%% publish a message
subscribe(Sock2, Tag) andalso
%% clean-up
close(Sock1) andalso
close(Sock2)
end).
prop_enter_without_login() ->
?FORALL({Token, Room}, {blob(), blob()},
begin
mm_test_common:setup(),
mm_login:add_token(Token),
%% make the connections
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
%% attempt to enter without logging in
cannot_enter(Sock, Token) andalso
%% login and succeed to enter
login(Sock, Token) andalso
enter(Sock, Room)
end).
prop_pub_without_enter() ->
?FORALL({Token, Content}, {blob(), blob()},
begin
mm_test_common:setup(),
mm_login:add_token(Token),
%% make the connections and login
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
login(Sock, Token) andalso
%% attempt to enter without logging in
room_error_for_publish(Sock, Content)
end).
%%%%%%%%%%%%%%%%%%
%%% Helpers %%%
%%%%%%%%%%%%%%%%%%
close(Sock) ->
ok =:= gen_tcp:close(Sock).
login(Sock, Token) ->
ok = gen_tcp:send(Sock, mm_encode:login(Token)),
{ok, mm_encode:login_successful()} =:= gen_tcp:recv(Sock, 0).
enter(Sock, Room) ->
ok = gen_tcp:send(Sock, mm_encode:enter(Room)),
{ok, mm_encode:enter_successful()} =:= gen_tcp:recv(Sock, 0).
cannot_enter(Sock, Room) ->
ok = gen_tcp:send(Sock, mm_encode:enter(Room)),
{ok, mm_encode:login_failure()} =:= gen_tcp:recv(Sock, 0).
subscribe(Sock, Tag) ->
ok = gen_tcp:send(Sock, mm_encode:subscribe(Tag)),
{ok, mm_encode:subscribe_successful()} =:= gen_tcp:recv(Sock, 0).
cannot_subscribe(Sock, Tag) ->
ok = gen_tcp:send(Sock, mm_encode:subscribe(Tag)),
{ok, mm_encode:subscribe_failure()} =:= gen_tcp:recv(Sock, 0).
publish(Sock, Content) ->
ok = gen_tcp:send(Sock, mm_encode:publish(Content)),
{ok, mm_encode:publish_successful()} =:= gen_tcp:recv(Sock, 0).
cannot_publish(Sock, Content) ->
ok = gen_tcp:send(Sock, mm_encode:publish(Content)),
{ok, mm_encode:publish_failure()} =:= gen_tcp:recv(Sock, 0).
receive_content(Sock, Tag, Content) ->
timer:sleep(10),
Payload1 = mm_encode:enter(Tag),
Payload2 = mm_encode:publish(Content),
{ok, <<Payload1/binary, Payload2/binary>>} =:= gen_tcp:recv(Sock, 0).
admin_publish(Sock, Token) ->
ok = gen_tcp:send(Sock, mm_encode:allow_publish(Token)),
{ok, mm_encode:permissions_successful()} =:= gen_tcp:recv(Sock, 0).
admin_subscribe(Sock, Token) ->
ok = gen_tcp:send(Sock, mm_encode:allow_subscribe(Token)),
{ok, mm_encode:permissions_successful()} =:= gen_tcp:recv(Sock, 0).
room_error_for_publish(Sock, Content) ->
ok = gen_tcp:send(Sock, mm_encode:publish(Content)),
{ok, mm_encode:room_failure()} =:= gen_tcp:recv(Sock, 0).
%%%%%%%%%%%%%%%%%%
%%% Generators %%%
%%%%%%%%%%%%%%%%%%
blob() ->
non_empty(binary()).
| null | https://raw.githubusercontent.com/mini-monkey/mini-monkey/4afa4385256c0f1d23db522c0725c3291a8c86c8/test/prop_user.erl | erlang |
Properties %%%
setup the system
make the connections
login both
enter room
mock permissions
pub / sub
receive messaage
revoke permissions
make sure we cannot subscribe and publish
clean-up
make the connections
login both
enter room
publisher cannot publish without permission
allow publisher to publish using admin token
publish a message
clean-up
make the connections
login both
enter room
publisher cannot publish without permission
allow publisher to publish using admin token
publish a message
clean-up
make the connections
attempt to enter without logging in
login and succeed to enter
make the connections and login
attempt to enter without logging in
Helpers %%%
Generators %%%
| -module(prop_user).
-include_lib("proper/include/proper.hrl").
-import(mm_test_common, [setup/0,
allow_admin/2,
allow_subscribe/2,
allow_publish/2,
disallow_admin/2,
disallow_subscribe/2,
disallow_publish/2]).
prop_user_minimal_pub_sub_test() ->
?FORALL({Token1, Token2, Room, Content, Tag}, {blob(), blob(), blob(), blob(), blob()},
begin
setup(),
mm_login:add_token(Token1),
mm_login:add_token(Token2),
{ok, Sock1} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
{ok, Sock2} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
true andalso
login(Sock1, Token1) andalso
login(Sock2, Token2) andalso
enter(Sock1, Room) andalso
enter(Sock2, Room) andalso
allow_subscribe(Room, Token1) andalso
allow_publish(Room, Token2) andalso
subscribe(Sock1, Tag) andalso
publish(Sock2, Content) andalso
receive_content(Sock1, Tag, Content) andalso
disallow_subscribe(Room, Token1) andalso
disallow_publish(Room, Token2) andalso
cannot_subscribe(Sock1, Tag) andalso
cannot_publish(Sock2, Content) andalso
close(Sock1) andalso
close(Sock2)
end).
prop_admin_for_pub() ->
?FORALL({TokenAdmin, TokenPub, Room, Content}, {blob(), blob(), blob(), blob()},
begin
setup(),
mm_login:add_token(TokenAdmin),
mm_login:add_token(TokenPub),
{ok, Sock1} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
{ok, Sock2} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
true andalso
login(Sock1, TokenAdmin) andalso
login(Sock2, TokenPub) andalso
enter(Sock1, Room) andalso
enter(Sock2, Room) andalso
allow admin to admin ( using god_token )
allow_admin(Room, TokenAdmin) andalso
cannot_publish(Sock2, Content) andalso
admin_publish(Sock1, TokenPub) andalso
publish(Sock2, Content) andalso
close(Sock1) andalso
close(Sock2)
end).
prop_admin_for_sub() ->
?FORALL({TokenAdmin, TokenSub, Room, Tag}, {blob(), blob(), blob(), blob()},
begin
setup(),
mm_login:add_token(TokenAdmin),
mm_login:add_token(TokenSub),
{ok, Sock1} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
{ok, Sock2} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
true andalso
login(Sock1, TokenAdmin) andalso
login(Sock2, TokenSub) andalso
enter(Sock1, Room) andalso
enter(Sock2, Room) andalso
allow admin to admin ( using god_token )
allow_admin(Room, TokenAdmin) andalso
cannot_subscribe(Sock2, Tag) andalso
admin_subscribe(Sock1, TokenSub) andalso
subscribe(Sock2, Tag) andalso
close(Sock1) andalso
close(Sock2)
end).
prop_enter_without_login() ->
?FORALL({Token, Room}, {blob(), blob()},
begin
mm_test_common:setup(),
mm_login:add_token(Token),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
cannot_enter(Sock, Token) andalso
login(Sock, Token) andalso
enter(Sock, Room)
end).
prop_pub_without_enter() ->
?FORALL({Token, Content}, {blob(), blob()},
begin
mm_test_common:setup(),
mm_login:add_token(Token),
{ok, Sock} = gen_tcp:connect("localhost", 1773, [binary, {active, false}]),
login(Sock, Token) andalso
room_error_for_publish(Sock, Content)
end).
close(Sock) ->
ok =:= gen_tcp:close(Sock).
login(Sock, Token) ->
ok = gen_tcp:send(Sock, mm_encode:login(Token)),
{ok, mm_encode:login_successful()} =:= gen_tcp:recv(Sock, 0).
enter(Sock, Room) ->
ok = gen_tcp:send(Sock, mm_encode:enter(Room)),
{ok, mm_encode:enter_successful()} =:= gen_tcp:recv(Sock, 0).
cannot_enter(Sock, Room) ->
ok = gen_tcp:send(Sock, mm_encode:enter(Room)),
{ok, mm_encode:login_failure()} =:= gen_tcp:recv(Sock, 0).
subscribe(Sock, Tag) ->
ok = gen_tcp:send(Sock, mm_encode:subscribe(Tag)),
{ok, mm_encode:subscribe_successful()} =:= gen_tcp:recv(Sock, 0).
cannot_subscribe(Sock, Tag) ->
ok = gen_tcp:send(Sock, mm_encode:subscribe(Tag)),
{ok, mm_encode:subscribe_failure()} =:= gen_tcp:recv(Sock, 0).
publish(Sock, Content) ->
ok = gen_tcp:send(Sock, mm_encode:publish(Content)),
{ok, mm_encode:publish_successful()} =:= gen_tcp:recv(Sock, 0).
cannot_publish(Sock, Content) ->
ok = gen_tcp:send(Sock, mm_encode:publish(Content)),
{ok, mm_encode:publish_failure()} =:= gen_tcp:recv(Sock, 0).
receive_content(Sock, Tag, Content) ->
timer:sleep(10),
Payload1 = mm_encode:enter(Tag),
Payload2 = mm_encode:publish(Content),
{ok, <<Payload1/binary, Payload2/binary>>} =:= gen_tcp:recv(Sock, 0).
admin_publish(Sock, Token) ->
ok = gen_tcp:send(Sock, mm_encode:allow_publish(Token)),
{ok, mm_encode:permissions_successful()} =:= gen_tcp:recv(Sock, 0).
admin_subscribe(Sock, Token) ->
ok = gen_tcp:send(Sock, mm_encode:allow_subscribe(Token)),
{ok, mm_encode:permissions_successful()} =:= gen_tcp:recv(Sock, 0).
room_error_for_publish(Sock, Content) ->
ok = gen_tcp:send(Sock, mm_encode:publish(Content)),
{ok, mm_encode:room_failure()} =:= gen_tcp:recv(Sock, 0).
blob() ->
non_empty(binary()).
|
257ab6c77a54c85efea4afa2762cb0350a199e11674b1b3ad17668516aec4ef8 | informatimago/lisp | annex-a.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.LANGUAGES.LINC")
(defparameter *ansi-c-grammar*
'(("(6.4)" token -->
keyword
identifier
constant
string-literal
punctuator)
("(6.4)" preprocessing-token -->
header-name
identifier
pp-number
character-constant
string-literal
punctuator
|each non-white-space character that cannot be one of the above|)
("(6.4.1)" keyword -->
|*|
|auto|
|break|
|case|
|char|
|const|
|continue|
|default|
|do|
|double|
|else|
|enum|
|extern|
|float|
|for|
|goto|
|if|
|inline|
|int|
|long|
|register|
|restrict|
|return|
|short|
|signed|
|sizeof|
|static|
|struct|
|switch|
|typedef|
|union|
|unsigned|
|void|
|volatile|
|while|
|_Alignas|
|_Alignof|
|_Atomic|
|_Bool|
|_Complex|
|_Generic|
|_Imaginary|
|_Noreturn|
|_Static_assert|
|_Thread_local|)
("(6.4.2.1)" identifier -->
identifier-nondigit
(identifier identifier-nondigit)
(identifier digit))
("(6.4.2.1)" identifier-nondigit -->
nondigit
universal-character-name
|other implementation-defined characters|)
("(6.4.2.1)" nondigit -->
\_
\a \b \c \d \e \f \g \h \i \j \k \l \m
\n \o \p \q \r \s \t \u \v \w \x \y \z
\A \B \C \D \E \F \G \H \I \J \K \L \M
\N \O \P \Q \R \S \T \U \V \W \X \Y \Z)
("(6.4.2.1)" digit -->
\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
("(6.4.3)" universal-character-name -->
(|\\u| hex-quad)
(|\\U| hex-quad hex-quad))
("(6.4.3)" hex-quad -->
(hexadecimal-digit hexadecimal-digit)
(hexadecimal-digit hexadecimal-digit))
("(6.4.4)" constant -->
integer-constant
floating-constant
enumeration-constant
character-constant)
("(6.4.4.1)" integer-constant -->
(decimal-constant (opt integer-suffix))
(octal-constant (opt integer-suffix))
(hexadecimal-constant (opt integer-suffix)))
("(6.4.4.1)" decimal-constant -->
nonzero-digit
(decimal-constant digit))
("(6.4.4.1)" octal-constant -->
\0
(octal-constant octal-digit))
("(6.4.4.1)" hexadecimal-constant -->
(hexadecimal-prefix hexadecimal-digit)
(hexadecimal-constant hexadecimal-digit))
("(6.4.4.1)" hexadecimal-prefix -->
|0x|
|0X|)
("(6.4.4.1)" nonzero-digit -->
\1 \2 \3 \4 \5 \6 \7 \8 \9)
("(6.4.4.1)" octal-digit -->
\0 \1 \2 \3 \4 \5 \6 \7)
("(6.4.4.1)" hexadecimal-digit -->
\0 \1 \2 \3 \4 \5 \6 \7 \8 \9
\a \b \c \d \e \f
\A \B \C \D \E \F)
("(6.4.4.1)" integer-suffix -->
(unsigned-suffix (opt long-suffix)) ; u ul
(unsigned-suffix long-long-suffix) ; ull
(long-suffix (opt unsigned-suffix)) ; lu
llu
("(6.4.4.1)" unsigned-suffix -->
\u
\U)
("(6.4.4.1)" long-suffix -->
\l
\L)
("(6.4.4.1)" long-long-suffix -->
|ll|
|LL|)
("(6.4.4.2)" floating-constant -->
decimal-floating-constant
hexadecimal-floating-constant)
("(6.4.4.2)" decimal-floating-constant -->
(fractional-constant (opt exponent-part) (opt floating-suffix))
(digit-sequence exponent-part (opt floating-suffix)))
("(6.4.4.2)" hexadecimal-floating-constant -->
(hexadecimal-prefix hexadecimal-fractional-constant binary-exponent-part (opt floating-suffix))
(hexadecimal-prefix hexadecimal-digit-sequence binary-exponent-part (opt floating-suffix)))
("(6.4.4.2)" fractional-constant -->
((opt digit-sequence) \. digit-sequence)
(digit-sequence \.))
("(6.4.4.2)" exponent-part -->
(|e| (opt sign) digit-sequence)
(|E| (opt sign) digit-sequence))
("(6.4.4.2)" sign -->
\+ \-)
("(6.4.4.2)" digit-sequence -->
digit
(digit-sequence digit))
("(6.4.4.2)" hexadecimal-fractional-constant -->
((opt hexadecimal-digit-sequence) \. hexadecimal-digit-sequence)
(hexadecimal-digit-sequence \.))
("(6.4.4.2)" binary-exponent-part -->
(|p| (opt sign) digit-sequence)
(|P| (opt sign) digit-sequence))
("(6.4.4.2)" hexadecimal-digit-sequence -->
hexadecimal-digit
(hexadecimal-digit-sequence hexadecimal-digit))
("(6.4.4.2)" floating-suffix -->
\f \l \F \L)
("(6.4.4.3)" enumeration-constant -->
identifier)
("(6.4.4.4)" character-constant -->
(\' c-char-sequence \')
(\L\' c-char-sequence \')
(\u\' c-char-sequence \')
(\U\' c-char-sequence \'))
("(6.4.4.4)" c-char-sequence -->
c-char
(c-char-sequence c-char))
("(6.4.4.4)" c-char -->
|any member of the source character set except the single-quote ', backslash \, or new-line character|
escape-sequence)
("(6.4.4.4)" escape-sequence -->
simple-escape-sequence
octal-escape-sequence
hexadecimal-escape-sequence
universal-character-name)
("(6.4.4.4)" simple-escape-sequence -->
\\\' \\\" \\\? \\\\ \\\a \\\b \\\f \\\n \\\r \\\t \\\v)
("(6.4.4.4)" octal-escape-sequence -->
(\\ octal-digit)
(\\ octal-digit octal-digit)
(\\ octal-digit octal-digit octal-digit))
("(6.4.4.4)" hexadecimal-escape-sequence -->
(|\\x| hexadecimal-digit)
(hexadecimal-escape-sequence hexadecimal-digit))
("(6.4.5)" string-literal -->
((opt encoding-prefix) \" (opt s-char-sequence) \"))
("(6.4.5)" encoding-prefix -->
|u8|
|u|
|U|
|L|)
("(6.4.5)" s-char-sequence -->
s-char
(s-char-sequence s-char))
("(6.4.5)" s-char -->
|any member of the source character set except the double-quote ", backslash \, or new-line character escape-sequence|)
("(6.4.6)" punctuator -->
\[ \] \( \) \{ \} \. \-\>
\+\+ \-\- \& \* \+ \- \~ \!
\/ \% \<\< \>\> \< \> \<\= \>\= \=\= \!\= \^ \| \&\& \|\|
\? \: \; \.\.\.
\= \*\= \/\= \%\= \+\= \-\= \<\<\= \>\>\= \&\= \^\= \|\=
\, \# \#\#
\<\: \:\> \<\% \%\> \%\: \%\:\%\:)
("(6.4.7)" header-name -->
(\< h-char-sequence \>)
(\" q-char-sequence \"))
("(6.4.7)" h-char-sequence -->
h-char
(h-char-sequence h-char))
("(6.4.7)" h-char -->
|any member of the source character set except the new-line character and >|)
("(6.4.7)" q-char-sequence -->
q-char
(q-char-sequence q-char))
("(6.4.7)" q-char -->
|any member of the source character set except the new-line character and "|)
("(6.4.8)" pp-number -->
digit
(\. digit)
(pp-number digit)
(pp-number identifier-nondigit)
(pp-number \e sign)
(pp-number \E sign)
(pp-number \p sign)
(pp-number \P sign)
(pp-number \.))
("(6.5.1)" primary-expression -->
identifier
constant
string-literal
(\( expression \))
generic-selection)
("(6.5.1.1)" generic-selection -->
(|_Generic| \( assignment-expression \, generic-assoc-list \)))
("(6.5.1.1)" generic-assoc-list -->
generic-association
(generic-assoc-list \, generic-association))
("(6.5.1.1)" generic-association -->
(type-name \: assignment-expression)
(|default| \: assignment-expression))
("(6.5.2)" postfix-expression -->
primary-expression
(postfix-expression \[ expression \])
(postfix-expression \( (opt argument-expression-list) \))
(postfix-expression \. identifier)
(postfix-expression |->| identifier)
(postfix-expression |++|)
(postfix-expression |--|)
(\( type-name \) \{ initializer-list \})
(\( type-name \) \{ initializer-list \, \}))
("(6.5.2)" argument-expression-list -->
assignment-expression
(argument-expression-list \, assignment-expression))
("(6.5.3)" unary-expression -->
postfix-expression
(|++| unary-expression)
(|--| unary-expression)
(unary-operator cast-expression)
(|sizeof| unary-expression)
(|sizeof| \( type-name \))
(|_Alignof| \( type-name \)))
("(6.5.3)" unary-operator -->
\& \* \+ \- \~ \!)
("(6.5.4)" cast-expression -->
unary-expression
(\( type-name \) cast-expression))
("(6.5.5)" multiplicative-expression -->
cast-expression
(multiplicative-expression \* cast-expression)
(multiplicative-expression \/ cast-expression)
(multiplicative-expression \% cast-expression))
("(6.5.6)" additive-expression -->
multiplicative-expression
(additive-expression \+ multiplicative-expression)
(additive-expression \- multiplicative-expression))
("(6.5.7)" shift-expression -->
additive-expression
(shift-expression |<<| additive-expression)
(shift-expression |>>| additive-expression))
("(6.5.8)" relational-expression -->
shift-expression
(relational-expression |<| shift-expression)
(relational-expression |>| shift-expression)
(relational-expression |<=| shift-expression)
(relational-expression |>=| shift-expression))
("(6.5.9)" equality-expression -->
relational-expression
(equality-expression |==| relational-expression)
(equality-expression |!=| relational-expression))
("(6.5.10)" AND-expression -->
equality-expression
(AND-expression |&| equality-expression))
("(6.5.11)" exclusive-OR-expression -->
AND-expression
(exclusive-OR-expression |^| AND-expression))
("(6.5.12)" inclusive-OR-expression -->
exclusive-OR-expression
(inclusive-OR-expression \| exclusive-OR-expression))
("(6.5.13)" logical-AND-expression -->
inclusive-OR-expression
(logical-AND-expression |&&| inclusive-OR-expression))
("(6.5.14)" logical-OR-expression -->
logical-AND-expression
(logical-OR-expression \|\| logical-AND-expression))
("(6.5.15)" conditional-expression -->
logical-OR-expression
(logical-OR-expression |?| expression |:| conditional-expression))
("(6.5.16)" assignment-expression -->
conditional-expression
(unary-expression assignment-operator assignment-expression))
("(6.5.16)" assignment-operator -->
\= \*\= \/\= \%\= \+\= \-\= \<\<\= \>\>\= \&\= \^\= \|\=)
("(6.5.17)" expression -->
assignment-expression
(expression \, assignment-expression))
("(6.6)" constant-expression -->
conditional-expression)
("(6.7)" declaration -->
(declaration-specifiers (opt init-declarator-list) \;)
static_assert-declaration)
("(6.7)" declaration-specifiers -->
(storage-class-specifier (opt declaration-specifiers))
(type-specifier (opt declaration-specifiers))
(type-qualifier (opt declaration-specifiers))
(function-specifier (opt declaration-specifiers))
(alignment-specifier (opt declaration-specifiers)))
("(6.7)" init-declarator-list -->
init-declarator
(init-declarator-list \, init-declarator))
("(6.7)" init-declarator -->
declarator
(declarator \= initializer))
("(6.7.1)" storage-class-specifier -->
|typedef|
|extern|
|static|
|_Thread_local|
|auto|
|register|)
("(6.7.2)" type-specifier -->
|void|
|char|
|short|
|int|
|long|
|float|
|double|
|signed|
|unsigned|
|_Bool|
|_Complex|
atomic-type-specifier
struct-or-union-specifier
enum-specifier
typedef-name)
("(6.7.2.1)" struct-or-union-specifier -->
(struct-or-union (opt identifier) \{ struct-declaration-list \})
struct-or-union identifier)
("(6.7.2.1)" struct-or-union -->
|struct|
|union|)
("(6.7.2.1)" struct-declaration-list -->
struct-declaration
(struct-declaration-list struct-declaration))
("(6.7.2.1)" struct-declaration -->
(specifier-qualifier-list (opt struct-declarator-list) \;)
static_assert-declaration)
("(6.7.2.1)" specifier-qualifier-list -->
(type-specifier (opt specifier-qualifier-list))
(type-qualifier (opt specifier-qualifier-list)))
("(6.7.2.1)" struct-declarator-list -->
struct-declarator
(struct-declarator-list \, struct-declarator))
("(6.7.2.1)" struct-declarator -->
declarator
((opt declarator) \: constant-expression))
("(6.7.2.2)" enum-specifier -->
(|enum| (opt identifier) \{ enumerator-list \})
(|enum| (opt identifier) \{ enumerator-list \, \})
(|enum| identifier))
("(6.7.2.2)" enumerator-list -->
enumerator
(enumerator-list \, enumerator))
("(6.7.2.2)" enumerator -->
enumeration-constant
(enumeration-constant \= constant-expression))
("(6.7.2.4)" atomic-type-specifier -->
(|_Atomic| \( type-name \)))
("(6.7.3)" type-qualifier -->
|const|
|restrict|
|volatile|
|_Atomic|)
("(6.7.4)" function-specifier -->
|inline|
|_Noreturn|)
("(6.7.5)" alignment-specifier -->
(|_Alignas| \( type-name \))
(|_Alignas| \( constant-expression \)))
("(6.7.6)" declarator -->
((opt pointer) direct-declarator))
("(6.7.6)" direct-declarator -->
identifier
(\( declarator \))
(direct-declarator \[ (opt type-qualifier-list) (opt assignment-expression) \])
(direct-declarator \[ static (opt type-qualifier-list) assignment-expression \])
(direct-declarator \[ type-qualifier-list static assignment-expression \])
(direct-declarator \[ (opt type-qualifier-list) \* \])
(direct-declarator \( parameter-type-list \))
(direct-declarator \( (opt identifier-list) \)))
("(6.7.6)" pointer -->
(\* (opt type-qualifier-list))
(\* (opt type-qualifier-list) pointer))
("(6.7.6)" type-qualifier-list -->
type-qualifier
(type-qualifier-list type-qualifier))
("(6.7.6)" parameter-type-list -->
parameter-list
(parameter-list \, |...|))
("(6.7.6)" parameter-list -->
parameter-declaration
(parameter-list \, parameter-declaration))
("(6.7.6)" parameter-declaration -->
(declaration-specifiers declarator)
(declaration-specifiers (opt abstract-declarator)))
("(6.7.6)" identifier-list -->
identifier
(identifier-list \, identifier))
("(6.7.7)" type-name -->
(specifier-qualifier-list (opt abstract-declarator)))
("(6.7.7)" abstract-declarator -->
pointer
((opt pointer) direct-abstract-declarator))
("(6.7.7)" direct-abstract-declarator -->
(\( abstract-declarator \))
((opt direct-abstract-declarator) \[ (opt type-qualifier-list) (opt assignment-expression) \])
((opt direct-abstract-declarator) \[ |static| (opt type-qualifier-list) assignment-expression \])
((opt direct-abstract-declarator) \[ type-qualifier-list |static| assignment-expression \])
((opt direct-abstract-declarator) \[ \* \])
((opt direct-abstract-declarator) \( (opt parameter-type-list) \)))
("(6.7.8)" typedef-name -->
identifier)
("(6.7.9)" initializer -->
assignment-expression
(\{ initializer-list \})
(\{ initializer-list \, \}))
("(6.7.9)" initializer-list -->
((opt designation) initializer)
(initializer-list \, (opt designation) initializer))
("(6.7.9)" designation -->
(designator-list \=))
("(6.7.9)" designator-list -->
designator
(designator-list designator))
("(6.7.9)" designator -->
(\[ constant-expression \])
(\. identifier))
("(6.7.10)" static_assert-declaration -->
(|_Static_assert| \( constant-expression \, string-literal \) \;))
("(6.8)" statement -->
labeled-statement
compound-statement
expression-statement
selection-statement
iteration-statement
jump-statement)
("(6.8.1)" labeled-statement -->
(identifier \: statement)
(|case| constant-expression \: statement)
(|default| \: statement))
("(6.8.2)" compound-statement -->
(\{ (opt block-item-list) \}))
("(6.8.2)" block-item-list -->
block-item
(block-item-list block-item))
("(6.8.2)" block-item -->
declaration
statement)
("(6.8.3)" expression-statement -->
((opt expression) \;))
("(6.8.4)" selection-statement -->
(|if| \( expression \) statement)
(|if| \( expression \) statement |else| statement)
(|switch| \( expression \) statement))
("(6.8.5)" iteration-statement -->
(|while| \( expression \) statement)
(|do| statement |while| \( expression \) \;)
(|for| \( (opt expression) \; (opt expression) \; (opt expression) \) statement)
(|for| \( declaration (opt expression) \; (opt expression) \) statement))
("(6.8.6)" jump-statement -->
(|goto| identifier \;)
(|continue| \;)
(|break| \;)
(|return| (opt expression) \;))
("(6.9)" translation-unit -->
external-declaration
(translation-unit external-declaration))
("(6.9)" external-declaration -->
function-definition
declaration)
("(6.9.1)" function-definition -->
(declaration-specifiers declarator (opt declaration-list) compound-statement))
("(6.9.1)" declaration-list -->
declaration
(declaration-list declaration))
("(6.10)" preprocessing-file -->
(opt group))
("(6.10)" group -->
group-part
(group group-part))
("(6.10)" group-part -->
if-section
(control-line text-line)
(\# non-directive))
("(6.10)" if-section -->
(if-group (opt elif-groups) (opt else-group) endif-line))
("(6.10)" if-group -->
(\# |if| constant-expression new-line (opt group))
(\# |ifdef| identifier new-line (opt group))
(\# |ifndef| identifier new-line (opt group)))
("(6.10)" elif-groups -->
elif-group
(elif-groups elif-group))
("(6.10)" elif-group -->
(\# |elif| constant-expression new-line (opt group)))
("(6.10)" else-group -->
(\# |else| new-line (opt group)))
("(6.10)" endif-line -->
(\# |endif|))
("(6.10)" control-line -->
(\# |include| pp-tokens new-line)
(\# |define| identifier replacement-list new-line)
(\# |define| identifier lparen (opt identifier-list) \) replacement-list new-line)
(\# |define| identifier lparen |...| \) replacement-list new-line)
(\# |define| identifier lparen identifier-list \, |...| \) replacement-list new-line)
(\# |undef| identifier new-line)
(\# |line| pp-tokens new-line)
(\# |error| (opt pp-tokens) new-line)
(\# |pragma| (opt pp-tokens) new-line)
(\# new-line))
("(6.10)" text-line -->
((opt pp-tokens) new-line))
("(6.10)" non-directive -->
(pp-tokens new-line))
("(6.10)" lparen -->
|a ( character not immediately preceded by white-space|)
("(6.10)" replacement-list -->
(opt pp-tokens))
("(6.10)" pp-tokens -->
preprocessing-token
(pp-tokens preprocessing-token))
("(6.10)" new-line -->
|the new-line character|)))
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/languages/linc/annex-a.lisp | lisp | u ul
ull
lu
\.\.\.
)
)
))
))
)
(opt expression) \; (opt expression) \) statement)
(opt expression) \) statement))
)
)
)
)) | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.LANGUAGES.LINC")
(defparameter *ansi-c-grammar*
'(("(6.4)" token -->
keyword
identifier
constant
string-literal
punctuator)
("(6.4)" preprocessing-token -->
header-name
identifier
pp-number
character-constant
string-literal
punctuator
|each non-white-space character that cannot be one of the above|)
("(6.4.1)" keyword -->
|*|
|auto|
|break|
|case|
|char|
|const|
|continue|
|default|
|do|
|double|
|else|
|enum|
|extern|
|float|
|for|
|goto|
|if|
|inline|
|int|
|long|
|register|
|restrict|
|return|
|short|
|signed|
|sizeof|
|static|
|struct|
|switch|
|typedef|
|union|
|unsigned|
|void|
|volatile|
|while|
|_Alignas|
|_Alignof|
|_Atomic|
|_Bool|
|_Complex|
|_Generic|
|_Imaginary|
|_Noreturn|
|_Static_assert|
|_Thread_local|)
("(6.4.2.1)" identifier -->
identifier-nondigit
(identifier identifier-nondigit)
(identifier digit))
("(6.4.2.1)" identifier-nondigit -->
nondigit
universal-character-name
|other implementation-defined characters|)
("(6.4.2.1)" nondigit -->
\_
\a \b \c \d \e \f \g \h \i \j \k \l \m
\n \o \p \q \r \s \t \u \v \w \x \y \z
\A \B \C \D \E \F \G \H \I \J \K \L \M
\N \O \P \Q \R \S \T \U \V \W \X \Y \Z)
("(6.4.2.1)" digit -->
\0 \1 \2 \3 \4 \5 \6 \7 \8 \9)
("(6.4.3)" universal-character-name -->
(|\\u| hex-quad)
(|\\U| hex-quad hex-quad))
("(6.4.3)" hex-quad -->
(hexadecimal-digit hexadecimal-digit)
(hexadecimal-digit hexadecimal-digit))
("(6.4.4)" constant -->
integer-constant
floating-constant
enumeration-constant
character-constant)
("(6.4.4.1)" integer-constant -->
(decimal-constant (opt integer-suffix))
(octal-constant (opt integer-suffix))
(hexadecimal-constant (opt integer-suffix)))
("(6.4.4.1)" decimal-constant -->
nonzero-digit
(decimal-constant digit))
("(6.4.4.1)" octal-constant -->
\0
(octal-constant octal-digit))
("(6.4.4.1)" hexadecimal-constant -->
(hexadecimal-prefix hexadecimal-digit)
(hexadecimal-constant hexadecimal-digit))
("(6.4.4.1)" hexadecimal-prefix -->
|0x|
|0X|)
("(6.4.4.1)" nonzero-digit -->
\1 \2 \3 \4 \5 \6 \7 \8 \9)
("(6.4.4.1)" octal-digit -->
\0 \1 \2 \3 \4 \5 \6 \7)
("(6.4.4.1)" hexadecimal-digit -->
\0 \1 \2 \3 \4 \5 \6 \7 \8 \9
\a \b \c \d \e \f
\A \B \C \D \E \F)
("(6.4.4.1)" integer-suffix -->
llu
("(6.4.4.1)" unsigned-suffix -->
\u
\U)
("(6.4.4.1)" long-suffix -->
\l
\L)
("(6.4.4.1)" long-long-suffix -->
|ll|
|LL|)
("(6.4.4.2)" floating-constant -->
decimal-floating-constant
hexadecimal-floating-constant)
("(6.4.4.2)" decimal-floating-constant -->
(fractional-constant (opt exponent-part) (opt floating-suffix))
(digit-sequence exponent-part (opt floating-suffix)))
("(6.4.4.2)" hexadecimal-floating-constant -->
(hexadecimal-prefix hexadecimal-fractional-constant binary-exponent-part (opt floating-suffix))
(hexadecimal-prefix hexadecimal-digit-sequence binary-exponent-part (opt floating-suffix)))
("(6.4.4.2)" fractional-constant -->
((opt digit-sequence) \. digit-sequence)
(digit-sequence \.))
("(6.4.4.2)" exponent-part -->
(|e| (opt sign) digit-sequence)
(|E| (opt sign) digit-sequence))
("(6.4.4.2)" sign -->
\+ \-)
("(6.4.4.2)" digit-sequence -->
digit
(digit-sequence digit))
("(6.4.4.2)" hexadecimal-fractional-constant -->
((opt hexadecimal-digit-sequence) \. hexadecimal-digit-sequence)
(hexadecimal-digit-sequence \.))
("(6.4.4.2)" binary-exponent-part -->
(|p| (opt sign) digit-sequence)
(|P| (opt sign) digit-sequence))
("(6.4.4.2)" hexadecimal-digit-sequence -->
hexadecimal-digit
(hexadecimal-digit-sequence hexadecimal-digit))
("(6.4.4.2)" floating-suffix -->
\f \l \F \L)
("(6.4.4.3)" enumeration-constant -->
identifier)
("(6.4.4.4)" character-constant -->
(\' c-char-sequence \')
(\L\' c-char-sequence \')
(\u\' c-char-sequence \')
(\U\' c-char-sequence \'))
("(6.4.4.4)" c-char-sequence -->
c-char
(c-char-sequence c-char))
("(6.4.4.4)" c-char -->
|any member of the source character set except the single-quote ', backslash \, or new-line character|
escape-sequence)
("(6.4.4.4)" escape-sequence -->
simple-escape-sequence
octal-escape-sequence
hexadecimal-escape-sequence
universal-character-name)
("(6.4.4.4)" simple-escape-sequence -->
\\\' \\\" \\\? \\\\ \\\a \\\b \\\f \\\n \\\r \\\t \\\v)
("(6.4.4.4)" octal-escape-sequence -->
(\\ octal-digit)
(\\ octal-digit octal-digit)
(\\ octal-digit octal-digit octal-digit))
("(6.4.4.4)" hexadecimal-escape-sequence -->
(|\\x| hexadecimal-digit)
(hexadecimal-escape-sequence hexadecimal-digit))
("(6.4.5)" string-literal -->
((opt encoding-prefix) \" (opt s-char-sequence) \"))
("(6.4.5)" encoding-prefix -->
|u8|
|u|
|U|
|L|)
("(6.4.5)" s-char-sequence -->
s-char
(s-char-sequence s-char))
("(6.4.5)" s-char -->
|any member of the source character set except the double-quote ", backslash \, or new-line character escape-sequence|)
("(6.4.6)" punctuator -->
\[ \] \( \) \{ \} \. \-\>
\+\+ \-\- \& \* \+ \- \~ \!
\/ \% \<\< \>\> \< \> \<\= \>\= \=\= \!\= \^ \| \&\& \|\|
\= \*\= \/\= \%\= \+\= \-\= \<\<\= \>\>\= \&\= \^\= \|\=
\, \# \#\#
\<\: \:\> \<\% \%\> \%\: \%\:\%\:)
("(6.4.7)" header-name -->
(\< h-char-sequence \>)
(\" q-char-sequence \"))
("(6.4.7)" h-char-sequence -->
h-char
(h-char-sequence h-char))
("(6.4.7)" h-char -->
|any member of the source character set except the new-line character and >|)
("(6.4.7)" q-char-sequence -->
q-char
(q-char-sequence q-char))
("(6.4.7)" q-char -->
|any member of the source character set except the new-line character and "|)
("(6.4.8)" pp-number -->
digit
(\. digit)
(pp-number digit)
(pp-number identifier-nondigit)
(pp-number \e sign)
(pp-number \E sign)
(pp-number \p sign)
(pp-number \P sign)
(pp-number \.))
("(6.5.1)" primary-expression -->
identifier
constant
string-literal
(\( expression \))
generic-selection)
("(6.5.1.1)" generic-selection -->
(|_Generic| \( assignment-expression \, generic-assoc-list \)))
("(6.5.1.1)" generic-assoc-list -->
generic-association
(generic-assoc-list \, generic-association))
("(6.5.1.1)" generic-association -->
(type-name \: assignment-expression)
(|default| \: assignment-expression))
("(6.5.2)" postfix-expression -->
primary-expression
(postfix-expression \[ expression \])
(postfix-expression \( (opt argument-expression-list) \))
(postfix-expression \. identifier)
(postfix-expression |->| identifier)
(postfix-expression |++|)
(postfix-expression |--|)
(\( type-name \) \{ initializer-list \})
(\( type-name \) \{ initializer-list \, \}))
("(6.5.2)" argument-expression-list -->
assignment-expression
(argument-expression-list \, assignment-expression))
("(6.5.3)" unary-expression -->
postfix-expression
(|++| unary-expression)
(|--| unary-expression)
(unary-operator cast-expression)
(|sizeof| unary-expression)
(|sizeof| \( type-name \))
(|_Alignof| \( type-name \)))
("(6.5.3)" unary-operator -->
\& \* \+ \- \~ \!)
("(6.5.4)" cast-expression -->
unary-expression
(\( type-name \) cast-expression))
("(6.5.5)" multiplicative-expression -->
cast-expression
(multiplicative-expression \* cast-expression)
(multiplicative-expression \/ cast-expression)
(multiplicative-expression \% cast-expression))
("(6.5.6)" additive-expression -->
multiplicative-expression
(additive-expression \+ multiplicative-expression)
(additive-expression \- multiplicative-expression))
("(6.5.7)" shift-expression -->
additive-expression
(shift-expression |<<| additive-expression)
(shift-expression |>>| additive-expression))
("(6.5.8)" relational-expression -->
shift-expression
(relational-expression |<| shift-expression)
(relational-expression |>| shift-expression)
(relational-expression |<=| shift-expression)
(relational-expression |>=| shift-expression))
("(6.5.9)" equality-expression -->
relational-expression
(equality-expression |==| relational-expression)
(equality-expression |!=| relational-expression))
("(6.5.10)" AND-expression -->
equality-expression
(AND-expression |&| equality-expression))
("(6.5.11)" exclusive-OR-expression -->
AND-expression
(exclusive-OR-expression |^| AND-expression))
("(6.5.12)" inclusive-OR-expression -->
exclusive-OR-expression
(inclusive-OR-expression \| exclusive-OR-expression))
("(6.5.13)" logical-AND-expression -->
inclusive-OR-expression
(logical-AND-expression |&&| inclusive-OR-expression))
("(6.5.14)" logical-OR-expression -->
logical-AND-expression
(logical-OR-expression \|\| logical-AND-expression))
("(6.5.15)" conditional-expression -->
logical-OR-expression
(logical-OR-expression |?| expression |:| conditional-expression))
("(6.5.16)" assignment-expression -->
conditional-expression
(unary-expression assignment-operator assignment-expression))
("(6.5.16)" assignment-operator -->
\= \*\= \/\= \%\= \+\= \-\= \<\<\= \>\>\= \&\= \^\= \|\=)
("(6.5.17)" expression -->
assignment-expression
(expression \, assignment-expression))
("(6.6)" constant-expression -->
conditional-expression)
("(6.7)" declaration -->
static_assert-declaration)
("(6.7)" declaration-specifiers -->
(storage-class-specifier (opt declaration-specifiers))
(type-specifier (opt declaration-specifiers))
(type-qualifier (opt declaration-specifiers))
(function-specifier (opt declaration-specifiers))
(alignment-specifier (opt declaration-specifiers)))
("(6.7)" init-declarator-list -->
init-declarator
(init-declarator-list \, init-declarator))
("(6.7)" init-declarator -->
declarator
(declarator \= initializer))
("(6.7.1)" storage-class-specifier -->
|typedef|
|extern|
|static|
|_Thread_local|
|auto|
|register|)
("(6.7.2)" type-specifier -->
|void|
|char|
|short|
|int|
|long|
|float|
|double|
|signed|
|unsigned|
|_Bool|
|_Complex|
atomic-type-specifier
struct-or-union-specifier
enum-specifier
typedef-name)
("(6.7.2.1)" struct-or-union-specifier -->
(struct-or-union (opt identifier) \{ struct-declaration-list \})
struct-or-union identifier)
("(6.7.2.1)" struct-or-union -->
|struct|
|union|)
("(6.7.2.1)" struct-declaration-list -->
struct-declaration
(struct-declaration-list struct-declaration))
("(6.7.2.1)" struct-declaration -->
static_assert-declaration)
("(6.7.2.1)" specifier-qualifier-list -->
(type-specifier (opt specifier-qualifier-list))
(type-qualifier (opt specifier-qualifier-list)))
("(6.7.2.1)" struct-declarator-list -->
struct-declarator
(struct-declarator-list \, struct-declarator))
("(6.7.2.1)" struct-declarator -->
declarator
((opt declarator) \: constant-expression))
("(6.7.2.2)" enum-specifier -->
(|enum| (opt identifier) \{ enumerator-list \})
(|enum| (opt identifier) \{ enumerator-list \, \})
(|enum| identifier))
("(6.7.2.2)" enumerator-list -->
enumerator
(enumerator-list \, enumerator))
("(6.7.2.2)" enumerator -->
enumeration-constant
(enumeration-constant \= constant-expression))
("(6.7.2.4)" atomic-type-specifier -->
(|_Atomic| \( type-name \)))
("(6.7.3)" type-qualifier -->
|const|
|restrict|
|volatile|
|_Atomic|)
("(6.7.4)" function-specifier -->
|inline|
|_Noreturn|)
("(6.7.5)" alignment-specifier -->
(|_Alignas| \( type-name \))
(|_Alignas| \( constant-expression \)))
("(6.7.6)" declarator -->
((opt pointer) direct-declarator))
("(6.7.6)" direct-declarator -->
identifier
(\( declarator \))
(direct-declarator \[ (opt type-qualifier-list) (opt assignment-expression) \])
(direct-declarator \[ static (opt type-qualifier-list) assignment-expression \])
(direct-declarator \[ type-qualifier-list static assignment-expression \])
(direct-declarator \[ (opt type-qualifier-list) \* \])
(direct-declarator \( parameter-type-list \))
(direct-declarator \( (opt identifier-list) \)))
("(6.7.6)" pointer -->
(\* (opt type-qualifier-list))
(\* (opt type-qualifier-list) pointer))
("(6.7.6)" type-qualifier-list -->
type-qualifier
(type-qualifier-list type-qualifier))
("(6.7.6)" parameter-type-list -->
parameter-list
(parameter-list \, |...|))
("(6.7.6)" parameter-list -->
parameter-declaration
(parameter-list \, parameter-declaration))
("(6.7.6)" parameter-declaration -->
(declaration-specifiers declarator)
(declaration-specifiers (opt abstract-declarator)))
("(6.7.6)" identifier-list -->
identifier
(identifier-list \, identifier))
("(6.7.7)" type-name -->
(specifier-qualifier-list (opt abstract-declarator)))
("(6.7.7)" abstract-declarator -->
pointer
((opt pointer) direct-abstract-declarator))
("(6.7.7)" direct-abstract-declarator -->
(\( abstract-declarator \))
((opt direct-abstract-declarator) \[ (opt type-qualifier-list) (opt assignment-expression) \])
((opt direct-abstract-declarator) \[ |static| (opt type-qualifier-list) assignment-expression \])
((opt direct-abstract-declarator) \[ type-qualifier-list |static| assignment-expression \])
((opt direct-abstract-declarator) \[ \* \])
((opt direct-abstract-declarator) \( (opt parameter-type-list) \)))
("(6.7.8)" typedef-name -->
identifier)
("(6.7.9)" initializer -->
assignment-expression
(\{ initializer-list \})
(\{ initializer-list \, \}))
("(6.7.9)" initializer-list -->
((opt designation) initializer)
(initializer-list \, (opt designation) initializer))
("(6.7.9)" designation -->
(designator-list \=))
("(6.7.9)" designator-list -->
designator
(designator-list designator))
("(6.7.9)" designator -->
(\[ constant-expression \])
(\. identifier))
("(6.7.10)" static_assert-declaration -->
("(6.8)" statement -->
labeled-statement
compound-statement
expression-statement
selection-statement
iteration-statement
jump-statement)
("(6.8.1)" labeled-statement -->
(identifier \: statement)
(|case| constant-expression \: statement)
(|default| \: statement))
("(6.8.2)" compound-statement -->
(\{ (opt block-item-list) \}))
("(6.8.2)" block-item-list -->
block-item
(block-item-list block-item))
("(6.8.2)" block-item -->
declaration
statement)
("(6.8.3)" expression-statement -->
("(6.8.4)" selection-statement -->
(|if| \( expression \) statement)
(|if| \( expression \) statement |else| statement)
(|switch| \( expression \) statement))
("(6.8.5)" iteration-statement -->
(|while| \( expression \) statement)
("(6.8.6)" jump-statement -->
("(6.9)" translation-unit -->
external-declaration
(translation-unit external-declaration))
("(6.9)" external-declaration -->
function-definition
declaration)
("(6.9.1)" function-definition -->
(declaration-specifiers declarator (opt declaration-list) compound-statement))
("(6.9.1)" declaration-list -->
declaration
(declaration-list declaration))
("(6.10)" preprocessing-file -->
(opt group))
("(6.10)" group -->
group-part
(group group-part))
("(6.10)" group-part -->
if-section
(control-line text-line)
(\# non-directive))
("(6.10)" if-section -->
(if-group (opt elif-groups) (opt else-group) endif-line))
("(6.10)" if-group -->
(\# |if| constant-expression new-line (opt group))
(\# |ifdef| identifier new-line (opt group))
(\# |ifndef| identifier new-line (opt group)))
("(6.10)" elif-groups -->
elif-group
(elif-groups elif-group))
("(6.10)" elif-group -->
(\# |elif| constant-expression new-line (opt group)))
("(6.10)" else-group -->
(\# |else| new-line (opt group)))
("(6.10)" endif-line -->
(\# |endif|))
("(6.10)" control-line -->
(\# |include| pp-tokens new-line)
(\# |define| identifier replacement-list new-line)
(\# |define| identifier lparen (opt identifier-list) \) replacement-list new-line)
(\# |define| identifier lparen |...| \) replacement-list new-line)
(\# |define| identifier lparen identifier-list \, |...| \) replacement-list new-line)
(\# |undef| identifier new-line)
(\# |line| pp-tokens new-line)
(\# |error| (opt pp-tokens) new-line)
(\# |pragma| (opt pp-tokens) new-line)
(\# new-line))
("(6.10)" text-line -->
((opt pp-tokens) new-line))
("(6.10)" non-directive -->
(pp-tokens new-line))
("(6.10)" lparen -->
|a ( character not immediately preceded by white-space|)
("(6.10)" replacement-list -->
(opt pp-tokens))
("(6.10)" pp-tokens -->
preprocessing-token
(pp-tokens preprocessing-token))
("(6.10)" new-line -->
|the new-line character|)))
|
1eca9f2795606281d53835b1348f0a4d4a0fa4476868a273bb42c1bd8bcf6a19 | heroku/logplex | live_upgrade.erl | f(UpgradeNode).
UpgradeNode = fun () ->
case logplex_app:config(git_branch) of
"v69.9" ->
io:format(whereis(user), "at=upgrade_start cur_vsn=69.8~n", []);
"v69.10" ->
io:format(whereis(user),
"at=upgrade type=retry cur_vsn=69.8 old_vsn=69.9~n", []);
Else ->
io:format(whereis(user),
"at=upgrade_start old_vsn=~p abort=wrong_version", [tl(Else)]),
erlang:error({wrong_version, Else})
end,
application:set_env(logplex, no_tail_warning, "Error L20 (Tail sessions forbidden) Tail sessions for this app are forbidden due to log volume."),
%% stateless
l(logplex_msg_buffer),
l(logplex_tcpsyslog_drain),
l(pobox),
%% Stateful changes to HTTP drains -- gotta suspend, reload, and then
%% resume all drains before going for the stateless drain buffer update
l(logplex_msg_buffer),
l(logplex_tcpsyslog_drain),
[catch logplex_tcpsyslog_drain:resize_msg_buffer(Pid,1024)
|| {Pid, tcpsyslog} <- gproc:lookup_local_properties(drain_type)],
application:set_env(logplex, git_branch, "v69.10"),
ok
end.
f(RollbackNode).
RollbackNode = fun () ->
case logplex_app:config(git_branch) of
"v69.10" ->
io:format(whereis(user),
"at=rollback cur_vsn=69.9 old_vsn=69.8~n", []);
Else ->
io:format(whereis(user),
"at=upgrade_start old_vsn=~p abort=wrong_version", [tl(Else)]),
erlang:error({wrong_version, Else})
end,
%% stateless
l(logplex_tcpsyslog_drain),
l(logplex_msg_buffer),
application:set_env(logplex, git_branch, "v69.9"),
ok
end.
f(NodeVersions).
NodeVersions = fun () ->
lists:keysort(3,
[ {N,
element(2, rpc:call(N, application, get_env, [logplex, git_branch])),
rpc:call(N, os, getenv, ["INSTANCE_NAME"])}
|| N <- [node() | nodes()] ])
end.
f(NodesAt).
NodesAt = fun (Vsn) ->
[ N || {N, V, _} <- NodeVersions(), V =:= Vsn ]
end.
f(RollingUpgrade).
RollingUpgrade = fun (Nodes) ->
lists:foldl(fun (N, {good, Upgraded}) ->
case rpc:call(N, erlang, apply, [ UpgradeNode, [] ]) of
ok ->
{good, [N | Upgraded]};
Else ->
{{bad, N, Else}, Upgraded}
end;
(N, {_, _} = Acc) -> Acc
end,
{good, []},
Nodes)
end.
f(RollingRollback).
RollingRollback = fun (Nodes) ->
lists:foldl(fun (N, {good, Upgraded}) ->
case rpc:call(N, erlang, apply, [ RollbackNode, [] ]) of
ok ->
{good, [N | Upgraded]};
Else ->
{{bad, N, Else}, Upgraded}
end;
(N, {_, _} = Acc) -> Acc
end,
{good, []},
Nodes)
end.
| null | https://raw.githubusercontent.com/heroku/logplex/fc520c44cf4687726d5d51464d3264ddc6abb0ba/upgrades/v69.9_v69.10/live_upgrade.erl | erlang | stateless
Stateful changes to HTTP drains -- gotta suspend, reload, and then
resume all drains before going for the stateless drain buffer update
stateless | f(UpgradeNode).
UpgradeNode = fun () ->
case logplex_app:config(git_branch) of
"v69.9" ->
io:format(whereis(user), "at=upgrade_start cur_vsn=69.8~n", []);
"v69.10" ->
io:format(whereis(user),
"at=upgrade type=retry cur_vsn=69.8 old_vsn=69.9~n", []);
Else ->
io:format(whereis(user),
"at=upgrade_start old_vsn=~p abort=wrong_version", [tl(Else)]),
erlang:error({wrong_version, Else})
end,
application:set_env(logplex, no_tail_warning, "Error L20 (Tail sessions forbidden) Tail sessions for this app are forbidden due to log volume."),
l(logplex_msg_buffer),
l(logplex_tcpsyslog_drain),
l(pobox),
l(logplex_msg_buffer),
l(logplex_tcpsyslog_drain),
[catch logplex_tcpsyslog_drain:resize_msg_buffer(Pid,1024)
|| {Pid, tcpsyslog} <- gproc:lookup_local_properties(drain_type)],
application:set_env(logplex, git_branch, "v69.10"),
ok
end.
f(RollbackNode).
RollbackNode = fun () ->
case logplex_app:config(git_branch) of
"v69.10" ->
io:format(whereis(user),
"at=rollback cur_vsn=69.9 old_vsn=69.8~n", []);
Else ->
io:format(whereis(user),
"at=upgrade_start old_vsn=~p abort=wrong_version", [tl(Else)]),
erlang:error({wrong_version, Else})
end,
l(logplex_tcpsyslog_drain),
l(logplex_msg_buffer),
application:set_env(logplex, git_branch, "v69.9"),
ok
end.
f(NodeVersions).
NodeVersions = fun () ->
lists:keysort(3,
[ {N,
element(2, rpc:call(N, application, get_env, [logplex, git_branch])),
rpc:call(N, os, getenv, ["INSTANCE_NAME"])}
|| N <- [node() | nodes()] ])
end.
f(NodesAt).
NodesAt = fun (Vsn) ->
[ N || {N, V, _} <- NodeVersions(), V =:= Vsn ]
end.
f(RollingUpgrade).
RollingUpgrade = fun (Nodes) ->
lists:foldl(fun (N, {good, Upgraded}) ->
case rpc:call(N, erlang, apply, [ UpgradeNode, [] ]) of
ok ->
{good, [N | Upgraded]};
Else ->
{{bad, N, Else}, Upgraded}
end;
(N, {_, _} = Acc) -> Acc
end,
{good, []},
Nodes)
end.
f(RollingRollback).
RollingRollback = fun (Nodes) ->
lists:foldl(fun (N, {good, Upgraded}) ->
case rpc:call(N, erlang, apply, [ RollbackNode, [] ]) of
ok ->
{good, [N | Upgraded]};
Else ->
{{bad, N, Else}, Upgraded}
end;
(N, {_, _} = Acc) -> Acc
end,
{good, []},
Nodes)
end.
|
5e9e34767a7d449ea9c860ce4c858ed91ec2a5fa4a3d0bbd078183074718d809 | rmloveland/scheme48-0.53 | inspect.scm | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
; A dirty little inspector.
; This breaks abstractions left and right.
Look and feel shamelessly plagiarized from the Lucid Lisp inspector .
; Inspector state:
; thing ; object currently being inspected, obtained as (focus-object)
; menu ; cached result of (prepare-menu thing). This is a list of
; lists (<name-or-#f> <value>).
; position ; position within menu; modified by M (more) command
; stack ; list of other things
(define-record-type inspector-state inspector-state?
(make-inspector-state menu position stack)
(menu inspector-state-menu)
(position inspector-state-position set-inspector-state-position!)
(stack inspector-state-stack))
; The inspector is a distinct REPL with its own state. This allows the
; user to continue with the same inspection stack after an error.
(define inspector-state repl-data)
(define set-inspector-state! set-repl-data!)
(define *menu-limit* 15) ; maximum menu entries
(define *write-depth* 3) ; limit for recursive writes
(define *write-length* 5) ; ditto
There are three commands for invoking the inspector with different
; initial objects:
; ,inspect -> focus object
; ,inspect <exp> -> value of <exp>
; ,debug -> continuation of stopped thread(s), preferentially
; chooses the thread with the most recent error
; ,threads -> list of current command level's threads
(define-command-syntax 'inspect "[<exp>]" "invoke the inspector"
'(&opt form))
(define-command-syntax 'debug "" "inspect the current continuation" '())
(define-command-syntax 'threads "" "inspect stopped threads" '())
(define (debug)
(showing-focus-object
(lambda ()
(set-focus-object! (or (command-continuation)
(command-threads)))))
(inspect))
(define (threads)
(showing-focus-object
(lambda ()
(set-focus-object! (command-threads))))
(inspect))
(define (inspect . maybe-exp)
(if (not (null? maybe-exp))
(with-limited-output
(lambda ()
(showing-focus-object
(lambda ()
(evaluate-and-select (car maybe-exp)
(environment-for-commands)))))))
(push-command-level inspector
(make-inspector-state (prepare-menu (focus-object))
0
'())))
;----------------
; Actual entry point for the inspector. We print the menu and then loop
; reading commands.
(define (inspector)
(present-menu)
(let loop ()
(let ((command (read-command-carefully "inspect: "
#f ; command preferred
(command-input)
inspector-commands)))
(cond ((eof-object? command)
(newline (command-output))
(proceed-with-command-level (cadr (command-levels))))
((not command) ; read command error
(loop))
(else
(with-limited-output
(lambda ()
(execute-inspector-command command)))
(loop))))))
(define (present-menu)
(let ((state (inspector-state)))
(display-menu (inspector-state-menu state)
(inspector-state-position state)
(command-output))))
; Go to a new thing by making a new inspector state.
(define (new-selection thing stack)
(set-inspector-state!
(make-inspector-state (prepare-menu thing) 0 stack)))
; Selection commands are either an integer, which selects a menu item,
; or `u' to move up the stack, `d' to move to the next continuation
; (only valid when the current object is a continuation), or `t' which
; moves to a procedure's template (only valid when the current object
; is a template).
(define (read-selection-command port)
(let ((x (read port)))
(if (or (integer? x)
(memq x '(u d t)))
x
(read-command-error port "invalid selection command" x))))
(define selection-command-syntax (list '&rest read-selection-command))
(define (inspector-commands name)
(if (integer? name)
selection-command-syntax
(case name
((? m q) '()) ; no arguments
((u d t) selection-command-syntax)
(else #f))))
; Execute a command.
;
; We save the current object and state to compare to the new ones to see
; if we need to display a new menu. The old object is pushed on the stack
; only if nothing has been popped off.
(define (execute-inspector-command command)
(let ((result-before (focus-object))
(state-before (inspector-state)))
(showing-focus-object
(lambda ()
(let ((name (car command)))
(if (integer? name)
(execute-selection-command command)
(case name
((u d t)
(execute-selection-command command))
((m) (inspect-more))
((q) (proceed-with-command-level (cadr (command-levels))))
((?) (inspect-help))
(else (execute-command command)))))))
(let ((result-after (focus-object))
(state-after (inspector-state)))
(if (not (eq? result-after result-before))
(begin (if (eq? state-after state-before)
(new-selection result-after
(cons result-before
(inspector-state-stack state-before))))
(present-menu))))))
; Choose a new object.
(define (execute-selection-command command)
(if (not (null? command))
(let ((name (car command)))
(if (integer? name)
(let ((menu (inspector-state-menu (inspector-state))))
(if (and (>= name 0)
(< name (length menu)))
(move-to-object! (menu-ref menu name))
(write-line "Invalid choice." (command-output))))
(case name
((u) (pop-inspector-stack))
((d) (inspect-next-continuation))
((t) (select-template))
(else (error "bad selection command" name))))
(execute-selection-command (cdr command)))))
; Procedures for the various commands.
(define (move-to-object! object)
(new-selection object
(cons (focus-object)
(inspector-state-stack (inspector-state))))
(set-focus-object! object))
(define (pop-inspector-stack)
(let ((stack (inspector-state-stack (inspector-state))))
(if (pair? stack)
(begin (new-selection (car stack) (cdr stack))
(set-focus-object! (car stack)))
(write-line "Can't go up from here." (command-output)))))
(define (inspect-next-continuation)
(if (continuation? (focus-object))
(move-to-object! (continuation-parent (focus-object)))
(write-line "Can't go down from a non-continuation." (command-output))))
(define (inspect-more)
(let* ((state (inspector-state))
(menu (inspector-state-menu state))
(position (inspector-state-position state)))
(if (> (length menu) (+ *menu-limit* position))
(let ((position (- (+ position *menu-limit*) 1)))
(set-inspector-state-position! state position)
(present-menu))
(write-line "There is no more." (command-output)))))
(define (select-template)
(move-to-object! (coerce-to-template (focus-object))))
(define (inspect-help)
(let ((o-port (command-output)))
(for-each (lambda (s) (display s o-port) (newline o-port))
'("q quit"
"u up stack (= go to previous object)"
"d down stack"
"t template"
"<integer> menu item"
"or any command processor command"
"multiple u d t <integer> commands can be put on one line"))))
;----------------
; Menus.
;
; A menu is a list of lists (<name-or-#f> <thing>).
(define (menu-ref menu n)
(cadr (list-ref menu n)))
; Get a menu for THING. We know about a fixed set of types.
(define (prepare-menu thing)
(cond ((list? thing)
(map (lambda (x)
(list #f x))
thing))
((pair? thing)
`((car ,(car thing)) (cdr ,(cdr thing))))
((vector? thing)
(prepare-menu (vector->list thing)))
((closure? thing)
(prepare-environment-menu
(closure-env thing)
(get-shape (template-debug-data (closure-template thing))
0)))
((template? thing)
(prepare-menu (template->list thing)))
((continuation? thing)
(prepare-continuation-menu thing))
((record? thing)
(prepare-record-menu thing))
((location? thing)
`((id ,(location-id thing))
(contents ,(contents thing))))
((weak-pointer? thing)
`((ref ,(weak-pointer-ref thing))))
(else '())))
(define (template->list template)
(do ((i (- (template-length template) 1) (- i 1))
(r '() (cons (template-ref template i) r)))
((< i 0) r)))
; Continuation menus have the both the saved operand stack and the
; save environment, for which names may be available.
(define (prepare-continuation-menu thing)
(let ((next (continuation-parent thing)))
`(,@(let recur ((c thing))
(if (eq? c next)
'()
(let ((z (continuation-arg-count c)))
(do ((i (- z 1) (- i 1))
(l (recur (continuation-cont c))
(cons (list #f (continuation-arg c i))
l)))
((< i 0) l)))))
,@(prepare-environment-menu (continuation-env thing)
(get-shape (continuation-debug-data thing)
(continuation-pc thing))))))
(define (continuation-debug-data thing)
(template-debug-data (continuation-template thing)))
; Records that have record types get printed with the names of the fields.
(define (prepare-record-menu thing)
(let ((rt (record-type thing))
(z (record-length thing)))
(if (record-type? rt)
(do ((i (- z 1) (- i 1))
(f (reverse (record-type-field-names rt)) (cdr f))
(l '() (cons (list (car f) (record-ref thing i)) l)))
((< i 1) l))
(do ((i (- z 1) (- i 1))
(l '() (cons (list #f (record-ref thing i)) l)))
((< i 0) l)))))
; We may have the names (`shape') for environments, in which case they
; are used in the menus.
(define (prepare-environment-menu env shape)
(if (vector? env)
(let ((values (rib-values env)))
(if (pair? shape)
(append (map list (car shape) values)
(prepare-environment-menu (vector-ref env 0)
(cdr shape)))
(append (map (lambda (x)
(list #f x))
values)
(prepare-environment-menu (vector-ref env 0)
shape))))
'()))
(define (rib-values env)
(let ((z (vector-length env)))
(do ((i 1 (+ i 1))
(l '() (cons (if (vector-unassigned? env i)
'unassigned
(vector-ref env i))
l)))
((>= i z) l))))
; Returns a list of proper lists describing the environment in effect
; at the given pc with the given template's code vector.
;
Entries in the environment - maps table ( one per template ) have the form
; #(parent-uid pc-in-parent (env-map ...))
;
Each environment map ( one per let or lambda - expression ) has the form
; #(pc-before pc-after (var ...) (env-map ...))
;
; Cf. procedure (note-environment vars segment) in comp.scm.
(define (get-shape dd pc)
(if (debug-data? dd)
(let loop ((emaps (debug-data-env-maps dd))
(shape (get-shape (get-debug-data
(debug-data-parent dd))
(debug-data-pc-in-parent dd))))
(if (null? emaps)
shape
(let ((pc-before (vector-ref (car emaps) 0))
(pc-after (vector-ref (car emaps) 1))
(vars (vector-ref (car emaps) 2))
(more-maps (vector-ref (car emaps) 3)))
(if (and (>= pc pc-before)
(< pc pc-after))
(loop more-maps
(cons (vector->list vars) shape))
(loop (cdr emaps) shape)))))
'()))
;----------------
; Printing menus.
;
If the current thing is a continuation we print its source code first .
; Then we step down the menu until we run out or we reach the menu limit.
(define (display-menu menu start port)
(newline port)
(maybe-display-source (focus-object) #f)
(let ((menu (list-tail menu start))
(limit (+ start *menu-limit*)))
(let loop ((i start) (menu menu))
(with-limited-output
(lambda ()
(cond ((null? menu))
((and (>= i limit)
(not (null? (cdr menu))))
(display " [m] more..." port) (newline port))
(else
(let ((item (car menu)))
(display " [" port)
(write i port)
(if (car item)
(begin (display ": " port)
(write-carefully (car item) port)))
(display "] " port)
(write-carefully
(value->expression (cadr item))
port)
(newline port)
(loop (+ i 1) (cdr menu))))))))))
; Exception continuations don't have source, so we get the source from
; the next continuation if it is from the same procedure invocation.
(define (maybe-display-source thing exception?)
(cond ((not (continuation? thing))
(values))
((exception-continuation? thing)
(let ((next (continuation-cont thing)))
(if (not (eq? next (continuation-parent thing)))
(maybe-display-source next #t))))
(else
(let ((dd (continuation-debug-data thing)))
(if dd
(let ((source (assoc (continuation-pc thing)
(debug-data-source dd))))
(if source
(display-source-info (cdr source) exception?))))))))
; Show the source code for a continuation, if we have it.
(define (display-source-info info exception?)
(if (pair? info)
(let ((o-port (command-output))
(i (car info))
(exp (cdr info)))
(if (and (integer? i) (list? exp))
(begin
(display (if exception?
"Next call is "
"Waiting for ")
o-port)
(limited-write (list-ref exp i) o-port
*write-depth* *write-length*)
(newline o-port)
(display " in " o-port)
(limited-write (append (sublist exp 0 i)
(list '^^^)
(list-tail exp (+ i 1)))
o-port
*write-depth* *write-length*)
(newline o-port))))))
;----------------
; A command to print out the file in which a procedure is defined.
; Why is this here and not in debug.scm?
(define-command-syntax 'where "[<procedure>]"
"show procedure's source file name"
'(&opt expression))
(define (where . maybe-exp)
(let ((proc (if (null? maybe-exp)
(focus-object)
(eval (car maybe-exp) (environment-for-commands))))
(port (command-output)))
(if (procedure? proc)
(let ((probe (where-defined proc)))
(if probe
(display probe port)
(display "Source file not recorded" port)))
(display "Not a procedure" port))
(newline port)))
(define (where-defined thing)
(let loop ((dd (template-debug-data (closure-template thing))))
(if (debug-data? dd)
(if (string? (debug-data-name dd))
(debug-data-name dd)
(loop (debug-data-parent dd)))
#f)))
;----------------
Utilities
(define (coerce-to-template obj)
(cond ((template? obj) obj)
((closure? obj) (closure-template obj))
((continuation? obj) (continuation-template obj))
(else (error "expected a procedure or continuation" obj))))
(define (with-limited-output thunk)
(let-fluids $write-depth *write-depth*
$write-length *write-length*
thunk))
| null | https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/scheme/env/inspect.scm | scheme | A dirty little inspector.
This breaks abstractions left and right.
Inspector state:
thing ; object currently being inspected, obtained as (focus-object)
menu ; cached result of (prepare-menu thing). This is a list of
lists (<name-or-#f> <value>).
position ; position within menu; modified by M (more) command
stack ; list of other things
The inspector is a distinct REPL with its own state. This allows the
user to continue with the same inspection stack after an error.
maximum menu entries
limit for recursive writes
ditto
initial objects:
,inspect -> focus object
,inspect <exp> -> value of <exp>
,debug -> continuation of stopped thread(s), preferentially
chooses the thread with the most recent error
,threads -> list of current command level's threads
----------------
Actual entry point for the inspector. We print the menu and then loop
reading commands.
command preferred
read command error
Go to a new thing by making a new inspector state.
Selection commands are either an integer, which selects a menu item,
or `u' to move up the stack, `d' to move to the next continuation
(only valid when the current object is a continuation), or `t' which
moves to a procedure's template (only valid when the current object
is a template).
no arguments
Execute a command.
We save the current object and state to compare to the new ones to see
if we need to display a new menu. The old object is pushed on the stack
only if nothing has been popped off.
Choose a new object.
Procedures for the various commands.
----------------
Menus.
A menu is a list of lists (<name-or-#f> <thing>).
Get a menu for THING. We know about a fixed set of types.
Continuation menus have the both the saved operand stack and the
save environment, for which names may be available.
Records that have record types get printed with the names of the fields.
We may have the names (`shape') for environments, in which case they
are used in the menus.
Returns a list of proper lists describing the environment in effect
at the given pc with the given template's code vector.
#(parent-uid pc-in-parent (env-map ...))
#(pc-before pc-after (var ...) (env-map ...))
Cf. procedure (note-environment vars segment) in comp.scm.
----------------
Printing menus.
Then we step down the menu until we run out or we reach the menu limit.
Exception continuations don't have source, so we get the source from
the next continuation if it is from the same procedure invocation.
Show the source code for a continuation, if we have it.
----------------
A command to print out the file in which a procedure is defined.
Why is this here and not in debug.scm?
---------------- | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
Look and feel shamelessly plagiarized from the Lucid Lisp inspector .
(define-record-type inspector-state inspector-state?
(make-inspector-state menu position stack)
(menu inspector-state-menu)
(position inspector-state-position set-inspector-state-position!)
(stack inspector-state-stack))
(define inspector-state repl-data)
(define set-inspector-state! set-repl-data!)
There are three commands for invoking the inspector with different
(define-command-syntax 'inspect "[<exp>]" "invoke the inspector"
'(&opt form))
(define-command-syntax 'debug "" "inspect the current continuation" '())
(define-command-syntax 'threads "" "inspect stopped threads" '())
(define (debug)
(showing-focus-object
(lambda ()
(set-focus-object! (or (command-continuation)
(command-threads)))))
(inspect))
(define (threads)
(showing-focus-object
(lambda ()
(set-focus-object! (command-threads))))
(inspect))
(define (inspect . maybe-exp)
(if (not (null? maybe-exp))
(with-limited-output
(lambda ()
(showing-focus-object
(lambda ()
(evaluate-and-select (car maybe-exp)
(environment-for-commands)))))))
(push-command-level inspector
(make-inspector-state (prepare-menu (focus-object))
0
'())))
(define (inspector)
(present-menu)
(let loop ()
(let ((command (read-command-carefully "inspect: "
(command-input)
inspector-commands)))
(cond ((eof-object? command)
(newline (command-output))
(proceed-with-command-level (cadr (command-levels))))
(loop))
(else
(with-limited-output
(lambda ()
(execute-inspector-command command)))
(loop))))))
(define (present-menu)
(let ((state (inspector-state)))
(display-menu (inspector-state-menu state)
(inspector-state-position state)
(command-output))))
(define (new-selection thing stack)
(set-inspector-state!
(make-inspector-state (prepare-menu thing) 0 stack)))
(define (read-selection-command port)
(let ((x (read port)))
(if (or (integer? x)
(memq x '(u d t)))
x
(read-command-error port "invalid selection command" x))))
(define selection-command-syntax (list '&rest read-selection-command))
(define (inspector-commands name)
(if (integer? name)
selection-command-syntax
(case name
((u d t) selection-command-syntax)
(else #f))))
(define (execute-inspector-command command)
(let ((result-before (focus-object))
(state-before (inspector-state)))
(showing-focus-object
(lambda ()
(let ((name (car command)))
(if (integer? name)
(execute-selection-command command)
(case name
((u d t)
(execute-selection-command command))
((m) (inspect-more))
((q) (proceed-with-command-level (cadr (command-levels))))
((?) (inspect-help))
(else (execute-command command)))))))
(let ((result-after (focus-object))
(state-after (inspector-state)))
(if (not (eq? result-after result-before))
(begin (if (eq? state-after state-before)
(new-selection result-after
(cons result-before
(inspector-state-stack state-before))))
(present-menu))))))
(define (execute-selection-command command)
(if (not (null? command))
(let ((name (car command)))
(if (integer? name)
(let ((menu (inspector-state-menu (inspector-state))))
(if (and (>= name 0)
(< name (length menu)))
(move-to-object! (menu-ref menu name))
(write-line "Invalid choice." (command-output))))
(case name
((u) (pop-inspector-stack))
((d) (inspect-next-continuation))
((t) (select-template))
(else (error "bad selection command" name))))
(execute-selection-command (cdr command)))))
(define (move-to-object! object)
(new-selection object
(cons (focus-object)
(inspector-state-stack (inspector-state))))
(set-focus-object! object))
(define (pop-inspector-stack)
(let ((stack (inspector-state-stack (inspector-state))))
(if (pair? stack)
(begin (new-selection (car stack) (cdr stack))
(set-focus-object! (car stack)))
(write-line "Can't go up from here." (command-output)))))
(define (inspect-next-continuation)
(if (continuation? (focus-object))
(move-to-object! (continuation-parent (focus-object)))
(write-line "Can't go down from a non-continuation." (command-output))))
(define (inspect-more)
(let* ((state (inspector-state))
(menu (inspector-state-menu state))
(position (inspector-state-position state)))
(if (> (length menu) (+ *menu-limit* position))
(let ((position (- (+ position *menu-limit*) 1)))
(set-inspector-state-position! state position)
(present-menu))
(write-line "There is no more." (command-output)))))
(define (select-template)
(move-to-object! (coerce-to-template (focus-object))))
(define (inspect-help)
(let ((o-port (command-output)))
(for-each (lambda (s) (display s o-port) (newline o-port))
'("q quit"
"u up stack (= go to previous object)"
"d down stack"
"t template"
"<integer> menu item"
"or any command processor command"
"multiple u d t <integer> commands can be put on one line"))))
(define (menu-ref menu n)
(cadr (list-ref menu n)))
(define (prepare-menu thing)
(cond ((list? thing)
(map (lambda (x)
(list #f x))
thing))
((pair? thing)
`((car ,(car thing)) (cdr ,(cdr thing))))
((vector? thing)
(prepare-menu (vector->list thing)))
((closure? thing)
(prepare-environment-menu
(closure-env thing)
(get-shape (template-debug-data (closure-template thing))
0)))
((template? thing)
(prepare-menu (template->list thing)))
((continuation? thing)
(prepare-continuation-menu thing))
((record? thing)
(prepare-record-menu thing))
((location? thing)
`((id ,(location-id thing))
(contents ,(contents thing))))
((weak-pointer? thing)
`((ref ,(weak-pointer-ref thing))))
(else '())))
(define (template->list template)
(do ((i (- (template-length template) 1) (- i 1))
(r '() (cons (template-ref template i) r)))
((< i 0) r)))
(define (prepare-continuation-menu thing)
(let ((next (continuation-parent thing)))
`(,@(let recur ((c thing))
(if (eq? c next)
'()
(let ((z (continuation-arg-count c)))
(do ((i (- z 1) (- i 1))
(l (recur (continuation-cont c))
(cons (list #f (continuation-arg c i))
l)))
((< i 0) l)))))
,@(prepare-environment-menu (continuation-env thing)
(get-shape (continuation-debug-data thing)
(continuation-pc thing))))))
(define (continuation-debug-data thing)
(template-debug-data (continuation-template thing)))
(define (prepare-record-menu thing)
(let ((rt (record-type thing))
(z (record-length thing)))
(if (record-type? rt)
(do ((i (- z 1) (- i 1))
(f (reverse (record-type-field-names rt)) (cdr f))
(l '() (cons (list (car f) (record-ref thing i)) l)))
((< i 1) l))
(do ((i (- z 1) (- i 1))
(l '() (cons (list #f (record-ref thing i)) l)))
((< i 0) l)))))
(define (prepare-environment-menu env shape)
(if (vector? env)
(let ((values (rib-values env)))
(if (pair? shape)
(append (map list (car shape) values)
(prepare-environment-menu (vector-ref env 0)
(cdr shape)))
(append (map (lambda (x)
(list #f x))
values)
(prepare-environment-menu (vector-ref env 0)
shape))))
'()))
(define (rib-values env)
(let ((z (vector-length env)))
(do ((i 1 (+ i 1))
(l '() (cons (if (vector-unassigned? env i)
'unassigned
(vector-ref env i))
l)))
((>= i z) l))))
Entries in the environment - maps table ( one per template ) have the form
Each environment map ( one per let or lambda - expression ) has the form
(define (get-shape dd pc)
(if (debug-data? dd)
(let loop ((emaps (debug-data-env-maps dd))
(shape (get-shape (get-debug-data
(debug-data-parent dd))
(debug-data-pc-in-parent dd))))
(if (null? emaps)
shape
(let ((pc-before (vector-ref (car emaps) 0))
(pc-after (vector-ref (car emaps) 1))
(vars (vector-ref (car emaps) 2))
(more-maps (vector-ref (car emaps) 3)))
(if (and (>= pc pc-before)
(< pc pc-after))
(loop more-maps
(cons (vector->list vars) shape))
(loop (cdr emaps) shape)))))
'()))
If the current thing is a continuation we print its source code first .
(define (display-menu menu start port)
(newline port)
(maybe-display-source (focus-object) #f)
(let ((menu (list-tail menu start))
(limit (+ start *menu-limit*)))
(let loop ((i start) (menu menu))
(with-limited-output
(lambda ()
(cond ((null? menu))
((and (>= i limit)
(not (null? (cdr menu))))
(display " [m] more..." port) (newline port))
(else
(let ((item (car menu)))
(display " [" port)
(write i port)
(if (car item)
(begin (display ": " port)
(write-carefully (car item) port)))
(display "] " port)
(write-carefully
(value->expression (cadr item))
port)
(newline port)
(loop (+ i 1) (cdr menu))))))))))
(define (maybe-display-source thing exception?)
(cond ((not (continuation? thing))
(values))
((exception-continuation? thing)
(let ((next (continuation-cont thing)))
(if (not (eq? next (continuation-parent thing)))
(maybe-display-source next #t))))
(else
(let ((dd (continuation-debug-data thing)))
(if dd
(let ((source (assoc (continuation-pc thing)
(debug-data-source dd))))
(if source
(display-source-info (cdr source) exception?))))))))
(define (display-source-info info exception?)
(if (pair? info)
(let ((o-port (command-output))
(i (car info))
(exp (cdr info)))
(if (and (integer? i) (list? exp))
(begin
(display (if exception?
"Next call is "
"Waiting for ")
o-port)
(limited-write (list-ref exp i) o-port
*write-depth* *write-length*)
(newline o-port)
(display " in " o-port)
(limited-write (append (sublist exp 0 i)
(list '^^^)
(list-tail exp (+ i 1)))
o-port
*write-depth* *write-length*)
(newline o-port))))))
(define-command-syntax 'where "[<procedure>]"
"show procedure's source file name"
'(&opt expression))
(define (where . maybe-exp)
(let ((proc (if (null? maybe-exp)
(focus-object)
(eval (car maybe-exp) (environment-for-commands))))
(port (command-output)))
(if (procedure? proc)
(let ((probe (where-defined proc)))
(if probe
(display probe port)
(display "Source file not recorded" port)))
(display "Not a procedure" port))
(newline port)))
(define (where-defined thing)
(let loop ((dd (template-debug-data (closure-template thing))))
(if (debug-data? dd)
(if (string? (debug-data-name dd))
(debug-data-name dd)
(loop (debug-data-parent dd)))
#f)))
Utilities
(define (coerce-to-template obj)
(cond ((template? obj) obj)
((closure? obj) (closure-template obj))
((continuation? obj) (continuation-template obj))
(else (error "expected a procedure or continuation" obj))))
(define (with-limited-output thunk)
(let-fluids $write-depth *write-depth*
$write-length *write-length*
thunk))
|
024573cabbe9a7a13f8f6025faeed914985271fc72127322653225e3fcd24db3 | input-output-hk/cardano-ledger-byron | SlotCount.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
# LANGUAGE GeneralizedNewtypeDeriving #
module Cardano.Chain.Slotting.SlotCount
( SlotCount(..)
)
where
import Cardano.Prelude
import Formatting.Buildable (Buildable)
import Cardano.Binary (FromCBOR, ToCBOR)
-- | A number of slots
newtype SlotCount = SlotCount
{ unSlotCount :: Word64
} deriving stock (Read, Show, Generic)
deriving newtype (Eq, Ord, Buildable, ToCBOR, FromCBOR)
deriving anyclass (NFData)
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger-byron/d309449e6c303a9f0dcc8dcf172df6f0b3195ed5/cardano-ledger/src/Cardano/Chain/Slotting/SlotCount.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
| A number of slots | # LANGUAGE GeneralizedNewtypeDeriving #
module Cardano.Chain.Slotting.SlotCount
( SlotCount(..)
)
where
import Cardano.Prelude
import Formatting.Buildable (Buildable)
import Cardano.Binary (FromCBOR, ToCBOR)
newtype SlotCount = SlotCount
{ unSlotCount :: Word64
} deriving stock (Read, Show, Generic)
deriving newtype (Eq, Ord, Buildable, ToCBOR, FromCBOR)
deriving anyclass (NFData)
|
d8704b410f434dcd240026a01789786df01ae044b710708f014777fa68238061 | ml4tp/tcoq | vernacentries.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Misctypes
val dump_global : Libnames.reference or_by_notation -> unit
* Vernacular entries
val show_prooftree : unit -> unit
val show_node : unit -> unit
val vernac_require :
Libnames.reference option -> bool option -> Libnames.reference list -> unit
(** This function can be used by any command that want to observe terms
in the context of the current goal *)
val get_current_context_of_args : int option -> Evd.evar_map * Environ.env
(** The main interpretation function of vernacular expressions *)
val interp :
?verbosely:bool ->
?proof:Proof_global.closed_proof ->
Loc.t * Vernacexpr.vernac_expr -> unit
* Print subgoals when the verbose flag is on .
Meant to be used inside vernac commands from plugins .
Meant to be used inside vernac commands from plugins. *)
val print_subgoals : unit -> unit
val try_print_subgoals : unit -> unit
(** The printing of goals via [print_subgoals] or during
[interp] can be controlled by the following flag.
Used for instance by coqide, since it has its own
goal-fetching mechanism. *)
val enable_goal_printing : bool ref
* Should Qed try to display the proof script ?
True by default , but false in ProofGeneral and coqIDE
True by default, but false in ProofGeneral and coqIDE *)
val qed_display_script : bool ref
(** Prepare a "match" template for a given inductive type.
For each branch of the match, we list the constructor name
followed by enough pattern variables.
[Not_found] is raised if the given string isn't the qualid of
a known inductive type. *)
val make_cases : string -> string list list
val vernac_end_proof :
?proof:Proof_global.closed_proof -> Vernacexpr.proof_end -> unit
val with_fail : bool -> (unit -> unit) -> unit
val command_focus : unit Proof.focus_kind
val interp_redexp_hook : (Environ.env -> Evd.evar_map -> Tacexpr.raw_red_expr ->
Evd.evar_map * Redexpr.red_expr) Hook.t
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/toplevel/vernacentries.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* This function can be used by any command that want to observe terms
in the context of the current goal
* The main interpretation function of vernacular expressions
* The printing of goals via [print_subgoals] or during
[interp] can be controlled by the following flag.
Used for instance by coqide, since it has its own
goal-fetching mechanism.
* Prepare a "match" template for a given inductive type.
For each branch of the match, we list the constructor name
followed by enough pattern variables.
[Not_found] is raised if the given string isn't the qualid of
a known inductive type. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Misctypes
val dump_global : Libnames.reference or_by_notation -> unit
* Vernacular entries
val show_prooftree : unit -> unit
val show_node : unit -> unit
val vernac_require :
Libnames.reference option -> bool option -> Libnames.reference list -> unit
val get_current_context_of_args : int option -> Evd.evar_map * Environ.env
val interp :
?verbosely:bool ->
?proof:Proof_global.closed_proof ->
Loc.t * Vernacexpr.vernac_expr -> unit
* Print subgoals when the verbose flag is on .
Meant to be used inside vernac commands from plugins .
Meant to be used inside vernac commands from plugins. *)
val print_subgoals : unit -> unit
val try_print_subgoals : unit -> unit
val enable_goal_printing : bool ref
* Should Qed try to display the proof script ?
True by default , but false in ProofGeneral and coqIDE
True by default, but false in ProofGeneral and coqIDE *)
val qed_display_script : bool ref
val make_cases : string -> string list list
val vernac_end_proof :
?proof:Proof_global.closed_proof -> Vernacexpr.proof_end -> unit
val with_fail : bool -> (unit -> unit) -> unit
val command_focus : unit Proof.focus_kind
val interp_redexp_hook : (Environ.env -> Evd.evar_map -> Tacexpr.raw_red_expr ->
Evd.evar_map * Redexpr.red_expr) Hook.t
|
d136a370343459b499dc392cb596ffc10b669a21ba2e8e3373b9bd10cd817d6f | TristanCacqueray/haskell-butler | Display.hs | -- | This module contains the logic to enable user access through HTTP.
module Butler.Display (
Display (..),
DisplayAddr (..),
AuthApplication (..),
OnClient,
startDisplay,
getClient,
DisplayEvent (..),
JwkStorage (..),
DisplayApplication (..),
module Butler.Display.Client,
-- * Application environment
serveApps,
serveDashboardApps,
) where
import Codec.Serialise.Decoding (decodeBytes)
import Codec.Serialise.Encoding (encodeBytes)
import Crypto.JOSE.JWK qualified as JOSE
import Data.Aeson (decodeStrict')
import Data.Attoparsec.ByteString.Char8 qualified as P
import Data.List (find)
import Data.Map.Strict qualified as Map
import Lucid
import Lucid.Htmx
import Network.HTTP.Types.Status qualified as HTTP
import Network.Socket
import Network.Wai qualified
import Network.WebSockets qualified as WS
import Servant
import Butler.App
import Butler.Core
import Butler.Core.Clock
import Butler.Core.Logger
import Butler.Core.Network
import Butler.Core.Process
import Butler.Core.Storage
import Butler.Display.Client
import Butler.Display.Session
import Butler.Display.WebSocket
import Butler.Prelude
import Butler.Window
import System.Posix.Env.ByteString (getEnv)
import XStatic.Butler
type OnClient = (Session -> Workspace -> ProcessIO (ProcessEnv, DisplayEvent -> ProcessIO ()))
newDisplay :: Sessions -> STM Display
newDisplay sessions = Display sessions <$> newTVar mempty
addDisplayClient :: Display -> DisplayClient -> STM ()
addDisplayClient display client = do
let alter = \case
Just clients -> Just (client : clients)
Nothing -> Just [client]
modifyTVar' display.clients (Map.alter alter client.session.sessionID)
getClient :: Display -> SessionID -> Endpoint -> STM (Maybe DisplayClient)
getClient display session endpoint = do
sessions <- readTVar display.clients
pure $ case Map.lookup session sessions of
Just clients -> Data.List.find (\c -> c.endpoint == endpoint) clients
Nothing -> Nothing
removeClient :: Display -> SessionID -> Endpoint -> STM ()
removeClient display session endpoint = do
let alter = \case
Just clients ->
let newClients = filter (\c -> c.endpoint /= endpoint) clients
in case newClients of
[] -> Nothing
xs -> Just xs
Nothing -> Nothing
modifyTVar' display.clients (Map.alter alter session)
dcSplash :: Html ()
dcSplash = do
with div_ [class_ "absolute top-0 left-0 z-50 bg-slate-200/80 flex h-screen w-screen"] do
with div_ [class_ "m-auto text-xl"] "Thanks for your time, see you next time!"
script_ "htmx.addClass(htmx.find('#display-pulse'), 'bg-red-500')"
newtype JwkStorage = JwkStorage JOSE.JWK
instance Serialise JwkStorage where
encode (JwkStorage jwk) = encodeBytes (from $ encodeJSON jwk)
decode = fmap decodeJWK decodeBytes
where
decodeJWK :: ByteString -> JwkStorage
decodeJWK bs = JwkStorage (fromMaybe (error "bad encoding?!") $ decodeStrict' bs)
connectRoute :: Display -> OnClient -> SockAddr -> Workspace -> ChannelName -> Session -> WS.Connection -> ProcessIO ()
connectRoute display onClient sockAddr workspaceM channel session connection = do
let clientAddr = from $ show sockAddr
ChannelName cn = channel
progName = "client-" <> cn
name = ProgramName $ progName <> "-" <> clientAddr
endpoint = Endpoint clientAddr
(processEnv, handler) <- onClient session workspaceM
clientM <- newEmptyMVar
clientProcess <- asProcess processEnv $ spawnProcess name do
clientProcess <- getSelfProcess
client <- atomically (newClient connection endpoint clientProcess session)
putMVar clientM client
-- Add the client to server state
let ev = UserConnected channel client
atomically do
addDisplayClient display client
handler ev
client <- takeMVar clientM
-- Wait for client completion
res <- atomically $ await clientProcess.thread
-- Remove the client from the server state
let ev = UserDisconnected channel client
atomically do
removeClient display session.sessionID endpoint
asProcess processEnv $ handler ev
logInfo "Client quit" ["endpoint" .= endpoint, "reason" .= into @Text res]
-- Say goodbye
case res of
Killed -> liftIO do
TODO : check for SocketClosed exception here
WS.sendTextData connection $ renderText do
with div_ [id_ "display-wins", class_ "h-full w-full", hxSwapOob_ "afterbegin"] dcSplash
WS.sendClose connection ("see you next time!" :: ByteString)
_ -> pure ()
data AuthApplication = AuthApplication
{ app :: WaiApplication
, getSession :: Maybe SessionID -> ProcessIO (Maybe Session)
}
data DisplayAddr = DisplayAddr WebProtocol Port
deriving (Eq)
defaultAddr :: DisplayAddr
defaultAddr = DisplayAddr (Https Nothing) 8085
| Parse listening addr
-- > > > displayAddrFromEnv " " @?= 8080
-- >>> displayAddrFromEnv "http:8080" @?= DisplayAddr Http 8080
-}
displayAddrFromEnv :: Maybe ByteString -> DisplayAddr
displayAddrFromEnv = \case
Nothing -> defaultAddr
Just env -> case P.parseOnly addrParser env of
Left e -> error $ "Invalid addr: " <> e
Right x -> x
where
addrParser :: P.Parser DisplayAddr
addrParser =
DisplayAddr
<$> (Http <$ "http:" <|> Https Nothing <$ "https:")
<*> P.decimal
startDisplay :: Maybe DisplayAddr -> [XStaticFile] -> (Sessions -> ProcessIO AuthApplication) -> (Display -> ProcessIO OnClient) -> ProcessIO Void
startDisplay mAddr xfiles mkAuthApp withDisplay = withSessions \sessions -> do
DisplayAddr proto port <- case mAddr of
Nothing -> displayAddrFromEnv <$> liftIO (getEnv "BUTLER_ADDR")
Just addr -> pure addr
display <- atomically (newDisplay sessions)
authApp <- mkAuthApp sessions
onClient <- withDisplay display
env <- ask
let wsSrv :: ServerT WebSocketAPI ProcessIO
wsSrv = websocketServer authApp.getSession (connectRoute display onClient)
wsApp :: WaiApplication
wsApp = Servant.serveWithContextT (Proxy @WebSocketAPI) EmptyContext (liftIO . runProcessIO env.os env.process) wsSrv
glApp req resp =
let wsRespHandler wsResp = case HTTP.statusCode (Network.Wai.responseStatus wsResp) of
404 -> authApp.app req resp
_ -> resp wsResp
in wsApp req wsRespHandler
webService xfiles glApp port proto
newtype DisplayApplication
= DisplayApplication
( [XStaticFile] -> (Sessions -> ProcessIO AuthApplication)
)
data SessionApps = SessionApps
{ env :: ProcessEnv
, clients :: DisplayClients
, shared :: AppSharedContext
}
-- | Group apps per session.
newtype AllSessionApps = AllSessionApps (MVar (Map SessionID SessionApps))
startSessionApps :: AllSessionApps -> Display -> SessionID -> [App] -> ProcessIO SessionApps
startSessionApps (AllSessionApps mv) display sessionID apps =
modifyMVar mv \allSessionApps -> case Map.lookup sessionID allSessionApps of
Just sa -> pure (allSessionApps, sa)
Nothing -> do
clients <- atomically newDisplayClients
Create a MVar so that the process can pass the created AppSharedContext
mvShared <- newEmptyMVar
-- Create a new process to manage a given session
process <- doStartSessionApps clients mvShared
-- Read the AppSharedContext
shared <- takeMVar mvShared
-- Create the SessionApps
os <- asks os
let sessionEnv = ProcessEnv os process
sa = SessionApps sessionEnv clients shared
pure (Map.insert sessionID sa allSessionApps, sa)
where
processName = ProgramName $ "sess-" <> into @Text sessionID
storageAddr = StorageAddress "sess-" <> into sessionID
doStartSessionApps clients mvShared = spawnProcess processName $ chroot storageAddr do
-- Start the apps
shared <- startApps apps display clients
Pass the created AppSharedContext
putMVar mvShared shared
-- Wait until all clients disconnected
waitForDisconnect clients
-- Remove the sa
modifyMVar_ mv (pure . Map.delete sessionID)
waitForDisconnect clients = fix \loop -> do
sleep 5_000
atomically (getClients clients) >>= \case
(_ : _) ->
-- clients are still connected, keep on waiting.
loop
[] -> do
clients are disconnected , wait 5 more seconds .
sleep 5_000
atomically (getClients clients) >>= \case
(_ : _) ->
-- a client connected back, likely a refresh, keep on waiting.
loop
[] ->
-- this is the end, exit the scope
pure ()
| Serve applications with one instance per client .
serveApps :: DisplayApplication -> [App] -> ProcessIO Void
serveApps (DisplayApplication mkAuth) apps = do
void $
waitProcess =<< superviseProcess "gui" do
startDisplay Nothing xfiles (mkAuth xfiles) $ \display -> do
allSessionApps <- AllSessionApps <$> newMVar mempty
pure $ \session _ws -> do
sa <- startSessionApps allSessionApps display session.sessionID apps
pure (sa.env, staticClientHandler sa.clients sa.shared)
error "Display exited?!"
where
xfiles = concatMap (.xfiles) apps <> defaultXFiles
| Serve applications with one instance for all clients .
serveDashboardApps :: DisplayApplication -> [App] -> ProcessIO Void
serveDashboardApps (DisplayApplication mkAuth) apps = do
void $
waitProcess =<< superviseProcess "gui" do
startDisplay Nothing xfiles (mkAuth xfiles) $ \display -> do
clients <- atomically newDisplayClients
shared <- startApps apps display clients
pure $ \_session _ws -> do
env <- ask
pure (env, staticClientHandler clients shared)
error "Display exited?!"
where
xfiles = concatMap (.xfiles) apps <> defaultXFiles
staticClientHandler :: DisplayClients -> AppSharedContext -> DisplayEvent -> ProcessIO ()
staticClientHandler clients shared displayEvent = case displayEvent of
UserConnected "htmx" client -> do
spawnThread_ (pingThread client)
spawnThread_ (sendThread client)
atomically $ addClient clients client
appInstances <- atomically (getApps shared.apps)
atomically $ sendHtml client do
with div_ [id_ "display-wins", class_ "flex"] do
forM_ appInstances \appInstance -> do
with div_ [wid_ appInstance.wid "w"] mempty
forM_ appInstances \appInstance -> writePipe appInstance.pipeAE (AppDisplay displayEvent)
forever do
dataMessage <- recvData client
case eventFromMessage client dataMessage of
Nothing -> logError "Unknown data" ["ev" .= LBSLog (into @LByteString dataMessage)]
Just (wid, ae) -> case Map.lookup wid appInstances of
Just appInstance -> writePipe appInstance.pipeAE ae
Nothing -> logError "Unknown wid" ["wid" .= wid]
UserDisconnected "htmx" client -> do
logInfo "Client disconnected" ["client" .= client]
atomically $ delClient clients client
appInstances <- atomically (getApps shared.apps)
forM_ appInstances \appInstance -> do
writePipe appInstance.pipeAE (AppDisplay displayEvent)
_ -> logError "Unknown event" ["ev" .= displayEvent]
| null | https://raw.githubusercontent.com/TristanCacqueray/haskell-butler/68cde9a74c530c7652c1dadf9a487b35ec0d0ab4/src/Butler/Display.hs | haskell | | This module contains the logic to enable user access through HTTP.
* Application environment
Add the client to server state
Wait for client completion
Remove the client from the server state
Say goodbye
> > > displayAddrFromEnv " " @?= 8080
>>> displayAddrFromEnv "http:8080" @?= DisplayAddr Http 8080
| Group apps per session.
Create a new process to manage a given session
Read the AppSharedContext
Create the SessionApps
Start the apps
Wait until all clients disconnected
Remove the sa
clients are still connected, keep on waiting.
a client connected back, likely a refresh, keep on waiting.
this is the end, exit the scope | module Butler.Display (
Display (..),
DisplayAddr (..),
AuthApplication (..),
OnClient,
startDisplay,
getClient,
DisplayEvent (..),
JwkStorage (..),
DisplayApplication (..),
module Butler.Display.Client,
serveApps,
serveDashboardApps,
) where
import Codec.Serialise.Decoding (decodeBytes)
import Codec.Serialise.Encoding (encodeBytes)
import Crypto.JOSE.JWK qualified as JOSE
import Data.Aeson (decodeStrict')
import Data.Attoparsec.ByteString.Char8 qualified as P
import Data.List (find)
import Data.Map.Strict qualified as Map
import Lucid
import Lucid.Htmx
import Network.HTTP.Types.Status qualified as HTTP
import Network.Socket
import Network.Wai qualified
import Network.WebSockets qualified as WS
import Servant
import Butler.App
import Butler.Core
import Butler.Core.Clock
import Butler.Core.Logger
import Butler.Core.Network
import Butler.Core.Process
import Butler.Core.Storage
import Butler.Display.Client
import Butler.Display.Session
import Butler.Display.WebSocket
import Butler.Prelude
import Butler.Window
import System.Posix.Env.ByteString (getEnv)
import XStatic.Butler
type OnClient = (Session -> Workspace -> ProcessIO (ProcessEnv, DisplayEvent -> ProcessIO ()))
newDisplay :: Sessions -> STM Display
newDisplay sessions = Display sessions <$> newTVar mempty
addDisplayClient :: Display -> DisplayClient -> STM ()
addDisplayClient display client = do
let alter = \case
Just clients -> Just (client : clients)
Nothing -> Just [client]
modifyTVar' display.clients (Map.alter alter client.session.sessionID)
getClient :: Display -> SessionID -> Endpoint -> STM (Maybe DisplayClient)
getClient display session endpoint = do
sessions <- readTVar display.clients
pure $ case Map.lookup session sessions of
Just clients -> Data.List.find (\c -> c.endpoint == endpoint) clients
Nothing -> Nothing
removeClient :: Display -> SessionID -> Endpoint -> STM ()
removeClient display session endpoint = do
let alter = \case
Just clients ->
let newClients = filter (\c -> c.endpoint /= endpoint) clients
in case newClients of
[] -> Nothing
xs -> Just xs
Nothing -> Nothing
modifyTVar' display.clients (Map.alter alter session)
dcSplash :: Html ()
dcSplash = do
with div_ [class_ "absolute top-0 left-0 z-50 bg-slate-200/80 flex h-screen w-screen"] do
with div_ [class_ "m-auto text-xl"] "Thanks for your time, see you next time!"
script_ "htmx.addClass(htmx.find('#display-pulse'), 'bg-red-500')"
newtype JwkStorage = JwkStorage JOSE.JWK
instance Serialise JwkStorage where
encode (JwkStorage jwk) = encodeBytes (from $ encodeJSON jwk)
decode = fmap decodeJWK decodeBytes
where
decodeJWK :: ByteString -> JwkStorage
decodeJWK bs = JwkStorage (fromMaybe (error "bad encoding?!") $ decodeStrict' bs)
connectRoute :: Display -> OnClient -> SockAddr -> Workspace -> ChannelName -> Session -> WS.Connection -> ProcessIO ()
connectRoute display onClient sockAddr workspaceM channel session connection = do
let clientAddr = from $ show sockAddr
ChannelName cn = channel
progName = "client-" <> cn
name = ProgramName $ progName <> "-" <> clientAddr
endpoint = Endpoint clientAddr
(processEnv, handler) <- onClient session workspaceM
clientM <- newEmptyMVar
clientProcess <- asProcess processEnv $ spawnProcess name do
clientProcess <- getSelfProcess
client <- atomically (newClient connection endpoint clientProcess session)
putMVar clientM client
let ev = UserConnected channel client
atomically do
addDisplayClient display client
handler ev
client <- takeMVar clientM
res <- atomically $ await clientProcess.thread
let ev = UserDisconnected channel client
atomically do
removeClient display session.sessionID endpoint
asProcess processEnv $ handler ev
logInfo "Client quit" ["endpoint" .= endpoint, "reason" .= into @Text res]
case res of
Killed -> liftIO do
TODO : check for SocketClosed exception here
WS.sendTextData connection $ renderText do
with div_ [id_ "display-wins", class_ "h-full w-full", hxSwapOob_ "afterbegin"] dcSplash
WS.sendClose connection ("see you next time!" :: ByteString)
_ -> pure ()
data AuthApplication = AuthApplication
{ app :: WaiApplication
, getSession :: Maybe SessionID -> ProcessIO (Maybe Session)
}
data DisplayAddr = DisplayAddr WebProtocol Port
deriving (Eq)
defaultAddr :: DisplayAddr
defaultAddr = DisplayAddr (Https Nothing) 8085
| Parse listening addr
-}
displayAddrFromEnv :: Maybe ByteString -> DisplayAddr
displayAddrFromEnv = \case
Nothing -> defaultAddr
Just env -> case P.parseOnly addrParser env of
Left e -> error $ "Invalid addr: " <> e
Right x -> x
where
addrParser :: P.Parser DisplayAddr
addrParser =
DisplayAddr
<$> (Http <$ "http:" <|> Https Nothing <$ "https:")
<*> P.decimal
startDisplay :: Maybe DisplayAddr -> [XStaticFile] -> (Sessions -> ProcessIO AuthApplication) -> (Display -> ProcessIO OnClient) -> ProcessIO Void
startDisplay mAddr xfiles mkAuthApp withDisplay = withSessions \sessions -> do
DisplayAddr proto port <- case mAddr of
Nothing -> displayAddrFromEnv <$> liftIO (getEnv "BUTLER_ADDR")
Just addr -> pure addr
display <- atomically (newDisplay sessions)
authApp <- mkAuthApp sessions
onClient <- withDisplay display
env <- ask
let wsSrv :: ServerT WebSocketAPI ProcessIO
wsSrv = websocketServer authApp.getSession (connectRoute display onClient)
wsApp :: WaiApplication
wsApp = Servant.serveWithContextT (Proxy @WebSocketAPI) EmptyContext (liftIO . runProcessIO env.os env.process) wsSrv
glApp req resp =
let wsRespHandler wsResp = case HTTP.statusCode (Network.Wai.responseStatus wsResp) of
404 -> authApp.app req resp
_ -> resp wsResp
in wsApp req wsRespHandler
webService xfiles glApp port proto
newtype DisplayApplication
= DisplayApplication
( [XStaticFile] -> (Sessions -> ProcessIO AuthApplication)
)
data SessionApps = SessionApps
{ env :: ProcessEnv
, clients :: DisplayClients
, shared :: AppSharedContext
}
newtype AllSessionApps = AllSessionApps (MVar (Map SessionID SessionApps))
startSessionApps :: AllSessionApps -> Display -> SessionID -> [App] -> ProcessIO SessionApps
startSessionApps (AllSessionApps mv) display sessionID apps =
modifyMVar mv \allSessionApps -> case Map.lookup sessionID allSessionApps of
Just sa -> pure (allSessionApps, sa)
Nothing -> do
clients <- atomically newDisplayClients
Create a MVar so that the process can pass the created AppSharedContext
mvShared <- newEmptyMVar
process <- doStartSessionApps clients mvShared
shared <- takeMVar mvShared
os <- asks os
let sessionEnv = ProcessEnv os process
sa = SessionApps sessionEnv clients shared
pure (Map.insert sessionID sa allSessionApps, sa)
where
processName = ProgramName $ "sess-" <> into @Text sessionID
storageAddr = StorageAddress "sess-" <> into sessionID
doStartSessionApps clients mvShared = spawnProcess processName $ chroot storageAddr do
shared <- startApps apps display clients
Pass the created AppSharedContext
putMVar mvShared shared
waitForDisconnect clients
modifyMVar_ mv (pure . Map.delete sessionID)
waitForDisconnect clients = fix \loop -> do
sleep 5_000
atomically (getClients clients) >>= \case
(_ : _) ->
loop
[] -> do
clients are disconnected , wait 5 more seconds .
sleep 5_000
atomically (getClients clients) >>= \case
(_ : _) ->
loop
[] ->
pure ()
| Serve applications with one instance per client .
serveApps :: DisplayApplication -> [App] -> ProcessIO Void
serveApps (DisplayApplication mkAuth) apps = do
void $
waitProcess =<< superviseProcess "gui" do
startDisplay Nothing xfiles (mkAuth xfiles) $ \display -> do
allSessionApps <- AllSessionApps <$> newMVar mempty
pure $ \session _ws -> do
sa <- startSessionApps allSessionApps display session.sessionID apps
pure (sa.env, staticClientHandler sa.clients sa.shared)
error "Display exited?!"
where
xfiles = concatMap (.xfiles) apps <> defaultXFiles
| Serve applications with one instance for all clients .
serveDashboardApps :: DisplayApplication -> [App] -> ProcessIO Void
serveDashboardApps (DisplayApplication mkAuth) apps = do
void $
waitProcess =<< superviseProcess "gui" do
startDisplay Nothing xfiles (mkAuth xfiles) $ \display -> do
clients <- atomically newDisplayClients
shared <- startApps apps display clients
pure $ \_session _ws -> do
env <- ask
pure (env, staticClientHandler clients shared)
error "Display exited?!"
where
xfiles = concatMap (.xfiles) apps <> defaultXFiles
staticClientHandler :: DisplayClients -> AppSharedContext -> DisplayEvent -> ProcessIO ()
staticClientHandler clients shared displayEvent = case displayEvent of
UserConnected "htmx" client -> do
spawnThread_ (pingThread client)
spawnThread_ (sendThread client)
atomically $ addClient clients client
appInstances <- atomically (getApps shared.apps)
atomically $ sendHtml client do
with div_ [id_ "display-wins", class_ "flex"] do
forM_ appInstances \appInstance -> do
with div_ [wid_ appInstance.wid "w"] mempty
forM_ appInstances \appInstance -> writePipe appInstance.pipeAE (AppDisplay displayEvent)
forever do
dataMessage <- recvData client
case eventFromMessage client dataMessage of
Nothing -> logError "Unknown data" ["ev" .= LBSLog (into @LByteString dataMessage)]
Just (wid, ae) -> case Map.lookup wid appInstances of
Just appInstance -> writePipe appInstance.pipeAE ae
Nothing -> logError "Unknown wid" ["wid" .= wid]
UserDisconnected "htmx" client -> do
logInfo "Client disconnected" ["client" .= client]
atomically $ delClient clients client
appInstances <- atomically (getApps shared.apps)
forM_ appInstances \appInstance -> do
writePipe appInstance.pipeAE (AppDisplay displayEvent)
_ -> logError "Unknown event" ["ev" .= displayEvent]
|
3d1dce7dc5013d9117be4f31b725126a5cb927b573923fc4374598681799e74f | f-o-a-m/kepler | Metrics.hs | module Network.ABCI.Server.Middleware.Metrics
( defaultBuckets
, mkMetricsMiddleware
) where
import Control.Monad (forM_)
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.IORef as Ref
import qualified Data.Map.Strict as Map
import Data.String.Conversions (cs)
import Data.Time (diffUTCTime,
getCurrentTime)
import Network.ABCI.Server.App (App (..),
MessageType (..),
Middleware,
demoteRequestType,
msgTypeKey)
import qualified System.Metrics.Prometheus.Concurrent.Registry as Registry
import qualified System.Metrics.Prometheus.Metric.Counter as Counter
import qualified System.Metrics.Prometheus.Metric.Histogram as Histogram
import qualified System.Metrics.Prometheus.MetricId as MetricId
---------------------------------------------------------------------------
-- mkMetrics
---------------------------------------------------------------------------
| Metrics logger middleware for ABCI server already within the KatipContext .
Great for ` App m ` with a ` KatipContext ` instance .
mkMetricsMiddleware
:: MonadIO m
=> [Histogram.UpperBound]
-> Registry.Registry
-> IO (Middleware m)
mkMetricsMiddleware buckets registry = do
Config{..} <- makeConfig buckets registry
return $ \(App app) -> App $ \ req -> do
startTime <- liftIO getCurrentTime
res <- app req
endTime <- liftIO getCurrentTime
let msgType = demoteRequestType req
duration = realToFrac $ diffUTCTime endTime startTime
liftIO $ do
incRequestCounter cfgCounterMap msgType
addToHistogram cfgHistogramMap msgType duration
pure res
where
incRequestCounter counterMapRef msgType = do
counter <- do
counterMap <- Ref.readIORef counterMapRef
case Map.lookup msgType counterMap of
Nothing -> error $ "Impossible missing counter for " <> msgTypeKey msgType
Just c -> return c
Counter.inc counter
addToHistogram histogramMapRef msgType duration = do
histogram <- do
histMap <- Ref.readIORef histogramMapRef
case Map.lookup msgType histMap of
Nothing -> error $ "Impossible missing histogram for " <> msgTypeKey msgType
Just c -> return c
Histogram.observe duration histogram
data Config = Config
{ cfgRegistry :: Registry.Registry
, cfgHistogramBuckets :: [Histogram.UpperBound]
, cfgCounterMap :: Ref.IORef (Map.Map MessageType Counter.Counter)
, cfgHistogramMap :: Ref.IORef (Map.Map MessageType Histogram.Histogram)
}
makeConfig
:: [Histogram.UpperBound]
-> Registry.Registry
-> IO Config
makeConfig bounds registry = do
counterMap <- Ref.newIORef Map.empty
histMap <- Ref.newIORef Map.empty
let cfg = Config
{ cfgRegistry = registry
, cfgHistogramBuckets = bounds
, cfgCounterMap = counterMap
, cfgHistogramMap = histMap
}
registerMetrics cfg
return cfg
registerMetrics
:: Config
-> IO ()
registerMetrics Config{..} = do
registerHistograms cfgHistogramBuckets cfgRegistry cfgHistogramMap
registerCounters cfgRegistry cfgCounterMap
where
registerHistograms
:: [Histogram.UpperBound]
-> Registry.Registry
-> Ref.IORef (Map.Map MessageType Histogram.Histogram)
-> IO ()
registerHistograms buckets registry histRef =
let histName = "abci_request_duration_seconds"
in forM_ [MTEcho .. MTCommit] $ \messageType -> do
let labels = MetricId.Labels . Map.fromList $
[ ("message_type", cs $ msgTypeKey messageType)
]
hist <- Registry.registerHistogram histName labels buckets registry
Ref.modifyIORef' histRef (Map.insert messageType hist)
registerCounters
:: Registry.Registry
-> Ref.IORef (Map.Map MessageType Counter.Counter)
-> IO ()
registerCounters registry counterRef =
let counterName = "abci_request_total"
in forM_ [MTEcho .. MTCommit] $ \messageType -> do
let labels = MetricId.Labels . Map.fromList $
[ ("message_type", cs $ msgTypeKey messageType)
]
counter <- Registry.registerCounter counterName labels registry
Ref.modifyIORef' counterRef (Map.insert messageType counter)
buckets with upper bounds [ 0.005 , 0.01 , 0.015 ... 5.0 ]
measured in seconds
defaultBuckets :: [Histogram.UpperBound]
defaultBuckets = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0]
| null | https://raw.githubusercontent.com/f-o-a-m/kepler/6c1ad7f37683f509c2f1660e3561062307d3056b/hs-abci-extra/src/Network/ABCI/Server/Middleware/Metrics.hs | haskell | -------------------------------------------------------------------------
mkMetrics
------------------------------------------------------------------------- | module Network.ABCI.Server.Middleware.Metrics
( defaultBuckets
, mkMetricsMiddleware
) where
import Control.Monad (forM_)
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.IORef as Ref
import qualified Data.Map.Strict as Map
import Data.String.Conversions (cs)
import Data.Time (diffUTCTime,
getCurrentTime)
import Network.ABCI.Server.App (App (..),
MessageType (..),
Middleware,
demoteRequestType,
msgTypeKey)
import qualified System.Metrics.Prometheus.Concurrent.Registry as Registry
import qualified System.Metrics.Prometheus.Metric.Counter as Counter
import qualified System.Metrics.Prometheus.Metric.Histogram as Histogram
import qualified System.Metrics.Prometheus.MetricId as MetricId
| Metrics logger middleware for ABCI server already within the KatipContext .
Great for ` App m ` with a ` KatipContext ` instance .
mkMetricsMiddleware
:: MonadIO m
=> [Histogram.UpperBound]
-> Registry.Registry
-> IO (Middleware m)
mkMetricsMiddleware buckets registry = do
Config{..} <- makeConfig buckets registry
return $ \(App app) -> App $ \ req -> do
startTime <- liftIO getCurrentTime
res <- app req
endTime <- liftIO getCurrentTime
let msgType = demoteRequestType req
duration = realToFrac $ diffUTCTime endTime startTime
liftIO $ do
incRequestCounter cfgCounterMap msgType
addToHistogram cfgHistogramMap msgType duration
pure res
where
incRequestCounter counterMapRef msgType = do
counter <- do
counterMap <- Ref.readIORef counterMapRef
case Map.lookup msgType counterMap of
Nothing -> error $ "Impossible missing counter for " <> msgTypeKey msgType
Just c -> return c
Counter.inc counter
addToHistogram histogramMapRef msgType duration = do
histogram <- do
histMap <- Ref.readIORef histogramMapRef
case Map.lookup msgType histMap of
Nothing -> error $ "Impossible missing histogram for " <> msgTypeKey msgType
Just c -> return c
Histogram.observe duration histogram
data Config = Config
{ cfgRegistry :: Registry.Registry
, cfgHistogramBuckets :: [Histogram.UpperBound]
, cfgCounterMap :: Ref.IORef (Map.Map MessageType Counter.Counter)
, cfgHistogramMap :: Ref.IORef (Map.Map MessageType Histogram.Histogram)
}
makeConfig
:: [Histogram.UpperBound]
-> Registry.Registry
-> IO Config
makeConfig bounds registry = do
counterMap <- Ref.newIORef Map.empty
histMap <- Ref.newIORef Map.empty
let cfg = Config
{ cfgRegistry = registry
, cfgHistogramBuckets = bounds
, cfgCounterMap = counterMap
, cfgHistogramMap = histMap
}
registerMetrics cfg
return cfg
registerMetrics
:: Config
-> IO ()
registerMetrics Config{..} = do
registerHistograms cfgHistogramBuckets cfgRegistry cfgHistogramMap
registerCounters cfgRegistry cfgCounterMap
where
registerHistograms
:: [Histogram.UpperBound]
-> Registry.Registry
-> Ref.IORef (Map.Map MessageType Histogram.Histogram)
-> IO ()
registerHistograms buckets registry histRef =
let histName = "abci_request_duration_seconds"
in forM_ [MTEcho .. MTCommit] $ \messageType -> do
let labels = MetricId.Labels . Map.fromList $
[ ("message_type", cs $ msgTypeKey messageType)
]
hist <- Registry.registerHistogram histName labels buckets registry
Ref.modifyIORef' histRef (Map.insert messageType hist)
registerCounters
:: Registry.Registry
-> Ref.IORef (Map.Map MessageType Counter.Counter)
-> IO ()
registerCounters registry counterRef =
let counterName = "abci_request_total"
in forM_ [MTEcho .. MTCommit] $ \messageType -> do
let labels = MetricId.Labels . Map.fromList $
[ ("message_type", cs $ msgTypeKey messageType)
]
counter <- Registry.registerCounter counterName labels registry
Ref.modifyIORef' counterRef (Map.insert messageType counter)
buckets with upper bounds [ 0.005 , 0.01 , 0.015 ... 5.0 ]
measured in seconds
defaultBuckets :: [Histogram.UpperBound]
defaultBuckets = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.