_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 |
|---|---|---|---|---|---|---|---|---|
9f0ea6d9da43f079e554e45b0c54263d7f71d5b8ca212dcfb190b005c8b7cd38 | alanz/ghc-exactprint | T10134a.hs | # LANGUAGE KindSignatures #
{-# LANGUAGE GADTs #-}
# LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
module T10134a where
import GHC.TypeLits
data Vec :: Nat -> Type -> Type where
Nil :: Vec 0 a
(:>) :: a -> Vec n a -> Vec (n + 1) a
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc86/T10134a.hs | haskell | # LANGUAGE GADTs # | # LANGUAGE KindSignatures #
# LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
module T10134a where
import GHC.TypeLits
data Vec :: Nat -> Type -> Type where
Nil :: Vec 0 a
(:>) :: a -> Vec n a -> Vec (n + 1) a
|
500ea5c5070e42b1c1dcc4bb265fd3772100466f7cb100d3eda0fbec7428f622 | jonasseglare/geex | type_test.clj | (ns geex.ebmd.type-test
(:require [geex.ebmd.type :as type]
[bluebell.utils.ebmd :as ebmd]
[clojure.test :refer :all]
[geex.core.seed :as seed]))
(deftest primitive-test
(is (ebmd/matches-arg-spec? ::type/double-value 3.0))
(is (ebmd/matches-arg-spec? ::type/float-value (float 3.0)))
(is (ebmd/matches-arg-spec? ::type/int-value (int 3)))
(is (ebmd/matches-arg-spec? ::type/long-value (long 3)))
(is (ebmd/matches-arg-spec? ::type/short-value (short 3)))
(is (ebmd/matches-arg-spec? ::type/byte-value (byte 3)))
(is (ebmd/matches-arg-spec? ::type/char-value (char 3)))
(is (ebmd/matches-arg-spec? ::type/boolean-value (boolean false))))
(ebmd/declare-poly add-0)
(ebmd/def-poly add-0 [::type/boolean-value a
::type/boolean-value b]
(or a b))
(ebmd/def-poly add-0 [::type/double-value a
::type/double-value b]
[:double (+ a b)])
(ebmd/def-poly add-0 [::type/float-value a
::type/float-value b]
[:float (+ a b)])
(deftest add-0-test
(is (= true (add-0 false true)))
(is (= [:double 3.7] (add-0 2 1.7)))
(is (= [:float 3.0] (add-0 2 (float 1.0)))))
(ebmd/declare-poly add-1)
(ebmd/def-poly add-1 [::type/real-value a
::type/real-value b]
[:real (+ a b)])
(ebmd/def-poly add-1 [::type/integer-value a
::type/integer-value b]
[:integer (+ a b)])
(ebmd/def-poly add-1 [::type/coll-value a
::type/coll-value b]
(into a b))
(ebmd/def-poly add-1 [::type/real-array-value a
::type/real-array-value b]
(double-array (map + (vec a) (vec b))))
(ebmd/def-poly add-1 [::type/real a
::type/real b]
[:common-real a b])
(deftest add-1-test
(is (= [:real 3.4] (add-1 1.4 2)))
(is (= [:integer 3] (add-1 1 2)))
(is (= #{1 2 3} (add-1 #{1 2} [3])))
(is (= [11.0 22.0 33.0]
(vec (add-1 (double-array [1 2 3])
(int-array [10 20 30])))))
(is (= (first (add-1 (seed/typed-seed Double/TYPE)
3))
:common-real)))
(deftest resolve-type-test
(is (nil? (type/resolve-type :kattskit)))
(is (= :kattskit
(type/resolve-type
(seed/typed-seed :kattskit))))
(is (= java.lang.AbstractMethodError
(type/resolve-type
java.lang.AbstractMethodError)))
(is (= Long/TYPE
(type/resolve-type ::type/long))))
| null | https://raw.githubusercontent.com/jonasseglare/geex/f1a48c14c983c054c91fb221b91f42de5fa8eee0/test/geex/ebmd/type_test.clj | clojure | (ns geex.ebmd.type-test
(:require [geex.ebmd.type :as type]
[bluebell.utils.ebmd :as ebmd]
[clojure.test :refer :all]
[geex.core.seed :as seed]))
(deftest primitive-test
(is (ebmd/matches-arg-spec? ::type/double-value 3.0))
(is (ebmd/matches-arg-spec? ::type/float-value (float 3.0)))
(is (ebmd/matches-arg-spec? ::type/int-value (int 3)))
(is (ebmd/matches-arg-spec? ::type/long-value (long 3)))
(is (ebmd/matches-arg-spec? ::type/short-value (short 3)))
(is (ebmd/matches-arg-spec? ::type/byte-value (byte 3)))
(is (ebmd/matches-arg-spec? ::type/char-value (char 3)))
(is (ebmd/matches-arg-spec? ::type/boolean-value (boolean false))))
(ebmd/declare-poly add-0)
(ebmd/def-poly add-0 [::type/boolean-value a
::type/boolean-value b]
(or a b))
(ebmd/def-poly add-0 [::type/double-value a
::type/double-value b]
[:double (+ a b)])
(ebmd/def-poly add-0 [::type/float-value a
::type/float-value b]
[:float (+ a b)])
(deftest add-0-test
(is (= true (add-0 false true)))
(is (= [:double 3.7] (add-0 2 1.7)))
(is (= [:float 3.0] (add-0 2 (float 1.0)))))
(ebmd/declare-poly add-1)
(ebmd/def-poly add-1 [::type/real-value a
::type/real-value b]
[:real (+ a b)])
(ebmd/def-poly add-1 [::type/integer-value a
::type/integer-value b]
[:integer (+ a b)])
(ebmd/def-poly add-1 [::type/coll-value a
::type/coll-value b]
(into a b))
(ebmd/def-poly add-1 [::type/real-array-value a
::type/real-array-value b]
(double-array (map + (vec a) (vec b))))
(ebmd/def-poly add-1 [::type/real a
::type/real b]
[:common-real a b])
(deftest add-1-test
(is (= [:real 3.4] (add-1 1.4 2)))
(is (= [:integer 3] (add-1 1 2)))
(is (= #{1 2 3} (add-1 #{1 2} [3])))
(is (= [11.0 22.0 33.0]
(vec (add-1 (double-array [1 2 3])
(int-array [10 20 30])))))
(is (= (first (add-1 (seed/typed-seed Double/TYPE)
3))
:common-real)))
(deftest resolve-type-test
(is (nil? (type/resolve-type :kattskit)))
(is (= :kattskit
(type/resolve-type
(seed/typed-seed :kattskit))))
(is (= java.lang.AbstractMethodError
(type/resolve-type
java.lang.AbstractMethodError)))
(is (= Long/TYPE
(type/resolve-type ::type/long))))
| |
94a2c2bcab42a711888d71ae1c533772af24235d4c4f175cb93aa87e1161fa9c | ctford/overtunes | organ_cornet.clj | (ns overtunes.instruments.organ-cornet
(:use [overtone.live])
)
From by .
(defcgen triangle-osc [freq phase {:default 0.0} harmonics {:default 40}]
(:ar (let
[
harmonic-numbers (take harmonics (iterate (partial + 2) 1))
every 4n -1 is
;; there a better way?!
]
(klang [
(map #(* freq %) harmonic-numbers ) ;; harmonics
(map #(/ 1.0 (* % %)) harmonic-numbers) ;; inverse square ampl
(map #(+ phase %) (map #(if (cosines %) (. Math PI) 0.0 ) harmonic-numbers )) ;; conditional phase shift by pi
])
))
)
(defcgen organ-env [dur {:default 1000} vol {:default 1.0}]
( :kr
(* vol
(env-gen (asr 0.1 1.0 0.5) (line:kr 1.0 0.0 (/ dur 1000)) :timeScale (/ dur 1000) :action FREE )))
)
(definst organ-cornet [freq 440 dur 1000 vol 1.0]
(*
(organ-env :dur dur :vol vol)
(apply +
(map
#(triangle-osc (* freq %)) (range 1 5)) )
0.25
)
)
| null | https://raw.githubusercontent.com/ctford/overtunes/44dc2d6482315e1893cf19000cfe3381a2c41da4/src/overtunes/instruments/organ_cornet.clj | clojure | there a better way?!
harmonics
inverse square ampl
conditional phase shift by pi | (ns overtunes.instruments.organ-cornet
(:use [overtone.live])
)
From by .
(defcgen triangle-osc [freq phase {:default 0.0} harmonics {:default 40}]
(:ar (let
[
harmonic-numbers (take harmonics (iterate (partial + 2) 1))
every 4n -1 is
]
(klang [
])
))
)
(defcgen organ-env [dur {:default 1000} vol {:default 1.0}]
( :kr
(* vol
(env-gen (asr 0.1 1.0 0.5) (line:kr 1.0 0.0 (/ dur 1000)) :timeScale (/ dur 1000) :action FREE )))
)
(definst organ-cornet [freq 440 dur 1000 vol 1.0]
(*
(organ-env :dur dur :vol vol)
(apply +
(map
#(triangle-osc (* freq %)) (range 1 5)) )
0.25
)
)
|
68d13471b6a6badb3d6dfe2075489c6c1524d12e4eefd1eba627d912654d5a9e | k0ral/hbro | Core.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module Hbro.Core (
-- * Types
CaseSensitivity(..)
, Direction(..)
, Wrap(..)
, ZoomDirection(..)
-- * Getters
, getCurrentURI
, getFaviconURI
, getFavicon
, getLoadProgress
, getPageTitle
, getPageData
-- * Browsing
, goHome
, load
, reload
, reloadBypassCache
, stopLoading
, goBack
, goForward
-- * Other
, printPage
, searchText
, searchText_
, spawnHbro
, spawnHbro'
, quit
, saveWebPage
, executeJSFile
) where
-- {{{ Imports
import Graphics.UI.Gtk.WebKit.Extended
import Hbro.Config as Config
import Hbro.Dyre
import Hbro.Error
import Hbro.Gui.MainView
import Hbro.Logger
import Hbro.Prelude as H
import Control.Concurrent.STM.MonadIO
import Data.IOData
import Graphics.UI.Gtk.Gdk.Pixbuf (Pixbuf)
import Graphics.UI.Gtk.General.General.Extended
import Graphics.UI.Gtk.WebKit.WebDataSource
import Graphics.UI.Gtk.WebKit.WebFrame
import Network.URI.Extended
import System.Process.Extended
-- }}}
-- {{{ Types
data CaseSensitivity = CaseSensitive | CaseInsensitive
instance ToBool CaseSensitivity where
toBool CaseSensitive = True
toBool CaseInsensitive = False
data Direction = Forward | Backward
instance ToBool Direction where
toBool Forward = True
toBool Backward = False
data Wrap = Wrap | NoWrap
instance ToBool Wrap where
toBool Wrap = True
toBool NoWrap = False
data ZoomDirection = In | Out
-- }}}
-- {{{ Getters
getCurrentURI :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m URI
getCurrentURI = webViewGetUri =<< getWebView
getFaviconURI :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m URI
getFaviconURI = webViewGetIconUri =<< getWebView
getFavicon :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => Int -> Int -> m Pixbuf
getFavicon w h = (\v -> webViewTryGetFaviconPixbuf v w h) =<< getWebView
getLoadProgress :: (MonadIO m, MonadReader r m, Has MainView r) => m Double
getLoadProgress = gSync . webViewGetProgress =<< getWebView
getPageTitle :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m Text
getPageTitle = webViewGetTitle =<< getWebView
-- | Return the HTML code of the current webpage.
getPageData :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m ByteString
getPageData = dataSourceGetData =<< io . webFrameGetDataSource =<< io . webViewGetMainFrame =<< getWebView
-- }}}
-- {{{ Browsing
goHome :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r, Has (TVar Config) r, MonadThrow m) => m ()
goHome = load =<< Config.get homePage_
load :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r, MonadThrow m) => URI -> m ()
load uri = do
debug $ "Loading URI: " <> show uri
-- void . logErrors $ do
-- currentURI <- getURI
-- guard (currentURI /= uri')
-- Browser.advance currentURI
-- load' uri'
webview <- getWebView
gSync . webViewLoadUri webview $ (show uri' :: Text)
where
uri' = case uriScheme uri of
[] -> uri { uriScheme = "http://" }
_ -> uri
-- baseOf uri = uri {
-- uriPath = (++ "/") . join "/" . Prelude.init . split "/" $ uriPath uri
-- }
load ' : : ( MonadBaseControl IO m , MonadReader GUI m , HasHTTPClient t , MonadThrow m ) = > URI - > m ( )
-- load' uri = do
-- page <- Client.retrieve uri
-- -- render page =<< Client.getURI
-- render page uri
reload, goBack, goForward :: (MonadIO m, MonadReader r m, Has MainView r, MonadLogger m) => m ()
-- reload = load =<< Client.getURI
-- goBack = load' =<< Browser.stepBackward =<< getURI
-- goForward = load' =<< Browser.stepForward =<< getURI
reload = gAsync . webViewReload =<< getWebView
goBack = do
(gSync . webViewCanGoBack =<< getWebView) >>= (`unless` warning "Unable to go back.")
gAsync . webViewGoBack =<< getWebView
goForward = do
(gSync . webViewCanGoForward =<< getWebView) >>= (`unless` warning "Unable to go forward.")
gAsync . webViewGoForward =<< getWebView
reloadBypassCache, stopLoading :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r) => m ()
reloadBypassCache = getWebView >>= gAsync . webViewReloadBypassCache >> debug "Reloading without cache."
stopLoading = getWebView >>= gAsync . webViewStopLoading >> debug "Stopped loading"
-- }}}
-- {{{
searchText :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r) => CaseSensitivity -> Direction -> Wrap -> Text -> m Bool
searchText s d w text = do
debug $ "Searching text: " <> text
v <- getWebView
gSync $ webViewSearchText v text (toBool s) (toBool d) (toBool w)
searchText_ :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r) => CaseSensitivity -> Direction -> Wrap -> Text -> m ()
searchText_ s d w text = void $ searchText s d w text
printPage :: (MonadIO m, MonadReader r m, Has MainView r) => m ()
printPage = gAsync . webFramePrint =<< gSync . webViewGetMainFrame =<< getWebView
-- }}}
-- | Spawn another browser instance.
spawnHbro :: (MonadIO m, MonadLogger m) => m ()
spawnHbro = do
executable <- getHbroExecutable
spawn (pack executable) []
-- | Spawn another browser instance and load the given URI at start-up.
spawnHbro' :: (MonadIO m, MonadLogger m) => URI -> m ()
spawnHbro' uri = do
executable <- getHbroExecutable
spawn (pack executable) ["-u", show uri]
-- | Terminate the program.
quit :: (MonadIO m) => m ()
quit = gAsync mainQuit
-- {{{ Misc
saveWebPage :: (ControlIO m, MonadLogger m, MonadReader r m, Has MainView r, MonadThrow m) => FilePath -> m ()
saveWebPage file = writeFile file =<< getPageData
-- | Execute a javascript file on current webpage.
executeJSFile :: (MonadIO m, MonadLogger m) => FilePath -> WebView -> m ()
executeJSFile filePath webView' = do
debug $ "Executing Javascript file: " <> pack filePath
script <- readFile filePath
let script' = unwords . map (<> "\n") . lines $ script
gAsync $ webViewExecuteScript webView' (script' :: Text)
-- }}}
-- | Save current web page to a file,
-- along with all its resources in a separated directory.
-- Doesn't work for now, because web_resource_get_data's binding is missing...
_savePage :: Text -> WebView -> IO ()
_savePage _path webView' = do
frame <- webViewGetMainFrame webView'
dataSource <- webFrameGetDataSource frame
_mainResource <- webDataSourceGetMainResource dataSource
_subResources <- webDataSourceGetSubresources dataSource
return ()
| null | https://raw.githubusercontent.com/k0ral/hbro/8926b53960eb7136c4dec94eb31f2426fa34c726/library/Hbro/Core.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE OverloadedStrings #
* Types
* Getters
* Browsing
* Other
{{{ Imports
}}}
{{{ Types
}}}
{{{ Getters
| Return the HTML code of the current webpage.
}}}
{{{ Browsing
void . logErrors $ do
currentURI <- getURI
guard (currentURI /= uri')
Browser.advance currentURI
load' uri'
baseOf uri = uri {
uriPath = (++ "/") . join "/" . Prelude.init . split "/" $ uriPath uri
}
load' uri = do
page <- Client.retrieve uri
-- render page =<< Client.getURI
render page uri
reload = load =<< Client.getURI
goBack = load' =<< Browser.stepBackward =<< getURI
goForward = load' =<< Browser.stepForward =<< getURI
}}}
{{{
}}}
| Spawn another browser instance.
| Spawn another browser instance and load the given URI at start-up.
| Terminate the program.
{{{ Misc
| Execute a javascript file on current webpage.
}}}
| Save current web page to a file,
along with all its resources in a separated directory.
Doesn't work for now, because web_resource_get_data's binding is missing... | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module Hbro.Core (
CaseSensitivity(..)
, Direction(..)
, Wrap(..)
, ZoomDirection(..)
, getCurrentURI
, getFaviconURI
, getFavicon
, getLoadProgress
, getPageTitle
, getPageData
, goHome
, load
, reload
, reloadBypassCache
, stopLoading
, goBack
, goForward
, printPage
, searchText
, searchText_
, spawnHbro
, spawnHbro'
, quit
, saveWebPage
, executeJSFile
) where
import Graphics.UI.Gtk.WebKit.Extended
import Hbro.Config as Config
import Hbro.Dyre
import Hbro.Error
import Hbro.Gui.MainView
import Hbro.Logger
import Hbro.Prelude as H
import Control.Concurrent.STM.MonadIO
import Data.IOData
import Graphics.UI.Gtk.Gdk.Pixbuf (Pixbuf)
import Graphics.UI.Gtk.General.General.Extended
import Graphics.UI.Gtk.WebKit.WebDataSource
import Graphics.UI.Gtk.WebKit.WebFrame
import Network.URI.Extended
import System.Process.Extended
data CaseSensitivity = CaseSensitive | CaseInsensitive
instance ToBool CaseSensitivity where
toBool CaseSensitive = True
toBool CaseInsensitive = False
data Direction = Forward | Backward
instance ToBool Direction where
toBool Forward = True
toBool Backward = False
data Wrap = Wrap | NoWrap
instance ToBool Wrap where
toBool Wrap = True
toBool NoWrap = False
data ZoomDirection = In | Out
getCurrentURI :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m URI
getCurrentURI = webViewGetUri =<< getWebView
getFaviconURI :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m URI
getFaviconURI = webViewGetIconUri =<< getWebView
getFavicon :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => Int -> Int -> m Pixbuf
getFavicon w h = (\v -> webViewTryGetFaviconPixbuf v w h) =<< getWebView
getLoadProgress :: (MonadIO m, MonadReader r m, Has MainView r) => m Double
getLoadProgress = gSync . webViewGetProgress =<< getWebView
getPageTitle :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m Text
getPageTitle = webViewGetTitle =<< getWebView
getPageData :: (MonadIO m, MonadReader r m, Has MainView r, MonadThrow m) => m ByteString
getPageData = dataSourceGetData =<< io . webFrameGetDataSource =<< io . webViewGetMainFrame =<< getWebView
goHome :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r, Has (TVar Config) r, MonadThrow m) => m ()
goHome = load =<< Config.get homePage_
load :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r, MonadThrow m) => URI -> m ()
load uri = do
debug $ "Loading URI: " <> show uri
webview <- getWebView
gSync . webViewLoadUri webview $ (show uri' :: Text)
where
uri' = case uriScheme uri of
[] -> uri { uriScheme = "http://" }
_ -> uri
load ' : : ( MonadBaseControl IO m , MonadReader GUI m , HasHTTPClient t , MonadThrow m ) = > URI - > m ( )
reload, goBack, goForward :: (MonadIO m, MonadReader r m, Has MainView r, MonadLogger m) => m ()
reload = gAsync . webViewReload =<< getWebView
goBack = do
(gSync . webViewCanGoBack =<< getWebView) >>= (`unless` warning "Unable to go back.")
gAsync . webViewGoBack =<< getWebView
goForward = do
(gSync . webViewCanGoForward =<< getWebView) >>= (`unless` warning "Unable to go forward.")
gAsync . webViewGoForward =<< getWebView
reloadBypassCache, stopLoading :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r) => m ()
reloadBypassCache = getWebView >>= gAsync . webViewReloadBypassCache >> debug "Reloading without cache."
stopLoading = getWebView >>= gAsync . webViewStopLoading >> debug "Stopped loading"
searchText :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r) => CaseSensitivity -> Direction -> Wrap -> Text -> m Bool
searchText s d w text = do
debug $ "Searching text: " <> text
v <- getWebView
gSync $ webViewSearchText v text (toBool s) (toBool d) (toBool w)
searchText_ :: (MonadIO m, MonadLogger m, MonadReader r m, Has MainView r) => CaseSensitivity -> Direction -> Wrap -> Text -> m ()
searchText_ s d w text = void $ searchText s d w text
printPage :: (MonadIO m, MonadReader r m, Has MainView r) => m ()
printPage = gAsync . webFramePrint =<< gSync . webViewGetMainFrame =<< getWebView
spawnHbro :: (MonadIO m, MonadLogger m) => m ()
spawnHbro = do
executable <- getHbroExecutable
spawn (pack executable) []
spawnHbro' :: (MonadIO m, MonadLogger m) => URI -> m ()
spawnHbro' uri = do
executable <- getHbroExecutable
spawn (pack executable) ["-u", show uri]
quit :: (MonadIO m) => m ()
quit = gAsync mainQuit
saveWebPage :: (ControlIO m, MonadLogger m, MonadReader r m, Has MainView r, MonadThrow m) => FilePath -> m ()
saveWebPage file = writeFile file =<< getPageData
executeJSFile :: (MonadIO m, MonadLogger m) => FilePath -> WebView -> m ()
executeJSFile filePath webView' = do
debug $ "Executing Javascript file: " <> pack filePath
script <- readFile filePath
let script' = unwords . map (<> "\n") . lines $ script
gAsync $ webViewExecuteScript webView' (script' :: Text)
_savePage :: Text -> WebView -> IO ()
_savePage _path webView' = do
frame <- webViewGetMainFrame webView'
dataSource <- webFrameGetDataSource frame
_mainResource <- webDataSourceGetMainResource dataSource
_subResources <- webDataSourceGetSubresources dataSource
return ()
|
0d579afdfefab93b07ad819c59d8d34ce5caf1f5945b7c856dd1811381796983 | quil-lang/qvm | grovel-system-constants.lisp | (in-package #:qvm)
#+unix
(progn
(include "unistd.h")
(constant ($sc-nprocessors-onln "_SC_NPROCESSORS_ONLN") :optional nil)
(constant ($sc-page-size "_SC_PAGE_SIZE") :optional nil)
)
| null | https://raw.githubusercontent.com/quil-lang/qvm/de95ead6e7df70a1f8e0212455a802bd0cef201c/src/grovel-system-constants.lisp | lisp | (in-package #:qvm)
#+unix
(progn
(include "unistd.h")
(constant ($sc-nprocessors-onln "_SC_NPROCESSORS_ONLN") :optional nil)
(constant ($sc-page-size "_SC_PAGE_SIZE") :optional nil)
)
| |
f33609a72d3bb72dfacf376201fde2acda0ef8f728342d989f397b1d75eab144 | godfat/sandbox | fib.hs | fib = 0 : 1 : [x+y | (x, y) <- zip fib (tail fib)]
combos = [(x, y) | x <- [0..1], y <- [2..3]]
fib = [ 0 , 1 ] + List[lambda{|x , y| } ]
combos = List[->(x , y){[x , y ] } , 0 .. 1 , 2 .. 3 ]
fib = [0, 1] + List[lambda{|x,y|}]
combos = List[->(x,y){[x,y]}, 0..1, 2..3]
-}
| null | https://raw.githubusercontent.com/godfat/sandbox/eb6294238f92543339adfdfb4ba88586ba0e82b8/haskell/fib.hs | haskell | fib = 0 : 1 : [x+y | (x, y) <- zip fib (tail fib)]
combos = [(x, y) | x <- [0..1], y <- [2..3]]
fib = [ 0 , 1 ] + List[lambda{|x , y| } ]
combos = List[->(x , y){[x , y ] } , 0 .. 1 , 2 .. 3 ]
fib = [0, 1] + List[lambda{|x,y|}]
combos = List[->(x,y){[x,y]}, 0..1, 2..3]
-}
| |
357aff64fe7df4c011ddfdbfd4963ccd8f584dd5caea4be2a5d4c0b3fbc3344d | kayhide/wakame | Wakame.hs | module Wakame
( module X
) where
import Wakame.Generics ()
import Wakame.Keys as X
import Wakame.Lacks as X
import Wakame.Merge as X
import Wakame.Nub as X
import Wakame.Row as X
import Wakame.Union as X
| null | https://raw.githubusercontent.com/kayhide/wakame/4d16ecf2221655300b5db588c2775cfc0b8d92cd/src/Wakame.hs | haskell | module Wakame
( module X
) where
import Wakame.Generics ()
import Wakame.Keys as X
import Wakame.Lacks as X
import Wakame.Merge as X
import Wakame.Nub as X
import Wakame.Row as X
import Wakame.Union as X
| |
a041822e86f220c2e5f9839529bb58aa8b72ecbf43e4eb6e654c89864564a5ab | markcox80/specialization-store | packages.lisp | (defpackage "SPECIALIZATION-STORE.TESTS"
(:use "COMMON-LISP"
"SPECIALIZATION-STORE"
"5AM")
(:export "ALL-TESTS"
"PROCESS-SYNTAX-LAYER-TESTS"))
(defpackage "SPECIALIZATION-STORE.LAMBDA-LISTS.TESTS"
(:use "COMMON-LISP"
"SPECIALIZATION-STORE.LAMBDA-LISTS"
"5AM")
(:export "LAMBDA-LIST-TESTS"))
(defpackage "SPECIALIZATION-STORE.STANDARD-STORE.TESTS"
(:use "COMMON-LISP"
"SPECIALIZATION-STORE"
"SPECIALIZATION-STORE.STANDARD-STORE"
"5AM")
(:export "STANDARD-STORE-TESTS"))
(5am:def-suite specialization-store.tests:all-tests)
(5am:def-suite specialization-store.lambda-lists.tests:lambda-list-tests :in specialization-store.tests:all-tests)
(5am:def-suite specialization-store.standard-store.tests:standard-store-tests :in specialization-store.tests:all-tests)
| null | https://raw.githubusercontent.com/markcox80/specialization-store/8d39a866a6f24986aad3cc52349e9cb2653496f3/tests/packages.lisp | lisp | (defpackage "SPECIALIZATION-STORE.TESTS"
(:use "COMMON-LISP"
"SPECIALIZATION-STORE"
"5AM")
(:export "ALL-TESTS"
"PROCESS-SYNTAX-LAYER-TESTS"))
(defpackage "SPECIALIZATION-STORE.LAMBDA-LISTS.TESTS"
(:use "COMMON-LISP"
"SPECIALIZATION-STORE.LAMBDA-LISTS"
"5AM")
(:export "LAMBDA-LIST-TESTS"))
(defpackage "SPECIALIZATION-STORE.STANDARD-STORE.TESTS"
(:use "COMMON-LISP"
"SPECIALIZATION-STORE"
"SPECIALIZATION-STORE.STANDARD-STORE"
"5AM")
(:export "STANDARD-STORE-TESTS"))
(5am:def-suite specialization-store.tests:all-tests)
(5am:def-suite specialization-store.lambda-lists.tests:lambda-list-tests :in specialization-store.tests:all-tests)
(5am:def-suite specialization-store.standard-store.tests:standard-store-tests :in specialization-store.tests:all-tests)
| |
dddcc95c97a7199545ec98788cca5f1a3182669b08b4bfeb3d4f65e7bfa7c1ee | mimoo/nixbyexample | main.ml | let () = Byexample.main ()
| null | https://raw.githubusercontent.com/mimoo/nixbyexample/d5575b796ba2e0022af069d1fc71cfa20f8c8754/tools/bin/main.ml | ocaml | let () = Byexample.main ()
| |
9a6ce3b95a77148ffaf1b859ae1deb22d185bf3b9c6e9135053c7b485bbba430 | ku-fpg/hermit | DataKinds.hs | # LANGUAGE GADTs , KindSignatures , DataKinds , TypeFamilies , TypeOperators #
module Main where
import Prelude hiding ((++),zipWith)
data Nat = Zero | Succ Nat
data Vec :: * -> Nat -> * where
Nil :: Vec a Zero
Cons :: a -> Vec a n -> Vec a (Succ n)
type family (m :: Nat) :+: (n :: Nat) :: Nat
type instance Zero :+: n = n
type instance (Succ m) :+: n = Succ (m :+: n)
(++) :: Vec a m -> Vec a n -> Vec a (m :+: n)
Nil ++ bs = bs
(a `Cons` as) ++ bs = a `Cons` (as ++ bs)
zipWith :: (a -> b -> c) -> Vec a n -> Vec b n -> Vec c n
zipWith f Nil Nil = Nil
zipWith f (Cons a as) (Cons b bs) = Cons (f a b) (zipWith f as bs)
------------------------------------------------
main :: IO ()
main = print "hello world"
------------------------------------------------
| null | https://raw.githubusercontent.com/ku-fpg/hermit/3e7be430fae74a9e3860b8b574f36efbf9648dec/examples/Talks/interact-with-hermit/DataKinds.hs | haskell | ----------------------------------------------
---------------------------------------------- | # LANGUAGE GADTs , KindSignatures , DataKinds , TypeFamilies , TypeOperators #
module Main where
import Prelude hiding ((++),zipWith)
data Nat = Zero | Succ Nat
data Vec :: * -> Nat -> * where
Nil :: Vec a Zero
Cons :: a -> Vec a n -> Vec a (Succ n)
type family (m :: Nat) :+: (n :: Nat) :: Nat
type instance Zero :+: n = n
type instance (Succ m) :+: n = Succ (m :+: n)
(++) :: Vec a m -> Vec a n -> Vec a (m :+: n)
Nil ++ bs = bs
(a `Cons` as) ++ bs = a `Cons` (as ++ bs)
zipWith :: (a -> b -> c) -> Vec a n -> Vec b n -> Vec c n
zipWith f Nil Nil = Nil
zipWith f (Cons a as) (Cons b bs) = Cons (f a b) (zipWith f as bs)
main :: IO ()
main = print "hello world"
|
1307412f709b867d0bf99d88c653ca300311a7996a3097dbc79e172eb8ffd143 | BinaryAnalysisPlatform/bap | emit_ida_script_main.ml | open Core_kernel[@@warning "-D"]
open Bap.Std
open Format
include Self()
module Buffer = Caml.Buffer
* uses a strange color coding , bgr , IIRC
let idacode_of_color = function
| `black -> 0x000000
| `red -> 0xCCCCFF
| `green -> 0x99FF99
| `yellow -> 0xC2FFFF
| `blue -> 0xFFB2B2
| `magenta -> 0xFFB2FF
| `cyan -> 0xFFFFB2
| `white -> 0xFFFFFF
| `gray -> 0xEAEAEA
| _ -> invalid_arg "unexpected color"
let string_of_color c = Sexp.to_string (sexp_of_color c)
* Each function in this module should return a string that should be
a valid piece of python code . Except for the prologue and epilogue
all pieces should be independent of each other , so that they can
be emitted to the script in an arbitrary order .
The emitted code can contain substitutions . Each substitution is a
string starting with a percent sign followed immediately by an
alpha numeric sequence , denoting the name , e.g. , [ $ name ] . The
substitution name can be also delimited with curly brackets , e.g. ,
[ $ { name } ] . Currently the following substitutions are supported
( i.e. , valid names are ):
" sub_name " - name of a parent subroutine
" addr " - an address of instruction that produced the term , or
None otherwise .
a valid piece of python code. Except for the prologue and epilogue
all pieces should be independent of each other, so that they can
be emitted to the script in an arbitrary order.
The emitted code can contain substitutions. Each substitution is a
string starting with a percent sign followed immediately by an
alpha numeric sequence, denoting the name, e.g., [$name]. The
substitution name can be also delimited with curly brackets, e.g.,
[${name}]. Currently the following substitutions are supported
(i.e., valid names are):
"sub_name" - name of a parent subroutine
"addr" - an address of instruction that produced the term, or
None otherwise.*)
module Py = struct
(** this is emitted at the start of the script *)
let prologue =
{|
from bap.utils import ida
|}
(** this is emitted at the end of the script *)
let epilogue =
{|
# eplogue code if needed
|}
let escape = unstage @@ String.Escaping.escape
~escapeworthy:['\''; '\\'; '$']
~escape_char:'\\'
let color s = sprintf "ida.set_color($addr, 0x%06x)" (idacode_of_color s)
let comment s =
sprintf "ida.comment.add($addr, '%s', '%s')"
(escape (Value.tagname s)) (escape (Value.to_string s))
let foreground s =
sprintf "ida.comment.add($addr, 'foreground', '%s')" (string_of_color s)
let background s =
sprintf "ida.comment.add($addr, 'background', '%s')" (string_of_color s)
end
(** [emit_attr buffer sub_name insn_addr attr] emits into the [buffer]
a python code that corresponds to the given attribute [attr], that
is attached to a term that occurs in the scope of a function with
a name [sub_name]. If the term is non-artifical, then [insn_addr]
is an address of a corresponding instruction, otherwise it is
[None].*)
let emit_attr buf sub_name addr attr =
let open Value.Match in
let substitute = function
| "sub_name" -> sub_name
| "addr" -> asprintf "%a" Word.pp_hex addr
| s -> s in
let case tag f = case tag (fun attr ->
Buffer.add_substitute buf substitute (f attr);
Buffer.add_char buf '\n') in
switch attr @@
case color Py.color @@
case foreground Py.foreground @@
case background Py.background @@
default (fun () ->
Buffer.add_substitute buf substitute (Py.comment attr);
Buffer.add_char buf '\n')
let program_visitor buf attrs =
object
inherit [string * word option] Term.visitor
method! leave_term _ t (name,addr) =
match addr with
| None -> name,addr
| Some addr ->
Term.attrs t |> Dict.to_sequence |> Seq.iter ~f:(fun (_,x) ->
let attr = Value.tagname x in
if List.mem ~equal:String.equal attrs attr
then emit_attr buf name addr x);
name,Some addr
method! enter_term _ t (name,_) =
name,Term.get_attr t address
method! enter_sub sub (_,addr) = Sub.name sub,addr
end
let extract_script data code attrs =
let open Value.Match in
let buf = Buffer.create 4096 in
Buffer.add_string buf Py.prologue;
Memmap.to_sequence data |> Seq.iter ~f:(fun (mem,x) ->
switch x @@
case python (fun line -> Buffer.add_string buf line) @@
default ignore);
(program_visitor buf attrs)#run code ("",None) |> ignore;
Buffer.add_string buf Py.epilogue;
Buffer.contents buf
let main dst attrs project =
let data = Project.memory project in
let code = Project.program project in
let data = extract_script data code attrs in
match dst with
| None -> print_string data
| Some dst -> Out_channel.write_all dst ~data
let () =
let () = Config.manpage [
`S "DESCRIPTION";
`P "Iterates through memory for tagged BIR attributes,
and dumps them into a python script, that can be later
loaded into IDA. The special `color' tag causes the
respective address to be colored.";
`S "SEE ALSO";
`P "$(b,bap-ida)(3), $(b,bap-plugin-ida)(1)"
] in
let dst = Config.(param (some string) "file" ~docv:"NAME"
~doc:"Dump annotations to the specified file $(docv). If
not specified, then the script will dumped into the
standard output") in
let attrs = Config.(param_all string "attr"
~doc: "Emit specified BIR attribute. Can be specified
multiple times.") in
Config.declare_extension ~doc:"generates IDA Python scripts"
~provides:["ida"; "python"; "pass"]
(fun {Config.get=(!)} ->
let main = main !dst !attrs in
Project.register_pass' main )
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/cbdf732d46c8e38df79d9942fc49bcb97915c657/plugins/emit_ida_script/emit_ida_script_main.ml | ocaml | * this is emitted at the start of the script
* this is emitted at the end of the script
* [emit_attr buffer sub_name insn_addr attr] emits into the [buffer]
a python code that corresponds to the given attribute [attr], that
is attached to a term that occurs in the scope of a function with
a name [sub_name]. If the term is non-artifical, then [insn_addr]
is an address of a corresponding instruction, otherwise it is
[None]. | open Core_kernel[@@warning "-D"]
open Bap.Std
open Format
include Self()
module Buffer = Caml.Buffer
* uses a strange color coding , bgr , IIRC
let idacode_of_color = function
| `black -> 0x000000
| `red -> 0xCCCCFF
| `green -> 0x99FF99
| `yellow -> 0xC2FFFF
| `blue -> 0xFFB2B2
| `magenta -> 0xFFB2FF
| `cyan -> 0xFFFFB2
| `white -> 0xFFFFFF
| `gray -> 0xEAEAEA
| _ -> invalid_arg "unexpected color"
let string_of_color c = Sexp.to_string (sexp_of_color c)
* Each function in this module should return a string that should be
a valid piece of python code . Except for the prologue and epilogue
all pieces should be independent of each other , so that they can
be emitted to the script in an arbitrary order .
The emitted code can contain substitutions . Each substitution is a
string starting with a percent sign followed immediately by an
alpha numeric sequence , denoting the name , e.g. , [ $ name ] . The
substitution name can be also delimited with curly brackets , e.g. ,
[ $ { name } ] . Currently the following substitutions are supported
( i.e. , valid names are ):
" sub_name " - name of a parent subroutine
" addr " - an address of instruction that produced the term , or
None otherwise .
a valid piece of python code. Except for the prologue and epilogue
all pieces should be independent of each other, so that they can
be emitted to the script in an arbitrary order.
The emitted code can contain substitutions. Each substitution is a
string starting with a percent sign followed immediately by an
alpha numeric sequence, denoting the name, e.g., [$name]. The
substitution name can be also delimited with curly brackets, e.g.,
[${name}]. Currently the following substitutions are supported
(i.e., valid names are):
"sub_name" - name of a parent subroutine
"addr" - an address of instruction that produced the term, or
None otherwise.*)
module Py = struct
let prologue =
{|
from bap.utils import ida
|}
let epilogue =
{|
# eplogue code if needed
|}
let escape = unstage @@ String.Escaping.escape
~escapeworthy:['\''; '\\'; '$']
~escape_char:'\\'
let color s = sprintf "ida.set_color($addr, 0x%06x)" (idacode_of_color s)
let comment s =
sprintf "ida.comment.add($addr, '%s', '%s')"
(escape (Value.tagname s)) (escape (Value.to_string s))
let foreground s =
sprintf "ida.comment.add($addr, 'foreground', '%s')" (string_of_color s)
let background s =
sprintf "ida.comment.add($addr, 'background', '%s')" (string_of_color s)
end
let emit_attr buf sub_name addr attr =
let open Value.Match in
let substitute = function
| "sub_name" -> sub_name
| "addr" -> asprintf "%a" Word.pp_hex addr
| s -> s in
let case tag f = case tag (fun attr ->
Buffer.add_substitute buf substitute (f attr);
Buffer.add_char buf '\n') in
switch attr @@
case color Py.color @@
case foreground Py.foreground @@
case background Py.background @@
default (fun () ->
Buffer.add_substitute buf substitute (Py.comment attr);
Buffer.add_char buf '\n')
let program_visitor buf attrs =
object
inherit [string * word option] Term.visitor
method! leave_term _ t (name,addr) =
match addr with
| None -> name,addr
| Some addr ->
Term.attrs t |> Dict.to_sequence |> Seq.iter ~f:(fun (_,x) ->
let attr = Value.tagname x in
if List.mem ~equal:String.equal attrs attr
then emit_attr buf name addr x);
name,Some addr
method! enter_term _ t (name,_) =
name,Term.get_attr t address
method! enter_sub sub (_,addr) = Sub.name sub,addr
end
let extract_script data code attrs =
let open Value.Match in
let buf = Buffer.create 4096 in
Buffer.add_string buf Py.prologue;
Memmap.to_sequence data |> Seq.iter ~f:(fun (mem,x) ->
switch x @@
case python (fun line -> Buffer.add_string buf line) @@
default ignore);
(program_visitor buf attrs)#run code ("",None) |> ignore;
Buffer.add_string buf Py.epilogue;
Buffer.contents buf
let main dst attrs project =
let data = Project.memory project in
let code = Project.program project in
let data = extract_script data code attrs in
match dst with
| None -> print_string data
| Some dst -> Out_channel.write_all dst ~data
let () =
let () = Config.manpage [
`S "DESCRIPTION";
`P "Iterates through memory for tagged BIR attributes,
and dumps them into a python script, that can be later
loaded into IDA. The special `color' tag causes the
respective address to be colored.";
`S "SEE ALSO";
`P "$(b,bap-ida)(3), $(b,bap-plugin-ida)(1)"
] in
let dst = Config.(param (some string) "file" ~docv:"NAME"
~doc:"Dump annotations to the specified file $(docv). If
not specified, then the script will dumped into the
standard output") in
let attrs = Config.(param_all string "attr"
~doc: "Emit specified BIR attribute. Can be specified
multiple times.") in
Config.declare_extension ~doc:"generates IDA Python scripts"
~provides:["ida"; "python"; "pass"]
(fun {Config.get=(!)} ->
let main = main !dst !attrs in
Project.register_pass' main )
|
b16c0954c00baebb5a0c74932dee33d6857efc0e288de04da42cd679163f483c | practicalli/clojure-through-code | live_demo.clj | Get Functional with Clojure
;;;;;;;;;;;;;;;;;;;;;;;
What is Clojure
;; A general purpose programming language
;; - a modern LISP
- hosted on the Java Virtual Machine ( JVM ) , Microsoft CLR , JavaScript Engines ( V8 , Node )
;;;;;;;;;;;;;;;;;;;;;;;
;; Why Clojure
;; Functional
;; - all functions return a value & can be used as arguments / parameters
;; - deterministic: given the same input you get the same result
Dynamic
;; - types: making it faster to develop & test ideas
;; - runtime: continuously compiling & running code for fast feedback
;; Immutable
;; - everything is immutable by default
;; - easier to reason and build concurrent systems
;; - easier to scale via paralelism
Extensibility & Interop
;; - Macros allows the community to extend the language
- use other libraries on the hosted runtime ( JVM , CLR , JS )
;; Persistent Data Structures
;; - list, map, vector, set are all immutable
;; - return new copies instead of being changed
;; - efficient memory sharing between data structure copies
;; Managing State with Software Transactional Memory (STM)
;; - atoms / refs wrap data structures to make mutable state
;; - STM controls state changes (like having an in-memory acid database)
;; Learning a new language helps improve how you use your current languages
;;;;;;;;;;;;;;;;;;;;;;;
;; Namespaces
;; Define the scope of your functions and data structures, similar in concept to java packages
Namespaces encourage a modular / component approach to Clojure
(ns clojure-through-code.live-demo)
;; This namespace matches the directory structure of the project
;; project-name
;; - src
;; - clojure_through_code
;; - live_demo.clj
;;;;;;;;;;;;;;;;;;;;;;;
Clojure Syntax
Clojure uses a prefix notation and ( ) [ ] : { } # @ ! special characters
;; no need for lots of ; , and other unneccessary things.
;; bind a name to data
(def my-data [1 2 3 "frog"])
my-data
;; See the types used in the hosted language
(type [1 2 3])
(def conference-name "CodeMotion: Tel Aviv")
(type conference-name)
;; bind a name to a function (behaviour)
(defn do-stuff [data]
(str data))
;;;;;;;;;;;;;;;;;;;;;;;
;; Evaluating Clojure
;; Values evaluate to themselves
1
"String"
[1 2 3 4 "Vector"]
{:key "value"}
;; Names can be bound to data or functions and when you evaluate the name it returns a value
Names built into the Clojure language
The full clojure version , major , minor & point version of Clojure
*clojure-version*
;; Calling simple functions
(+ 1 2 3 4 5)
;; precidence is explicit - no uncertanty
(+ 1 2 (- 4 -2) (* (/ 36 3) 4) 5)
;; calling a function we defined previously
(do-stuff my-data)
The first element of a list is evaluated as a function call .
In Clojure everything is in a List , after all its a dialect of LISP ( which stands for List Processing ) .
Effectively you are writing your Clojure coe as an Abstract Syntax Tree ( AST ) , so your code represents the structure .
;;;;;;;;;;;;;;;;;;;;;;;;;
Using Java Interoperability
java.lang is part of the Clojure runtime environment , so when ever you run a Clojure REPL you can call any Java methods
;; without having to import them or include any dependencies
;; Using java.lang.String methods
(.toUpperCase "fred")
From java.lang . System getProperty ( ) as documented at :
;;
;; Using java.lang.System static methods
(System/getProperty "java.version")
(System/getProperty "java.vm.name")
Make the result prettier using the Clojure str function
(str "Current Java version: " (System/getProperty "java.version"))
;; Functions can be used as arguments to function calls
(slurp "project.clj")
(read-string (slurp "project.clj"))
(nth (read-string (slurp "project.clj")) 2)
;; The above code is classic Lisp, you read it from the inside out, so in this case you
;; start with (slurp ...) and what it returns is used as the argument to read-string...
;; Get the contents of the project.clj file using `slurp`
;; Read the text of that file using read-string
Select just the third string using nth 2 ( using an index starting at 0 )
;; You can format the code differently, but in this case its not much easier to read
(nth
(read-string
(slurp "project.clj"))
2)
Macros
;; the same behaviour as above can be written using the threading macro
;; which can make code easier to read by reading sequentially down the list of functions.
(->
"./project.clj"
slurp
read-string
(nth 2))
;; using the macroexpand function you can see what code is actually created
;; Using the threading macro, the result of every function is passed onto the next function
;; in the list. This can be seen very clearly usng ,,, to denote where the value is passed
;; to the next function
(->
"./project.clj"
slurp ,,,
read-string ,,,
(nth ,,, 2))
;; Remember, commas in clojure are ignored
;; To make this really simple lets create a contrived example of the threading macro.
;; Here we use the str function to join strings together. Each individual string call
joins its own strings together , then passes them as a single string as the first argument to the next function
(->
(str "This" " " "is" " ")
(str "the" " " "treading" " " "macro")
(str " in" " " "action."))
;; Using the ->> threading macro, the result of a function is passed as the last parameter
;; of the next function call. So in another simple series of str function calls,
;; our text comes out backwards.
(->>
(str " This")
(str " is")
(str " backwards"))
;; add all project information to a map
(->> "project.clj"
slurp
read-string
(drop 2)
(cons :version)
(apply hash-map)
(def project))
project
;;;;;;;;;;;;;;;;;;;;;;;
;; Working with strings & side-effects
You could use the Java - like function ` println ` to output strings .
(str "Hello, whats different with me? What value do I return")
However , something different happens when you evaluate this expression . This is refered to as a side - effect because when you call this function it returns nil . The actual text is output to the REPL or console .
In Clojure , you are more likely to use the ` str ` function when working with strings .
(str "Hello, I am returned as a value of this expression")
;; join strings together with the function str
(str "Hello" ", " "HackTheTower UK")
;; using println shows the results in console window, as its a side affect
;; using srt you see the results of the evaluation inline with the code,
; as the result of a definition or an expression.
;; Avoid code that creates side-effects where possible to keep your software less complex.
;; using the fast feedback of the REPL usually works beter than println statements in debuging
;;;;;;;;;;;;;;;;;;;;;;;;
Simple math to show you the basic structure of Clojure
; Math is straightforward
(+ 1 1 2489 459 2.)
(- 2 1)
(* 1 2)
(/ 2 1)
(/ 22 7)
(/ 22 7.0)
(/ 5 20)
(/ 38 4)
(/ (* 22/7 3) 3)
;; Ratios delay the need to drop into decimal numbers. Once you create a decimal number then everything it touches had a greater potential to becoming a decimal.
Prefix motation means we can define a value of 22/7 as a value without it being interprested as an operation or function to evaluate .
Clojure uses Prefix notation , so math operations on many arguments is easy .
(+ 1 2 3 4 5)
(+ 1 2 (* 3 4) (- 5 6 -7))
(+)
(*)
(* 2)
(+ 4)
(+ 1 2 3)
(< 1 2 3)
(< 1 3 8 4)
Clojure functions typically support a variable number of arguments ( Variadic functions ) .
;; Functions can also be defined to respond with different behaviour based on the number of arguments given (multi-arity). Arity means the number of arguments a function can be called with.
(inc 3)
(dec 4)
(min 1 2 3 5 8 13)
(max 1 2 3 5 8 13)
(apply + [1 2 3])
(apply / [1 2 3])
(/ 53)
(map + [1 2 3.0] [4.0 5 6])
(repeat 4 9)
;; Data oriented
Clojure & FP typically have many functions to manipulate data
;;;;;;;;;;;;;;;;;;;;;;;;;;;
Equality & Identity
Clojure values make these things relatively trivial
; Equality is =
(= 1 1)
(= 2 1)
(identical? "foo" "bar")
(identical? "foo" "foo")
(= "foo" "bar")
(= "foo" "foo")
(identical? :foo :bar)
(identical? :foo :foo)
;; Equality is very useful when your data structures are immutable
;; Keywords exist as identifiers and for very fast comparisons
(def my-map {:foo "a"})
my-map
(def my-map [ 1 2 3 4 ])
(= "a" (:foo my-map))
; Use the not function for logic
(not true)
(if nil
(str "Return if true")
(str "Return if false"))
(defn is-small? [number]
(if (< number 100) "yes" "no"))
(is-small? 50)
;;;;;;;;;;;;;;;;;
;; Persistent Data Structures
;; Lists
;; you can use the list function to create a new list
(list 1 2 3 4)
(list -1 -0.234 0 1.3 8/5 3.1415926)
(list "cat" "dog" "rabit" "fish" 12 22/7)
(list :cat :dog :rabit :fish)
you can mix types because Clojure is dynamic and it will work it out later ,
;; you can even have functions as elements, because functions always return a value
(list :cat 1 "fish" 22/7 (str "fish" "n" "chips"))
( 1 2 3 4 )
;; This list causes an error when evaluated
(quote (1 2 3 4))
'(1 2 3 4)
'(-1 -0.234 0 1.3 8/5 3.1415926)
'("cat" "dog" "rabit" "fish")
'(:cat :dog :rabit :fish)
'(:cat 1 "fish" 22/7 (str "fish" "n" "chips"))
one unique thing about lists is that the first element is always evaluated as a function call ,
;; with the remaining elements as arguments.
;; Vectors
(vector 1 2 3 4)
[1 2 3 4]
[1 2.4 3.1435893 11/4 5.0 6 7]
[:cat :dog :rabit :fish]
[:cat 1 "fish" 22/7 (str "fish" "n" "chips")]
[]
;; Maps
;; Key - Value pairs, think of a Hash Map
{:key "value"}
(:live-the-universe-and-everything 42)
(def starwars-characters
{:luke {:fullname "Luke Skywarker" :skill "Targeting Swamp Rats"}
:vader {:fullname "Darth Vader" :skill "Crank phone calls"}
:jarjar {:fullname "JarJar Binks" :skill "Upsetting a generation of fans"}})
;; Now we can refer to the characters using keywords
Using the get function we return all the informatoin about
(get starwars-characters :luke)
By wrapping the get function around our first , we can get a specific
piece of information about
(get (get starwars-characters :luke) :fullname)
;; There is also the get-in function that makes the syntax a little easier to read
(get-in starwars-characters [:luke :fullname])
(get-in starwars-characters [:vader :fullname])
Or you can get really Clojurey by just talking to the map directly
(starwars-characters :luke)
(:fullname (:luke starwars-characters))
(:skill (:luke starwars-characters))
(starwars-characters :vader)
(:skill (:vader starwars-characters))
(:fullname (:vader starwars-characters))
;; And finally we can also use the threading macro to minimise our code further
(-> starwars-characters
:luke)
(-> starwars-characters
:luke
:fullname)
(-> starwars-characters
:luke
:skill)
;; Combination of data structures
{:starwars {
:characters {
:jedi ["Luke Skywalker"
"Obiwan Kenobi"]
:sith ["Darth Vader"
"Darth Sideous"]
:droids ["C3P0"
"R2D2"]}
:ships {
:rebel-alliance ["Millenium Falcon"
"X-wing figher"]
:imperial-empire ["Intergalactic Cruser"
"Destroyer"
"Im just making these up now"]}}}
;; Sets
;;;;;;;;;;;;;;;;;;;;;;;;
;; Types in Clojure
There are types underneath Clojure , however Clojure manages them for your
;; You can take a peek at them if you want...
; Vectors and Lists are java classes too!
(class [1 2 3])
(class '(1 2 3))
(class "Guess what type I am")
;;;;;;;;;;;;;;;;;;;;;;
;; Using Functions
;; Lets define a very simple anonymous function, that returns a string
(fn [] "Hello Clojurian, hope you are enjoying the REPL")
;; Anonnymous function that squares a number
(fn [x] (* x x))
; We can also give a name to a function using def
(def i-have-a-name (fn [] "I am not a number, I am a named function - actually we call the name a symbol and it can be used as a reference to the function."))
(i-have-a-name)
You can shorten this process by using defn
(defn i-have-a-name [] "Oh, I am a new function definition, but have the same name (symbol).")
(i-have-a-name)
; The [] is the list of arguments for the function.
(defn hello [name]
(str "Hello there " name))
= > " Hello "
You can also use the annonymous function shorthand , # ( ) , to create functions , ( not that useful in this simple example ) . The % 1 placeholder takes the first argument to the function . You can use % 1 , % 2 and % 3
(def hello2 #(str "Hello " %1 ", are you awake yet?"))
(hello2 "Mike")
;; A function definition that calls different behaviour based on the number of
;; arguments it is called with
(defn greet
([] (greet "you"))
([name] (print "Hello" name)))
(greet)
When greet is called with no arguments , then the first line of the functions behaviour is called . If you look closely , you see this is not adding duplicate code to our function as
(greet "World")
;; Refactor greet function
(defn greet
([] (greet "you"))
([name] (greet name 21 "London"))
([name age address] (print "Hello" name, "I see you are" age "and live at" address)))
Variadic functions
(defn greet [name & rest]
(str "Hello " name " " rest))
(greet "John" "Paul" "George" "Ringo")
= > Hello ( )
;; unpack the additional arguments from the list
(defn greet [name & rest]
(apply print "Hello" name rest))
;; Using functions as parameters
;; Pattern mantching example
The classic fizzbuzz game were you substitute any number cleanly divisible by 3 with fix and any number cleanly divisible by 5 with buzz .
If the number is cleanly divisible by 3 & 5 then substitute fizzbuzz .
;; Include the library that has the match function
(require '[clojure.core.match :refer [match]])
(defn fizzbuzz
[number]
(match [(mod number 3) (mod number 5)]
[0 0] :fizzbuzz
[0 _] :fizz
[_ 0] :buzz
:else number))
;; This is an example of a simple pattern matching problem.
First we calculate the modulus of the number given as an argument by 3 then the same number by 5 .
;; If the modulus value is 0 then the number is divisible exactly without remainder.
The result of these two function calls are the elements of a vector ( an array - like strucutre )
;;
;; Using the require function we include the match function from the library clojure/core.match
;;
;; (match may seem similar to a case statement from other languages).
We use match to compare the two results returned from the modulus functions .
There are 3 possible patterns to match against , each returns the appropriate value ( fizz , buzz , or fizzbuzz )
;; If there is no match, then the original number is returned.
;; The underscore character, _, means that any number will match in that position.
;; If you would like to try this out in the REPL, dont forget to include this namespace if you are not currently in it
;; (require '[clojure-through-code.live-demo :refer :all])
Now we can call fizbuzz for a specfic number
(fizzbuzz 1)
(fizzbuzz 3)
(fizzbuzz 4)
(fizzbuzz 15)
;; If we want to convert a sequence of numbers, then we can call fizzbuzz over a collection (eg, a vector) of numbers
;; using the map function
(map fizzbuzz [1 2 3 4 5])
;; We can make a function called play-fizzbuzz to make it easy to use
;; The function takes the highest number in the range and generates all the numbers from 0 to that number.
;; Finally, we convert the results into strings
(defn play-fizbuzz [max-number]
(->> (range max-number)
(map fizzbuzz)
(map str)))
;; Now, lets call our play-fizzbuzz function with the highest number in the range of numbers we want to play fizzbuzz on.
(play-fizbuzz 30)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Java Interoperability
(def hello-message
(str "Hello " conference-name))
;; Create a simple Swing dialog box
(javax.swing.JOptionPane/showMessageDialog nil hello-message)
;;;;;;;;;;;;;
;; Working with mutable state
;; Using an atom
;; We want to manage players for an online card-game
;; Use a vector wraped by an atom for safe mutable state
(def players (atom []))
;; Or we may want to limit the number of players
(def players (atom [] :validator #(<= (count %) 4)))
the second definition of players point the var name to something new
;; we havent changed what players was, it just points to something diferent
;; Add players
(swap! players conj "Player One")
;; View players
(deref players)
@players
(swap! players conj "Player Two")
(reset! players ["Player One"])
(reset! players [])
;; Add players by name
(defn joining-game [name]
(swap! players conj name))
(joining-game "Rachel")
(joining-game "Harriet")
(joining-game "Idan")
(joining-game "Joe")
( joining - game " Terry " ) ; ; ca nt add a third name due to the : validator condition on the atom
( joining - game " " " " ) ; ; too many parameters
@players
(def game-account (ref 1000))
(def toms-account (ref 500))
(def dick-account (ref 500))
(def harry-account (ref 500))
(def betty-account (ref 500))
@betty-account
(defn credit-table [player-account]
(dosync
(alter player-account - 100)
(alter game-account + 100)))
(defn add-to-table [name]
(swap! players conj name))
(defn join-game [name account]
( if ( < account 100 )
;; (println "You're broke")
(credit-table account)
(add-to-table name))
(join-game "Betty" betty-account)
;; Using a ref
(def all-the-cats (ref 3))
(defn updated-cat-count [fn-key reference old-value new-value]
;; Takes a function key, reference, old value and new value
(println (str "Number of cats was " old-value))
(println (str "Number of cats is now " new-value)))
;; Watch for changes in the all-the-cats ref
(add-watch all-the-cats :cat-count-watcher updated-cat-count)
;; evaluate the following code to increment the cats
;; view the results in the repl output (to see the println output)
(dosync (alter all-the-cats inc))
;;;;;;;;;;;;;
;; Resources
;; clojure.org
;; clojuredocs.org
4clojure.org
;; braveclojure.com
;; jr0cket.co.uk
;; different map functions
both functions will take a sequence of numbers for a point on a map , eg [ 24 -15 ]
;; map will return a result as a list
;; mapv will return a result as a vector
(defn degrees->radians [point]
(map #(Math/toRadians %) point))
(defn degrees->radians [point]
(mapv #(Math/toRadians %) point))
(degrees->radians [1 10])
| null | https://raw.githubusercontent.com/practicalli/clojure-through-code/82834cdab6b5315aea630386c851200f98d5e48f/src/clojure_through_code/live_demo.clj | clojure |
A general purpose programming language
- a modern LISP
Why Clojure
Functional
- all functions return a value & can be used as arguments / parameters
- deterministic: given the same input you get the same result
- types: making it faster to develop & test ideas
- runtime: continuously compiling & running code for fast feedback
Immutable
- everything is immutable by default
- easier to reason and build concurrent systems
- easier to scale via paralelism
- Macros allows the community to extend the language
Persistent Data Structures
- list, map, vector, set are all immutable
- return new copies instead of being changed
- efficient memory sharing between data structure copies
Managing State with Software Transactional Memory (STM)
- atoms / refs wrap data structures to make mutable state
- STM controls state changes (like having an in-memory acid database)
Learning a new language helps improve how you use your current languages
Namespaces
Define the scope of your functions and data structures, similar in concept to java packages
This namespace matches the directory structure of the project
project-name
- src
- clojure_through_code
- live_demo.clj
no need for lots of ; , and other unneccessary things.
bind a name to data
See the types used in the hosted language
bind a name to a function (behaviour)
Evaluating Clojure
Values evaluate to themselves
Names can be bound to data or functions and when you evaluate the name it returns a value
Calling simple functions
precidence is explicit - no uncertanty
calling a function we defined previously
without having to import them or include any dependencies
Using java.lang.String methods
Using java.lang.System static methods
Functions can be used as arguments to function calls
The above code is classic Lisp, you read it from the inside out, so in this case you
start with (slurp ...) and what it returns is used as the argument to read-string...
Get the contents of the project.clj file using `slurp`
Read the text of that file using read-string
You can format the code differently, but in this case its not much easier to read
the same behaviour as above can be written using the threading macro
which can make code easier to read by reading sequentially down the list of functions.
using the macroexpand function you can see what code is actually created
Using the threading macro, the result of every function is passed onto the next function
in the list. This can be seen very clearly usng ,,, to denote where the value is passed
to the next function
Remember, commas in clojure are ignored
To make this really simple lets create a contrived example of the threading macro.
Here we use the str function to join strings together. Each individual string call
Using the ->> threading macro, the result of a function is passed as the last parameter
of the next function call. So in another simple series of str function calls,
our text comes out backwards.
add all project information to a map
Working with strings & side-effects
join strings together with the function str
using println shows the results in console window, as its a side affect
using srt you see the results of the evaluation inline with the code,
as the result of a definition or an expression.
Avoid code that creates side-effects where possible to keep your software less complex.
using the fast feedback of the REPL usually works beter than println statements in debuging
Math is straightforward
Ratios delay the need to drop into decimal numbers. Once you create a decimal number then everything it touches had a greater potential to becoming a decimal.
Functions can also be defined to respond with different behaviour based on the number of arguments given (multi-arity). Arity means the number of arguments a function can be called with.
Data oriented
Equality is =
Equality is very useful when your data structures are immutable
Keywords exist as identifiers and for very fast comparisons
Use the not function for logic
Persistent Data Structures
Lists
you can use the list function to create a new list
you can even have functions as elements, because functions always return a value
This list causes an error when evaluated
with the remaining elements as arguments.
Vectors
Maps
Key - Value pairs, think of a Hash Map
Now we can refer to the characters using keywords
There is also the get-in function that makes the syntax a little easier to read
And finally we can also use the threading macro to minimise our code further
Combination of data structures
Sets
Types in Clojure
You can take a peek at them if you want...
Vectors and Lists are java classes too!
Using Functions
Lets define a very simple anonymous function, that returns a string
Anonnymous function that squares a number
We can also give a name to a function using def
The [] is the list of arguments for the function.
A function definition that calls different behaviour based on the number of
arguments it is called with
Refactor greet function
unpack the additional arguments from the list
Using functions as parameters
Pattern mantching example
Include the library that has the match function
This is an example of a simple pattern matching problem.
If the modulus value is 0 then the number is divisible exactly without remainder.
Using the require function we include the match function from the library clojure/core.match
(match may seem similar to a case statement from other languages).
If there is no match, then the original number is returned.
The underscore character, _, means that any number will match in that position.
If you would like to try this out in the REPL, dont forget to include this namespace if you are not currently in it
(require '[clojure-through-code.live-demo :refer :all])
If we want to convert a sequence of numbers, then we can call fizzbuzz over a collection (eg, a vector) of numbers
using the map function
We can make a function called play-fizzbuzz to make it easy to use
The function takes the highest number in the range and generates all the numbers from 0 to that number.
Finally, we convert the results into strings
Now, lets call our play-fizzbuzz function with the highest number in the range of numbers we want to play fizzbuzz on.
Create a simple Swing dialog box
Working with mutable state
Using an atom
We want to manage players for an online card-game
Use a vector wraped by an atom for safe mutable state
Or we may want to limit the number of players
we havent changed what players was, it just points to something diferent
Add players
View players
Add players by name
; ca nt add a third name due to the : validator condition on the atom
; too many parameters
(println "You're broke")
Using a ref
Takes a function key, reference, old value and new value
Watch for changes in the all-the-cats ref
evaluate the following code to increment the cats
view the results in the repl output (to see the println output)
Resources
clojure.org
clojuredocs.org
braveclojure.com
jr0cket.co.uk
different map functions
map will return a result as a list
mapv will return a result as a vector | Get Functional with Clojure
What is Clojure
- hosted on the Java Virtual Machine ( JVM ) , Microsoft CLR , JavaScript Engines ( V8 , Node )
Dynamic
Extensibility & Interop
- use other libraries on the hosted runtime ( JVM , CLR , JS )
Namespaces encourage a modular / component approach to Clojure
(ns clojure-through-code.live-demo)
Clojure Syntax
Clojure uses a prefix notation and ( ) [ ] : { } # @ ! special characters
(def my-data [1 2 3 "frog"])
my-data
(type [1 2 3])
(def conference-name "CodeMotion: Tel Aviv")
(type conference-name)
(defn do-stuff [data]
(str data))
1
"String"
[1 2 3 4 "Vector"]
{:key "value"}
Names built into the Clojure language
The full clojure version , major , minor & point version of Clojure
*clojure-version*
(+ 1 2 3 4 5)
(+ 1 2 (- 4 -2) (* (/ 36 3) 4) 5)
(do-stuff my-data)
The first element of a list is evaluated as a function call .
In Clojure everything is in a List , after all its a dialect of LISP ( which stands for List Processing ) .
Effectively you are writing your Clojure coe as an Abstract Syntax Tree ( AST ) , so your code represents the structure .
Using Java Interoperability
java.lang is part of the Clojure runtime environment , so when ever you run a Clojure REPL you can call any Java methods
(.toUpperCase "fred")
From java.lang . System getProperty ( ) as documented at :
(System/getProperty "java.version")
(System/getProperty "java.vm.name")
Make the result prettier using the Clojure str function
(str "Current Java version: " (System/getProperty "java.version"))
(slurp "project.clj")
(read-string (slurp "project.clj"))
(nth (read-string (slurp "project.clj")) 2)
Select just the third string using nth 2 ( using an index starting at 0 )
(nth
(read-string
(slurp "project.clj"))
2)
Macros
(->
"./project.clj"
slurp
read-string
(nth 2))
(->
"./project.clj"
slurp ,,,
read-string ,,,
(nth ,,, 2))
joins its own strings together , then passes them as a single string as the first argument to the next function
(->
(str "This" " " "is" " ")
(str "the" " " "treading" " " "macro")
(str " in" " " "action."))
(->>
(str " This")
(str " is")
(str " backwards"))
(->> "project.clj"
slurp
read-string
(drop 2)
(cons :version)
(apply hash-map)
(def project))
project
You could use the Java - like function ` println ` to output strings .
(str "Hello, whats different with me? What value do I return")
However , something different happens when you evaluate this expression . This is refered to as a side - effect because when you call this function it returns nil . The actual text is output to the REPL or console .
In Clojure , you are more likely to use the ` str ` function when working with strings .
(str "Hello, I am returned as a value of this expression")
(str "Hello" ", " "HackTheTower UK")
Simple math to show you the basic structure of Clojure
(+ 1 1 2489 459 2.)
(- 2 1)
(* 1 2)
(/ 2 1)
(/ 22 7)
(/ 22 7.0)
(/ 5 20)
(/ 38 4)
(/ (* 22/7 3) 3)
Prefix motation means we can define a value of 22/7 as a value without it being interprested as an operation or function to evaluate .
Clojure uses Prefix notation , so math operations on many arguments is easy .
(+ 1 2 3 4 5)
(+ 1 2 (* 3 4) (- 5 6 -7))
(+)
(*)
(* 2)
(+ 4)
(+ 1 2 3)
(< 1 2 3)
(< 1 3 8 4)
Clojure functions typically support a variable number of arguments ( Variadic functions ) .
(inc 3)
(dec 4)
(min 1 2 3 5 8 13)
(max 1 2 3 5 8 13)
(apply + [1 2 3])
(apply / [1 2 3])
(/ 53)
(map + [1 2 3.0] [4.0 5 6])
(repeat 4 9)
Clojure & FP typically have many functions to manipulate data
Equality & Identity
Clojure values make these things relatively trivial
(= 1 1)
(= 2 1)
(identical? "foo" "bar")
(identical? "foo" "foo")
(= "foo" "bar")
(= "foo" "foo")
(identical? :foo :bar)
(identical? :foo :foo)
(def my-map {:foo "a"})
my-map
(def my-map [ 1 2 3 4 ])
(= "a" (:foo my-map))
(not true)
(if nil
(str "Return if true")
(str "Return if false"))
(defn is-small? [number]
(if (< number 100) "yes" "no"))
(is-small? 50)
(list 1 2 3 4)
(list -1 -0.234 0 1.3 8/5 3.1415926)
(list "cat" "dog" "rabit" "fish" 12 22/7)
(list :cat :dog :rabit :fish)
you can mix types because Clojure is dynamic and it will work it out later ,
(list :cat 1 "fish" 22/7 (str "fish" "n" "chips"))
( 1 2 3 4 )
(quote (1 2 3 4))
'(1 2 3 4)
'(-1 -0.234 0 1.3 8/5 3.1415926)
'("cat" "dog" "rabit" "fish")
'(:cat :dog :rabit :fish)
'(:cat 1 "fish" 22/7 (str "fish" "n" "chips"))
one unique thing about lists is that the first element is always evaluated as a function call ,
(vector 1 2 3 4)
[1 2 3 4]
[1 2.4 3.1435893 11/4 5.0 6 7]
[:cat :dog :rabit :fish]
[:cat 1 "fish" 22/7 (str "fish" "n" "chips")]
[]
{:key "value"}
(:live-the-universe-and-everything 42)
(def starwars-characters
{:luke {:fullname "Luke Skywarker" :skill "Targeting Swamp Rats"}
:vader {:fullname "Darth Vader" :skill "Crank phone calls"}
:jarjar {:fullname "JarJar Binks" :skill "Upsetting a generation of fans"}})
Using the get function we return all the informatoin about
(get starwars-characters :luke)
By wrapping the get function around our first , we can get a specific
piece of information about
(get (get starwars-characters :luke) :fullname)
(get-in starwars-characters [:luke :fullname])
(get-in starwars-characters [:vader :fullname])
Or you can get really Clojurey by just talking to the map directly
(starwars-characters :luke)
(:fullname (:luke starwars-characters))
(:skill (:luke starwars-characters))
(starwars-characters :vader)
(:skill (:vader starwars-characters))
(:fullname (:vader starwars-characters))
(-> starwars-characters
:luke)
(-> starwars-characters
:luke
:fullname)
(-> starwars-characters
:luke
:skill)
{:starwars {
:characters {
:jedi ["Luke Skywalker"
"Obiwan Kenobi"]
:sith ["Darth Vader"
"Darth Sideous"]
:droids ["C3P0"
"R2D2"]}
:ships {
:rebel-alliance ["Millenium Falcon"
"X-wing figher"]
:imperial-empire ["Intergalactic Cruser"
"Destroyer"
"Im just making these up now"]}}}
There are types underneath Clojure , however Clojure manages them for your
(class [1 2 3])
(class '(1 2 3))
(class "Guess what type I am")
(fn [] "Hello Clojurian, hope you are enjoying the REPL")
(fn [x] (* x x))
(def i-have-a-name (fn [] "I am not a number, I am a named function - actually we call the name a symbol and it can be used as a reference to the function."))
(i-have-a-name)
You can shorten this process by using defn
(defn i-have-a-name [] "Oh, I am a new function definition, but have the same name (symbol).")
(i-have-a-name)
(defn hello [name]
(str "Hello there " name))
= > " Hello "
You can also use the annonymous function shorthand , # ( ) , to create functions , ( not that useful in this simple example ) . The % 1 placeholder takes the first argument to the function . You can use % 1 , % 2 and % 3
(def hello2 #(str "Hello " %1 ", are you awake yet?"))
(hello2 "Mike")
(defn greet
([] (greet "you"))
([name] (print "Hello" name)))
(greet)
When greet is called with no arguments , then the first line of the functions behaviour is called . If you look closely , you see this is not adding duplicate code to our function as
(greet "World")
(defn greet
([] (greet "you"))
([name] (greet name 21 "London"))
([name age address] (print "Hello" name, "I see you are" age "and live at" address)))
Variadic functions
(defn greet [name & rest]
(str "Hello " name " " rest))
(greet "John" "Paul" "George" "Ringo")
= > Hello ( )
(defn greet [name & rest]
(apply print "Hello" name rest))
The classic fizzbuzz game were you substitute any number cleanly divisible by 3 with fix and any number cleanly divisible by 5 with buzz .
If the number is cleanly divisible by 3 & 5 then substitute fizzbuzz .
(require '[clojure.core.match :refer [match]])
(defn fizzbuzz
[number]
(match [(mod number 3) (mod number 5)]
[0 0] :fizzbuzz
[0 _] :fizz
[_ 0] :buzz
:else number))
First we calculate the modulus of the number given as an argument by 3 then the same number by 5 .
The result of these two function calls are the elements of a vector ( an array - like strucutre )
We use match to compare the two results returned from the modulus functions .
There are 3 possible patterns to match against , each returns the appropriate value ( fizz , buzz , or fizzbuzz )
Now we can call fizbuzz for a specfic number
(fizzbuzz 1)
(fizzbuzz 3)
(fizzbuzz 4)
(fizzbuzz 15)
(map fizzbuzz [1 2 3 4 5])
(defn play-fizbuzz [max-number]
(->> (range max-number)
(map fizzbuzz)
(map str)))
(play-fizbuzz 30)
Java Interoperability
(def hello-message
(str "Hello " conference-name))
(javax.swing.JOptionPane/showMessageDialog nil hello-message)
(def players (atom []))
(def players (atom [] :validator #(<= (count %) 4)))
the second definition of players point the var name to something new
(swap! players conj "Player One")
(deref players)
@players
(swap! players conj "Player Two")
(reset! players ["Player One"])
(reset! players [])
(defn joining-game [name]
(swap! players conj name))
(joining-game "Rachel")
(joining-game "Harriet")
(joining-game "Idan")
(joining-game "Joe")
@players
(def game-account (ref 1000))
(def toms-account (ref 500))
(def dick-account (ref 500))
(def harry-account (ref 500))
(def betty-account (ref 500))
@betty-account
(defn credit-table [player-account]
(dosync
(alter player-account - 100)
(alter game-account + 100)))
(defn add-to-table [name]
(swap! players conj name))
(defn join-game [name account]
( if ( < account 100 )
(credit-table account)
(add-to-table name))
(join-game "Betty" betty-account)
(def all-the-cats (ref 3))
(defn updated-cat-count [fn-key reference old-value new-value]
(println (str "Number of cats was " old-value))
(println (str "Number of cats is now " new-value)))
(add-watch all-the-cats :cat-count-watcher updated-cat-count)
(dosync (alter all-the-cats inc))
4clojure.org
both functions will take a sequence of numbers for a point on a map , eg [ 24 -15 ]
(defn degrees->radians [point]
(map #(Math/toRadians %) point))
(defn degrees->radians [point]
(mapv #(Math/toRadians %) point))
(degrees->radians [1 10])
|
a8e39f30fe17bba4779d7498cdb28b5e7f3dd94525b0511202a7abd6f723531d | kappelmann/eidi2_repetitorium_tum | ha14.ml | open Ha14_angabe
let master bind_addr port tickets = failwith "Todo" | null | https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/additional_exercises/2016_17/Blatt%2014%20L%C3%B6sungen/ocaml/ha14.ml | ocaml | open Ha14_angabe
let master bind_addr port tickets = failwith "Todo" | |
4f9ddb9436f2e577564072cd3ae49db43280b7b34630280c36392772db3021bd | opencog/opencog | nn.scm | ;
; "He stood at the goal line."
(define nn
(BindLink
(VariableList
(var-decl "$a-parse" "ParseNode")
(var-decl "$N1" "WordInstanceNode")
(var-decl "$N2" "WordInstanceNode")
(var-decl "$N1-lemma" "WordNode")
(var-decl "$N2-lemma" "WordNode")
)
(AndLink
(word-in-parse "$N1" "$a-parse")
(word-in-parse "$N2" "$a-parse")
(word-lemma "$N1" "$N1-lemma")
(word-lemma "$N2" "$N2-lemma")
(dependency "_nn" "$N1" "$N2")
)
(ExecutionOutputLink
(GroundedSchemaNode "scm: nn-rule")
(ListLink
(VariableNode "$N1-lemma")
(VariableNode "$N1")
(VariableNode "$N2-lemma")
(VariableNode "$N2")
)
)
)
)
| null | https://raw.githubusercontent.com/opencog/opencog/53f2c2c8e26160e3321b399250afb0e3dbc64d4c/opencog/nlp/relex2logic/rules/nn.scm | scheme |
"He stood at the goal line." | (define nn
(BindLink
(VariableList
(var-decl "$a-parse" "ParseNode")
(var-decl "$N1" "WordInstanceNode")
(var-decl "$N2" "WordInstanceNode")
(var-decl "$N1-lemma" "WordNode")
(var-decl "$N2-lemma" "WordNode")
)
(AndLink
(word-in-parse "$N1" "$a-parse")
(word-in-parse "$N2" "$a-parse")
(word-lemma "$N1" "$N1-lemma")
(word-lemma "$N2" "$N2-lemma")
(dependency "_nn" "$N1" "$N2")
)
(ExecutionOutputLink
(GroundedSchemaNode "scm: nn-rule")
(ListLink
(VariableNode "$N1-lemma")
(VariableNode "$N1")
(VariableNode "$N2-lemma")
(VariableNode "$N2")
)
)
)
)
|
a3a8ca2a1e9381ba26d774d72fbdf2b62fc191cce7ebd28170763ed7482ca175 | cyverse-archive/DiscoveryEnvironmentBackend | reference_genome.clj | (ns metadactyl.routes.domain.reference-genome
(:use [common-swagger-api.schema :only [->optional-param describe]]
[metadactyl.routes.params]
[schema.core :only [defschema optional-key]])
(:import [java.util Date UUID]))
(def ReferenceGenomeIdParam (describe UUID "A UUID that is used to identify the Reference Genome"))
(defschema ReferenceGenomeListingParams
(merge SecuredQueryParams
{(optional-key :deleted)
(describe Boolean
"Whether or not to include Reference Genomes that have been marked as deleted
(false by default).")
(optional-key :created_by)
(describe String "Filters the Reference Genome listing by the user that added them.")}))
(defschema ReferenceGenome
{:id
ReferenceGenomeIdParam
:name
(describe String "The Reference Genome's name")
:path
(describe String "The path of the directory containing the Reference Genome")
(optional-key :deleted)
(describe Boolean "Whether the Reference Genome is marked as deleted")
:created_by
(describe String "The username of the user that added the Reference Genome")
(optional-key :created_on)
(describe Date "The date the Reference Genome was added")
:last_modified_by
(describe String "The username of the user that updated the Reference Genome")
(optional-key :last_modified_on)
(describe Date "The date of last modification to the Reference Genome")})
(defschema ReferenceGenomesList
{:genomes (describe [ReferenceGenome] "Listing of Reference Genomes.")})
(defschema ReferenceGenomeSetRequest
(-> ReferenceGenome
(->optional-param :id)))
(defschema ReferenceGenomesSetRequest
{:genomes (describe [ReferenceGenomeSetRequest] "Listing of Reference Genomes.")})
(defschema ReferenceGenomeRequest
(-> ReferenceGenomeSetRequest
(->optional-param :created_by)
(->optional-param :last_modified_by)))
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/metadactyl-clj/src/metadactyl/routes/domain/reference_genome.clj | clojure | (ns metadactyl.routes.domain.reference-genome
(:use [common-swagger-api.schema :only [->optional-param describe]]
[metadactyl.routes.params]
[schema.core :only [defschema optional-key]])
(:import [java.util Date UUID]))
(def ReferenceGenomeIdParam (describe UUID "A UUID that is used to identify the Reference Genome"))
(defschema ReferenceGenomeListingParams
(merge SecuredQueryParams
{(optional-key :deleted)
(describe Boolean
"Whether or not to include Reference Genomes that have been marked as deleted
(false by default).")
(optional-key :created_by)
(describe String "Filters the Reference Genome listing by the user that added them.")}))
(defschema ReferenceGenome
{:id
ReferenceGenomeIdParam
:name
(describe String "The Reference Genome's name")
:path
(describe String "The path of the directory containing the Reference Genome")
(optional-key :deleted)
(describe Boolean "Whether the Reference Genome is marked as deleted")
:created_by
(describe String "The username of the user that added the Reference Genome")
(optional-key :created_on)
(describe Date "The date the Reference Genome was added")
:last_modified_by
(describe String "The username of the user that updated the Reference Genome")
(optional-key :last_modified_on)
(describe Date "The date of last modification to the Reference Genome")})
(defschema ReferenceGenomesList
{:genomes (describe [ReferenceGenome] "Listing of Reference Genomes.")})
(defschema ReferenceGenomeSetRequest
(-> ReferenceGenome
(->optional-param :id)))
(defschema ReferenceGenomesSetRequest
{:genomes (describe [ReferenceGenomeSetRequest] "Listing of Reference Genomes.")})
(defschema ReferenceGenomeRequest
(-> ReferenceGenomeSetRequest
(->optional-param :created_by)
(->optional-param :last_modified_by)))
| |
abf627320d8fc7f5cda2b8b4c93f8ee180c87107a5c5681c0517567ea7ae725e | samoht/camloo | lam.scm | ;; Le module
(module
__caml_lam
(library camloo-runtime)
(import
__caml_misc
__caml_const
__caml_lambda
__caml_prim
__caml_globals)
(export
(string_for_C_read_34@lam x1)
current_out_stream_102@lam
(ps_179@lam x1)
(pn_129@lam x1)
(pc_182@lam x1)
(pi_71@lam x1)
(pf_249@lam x1)
(prim_test_234@lam x1)
(dump_lam_160@lam x1)
(dump_struct_constant_199@lam x1)
(dump_lams_227@lam x1)
(pdummy_size_74@lam x1)
(dump_primitive_237@lam x1)
(dump_atomic_constant_103@lam x1)
(dump_constr_95@lam x1)
(dump_constr_tag_75@lam x1)
(dump_qualified_ident_170@lam x1)
(dump_bool_test_110@lam x1)
(dump_float_primitive_199@lam x1)
(dump_lambda_193@lam x1)
(3-232-dump_lambda_193@lam x1 x2 x3)))
L'initialisation du module
(init_camloo!)
;; Les variables globales
;; Les expressions globales
(define (string_for_C_read_34@lam x1)
(let ((x2 0))
(begin
(let ((stop1001 (-fx (string-length x1) 1)))
(let for1000 ((i3 0))
(if (<=fx i3 stop1001)
(begin
(set! x2
(+fx x2
(let ((x5 ((nth_char_166@string x1) i3)))
(labels
((staticfail1002 () (if (is_printable x5) 1 4)))
(case x5
((#\tab #\newline #\\ #\") 2)
(else (staticfail1002)))))))
(for1000 (+fx i3 1)))
(unspecified))))
(if (eq? x2 (string-length x1))
x1
(let ((x3 (create_string_138@string x2)))
(begin
(set! x2 0)
(begin
(let ((stop1004 (-fx (string-length x1) 1)))
(let for1003 ((i4 0))
(if (<=fx i4 stop1004)
(begin
(begin
(let ((x6 ((nth_char_166@string x1) i4)))
(labels
((staticfail1005
()
(if (is_printable x6)
(((set_nth_char_28@string x3) x2) x6)
(let ((x7 (int_of_char x6)))
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(begin
(((set_nth_char_28@string x3) x2)
(char_of_int_212@char
(+fx 48 (/fx x7 64))))
(begin
(set! x2 (+fx x2 1))
(begin
(((set_nth_char_28@string x3) x2)
(char_of_int_212@char
(+fx 48 (modulo (/fx x7 8) 8))))
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2)
(char_of_int_212@char
(+fx 48
(modulo
x7
8))))))))))))))
(case x6
((#\")
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\"))))
((#\\)
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\\))))
((#\newline)
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\n))))
((#\tab)
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\t))))
(else (staticfail1005)))))
(set! x2 (+fx x2 1)))
(for1003 (+fx i4 1)))
(unspecified))))
x3)))))))
(define current_out_stream_102@lam
(make-cell stdout_127@io))
(define (ps_179@lam x1)
((output_string_156@io
(cell-ref current_out_stream_102@lam))
x1))
(define (pn_129@lam x1)
(output_char
(cell-ref current_out_stream_102@lam)
#\newline))
(define (pc_182@lam x1)
(output_char
(cell-ref current_out_stream_102@lam)
x1))
(define (pi_71@lam x1)
(ps_179@lam (string_of_int_188@int x1)))
(define (pf_249@lam x1)
(begin
(((fprintf_48@printf
(cell-ref current_out_stream_102@lam))
"%f")
x1)
#f))
(define (prim_test_234@lam x1)
(let ((g1012 x1))
(cond ((eq? g1012 #f) (ps_179@lam "PTeq"))
((eq? g1012 #t) (ps_179@lam "PTnoteq"))
((eq? g1012 #u0000) (ps_179@lam "PTlt"))
((eq? g1012 #a000) (ps_179@lam "PTle"))
((eq? g1012 #<0006>) (ps_179@lam "PTgt"))
((eq? g1012 #<0007>) (ps_179@lam "PTge"))
(else (ps_179@lam "PTnoteqimm")))))
(begin
(define (dump_lam_160@lam x1)
(let ((g1013 x1))
(cond ((eq? g1013 #<000a>)
(ps_179@lam "(Lstaticfail)"))
(else
(case (caml-regular-constr-tag g1013)
((1)
(begin
(ps_179@lam "(Lvar ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((2)
(begin
(ps_179@lam "(Lconst ")
(begin
(dump_struct_constant_199@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((3)
(begin
(ps_179@lam "(Lapply ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(dump_lams_227@lam (caml-constr-get-field x1 1))
(ps_179@lam ")")))))
((4)
(begin
(ps_179@lam "(Lfunction ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((5)
(labels
((staticfail1006
()
(begin
(ps_179@lam "(Llet ")
(begin
(dump_lams_227@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")")))))))
(if (null? (caml-constr-get-field x1 0))
(dump_lam_160@lam (caml-constr-get-field x1 1))
(staticfail1006))))
((6)
(begin
(ps_179@lam "(Lletrec (")
(begin
((do_list_18@list
(lambda (x2)
(begin
(ps_179@lam "(")
(begin
(dump_lam_160@lam (caml-constr-get-field x2 0))
(begin
(ps_179@lam " (")
(begin
(pdummy_size_74@lam
(caml-constr-get-field x2 1))
(ps_179@lam "))")))))))
(caml-constr-get-field x1 0))
(begin
(ps_179@lam ") ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((7)
(begin
(ps_179@lam "(Lprim ")
(begin
(dump_primitive_237@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lams_227@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((8)
(begin
(ps_179@lam "(Lcond ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " (")
(begin
((do_list_18@list
(lambda (x2)
(begin
(ps_179@lam "(")
(begin
(dump_atomic_constant_103@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam
(caml-constr-get-field x2 1))
(ps_179@lam ") ")))))))
(caml-constr-get-field x1 1))
(ps_179@lam "))"))))))
((9)
(begin
(ps_179@lam "(Lswitch ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam "(")
(begin
((do_list_18@list
(lambda (x2)
(begin
(ps_179@lam "(")
(begin
(dump_constr_95@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam
(caml-constr-get-field x2 1))
(ps_179@lam ") ")))))))
(caml-constr-get-field x1 2))
(ps_179@lam "))"))))))))
((11)
(begin
(ps_179@lam "(Lstatichandle ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((12)
(begin
(ps_179@lam "(Lhandle ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((13)
(begin
(ps_179@lam "(Lifthenelse ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 2))
(ps_179@lam ")"))))))))
((14)
(begin
(ps_179@lam "(Lsequence ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((15)
(begin
(ps_179@lam "(Lwhile ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((16)
(begin
(ps_179@lam "(Lfor ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam " ")
(begin
(if (caml-constr-get-field x1 2)
(ps_179@lam "#t ")
(ps_179@lam "#f "))
(begin
(dump_lam_160@lam (caml-constr-get-field x1 3))
(ps_179@lam ")")))))))))
((17)
(begin
(ps_179@lam "(Lsequand ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((18)
(begin
(ps_179@lam "(Lsequor ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
(else
(begin
(ps_179@lam "(Lshared ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam
(cell-ref (caml-constr-get-field x1 1)))
(ps_179@lam ")")))))))))))
(begin
(define (dump_lams_227@lam x1)
(begin
(ps_179@lam "(")
(begin
((do_list_18@list
(lambda (x2)
(begin (dump_lam_160@lam x2) (ps_179@lam " "))))
x1)
(ps_179@lam ")"))))
(begin
(define (dump_atomic_constant_103@lam x1)
(case (caml-regular-constr-tag x1)
((1) (pi_71@lam (caml-constr-get-field x1 0)))
((2) (pf_249@lam (caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "#")
(begin
(pc_182@lam #\")
(begin
(ps_179@lam
(string_for_C_read_34@lam
(caml-constr-get-field x1 0)))
(pc_182@lam #\")))))
(else
(labels
((staticfail1007
()
(begin
(ps_179@lam "#a")
(let ((x2 (int_of_char (caml-constr-get-field x1 0))))
(let ((x3 (string_of_int_188@int x2)))
(if (<fx x2 10)
(begin (ps_179@lam "00") (ps_179@lam x3))
(if (<fx x2 100)
(begin (ps_179@lam "0") (ps_179@lam x3))
(ps_179@lam x3))))))))
(let ((g1014 (caml-constr-get-field x1 0)))
(cond ((char=? g1014 #\newline)
(begin (ps_179@lam "#\\") (ps_179@lam "Newline")))
((char=? g1014 #\tab)
(begin (ps_179@lam "#\\") (ps_179@lam "tab")))
(else (staticfail1007))))))))
(begin
(define (dump_struct_constant_199@lam x1)
(case (caml-regular-constr-tag x1)
((1)
(begin
(ps_179@lam "(SCatom ")
(begin
(dump_atomic_constant_103@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
(else
(begin
(ps_179@lam "(SCblock ")
(begin
(dump_constr_tag_75@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " (")
(begin
((do_list_18@list
(lambda (x2)
(begin
(dump_struct_constant_199@lam x2)
(ps_179@lam " "))))
(caml-constr-get-field x1 1))
(ps_179@lam "))"))))))))
(begin
(define (dump_qualified_ident_170@lam x1)
(begin
(ps_179@lam "(qualifiedident ")
(begin
(pc_182@lam #\")
(begin
(ps_179@lam (caml-constr-get-field x1 0))
(begin
(pc_182@lam #\")
(begin
(ps_179@lam " ")
(begin
(pc_182@lam #\")
(begin
(ps_179@lam (caml-constr-get-field x1 1))
(begin (pc_182@lam #\") (ps_179@lam ")"))))))))))
(begin
(define (dump_constr_tag_75@lam x1)
(case (caml-regular-constr-tag x1)
((1)
(begin
(ps_179@lam "(ConstrExtensible ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
(else
(begin
(ps_179@lam "(ConstrRegular ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 2))
(ps_179@lam ")"))))))))))
(begin
(define (dump_constr_95@lam x1)
(let ((x2 (caml-constr-get-field
(caml-constr-get-field x1 1)
3)))
(case (caml-regular-constr-tag x2)
((1)
(begin
(ps_179@lam "(ConstrExtensible ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x2 1))
(ps_179@lam ")"))))))
(else
(let ((x3 (caml-constr-get-field
(caml-constr-get-field x1 1)
4)))
(labels
((staticfail1008
()
(begin
(ps_179@lam "(ConstrRegular ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x2 1))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x2 2))
(ps_179@lam ")")))))))))
(let ((g1015 x3))
(cond ((eq? g1015 #f)
(begin
(ps_179@lam "(ConstrConstant ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam
(caml-constr-get-field x2 1))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam
(caml-constr-get-field x2 2))
(ps_179@lam ")"))))))))
(else (staticfail1008))))))))))
(begin
(define (pdummy_size_74@lam x1)
(let ((g1016 x1))
(cond ((eq? g1016 #unspecified)
(ps_179@lam "function "))
((eq? g1016 #<0006>) (ps_179@lam "stream"))
((eq? g1016 #<0007>) (ps_179@lam "parser"))
(else
(case (caml-regular-constr-tag g1016)
((1)
(begin
(ps_179@lam "tuple ")
(pi_71@lam (caml-constr-get-field x1 0))))
((2)
(begin
(dump_constr_95@lam
(caml-constr-get-field x1 0))
(pi_71@lam (caml-constr-get-field x1 1))))
((4)
(begin
(ps_179@lam "vector ")
(pi_71@lam (caml-constr-get-field x1 0))))
(else
(begin
(ps_179@lam "record ")
(pi_71@lam (caml-constr-get-field x1 0)))))))))
(begin
(define (dump_primitive_237@lam x1)
(let ((g1017 x1))
(cond ((eq? g1017 #f) (ps_179@lam "Pidentity"))
((eq? g1017 #a000) (ps_179@lam "Pupdate"))
((eq? g1017 #<0008>) (ps_179@lam "Ptag-of"))
((eq? g1017 #<000c>) (ps_179@lam "Praise"))
((eq? g1017 #<000d>) (ps_179@lam "Pnot"))
((eq? g1017 #<000e>) (ps_179@lam "Pnegint"))
((eq? g1017 #<000f>) (ps_179@lam "Psuccint"))
((eq? g1017 #<0010>) (ps_179@lam "Ppredint"))
((eq? g1017 #<0011>) (ps_179@lam "Paddint"))
((eq? g1017 #<0012>) (ps_179@lam "Psubint"))
((eq? g1017 #<0013>) (ps_179@lam "Pmulint"))
((eq? g1017 #<0014>) (ps_179@lam "Pdivint"))
((eq? g1017 #<0015>) (ps_179@lam "Pmodint"))
((eq? g1017 #<0016>) (ps_179@lam "Pandint"))
((eq? g1017 #<0017>) (ps_179@lam "Porint"))
((eq? g1017 #<0018>) (ps_179@lam "Pxorint"))
((eq? g1017 #<0019>)
(ps_179@lam "Pshiftleftint"))
((eq? g1017 #<001a>)
(ps_179@lam "Pshiftrightintsigned"))
((eq? g1017 #<001b>)
(ps_179@lam "Pshiftrightintunsigned"))
((eq? g1017 #<001c>) (ps_179@lam "Pincr"))
((eq? g1017 #<001d>) (ps_179@lam "Pdecr"))
((eq? g1017 #<001e>) (ps_179@lam "Pintoffloat"))
((eq? g1017 #<0020>)
(ps_179@lam "Pstringlength"))
((eq? g1017 #<0021>)
(ps_179@lam "Pgetstringchar"))
((eq? g1017 #<0022>)
(ps_179@lam "Psetstringchar"))
((eq? g1017 #<0023>) (ps_179@lam "Pmakevector"))
((eq? g1017 #<0024>) (ps_179@lam "Pvectlength"))
((eq? g1017 #<0025>) (ps_179@lam "Pgetvectitem"))
((eq? g1017 #<0026>) (ps_179@lam "Psetvectitem"))
(else
(case (caml-regular-constr-tag g1017)
((2)
(begin
(ps_179@lam "(Pget_global ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((3)
(begin
(ps_179@lam "(Pset_global ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((4)
(begin
(ps_179@lam "(Pdummy ")
(begin
(pdummy_size_74@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((6)
(begin
(ps_179@lam "(Ptest ")
(begin
(dump_bool_test_110@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((7)
(begin
(ps_179@lam "(Pmakeblock ")
(begin
(dump_constr_tag_75@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((9)
(begin
(ps_179@lam "(Pfield ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((10)
(begin
(ps_179@lam "(Psetfield ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((11)
(begin
(ps_179@lam "(Pccall ")
(begin
(ps_179@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
(else
(begin
(ps_179@lam "(Pfloatprim ")
(begin
(dump_float_primitive_199@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))))))
(begin
(define (dump_float_primitive_199@lam x1)
(let ((g1018 x1))
(cond ((eq? g1018 #f) (ps_179@lam "Pfloatofint"))
((eq? g1018 #t) (ps_179@lam "Pnegfloat"))
((eq? g1018 #unspecified)
(ps_179@lam "Paddfloat"))
((eq? g1018 #u0000) (ps_179@lam "Psubfloat"))
((eq? g1018 #a000) (ps_179@lam "Pmulfloat"))
((eq? g1018 #<0006>) (ps_179@lam "Pdivfloat"))
(else #f))))
(define (dump_bool_test_110@lam x1)
(let ((g1019 x1))
(cond ((eq? g1019 #f) (ps_179@lam "Peq"))
((eq? g1019 #t) (ps_179@lam "Pnoteq_test"))
(else
(case (caml-regular-constr-tag g1019)
((3)
(labels
((staticfail1009
()
(begin
(ps_179@lam "(Pint_test ")
(begin
(prim_test_234@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))
(case (if (caml-constant-constr?
(caml-constr-get-field x1 0))
-1
(caml-regular-constr-tag
(caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "(Pint_test (Pnoteqimm ")
(begin
(pi_71@lam
(caml-constr-get-field
(caml-constr-get-field x1 0)
0))
(ps_179@lam "))"))))
(else (staticfail1009)))))
((4)
(labels
((staticfail1010
()
(begin
(ps_179@lam "(Pfloat_test ")
(begin
(prim_test_234@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))
(case (if (caml-constant-constr?
(caml-constr-get-field x1 0))
-1
(caml-regular-constr-tag
(caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "(Pint_test (Pnoteqimm ")
(begin
(pf_249@lam
(caml-constr-get-field
(caml-constr-get-field x1 0)
0))
(ps_179@lam "))"))))
(else (staticfail1010)))))
((5)
(labels
((staticfail1011
()
(begin
(ps_179@lam "(Pstring_test ")
(begin
(prim_test_234@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))
(case (if (caml-constant-constr?
(caml-constr-get-field x1 0))
-1
(caml-regular-constr-tag
(caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "(Pint_test (Pnoteqimm ")
(begin
(ps_179@lam
(caml-constr-get-field
(caml-constr-get-field x1 0)
0))
(ps_179@lam "))"))))
(else (staticfail1011)))))
(else
(dump_constr_tag_75@lam
(caml-constr-get-field
x1
0))))))))
))))))))))
(begin
(define (dump_lambda_193@lam x1)
(lambda (x2)
(lambda (x3)
(3-232-dump_lambda_193@lam x1 x2 x3))))
(define (3-232-dump_lambda_193@lam x1 x2 x3)
(begin
(cell-set! current_out_stream_102@lam x1)
(begin
(if x2
(begin
(ps_179@lam "(rec ")
(begin (dump_lam_160@lam x3) (ps_179@lam ")")))
(dump_lam_160@lam x3))
(pn_129@lam #f))))
)
| null | https://raw.githubusercontent.com/samoht/camloo/29a578a152fa23a3125a2a5b23e325b6d45d3abd/src/camloo/Llib.bootstrap/lam.scm | scheme | Le module
Les variables globales
Les expressions globales | (module
__caml_lam
(library camloo-runtime)
(import
__caml_misc
__caml_const
__caml_lambda
__caml_prim
__caml_globals)
(export
(string_for_C_read_34@lam x1)
current_out_stream_102@lam
(ps_179@lam x1)
(pn_129@lam x1)
(pc_182@lam x1)
(pi_71@lam x1)
(pf_249@lam x1)
(prim_test_234@lam x1)
(dump_lam_160@lam x1)
(dump_struct_constant_199@lam x1)
(dump_lams_227@lam x1)
(pdummy_size_74@lam x1)
(dump_primitive_237@lam x1)
(dump_atomic_constant_103@lam x1)
(dump_constr_95@lam x1)
(dump_constr_tag_75@lam x1)
(dump_qualified_ident_170@lam x1)
(dump_bool_test_110@lam x1)
(dump_float_primitive_199@lam x1)
(dump_lambda_193@lam x1)
(3-232-dump_lambda_193@lam x1 x2 x3)))
L'initialisation du module
(init_camloo!)
(define (string_for_C_read_34@lam x1)
(let ((x2 0))
(begin
(let ((stop1001 (-fx (string-length x1) 1)))
(let for1000 ((i3 0))
(if (<=fx i3 stop1001)
(begin
(set! x2
(+fx x2
(let ((x5 ((nth_char_166@string x1) i3)))
(labels
((staticfail1002 () (if (is_printable x5) 1 4)))
(case x5
((#\tab #\newline #\\ #\") 2)
(else (staticfail1002)))))))
(for1000 (+fx i3 1)))
(unspecified))))
(if (eq? x2 (string-length x1))
x1
(let ((x3 (create_string_138@string x2)))
(begin
(set! x2 0)
(begin
(let ((stop1004 (-fx (string-length x1) 1)))
(let for1003 ((i4 0))
(if (<=fx i4 stop1004)
(begin
(begin
(let ((x6 ((nth_char_166@string x1) i4)))
(labels
((staticfail1005
()
(if (is_printable x6)
(((set_nth_char_28@string x3) x2) x6)
(let ((x7 (int_of_char x6)))
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(begin
(((set_nth_char_28@string x3) x2)
(char_of_int_212@char
(+fx 48 (/fx x7 64))))
(begin
(set! x2 (+fx x2 1))
(begin
(((set_nth_char_28@string x3) x2)
(char_of_int_212@char
(+fx 48 (modulo (/fx x7 8) 8))))
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2)
(char_of_int_212@char
(+fx 48
(modulo
x7
8))))))))))))))
(case x6
((#\")
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\"))))
((#\\)
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\\))))
((#\newline)
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\n))))
((#\tab)
(begin
(((set_nth_char_28@string x3) x2) #\\)
(begin
(set! x2 (+fx x2 1))
(((set_nth_char_28@string x3) x2) #\t))))
(else (staticfail1005)))))
(set! x2 (+fx x2 1)))
(for1003 (+fx i4 1)))
(unspecified))))
x3)))))))
(define current_out_stream_102@lam
(make-cell stdout_127@io))
(define (ps_179@lam x1)
((output_string_156@io
(cell-ref current_out_stream_102@lam))
x1))
(define (pn_129@lam x1)
(output_char
(cell-ref current_out_stream_102@lam)
#\newline))
(define (pc_182@lam x1)
(output_char
(cell-ref current_out_stream_102@lam)
x1))
(define (pi_71@lam x1)
(ps_179@lam (string_of_int_188@int x1)))
(define (pf_249@lam x1)
(begin
(((fprintf_48@printf
(cell-ref current_out_stream_102@lam))
"%f")
x1)
#f))
(define (prim_test_234@lam x1)
(let ((g1012 x1))
(cond ((eq? g1012 #f) (ps_179@lam "PTeq"))
((eq? g1012 #t) (ps_179@lam "PTnoteq"))
((eq? g1012 #u0000) (ps_179@lam "PTlt"))
((eq? g1012 #a000) (ps_179@lam "PTle"))
((eq? g1012 #<0006>) (ps_179@lam "PTgt"))
((eq? g1012 #<0007>) (ps_179@lam "PTge"))
(else (ps_179@lam "PTnoteqimm")))))
(begin
(define (dump_lam_160@lam x1)
(let ((g1013 x1))
(cond ((eq? g1013 #<000a>)
(ps_179@lam "(Lstaticfail)"))
(else
(case (caml-regular-constr-tag g1013)
((1)
(begin
(ps_179@lam "(Lvar ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((2)
(begin
(ps_179@lam "(Lconst ")
(begin
(dump_struct_constant_199@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((3)
(begin
(ps_179@lam "(Lapply ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(dump_lams_227@lam (caml-constr-get-field x1 1))
(ps_179@lam ")")))))
((4)
(begin
(ps_179@lam "(Lfunction ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((5)
(labels
((staticfail1006
()
(begin
(ps_179@lam "(Llet ")
(begin
(dump_lams_227@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")")))))))
(if (null? (caml-constr-get-field x1 0))
(dump_lam_160@lam (caml-constr-get-field x1 1))
(staticfail1006))))
((6)
(begin
(ps_179@lam "(Lletrec (")
(begin
((do_list_18@list
(lambda (x2)
(begin
(ps_179@lam "(")
(begin
(dump_lam_160@lam (caml-constr-get-field x2 0))
(begin
(ps_179@lam " (")
(begin
(pdummy_size_74@lam
(caml-constr-get-field x2 1))
(ps_179@lam "))")))))))
(caml-constr-get-field x1 0))
(begin
(ps_179@lam ") ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((7)
(begin
(ps_179@lam "(Lprim ")
(begin
(dump_primitive_237@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lams_227@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((8)
(begin
(ps_179@lam "(Lcond ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " (")
(begin
((do_list_18@list
(lambda (x2)
(begin
(ps_179@lam "(")
(begin
(dump_atomic_constant_103@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam
(caml-constr-get-field x2 1))
(ps_179@lam ") ")))))))
(caml-constr-get-field x1 1))
(ps_179@lam "))"))))))
((9)
(begin
(ps_179@lam "(Lswitch ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam "(")
(begin
((do_list_18@list
(lambda (x2)
(begin
(ps_179@lam "(")
(begin
(dump_constr_95@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam
(caml-constr-get-field x2 1))
(ps_179@lam ") ")))))))
(caml-constr-get-field x1 2))
(ps_179@lam "))"))))))))
((11)
(begin
(ps_179@lam "(Lstatichandle ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((12)
(begin
(ps_179@lam "(Lhandle ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((13)
(begin
(ps_179@lam "(Lifthenelse ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 2))
(ps_179@lam ")"))))))))
((14)
(begin
(ps_179@lam "(Lsequence ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((15)
(begin
(ps_179@lam "(Lwhile ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((16)
(begin
(ps_179@lam "(Lfor ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam " ")
(begin
(if (caml-constr-get-field x1 2)
(ps_179@lam "#t ")
(ps_179@lam "#f "))
(begin
(dump_lam_160@lam (caml-constr-get-field x1 3))
(ps_179@lam ")")))))))))
((17)
(begin
(ps_179@lam "(Lsequand ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
((18)
(begin
(ps_179@lam "(Lsequor ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
(else
(begin
(ps_179@lam "(Lshared ")
(begin
(dump_lam_160@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam
(cell-ref (caml-constr-get-field x1 1)))
(ps_179@lam ")")))))))))))
(begin
(define (dump_lams_227@lam x1)
(begin
(ps_179@lam "(")
(begin
((do_list_18@list
(lambda (x2)
(begin (dump_lam_160@lam x2) (ps_179@lam " "))))
x1)
(ps_179@lam ")"))))
(begin
(define (dump_atomic_constant_103@lam x1)
(case (caml-regular-constr-tag x1)
((1) (pi_71@lam (caml-constr-get-field x1 0)))
((2) (pf_249@lam (caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "#")
(begin
(pc_182@lam #\")
(begin
(ps_179@lam
(string_for_C_read_34@lam
(caml-constr-get-field x1 0)))
(pc_182@lam #\")))))
(else
(labels
((staticfail1007
()
(begin
(ps_179@lam "#a")
(let ((x2 (int_of_char (caml-constr-get-field x1 0))))
(let ((x3 (string_of_int_188@int x2)))
(if (<fx x2 10)
(begin (ps_179@lam "00") (ps_179@lam x3))
(if (<fx x2 100)
(begin (ps_179@lam "0") (ps_179@lam x3))
(ps_179@lam x3))))))))
(let ((g1014 (caml-constr-get-field x1 0)))
(cond ((char=? g1014 #\newline)
(begin (ps_179@lam "#\\") (ps_179@lam "Newline")))
((char=? g1014 #\tab)
(begin (ps_179@lam "#\\") (ps_179@lam "tab")))
(else (staticfail1007))))))))
(begin
(define (dump_struct_constant_199@lam x1)
(case (caml-regular-constr-tag x1)
((1)
(begin
(ps_179@lam "(SCatom ")
(begin
(dump_atomic_constant_103@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
(else
(begin
(ps_179@lam "(SCblock ")
(begin
(dump_constr_tag_75@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " (")
(begin
((do_list_18@list
(lambda (x2)
(begin
(dump_struct_constant_199@lam x2)
(ps_179@lam " "))))
(caml-constr-get-field x1 1))
(ps_179@lam "))"))))))))
(begin
(define (dump_qualified_ident_170@lam x1)
(begin
(ps_179@lam "(qualifiedident ")
(begin
(pc_182@lam #\")
(begin
(ps_179@lam (caml-constr-get-field x1 0))
(begin
(pc_182@lam #\")
(begin
(ps_179@lam " ")
(begin
(pc_182@lam #\")
(begin
(ps_179@lam (caml-constr-get-field x1 1))
(begin (pc_182@lam #\") (ps_179@lam ")"))))))))))
(begin
(define (dump_constr_tag_75@lam x1)
(case (caml-regular-constr-tag x1)
((1)
(begin
(ps_179@lam "(ConstrExtensible ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
(else
(begin
(ps_179@lam "(ConstrRegular ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 1))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 2))
(ps_179@lam ")"))))))))))
(begin
(define (dump_constr_95@lam x1)
(let ((x2 (caml-constr-get-field
(caml-constr-get-field x1 1)
3)))
(case (caml-regular-constr-tag x2)
((1)
(begin
(ps_179@lam "(ConstrExtensible ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x2 1))
(ps_179@lam ")"))))))
(else
(let ((x3 (caml-constr-get-field
(caml-constr-get-field x1 1)
4)))
(labels
((staticfail1008
()
(begin
(ps_179@lam "(ConstrRegular ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x2 1))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x2 2))
(ps_179@lam ")")))))))))
(let ((g1015 x3))
(cond ((eq? g1015 #f)
(begin
(ps_179@lam "(ConstrConstant ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x2 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam
(caml-constr-get-field x2 1))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam
(caml-constr-get-field x2 2))
(ps_179@lam ")"))))))))
(else (staticfail1008))))))))))
(begin
(define (pdummy_size_74@lam x1)
(let ((g1016 x1))
(cond ((eq? g1016 #unspecified)
(ps_179@lam "function "))
((eq? g1016 #<0006>) (ps_179@lam "stream"))
((eq? g1016 #<0007>) (ps_179@lam "parser"))
(else
(case (caml-regular-constr-tag g1016)
((1)
(begin
(ps_179@lam "tuple ")
(pi_71@lam (caml-constr-get-field x1 0))))
((2)
(begin
(dump_constr_95@lam
(caml-constr-get-field x1 0))
(pi_71@lam (caml-constr-get-field x1 1))))
((4)
(begin
(ps_179@lam "vector ")
(pi_71@lam (caml-constr-get-field x1 0))))
(else
(begin
(ps_179@lam "record ")
(pi_71@lam (caml-constr-get-field x1 0)))))))))
(begin
(define (dump_primitive_237@lam x1)
(let ((g1017 x1))
(cond ((eq? g1017 #f) (ps_179@lam "Pidentity"))
((eq? g1017 #a000) (ps_179@lam "Pupdate"))
((eq? g1017 #<0008>) (ps_179@lam "Ptag-of"))
((eq? g1017 #<000c>) (ps_179@lam "Praise"))
((eq? g1017 #<000d>) (ps_179@lam "Pnot"))
((eq? g1017 #<000e>) (ps_179@lam "Pnegint"))
((eq? g1017 #<000f>) (ps_179@lam "Psuccint"))
((eq? g1017 #<0010>) (ps_179@lam "Ppredint"))
((eq? g1017 #<0011>) (ps_179@lam "Paddint"))
((eq? g1017 #<0012>) (ps_179@lam "Psubint"))
((eq? g1017 #<0013>) (ps_179@lam "Pmulint"))
((eq? g1017 #<0014>) (ps_179@lam "Pdivint"))
((eq? g1017 #<0015>) (ps_179@lam "Pmodint"))
((eq? g1017 #<0016>) (ps_179@lam "Pandint"))
((eq? g1017 #<0017>) (ps_179@lam "Porint"))
((eq? g1017 #<0018>) (ps_179@lam "Pxorint"))
((eq? g1017 #<0019>)
(ps_179@lam "Pshiftleftint"))
((eq? g1017 #<001a>)
(ps_179@lam "Pshiftrightintsigned"))
((eq? g1017 #<001b>)
(ps_179@lam "Pshiftrightintunsigned"))
((eq? g1017 #<001c>) (ps_179@lam "Pincr"))
((eq? g1017 #<001d>) (ps_179@lam "Pdecr"))
((eq? g1017 #<001e>) (ps_179@lam "Pintoffloat"))
((eq? g1017 #<0020>)
(ps_179@lam "Pstringlength"))
((eq? g1017 #<0021>)
(ps_179@lam "Pgetstringchar"))
((eq? g1017 #<0022>)
(ps_179@lam "Psetstringchar"))
((eq? g1017 #<0023>) (ps_179@lam "Pmakevector"))
((eq? g1017 #<0024>) (ps_179@lam "Pvectlength"))
((eq? g1017 #<0025>) (ps_179@lam "Pgetvectitem"))
((eq? g1017 #<0026>) (ps_179@lam "Psetvectitem"))
(else
(case (caml-regular-constr-tag g1017)
((2)
(begin
(ps_179@lam "(Pget_global ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((3)
(begin
(ps_179@lam "(Pset_global ")
(begin
(dump_qualified_ident_170@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((4)
(begin
(ps_179@lam "(Pdummy ")
(begin
(pdummy_size_74@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((6)
(begin
(ps_179@lam "(Ptest ")
(begin
(dump_bool_test_110@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((7)
(begin
(ps_179@lam "(Pmakeblock ")
(begin
(dump_constr_tag_75@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((9)
(begin
(ps_179@lam "(Pfield ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((10)
(begin
(ps_179@lam "(Psetfield ")
(begin
(pi_71@lam (caml-constr-get-field x1 0))
(ps_179@lam ")"))))
((11)
(begin
(ps_179@lam "(Pccall ")
(begin
(ps_179@lam (caml-constr-get-field x1 0))
(begin
(ps_179@lam " ")
(begin
(pi_71@lam (caml-constr-get-field x1 1))
(ps_179@lam ")"))))))
(else
(begin
(ps_179@lam "(Pfloatprim ")
(begin
(dump_float_primitive_199@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))))))
(begin
(define (dump_float_primitive_199@lam x1)
(let ((g1018 x1))
(cond ((eq? g1018 #f) (ps_179@lam "Pfloatofint"))
((eq? g1018 #t) (ps_179@lam "Pnegfloat"))
((eq? g1018 #unspecified)
(ps_179@lam "Paddfloat"))
((eq? g1018 #u0000) (ps_179@lam "Psubfloat"))
((eq? g1018 #a000) (ps_179@lam "Pmulfloat"))
((eq? g1018 #<0006>) (ps_179@lam "Pdivfloat"))
(else #f))))
(define (dump_bool_test_110@lam x1)
(let ((g1019 x1))
(cond ((eq? g1019 #f) (ps_179@lam "Peq"))
((eq? g1019 #t) (ps_179@lam "Pnoteq_test"))
(else
(case (caml-regular-constr-tag g1019)
((3)
(labels
((staticfail1009
()
(begin
(ps_179@lam "(Pint_test ")
(begin
(prim_test_234@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))
(case (if (caml-constant-constr?
(caml-constr-get-field x1 0))
-1
(caml-regular-constr-tag
(caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "(Pint_test (Pnoteqimm ")
(begin
(pi_71@lam
(caml-constr-get-field
(caml-constr-get-field x1 0)
0))
(ps_179@lam "))"))))
(else (staticfail1009)))))
((4)
(labels
((staticfail1010
()
(begin
(ps_179@lam "(Pfloat_test ")
(begin
(prim_test_234@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))
(case (if (caml-constant-constr?
(caml-constr-get-field x1 0))
-1
(caml-regular-constr-tag
(caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "(Pint_test (Pnoteqimm ")
(begin
(pf_249@lam
(caml-constr-get-field
(caml-constr-get-field x1 0)
0))
(ps_179@lam "))"))))
(else (staticfail1010)))))
((5)
(labels
((staticfail1011
()
(begin
(ps_179@lam "(Pstring_test ")
(begin
(prim_test_234@lam
(caml-constr-get-field x1 0))
(ps_179@lam ")")))))
(case (if (caml-constant-constr?
(caml-constr-get-field x1 0))
-1
(caml-regular-constr-tag
(caml-constr-get-field x1 0)))
((3)
(begin
(ps_179@lam "(Pint_test (Pnoteqimm ")
(begin
(ps_179@lam
(caml-constr-get-field
(caml-constr-get-field x1 0)
0))
(ps_179@lam "))"))))
(else (staticfail1011)))))
(else
(dump_constr_tag_75@lam
(caml-constr-get-field
x1
0))))))))
))))))))))
(begin
(define (dump_lambda_193@lam x1)
(lambda (x2)
(lambda (x3)
(3-232-dump_lambda_193@lam x1 x2 x3))))
(define (3-232-dump_lambda_193@lam x1 x2 x3)
(begin
(cell-set! current_out_stream_102@lam x1)
(begin
(if x2
(begin
(ps_179@lam "(rec ")
(begin (dump_lam_160@lam x3) (ps_179@lam ")")))
(dump_lam_160@lam x3))
(pn_129@lam #f))))
)
|
3d31829140eb98860d2f8b2525a47db9fae31ed38d8e8078003a75cc7de33552 | simplegeo/erlang | naughty_child.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2002 - 2009 . 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%
%%
%%% DESCRIPTION: Implements a naughty child process that does unlink
%%% from its supervisor. Used by the supervisor test suite.
-module(naughty_child).
-behaviour(gen_server).
%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
%%--------------------------------------------------------------------
%% External exports
-export([start_link/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-record(state, {}).
%%====================================================================
%% External functions
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link/0
%% Description: Starts the server
%%--------------------------------------------------------------------
start_link(Pid) ->
gen_server:start_link({local, naughty_foo}, ?MODULE, [Pid], []).
%%====================================================================
%% Server functions
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init/1
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([Pid]) ->
unlink(Pid),
{ok, #state{}}.
%%--------------------------------------------------------------------
Function : handle_call/3
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
%% Function: handle_cast/2
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast(_Msg, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: handle_info/2
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info(_Info, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate/2
%% Description: Shutdown the server
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
%% Func: code_change/3
%% Purpose: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
| null | https://raw.githubusercontent.com/simplegeo/erlang/15eda8de27ba73d176c7eeb3a70a64167f50e2c4/lib/stdlib/test/naughty_child.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%
DESCRIPTION: Implements a naughty child process that does unlink
from its supervisor. Used by the supervisor test suite.
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
External exports
gen_server callbacks
====================================================================
External functions
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
====================================================================
Server functions
====================================================================
--------------------------------------------------------------------
Function: init/1
Description: Initiates the server
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Handling call messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_cast/2
Description: Handling cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_info/2
Description: Handling all non call/cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: terminate/2
Description: Shutdown the server
--------------------------------------------------------------------
--------------------------------------------------------------------
Func: code_change/3
Purpose: Convert process state when code is changed
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright Ericsson AB 2002 - 2009 . 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 "
-module(naughty_child).
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
code_change/3]).
-record(state, {}).
Function : start_link/0
start_link(Pid) ->
gen_server:start_link({local, naughty_foo}, ?MODULE, [Pid], []).
init([Pid]) ->
unlink(Pid),
{ok, #state{}}.
Function : handle_call/3
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
|
e935b76792203e7ff918c4c0a1c126456160e25df8e780c2e97d01a4b433c0b8 | gas2serra/cldk | medium.lisp | (in-package :cldk-raster-image)
;;;
;;; Medium
;;;
(defclass raster-image-medium (render-medium-mixin basic-medium)
())
| null | https://raw.githubusercontent.com/gas2serra/cldk/63c8322aedac44249ff8f28cd4f5f59a48ab1441/mcclim/Backends/RasterImage/medium.lisp | lisp |
Medium
| (in-package :cldk-raster-image)
(defclass raster-image-medium (render-medium-mixin basic-medium)
())
|
9205db9dd951d1b54c4edb36be9cb766209c66ac1d4b213da462848f376cbbed | nivertech/github-backup | Git.hs | git repository handling
-
- This is written to be completely independant of git - annex and should be
- suitable for other uses .
-
- Copyright 2010 , 2011 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- This is written to be completely independant of git-annex and should be
- suitable for other uses.
-
- Copyright 2010, 2011 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Git (
Repo(..),
Ref(..),
Branch,
Sha,
Tag,
repoIsUrl,
repoIsSsh,
repoIsHttp,
repoIsLocalBare,
repoDescribe,
repoLocation,
workTree,
gitDir,
configTrue,
attributes,
assertLocal,
) where
import qualified Data.Map as M
import Data.Char
import Network.URI (uriPath, uriScheme, unEscapeString)
import Common
import Git.Types
{- User-visible description of a git repo. -}
repoDescribe :: Repo -> String
repoDescribe Repo { remoteName = Just name } = name
repoDescribe Repo { location = Url url } = show url
repoDescribe Repo { location = Dir dir } = dir
repoDescribe Repo { location = Unknown } = "UNKNOWN"
{- Location of the repo, either as a path or url. -}
repoLocation :: Repo -> String
repoLocation Repo { location = Url url } = show url
repoLocation Repo { location = Dir dir } = dir
repoLocation Repo { location = Unknown } = undefined
{- Some code needs to vary between URL and normal repos,
- or bare and non-bare, these functions help with that. -}
repoIsUrl :: Repo -> Bool
repoIsUrl Repo { location = Url _ } = True
repoIsUrl _ = False
repoIsSsh :: Repo -> Bool
repoIsSsh Repo { location = Url url }
| scheme == "ssh:" = True
-- git treats these the same as ssh
| scheme == "git+ssh:" = True
| scheme == "ssh+git:" = True
| otherwise = False
where
scheme = uriScheme url
repoIsSsh _ = False
repoIsHttp :: Repo -> Bool
repoIsHttp Repo { location = Url url }
| uriScheme url == "http:" = True
| uriScheme url == "https:" = True
| otherwise = False
repoIsHttp _ = False
configAvail ::Repo -> Bool
configAvail Repo { config = c } = c /= M.empty
repoIsLocalBare :: Repo -> Bool
repoIsLocalBare r@(Repo { location = Dir _ }) = configAvail r && configBare r
repoIsLocalBare _ = False
assertLocal :: Repo -> a -> a
assertLocal repo action =
if not $ repoIsUrl repo
then action
else error $ "acting on non-local git repo " ++ repoDescribe repo ++
" not supported"
configBare :: Repo -> Bool
configBare repo = maybe unknown configTrue $ M.lookup "core.bare" $ config repo
where
unknown = error $ "it is not known if git repo " ++
repoDescribe repo ++
" is a bare repository; config not read"
{- Path to a repository's gitattributes file. -}
attributes :: Repo -> String
attributes repo
| configBare repo = workTree repo ++ "/info/.gitattributes"
| otherwise = workTree repo ++ "/.gitattributes"
{- Path to a repository's .git directory. -}
gitDir :: Repo -> String
gitDir repo
| configBare repo = workTree repo
| otherwise = workTree repo </> ".git"
{- Path to a repository's --work-tree, that is, its top.
-
- Note that for URL repositories, this is the path on the remote host. -}
workTree :: Repo -> FilePath
workTree Repo { location = Url u } = unEscapeString $ uriPath u
workTree Repo { location = Dir d } = d
workTree Repo { location = Unknown } = undefined
{- Checks if a string from git config is a true value. -}
configTrue :: String -> Bool
configTrue s = map toLower s == "true"
| null | https://raw.githubusercontent.com/nivertech/github-backup/490bc0e1fe0395a54e70de5aa0201c81d1a64476/Git.hs | haskell | User-visible description of a git repo.
Location of the repo, either as a path or url.
Some code needs to vary between URL and normal repos,
- or bare and non-bare, these functions help with that.
git treats these the same as ssh
Path to a repository's gitattributes file.
Path to a repository's .git directory.
Path to a repository's --work-tree, that is, its top.
-
- Note that for URL repositories, this is the path on the remote host.
Checks if a string from git config is a true value. | git repository handling
-
- This is written to be completely independant of git - annex and should be
- suitable for other uses .
-
- Copyright 2010 , 2011 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- This is written to be completely independant of git-annex and should be
- suitable for other uses.
-
- Copyright 2010, 2011 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Git (
Repo(..),
Ref(..),
Branch,
Sha,
Tag,
repoIsUrl,
repoIsSsh,
repoIsHttp,
repoIsLocalBare,
repoDescribe,
repoLocation,
workTree,
gitDir,
configTrue,
attributes,
assertLocal,
) where
import qualified Data.Map as M
import Data.Char
import Network.URI (uriPath, uriScheme, unEscapeString)
import Common
import Git.Types
repoDescribe :: Repo -> String
repoDescribe Repo { remoteName = Just name } = name
repoDescribe Repo { location = Url url } = show url
repoDescribe Repo { location = Dir dir } = dir
repoDescribe Repo { location = Unknown } = "UNKNOWN"
repoLocation :: Repo -> String
repoLocation Repo { location = Url url } = show url
repoLocation Repo { location = Dir dir } = dir
repoLocation Repo { location = Unknown } = undefined
repoIsUrl :: Repo -> Bool
repoIsUrl Repo { location = Url _ } = True
repoIsUrl _ = False
repoIsSsh :: Repo -> Bool
repoIsSsh Repo { location = Url url }
| scheme == "ssh:" = True
| scheme == "git+ssh:" = True
| scheme == "ssh+git:" = True
| otherwise = False
where
scheme = uriScheme url
repoIsSsh _ = False
repoIsHttp :: Repo -> Bool
repoIsHttp Repo { location = Url url }
| uriScheme url == "http:" = True
| uriScheme url == "https:" = True
| otherwise = False
repoIsHttp _ = False
configAvail ::Repo -> Bool
configAvail Repo { config = c } = c /= M.empty
repoIsLocalBare :: Repo -> Bool
repoIsLocalBare r@(Repo { location = Dir _ }) = configAvail r && configBare r
repoIsLocalBare _ = False
assertLocal :: Repo -> a -> a
assertLocal repo action =
if not $ repoIsUrl repo
then action
else error $ "acting on non-local git repo " ++ repoDescribe repo ++
" not supported"
configBare :: Repo -> Bool
configBare repo = maybe unknown configTrue $ M.lookup "core.bare" $ config repo
where
unknown = error $ "it is not known if git repo " ++
repoDescribe repo ++
" is a bare repository; config not read"
attributes :: Repo -> String
attributes repo
| configBare repo = workTree repo ++ "/info/.gitattributes"
| otherwise = workTree repo ++ "/.gitattributes"
gitDir :: Repo -> String
gitDir repo
| configBare repo = workTree repo
| otherwise = workTree repo </> ".git"
workTree :: Repo -> FilePath
workTree Repo { location = Url u } = unEscapeString $ uriPath u
workTree Repo { location = Dir d } = d
workTree Repo { location = Unknown } = undefined
configTrue :: String -> Bool
configTrue s = map toLower s == "true"
|
2e17e8132aaf65ee4cbafc2b6e8c8ce2e9df8c5f3ba0d31f949c003763f64a14 | lichtblau/CommonQt | t12.lisp | ;;; -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
;;; -t12.html
(defpackage :qt-tutorial-12
(:use :cl :qt)
(:export #:main))
(in-package :qt-tutorial-12)
(named-readtables:in-readtable :qt)
(defvar *qapp*)
(defclass cannon-field ()
((current-angle :initform 45
:accessor current-angle)
(current-force :initform 0
:accessor current-force)
(timer-count :initform 0
:accessor timer-count)
(auto-shoot-timer :accessor auto-shoot-timer)
(shoot-angle :initform 0
:accessor shoot-angle)
(shoot-force :initform 0
:accessor shoot-force)
(target :accessor target))
(:metaclass qt-class)
(:qt-superclass "QWidget")
(:slots ("setAngle(int)" (lambda (this newval)
(setf (current-angle this)
(min (max 5 newval) 70))))
("setForce(int)" (lambda (this newval)
(setf (current-force this)
(max 0 newval))))
("void moveShot()" move-shot)
("void shoot()" shoot))
(:signals ("angleChanged(int)")
("forceChanged(int)")
("void hit()")
("void missed()"))
(:override ("paintEvent" paint-event)))
(defmethod (setf current-angle) :around (newval (instance cannon-field))
(let ((oldval (current-angle instance)))
(prog1
(call-next-method)
(unless (eql oldval newval)
(#_update instance (cannon-rect instance))
(emit-signal instance "angleChanged(int)" newval)))))
(defmethod (setf current-force) :around (newval (instance cannon-field))
(let ((oldval (current-force instance)))
(prog1
(call-next-method)
(unless (eql oldval newval)
(#_update instance (cannon-rect instance))
(emit-signal instance "forceChanged(int)" newval)))))
(defun cannon-rect (instance)
(let ((result (#_new QRect 0 0 50 50)))
(#_moveBottomLeft result (#_bottomLeft (#_rect instance)))
result))
(defun target-rect (instance)
(let ((result (#_new QRect 0 0 20 10)))
(#_moveCenter result (#_new QPoint
(#_x (target instance))
(- (#_height instance)
1
(#_y (target instance)))))
result))
(defun shot-rect (instance)
(let* ((gravity 4.0d0)
(time (/ (timer-count instance) 20.0d0))
(velocity (shoot-force instance))
(radians (* (shoot-angle instance) (/ pi 180.0d0)))
(velx (* velocity (cos radians)))
(vely (* velocity (sin radians)))
(barrelRect (#_new QRect 30 -5 20 10))
(x0 (* (+ (#_right barrelRect) 5.0d0) (cos radians)))
(y0 (* (+ (#_right barrelRect) 5.0d0) (sin radians)))
(x (+ x0 (* velx time)))
(y (+ y0 (* vely time) (- (* 0.5d0 gravity time time))))
(result (#_new QRect 0 0 6 6)))
(#_moveCenter result (#_new QPoint
(round x)
(- (#_height instance) 1 (round y))))
result))
(defun shoot (instance)
(unless (#_isActive (auto-shoot-timer instance))
(setf (timer-count instance) 0)
(setf (shoot-angle instance) (current-angle instance))
(setf (shoot-force instance) (current-force instance))
(#_start (auto-shoot-timer instance) 5)))
(defun move-shot (instance)
(let ((old (shot-rect instance)))
(incf (timer-count instance))
(let ((new (shot-rect instance)))
(cond
((#_intersects new (target-rect instance))
(#_stop (auto-shoot-timer instance))
(emit-signal instance "hit()"))
((or (> (#_x new) (#_width instance))
(> (#_y new) (#_height instance)))
(#_stop (auto-shoot-timer instance))
(emit-signal instance "missed()"))
(t
(setf old (#_unite old new)))))
(#_update instance old)))
(defmethod initialize-instance :after ((instance cannon-field) &key parent)
(if parent
(new instance parent)
(new instance))
(setf (auto-shoot-timer instance) (#_new QTimer instance))
(#_connect "QObject"
(auto-shoot-timer instance)
(QSIGNAL "timeout()")
instance
(QSLOT "moveShot()"))
(#_setPalette instance (#_new QPalette (#_new QColor 250 250 200)))
(#_setAutoFillBackground instance (bool 1))
(new-target instance))
(defun new-target (instance)
(setf (target instance)
(#_new QPoint
(+ 200 (random 190))
(+ 10 (random 255))))
(#_update instance))
(defun paint-shot (instance painter)
(#_setPen painter (#_NoPen "Qt"))
(#_setBrush painter (#_new QBrush (#_black "Qt") (#_SolidPattern "Qt")))
(#_drawRect painter (shot-rect instance)))
(defun paint-cannon (instance painter)
(#_setPen painter (#_NoPen "Qt"))
(#_setBrush painter (#_new QBrush (#_blue "Qt") (#_SolidPattern "Qt")))
(#_save painter)
(#_translate painter 0 (#_height (#_rect instance)))
(#_drawPie painter (#_new QRect -35 -35 70 70) 0 (* 90 16))
(#_rotate painter (- (current-angle instance)))
(#_drawRect painter (#_new QRect 30 -5 20 10))
(#_restore painter))
(defun paint-target (instance painter)
(#_setPen painter (#_NoPen "Qt"))
(#_setBrush painter (#_new QBrush (#_red "Qt") (#_SolidPattern "Qt")))
(#_drawRect painter (target-rect instance)))
(defmethod paint-event ((instance cannon-field) paint-event)
(let ((painter (#_new QPainter instance)))
(paint-cannon instance painter)
(when (#_isActive (auto-shoot-timer instance))
(paint-shot instance painter))
(paint-target instance painter)
(#_end painter)))
(defclass lcd-range ()
((slider :accessor slider)
(label :accessor label))
(:metaclass qt-class)
(:qt-superclass "QWidget")
(:slots ("setValue(int)" (lambda (this int) (setf (value this) int)))
("setRange(int,int)" set-range))
(:signals ("valueChanged(int)")))
(defmethod value ((instance lcd-range))
(#_value (slider instance)))
(defmethod (setf value) (newval (instance lcd-range))
(#_setValue (slider instance) newval))
(defmethod text ((instance lcd-range))
(#_text (label instance)))
(defmethod (setf text) (newval (instance lcd-range))
(#_setText (label instance) newval))
(defun set-range (instance min max)
(when (or (minusp min) (> max 99) (> min max))
(warn "invalid SET-RANGE(~D, ~D)" min max))
(#_setRange (slider instance) min max))
(defmethod initialize-instance
:after
((instance lcd-range) &key parent text)
(if parent
(new instance parent)
(new instance))
(let ((lcd (#_new QLCDNumber 2)))
(#_setSegmentStyle lcd (#_Filled "QLCDNumber"))
(let ((slider (#_new QSlider (#_Horizontal "Qt"))))
(setf (slider instance) slider)
(#_setRange slider 0 99)
(#_setValue slider 0)
(#_connect "QObject"
slider
(QSIGNAL "valueChanged(int)")
lcd
(QSLOT "display(int)"))
(#_connect "QObject"
slider
(QSIGNAL "valueChanged(int)")
instance
(QSIGNAL "valueChanged(int)"))
(let ((label (#_new QLabel)))
(setf (label instance) label)
(#_setAlignment label (logior (primitive-value
(#_AlignHCenter "Qt"))
(primitive-value
(#_AlignTop "Qt"))))
(let ((layout (#_new QVBoxLayout)))
(#_addWidget layout lcd)
(#_addWidget layout slider)
(#_addWidget layout label)
(#_setLayout instance layout)))
(#_setFocusProxy instance slider)))
(when text
(setf (text instance) text)))
(defclass my-widget ()
()
(:metaclass qt-class)
(:qt-superclass "QWidget"))
(defmethod initialize-instance :after ((instance my-widget) &key parent)
(if parent
(new instance parent)
(new instance))
(let ((quit (#_new QPushButton (qstring "Quit")))
(shoot (#_new QPushButton (qstring "Shoot"))))
(#_setFont quit (#_new QFont (qstring "Times") 18 (#_Bold "QFont")))
(#_setFont shoot (#_new QFont (qstring "Times") 18 (#_Bold "QFont")))
(#_connect "QObject"
quit
(QSIGNAL "clicked()")
*qapp*
(QSLOT "quit()"))
(let ((angle (make-instance 'lcd-range :text "ANGLE"))
(force (make-instance 'lcd-range :text "FORCE"))
(cannon-field (make-instance 'cannon-field)))
(#_connect "QObject"
shoot
(QSIGNAL "clicked()")
cannon-field
(QSLOT "shoot()"))
(set-range angle 5 70)
(set-range force 10 50)
(#_connect "QObject"
angle
(QSIGNAL "valueChanged(int)")
cannon-field
(QSLOT "setAngle(int)"))
(#_connect "QObject"
cannon-field
(QSIGNAL "angleChanged(int)")
angle
(QSLOT "setValue(int)"))
(#_connect "QObject"
force
(QSIGNAL "valueChanged(int)")
cannon-field
(QSLOT "setForce(int)"))
(#_connect "QObject"
cannon-field
(QSIGNAL "forceChanged(int)")
force
(QSLOT "setValue(int)"))
(let ((left-layout (#_new QVBoxLayout))
(top-layout (#_new QHBoxLayout))
(grid (#_new QGridLayout)))
(#_addWidget left-layout angle)
(#_addWidget left-layout force)
(#_addWidget top-layout shoot)
(#_addStretch top-layout 1)
(#_addWidget grid quit 0 0)
(#_addLayout grid top-layout 0 1)
(#_addLayout grid left-layout 1 0)
(#_addWidget grid cannon-field 1 1 2 1)
(#_setColumnStretch grid 1 10)
(#_setLayout instance grid))
(setf (value angle) 60)
(setf (value force) 25)
(#_setFocus angle))))
(defun main ()
(setf *qapp* (make-qapplication))
(let ((window (make-instance 'my-widget)))
(#_setGeometry window 100 100 500 355)
(#_show window)
(unwind-protect
(#_exec *qapp*)
(#_hide window))))
| null | https://raw.githubusercontent.com/lichtblau/CommonQt/fa14472594b2b2b34695ec3fff6f858a03ec5813/tutorial/old/t12.lisp | lisp | -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
-t12.html |
(defpackage :qt-tutorial-12
(:use :cl :qt)
(:export #:main))
(in-package :qt-tutorial-12)
(named-readtables:in-readtable :qt)
(defvar *qapp*)
(defclass cannon-field ()
((current-angle :initform 45
:accessor current-angle)
(current-force :initform 0
:accessor current-force)
(timer-count :initform 0
:accessor timer-count)
(auto-shoot-timer :accessor auto-shoot-timer)
(shoot-angle :initform 0
:accessor shoot-angle)
(shoot-force :initform 0
:accessor shoot-force)
(target :accessor target))
(:metaclass qt-class)
(:qt-superclass "QWidget")
(:slots ("setAngle(int)" (lambda (this newval)
(setf (current-angle this)
(min (max 5 newval) 70))))
("setForce(int)" (lambda (this newval)
(setf (current-force this)
(max 0 newval))))
("void moveShot()" move-shot)
("void shoot()" shoot))
(:signals ("angleChanged(int)")
("forceChanged(int)")
("void hit()")
("void missed()"))
(:override ("paintEvent" paint-event)))
(defmethod (setf current-angle) :around (newval (instance cannon-field))
(let ((oldval (current-angle instance)))
(prog1
(call-next-method)
(unless (eql oldval newval)
(#_update instance (cannon-rect instance))
(emit-signal instance "angleChanged(int)" newval)))))
(defmethod (setf current-force) :around (newval (instance cannon-field))
(let ((oldval (current-force instance)))
(prog1
(call-next-method)
(unless (eql oldval newval)
(#_update instance (cannon-rect instance))
(emit-signal instance "forceChanged(int)" newval)))))
(defun cannon-rect (instance)
(let ((result (#_new QRect 0 0 50 50)))
(#_moveBottomLeft result (#_bottomLeft (#_rect instance)))
result))
(defun target-rect (instance)
(let ((result (#_new QRect 0 0 20 10)))
(#_moveCenter result (#_new QPoint
(#_x (target instance))
(- (#_height instance)
1
(#_y (target instance)))))
result))
(defun shot-rect (instance)
(let* ((gravity 4.0d0)
(time (/ (timer-count instance) 20.0d0))
(velocity (shoot-force instance))
(radians (* (shoot-angle instance) (/ pi 180.0d0)))
(velx (* velocity (cos radians)))
(vely (* velocity (sin radians)))
(barrelRect (#_new QRect 30 -5 20 10))
(x0 (* (+ (#_right barrelRect) 5.0d0) (cos radians)))
(y0 (* (+ (#_right barrelRect) 5.0d0) (sin radians)))
(x (+ x0 (* velx time)))
(y (+ y0 (* vely time) (- (* 0.5d0 gravity time time))))
(result (#_new QRect 0 0 6 6)))
(#_moveCenter result (#_new QPoint
(round x)
(- (#_height instance) 1 (round y))))
result))
(defun shoot (instance)
(unless (#_isActive (auto-shoot-timer instance))
(setf (timer-count instance) 0)
(setf (shoot-angle instance) (current-angle instance))
(setf (shoot-force instance) (current-force instance))
(#_start (auto-shoot-timer instance) 5)))
(defun move-shot (instance)
(let ((old (shot-rect instance)))
(incf (timer-count instance))
(let ((new (shot-rect instance)))
(cond
((#_intersects new (target-rect instance))
(#_stop (auto-shoot-timer instance))
(emit-signal instance "hit()"))
((or (> (#_x new) (#_width instance))
(> (#_y new) (#_height instance)))
(#_stop (auto-shoot-timer instance))
(emit-signal instance "missed()"))
(t
(setf old (#_unite old new)))))
(#_update instance old)))
(defmethod initialize-instance :after ((instance cannon-field) &key parent)
(if parent
(new instance parent)
(new instance))
(setf (auto-shoot-timer instance) (#_new QTimer instance))
(#_connect "QObject"
(auto-shoot-timer instance)
(QSIGNAL "timeout()")
instance
(QSLOT "moveShot()"))
(#_setPalette instance (#_new QPalette (#_new QColor 250 250 200)))
(#_setAutoFillBackground instance (bool 1))
(new-target instance))
(defun new-target (instance)
(setf (target instance)
(#_new QPoint
(+ 200 (random 190))
(+ 10 (random 255))))
(#_update instance))
(defun paint-shot (instance painter)
(#_setPen painter (#_NoPen "Qt"))
(#_setBrush painter (#_new QBrush (#_black "Qt") (#_SolidPattern "Qt")))
(#_drawRect painter (shot-rect instance)))
(defun paint-cannon (instance painter)
(#_setPen painter (#_NoPen "Qt"))
(#_setBrush painter (#_new QBrush (#_blue "Qt") (#_SolidPattern "Qt")))
(#_save painter)
(#_translate painter 0 (#_height (#_rect instance)))
(#_drawPie painter (#_new QRect -35 -35 70 70) 0 (* 90 16))
(#_rotate painter (- (current-angle instance)))
(#_drawRect painter (#_new QRect 30 -5 20 10))
(#_restore painter))
(defun paint-target (instance painter)
(#_setPen painter (#_NoPen "Qt"))
(#_setBrush painter (#_new QBrush (#_red "Qt") (#_SolidPattern "Qt")))
(#_drawRect painter (target-rect instance)))
(defmethod paint-event ((instance cannon-field) paint-event)
(let ((painter (#_new QPainter instance)))
(paint-cannon instance painter)
(when (#_isActive (auto-shoot-timer instance))
(paint-shot instance painter))
(paint-target instance painter)
(#_end painter)))
(defclass lcd-range ()
((slider :accessor slider)
(label :accessor label))
(:metaclass qt-class)
(:qt-superclass "QWidget")
(:slots ("setValue(int)" (lambda (this int) (setf (value this) int)))
("setRange(int,int)" set-range))
(:signals ("valueChanged(int)")))
(defmethod value ((instance lcd-range))
(#_value (slider instance)))
(defmethod (setf value) (newval (instance lcd-range))
(#_setValue (slider instance) newval))
(defmethod text ((instance lcd-range))
(#_text (label instance)))
(defmethod (setf text) (newval (instance lcd-range))
(#_setText (label instance) newval))
(defun set-range (instance min max)
(when (or (minusp min) (> max 99) (> min max))
(warn "invalid SET-RANGE(~D, ~D)" min max))
(#_setRange (slider instance) min max))
(defmethod initialize-instance
:after
((instance lcd-range) &key parent text)
(if parent
(new instance parent)
(new instance))
(let ((lcd (#_new QLCDNumber 2)))
(#_setSegmentStyle lcd (#_Filled "QLCDNumber"))
(let ((slider (#_new QSlider (#_Horizontal "Qt"))))
(setf (slider instance) slider)
(#_setRange slider 0 99)
(#_setValue slider 0)
(#_connect "QObject"
slider
(QSIGNAL "valueChanged(int)")
lcd
(QSLOT "display(int)"))
(#_connect "QObject"
slider
(QSIGNAL "valueChanged(int)")
instance
(QSIGNAL "valueChanged(int)"))
(let ((label (#_new QLabel)))
(setf (label instance) label)
(#_setAlignment label (logior (primitive-value
(#_AlignHCenter "Qt"))
(primitive-value
(#_AlignTop "Qt"))))
(let ((layout (#_new QVBoxLayout)))
(#_addWidget layout lcd)
(#_addWidget layout slider)
(#_addWidget layout label)
(#_setLayout instance layout)))
(#_setFocusProxy instance slider)))
(when text
(setf (text instance) text)))
(defclass my-widget ()
()
(:metaclass qt-class)
(:qt-superclass "QWidget"))
(defmethod initialize-instance :after ((instance my-widget) &key parent)
(if parent
(new instance parent)
(new instance))
(let ((quit (#_new QPushButton (qstring "Quit")))
(shoot (#_new QPushButton (qstring "Shoot"))))
(#_setFont quit (#_new QFont (qstring "Times") 18 (#_Bold "QFont")))
(#_setFont shoot (#_new QFont (qstring "Times") 18 (#_Bold "QFont")))
(#_connect "QObject"
quit
(QSIGNAL "clicked()")
*qapp*
(QSLOT "quit()"))
(let ((angle (make-instance 'lcd-range :text "ANGLE"))
(force (make-instance 'lcd-range :text "FORCE"))
(cannon-field (make-instance 'cannon-field)))
(#_connect "QObject"
shoot
(QSIGNAL "clicked()")
cannon-field
(QSLOT "shoot()"))
(set-range angle 5 70)
(set-range force 10 50)
(#_connect "QObject"
angle
(QSIGNAL "valueChanged(int)")
cannon-field
(QSLOT "setAngle(int)"))
(#_connect "QObject"
cannon-field
(QSIGNAL "angleChanged(int)")
angle
(QSLOT "setValue(int)"))
(#_connect "QObject"
force
(QSIGNAL "valueChanged(int)")
cannon-field
(QSLOT "setForce(int)"))
(#_connect "QObject"
cannon-field
(QSIGNAL "forceChanged(int)")
force
(QSLOT "setValue(int)"))
(let ((left-layout (#_new QVBoxLayout))
(top-layout (#_new QHBoxLayout))
(grid (#_new QGridLayout)))
(#_addWidget left-layout angle)
(#_addWidget left-layout force)
(#_addWidget top-layout shoot)
(#_addStretch top-layout 1)
(#_addWidget grid quit 0 0)
(#_addLayout grid top-layout 0 1)
(#_addLayout grid left-layout 1 0)
(#_addWidget grid cannon-field 1 1 2 1)
(#_setColumnStretch grid 1 10)
(#_setLayout instance grid))
(setf (value angle) 60)
(setf (value force) 25)
(#_setFocus angle))))
(defun main ()
(setf *qapp* (make-qapplication))
(let ((window (make-instance 'my-widget)))
(#_setGeometry window 100 100 500 355)
(#_show window)
(unwind-protect
(#_exec *qapp*)
(#_hide window))))
|
4d2e228cc94ba753b664c73154712189e99bf0d2515f992ab7cc1e863a6cc811 | tek/ribosome | Persist.hs | -- |Persisting data across vim sessions
module Ribosome.Effect.Persist where
import Path (File, Path, Rel)
-- |This effect abstracts storing data of type @a@ in the file system to allow loading it when a plugin starts.
--
-- Each distinct type corresponds to a separate copy of this effect. When the same type should be stored in separate
-- files for different components of the plugin, use 'Tagged'.
-- The subdirectory or file name used for a type is specified to the interpreter.
-- If the constructor 'store' is called with 'Just' a file name, each value is stored in a separate file, otherwise the
-- same file is overwritten on every call to 'store'.
--
The default interpreter delegates file path resolution to the effect ' Ribosome . Persist . PersistPath ' and uses JSON to
-- codec the data.
data Persist a :: Effect where
|Store a value in the persistence file or , if the first argument is ' Just ' , in that file in the persistence
-- directory.
Store :: Maybe (Path Rel File) -> a -> Persist a m ()
|Load a value from the persistence file or , if the first argument is ' Just ' , from that file in the persistence
-- directory.
-- Returns 'Nothing' if the file doesn't exist.
Load :: Maybe (Path Rel File) -> Persist a m (Maybe a)
makeSem_ ''Persist
|Store a value in the persistence file or , if the first argument is ' Just ' , in that file in the persistence
-- directory.
store ::
∀ a r .
Member (Persist a) r =>
Maybe (Path Rel File) ->
a ->
Sem r ()
|Load a value from the persistence file or , if the first argument is ' Just ' , from that file in the persistence
-- directory.
-- Returns 'Nothing' if the file doesn't exist.
load ::
∀ a r .
Member (Persist a) r =>
Maybe (Path Rel File) ->
Sem r (Maybe a)
|Load a value from the persistence file or , if the first argument is ' Just ' , from that file in the persistence
-- directory.
-- Returns the fallback value if the file doesn't exist.
loadOr ::
Member (Persist a) r =>
Maybe (Path Rel File) ->
a ->
Sem r a
loadOr path a =
fromMaybe a <$> load path
-- |Load a value from the persistence file.
-- Returns 'Nothing' if the file doesn't exist.
loadSingle ::
Member (Persist a) r =>
Sem r (Maybe a)
loadSingle =
load Nothing
-- |Load a value from the persistence file.
-- Returns the fallback value if the file doesn't exist.
loadSingleOr ::
Member (Persist a) r =>
a ->
Sem r a
loadSingleOr a =
fromMaybe a <$> loadSingle
-- |Load a value from the specified file in the persistence directory.
-- Returns 'Nothing' if the file doesn't exist.
loadPath ::
Member (Persist a) r =>
Path Rel File ->
Sem r (Maybe a)
loadPath path =
load (Just path)
-- |Load a value from the specified file in the persistence directory.
-- Returns the fallback value if the file doesn't exist.
loadPathOr ::
Member (Persist a) r =>
Path Rel File ->
a ->
Sem r a
loadPathOr path a =
fromMaybe a <$> loadPath path
| null | https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/ribosome/lib/Ribosome/Effect/Persist.hs | haskell | |Persisting data across vim sessions
|This effect abstracts storing data of type @a@ in the file system to allow loading it when a plugin starts.
Each distinct type corresponds to a separate copy of this effect. When the same type should be stored in separate
files for different components of the plugin, use 'Tagged'.
The subdirectory or file name used for a type is specified to the interpreter.
If the constructor 'store' is called with 'Just' a file name, each value is stored in a separate file, otherwise the
same file is overwritten on every call to 'store'.
codec the data.
directory.
directory.
Returns 'Nothing' if the file doesn't exist.
directory.
directory.
Returns 'Nothing' if the file doesn't exist.
directory.
Returns the fallback value if the file doesn't exist.
|Load a value from the persistence file.
Returns 'Nothing' if the file doesn't exist.
|Load a value from the persistence file.
Returns the fallback value if the file doesn't exist.
|Load a value from the specified file in the persistence directory.
Returns 'Nothing' if the file doesn't exist.
|Load a value from the specified file in the persistence directory.
Returns the fallback value if the file doesn't exist. | module Ribosome.Effect.Persist where
import Path (File, Path, Rel)
The default interpreter delegates file path resolution to the effect ' Ribosome . Persist . PersistPath ' and uses JSON to
data Persist a :: Effect where
|Store a value in the persistence file or , if the first argument is ' Just ' , in that file in the persistence
Store :: Maybe (Path Rel File) -> a -> Persist a m ()
|Load a value from the persistence file or , if the first argument is ' Just ' , from that file in the persistence
Load :: Maybe (Path Rel File) -> Persist a m (Maybe a)
makeSem_ ''Persist
|Store a value in the persistence file or , if the first argument is ' Just ' , in that file in the persistence
store ::
∀ a r .
Member (Persist a) r =>
Maybe (Path Rel File) ->
a ->
Sem r ()
|Load a value from the persistence file or , if the first argument is ' Just ' , from that file in the persistence
load ::
∀ a r .
Member (Persist a) r =>
Maybe (Path Rel File) ->
Sem r (Maybe a)
|Load a value from the persistence file or , if the first argument is ' Just ' , from that file in the persistence
loadOr ::
Member (Persist a) r =>
Maybe (Path Rel File) ->
a ->
Sem r a
loadOr path a =
fromMaybe a <$> load path
loadSingle ::
Member (Persist a) r =>
Sem r (Maybe a)
loadSingle =
load Nothing
loadSingleOr ::
Member (Persist a) r =>
a ->
Sem r a
loadSingleOr a =
fromMaybe a <$> loadSingle
loadPath ::
Member (Persist a) r =>
Path Rel File ->
Sem r (Maybe a)
loadPath path =
load (Just path)
loadPathOr ::
Member (Persist a) r =>
Path Rel File ->
a ->
Sem r a
loadPathOr path a =
fromMaybe a <$> loadPath path
|
42061c95bbc78e2ae6cfa05142d45500bc95956be738d496e19a9571d55fd4b9 | MaskRay/OJHaskell | jabuke.hs | import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Char
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as B
data T x y = T !x !y
parse = do
_ <- readInt
m <- readInt
j <- readInt
xs <- replicateM j readInt
return (m,xs)
where
readInt = state $ fromJust . B.readInt . B.dropWhile isSpace
go m = t . foldl' f (T 1 0)
where
t (T _ s) = s
f (T l s) x
| x < l = T x (s+l-x)
| l+m <= x = T (x-m+1) (s+x-l-m+1)
| otherwise = T l s
main = do
(m,xs) <- evalState parse <$> B.getContents
print $ go m xs
| null | https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Croatian%20Open%20Competition%20in%20Informatics/2011-2012/contest%20%231/jabuke.hs | haskell | import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Char
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as B
data T x y = T !x !y
parse = do
_ <- readInt
m <- readInt
j <- readInt
xs <- replicateM j readInt
return (m,xs)
where
readInt = state $ fromJust . B.readInt . B.dropWhile isSpace
go m = t . foldl' f (T 1 0)
where
t (T _ s) = s
f (T l s) x
| x < l = T x (s+l-x)
| l+m <= x = T (x-m+1) (s+x-l-m+1)
| otherwise = T l s
main = do
(m,xs) <- evalState parse <$> B.getContents
print $ go m xs
| |
857f3e45ce5c347bf7ca36ab4433d238f6d0a16b3687ef72e7be6b4450d1f01c | racket/typed-racket | tc-app-contracts.rkt | #lang racket/unit
;; This module provides custom type-checking rules for the expansion
;; of contracted values
(require "../../utils/utils.rkt"
"signatures.rkt"
"utils.rkt"
syntax/parse
"../signatures.rkt"
(only-in typed-racket/types/type-table add-typeof-expr)
(only-in typed-racket/types/tc-result ret)
(for-template racket/base
;; shift -1 because it's provided +1
racket/contract/private/provide))
(import tc-expr^)
(export tc-app-contracts^)
(define-tc/app-syntax-class (tc/app-contracts expected)
(pattern (ctc-id:id blame e ...)
;; check that this is an application from the contract system
#:when (contract-neg-party-property #'ctc-id)
(check-contract #'ctc-id #'(e ...) expected)))
;; Assume that the contracted thing is of the same type the type
;; environment assigned to the exported identifier. Note that this
;; is only sound if the contract is a chaperone contract, so don't
;; put things in the base type environment if they have impersonator
;; contracts installed.
(define (check-contract orig-value-id other-args expected)
(define ctc-id (contract-rename-id-property orig-value-id))
(define ctc-ty (tc-expr/t ctc-id))
(add-typeof-expr orig-value-id (ret ctc-ty))
(tc-expr/check #`(#%plain-app
#,ctc-id
. #,other-args)
expected))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-lib/typed-racket/typecheck/tc-app/tc-app-contracts.rkt | racket | This module provides custom type-checking rules for the expansion
of contracted values
shift -1 because it's provided +1
check that this is an application from the contract system
Assume that the contracted thing is of the same type the type
environment assigned to the exported identifier. Note that this
is only sound if the contract is a chaperone contract, so don't
put things in the base type environment if they have impersonator
contracts installed. | #lang racket/unit
(require "../../utils/utils.rkt"
"signatures.rkt"
"utils.rkt"
syntax/parse
"../signatures.rkt"
(only-in typed-racket/types/type-table add-typeof-expr)
(only-in typed-racket/types/tc-result ret)
(for-template racket/base
racket/contract/private/provide))
(import tc-expr^)
(export tc-app-contracts^)
(define-tc/app-syntax-class (tc/app-contracts expected)
(pattern (ctc-id:id blame e ...)
#:when (contract-neg-party-property #'ctc-id)
(check-contract #'ctc-id #'(e ...) expected)))
(define (check-contract orig-value-id other-args expected)
(define ctc-id (contract-rename-id-property orig-value-id))
(define ctc-ty (tc-expr/t ctc-id))
(add-typeof-expr orig-value-id (ret ctc-ty))
(tc-expr/check #`(#%plain-app
#,ctc-id
. #,other-args)
expected))
|
f0fe1f3c27c5a34cf4b9ff3d729c7979619a09a5ad8d272d9ae02e6a3963f37c | fmthoma/shell-scripting-with-haskell | my-application-helpful.hs | #!/usr/bin/env stack
-- stack runhaskell --resolver=lts-8.0 --package=optparse-generic
# LANGUAGE DataKinds , DeriveGeneric , OverloadedStrings , TypeOperators #
import Options.Generic
data Command
= Foo
| Bar (Text <?> "Enter text here.")
(Maybe Text <?> "Some more text, if you want")
| Baz { switch :: Bool <?> "Turn it on!"
, volume :: Int <?> "Goes to eleven!" }
deriving (Show, Generic)
instance ParseRecord Command
main = do
command <- getRecord "My Application" :: IO Command
print command
| null | https://raw.githubusercontent.com/fmthoma/shell-scripting-with-haskell/bf7738fbbc806d3a9a072809fe2a91ec5865d8ec/optparse/my-application-helpful.hs | haskell | stack runhaskell --resolver=lts-8.0 --package=optparse-generic | #!/usr/bin/env stack
# LANGUAGE DataKinds , DeriveGeneric , OverloadedStrings , TypeOperators #
import Options.Generic
data Command
= Foo
| Bar (Text <?> "Enter text here.")
(Maybe Text <?> "Some more text, if you want")
| Baz { switch :: Bool <?> "Turn it on!"
, volume :: Int <?> "Goes to eleven!" }
deriving (Show, Generic)
instance ParseRecord Command
main = do
command <- getRecord "My Application" :: IO Command
print command
|
e36b91f01da5cd0486f03c92736957efa70880d0c4885d3f0aae2cb0892a2804 | toothbrush/dotfs | Datatypes.hs | {-# LANGUAGE GADTs, ExistentialQuantification, FlexibleInstances #-}
module System.DotFS.Core.Datatypes where
import Data.Maybe
import Text.ParserCombinators.Parsec.Prim
import Data.Map (lookup, fromList, Map)
import Data.Char (toLower)
import Prelude hiding (lookup)
data Conf = C FilePath deriving Show
-- our threaded parser type
type VarParser a = GenParser Char DFSState a
-- and the results
type VarName = String
type DFSState = Map VarName DFSExpr
type Mountpoint = FilePath
-- | primitives
data Value = VInt Integer
| VBool Bool
| VString String
deriving Eq
instance Show Value where
show (VInt i) = show i
show (VBool b) = map toLower $ show b
show (VString s) = s
-- | a config file is either just a normal file, to be passed
-- through unchanged, or else it's an annotated file with a header
-- and a body.
a proper AST for our config files , in other words .
data Config = Vanilla
| Annotated Header Body
deriving Show
type Header = DFSState
type Body = [BodyElem]
-- | the body is either a conditional block (shown depending on some
-- boolean value) or a literal expression (usually a variable inserted somewhere)
-- or, of course, verbatim content. These components can be chained.
data BodyElem = Cond DFSExpr Body
| Ref DFSExpr
| Verb String
deriving Show
-- | an expression
data DFSExpr = Var VarName
| Prim Value
| Sys String
| If DFSExpr DFSExpr DFSExpr
| UniOp Op DFSExpr
| BiOp Op DFSExpr DFSExpr
deriving Eq
instance Show DFSExpr where
show (Var n) = n
show (Prim v) = show v
show (Sys s) = s
show (If c e1 e2) = "if("++show c++"){"++show e1++"}else{" ++ show e2 ++ "}"
show (UniOp o e) = "(" ++ show o ++ show e ++ ")"
show (BiOp o e1 e2) = "("++show e1++ show o ++ show e2++")"
instance Show Op where
show op = (\o -> " "++o++" ") $
fromMaybe "?" (lookup op (fromList
[ (Add, "+")
, (Sub, "-")
, (Div, "/")
, (Mul, "*")
, (Eq, "==")
, (LTOp, "<")
, (GTOp, ">")
, (LEQ, "<=")
, (GEQ, ">=")
, (NEQ, "!=")
, (And, "&&")
, (Or, "||")
, (Not, "!")
]))
data Op = Add | Sub | Mul | Div
| Eq | LTOp| GTOp| LEQ | GEQ | NEQ
| And | Or | Not
deriving (Eq,Ord)
| null | https://raw.githubusercontent.com/toothbrush/dotfs/36c7e62bda235728ffbb501fe1d2c34210a870a8/System/DotFS/Core/Datatypes.hs | haskell | # LANGUAGE GADTs, ExistentialQuantification, FlexibleInstances #
our threaded parser type
and the results
| primitives
| a config file is either just a normal file, to be passed
through unchanged, or else it's an annotated file with a header
and a body.
| the body is either a conditional block (shown depending on some
boolean value) or a literal expression (usually a variable inserted somewhere)
or, of course, verbatim content. These components can be chained.
| an expression | module System.DotFS.Core.Datatypes where
import Data.Maybe
import Text.ParserCombinators.Parsec.Prim
import Data.Map (lookup, fromList, Map)
import Data.Char (toLower)
import Prelude hiding (lookup)
data Conf = C FilePath deriving Show
type VarParser a = GenParser Char DFSState a
type VarName = String
type DFSState = Map VarName DFSExpr
type Mountpoint = FilePath
data Value = VInt Integer
| VBool Bool
| VString String
deriving Eq
instance Show Value where
show (VInt i) = show i
show (VBool b) = map toLower $ show b
show (VString s) = s
a proper AST for our config files , in other words .
data Config = Vanilla
| Annotated Header Body
deriving Show
type Header = DFSState
type Body = [BodyElem]
data BodyElem = Cond DFSExpr Body
| Ref DFSExpr
| Verb String
deriving Show
data DFSExpr = Var VarName
| Prim Value
| Sys String
| If DFSExpr DFSExpr DFSExpr
| UniOp Op DFSExpr
| BiOp Op DFSExpr DFSExpr
deriving Eq
instance Show DFSExpr where
show (Var n) = n
show (Prim v) = show v
show (Sys s) = s
show (If c e1 e2) = "if("++show c++"){"++show e1++"}else{" ++ show e2 ++ "}"
show (UniOp o e) = "(" ++ show o ++ show e ++ ")"
show (BiOp o e1 e2) = "("++show e1++ show o ++ show e2++")"
instance Show Op where
show op = (\o -> " "++o++" ") $
fromMaybe "?" (lookup op (fromList
[ (Add, "+")
, (Sub, "-")
, (Div, "/")
, (Mul, "*")
, (Eq, "==")
, (LTOp, "<")
, (GTOp, ">")
, (LEQ, "<=")
, (GEQ, ">=")
, (NEQ, "!=")
, (And, "&&")
, (Or, "||")
, (Not, "!")
]))
data Op = Add | Sub | Mul | Div
| Eq | LTOp| GTOp| LEQ | GEQ | NEQ
| And | Or | Not
deriving (Eq,Ord)
|
c52ea727d7e48f4db71a3325e205a8ed6803509fd724b176b6ec416ac68df014 | pfdietz/ansi-test | loop12.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Nov 17 08:47:43 2002
Contains : Tests for ALWAYS , NEVER , THEREIS
;;; Tests of ALWAYS clauses
(deftest loop.12.1
(loop for i in '(1 2 3 4) always (< i 10))
t)
(deftest loop.12.2
(loop for i in nil always nil)
t)
(deftest loop.12.3
(loop for i in '(a) always nil)
nil)
(deftest loop.12.4
(loop for i in '(1 2 3 4 5 6 7)
always t
until (> i 5))
t)
(deftest loop.12.5
(loop for i in '(1 2 3 4 5 6 7)
always (< i 6)
until (>= i 5))
t)
(deftest loop.12.6
(loop for x in '(a b c d e) always x)
t)
(deftest loop.12.7
(loop for x in '(1 2 3 4 5 6)
always (< x 20)
never (> x 10))
t)
(deftest loop.12.8
(loop for x in '(1 2 3 4 5 6)
always (< x 20)
never (> x 5))
nil)
(deftest loop.12.9
(loop for x in '(1 2 3 4 5 6)
never (> x 5)
always (< x 20))
nil)
(deftest loop.12.10
(loop for x in '(1 2 3 4 5)
always (< x 10)
finally (return 'good))
good)
(deftest loop.12.11
(loop for x in '(1 2 3 4 5)
always (< x 3)
finally (return 'bad))
nil)
(deftest loop.12.12
(loop for x in '(1 2 3 4 5 6)
always t
when (= x 4) do (loop-finish))
t)
(deftest loop.12.13
(loop for x in '(1 2 3 4 5 6)
do (loop-finish)
always nil)
t)
;;; Tests of NEVER
(deftest loop.12.21
(loop for i in '(1 2 3 4) never (> i 10))
t)
(deftest loop.12.22
(loop for i in nil never t)
t)
(deftest loop.12.23
(loop for i in '(a) never t)
nil)
(deftest loop.12.24
(loop for i in '(1 2 3 4 5 6 7)
never nil
until (> i 5))
t)
(deftest loop.12.25
(loop for i in '(1 2 3 4 5 6 7)
never (>= i 6)
until (>= i 5))
t)
(deftest loop.12.26
(loop for x in '(a b c d e) never (not x))
t)
(deftest loop.12.30
(loop for x in '(1 2 3 4 5)
never (>= x 10)
finally (return 'good))
good)
(deftest loop.12.31
(loop for x in '(1 2 3 4 5)
never (>= x 3)
finally (return 'bad))
nil)
(deftest loop.12.32
(loop for x in '(1 2 3 4 5 6)
never nil
when (= x 4) do (loop-finish))
t)
(deftest loop.12.33
(loop for x in '(1 2 3 4 5 6)
do (loop-finish)
never t)
t)
;;; Tests of THEREIS
(deftest loop.12.41
(loop for x in '(1 2 3 4 5)
thereis (and (eqlt x 3) 'good))
good)
(deftest loop.12.42
(loop for x in '(nil nil a nil nil)
thereis x)
a)
(deftest loop.12.43
(loop for x in '(1 2 3 4 5)
thereis (eql x 4)
when (eql x 2) do (loop-finish))
nil)
;;; Error cases
(deftest loop.12.error.50
(signals-error
(loop for i from 1 to 10
collect i
always (< i 20))
program-error)
t)
(deftest loop.12.error.50a
(signals-error
(loop for i from 1 to 10
always (< i 20)
collect i)
program-error)
t)
(deftest loop.12.error.51
(signals-error
(loop for i from 1 to 10
collect i
never (> i 20))
program-error)
t)
(deftest loop.12.error.51a
(signals-error
(loop for i from 1 to 10
never (> i 20)
collect i)
program-error)
t)
(deftest loop.12.error.52
(signals-error
(loop for i from 1 to 10
collect i
thereis (> i 20))
program-error)
t)
(deftest loop.12.error.52a
(signals-error
(loop for i from 1 to 10
thereis (> i 20)
collect i)
program-error)
t)
;;; Non-error cases
(deftest loop.12.53
(loop for i from 1 to 10
collect i into foo
always (< i 20))
t)
(deftest loop.12.53a
(loop for i from 1 to 10
always (< i 20)
collect i into foo)
t)
(deftest loop.12.54
(loop for i from 1 to 10
collect i into foo
never (> i 20))
t)
(deftest loop.12.54a
(loop for i from 1 to 10
never (> i 20)
collect i into foo)
t)
(deftest loop.12.55
(loop for i from 1 to 10
collect i into foo
thereis i)
1)
(deftest loop.12.55a
(loop for i from 1 to 10
thereis i
collect i into foo)
1)
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest loop.12.56
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) always (expand-in-current-env (%m (< i 10)))))
t)
(deftest loop.12.57
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) always (expand-in-current-env (%m t))))
t)
(deftest loop.12.58
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) never (expand-in-current-env (%m (>= i 10)))))
t)
(deftest loop.12.59
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) never (expand-in-current-env (%m t))))
nil)
(deftest loop.12.60
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4)
thereis (expand-in-current-env (%m (and (>= i 2) (+ i 1))))))
3)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/iteration/loop12.lsp | lisp | -*- Mode: Lisp -*-
Tests of ALWAYS clauses
Tests of NEVER
Tests of THEREIS
Error cases
Non-error cases
Test that explicit calls to macroexpand in subforms
are done in the correct environment | Author :
Created : Sun Nov 17 08:47:43 2002
Contains : Tests for ALWAYS , NEVER , THEREIS
(deftest loop.12.1
(loop for i in '(1 2 3 4) always (< i 10))
t)
(deftest loop.12.2
(loop for i in nil always nil)
t)
(deftest loop.12.3
(loop for i in '(a) always nil)
nil)
(deftest loop.12.4
(loop for i in '(1 2 3 4 5 6 7)
always t
until (> i 5))
t)
(deftest loop.12.5
(loop for i in '(1 2 3 4 5 6 7)
always (< i 6)
until (>= i 5))
t)
(deftest loop.12.6
(loop for x in '(a b c d e) always x)
t)
(deftest loop.12.7
(loop for x in '(1 2 3 4 5 6)
always (< x 20)
never (> x 10))
t)
(deftest loop.12.8
(loop for x in '(1 2 3 4 5 6)
always (< x 20)
never (> x 5))
nil)
(deftest loop.12.9
(loop for x in '(1 2 3 4 5 6)
never (> x 5)
always (< x 20))
nil)
(deftest loop.12.10
(loop for x in '(1 2 3 4 5)
always (< x 10)
finally (return 'good))
good)
(deftest loop.12.11
(loop for x in '(1 2 3 4 5)
always (< x 3)
finally (return 'bad))
nil)
(deftest loop.12.12
(loop for x in '(1 2 3 4 5 6)
always t
when (= x 4) do (loop-finish))
t)
(deftest loop.12.13
(loop for x in '(1 2 3 4 5 6)
do (loop-finish)
always nil)
t)
(deftest loop.12.21
(loop for i in '(1 2 3 4) never (> i 10))
t)
(deftest loop.12.22
(loop for i in nil never t)
t)
(deftest loop.12.23
(loop for i in '(a) never t)
nil)
(deftest loop.12.24
(loop for i in '(1 2 3 4 5 6 7)
never nil
until (> i 5))
t)
(deftest loop.12.25
(loop for i in '(1 2 3 4 5 6 7)
never (>= i 6)
until (>= i 5))
t)
(deftest loop.12.26
(loop for x in '(a b c d e) never (not x))
t)
(deftest loop.12.30
(loop for x in '(1 2 3 4 5)
never (>= x 10)
finally (return 'good))
good)
(deftest loop.12.31
(loop for x in '(1 2 3 4 5)
never (>= x 3)
finally (return 'bad))
nil)
(deftest loop.12.32
(loop for x in '(1 2 3 4 5 6)
never nil
when (= x 4) do (loop-finish))
t)
(deftest loop.12.33
(loop for x in '(1 2 3 4 5 6)
do (loop-finish)
never t)
t)
(deftest loop.12.41
(loop for x in '(1 2 3 4 5)
thereis (and (eqlt x 3) 'good))
good)
(deftest loop.12.42
(loop for x in '(nil nil a nil nil)
thereis x)
a)
(deftest loop.12.43
(loop for x in '(1 2 3 4 5)
thereis (eql x 4)
when (eql x 2) do (loop-finish))
nil)
(deftest loop.12.error.50
(signals-error
(loop for i from 1 to 10
collect i
always (< i 20))
program-error)
t)
(deftest loop.12.error.50a
(signals-error
(loop for i from 1 to 10
always (< i 20)
collect i)
program-error)
t)
(deftest loop.12.error.51
(signals-error
(loop for i from 1 to 10
collect i
never (> i 20))
program-error)
t)
(deftest loop.12.error.51a
(signals-error
(loop for i from 1 to 10
never (> i 20)
collect i)
program-error)
t)
(deftest loop.12.error.52
(signals-error
(loop for i from 1 to 10
collect i
thereis (> i 20))
program-error)
t)
(deftest loop.12.error.52a
(signals-error
(loop for i from 1 to 10
thereis (> i 20)
collect i)
program-error)
t)
(deftest loop.12.53
(loop for i from 1 to 10
collect i into foo
always (< i 20))
t)
(deftest loop.12.53a
(loop for i from 1 to 10
always (< i 20)
collect i into foo)
t)
(deftest loop.12.54
(loop for i from 1 to 10
collect i into foo
never (> i 20))
t)
(deftest loop.12.54a
(loop for i from 1 to 10
never (> i 20)
collect i into foo)
t)
(deftest loop.12.55
(loop for i from 1 to 10
collect i into foo
thereis i)
1)
(deftest loop.12.55a
(loop for i from 1 to 10
thereis i
collect i into foo)
1)
(deftest loop.12.56
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) always (expand-in-current-env (%m (< i 10)))))
t)
(deftest loop.12.57
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) always (expand-in-current-env (%m t))))
t)
(deftest loop.12.58
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) never (expand-in-current-env (%m (>= i 10)))))
t)
(deftest loop.12.59
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4) never (expand-in-current-env (%m t))))
nil)
(deftest loop.12.60
(macrolet
((%m (z) z))
(loop for i in '(1 2 3 4)
thereis (expand-in-current-env (%m (and (>= i 2) (+ i 1))))))
3)
|
6ece7e215050036d6eb0c878ecb01e4c97b951994641bd4bf518002d2d24c893 | footprintanalytics/footprint-web | on_demand_test.clj | (ns metabase.models.on-demand-test
"Tests for On-Demand FieldValues updating behavior for Cards and Dashboards."
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :as dashboard :refer [Dashboard]]
[metabase.models.database :refer [Database]]
[metabase.models.field :as field :refer [Field]]
[metabase.models.field-values :as field-values]
[metabase.models.table :refer [Table]]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]))
(defn- do-with-mocked-field-values-updating
"Run F the function responsible for updating FieldValues bound to a mock function that instead just records the names
of Fields that should have been updated. Returns the set of updated Field names."
{:style/indent 0}
[f]
(let [updated-field-names (atom #{})]
(with-redefs [field-values/create-or-update-full-field-values! (fn [field]
(swap! updated-field-names conj (:name field)))]
(f updated-field-names)
@updated-field-names)))
(defn- basic-native-query []
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS"}})
(defn- native-query-with-template-tag [field-or-id]
{:database (field/field-id->database-id (u/the-id field-or-id))
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS nWHERE {{category}}"
:template-tags {:category {:name "category"
:display-name "Category"
:type "dimension"
:dimension [:field (u/the-id field-or-id) nil]
:widget-type "category"
:default "Widget"}}}})
(defn- do-with-updated-fields-for-card {:style/indent 1} [options & [f]]
(mt/with-temp* [Database [db (:db options)]
Table [table (merge {:db_id (u/the-id db)}
(:table options))]
Field [field (merge {:table_id (u/the-id table), :has_field_values "list"}
(:field options))]]
(do-with-mocked-field-values-updating
(fn [updated-field-names]
(mt/with-temp Card [card (merge {:dataset_query (native-query-with-template-tag field)}
(:card options))]
(when f
(f {:db db, :table table, :field field, :card card, :updated-field-names updated-field-names})))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | CARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- field-values-were-updated-for-new-card? [options]
(boolean (seq (do-with-updated-fields-for-card options))))
(deftest newly-created-card-test
(testing "Newly created Card with param referencing Field"
(testing "in On-Demand DB should get updated FieldValues"
(is (= true
(field-values-were-updated-for-new-card? {:db {:is_on_demand true}}))))
(testing "in non-On-Demand DB should *not* get updated FieldValues"
(is (= false
(field-values-were-updated-for-new-card? {:db {:is_on_demand false}}))))))
(deftest existing-card-test
(testing "Existing Card"
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
create Parameterized Card with field in On - Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
now update the Card ... since param did n't change at all FieldValues
;; should not be updated
(db/update! Card (u/the-id card) card))))))
(testing "with changed param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create parameterized Card with Field in On-Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [table card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
now Change the Field that is referenced by the Card 's SQL param
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand true}
:card {:dataset_query (basic-native-query)}
:field {:name "New Field"}}
(fn [{:keys [field card]}]
now change the query to one that references our Field in a
on - demand DB . Field should have updated values
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
create a parameterized Card with a Field that belongs to a non - on - demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [card]}]
update the Card . Field should get updated values
(db/update! Card (u/the-id card) card))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand false}
:card {:dataset_query (basic-native-query)}}
(fn [{:keys [field card]}]
now change the query to one that references a Field . Field should
not get values since DB is not On - Demand
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
create a parameterized Card with a Field that belongs to a non - on - demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [table card]}]
change the query to one referencing a different Field . Field should
not get values since DB is not On - Demand
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DASHBOARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- basic-mbql-query []
{:database (data/id)
:type :query
:query {:source-table (data/id :venues)
:aggregation [[:count]]}})
(defn- parameter-mappings-for-card-and-field [card-or-id field-or-id]
[{:card_id (u/the-id card-or-id)
:target [:dimension [:field (u/the-id field-or-id) nil]]}])
(defn- add-dashcard-with-parameter-mapping! [dashboard-or-id card-or-id field-or-id]
(dashboard/add-dashcard! dashboard-or-id card-or-id
{:parameter_mappings (parameter-mappings-for-card-and-field card-or-id field-or-id)}))
(defn- do-with-updated-fields-for-dashboard {:style/indent 1} [options & [f]]
(do-with-updated-fields-for-card (merge {:card {:dataset_query (basic-mbql-query)}}
options)
(fn [objects]
(mt/with-temp Dashboard [dash]
(let [dashcard (add-dashcard-with-parameter-mapping! dash (:card objects) (:field objects))]
(when f
(f (assoc objects
:dash dash
:dashcard dashcard))))))))
(deftest existing-dashboard-test
(testing "Existing Dashboard"
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"My Cool Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}
:field {:name "My Cool Field"}}))))
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [field card dash updated-field-names]}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
ok , now add a new Card with a param that references the same field
The field should n't get new values because the set of referenced did n't change
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [table card dash dashcard updated-field-names]}]
create a Dashboard and add a DashboardCard with a param mapping
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:name "New Field"
:has_field_values "list"}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
ok , now update the parameter mapping to the new field . The new Field should get new values
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [field card dash]}]
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [table card dash dashcard]}]
(mt/with-temp Field [new-field {:table_id (u/the-id table), :has_field_values "list"}]
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/models/on_demand_test.clj | clojure | +----------------------------------------------------------------------------------------------------------------+
| CARDS |
+----------------------------------------------------------------------------------------------------------------+
clear out the list of updated field names
should not be updated
create parameterized Card with Field in On-Demand DB
clear out the list of updated field names
create a Card with non-parameterized query
create a Card with non-parameterized query
+----------------------------------------------------------------------------------------------------------------+
| DASHBOARDS |
+----------------------------------------------------------------------------------------------------------------+
Create a On-Demand DB and MBQL Card
Create a On-Demand DB and MBQL Card
clear out the list of updated Field Names
Create a On-Demand DB and MBQL Card
clear out the list of updated Field Names | (ns metabase.models.on-demand-test
"Tests for On-Demand FieldValues updating behavior for Cards and Dashboards."
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :as dashboard :refer [Dashboard]]
[metabase.models.database :refer [Database]]
[metabase.models.field :as field :refer [Field]]
[metabase.models.field-values :as field-values]
[metabase.models.table :refer [Table]]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]))
(defn- do-with-mocked-field-values-updating
"Run F the function responsible for updating FieldValues bound to a mock function that instead just records the names
of Fields that should have been updated. Returns the set of updated Field names."
{:style/indent 0}
[f]
(let [updated-field-names (atom #{})]
(with-redefs [field-values/create-or-update-full-field-values! (fn [field]
(swap! updated-field-names conj (:name field)))]
(f updated-field-names)
@updated-field-names)))
(defn- basic-native-query []
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS"}})
(defn- native-query-with-template-tag [field-or-id]
{:database (field/field-id->database-id (u/the-id field-or-id))
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS nWHERE {{category}}"
:template-tags {:category {:name "category"
:display-name "Category"
:type "dimension"
:dimension [:field (u/the-id field-or-id) nil]
:widget-type "category"
:default "Widget"}}}})
(defn- do-with-updated-fields-for-card {:style/indent 1} [options & [f]]
(mt/with-temp* [Database [db (:db options)]
Table [table (merge {:db_id (u/the-id db)}
(:table options))]
Field [field (merge {:table_id (u/the-id table), :has_field_values "list"}
(:field options))]]
(do-with-mocked-field-values-updating
(fn [updated-field-names]
(mt/with-temp Card [card (merge {:dataset_query (native-query-with-template-tag field)}
(:card options))]
(when f
(f {:db db, :table table, :field field, :card card, :updated-field-names updated-field-names})))))))
(defn- field-values-were-updated-for-new-card? [options]
(boolean (seq (do-with-updated-fields-for-card options))))
(deftest newly-created-card-test
(testing "Newly created Card with param referencing Field"
(testing "in On-Demand DB should get updated FieldValues"
(is (= true
(field-values-were-updated-for-new-card? {:db {:is_on_demand true}}))))
(testing "in non-On-Demand DB should *not* get updated FieldValues"
(is (= false
(field-values-were-updated-for-new-card? {:db {:is_on_demand false}}))))))
(deftest existing-card-test
(testing "Existing Card"
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
create Parameterized Card with field in On - Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [card updated-field-names]}]
(reset! updated-field-names #{})
now update the Card ... since param did n't change at all FieldValues
(db/update! Card (u/the-id card) card))))))
(testing "with changed param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [table card updated-field-names]}]
(reset! updated-field-names #{})
now Change the Field that is referenced by the Card 's SQL param
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
(do-with-updated-fields-for-card
{:db {:is_on_demand true}
:card {:dataset_query (basic-native-query)}
:field {:name "New Field"}}
(fn [{:keys [field card]}]
now change the query to one that references our Field in a
on - demand DB . Field should have updated values
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
create a parameterized Card with a Field that belongs to a non - on - demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [card]}]
update the Card . Field should get updated values
(db/update! Card (u/the-id card) card))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-card
{:db {:is_on_demand false}
:card {:dataset_query (basic-native-query)}}
(fn [{:keys [field card]}]
now change the query to one that references a Field . Field should
not get values since DB is not On - Demand
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
create a parameterized Card with a Field that belongs to a non - on - demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [table card]}]
change the query to one referencing a different Field . Field should
not get values since DB is not On - Demand
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))))
(defn- basic-mbql-query []
{:database (data/id)
:type :query
:query {:source-table (data/id :venues)
:aggregation [[:count]]}})
(defn- parameter-mappings-for-card-and-field [card-or-id field-or-id]
[{:card_id (u/the-id card-or-id)
:target [:dimension [:field (u/the-id field-or-id) nil]]}])
(defn- add-dashcard-with-parameter-mapping! [dashboard-or-id card-or-id field-or-id]
(dashboard/add-dashcard! dashboard-or-id card-or-id
{:parameter_mappings (parameter-mappings-for-card-and-field card-or-id field-or-id)}))
(defn- do-with-updated-fields-for-dashboard {:style/indent 1} [options & [f]]
(do-with-updated-fields-for-card (merge {:card {:dataset_query (basic-mbql-query)}}
options)
(fn [objects]
(mt/with-temp Dashboard [dash]
(let [dashcard (add-dashcard-with-parameter-mapping! dash (:card objects) (:field objects))]
(when f
(f (assoc objects
:dash dash
:dashcard dashcard))))))))
(deftest existing-dashboard-test
(testing "Existing Dashboard"
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"My Cool Field"}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}
:field {:name "My Cool Field"}}))))
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [field card dash updated-field-names]}]
(reset! updated-field-names #{})
ok , now add a new Card with a param that references the same field
The field should n't get new values because the set of referenced did n't change
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [table card dash dashcard updated-field-names]}]
create a Dashboard and add a DashboardCard with a param mapping
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:name "New Field"
:has_field_values "list"}]
(reset! updated-field-names #{})
ok , now update the parameter mapping to the new field . The new Field should get new values
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [field card dash]}]
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [table card dash dashcard]}]
(mt/with-temp Field [new-field {:table_id (u/the-id table), :has_field_values "list"}]
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))))
|
0e4a13d8a975b0b17df08665a5f287c69d92147b4b67744765f7cc3220d43af3 | ilevd/compile-time | core.clj | (ns compile-time.core)
(defmacro run
"Pass body to evaluate it at compile time.
All forms will be evaluated and the result of evaluating the last form will be returned."
[& forms]
(run! eval (butlast forms))
(eval (last forms)))
(defmacro run-fn
"Pass function and args to evaluate it at compile time."
[f & args]
(if (symbol? f)
(apply (resolve f) args)
(apply (eval f) args)))
| null | https://raw.githubusercontent.com/ilevd/compile-time/b63f30ab00a667fd4aee21af49335f0b12e89a85/src/compile_time/core.clj | clojure | (ns compile-time.core)
(defmacro run
"Pass body to evaluate it at compile time.
All forms will be evaluated and the result of evaluating the last form will be returned."
[& forms]
(run! eval (butlast forms))
(eval (last forms)))
(defmacro run-fn
"Pass function and args to evaluate it at compile time."
[f & args]
(if (symbol? f)
(apply (resolve f) args)
(apply (eval f) args)))
| |
8278ec8fd6f907f956b247c586ac5e8bed854e2ed2b677fd9dc620c79a686de0 | RichiH/git-annex | LockPool.hs | Wraps Utility . LockPool , making pid locks be used when git - annex is so
- configured .
-
- Copyright 2015 < >
-
- Licensed under the GNU GPL version 3 or higher .
- configured.
-
- Copyright 2015 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE CPP #
module Annex.LockPool (module X) where
#ifndef mingw32_HOST_OS
import Annex.LockPool.PosixOrPid as X
#else
import Utility.LockPool.Windows as X
#endif
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Annex/LockPool.hs | haskell | Wraps Utility . LockPool , making pid locks be used when git - annex is so
- configured .
-
- Copyright 2015 < >
-
- Licensed under the GNU GPL version 3 or higher .
- configured.
-
- Copyright 2015 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
# LANGUAGE CPP #
module Annex.LockPool (module X) where
#ifndef mingw32_HOST_OS
import Annex.LockPool.PosixOrPid as X
#else
import Utility.LockPool.Windows as X
#endif
| |
59b55f920b0f281f33684d9c279688ed9a8af8b93018b256daecbaa836e58a5f | stschiff/sequenceTools | smartpca_wrapper.hs | #!/usr/bin/env stack
-- stack script --resolver lts-14.1 --package turtle
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative (optional)
import Prelude hiding (FilePath)
import Turtle
data Options = Options {
optGeno :: FilePath,
optSnp :: FilePath,
optInd :: FilePath,
optOutPrefix :: FilePath,
optLSQproject :: Bool,
optPopList :: Maybe FilePath
}
main = do
args <- options "Eigensoft smartpca wrapper" parser
runManaged $ do
paramFile <- mktempfile "." "smartpca_wrapper"
let content = [(format ("genotypename:\t"%fp) (optGeno args)),
(format ("snpname:\t"%fp) (optSnp args)),
(format ("indivname:\t"%fp) (optInd args)),
(format ("evecoutname:\t"%fp%".evec.txt") (optOutPrefix args)),
(format ("evaloutname:\t"%fp%".eval.txt") (optOutPrefix args))]
lsqProjectLine = if (optLSQproject args) then return "lsqproject:\tYES" else empty
popListLine = case optPopList args of
Just popList -> return . unsafeTextToLine $ format ("poplistname:\t"%fp) popList
Nothing -> empty
output paramFile $ select (map unsafeTextToLine content) <|> lsqProjectLine <|> popListLine
ec <- proc "smartpca" ["-p", format fp paramFile] empty
case ec of
ExitSuccess -> return ()
ExitFailure n -> err . unsafeTextToLine $ format ("mergeit failed with exit code "%d) n
parser :: Parser Options
parser = Options <$> optPath "geno" 'g' "Genotype File"
<*> optPath "snp" 's' "Snp File"
<*> optPath "ind" 'i' "Ind File"
<*> optPath "outPrefix" 'o' "Output prefix for *.evec.txt and *.eval.txt output \
\files"
<*> switch "lsqProject" 'l' "set lsqproject option to YES"
<*> optional (optPath "popList" 'p' "give poplist file to restrict PCA to \
\populations listed.")
| null | https://raw.githubusercontent.com/stschiff/sequenceTools/7bdebf13937d8f6dff7da8b67091d57b6d4c47c4/scripts/smartpca_wrapper.hs | haskell | stack script --resolver lts-14.1 --package turtle
# LANGUAGE OverloadedStrings # | #!/usr/bin/env stack
import Control.Applicative (optional)
import Prelude hiding (FilePath)
import Turtle
data Options = Options {
optGeno :: FilePath,
optSnp :: FilePath,
optInd :: FilePath,
optOutPrefix :: FilePath,
optLSQproject :: Bool,
optPopList :: Maybe FilePath
}
main = do
args <- options "Eigensoft smartpca wrapper" parser
runManaged $ do
paramFile <- mktempfile "." "smartpca_wrapper"
let content = [(format ("genotypename:\t"%fp) (optGeno args)),
(format ("snpname:\t"%fp) (optSnp args)),
(format ("indivname:\t"%fp) (optInd args)),
(format ("evecoutname:\t"%fp%".evec.txt") (optOutPrefix args)),
(format ("evaloutname:\t"%fp%".eval.txt") (optOutPrefix args))]
lsqProjectLine = if (optLSQproject args) then return "lsqproject:\tYES" else empty
popListLine = case optPopList args of
Just popList -> return . unsafeTextToLine $ format ("poplistname:\t"%fp) popList
Nothing -> empty
output paramFile $ select (map unsafeTextToLine content) <|> lsqProjectLine <|> popListLine
ec <- proc "smartpca" ["-p", format fp paramFile] empty
case ec of
ExitSuccess -> return ()
ExitFailure n -> err . unsafeTextToLine $ format ("mergeit failed with exit code "%d) n
parser :: Parser Options
parser = Options <$> optPath "geno" 'g' "Genotype File"
<*> optPath "snp" 's' "Snp File"
<*> optPath "ind" 'i' "Ind File"
<*> optPath "outPrefix" 'o' "Output prefix for *.evec.txt and *.eval.txt output \
\files"
<*> switch "lsqProject" 'l' "set lsqproject option to YES"
<*> optional (optPath "popList" 'p' "give poplist file to restrict PCA to \
\populations listed.")
|
13050f31a2f3ad027bcc436b3283ae00f2e33e6c36fd1cd5c84090c40527227c | yzh44yzh/practical_erlang | list_zipper.erl | -module(list_zipper).
-export([from_list/1, to_list/1,
left/1, left/2,
right/1, right/2,
get/1, set/2, position/1,
find/2, find_left/2, find_right/2
]).
-type lz() :: {[any()], any(), [any()], pos_integer()}.
-export_type([lz/0]).
%%% Module API
-spec from_list(list()) -> lz().
from_list([H | T]) ->
{[], H, T, 1}.
-spec to_list(lz()) -> list().
to_list({Left, Current, Right, _}) ->
lists:reverse(Left) ++ [Current | Right].
-spec left(lz()) -> {ok, lz()} | {error, no_move}.
left({[], _, _, _}) -> {error, no_move};
left({[H | Left], Current, Right, Position}) ->
{ok, {Left, H, [Current | Right], Position - 1}}.
-spec left(lz(), pos_integer()) -> {ok, lz()} | {error, no_move}.
left(Zipper, 0) -> {ok, Zipper};
left(Zipper, Steps) when Steps > 0 ->
case left(Zipper) of
{ok, Zipper2} -> left(Zipper2, Steps - 1);
Error -> Error
end.
-spec right(lz()) -> {ok, lz()} | {error, no_move}.
right({_, _, [], _}) -> {error, no_move};
right({Left, Current, [H | Right], Position}) ->
{ok, {[Current | Left], H, Right, Position + 1}}.
-spec right(lz(), pos_integer()) -> {ok, lz()} | {error, no_move}.
right(Zipper, 0) -> {ok, Zipper};
right(Zipper, Steps) when Steps > 0 ->
case right(Zipper) of
{ok, Zipper2} -> right(Zipper2, Steps - 1);
Error -> Error
end.
-spec get(lz()) -> any().
get({_, Current, _, _}) -> Current.
-spec set(lz(), any()) -> any().
set({Left, _, Right, Position}, Value) ->
{Left, Value, Right, Position}.
-spec position(lz()) -> pos_integer().
position({_, _, _, Position}) -> Position.
-spec find(lz(), any()) -> {ok, lz()} | {error, not_found}.
find(Zipper, Value) ->
{ok, Begin} = left(Zipper, position(Zipper) - 1),
case list_zipper:get(Begin) of
Value -> {ok, Begin};
_ -> find_right(Begin, Value)
end.
-spec find_right(lz(), any()) -> {ok, lz()} | {error, not_found}.
find_right(Zipper, Value) ->
find_direction(Zipper, Value, right).
-spec find_left(lz(), any()) -> {ok, lz()} | {error, not_found}.
find_left(Zipper, Value) ->
find_direction(Zipper, Value, left).
%%% Inner Functions
-spec find_direction(lz(), any(), left | right) -> {ok, lz()} | {error, not_found}.
find_direction(Zipper, Value, Direction) ->
case list_zipper:Direction(Zipper) of
{ok, Zipper2} ->
case list_zipper:get(Zipper2) of
Value -> {ok, Zipper2};
_ -> find_direction(Zipper2, Value, Direction)
end;
{error, no_move} -> {error, not_found}
end.
| null | https://raw.githubusercontent.com/yzh44yzh/practical_erlang/c9eec8cf44e152bf50d9bc6d5cb87fee4764f609/final_exercise/src/list_zipper.erl | erlang | Module API
Inner Functions | -module(list_zipper).
-export([from_list/1, to_list/1,
left/1, left/2,
right/1, right/2,
get/1, set/2, position/1,
find/2, find_left/2, find_right/2
]).
-type lz() :: {[any()], any(), [any()], pos_integer()}.
-export_type([lz/0]).
-spec from_list(list()) -> lz().
from_list([H | T]) ->
{[], H, T, 1}.
-spec to_list(lz()) -> list().
to_list({Left, Current, Right, _}) ->
lists:reverse(Left) ++ [Current | Right].
-spec left(lz()) -> {ok, lz()} | {error, no_move}.
left({[], _, _, _}) -> {error, no_move};
left({[H | Left], Current, Right, Position}) ->
{ok, {Left, H, [Current | Right], Position - 1}}.
-spec left(lz(), pos_integer()) -> {ok, lz()} | {error, no_move}.
left(Zipper, 0) -> {ok, Zipper};
left(Zipper, Steps) when Steps > 0 ->
case left(Zipper) of
{ok, Zipper2} -> left(Zipper2, Steps - 1);
Error -> Error
end.
-spec right(lz()) -> {ok, lz()} | {error, no_move}.
right({_, _, [], _}) -> {error, no_move};
right({Left, Current, [H | Right], Position}) ->
{ok, {[Current | Left], H, Right, Position + 1}}.
-spec right(lz(), pos_integer()) -> {ok, lz()} | {error, no_move}.
right(Zipper, 0) -> {ok, Zipper};
right(Zipper, Steps) when Steps > 0 ->
case right(Zipper) of
{ok, Zipper2} -> right(Zipper2, Steps - 1);
Error -> Error
end.
-spec get(lz()) -> any().
get({_, Current, _, _}) -> Current.
-spec set(lz(), any()) -> any().
set({Left, _, Right, Position}, Value) ->
{Left, Value, Right, Position}.
-spec position(lz()) -> pos_integer().
position({_, _, _, Position}) -> Position.
-spec find(lz(), any()) -> {ok, lz()} | {error, not_found}.
find(Zipper, Value) ->
{ok, Begin} = left(Zipper, position(Zipper) - 1),
case list_zipper:get(Begin) of
Value -> {ok, Begin};
_ -> find_right(Begin, Value)
end.
-spec find_right(lz(), any()) -> {ok, lz()} | {error, not_found}.
find_right(Zipper, Value) ->
find_direction(Zipper, Value, right).
-spec find_left(lz(), any()) -> {ok, lz()} | {error, not_found}.
find_left(Zipper, Value) ->
find_direction(Zipper, Value, left).
-spec find_direction(lz(), any(), left | right) -> {ok, lz()} | {error, not_found}.
find_direction(Zipper, Value, Direction) ->
case list_zipper:Direction(Zipper) of
{ok, Zipper2} ->
case list_zipper:get(Zipper2) of
Value -> {ok, Zipper2};
_ -> find_direction(Zipper2, Value, Direction)
end;
{error, no_move} -> {error, not_found}
end.
|
a24c70bbf047b75816230556384027e833eac72218317add6b4d6f5e8cdabf8f | myaosato/clcm | thematic-break.lisp | (defpackage :clcm/nodes/thematic-break
(:use :cl
:clcm/line
:clcm/node)
(:import-from :cl-ppcre
:scan)
(:export :thematic-break-node
:is-thematic-break-line
:attach-thematic-break!?))
(in-package :clcm/nodes/thematic-break)
;;
(defclass thematic-break-node (node)
())
;; close not use
;;(defmethod close!? ((node thematic-break-node) line offset) nil)
;; add not use
;;(defmethod add!? ((node thematic-break-node) line offset) nil)
;; ->html
(defmethod ->html ((node thematic-break-node))
(format nil "<hr />~%"))
;;
(defun is-thematic-break-line (line offset)
(multiple-value-bind (indent contents) (get-indented-depth-and-line line offset)
(and (<= indent 3)
(or (scan "^(?:\\*\\s*){3,}$" contents :start indent)
(scan "^(?:_\\s*){3,}$" contents :start indent)
(scan "^(?:-\\s*){3,}$" contents :start indent)))))
(defun attach-thematic-break!? (node line offset)
(when (is-thematic-break-line line offset)
(let ((child (make-instance 'thematic-break-node :is-open nil)))
(add-child node child)
child)))
| null | https://raw.githubusercontent.com/myaosato/clcm/fd0390bedf00c5be3f5c2eb8176ff73bede797b0/src/nodes/thematic-break.lisp | lisp |
close not use
(defmethod close!? ((node thematic-break-node) line offset) nil)
add not use
(defmethod add!? ((node thematic-break-node) line offset) nil)
->html
| (defpackage :clcm/nodes/thematic-break
(:use :cl
:clcm/line
:clcm/node)
(:import-from :cl-ppcre
:scan)
(:export :thematic-break-node
:is-thematic-break-line
:attach-thematic-break!?))
(in-package :clcm/nodes/thematic-break)
(defclass thematic-break-node (node)
())
(defmethod ->html ((node thematic-break-node))
(format nil "<hr />~%"))
(defun is-thematic-break-line (line offset)
(multiple-value-bind (indent contents) (get-indented-depth-and-line line offset)
(and (<= indent 3)
(or (scan "^(?:\\*\\s*){3,}$" contents :start indent)
(scan "^(?:_\\s*){3,}$" contents :start indent)
(scan "^(?:-\\s*){3,}$" contents :start indent)))))
(defun attach-thematic-break!? (node line offset)
(when (is-thematic-break-line line offset)
(let ((child (make-instance 'thematic-break-node :is-open nil)))
(add-child node child)
child)))
|
224009bb68d866be98bceb9f389dfca13a39f76426e51d01940170ee194c7f12 | haskell/haskell-language-server | Main.hs | Copyright ( c ) 2019 The DAML Authors . All rights reserved .
SPDX - License - Identifier : Apache-2.0
GHC no longer exports def in GHC 8.6 and above
# LANGUAGE TemplateHaskell #
module Main(main) where
import Arguments (Arguments (..),
getArguments)
import Control.Monad.Extra (unless)
import Control.Monad.IO.Class (liftIO)
import Data.Default (def)
import Data.Function ((&))
import Data.Version (showVersion)
import Development.GitRev (gitHash)
import Development.IDE (action)
import Development.IDE.Core.OfInterest (kick)
import Development.IDE.Core.Rules (mainRule)
import qualified Development.IDE.Core.Rules as Rules
import Development.IDE.Core.Tracing (withTelemetryLogger)
import qualified Development.IDE.Main as IDEMain
import qualified Development.IDE.Monitoring.EKG as EKG
import qualified Development.IDE.Monitoring.OpenTelemetry as OpenTelemetry
import qualified Development.IDE.Plugin.HLS.GhcIde as GhcIde
import Development.IDE.Types.Logger (Logger (Logger),
LoggingColumn (DataColumn, PriorityColumn),
Pretty (pretty),
Priority (Debug, Error, Info),
WithPriority (WithPriority, priority),
cfilter,
cmapWithPrio,
defaultLayoutOptions,
layoutPretty,
makeDefaultStderrRecorder,
renderStrict)
import qualified Development.IDE.Types.Logger as Logger
import Development.IDE.Types.Options
import GHC.Stack (emptyCallStack)
import Ide.Plugin.Config (Config (checkParents, checkProject))
import Ide.PluginUtils (pluginDescToIdePlugins)
import Ide.Types (PluginDescriptor (pluginNotificationHandlers),
defaultPluginDescriptor,
mkPluginNotificationHandler)
import Language.LSP.Server as LSP
import Language.LSP.Types as LSP
import Paths_ghcide (version)
import qualified System.Directory.Extra as IO
import System.Environment (getExecutablePath)
import System.Exit (exitSuccess)
import System.Info (compilerVersion)
import System.IO (hPutStrLn, stderr)
data Log
= LogIDEMain IDEMain.Log
| LogRules Rules.Log
| LogGhcIde GhcIde.Log
instance Pretty Log where
pretty = \case
LogIDEMain log -> pretty log
LogRules log -> pretty log
LogGhcIde log -> pretty log
ghcideVersion :: IO String
ghcideVersion = do
path <- getExecutablePath
let gitHashSection = case $(gitHash) of
x | x == "UNKNOWN" -> ""
x -> " (GIT hash: " <> x <> ")"
return $ "ghcide version: " <> showVersion version
<> " (GHC: " <> showVersion compilerVersion
<> ") (PATH: " <> path <> ")"
<> gitHashSection
main :: IO ()
main = withTelemetryLogger $ \telemetryLogger -> do
-- stderr recorder just for plugin cli commands
pluginCliRecorder <-
cmapWithPrio pretty
<$> makeDefaultStderrRecorder (Just [PriorityColumn, DataColumn]) Info
let hlsPlugins = pluginDescToIdePlugins (GhcIde.descriptors (cmapWithPrio LogGhcIde pluginCliRecorder))
-- WARNING: If you write to stdout before runLanguageServer
-- then the language server will not work
Arguments{..} <- getArguments hlsPlugins
if argsVersion then ghcideVersion >>= putStrLn >> exitSuccess
else hPutStrLn stderr {- see WARNING above -} =<< ghcideVersion
-- if user uses --cwd option we need to make this path absolute (and set the current directory to it)
argsCwd <- case argsCwd of
Nothing -> IO.getCurrentDirectory
Just root -> IO.setCurrentDirectory root >> IO.getCurrentDirectory
let minPriority = if argsVerbose then Debug else Info
docWithPriorityRecorder <- makeDefaultStderrRecorder (Just [PriorityColumn, DataColumn]) minPriority
(lspLogRecorder, cb1) <- Logger.withBacklog Logger.lspClientLogRecorder
(lspMessageRecorder, cb2) <- Logger.withBacklog Logger.lspClientMessageRecorder
-- This plugin just installs a handler for the `initialized` notification, which then
picks up the LSP environment and feeds it to our recorders
let lspRecorderPlugin = (defaultPluginDescriptor "LSPRecorderCallback")
{ pluginNotificationHandlers = mkPluginNotificationHandler LSP.SInitialized $ \_ _ _ _ -> do
env <- LSP.getLspEnv
liftIO $ (cb1 <> cb2) env
}
let docWithFilteredPriorityRecorder =
(docWithPriorityRecorder & cfilter (\WithPriority{ priority } -> priority >= minPriority)) <>
(lspLogRecorder & cmapWithPrio (renderStrict . layoutPretty defaultLayoutOptions)
& cfilter (\WithPriority{ priority } -> priority >= minPriority)) <>
(lspMessageRecorder & cmapWithPrio (renderStrict . layoutPretty defaultLayoutOptions)
& cfilter (\WithPriority{ priority } -> priority >= Error))
-- exists so old-style logging works. intended to be phased out
let logger = Logger $ \p m -> Logger.logger_ docWithFilteredPriorityRecorder (WithPriority p emptyCallStack (pretty m))
let recorder = docWithFilteredPriorityRecorder
& cmapWithPrio pretty
let arguments =
if argsTesting
then IDEMain.testing (cmapWithPrio LogIDEMain recorder) logger hlsPlugins
else IDEMain.defaultArguments (cmapWithPrio LogIDEMain recorder) logger hlsPlugins
IDEMain.defaultMain (cmapWithPrio LogIDEMain recorder) arguments
{ IDEMain.argsProjectRoot = Just argsCwd
, IDEMain.argCommand = argsCommand
, IDEMain.argsLogger = IDEMain.argsLogger arguments <> pure telemetryLogger
, IDEMain.argsHlsPlugins = IDEMain.argsHlsPlugins arguments <> pluginDescToIdePlugins [lspRecorderPlugin]
, IDEMain.argsRules = do
-- install the main and ghcide-plugin rules
mainRule (cmapWithPrio LogRules recorder) def
-- install the kick action, which triggers a typecheck on every
-- Shake database restart, i.e. on every user edit.
unless argsDisableKick $
action kick
, IDEMain.argsThreads = case argsThreads of 0 -> Nothing ; i -> Just (fromIntegral i)
, IDEMain.argsIdeOptions = \config sessionLoader ->
let defOptions = IDEMain.argsIdeOptions arguments config sessionLoader
in defOptions
{ optShakeProfiling = argsShakeProfiling
, optCheckParents = pure $ checkParents config
, optCheckProject = pure $ checkProject config
, optRunSubset = not argsConservativeChangeTracking
, optVerifyCoreFile = argsVerifyCoreFile
}
, IDEMain.argsMonitoring = OpenTelemetry.monitoring <> EKG.monitoring logger argsMonitoringPort
}
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/6f5a73507f8d9266a486feaf8695c052362b9b95/ghcide/exe/Main.hs | haskell | stderr recorder just for plugin cli commands
WARNING: If you write to stdout before runLanguageServer
then the language server will not work
see WARNING above
if user uses --cwd option we need to make this path absolute (and set the current directory to it)
This plugin just installs a handler for the `initialized` notification, which then
exists so old-style logging works. intended to be phased out
install the main and ghcide-plugin rules
install the kick action, which triggers a typecheck on every
Shake database restart, i.e. on every user edit. | Copyright ( c ) 2019 The DAML Authors . All rights reserved .
SPDX - License - Identifier : Apache-2.0
GHC no longer exports def in GHC 8.6 and above
# LANGUAGE TemplateHaskell #
module Main(main) where
import Arguments (Arguments (..),
getArguments)
import Control.Monad.Extra (unless)
import Control.Monad.IO.Class (liftIO)
import Data.Default (def)
import Data.Function ((&))
import Data.Version (showVersion)
import Development.GitRev (gitHash)
import Development.IDE (action)
import Development.IDE.Core.OfInterest (kick)
import Development.IDE.Core.Rules (mainRule)
import qualified Development.IDE.Core.Rules as Rules
import Development.IDE.Core.Tracing (withTelemetryLogger)
import qualified Development.IDE.Main as IDEMain
import qualified Development.IDE.Monitoring.EKG as EKG
import qualified Development.IDE.Monitoring.OpenTelemetry as OpenTelemetry
import qualified Development.IDE.Plugin.HLS.GhcIde as GhcIde
import Development.IDE.Types.Logger (Logger (Logger),
LoggingColumn (DataColumn, PriorityColumn),
Pretty (pretty),
Priority (Debug, Error, Info),
WithPriority (WithPriority, priority),
cfilter,
cmapWithPrio,
defaultLayoutOptions,
layoutPretty,
makeDefaultStderrRecorder,
renderStrict)
import qualified Development.IDE.Types.Logger as Logger
import Development.IDE.Types.Options
import GHC.Stack (emptyCallStack)
import Ide.Plugin.Config (Config (checkParents, checkProject))
import Ide.PluginUtils (pluginDescToIdePlugins)
import Ide.Types (PluginDescriptor (pluginNotificationHandlers),
defaultPluginDescriptor,
mkPluginNotificationHandler)
import Language.LSP.Server as LSP
import Language.LSP.Types as LSP
import Paths_ghcide (version)
import qualified System.Directory.Extra as IO
import System.Environment (getExecutablePath)
import System.Exit (exitSuccess)
import System.Info (compilerVersion)
import System.IO (hPutStrLn, stderr)
data Log
= LogIDEMain IDEMain.Log
| LogRules Rules.Log
| LogGhcIde GhcIde.Log
instance Pretty Log where
pretty = \case
LogIDEMain log -> pretty log
LogRules log -> pretty log
LogGhcIde log -> pretty log
ghcideVersion :: IO String
ghcideVersion = do
path <- getExecutablePath
let gitHashSection = case $(gitHash) of
x | x == "UNKNOWN" -> ""
x -> " (GIT hash: " <> x <> ")"
return $ "ghcide version: " <> showVersion version
<> " (GHC: " <> showVersion compilerVersion
<> ") (PATH: " <> path <> ")"
<> gitHashSection
main :: IO ()
main = withTelemetryLogger $ \telemetryLogger -> do
pluginCliRecorder <-
cmapWithPrio pretty
<$> makeDefaultStderrRecorder (Just [PriorityColumn, DataColumn]) Info
let hlsPlugins = pluginDescToIdePlugins (GhcIde.descriptors (cmapWithPrio LogGhcIde pluginCliRecorder))
Arguments{..} <- getArguments hlsPlugins
if argsVersion then ghcideVersion >>= putStrLn >> exitSuccess
argsCwd <- case argsCwd of
Nothing -> IO.getCurrentDirectory
Just root -> IO.setCurrentDirectory root >> IO.getCurrentDirectory
let minPriority = if argsVerbose then Debug else Info
docWithPriorityRecorder <- makeDefaultStderrRecorder (Just [PriorityColumn, DataColumn]) minPriority
(lspLogRecorder, cb1) <- Logger.withBacklog Logger.lspClientLogRecorder
(lspMessageRecorder, cb2) <- Logger.withBacklog Logger.lspClientMessageRecorder
picks up the LSP environment and feeds it to our recorders
let lspRecorderPlugin = (defaultPluginDescriptor "LSPRecorderCallback")
{ pluginNotificationHandlers = mkPluginNotificationHandler LSP.SInitialized $ \_ _ _ _ -> do
env <- LSP.getLspEnv
liftIO $ (cb1 <> cb2) env
}
let docWithFilteredPriorityRecorder =
(docWithPriorityRecorder & cfilter (\WithPriority{ priority } -> priority >= minPriority)) <>
(lspLogRecorder & cmapWithPrio (renderStrict . layoutPretty defaultLayoutOptions)
& cfilter (\WithPriority{ priority } -> priority >= minPriority)) <>
(lspMessageRecorder & cmapWithPrio (renderStrict . layoutPretty defaultLayoutOptions)
& cfilter (\WithPriority{ priority } -> priority >= Error))
let logger = Logger $ \p m -> Logger.logger_ docWithFilteredPriorityRecorder (WithPriority p emptyCallStack (pretty m))
let recorder = docWithFilteredPriorityRecorder
& cmapWithPrio pretty
let arguments =
if argsTesting
then IDEMain.testing (cmapWithPrio LogIDEMain recorder) logger hlsPlugins
else IDEMain.defaultArguments (cmapWithPrio LogIDEMain recorder) logger hlsPlugins
IDEMain.defaultMain (cmapWithPrio LogIDEMain recorder) arguments
{ IDEMain.argsProjectRoot = Just argsCwd
, IDEMain.argCommand = argsCommand
, IDEMain.argsLogger = IDEMain.argsLogger arguments <> pure telemetryLogger
, IDEMain.argsHlsPlugins = IDEMain.argsHlsPlugins arguments <> pluginDescToIdePlugins [lspRecorderPlugin]
, IDEMain.argsRules = do
mainRule (cmapWithPrio LogRules recorder) def
unless argsDisableKick $
action kick
, IDEMain.argsThreads = case argsThreads of 0 -> Nothing ; i -> Just (fromIntegral i)
, IDEMain.argsIdeOptions = \config sessionLoader ->
let defOptions = IDEMain.argsIdeOptions arguments config sessionLoader
in defOptions
{ optShakeProfiling = argsShakeProfiling
, optCheckParents = pure $ checkParents config
, optCheckProject = pure $ checkProject config
, optRunSubset = not argsConservativeChangeTracking
, optVerifyCoreFile = argsVerifyCoreFile
}
, IDEMain.argsMonitoring = OpenTelemetry.monitoring <> EKG.monitoring logger argsMonitoringPort
}
|
09bfda67282947f20037999a536f868654aaf982cc7b764d69175b675feed7a4 | Drup/dowsing | Hullot.mli | (** Hullot trees.
Allow to quickly iterates through bitsets that must
be both "large enough" and "small enough".
Parametrized by a bitvector module.
*)
module type S = sig
type bitset
(** [iter ~len ~big ~small] returns the sequence of
bitset [bs] of size [n] such that each [large bs]
and [small bs] are both true.
We assume that:
- if [small s] holds, then for all subset [bs'] of [bs],
[small bs'] holds,
- if [large s] holds, then for all superset [bs'] of [bs],
[large bs'] holds.
*)
val iter : len:int -> small:(bitset -> bool) -> large:(bitset -> bool) -> bitset Iter.t
end
include S with type bitset = Bitv.t
module Default : S with type bitset = Bitv.t
module Make (M : Bitv.S) : S with type bitset = M.t
| null | https://raw.githubusercontent.com/Drup/dowsing/ddb1c5c3f5c89e1b3ee95bc449ab456f7af19719/lib/unification/Hullot.mli | ocaml | * Hullot trees.
Allow to quickly iterates through bitsets that must
be both "large enough" and "small enough".
Parametrized by a bitvector module.
* [iter ~len ~big ~small] returns the sequence of
bitset [bs] of size [n] such that each [large bs]
and [small bs] are both true.
We assume that:
- if [small s] holds, then for all subset [bs'] of [bs],
[small bs'] holds,
- if [large s] holds, then for all superset [bs'] of [bs],
[large bs'] holds.
|
module type S = sig
type bitset
val iter : len:int -> small:(bitset -> bool) -> large:(bitset -> bool) -> bitset Iter.t
end
include S with type bitset = Bitv.t
module Default : S with type bitset = Bitv.t
module Make (M : Bitv.S) : S with type bitset = M.t
|
b27ed61b42d722fe8aed2e756fef33bf91cb8f4bd0d0abfb7d907079390f308d | AshleyYakeley/Truth | FullNameRef.hs | module Pinafore.Language.Name.FullNameRef where
import Pinafore.Language.Name.FullName
import Pinafore.Language.Name.Name
import Pinafore.Language.Name.Namespace
import Pinafore.Language.Name.NamespaceRef
import Pinafore.Language.Name.ToText
import Shapes
data FullNameRef = MkFullNameRef
{ fnName :: Name
, fnSpace :: NamespaceRef
} deriving (Eq, Ord)
pattern UnqualifiedFullNameRef :: Name -> FullNameRef
pattern UnqualifiedFullNameRef n =
MkFullNameRef n CurrentNamespaceRef
fullNameRefToUnqualified :: FullNameRef -> Maybe Name
fullNameRefToUnqualified (UnqualifiedFullNameRef n) = Just n
fullNameRefToUnqualified _ = Nothing
instance ToText FullNameRef where
toText (MkFullNameRef name RootNamespaceRef)
| nameIsInfix name = toText name
toText (MkFullNameRef name CurrentNamespaceRef) = toText name
toText (MkFullNameRef name RootNamespaceRef) = toText name <> "."
toText (MkFullNameRef name ns) = toText name <> "." <> toText ns
instance Show FullNameRef where
show = unpack . toText
instance IsString FullNameRef where
fromString "." = MkFullNameRef "." CurrentNamespaceRef
fromString s =
case nonEmpty s of
Just ns
| '.' <- last ns -> fullNameRef $ fromString s
_ ->
case fromString s of
MkFullName n (MkNamespace ns) -> MkFullNameRef n (RelativeNamespaceRef ns)
namespaceConcatFullName :: Namespace -> FullNameRef -> FullName
namespaceConcatFullName ns (MkFullNameRef name nref) = MkFullName name (namespaceConcatRef ns nref)
fullNameRef :: FullName -> FullNameRef
fullNameRef (MkFullName name ns) = MkFullNameRef name (AbsoluteNamespaceRef ns)
fullNameRootRelative :: FullName -> FullNameRef
fullNameRootRelative (MkFullName n ns) = MkFullNameRef n (namespaceRootRelative ns)
| All the ways a ' FullName ' can be split into a ' ' and ' FullNameRef ' , starting with the longest ' ' and shortest ' FullNameRef ' .
fullNameSplits :: FullName -> [(Namespace, FullNameRef)]
fullNameSplits (MkFullName name ns) = fmap (fmap $ \nsr -> MkFullNameRef name nsr) $ namespaceSplits ns
namespaceWithinFullNameRef :: Namespace -> FullName -> Maybe FullNameRef
namespaceWithinFullNameRef na (MkFullName n nb) = fmap (MkFullNameRef n) $ namespaceWithinRef na nb
namespaceRelativeFullName :: Namespace -> FullName -> FullNameRef
namespaceRelativeFullName na (MkFullName n nb) = MkFullNameRef n $ namespaceRelative na nb
relativeNamespace :: [Namespace] -> Namespace -> NamespaceRef
relativeNamespace basens fn =
fromMaybe (namespaceRootRelative fn) $
choice $ fmap (\(ns, fref) -> ifpure (elem ns basens) fref) $ namespaceSplits fn
relativeFullName :: [Namespace] -> FullName -> FullNameRef
relativeFullName basens fn =
fromMaybe (fullNameRootRelative fn) $
choice $ fmap (\(ns, fref) -> ifpure (elem ns basens) fref) $ fullNameSplits fn
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/f567d19253bb471cbd8c39095fb414229b27706a/Pinafore/pinafore-language/lib/Pinafore/Language/Name/FullNameRef.hs | haskell | module Pinafore.Language.Name.FullNameRef where
import Pinafore.Language.Name.FullName
import Pinafore.Language.Name.Name
import Pinafore.Language.Name.Namespace
import Pinafore.Language.Name.NamespaceRef
import Pinafore.Language.Name.ToText
import Shapes
data FullNameRef = MkFullNameRef
{ fnName :: Name
, fnSpace :: NamespaceRef
} deriving (Eq, Ord)
pattern UnqualifiedFullNameRef :: Name -> FullNameRef
pattern UnqualifiedFullNameRef n =
MkFullNameRef n CurrentNamespaceRef
fullNameRefToUnqualified :: FullNameRef -> Maybe Name
fullNameRefToUnqualified (UnqualifiedFullNameRef n) = Just n
fullNameRefToUnqualified _ = Nothing
instance ToText FullNameRef where
toText (MkFullNameRef name RootNamespaceRef)
| nameIsInfix name = toText name
toText (MkFullNameRef name CurrentNamespaceRef) = toText name
toText (MkFullNameRef name RootNamespaceRef) = toText name <> "."
toText (MkFullNameRef name ns) = toText name <> "." <> toText ns
instance Show FullNameRef where
show = unpack . toText
instance IsString FullNameRef where
fromString "." = MkFullNameRef "." CurrentNamespaceRef
fromString s =
case nonEmpty s of
Just ns
| '.' <- last ns -> fullNameRef $ fromString s
_ ->
case fromString s of
MkFullName n (MkNamespace ns) -> MkFullNameRef n (RelativeNamespaceRef ns)
namespaceConcatFullName :: Namespace -> FullNameRef -> FullName
namespaceConcatFullName ns (MkFullNameRef name nref) = MkFullName name (namespaceConcatRef ns nref)
fullNameRef :: FullName -> FullNameRef
fullNameRef (MkFullName name ns) = MkFullNameRef name (AbsoluteNamespaceRef ns)
fullNameRootRelative :: FullName -> FullNameRef
fullNameRootRelative (MkFullName n ns) = MkFullNameRef n (namespaceRootRelative ns)
| All the ways a ' FullName ' can be split into a ' ' and ' FullNameRef ' , starting with the longest ' ' and shortest ' FullNameRef ' .
fullNameSplits :: FullName -> [(Namespace, FullNameRef)]
fullNameSplits (MkFullName name ns) = fmap (fmap $ \nsr -> MkFullNameRef name nsr) $ namespaceSplits ns
namespaceWithinFullNameRef :: Namespace -> FullName -> Maybe FullNameRef
namespaceWithinFullNameRef na (MkFullName n nb) = fmap (MkFullNameRef n) $ namespaceWithinRef na nb
namespaceRelativeFullName :: Namespace -> FullName -> FullNameRef
namespaceRelativeFullName na (MkFullName n nb) = MkFullNameRef n $ namespaceRelative na nb
relativeNamespace :: [Namespace] -> Namespace -> NamespaceRef
relativeNamespace basens fn =
fromMaybe (namespaceRootRelative fn) $
choice $ fmap (\(ns, fref) -> ifpure (elem ns basens) fref) $ namespaceSplits fn
relativeFullName :: [Namespace] -> FullName -> FullNameRef
relativeFullName basens fn =
fromMaybe (fullNameRootRelative fn) $
choice $ fmap (\(ns, fref) -> ifpure (elem ns basens) fref) $ fullNameSplits fn
| |
45bf879599ea4334edd1d736793913c124f4f250bc1708c15c3ca2c68d8e3b55 | axolotl-lang/axolotl | ArbitraryBlock.hs | module Analyser.Analysers.ArbitraryBlock where
import Analyser.Util (AnalyserResult, Env, getTypeOfExpr, hUnion)
import Control.Monad.State
( MonadIO (liftIO),
MonadState (get),
StateT (runStateT),
)
import qualified Data.HashTable.IO as H
import qualified Data.Text as T
import Parser.Ast (Expr (ArbitraryBlock, Nil))
{-
Analysing arbitrary blocks means we need to analyse
all the expressions inside that arbitrary block, so
we just run it thorugh analyseExprs.
-}
type AnalyseExprsFn = StateT Env IO AnalyserResult -> Expr -> StateT Env IO AnalyserResult
analyseArbitraryBlock :: AnalyserResult -> [Expr] -> AnalyseExprsFn -> StateT Env IO AnalyserResult
acc : : [ Either Text Expr ] - > the resultant accumulator for analyseExprs
-- body :: [Expr] -> the set of exprs that the block is formed by
analyseExprs : : AnalyseExprsFn - > the analyseExprs function from Analyser.hs
analyseArbitraryBlock acc body analyseExprs = do
env <- get
h1 <- liftIO $ H.newSized 1000
h2 <- liftIO $ H.newSized 1000
result <- liftIO $ runStateT (foldl analyseExprs (pure []) body) (h1, h2)
-- we now need to union the definitions made inside
-- this scope with the definitions made outside this scope
-- before this point, and pass them to getTypeOfExpr, since
-- the previously made definitions can be required to
-- determine the type of an expression in the current
-- scope, and so they must be available too
let env' = snd result
gd <- liftIO $ fst env' `hUnion` fst env
r <- liftIO $ getTypeOfExpr (if null body then Nil else last body) gd
pure $ acc <> [sequence (fst result) >>= \v -> r >> Right (ArbitraryBlock v)]
| null | https://raw.githubusercontent.com/axolotl-lang/axolotl/5567faebca0625eb46eba79d973fe8d2459c827e/src/Analyser/Analysers/ArbitraryBlock.hs | haskell |
Analysing arbitrary blocks means we need to analyse
all the expressions inside that arbitrary block, so
we just run it thorugh analyseExprs.
body :: [Expr] -> the set of exprs that the block is formed by
we now need to union the definitions made inside
this scope with the definitions made outside this scope
before this point, and pass them to getTypeOfExpr, since
the previously made definitions can be required to
determine the type of an expression in the current
scope, and so they must be available too | module Analyser.Analysers.ArbitraryBlock where
import Analyser.Util (AnalyserResult, Env, getTypeOfExpr, hUnion)
import Control.Monad.State
( MonadIO (liftIO),
MonadState (get),
StateT (runStateT),
)
import qualified Data.HashTable.IO as H
import qualified Data.Text as T
import Parser.Ast (Expr (ArbitraryBlock, Nil))
type AnalyseExprsFn = StateT Env IO AnalyserResult -> Expr -> StateT Env IO AnalyserResult
analyseArbitraryBlock :: AnalyserResult -> [Expr] -> AnalyseExprsFn -> StateT Env IO AnalyserResult
acc : : [ Either Text Expr ] - > the resultant accumulator for analyseExprs
analyseExprs : : AnalyseExprsFn - > the analyseExprs function from Analyser.hs
analyseArbitraryBlock acc body analyseExprs = do
env <- get
h1 <- liftIO $ H.newSized 1000
h2 <- liftIO $ H.newSized 1000
result <- liftIO $ runStateT (foldl analyseExprs (pure []) body) (h1, h2)
let env' = snd result
gd <- liftIO $ fst env' `hUnion` fst env
r <- liftIO $ getTypeOfExpr (if null body then Nil else last body) gd
pure $ acc <> [sequence (fst result) >>= \v -> r >> Right (ArbitraryBlock v)]
|
cebea420a5e470b0ed473b0b5ec8d8d343cbacd6be9d90586037d673cdbdf745 | INRIA/zelus | translate.ml | (***********************************************************************)
(* *)
(* *)
(* Zelus, a synchronous language for hybrid systems *)
(* *)
( c ) 2020 Paris ( see the file )
(* *)
(* Copyright Institut National de Recherche en Informatique et en *)
Automatique . All rights reserved . This file is distributed under
the terms of the INRIA Non - Commercial License Agreement ( see the
(* LICENSE file). *)
(* *)
(* *********************************************************************)
translation from zelus code to obc
(* applied to normalized and scheduled code *)
open Zmisc
open Zident
open Global
open Deftypes
open Obc
(* application *)
let app e_fun e_list =
match e_list with | [] -> e_fun | _ -> Oapp(e_fun, e_list)
let sequence inst1 inst2 =
match inst1, inst2 with
| (Osequence [], inst) | (inst, Osequence []) -> inst
| Osequence(l1), Osequence(l2) -> Osequence(l1 @ l2)
| _, Osequence(l2) -> Osequence(inst1 :: l2)
| _ -> Osequence [inst1; inst2]
(** Translation of the kind *)
let kind = function
| Zelus.S | Zelus.A | Zelus.AD | Zelus.AS -> Ofun
| Zelus.C | Zelus.D -> Onode | Zelus.P -> Onode
(** Translating type expressions. *)
let rec type_expression { Zelus.desc = desc } =
match desc with
| Zelus.Etypevar(s) -> Otypevar(s)
| Zelus.Etypeconstr(ln, ty_list) ->
Otypeconstr(ln, List.map type_expression ty_list)
| Zelus.Etypetuple(ty_list) ->
Otypetuple(List.map type_expression ty_list)
| Zelus.Etypevec(ty, s) ->
Otypevec(type_expression ty, size s)
| Zelus.Etypefun(k, opt_name, ty_arg, ty_res) ->
Otypefun(kind k, opt_name, type_expression ty_arg, type_expression ty_res)
and type_of_type_decl { Zelus.desc = desc } =
match desc with
| Zelus.Eabstract_type -> Oabstract_type
| Zelus.Eabbrev(ty) -> Oabbrev(type_expression ty)
| Zelus.Evariant_type(constr_decl_list) ->
Ovariant_type(List.map constr_decl constr_decl_list)
| Zelus.Erecord_type(n_ty_list) ->
Orecord_type(List.map (fun (n, ty) -> (n, type_expression ty)) n_ty_list)
and constr_decl { desc = desc } =
match desc with
| Econstr0decl(n) -> Oconstr0decl(n)
| Econstr1decl(n, ty_list) ->
Oconstr1decl(n, List.map type_expression ty_list)
and size { Zelus.desc = desc } =
match desc with
| Zelus.Sconst(i) -> Sconst(i)
| Zelus.Sglobal(ln) -> Sglobal(ln)
| Zelus.Sname(n) -> Sname(n)
| Zelus.Sop(op, s1, s2) ->
let operator = function Zelus.Splus -> Splus | Zelus.Sminus -> Sminus in
Sop(operator op, size s1, size s2)
(* is-it a mutable value? Only vectors are considered at the moment *)
let rec is_mutable { t_desc = desc } =
match desc with
| Tvec _ -> true
| Tlink(link) -> is_mutable link
| _ -> false
(* translating an internal type into a type expression *)
let type_expression_of_typ ty =
let ty_exp = Interface.type_expression_of_typ ty in
type_expression ty_exp
(* The translation uses an environment to store information about identifiers *)
type env = entry Env.t (* the symbol table *)
and entry =
{ e_typ: Deftypes.typ;
e_sort: sort;
e_size: loop_path; (* [e.(i_1)...(i_n)] *)
}
and sort =
| In of exp
(* the variable [x] is implemented by [e.(i_1)...(i_n)]; e.g., [x in e] *)
| Out of Zident.t * Deftypes.tsort
(* the variable [x] is stored into [y.(i_1)...(i_n); e.g. [x out y]] *)
and loop_path = Zident.t list
type code =
{ mem: mentry State.t; (* set of state variables *)
init: Obc.inst; (* sequence of initializations for [mem] *)
instances: ientry State.t; (* set of instances *)
reset: Obc.inst; (* sequence of equations for resetting the block *)
step: inst; (* body *)
}
let fprint ff (env: entry Env.t) =
let fprint_entry ff { e_typ = ty; e_sort = sort; e_size = size } =
Format.fprintf ff "@[{ typ = %a;@,size = %a}@]"
Ptypes.output ty
(Pp_tools.print_list_r Printer.name "[" "," "]") size in
Zident.Env.fprint_t fprint_entry ff env
let empty_code = { mem = State.empty; init = Osequence [];
instances = State.empty;
reset = Osequence []; step = Osequence [] }
let seq { mem = m1; init = i1; instances = j1; reset = r1; step = s1 }
{ mem = m2; init = i2; instances = j2; reset = r2; step = s2 } =
{ mem = State.seq m1 m2; init = sequence i1 i2; instances = State.par j1 j2;
reset = sequence r1 r2; step = sequence s1 s2 }
let empty_path = []
(** Look for an entry in the environment *)
let entry_of n env =
try
Env.find n env
with Not_found ->
Zmisc.internal_error "Unbound variable" Printer.name n
(** Translation of immediate values *)
let immediate = function
| Deftypes.Eint(i) -> Oint(i)
| Deftypes.Efloat(f) -> Ofloat(f)
| Deftypes.Ebool(b) -> Obool(b)
| Deftypes.Echar(c) -> Ochar(c)
| Deftypes.Estring(s) -> Ostring(s)
| Deftypes.Evoid -> Ovoid
let constant = function
| Deftypes.Cimmediate(i) -> Oconst(immediate i)
| Deftypes.Cglobal(ln) -> Oglobal(ln)
(* read/write of a state variable. *)
let state is_read n k =
match k with
| None -> Oleft_state_name(n)
| Some(k) ->
match k with
| Deftypes.Cont ->
Oleft_state_primitive_access (Oleft_state_name(n), Ocont)
| Deftypes.Zero ->
Oleft_state_primitive_access
(Oleft_state_name(n), if is_read then Ozero_in else Ozero_out)
| Deftypes.Horizon | Deftypes.Period
| Deftypes.Encore | Deftypes.Major -> Oleft_state_name(n)
(* index in an array *)
let rec index e =
function [] -> e | ei :: ei_list -> Oaccess(index e ei_list, Olocal(ei))
let rec left_value_index lv =
function
| [] -> lv
| ei :: ei_list -> Oleft_index(left_value_index lv ei_list, Olocal(ei))
let rec left_state_value_index lv = function
| [] -> lv
| ei :: ei_list ->
Oleft_state_index(left_state_value_index lv ei_list, Olocal(ei))
(* read of a variable *)
let var { e_sort = sort; e_typ = ty; e_size = ei_list } =
match sort with
| In(e) -> index e ei_list
| Out(n, sort) ->
match sort with
| Sstatic | Sval -> index (Olocal(n)) ei_list
| Svar _ ->
index (Ovar(is_mutable ty, n)) ei_list
| Smem { m_kind = k } ->
Ostate(left_state_value_index (state true n k) ei_list)
(** Make an assignment according to the sort of a variable [n] *)
let assign { e_sort = sort; e_size = ei_list } e =
match sort with
| In _ -> assert false
| Out(n, sort) ->
match sort with
| Sstatic | Sval -> assert false
| Svar _ -> Oassign(left_value_index (Oleft_name n) ei_list, e)
| Smem { m_kind = k } ->
Oassign_state(left_state_value_index (state false n k) ei_list, e)
(** Generate the code for a definition *)
let def { e_typ = ty; e_sort = sort; e_size = ei_list } e
({ step = s } as code) =
match sort with
| In _ -> assert false
| Out(n, sort) ->
match sort with
| Sstatic | Sval ->
{ code with step =
Olet(Ovarpat(n, type_expression_of_typ ty), e, s) }
| Svar _ ->
{ code with step =
sequence
(Oassign(left_value_index (Oleft_name n) ei_list, e))
s }
| Smem { m_kind = k } ->
{ code with step = sequence
(Oassign_state(left_state_value_index
(state false n k) ei_list, e)) s }
(** Generate the code for [der x = e] *)
let der { e_sort = sort; e_size = ei_list } e ({ step = s } as code) =
match sort with
| In _ -> assert false
| Out(n, sort) ->
{ code with step =
sequence
(Oassign_state(left_state_value_index
(Oleft_state_primitive_access
(Oleft_state_name(n), Oder)) ei_list,
e))
s }
(** Generate an if/then *)
let ifthen r_e i_code s = sequence (Oif(r_e, i_code, None)) s
(** Generate a for loop *)
let for_loop direction ix e1 e2 i_body =
match i_body with
| Osequence [] -> Osequence []
| _ -> Ofor(direction, ix, e1, e2, i_body)
(** Generate the code for the definition of a value *)
let letpat p e ({ step = s } as code) =
{ code with step = Olet(p, e, s) }
(** Generate the code for initializing shared variables *)
let rec letvar l s =
match l with
| [] -> s
| (n, is_mutable, ty, v_opt) :: l ->
Oletvar(n, is_mutable, ty, v_opt, letvar l s)
(** Compile an equation [n += e] *)
let pluseq ({ e_sort = sort; e_size = ei_list } as entry)
e ({ step = s } as code) =
let ln =
match sort with
| In _ -> assert false
| Out(n, sort) ->
match sort with
| Svar { v_combine = Some(ln) } | Smem { m_combine = Some(ln) } -> ln
| _ -> Zmisc.internal_error "Unbound variable" Printer.name n in
{ code with step =
sequence (assign entry
(Oapp(Oglobal(ln), [var entry; e]))) s }
let out_of n env =
let { e_typ = ty; e_sort = sort; e_size = ix_list } = entry_of n env in
match sort with
| In _ -> assert false
| Out(x, sort) -> x, ty, sort, ix_list
(** Translate size expressions *)
let rec size_of_type = function
| Tconst(i) -> Sconst(i)
| Tglobal(q) -> Sglobal(Lident.Modname(q))
| Tname(n) -> Sname(n)
| Top(op, s1, s2) ->
let e1 = size_of_type s1 in
let e2 = size_of_type s2 in
match op with
| Tplus -> Sop(Splus, e1, e2)
| Tminus -> Sop(Sminus, e1, e2)
(** Translate size expressions *)
let rec size { Zelus.desc = desc } =
match desc with
| Zelus.Sconst(i) -> Sconst(i)
| Zelus.Sglobal(ln) -> Sglobal(ln)
| Zelus.Sname n -> Sname(n)
| Zelus.Sop(op, s1, s2) ->
let s1 = size s1 in
let s2 = size s2 in
match op with
| Zelus.Splus -> Sop(Splus, s1, s2)
| Zelus.Sminus -> Sop(Sminus, s1, s2)
(* makes an initial value from a type. returns None when it fails *)
let choose env ty =
let tuple l = Otuple(l) in
let efalse = Oconst(Obool(false)) in
let echar0 = Oconst(Ochar('a')) in
on purpose , take an initial value different from zero
let ezero = Oconst(Oint(42)) in
let efzero = Oconst(Ofloat(42.0)) in
let estring0 = Oconst(Ostring("aaaaaaa")) in
let evoid = Oconst(Ovoid) in
let eany = Oconst(Oany) in
let vec e s = Ovec(e, s) in
let rec value_from_deftype id =
try
let { info = { type_desc = ty_c } } =
Modules.find_type (Lident.Modname(id)) in
match ty_c with
| Variant_type(g_list) -> value_from_variant_list g_list
| Abstract_type -> eany
| Record_type(l_list) ->
Orecord(
List.map
(fun { qualid = qualid; info = { label_res = ty } } ->
(Lident.Modname(qualid), value ty)) l_list)
| Abbrev(_, ty) -> value ty
with
| Not_found -> eany
and value ty =
match ty.t_desc with
| Tvar -> eany
| Tproduct(ty_l) -> tuple (List.map value ty_l)
| Tfun _ -> eany
| Tvec(ty, s) -> vec (value ty) (size_of_type s)
| Tconstr(id, _, _) ->
if id = Initial.int_ident then ezero
else if id = Initial.bool_ident then efalse
else if id = Initial.char_ident then echar0
else if id = Initial.float_ident then efzero
else if id = Initial.string_ident then estring0
else if id = Initial.unit_ident then evoid
else if id = Initial.zero_ident then efalse
else
(* try to find a value from its type definition *)
(* we do not consider type instantiation here *)
value_from_deftype id
| Tlink(link) -> value link
and value_from_variant_list g_list =
let rec findrec g_list =
match g_list with
| [] -> raise Not_found
| { qualid = qualid; info = { constr_arity = arity } } :: g_list ->
if arity = 0 then Oconstr0(Lident.Modname(qualid))
else findrec g_list in
try
(* look for a constructor with arity 0 *)
findrec g_list
with
| Not_found ->
otherwise , pick one
let { qualid = qualid; info = { constr_arg = ty_list } } =
List.hd g_list in
Oconstr1(Lident.Modname(qualid), List.map value ty_list) in
Some(value ty)
(** Computes a default value *)
let default env ty v_opt =
match v_opt with
| None -> choose env ty
| Some(v) -> Some(constant v)
(** Extension of an environment *)
(* The access to a state variable [x] is turned into the access on an *)
array access x.(i1) ... ) if loop_path = [ i1; ... ;in ]
let append loop_path l_env env =
(* add a memory variable for every state variable in [l_env] *)
(* and a [letvar] declaration for every shared variable *)
let addrec n { t_sort = k; t_typ = ty } (env_acc, mem_acc, var_acc) =
match k with
| Sstatic
| Sval ->
Env.add n { e_typ = ty; e_sort = Out(n, k); e_size = [] } env_acc,
mem_acc, var_acc
| Svar { v_default = v_opt } ->
Env.add n { e_typ = ty; e_sort = Out(n, k); e_size = [] } env_acc,
mem_acc, (n, is_mutable ty, ty, default env ty v_opt) :: var_acc
| Smem { m_kind = k_opt } ->
Env.add n
{ e_typ = ty; e_sort = Out(n, k); e_size = loop_path } env_acc,
State.cons { m_name = n; m_value = choose env ty; m_typ = ty;
m_kind = k_opt; m_size = [] } mem_acc,
var_acc in
Env.fold addrec l_env (env, State.empty, [])
(** Translation of a stateful function application [f se1 ... sen e] *)
(* if [loop_path = [i1;...;ik]
* instance o = f se1 ... sen
* call o.(i1)...(ik).step(e)
* reset with o.(i1)...(ik).reset *)
let apply k env loop_path e e_list
({ mem = m; init = i; instances = j; reset = r; step = s } as code) =
match k with
| Deftypes.Tstatic _
| Deftypes.Tany | Deftypes.Tdiscrete(false) -> Oapp(e, e_list), code
| Deftypes.Tdiscrete(true)
| Deftypes.Tcont
| Deftypes.Tproba ->
the first [ n-1 ] arguments are static
let se_list, arg = Zmisc.firsts e_list in
let f_opt = match e with | Oglobal(g) -> Some(g) | _ -> None in
let loop_path = List.map (fun ix -> Olocal(ix)) loop_path in
(* create an instance *)
let o = Zident.fresh "i" in
let j_code = { i_name = o; i_machine = e; i_kind = k;
i_params = se_list; i_size = [] } in
let reset_code =
Omethodcall({ met_machine = f_opt; met_name = Oaux.reset;
met_instance = Some(o, loop_path); met_args = [] }) in
let step_code =
Omethodcall({ met_machine = f_opt; met_name = Oaux.step;
met_instance = Some(o, loop_path); met_args = [arg] }) in
step_code,
{ code with instances = State.cons j_code j;
init = sequence (Oexp(reset_code)) i;
reset = sequence (Oexp(reset_code)) r }
(** Translation of expressions under an environment [env] *)
(* [code] is the code already generated in the context. *)
(* [exp env e code = e', code'] where [code'] extends [code] with new *)
(* memory, instantiation and reset. The step field is untouched *)
(* [loop_path = [i1;...;in]] is the loop path if [e] appears in *)
(* a nested loop forall in ... forall i1 do ... e ... *)
let rec exp env loop_path code { Zelus.e_desc = desc } =
match desc with
| Zelus.Econst(i) -> Oconst(immediate i), code
| Zelus.Elocal(n)
| Zelus.Elast(n) -> var (entry_of n env), code
| Zelus.Eglobal { lname = ln } -> Oglobal(ln), code
| Zelus.Econstr0(ln) -> Oconstr0(ln), code
| Zelus.Econstr1(ln, e_list) ->
let e_list, code = Zmisc.map_fold (exp env loop_path) code e_list in
Oconstr1(ln, e_list), code
| Zelus.Etuple(e_list) ->
let e_list, code = Zmisc.map_fold (exp env loop_path) code e_list in
Otuple(e_list), code
| Zelus.Erecord(label_e_list) ->
let label_e_list, code =
Zmisc.map_fold
(fun code (l, e) -> let e, code = exp env loop_path code e in
(l, e), code) code label_e_list in
Orecord(label_e_list), code
| Zelus.Erecord_access(e_record, longname) ->
let e_record, code =
exp env loop_path code e_record in
Orecord_access(e_record, longname), code
| Zelus.Erecord_with(e_record, label_e_list) ->
let e_record, code =
exp env loop_path code e_record in
let label_e_list, code =
Zmisc.map_fold
(fun code (l, e) -> let e, code = exp env loop_path code e in
(l, e), code) code label_e_list in
Orecord_with(e_record, label_e_list), code
| Zelus.Etypeconstraint(e, ty_exp) ->
let e, code = exp env loop_path code e in
let ty_exp = type_expression ty_exp in
Otypeconstraint(e, ty_exp), code
| Zelus.Eop(Zelus.Eup, [e]) ->
implement the zero - crossing up(x ) by up(if x > = 0 then 1 else -1 )
let e = if !Zmisc.zsign then Zaux.sgn e else e in
exp env loop_path code e
| Zelus.Eop(Zelus.Ehorizon, [e]) ->
exp env loop_path code e
| Zelus.Eop(Zelus.Eifthenelse, [e1; e2; e3]) ->
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
let e3, code = exp env loop_path code e3 in
Oifthenelse(e1, e2, e3), code
| Zelus.Eop(Zelus.Eaccess, [e1; e2]) ->
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
Oaccess(e1, e2), code
| Zelus.Eop(Zelus.Eupdate, [e1; i; e2]) ->
let _, se = Ztypes.filter_vec e1.Zelus.e_typ in
let se = size_of_type se in
let e1, code = exp env loop_path code e1 in
let i, code = exp env loop_path code i in
let e2, code = exp env loop_path code e2 in
Oupdate(se, e1, i, e2), code
| Zelus.Eop(Zelus.Eslice(s1, s2), [e]) ->
let s1 = size s1 in
let s2 = size s2 in
let e, code = exp env loop_path code e in
Oslice(e, s1, s2), code
| Zelus.Eop(Zelus.Econcat, [e1; e2]) ->
let _, s1 = Ztypes.filter_vec e1.Zelus.e_typ in
let _, s2 = Ztypes.filter_vec e2.Zelus.e_typ in
let s1 = size_of_type s1 in
let s2 = size_of_type s2 in
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
Oconcat(e1, s1, e2, s2), code
| Zelus.Eop(Zelus.Eatomic, [e]) ->
exp env loop_path code e
| Zelus.Elet _ | Zelus.Eseq _ | Zelus.Eperiod _
| Zelus.Eop _ | Zelus.Epresent _
| Zelus.Ematch _ | Zelus.Eblock _ -> assert false
| Zelus.Eapp(_, e_fun, e_list) ->
(* compute the sequence of static arguments and non static ones *)
let se_list, ne_list, ty_res =
Ztypes.split_arguments e_fun.Zelus.e_typ e_list in
let e_fun, code = exp env loop_path code e_fun in
let se_list, code = Zmisc.map_fold (exp env loop_path) code se_list in
let ne_list, code = Zmisc.map_fold (exp env loop_path) code ne_list in
let e_fun = app e_fun se_list in
match ne_list with
| [] -> e_fun, code
| _ -> let k = Ztypes.kind_of_funtype ty_res in
apply k env loop_path e_fun ne_list code
(** Patterns *)
and pattern { Zelus.p_desc = desc; Zelus.p_typ = ty } =
match desc with
| Zelus.Ewildpat -> Owildpat
| Zelus.Econstpat(im) -> Oconstpat(immediate im)
| Zelus.Econstr0pat(c0) -> Oconstr0pat(c0)
| Zelus.Econstr1pat(c1, p_list) ->
Oconstr1pat(c1, List.map pattern p_list)
| Zelus.Etuplepat(p_list) -> Otuplepat(List.map pattern p_list)
| Zelus.Evarpat(n) -> Ovarpat(n, type_expression_of_typ ty)
| Zelus.Erecordpat(label_pat_list) ->
Orecordpat(List.map (fun (label, pat) -> (label, pattern pat))
label_pat_list)
| Zelus.Etypeconstraintpat(p, ty) ->
Otypeconstraintpat(pattern p, type_expression ty)
| Zelus.Ealiaspat(p, n) -> Oaliaspat(pattern p, n)
| Zelus.Eorpat(p1, p2) -> Oorpat(pattern p1, pattern p2)
(** Equations *)
let rec equation env loop_path { Zelus.eq_desc = desc } code =
match desc with
| Zelus.EQeq({ Zelus.p_desc = Zelus.Evarpat(n) }, e) ->
let e, code = exp env loop_path code e in
def (entry_of n env) e code
| Zelus.EQeq(p, e) ->
let e, code = exp env loop_path code e in
letpat (pattern p) e code
| Zelus.EQpluseq(n, e) ->
let e, code = exp env loop_path code e in
pluseq (entry_of n env) e code
| Zelus.EQder(n, e, None, []) ->
let e, code = exp env loop_path code e in
der (entry_of n env) e code
| Zelus.EQmatch(_, e, p_h_list) ->
let e, code = exp env loop_path code e in
let p_step_h_list, p_h_code = match_handlers env loop_path p_h_list in
seq { p_h_code with step = Omatch(e, p_step_h_list) } code
| Zelus.EQreset([{ Zelus.eq_desc = Zelus.EQinit(x, e) }], r_e)
when not (Reset.static e) ->
let r_e, code = exp env loop_path code r_e in
let e, ({ init = i_code } as e_code) = exp env loop_path empty_code e in
let { step = s } as code = seq e_code code in
{ code with step =
ifthen r_e (sequence (assign (entry_of x env) e) i_code) s }
| Zelus.EQreset(eq_list, r_e) ->
let { init = i_code } = code in
let { init = ri_code } as r_code =
equation_list env loop_path eq_list { code with init = Osequence [] } in
let r_e, r_code = exp env loop_path r_code r_e in
(* execute the initialization code when [e] is true *)
let { step = s } as code = seq r_code { empty_code with init = i_code } in
{ code with step = ifthen r_e ri_code s }
| Zelus.EQinit(x, e) ->
let e_c, code = exp env loop_path code e in
let x_e = assign (entry_of x env) e_c in
(* initialization of a state variable with a static value *)
if Reset.static e
then seq { empty_code with init = x_e; reset = x_e } code
else seq { empty_code with step = x_e } code
| Zelus.EQforall { Zelus.for_index = i_list; Zelus.for_init = init_list;
Zelus.for_body = b_eq_list } ->
[ forall i in e1 .. e2 , xi in , ... , oi in o , ... do body done ]
* is translated into :
* for i = e1 to e2 do
...
* with xi into ei.(i ) , oi into o.(i )
* - every instance o from the body must be an array
* - every state variable m from the body must be an array
* is translated into:
* for i = e1 to e2 do
...
* with xi into ei.(i), oi into o.(i)
* - every instance o from the body must be an array
* - every state variable m from the body must be an array *)
(* look for the index [i in e1..e2] *)
let rec index code = function
| [] -> let id = Zident.fresh "i" in
(id, Oconst(Oint(0)), Oconst(Oint(0))), code
| { Zelus.desc = desc } :: i_list ->
match desc with
| Zelus.Eindex(x, e1, e2) ->
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
(x, e1, e2), code
| Zelus.Einput _ | Zelus.Eoutput _ -> index code i_list in
(* extend the environment for in/out variables *)
(* [ix] is the index of the loop *)
let in_out ix (env_acc, code) { Zelus.desc = desc } =
match desc with
| Zelus.Einput(x, ({ Zelus.e_typ = ty } as e)) ->
let e, code = exp env loop_path code e in
Env.add x { e_typ = ty; e_sort = In(e); e_size = [ix] } env_acc, code
| Zelus.Eoutput(x, y) ->
let y, ty, sort, ix_list = out_of y env in
Env.add x { e_typ = ty; e_sort = Out(y, sort);
e_size = ix :: ix_list } env_acc, code
| Zelus.Eindex(i, { Zelus.e_typ = ty }, _) ->
Env.add i { e_typ = ty; e_sort = Out(i, Deftypes.Sval);
e_size = [] } env_acc, code in
(* transforms an instance into an array of instances *)
let array_of_instance size ({ i_size } as ientry) =
{ ientry with i_size = size :: i_size } in
let array_of_memory size ({ m_size } as mentry) =
{ mentry with m_size = size :: m_size } in
(* generate the code for the initialization part of the for loop *)
let init code { Zelus.desc = desc } =
match desc with
| Zelus.Einit_last(x, e) ->
let e, code = exp env loop_path code e in
assign (entry_of x env) e, code in
(* first compute the index [i in e1 .. e2] *)
let (ix, e1, e2), code = index code i_list in
(* extend the environment [env] with input and output variables *)
let env, code = List.fold_left (in_out ix) (env, code) i_list in
let { mem = m_code; init = i_code; instances = j_code;
reset = r_code; step = s_code } =
block env (ix :: loop_path) b_eq_list in
(* transforms instances into arrays *)
let j_code =
State.map
(array_of_instance (Oaux.plus (Oaux.minus e2 e1) Oaux.one)) j_code in
let m_code =
State.map
(array_of_memory (Oaux.plus (Oaux.minus e2 e1) Oaux.one)) m_code in
(* generate the initialization code *)
let initialization_list,
{ mem = m; instances = j; init = i; reset = r; step = s } =
Zmisc.map_fold init code init_list in
{ mem = State.seq m_code m; instances = State.seq j_code j;
init = sequence (for_loop true ix e1 e2 i_code) i;
reset = sequence (for_loop true ix e1 e2 r_code) r;
step = sequence (Osequence initialization_list)
(sequence (for_loop true ix e1 e2 s_code) s) }
| Zelus.EQbefore(before_eq_list) ->
equation_list env loop_path before_eq_list code
| Zelus.EQand _ | Zelus.EQblock _ | Zelus.EQnext _
| Zelus.EQder _ | Zelus.EQemit _ | Zelus.EQautomaton _
| Zelus.EQpresent _ -> assert false
and equation_list env loop_path eq_list code =
List.fold_right (fun eq code -> equation env loop_path eq code) eq_list code
(* Translation of a math/with handler. *)
and match_handlers env loop_path p_h_list =
let body code { Zelus.m_pat = p; Zelus.m_body = b; Zelus.m_env = m_env } =
let env, mem_acc, var_acc = append loop_path m_env env in
let { mem = m_code; step = s_code } as b_code = block env loop_path b in
{ w_pat = pattern p; w_body = letvar var_acc s_code },
seq code
{ b_code with step = Osequence []; mem = State.seq mem_acc m_code } in
Zmisc.map_fold body empty_code p_h_list
and local env loop_path { Zelus.l_eq = eq_list; Zelus.l_env = l_env } e =
let env, mem_acc, var_acc = append loop_path l_env env in
let e, code = exp env loop_path empty_code e in
let eq_code =
equation_list env loop_path eq_list { code with step = Oexp(e) } in
add_mem_vars_to_code eq_code mem_acc var_acc
and block env loop_path { Zelus.b_body = eq_list; Zelus.b_env = n_env } =
let env, mem_acc, var_acc = append loop_path n_env env in
let eq_code = equation_list env loop_path eq_list empty_code in
add_mem_vars_to_code eq_code mem_acc var_acc
and add_mem_vars_to_code ({ mem; step } as code) mem_acc var_acc =
{ code with mem = State.seq mem_acc mem; step = letvar var_acc step }
(* Define a function or a machine according to a kind [k] *)
let machine n k pat_list { mem = m; instances = j; reset = r; step = s }
ty_res =
let k = Interface.kindtype k in
match k with
| Deftypes.Tstatic _ | Deftypes.Tany
| Deftypes.Tdiscrete(false) -> Oletfun(n, pat_list, s)
| Deftypes.Tdiscrete(true) | Deftypes.Tcont | Deftypes.Tproba ->
(* the [n-1] parameters are static *)
let pat_list, p = Zmisc.firsts pat_list in
let body =
{ ma_kind = k;
ma_params = pat_list;
ma_initialize = None;
ma_memories = State.list [] m;
ma_instances = State.list [] j;
ma_methods =
[ { me_name = Oaux.reset; me_params = []; me_body = r;
me_typ = Initial.typ_unit };
{ me_name = Oaux.step; me_params = [p]; me_body = s;
me_typ = ty_res } ] } in
Oletmachine(n, body)
(* Translation of an expression. After normalisation *)
(* the body of a function is either of the form [e] with [e] stateless *)
or [ let in e ] with [ e ] stateless
let expression env ({ Zelus.e_desc = desc } as e) =
match desc with
| Zelus.Elet(l, e_let) -> local env empty_path l e_let
| _ -> let e, code = exp env empty_path empty_code e in
{ code with step = Oexp(e) }
(** Translation of a declaration *)
let implementation { Zelus.desc = desc } =
match desc with
| Zelus.Eopen(n) -> Oopen(n)
| Zelus.Etypedecl(n, params, ty_decl) ->
Otypedecl([n, params, type_of_type_decl ty_decl])
| Zelus.Econstdecl(n, _, e) ->
(* There should be no memory allocated by [e] *)
let { step = s } = expression Env.empty e in
Oletvalue(n, s)
| Zelus.Efundecl(n, { Zelus.f_kind = k; Zelus.f_args = pat_list;
Zelus.f_body = e; Zelus.f_env = f_env }) ->
let pat_list = List.map pattern pat_list in
let env, mem_acc, var_acc = append empty_path f_env Env.empty in
let code = expression env e in
let code = add_mem_vars_to_code code mem_acc var_acc in
machine n k pat_list code e.Zelus.e_typ
let implementation_list impl_list = Zmisc.iter implementation impl_list
| null | https://raw.githubusercontent.com/INRIA/zelus/685428574b0f9100ad5a41bbaa416cd7a2506d5e/compiler/gencode/translate.ml | ocaml | *********************************************************************
Zelus, a synchronous language for hybrid systems
Copyright Institut National de Recherche en Informatique et en
LICENSE file).
********************************************************************
applied to normalized and scheduled code
application
* Translation of the kind
* Translating type expressions.
is-it a mutable value? Only vectors are considered at the moment
translating an internal type into a type expression
The translation uses an environment to store information about identifiers
the symbol table
[e.(i_1)...(i_n)]
the variable [x] is implemented by [e.(i_1)...(i_n)]; e.g., [x in e]
the variable [x] is stored into [y.(i_1)...(i_n); e.g. [x out y]]
set of state variables
sequence of initializations for [mem]
set of instances
sequence of equations for resetting the block
body
* Look for an entry in the environment
* Translation of immediate values
read/write of a state variable.
index in an array
read of a variable
* Make an assignment according to the sort of a variable [n]
* Generate the code for a definition
* Generate the code for [der x = e]
* Generate an if/then
* Generate a for loop
* Generate the code for the definition of a value
* Generate the code for initializing shared variables
* Compile an equation [n += e]
* Translate size expressions
* Translate size expressions
makes an initial value from a type. returns None when it fails
try to find a value from its type definition
we do not consider type instantiation here
look for a constructor with arity 0
* Computes a default value
* Extension of an environment
The access to a state variable [x] is turned into the access on an
add a memory variable for every state variable in [l_env]
and a [letvar] declaration for every shared variable
* Translation of a stateful function application [f se1 ... sen e]
if [loop_path = [i1;...;ik]
* instance o = f se1 ... sen
* call o.(i1)...(ik).step(e)
* reset with o.(i1)...(ik).reset
create an instance
* Translation of expressions under an environment [env]
[code] is the code already generated in the context.
[exp env e code = e', code'] where [code'] extends [code] with new
memory, instantiation and reset. The step field is untouched
[loop_path = [i1;...;in]] is the loop path if [e] appears in
a nested loop forall in ... forall i1 do ... e ...
compute the sequence of static arguments and non static ones
* Patterns
* Equations
execute the initialization code when [e] is true
initialization of a state variable with a static value
look for the index [i in e1..e2]
extend the environment for in/out variables
[ix] is the index of the loop
transforms an instance into an array of instances
generate the code for the initialization part of the for loop
first compute the index [i in e1 .. e2]
extend the environment [env] with input and output variables
transforms instances into arrays
generate the initialization code
Translation of a math/with handler.
Define a function or a machine according to a kind [k]
the [n-1] parameters are static
Translation of an expression. After normalisation
the body of a function is either of the form [e] with [e] stateless
* Translation of a declaration
There should be no memory allocated by [e] | ( c ) 2020 Paris ( see the file )
Automatique . All rights reserved . This file is distributed under
the terms of the INRIA Non - Commercial License Agreement ( see the
translation from zelus code to obc
open Zmisc
open Zident
open Global
open Deftypes
open Obc
let app e_fun e_list =
match e_list with | [] -> e_fun | _ -> Oapp(e_fun, e_list)
let sequence inst1 inst2 =
match inst1, inst2 with
| (Osequence [], inst) | (inst, Osequence []) -> inst
| Osequence(l1), Osequence(l2) -> Osequence(l1 @ l2)
| _, Osequence(l2) -> Osequence(inst1 :: l2)
| _ -> Osequence [inst1; inst2]
let kind = function
| Zelus.S | Zelus.A | Zelus.AD | Zelus.AS -> Ofun
| Zelus.C | Zelus.D -> Onode | Zelus.P -> Onode
let rec type_expression { Zelus.desc = desc } =
match desc with
| Zelus.Etypevar(s) -> Otypevar(s)
| Zelus.Etypeconstr(ln, ty_list) ->
Otypeconstr(ln, List.map type_expression ty_list)
| Zelus.Etypetuple(ty_list) ->
Otypetuple(List.map type_expression ty_list)
| Zelus.Etypevec(ty, s) ->
Otypevec(type_expression ty, size s)
| Zelus.Etypefun(k, opt_name, ty_arg, ty_res) ->
Otypefun(kind k, opt_name, type_expression ty_arg, type_expression ty_res)
and type_of_type_decl { Zelus.desc = desc } =
match desc with
| Zelus.Eabstract_type -> Oabstract_type
| Zelus.Eabbrev(ty) -> Oabbrev(type_expression ty)
| Zelus.Evariant_type(constr_decl_list) ->
Ovariant_type(List.map constr_decl constr_decl_list)
| Zelus.Erecord_type(n_ty_list) ->
Orecord_type(List.map (fun (n, ty) -> (n, type_expression ty)) n_ty_list)
and constr_decl { desc = desc } =
match desc with
| Econstr0decl(n) -> Oconstr0decl(n)
| Econstr1decl(n, ty_list) ->
Oconstr1decl(n, List.map type_expression ty_list)
and size { Zelus.desc = desc } =
match desc with
| Zelus.Sconst(i) -> Sconst(i)
| Zelus.Sglobal(ln) -> Sglobal(ln)
| Zelus.Sname(n) -> Sname(n)
| Zelus.Sop(op, s1, s2) ->
let operator = function Zelus.Splus -> Splus | Zelus.Sminus -> Sminus in
Sop(operator op, size s1, size s2)
let rec is_mutable { t_desc = desc } =
match desc with
| Tvec _ -> true
| Tlink(link) -> is_mutable link
| _ -> false
let type_expression_of_typ ty =
let ty_exp = Interface.type_expression_of_typ ty in
type_expression ty_exp
and entry =
{ e_typ: Deftypes.typ;
e_sort: sort;
}
and sort =
| In of exp
| Out of Zident.t * Deftypes.tsort
and loop_path = Zident.t list
type code =
}
let fprint ff (env: entry Env.t) =
let fprint_entry ff { e_typ = ty; e_sort = sort; e_size = size } =
Format.fprintf ff "@[{ typ = %a;@,size = %a}@]"
Ptypes.output ty
(Pp_tools.print_list_r Printer.name "[" "," "]") size in
Zident.Env.fprint_t fprint_entry ff env
let empty_code = { mem = State.empty; init = Osequence [];
instances = State.empty;
reset = Osequence []; step = Osequence [] }
let seq { mem = m1; init = i1; instances = j1; reset = r1; step = s1 }
{ mem = m2; init = i2; instances = j2; reset = r2; step = s2 } =
{ mem = State.seq m1 m2; init = sequence i1 i2; instances = State.par j1 j2;
reset = sequence r1 r2; step = sequence s1 s2 }
let empty_path = []
let entry_of n env =
try
Env.find n env
with Not_found ->
Zmisc.internal_error "Unbound variable" Printer.name n
let immediate = function
| Deftypes.Eint(i) -> Oint(i)
| Deftypes.Efloat(f) -> Ofloat(f)
| Deftypes.Ebool(b) -> Obool(b)
| Deftypes.Echar(c) -> Ochar(c)
| Deftypes.Estring(s) -> Ostring(s)
| Deftypes.Evoid -> Ovoid
let constant = function
| Deftypes.Cimmediate(i) -> Oconst(immediate i)
| Deftypes.Cglobal(ln) -> Oglobal(ln)
let state is_read n k =
match k with
| None -> Oleft_state_name(n)
| Some(k) ->
match k with
| Deftypes.Cont ->
Oleft_state_primitive_access (Oleft_state_name(n), Ocont)
| Deftypes.Zero ->
Oleft_state_primitive_access
(Oleft_state_name(n), if is_read then Ozero_in else Ozero_out)
| Deftypes.Horizon | Deftypes.Period
| Deftypes.Encore | Deftypes.Major -> Oleft_state_name(n)
let rec index e =
function [] -> e | ei :: ei_list -> Oaccess(index e ei_list, Olocal(ei))
let rec left_value_index lv =
function
| [] -> lv
| ei :: ei_list -> Oleft_index(left_value_index lv ei_list, Olocal(ei))
let rec left_state_value_index lv = function
| [] -> lv
| ei :: ei_list ->
Oleft_state_index(left_state_value_index lv ei_list, Olocal(ei))
let var { e_sort = sort; e_typ = ty; e_size = ei_list } =
match sort with
| In(e) -> index e ei_list
| Out(n, sort) ->
match sort with
| Sstatic | Sval -> index (Olocal(n)) ei_list
| Svar _ ->
index (Ovar(is_mutable ty, n)) ei_list
| Smem { m_kind = k } ->
Ostate(left_state_value_index (state true n k) ei_list)
let assign { e_sort = sort; e_size = ei_list } e =
match sort with
| In _ -> assert false
| Out(n, sort) ->
match sort with
| Sstatic | Sval -> assert false
| Svar _ -> Oassign(left_value_index (Oleft_name n) ei_list, e)
| Smem { m_kind = k } ->
Oassign_state(left_state_value_index (state false n k) ei_list, e)
let def { e_typ = ty; e_sort = sort; e_size = ei_list } e
({ step = s } as code) =
match sort with
| In _ -> assert false
| Out(n, sort) ->
match sort with
| Sstatic | Sval ->
{ code with step =
Olet(Ovarpat(n, type_expression_of_typ ty), e, s) }
| Svar _ ->
{ code with step =
sequence
(Oassign(left_value_index (Oleft_name n) ei_list, e))
s }
| Smem { m_kind = k } ->
{ code with step = sequence
(Oassign_state(left_state_value_index
(state false n k) ei_list, e)) s }
let der { e_sort = sort; e_size = ei_list } e ({ step = s } as code) =
match sort with
| In _ -> assert false
| Out(n, sort) ->
{ code with step =
sequence
(Oassign_state(left_state_value_index
(Oleft_state_primitive_access
(Oleft_state_name(n), Oder)) ei_list,
e))
s }
let ifthen r_e i_code s = sequence (Oif(r_e, i_code, None)) s
let for_loop direction ix e1 e2 i_body =
match i_body with
| Osequence [] -> Osequence []
| _ -> Ofor(direction, ix, e1, e2, i_body)
let letpat p e ({ step = s } as code) =
{ code with step = Olet(p, e, s) }
let rec letvar l s =
match l with
| [] -> s
| (n, is_mutable, ty, v_opt) :: l ->
Oletvar(n, is_mutable, ty, v_opt, letvar l s)
let pluseq ({ e_sort = sort; e_size = ei_list } as entry)
e ({ step = s } as code) =
let ln =
match sort with
| In _ -> assert false
| Out(n, sort) ->
match sort with
| Svar { v_combine = Some(ln) } | Smem { m_combine = Some(ln) } -> ln
| _ -> Zmisc.internal_error "Unbound variable" Printer.name n in
{ code with step =
sequence (assign entry
(Oapp(Oglobal(ln), [var entry; e]))) s }
let out_of n env =
let { e_typ = ty; e_sort = sort; e_size = ix_list } = entry_of n env in
match sort with
| In _ -> assert false
| Out(x, sort) -> x, ty, sort, ix_list
let rec size_of_type = function
| Tconst(i) -> Sconst(i)
| Tglobal(q) -> Sglobal(Lident.Modname(q))
| Tname(n) -> Sname(n)
| Top(op, s1, s2) ->
let e1 = size_of_type s1 in
let e2 = size_of_type s2 in
match op with
| Tplus -> Sop(Splus, e1, e2)
| Tminus -> Sop(Sminus, e1, e2)
let rec size { Zelus.desc = desc } =
match desc with
| Zelus.Sconst(i) -> Sconst(i)
| Zelus.Sglobal(ln) -> Sglobal(ln)
| Zelus.Sname n -> Sname(n)
| Zelus.Sop(op, s1, s2) ->
let s1 = size s1 in
let s2 = size s2 in
match op with
| Zelus.Splus -> Sop(Splus, s1, s2)
| Zelus.Sminus -> Sop(Sminus, s1, s2)
let choose env ty =
let tuple l = Otuple(l) in
let efalse = Oconst(Obool(false)) in
let echar0 = Oconst(Ochar('a')) in
on purpose , take an initial value different from zero
let ezero = Oconst(Oint(42)) in
let efzero = Oconst(Ofloat(42.0)) in
let estring0 = Oconst(Ostring("aaaaaaa")) in
let evoid = Oconst(Ovoid) in
let eany = Oconst(Oany) in
let vec e s = Ovec(e, s) in
let rec value_from_deftype id =
try
let { info = { type_desc = ty_c } } =
Modules.find_type (Lident.Modname(id)) in
match ty_c with
| Variant_type(g_list) -> value_from_variant_list g_list
| Abstract_type -> eany
| Record_type(l_list) ->
Orecord(
List.map
(fun { qualid = qualid; info = { label_res = ty } } ->
(Lident.Modname(qualid), value ty)) l_list)
| Abbrev(_, ty) -> value ty
with
| Not_found -> eany
and value ty =
match ty.t_desc with
| Tvar -> eany
| Tproduct(ty_l) -> tuple (List.map value ty_l)
| Tfun _ -> eany
| Tvec(ty, s) -> vec (value ty) (size_of_type s)
| Tconstr(id, _, _) ->
if id = Initial.int_ident then ezero
else if id = Initial.bool_ident then efalse
else if id = Initial.char_ident then echar0
else if id = Initial.float_ident then efzero
else if id = Initial.string_ident then estring0
else if id = Initial.unit_ident then evoid
else if id = Initial.zero_ident then efalse
else
value_from_deftype id
| Tlink(link) -> value link
and value_from_variant_list g_list =
let rec findrec g_list =
match g_list with
| [] -> raise Not_found
| { qualid = qualid; info = { constr_arity = arity } } :: g_list ->
if arity = 0 then Oconstr0(Lident.Modname(qualid))
else findrec g_list in
try
findrec g_list
with
| Not_found ->
otherwise , pick one
let { qualid = qualid; info = { constr_arg = ty_list } } =
List.hd g_list in
Oconstr1(Lident.Modname(qualid), List.map value ty_list) in
Some(value ty)
let default env ty v_opt =
match v_opt with
| None -> choose env ty
| Some(v) -> Some(constant v)
array access x.(i1) ... ) if loop_path = [ i1; ... ;in ]
let append loop_path l_env env =
let addrec n { t_sort = k; t_typ = ty } (env_acc, mem_acc, var_acc) =
match k with
| Sstatic
| Sval ->
Env.add n { e_typ = ty; e_sort = Out(n, k); e_size = [] } env_acc,
mem_acc, var_acc
| Svar { v_default = v_opt } ->
Env.add n { e_typ = ty; e_sort = Out(n, k); e_size = [] } env_acc,
mem_acc, (n, is_mutable ty, ty, default env ty v_opt) :: var_acc
| Smem { m_kind = k_opt } ->
Env.add n
{ e_typ = ty; e_sort = Out(n, k); e_size = loop_path } env_acc,
State.cons { m_name = n; m_value = choose env ty; m_typ = ty;
m_kind = k_opt; m_size = [] } mem_acc,
var_acc in
Env.fold addrec l_env (env, State.empty, [])
let apply k env loop_path e e_list
({ mem = m; init = i; instances = j; reset = r; step = s } as code) =
match k with
| Deftypes.Tstatic _
| Deftypes.Tany | Deftypes.Tdiscrete(false) -> Oapp(e, e_list), code
| Deftypes.Tdiscrete(true)
| Deftypes.Tcont
| Deftypes.Tproba ->
the first [ n-1 ] arguments are static
let se_list, arg = Zmisc.firsts e_list in
let f_opt = match e with | Oglobal(g) -> Some(g) | _ -> None in
let loop_path = List.map (fun ix -> Olocal(ix)) loop_path in
let o = Zident.fresh "i" in
let j_code = { i_name = o; i_machine = e; i_kind = k;
i_params = se_list; i_size = [] } in
let reset_code =
Omethodcall({ met_machine = f_opt; met_name = Oaux.reset;
met_instance = Some(o, loop_path); met_args = [] }) in
let step_code =
Omethodcall({ met_machine = f_opt; met_name = Oaux.step;
met_instance = Some(o, loop_path); met_args = [arg] }) in
step_code,
{ code with instances = State.cons j_code j;
init = sequence (Oexp(reset_code)) i;
reset = sequence (Oexp(reset_code)) r }
let rec exp env loop_path code { Zelus.e_desc = desc } =
match desc with
| Zelus.Econst(i) -> Oconst(immediate i), code
| Zelus.Elocal(n)
| Zelus.Elast(n) -> var (entry_of n env), code
| Zelus.Eglobal { lname = ln } -> Oglobal(ln), code
| Zelus.Econstr0(ln) -> Oconstr0(ln), code
| Zelus.Econstr1(ln, e_list) ->
let e_list, code = Zmisc.map_fold (exp env loop_path) code e_list in
Oconstr1(ln, e_list), code
| Zelus.Etuple(e_list) ->
let e_list, code = Zmisc.map_fold (exp env loop_path) code e_list in
Otuple(e_list), code
| Zelus.Erecord(label_e_list) ->
let label_e_list, code =
Zmisc.map_fold
(fun code (l, e) -> let e, code = exp env loop_path code e in
(l, e), code) code label_e_list in
Orecord(label_e_list), code
| Zelus.Erecord_access(e_record, longname) ->
let e_record, code =
exp env loop_path code e_record in
Orecord_access(e_record, longname), code
| Zelus.Erecord_with(e_record, label_e_list) ->
let e_record, code =
exp env loop_path code e_record in
let label_e_list, code =
Zmisc.map_fold
(fun code (l, e) -> let e, code = exp env loop_path code e in
(l, e), code) code label_e_list in
Orecord_with(e_record, label_e_list), code
| Zelus.Etypeconstraint(e, ty_exp) ->
let e, code = exp env loop_path code e in
let ty_exp = type_expression ty_exp in
Otypeconstraint(e, ty_exp), code
| Zelus.Eop(Zelus.Eup, [e]) ->
implement the zero - crossing up(x ) by up(if x > = 0 then 1 else -1 )
let e = if !Zmisc.zsign then Zaux.sgn e else e in
exp env loop_path code e
| Zelus.Eop(Zelus.Ehorizon, [e]) ->
exp env loop_path code e
| Zelus.Eop(Zelus.Eifthenelse, [e1; e2; e3]) ->
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
let e3, code = exp env loop_path code e3 in
Oifthenelse(e1, e2, e3), code
| Zelus.Eop(Zelus.Eaccess, [e1; e2]) ->
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
Oaccess(e1, e2), code
| Zelus.Eop(Zelus.Eupdate, [e1; i; e2]) ->
let _, se = Ztypes.filter_vec e1.Zelus.e_typ in
let se = size_of_type se in
let e1, code = exp env loop_path code e1 in
let i, code = exp env loop_path code i in
let e2, code = exp env loop_path code e2 in
Oupdate(se, e1, i, e2), code
| Zelus.Eop(Zelus.Eslice(s1, s2), [e]) ->
let s1 = size s1 in
let s2 = size s2 in
let e, code = exp env loop_path code e in
Oslice(e, s1, s2), code
| Zelus.Eop(Zelus.Econcat, [e1; e2]) ->
let _, s1 = Ztypes.filter_vec e1.Zelus.e_typ in
let _, s2 = Ztypes.filter_vec e2.Zelus.e_typ in
let s1 = size_of_type s1 in
let s2 = size_of_type s2 in
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
Oconcat(e1, s1, e2, s2), code
| Zelus.Eop(Zelus.Eatomic, [e]) ->
exp env loop_path code e
| Zelus.Elet _ | Zelus.Eseq _ | Zelus.Eperiod _
| Zelus.Eop _ | Zelus.Epresent _
| Zelus.Ematch _ | Zelus.Eblock _ -> assert false
| Zelus.Eapp(_, e_fun, e_list) ->
let se_list, ne_list, ty_res =
Ztypes.split_arguments e_fun.Zelus.e_typ e_list in
let e_fun, code = exp env loop_path code e_fun in
let se_list, code = Zmisc.map_fold (exp env loop_path) code se_list in
let ne_list, code = Zmisc.map_fold (exp env loop_path) code ne_list in
let e_fun = app e_fun se_list in
match ne_list with
| [] -> e_fun, code
| _ -> let k = Ztypes.kind_of_funtype ty_res in
apply k env loop_path e_fun ne_list code
and pattern { Zelus.p_desc = desc; Zelus.p_typ = ty } =
match desc with
| Zelus.Ewildpat -> Owildpat
| Zelus.Econstpat(im) -> Oconstpat(immediate im)
| Zelus.Econstr0pat(c0) -> Oconstr0pat(c0)
| Zelus.Econstr1pat(c1, p_list) ->
Oconstr1pat(c1, List.map pattern p_list)
| Zelus.Etuplepat(p_list) -> Otuplepat(List.map pattern p_list)
| Zelus.Evarpat(n) -> Ovarpat(n, type_expression_of_typ ty)
| Zelus.Erecordpat(label_pat_list) ->
Orecordpat(List.map (fun (label, pat) -> (label, pattern pat))
label_pat_list)
| Zelus.Etypeconstraintpat(p, ty) ->
Otypeconstraintpat(pattern p, type_expression ty)
| Zelus.Ealiaspat(p, n) -> Oaliaspat(pattern p, n)
| Zelus.Eorpat(p1, p2) -> Oorpat(pattern p1, pattern p2)
let rec equation env loop_path { Zelus.eq_desc = desc } code =
match desc with
| Zelus.EQeq({ Zelus.p_desc = Zelus.Evarpat(n) }, e) ->
let e, code = exp env loop_path code e in
def (entry_of n env) e code
| Zelus.EQeq(p, e) ->
let e, code = exp env loop_path code e in
letpat (pattern p) e code
| Zelus.EQpluseq(n, e) ->
let e, code = exp env loop_path code e in
pluseq (entry_of n env) e code
| Zelus.EQder(n, e, None, []) ->
let e, code = exp env loop_path code e in
der (entry_of n env) e code
| Zelus.EQmatch(_, e, p_h_list) ->
let e, code = exp env loop_path code e in
let p_step_h_list, p_h_code = match_handlers env loop_path p_h_list in
seq { p_h_code with step = Omatch(e, p_step_h_list) } code
| Zelus.EQreset([{ Zelus.eq_desc = Zelus.EQinit(x, e) }], r_e)
when not (Reset.static e) ->
let r_e, code = exp env loop_path code r_e in
let e, ({ init = i_code } as e_code) = exp env loop_path empty_code e in
let { step = s } as code = seq e_code code in
{ code with step =
ifthen r_e (sequence (assign (entry_of x env) e) i_code) s }
| Zelus.EQreset(eq_list, r_e) ->
let { init = i_code } = code in
let { init = ri_code } as r_code =
equation_list env loop_path eq_list { code with init = Osequence [] } in
let r_e, r_code = exp env loop_path r_code r_e in
let { step = s } as code = seq r_code { empty_code with init = i_code } in
{ code with step = ifthen r_e ri_code s }
| Zelus.EQinit(x, e) ->
let e_c, code = exp env loop_path code e in
let x_e = assign (entry_of x env) e_c in
if Reset.static e
then seq { empty_code with init = x_e; reset = x_e } code
else seq { empty_code with step = x_e } code
| Zelus.EQforall { Zelus.for_index = i_list; Zelus.for_init = init_list;
Zelus.for_body = b_eq_list } ->
[ forall i in e1 .. e2 , xi in , ... , oi in o , ... do body done ]
* is translated into :
* for i = e1 to e2 do
...
* with xi into ei.(i ) , oi into o.(i )
* - every instance o from the body must be an array
* - every state variable m from the body must be an array
* is translated into:
* for i = e1 to e2 do
...
* with xi into ei.(i), oi into o.(i)
* - every instance o from the body must be an array
* - every state variable m from the body must be an array *)
let rec index code = function
| [] -> let id = Zident.fresh "i" in
(id, Oconst(Oint(0)), Oconst(Oint(0))), code
| { Zelus.desc = desc } :: i_list ->
match desc with
| Zelus.Eindex(x, e1, e2) ->
let e1, code = exp env loop_path code e1 in
let e2, code = exp env loop_path code e2 in
(x, e1, e2), code
| Zelus.Einput _ | Zelus.Eoutput _ -> index code i_list in
let in_out ix (env_acc, code) { Zelus.desc = desc } =
match desc with
| Zelus.Einput(x, ({ Zelus.e_typ = ty } as e)) ->
let e, code = exp env loop_path code e in
Env.add x { e_typ = ty; e_sort = In(e); e_size = [ix] } env_acc, code
| Zelus.Eoutput(x, y) ->
let y, ty, sort, ix_list = out_of y env in
Env.add x { e_typ = ty; e_sort = Out(y, sort);
e_size = ix :: ix_list } env_acc, code
| Zelus.Eindex(i, { Zelus.e_typ = ty }, _) ->
Env.add i { e_typ = ty; e_sort = Out(i, Deftypes.Sval);
e_size = [] } env_acc, code in
let array_of_instance size ({ i_size } as ientry) =
{ ientry with i_size = size :: i_size } in
let array_of_memory size ({ m_size } as mentry) =
{ mentry with m_size = size :: m_size } in
let init code { Zelus.desc = desc } =
match desc with
| Zelus.Einit_last(x, e) ->
let e, code = exp env loop_path code e in
assign (entry_of x env) e, code in
let (ix, e1, e2), code = index code i_list in
let env, code = List.fold_left (in_out ix) (env, code) i_list in
let { mem = m_code; init = i_code; instances = j_code;
reset = r_code; step = s_code } =
block env (ix :: loop_path) b_eq_list in
let j_code =
State.map
(array_of_instance (Oaux.plus (Oaux.minus e2 e1) Oaux.one)) j_code in
let m_code =
State.map
(array_of_memory (Oaux.plus (Oaux.minus e2 e1) Oaux.one)) m_code in
let initialization_list,
{ mem = m; instances = j; init = i; reset = r; step = s } =
Zmisc.map_fold init code init_list in
{ mem = State.seq m_code m; instances = State.seq j_code j;
init = sequence (for_loop true ix e1 e2 i_code) i;
reset = sequence (for_loop true ix e1 e2 r_code) r;
step = sequence (Osequence initialization_list)
(sequence (for_loop true ix e1 e2 s_code) s) }
| Zelus.EQbefore(before_eq_list) ->
equation_list env loop_path before_eq_list code
| Zelus.EQand _ | Zelus.EQblock _ | Zelus.EQnext _
| Zelus.EQder _ | Zelus.EQemit _ | Zelus.EQautomaton _
| Zelus.EQpresent _ -> assert false
and equation_list env loop_path eq_list code =
List.fold_right (fun eq code -> equation env loop_path eq code) eq_list code
and match_handlers env loop_path p_h_list =
let body code { Zelus.m_pat = p; Zelus.m_body = b; Zelus.m_env = m_env } =
let env, mem_acc, var_acc = append loop_path m_env env in
let { mem = m_code; step = s_code } as b_code = block env loop_path b in
{ w_pat = pattern p; w_body = letvar var_acc s_code },
seq code
{ b_code with step = Osequence []; mem = State.seq mem_acc m_code } in
Zmisc.map_fold body empty_code p_h_list
and local env loop_path { Zelus.l_eq = eq_list; Zelus.l_env = l_env } e =
let env, mem_acc, var_acc = append loop_path l_env env in
let e, code = exp env loop_path empty_code e in
let eq_code =
equation_list env loop_path eq_list { code with step = Oexp(e) } in
add_mem_vars_to_code eq_code mem_acc var_acc
and block env loop_path { Zelus.b_body = eq_list; Zelus.b_env = n_env } =
let env, mem_acc, var_acc = append loop_path n_env env in
let eq_code = equation_list env loop_path eq_list empty_code in
add_mem_vars_to_code eq_code mem_acc var_acc
and add_mem_vars_to_code ({ mem; step } as code) mem_acc var_acc =
{ code with mem = State.seq mem_acc mem; step = letvar var_acc step }
let machine n k pat_list { mem = m; instances = j; reset = r; step = s }
ty_res =
let k = Interface.kindtype k in
match k with
| Deftypes.Tstatic _ | Deftypes.Tany
| Deftypes.Tdiscrete(false) -> Oletfun(n, pat_list, s)
| Deftypes.Tdiscrete(true) | Deftypes.Tcont | Deftypes.Tproba ->
let pat_list, p = Zmisc.firsts pat_list in
let body =
{ ma_kind = k;
ma_params = pat_list;
ma_initialize = None;
ma_memories = State.list [] m;
ma_instances = State.list [] j;
ma_methods =
[ { me_name = Oaux.reset; me_params = []; me_body = r;
me_typ = Initial.typ_unit };
{ me_name = Oaux.step; me_params = [p]; me_body = s;
me_typ = ty_res } ] } in
Oletmachine(n, body)
or [ let in e ] with [ e ] stateless
let expression env ({ Zelus.e_desc = desc } as e) =
match desc with
| Zelus.Elet(l, e_let) -> local env empty_path l e_let
| _ -> let e, code = exp env empty_path empty_code e in
{ code with step = Oexp(e) }
let implementation { Zelus.desc = desc } =
match desc with
| Zelus.Eopen(n) -> Oopen(n)
| Zelus.Etypedecl(n, params, ty_decl) ->
Otypedecl([n, params, type_of_type_decl ty_decl])
| Zelus.Econstdecl(n, _, e) ->
let { step = s } = expression Env.empty e in
Oletvalue(n, s)
| Zelus.Efundecl(n, { Zelus.f_kind = k; Zelus.f_args = pat_list;
Zelus.f_body = e; Zelus.f_env = f_env }) ->
let pat_list = List.map pattern pat_list in
let env, mem_acc, var_acc = append empty_path f_env Env.empty in
let code = expression env e in
let code = add_mem_vars_to_code code mem_acc var_acc in
machine n k pat_list code e.Zelus.e_typ
let implementation_list impl_list = Zmisc.iter implementation impl_list
|
d04774b7883912f6c024d4155a287893a9811b6013b1fd19c4acc7bca4fd636c | screenshotbot/screenshotbot-oss | test-object.lisp | ;;;; Copyright 2018-Present Modern Interpreters Inc.
;;;;
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 /.
(uiop:define-package :screenshotbot/model/test-object
(:use #:cl #:alexandria)
(:import-from #:bknr.datastore
#:store-object
#:persistent-class)
(:import-from #:util/store
#:with-class-validation)
(:export #:test-object))
(in-package :screenshotbot/model/test-object)
(with-class-validation
(defclass test-object (store-object)
()
(:metaclass persistent-class)))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/053a95a8ac234b20b12d4182dccc3065e594ee53/src/screenshotbot/model/test-object.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
| 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 /.
(uiop:define-package :screenshotbot/model/test-object
(:use #:cl #:alexandria)
(:import-from #:bknr.datastore
#:store-object
#:persistent-class)
(:import-from #:util/store
#:with-class-validation)
(:export #:test-object))
(in-package :screenshotbot/model/test-object)
(with-class-validation
(defclass test-object (store-object)
()
(:metaclass persistent-class)))
|
34018ffbb4b8c32d27d8c53c15e25c94fc3bd10dc08c9b3977ca869d57e20cd6 | dsheets/gloc | jssl.ml | open Printf
open Quot
type ('c,'sv,'dv) repr = ('c,'sv,'dv) code
let bool b = literal (string_of_bool b)
let float f = literal (string_of_float f)
let lam fn = func fn
let app = function
| `Fn f ->
if f#bound then (fun a -> literal (sprintf "%s(%s)" f#name (v a)))
else f#fn
| `Lit _ -> raise (Type_error "Cannot apply literal")
let (&&) a b = literal (sprintf "(%s && %s)" (v a) (v b))
let (||) a b = literal (sprintf "(%s || %s)" (v a) (v b))
let (+:) x y = literal (sprintf "(%s + %s)" (v x) (v y))
let (-:) x y = literal (sprintf "(%s - %s)" (v x) (v y))
let ( *:)x y = literal (sprintf "(%s * %s)" (v x) (v y))
let (/:) x y = literal (sprintf "(%s / %s)" (v x) (v y))
let sqrt f = literal (sprintf "Math.sqrt(%s)" (v f))
let leqf x y = literal (sprintf "(%s <= %s)" (v x) (v y))
let bind name v = v#bind name
let run r = r#string
| null | https://raw.githubusercontent.com/dsheets/gloc/d5917c072ec314ae93a61344da2407f520fac1b5/sketch/jssl.ml | ocaml | open Printf
open Quot
type ('c,'sv,'dv) repr = ('c,'sv,'dv) code
let bool b = literal (string_of_bool b)
let float f = literal (string_of_float f)
let lam fn = func fn
let app = function
| `Fn f ->
if f#bound then (fun a -> literal (sprintf "%s(%s)" f#name (v a)))
else f#fn
| `Lit _ -> raise (Type_error "Cannot apply literal")
let (&&) a b = literal (sprintf "(%s && %s)" (v a) (v b))
let (||) a b = literal (sprintf "(%s || %s)" (v a) (v b))
let (+:) x y = literal (sprintf "(%s + %s)" (v x) (v y))
let (-:) x y = literal (sprintf "(%s - %s)" (v x) (v y))
let ( *:)x y = literal (sprintf "(%s * %s)" (v x) (v y))
let (/:) x y = literal (sprintf "(%s / %s)" (v x) (v y))
let sqrt f = literal (sprintf "Math.sqrt(%s)" (v f))
let leqf x y = literal (sprintf "(%s <= %s)" (v x) (v y))
let bind name v = v#bind name
let run r = r#string
| |
680854f3f85f251e9367452877a276da0137bb27e1a4de552c3c6c294cab900f | diagrams/diagrams-lib | Align.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.ThreeD.Align
Copyright : ( c ) 2013 diagrams - lib team ( see LICENSE )
-- License : BSD-style (see LICENSE)
-- Maintainer :
--
Alignment combinators specialized for three dimensions . See
" Diagrams . Align " for more general alignment combinators .
--
-- The basic idea is that alignment is achieved by moving diagrams'
-- local origins relative to their envelopes or traces (or some other
-- sort of boundary). For example, to align several diagrams along
their tops , we first move their local origins to the upper edge of
-- their boundary (using e.g. @map 'alignZMax'@), and then put them
-- together with their local origins along a line (using e.g. 'cat'
from " Diagrams . Combinators " ) .
--
-----------------------------------------------------------------------------
module Diagrams.ThreeD.Align
( -- * Absolute alignment
-- ** Align by envelope
alignXMin, alignXMax, alignYMin, alignYMax, alignZMin, alignZMax
-- ** Align by trace
, snugXMin, snugXMax, snugYMin, snugYMax, snugZMin, snugZMax
-- * Relative alignment
, alignX, snugX, alignY, snugY, alignZ, snugZ
-- * Centering
, centerX, centerY, centerZ
, centerXY, centerXZ, centerYZ, centerXYZ
, snugCenterX, snugCenterY, snugCenterZ
, snugCenterXY, snugCenterXZ, snugCenterYZ, snugCenterXYZ
) where
import Diagrams.Core
import Diagrams.Align
import Diagrams.ThreeD.Types
import Diagrams.ThreeD.Vector
import Diagrams.TwoD.Align
-- | Translate the diagram along unitX so that all points have
-- positive x-values.
alignXMin :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignXMin = align unit_X
snugXMin :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugXMin = snug unit_X
-- | Translate the diagram along unitX so that all points have
-- negative x-values.
alignXMax :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignXMax = align unitX
snugXMax :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugXMax = snug unitX
-- | Translate the diagram along unitY so that all points have
-- positive y-values.
alignYMin :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignYMin = align unit_Y
snugYMin :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugYMin = snug unit_Y
-- | Translate the diagram along unitY so that all points have
-- negative y-values.
alignYMax :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignYMax = align unitY
snugYMax :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugYMax = snug unitY
-- | Translate the diagram along unitZ so that all points have
-- positive z-values.
alignZMin :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignZMin = align unit_Z
snugZMin :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugZMin = snug unit_Z
-- | Translate the diagram along unitZ so that all points have
-- negative z-values.
alignZMax :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignZMax = align unitZ
snugZMax :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugZMax = snug unitZ
-- | Like 'alignX', but moving the local origin in the Z direction, with an
argument of @1@ corresponding to the top edge and @(-1)@ corresponding
-- to the bottom edge.
alignZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => n -> a -> a
alignZ = alignBy unitZ
-- | See the documentation for 'alignZ'.
snugZ :: (V a ~ v, N a ~ n, Alignable a, Traced a, HasOrigin a,
R3 v, Fractional n) => n -> a -> a
snugZ = snugBy unitZ
-- | Center the local origin along the Z-axis.
centerZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerZ = alignBy unitZ 0
snugCenterZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterZ = snugBy unitZ 0
-- | Center along both the X- and Z-axes.
centerXZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerXZ = centerX . centerZ
snugCenterXZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterXZ = snugCenterX . snugCenterZ
-- | Center along both the Y- and Z-axes.
centerYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerYZ = centerZ . centerY
snugCenterYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterYZ = snugCenterZ . snugCenterY
| Center an object in three dimensions .
centerXYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerXYZ = centerX . centerY . centerZ
snugCenterXYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterXYZ = snugCenterX . snugCenterY . snugCenterZ
| null | https://raw.githubusercontent.com/diagrams/diagrams-lib/6f66ce6bd5aed81d8a1330c143ea012724dbac3c/src/Diagrams/ThreeD/Align.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE TypeFamilies #
---------------------------------------------------------------------------
|
Module : Diagrams.ThreeD.Align
License : BSD-style (see LICENSE)
Maintainer :
The basic idea is that alignment is achieved by moving diagrams'
local origins relative to their envelopes or traces (or some other
sort of boundary). For example, to align several diagrams along
their boundary (using e.g. @map 'alignZMax'@), and then put them
together with their local origins along a line (using e.g. 'cat'
---------------------------------------------------------------------------
* Absolute alignment
** Align by envelope
** Align by trace
* Relative alignment
* Centering
| Translate the diagram along unitX so that all points have
positive x-values.
| Translate the diagram along unitX so that all points have
negative x-values.
| Translate the diagram along unitY so that all points have
positive y-values.
| Translate the diagram along unitY so that all points have
negative y-values.
| Translate the diagram along unitZ so that all points have
positive z-values.
| Translate the diagram along unitZ so that all points have
negative z-values.
| Like 'alignX', but moving the local origin in the Z direction, with an
to the bottom edge.
| See the documentation for 'alignZ'.
| Center the local origin along the Z-axis.
| Center along both the X- and Z-axes.
| Center along both the Y- and Z-axes. |
Copyright : ( c ) 2013 diagrams - lib team ( see LICENSE )
Alignment combinators specialized for three dimensions . See
" Diagrams . Align " for more general alignment combinators .
their tops , we first move their local origins to the upper edge of
from " Diagrams . Combinators " ) .
module Diagrams.ThreeD.Align
alignXMin, alignXMax, alignYMin, alignYMax, alignZMin, alignZMax
, snugXMin, snugXMax, snugYMin, snugYMax, snugZMin, snugZMax
, alignX, snugX, alignY, snugY, alignZ, snugZ
, centerX, centerY, centerZ
, centerXY, centerXZ, centerYZ, centerXYZ
, snugCenterX, snugCenterY, snugCenterZ
, snugCenterXY, snugCenterXZ, snugCenterYZ, snugCenterXYZ
) where
import Diagrams.Core
import Diagrams.Align
import Diagrams.ThreeD.Types
import Diagrams.ThreeD.Vector
import Diagrams.TwoD.Align
alignXMin :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignXMin = align unit_X
snugXMin :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugXMin = snug unit_X
alignXMax :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignXMax = align unitX
snugXMax :: (InSpace v n a, R1 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugXMax = snug unitX
alignYMin :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignYMin = align unit_Y
snugYMin :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugYMin = snug unit_Y
alignYMax :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignYMax = align unitY
snugYMax :: (InSpace v n a, R2 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugYMax = snug unitY
alignZMin :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignZMin = align unit_Z
snugZMin :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugZMin = snug unit_Z
alignZMax :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
alignZMax = align unitZ
snugZMax :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugZMax = snug unitZ
argument of @1@ corresponding to the top edge and @(-1)@ corresponding
alignZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => n -> a -> a
alignZ = alignBy unitZ
snugZ :: (V a ~ v, N a ~ n, Alignable a, Traced a, HasOrigin a,
R3 v, Fractional n) => n -> a -> a
snugZ = snugBy unitZ
centerZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerZ = alignBy unitZ 0
snugCenterZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterZ = snugBy unitZ 0
centerXZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerXZ = centerX . centerZ
snugCenterXZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterXZ = snugCenterX . snugCenterZ
centerYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerYZ = centerZ . centerY
snugCenterYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterYZ = snugCenterZ . snugCenterY
| Center an object in three dimensions .
centerXYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a) => a -> a
centerXYZ = centerX . centerY . centerZ
snugCenterXYZ :: (InSpace v n a, R3 v, Fractional n, Alignable a, HasOrigin a, Traced a) => a -> a
snugCenterXYZ = snugCenterX . snugCenterY . snugCenterZ
|
1295d76c7dd84743f91258b8a11c7aa78320663ff83d50c1377de3067e1dd7a2 | jaspervdj/b-tree | Invariants.hs | -- | A number of invariant checks on the B-tree type
module Data.BTree.Invariants
( invariants
, nodeSizeInvariant
, balancingInvariant
) where
import Data.BTree.Internal
import qualified Data.BTree.Array as A
-- | Check all invariants
invariants :: BTree k v -> Bool
invariants btree = all ($ btree) [nodeSizeInvariant, balancingInvariant]
-- | Size of the root node (number of keys in it)
rootSize :: BTree k v -> Int
rootSize (Leaf s _ _) = s
rootSize (Node s _ _ _) = s
-- | Get the children of the root node as a list
rootChildren :: BTree k v -> [BTree k v]
rootChildren (Leaf _ _ _) = []
rootChildren (Node s _ _ c) = A.toList (s + 1) c
-- | Check if a tree is a leaf
isLeaf :: BTree k v -> Bool
isLeaf (Leaf _ _ _) = True
isLeaf _ = False
-- | Check that each node contains enough keys
nodeSizeInvariant :: BTree k v -> Bool
nodeSizeInvariant = all nodeSizeInvariant' . rootChildren
where
nodeSizeInvariant' btree =
invariant (rootSize btree) &&
all nodeSizeInvariant' (rootChildren btree)
invariant s
| s >= maxNodeSize `div` 2 && s <= maxNodeSize = True
| otherwise = False
-- | Check for perfect balancing
balancingInvariant :: BTree k v -> Bool
balancingInvariant = equal . depths
where
-- Check if all elements in a list are equal
equal (x : y : t) = x == y && equal (y : t)
equal _ = True
-- Depths of all leaves
depths tree
| isLeaf tree = [0 :: Int]
| otherwise = rootChildren tree >>= map (+ 1) . depths
| null | https://raw.githubusercontent.com/jaspervdj/b-tree/0f1cc1ccf9538c399fe4f7979565ad132b81764a/tests/Data/BTree/Invariants.hs | haskell | | A number of invariant checks on the B-tree type
| Check all invariants
| Size of the root node (number of keys in it)
| Get the children of the root node as a list
| Check if a tree is a leaf
| Check that each node contains enough keys
| Check for perfect balancing
Check if all elements in a list are equal
Depths of all leaves | module Data.BTree.Invariants
( invariants
, nodeSizeInvariant
, balancingInvariant
) where
import Data.BTree.Internal
import qualified Data.BTree.Array as A
invariants :: BTree k v -> Bool
invariants btree = all ($ btree) [nodeSizeInvariant, balancingInvariant]
rootSize :: BTree k v -> Int
rootSize (Leaf s _ _) = s
rootSize (Node s _ _ _) = s
rootChildren :: BTree k v -> [BTree k v]
rootChildren (Leaf _ _ _) = []
rootChildren (Node s _ _ c) = A.toList (s + 1) c
isLeaf :: BTree k v -> Bool
isLeaf (Leaf _ _ _) = True
isLeaf _ = False
nodeSizeInvariant :: BTree k v -> Bool
nodeSizeInvariant = all nodeSizeInvariant' . rootChildren
where
nodeSizeInvariant' btree =
invariant (rootSize btree) &&
all nodeSizeInvariant' (rootChildren btree)
invariant s
| s >= maxNodeSize `div` 2 && s <= maxNodeSize = True
| otherwise = False
balancingInvariant :: BTree k v -> Bool
balancingInvariant = equal . depths
where
equal (x : y : t) = x == y && equal (y : t)
equal _ = True
depths tree
| isLeaf tree = [0 :: Int]
| otherwise = rootChildren tree >>= map (+ 1) . depths
|
a69e86293f17956b0d0561339742303cad845794ff2d4d5f328089c4dd43e72e | ghcjs/ghcjs | conc008.hs |
module Main where
import Control.Concurrent
import Control.Exception
Send ourselves a KillThread signal , catch it and recover .
main = do
id <- myThreadId
Control.Exception.catch (killThread id) $
\e -> putStr (show (e::SomeException))
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/concurrent/conc008.hs | haskell |
module Main where
import Control.Concurrent
import Control.Exception
Send ourselves a KillThread signal , catch it and recover .
main = do
id <- myThreadId
Control.Exception.catch (killThread id) $
\e -> putStr (show (e::SomeException))
| |
bc3fed9680d6b6512819363580bd26a93c889577c7fd29e6f489220787b9128c | manuel-serrano/hop | interface.scm | ;*=====================================================================*/
* Author : * /
* Copyright : 2007 - 2009 , see LICENSE file * /
;* ------------------------------------------------------------- */
* This file is part of Scheme2Js . * /
;* */
* Scheme2Js is distributed in the hope that it will be useful , * /
;* but WITHOUT ANY WARRANTY; without even the implied warranty of */
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
;* LICENSE file for more details. */
;*=====================================================================*/
(module interface
(main my-main))
(define *ignored-prefixes* '())
(define *prefix* #f)
(define (interface-name var)
(string-append *prefix*
(remove-prefix (symbol->string var)
*ignored-prefixes*)))
(define (print-meta m)
(display "/*** META ")
(pp m)
(print " */"))
(define (print-var/meta var/kind/meta)
(let ((var (car var/kind/meta))
(meta (caddr var/kind/meta)))
(if var
(begin
(print-meta meta)
(print "var " (interface-name var) " = " var ";")
(print))
(begin
(print-meta meta)
(print)))))
(define *out-file* #f)
(define *in-files* '())
(define (handle-args args)
(args-parse (cdr args)
(section "Help")
(("?")
(args-parse-usage #f))
((("-h" "--help") (help "?,-h,--help" "This help message"))
(args-parse-usage #f))
(section "Misc")
(("-o" ?file (help "The output file. '-' prints to stdout."))
(set! *out-file* file))
(("--interface-prefix" ?prefix (help "interface-prefix"))
(set! *prefix* prefix))
(("--ignored-prefixes" ?list
(help "scheme-list of ignored original prefixes"))
(set! *ignored-prefixes* (with-input-from-string list read)))
(else
(set! *in-files* (append! *in-files* (list else))))))
(define (my-main args)
(handle-args args)
(if (not *out-file*)
(error "interface" "no out-file given" #f))
(if (null? *in-files*)
(error "interface" "no input-file(s) given" #f))
(if (not *prefix*)
(error "interface" "no prefix given" #f))
(let ((metas (read-metas (open-multi-file *in-files*))))
(with-output-to-file *out-file*
(lambda ()
(for-each print-var/meta metas))))
(exit 0))
| null | https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/scheme2js/runtime/interface.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* */
* but WITHOUT ANY WARRANTY; without even the implied warranty of */
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
* LICENSE file for more details. */
*=====================================================================*/ | * Author : * /
* Copyright : 2007 - 2009 , see LICENSE file * /
* This file is part of Scheme2Js . * /
* Scheme2Js is distributed in the hope that it will be useful , * /
(module interface
(main my-main))
(define *ignored-prefixes* '())
(define *prefix* #f)
(define (interface-name var)
(string-append *prefix*
(remove-prefix (symbol->string var)
*ignored-prefixes*)))
(define (print-meta m)
(display "/*** META ")
(pp m)
(print " */"))
(define (print-var/meta var/kind/meta)
(let ((var (car var/kind/meta))
(meta (caddr var/kind/meta)))
(if var
(begin
(print-meta meta)
(print "var " (interface-name var) " = " var ";")
(print))
(begin
(print-meta meta)
(print)))))
(define *out-file* #f)
(define *in-files* '())
(define (handle-args args)
(args-parse (cdr args)
(section "Help")
(("?")
(args-parse-usage #f))
((("-h" "--help") (help "?,-h,--help" "This help message"))
(args-parse-usage #f))
(section "Misc")
(("-o" ?file (help "The output file. '-' prints to stdout."))
(set! *out-file* file))
(("--interface-prefix" ?prefix (help "interface-prefix"))
(set! *prefix* prefix))
(("--ignored-prefixes" ?list
(help "scheme-list of ignored original prefixes"))
(set! *ignored-prefixes* (with-input-from-string list read)))
(else
(set! *in-files* (append! *in-files* (list else))))))
(define (my-main args)
(handle-args args)
(if (not *out-file*)
(error "interface" "no out-file given" #f))
(if (null? *in-files*)
(error "interface" "no input-file(s) given" #f))
(if (not *prefix*)
(error "interface" "no prefix given" #f))
(let ((metas (read-metas (open-multi-file *in-files*))))
(with-output-to-file *out-file*
(lambda ()
(for-each print-var/meta metas))))
(exit 0))
|
d943d20d5b6ebe2aa7c072e2ef4aa2150450f9f782067095d449296c9fe994a0 | katydid/katydid-haskell | Spec.hs | # LANGUAGE FlexibleInstances #
-- |
-- This module runs the relapse parsing and validation tests.
module Main where
import qualified Test.Tasty as T
import qualified Test.Tasty.HUnit as HUnit
import qualified ParserSpec
import qualified Suite
import qualified RelapseSpec
import qualified DeriveSpec
import qualified Data.Katydid.Parser.Protobuf.Descriptor
import qualified Data.Katydid.Parser.Protobuf.Protobuf
main :: IO ()
main = do
testSuiteCases <- Suite.readTestCases
T.defaultMain $ T.testGroup
"Tests"
[ ParserSpec.tests
, RelapseSpec.tests
, Suite.tests testSuiteCases
, DeriveSpec.tests
, Data.Katydid.Parser.Protobuf.Descriptor.tests
, Data.Katydid.Parser.Protobuf.Protobuf.tests
]
| null | https://raw.githubusercontent.com/katydid/katydid-haskell/4588cd8676628cd15c671d61b65bdc2f3a199a38/test/Spec.hs | haskell | |
This module runs the relapse parsing and validation tests. | # LANGUAGE FlexibleInstances #
module Main where
import qualified Test.Tasty as T
import qualified Test.Tasty.HUnit as HUnit
import qualified ParserSpec
import qualified Suite
import qualified RelapseSpec
import qualified DeriveSpec
import qualified Data.Katydid.Parser.Protobuf.Descriptor
import qualified Data.Katydid.Parser.Protobuf.Protobuf
main :: IO ()
main = do
testSuiteCases <- Suite.readTestCases
T.defaultMain $ T.testGroup
"Tests"
[ ParserSpec.tests
, RelapseSpec.tests
, Suite.tests testSuiteCases
, DeriveSpec.tests
, Data.Katydid.Parser.Protobuf.Descriptor.tests
, Data.Katydid.Parser.Protobuf.Protobuf.tests
]
|
6fc8524bc214f10de40c50a7dbb222962bb2abc3461ae34619d98e3d1a45b8e4 | release-project/benchmarks | ant_colony.erl | %% A single ant colony: spawns a set of ants, loops round getting them to construct new solutions
-module(ant_colony).
-export([init/5]).
-include ("types.hrl").
% The value 'none' below is used to represent the state at the very start
% when we don't have a current best solution.
-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 ( ( ) , [ pid ( ) ] , solution ( ) | none ) - > solution ( ) .
aco_loop (0, _, _, _, _, Best_Solution) ->
Best_Solution;
aco_loop (Iter_Local, Num_Jobs, Inputs, Params, Ants, Best_Solution) ->
lists:foreach (fun (Pid) -> Pid ! {self(), find_solution} end, Ants),
New_Solution = collect_ants(length(Ants), none),
% io:format ("Colony ~p got new solution~n",[self()]),
{Cost1, _} = New_Solution,
Improved_Solution = localsearch:vnd_loop(New_Solution, Inputs, Params),
{Cost, _} = Improved_Solution,
#params{vverbose=Vverbose} = Params,
case Vverbose of
true -> io:format ("Colony ~p: cost = ~p -> ~p~n", [self(), Cost1, Cost]);
false -> ok
end,
New_Best_Solution = best_solution (Improved_Solution, Best_Solution),
ok = update:update_pheromones(Num_Jobs, New_Best_Solution, Params),
aco_loop (Iter_Local-1, Num_Jobs, Inputs, Params, Ants, New_Best_Solution).
main (Iter_Local, Num_Jobs, Inputs, Params, Ants, Current_Best) ->
receive
{Master, run} ->
% io:format ("~p: received run in main~n", [self()]),
% io:format ("Colony ~p got run from ~p~n", [self(),From]),
New_Solution = aco_loop (Iter_Local, Num_Jobs,
Inputs, Params,
Ants, Current_Best),
io : format ( " tau[1 ] = ~p ~ n " , [ ets : lookup(tau,1 ) ] ) ,
% io:format ("Colony ~p returning solution ~p~n", [self(), New_Solution]),
% Master ! {colony_done, {New_Solution, self()}},
#params{repl=Repl} = Params,
lists:foreach (fun (_ID) -> Master ! {colony_done, {New_Solution, self()}} end, lists:seq(1, Repl)),
% Send message Repl times. Is there an easier way to do this?
main (Iter_Local, Num_Jobs, Inputs, Params, Ants, New_Solution);
{_Master, {update, Global_Best_Solution}} ->
% io:format ("~p: received update in main~n", [self()]),
update:update_pheromones (Num_Jobs, Global_Best_Solution, Params),
main (Iter_Local, Num_Jobs, Inputs, Params, Ants, Current_Best);
%% NOTE!!!! Having updated tau according to the global best solution, the
%% colony carries on with its OWN current best solution. We could also
%% carry on with the global best solution: might this lead to stagnation?
{Master, stop_ants} -> % called by master at end of main loop
% io:format ("~p: received stop_ants in main~n", [self()]),
ok = lists:foreach (fun (Pid) -> Pid ! {self(), stop} end, Ants),
ets:delete(tau),
Note that the value of X!msg is msg , so main returns ok .
Msg -> error ({"Unexpected message in ant_colony:main", Msg})
end.
%% For each VM, set up the ETS table and spawn the required number of ants.
Then get each VM to perform ( say ) 50 iterations and report best solution .
%% Send overall best solution to all VMs (or maybe get the owner of the best
%% solution to send it to everyone), and start a new round of iterations.
%% Stop after a certain number of global iterations.
-spec spawn_ants(integer(), list()) -> [pid(),...].
spawn_ants(Num_Ants,Args) -> lists:map (fun (_) -> spawn(ant, start, Args) end, lists:seq(1,Num_Ants)).
-spec init(integer(), integer(), numjobs(), inputs(), params()) -> ok.
init (Num_Ants, Iter_Local, Num_Jobs, Inputs, Params) ->
% 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, public, named_table])
end,
#params{tau0=Tau0} = Params,
Tau = lists:map(fun(I) -> {I, util:make_tuple(Num_Jobs, Tau0)} end, lists:seq(1, Num_Jobs)),
ets:insert(tau, Tau),
% io:format("~p~n", [ets:tab2list(tau)]),
Ants = spawn_ants(Num_Ants, [Num_Jobs, Inputs, Params]),
main(Iter_Local, Num_Jobs, Inputs, Params, Ants, none).
We could also put Num_Jobs , Durations , Weights , Deadlines ,
Alpha , Beta , Q0 ( all read_only ) in an ETS table and reduce
% the number of parameters in a lot of function calls.
| null | https://raw.githubusercontent.com/release-project/benchmarks/55f042dca3a2c680e2967c59edc9636456047bd5/ACO/TL-ACO/ant_colony.erl | erlang | A single ant colony: spawns a set of ants, loops round getting them to construct new solutions
The value 'none' below is used to represent the state at the very start
when we don't have a current best solution.
or use lists:foldl.
io:format ("Colony ~p got new solution~n",[self()]),
io:format ("~p: received run in main~n", [self()]),
io:format ("Colony ~p got run from ~p~n", [self(),From]),
io:format ("Colony ~p returning solution ~p~n", [self(), New_Solution]),
Master ! {colony_done, {New_Solution, self()}},
Send message Repl times. Is there an easier way to do this?
io:format ("~p: received update in main~n", [self()]),
NOTE!!!! Having updated tau according to the global best solution, the
colony carries on with its OWN current best solution. We could also
carry on with the global best solution: might this lead to stagnation?
called by master at end of main loop
io:format ("~p: received stop_ants in main~n", [self()]),
For each VM, set up the ETS table and spawn the required number of ants.
Send overall best solution to all VMs (or maybe get the owner of the best
solution to send it to everyone), and start a new round of iterations.
Stop after a certain number of global iterations.
Set up ets table: visible to all ants
Already exists: maybe left over from interrupted run.
io:format("~p~n", [ets:tab2list(tau)]),
the number of parameters in a lot of function calls. |
-module(ant_colony).
-export([init/5]).
-include ("types.hrl").
-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 ( ( ) , [ pid ( ) ] , solution ( ) | none ) - > solution ( ) .
aco_loop (0, _, _, _, _, Best_Solution) ->
Best_Solution;
aco_loop (Iter_Local, Num_Jobs, Inputs, Params, Ants, Best_Solution) ->
lists:foreach (fun (Pid) -> Pid ! {self(), find_solution} end, Ants),
New_Solution = collect_ants(length(Ants), none),
{Cost1, _} = New_Solution,
Improved_Solution = localsearch:vnd_loop(New_Solution, Inputs, Params),
{Cost, _} = Improved_Solution,
#params{vverbose=Vverbose} = Params,
case Vverbose of
true -> io:format ("Colony ~p: cost = ~p -> ~p~n", [self(), Cost1, Cost]);
false -> ok
end,
New_Best_Solution = best_solution (Improved_Solution, Best_Solution),
ok = update:update_pheromones(Num_Jobs, New_Best_Solution, Params),
aco_loop (Iter_Local-1, Num_Jobs, Inputs, Params, Ants, New_Best_Solution).
main (Iter_Local, Num_Jobs, Inputs, Params, Ants, Current_Best) ->
receive
{Master, run} ->
New_Solution = aco_loop (Iter_Local, Num_Jobs,
Inputs, Params,
Ants, Current_Best),
io : format ( " tau[1 ] = ~p ~ n " , [ ets : lookup(tau,1 ) ] ) ,
#params{repl=Repl} = Params,
lists:foreach (fun (_ID) -> Master ! {colony_done, {New_Solution, self()}} end, lists:seq(1, Repl)),
main (Iter_Local, Num_Jobs, Inputs, Params, Ants, New_Solution);
{_Master, {update, Global_Best_Solution}} ->
update:update_pheromones (Num_Jobs, Global_Best_Solution, Params),
main (Iter_Local, Num_Jobs, Inputs, Params, Ants, Current_Best);
ok = lists:foreach (fun (Pid) -> Pid ! {self(), stop} end, Ants),
ets:delete(tau),
Note that the value of X!msg is msg , so main returns ok .
Msg -> error ({"Unexpected message in ant_colony:main", Msg})
end.
Then get each VM to perform ( say ) 50 iterations and report best solution .
-spec spawn_ants(integer(), list()) -> [pid(),...].
spawn_ants(Num_Ants,Args) -> lists:map (fun (_) -> spawn(ant, start, Args) end, lists:seq(1,Num_Ants)).
-spec init(integer(), integer(), numjobs(), inputs(), params()) -> ok.
init (Num_Ants, Iter_Local, Num_Jobs, Inputs, Params) ->
case lists:member(tau, ets:all()) of
false -> ets:new(tau, [set, public, named_table])
end,
#params{tau0=Tau0} = Params,
Tau = lists:map(fun(I) -> {I, util:make_tuple(Num_Jobs, Tau0)} end, lists:seq(1, Num_Jobs)),
ets:insert(tau, Tau),
Ants = spawn_ants(Num_Ants, [Num_Jobs, Inputs, Params]),
main(Iter_Local, Num_Jobs, Inputs, Params, Ants, none).
We could also put Num_Jobs , Durations , Weights , Deadlines ,
Alpha , Beta , Q0 ( all read_only ) in an ETS table and reduce
|
5c9ebd81973abf4241fc860422c8b7533b81cb5dd2ee967f206a2c3a033c707b | K2InformaticsGmbH/imem | imem_sql.erl | -module(imem_sql).
-include("imem_sql.hrl").
-define(MaxChar,16#FFFFFF).
-export([ exec/5
, parse/1
, prune_fields/2
]).
-export([ escape_sql/1
, un_escape_sql/1
, meta_rec/4
, params_from_opts/2
, statement_class/1
, parse_sql_name/1
, physical_table_names/1
, cluster_table_names/1
]).
physical_table_names({as, TableName, _Alias}) -> physical_table_names(TableName);
physical_table_names(TableName) -> imem_meta:physical_table_names(TableName).
cluster_table_names({as, TableName, _Alias}) -> cluster_table_names(TableName);
cluster_table_names(TableName) -> imem_meta:cluster_table_names(TableName).
statement_class({as, TableName, _Alias}) -> statement_class(TableName);
statement_class(TableAlias) ->
case { imem_meta:is_time_partitioned_alias(TableAlias)
, imem_meta:is_node_sharded_alias(TableAlias)
, imem_meta:is_local_alias(TableAlias)
} of
{false,false,false} -> "R"; % remote query of a simple table/partition on another node
{false,false,true} -> "L"; % local query (mapped to "" in GUI)
{false,true, false} -> "C"; % cluster sharded query, simple table/partition across all nodes
{true ,false,false} -> "RP"; % remote partitioned, time partitions on another node
{true ,false,true} -> "P"; % partitioned, time partitions on local node
{true ,true ,false} -> "CP" % cluster partitioned, all partitions on all nodes
end.
-spec parse_sql_name(ddString()) -> tuple().
parse_sql_name(SqlName) ->
case parse_sql_name(SqlName,0,[],[]) of
[N] -> {"",N};
[S,N] -> {S,N};
Other -> ?ClientError({"Bad SQL name", Other})
end.
parse_sql_name([], _, Temp, Acc) ->
lists:reverse([lists:reverse(Temp)|Acc]);
parse_sql_name([$.|Rest], L, Temp, Acc) when L rem 2 == 0 ->
parse_sql_name(Rest, L, [], [lists:reverse(Temp)|Acc]);
parse_sql_name([$"|Rest], L, Temp, Acc) ->
parse_sql_name(Rest, L+1, [$"|Temp], Acc);
parse_sql_name([Ch|Rest], L, Temp, Acc) ->
parse_sql_name(Rest, L, [Ch|Temp], Acc).
parse(Sql) ->
case sqlparse:parsetree(Sql) of
{ok, [{ParseTree,_}|_]} -> ParseTree;
{lex_error, Error} -> ?ClientError({"SQL lexer error", Error});
{parse_error, Error} -> ?ClientError({"SQL parser error", Error})
end.
prune_fields(InFields, ParseTree) ->
imem_prune_fields:match(ParseTree, InFields).
params_from_opts(Opts,ParseTree) when is_list(Opts) ->
case lists:keyfind(params, 1, Opts) of
false ->
[];
{_, Params} ->
SortedTriples = lists:sort(Params),
Names = [element(1,T) || T <- SortedTriples],
case imem_sql:prune_fields(Names,ParseTree) of
Names -> SortedTriples;
Less -> ?ClientError({"Unused statement parameter(s)",{Names -- Less}})
end
end.
{ RetCode , StmtResult } = imem_sql : exec(undefined , " SELECT * FROM ddAccount " , 100 , [ ] , false ) .
# stmtResults{stmtRefs = StmtRefs , rowCols = RowCols , rowFun = RowFun } = StmtResult .
List = imem_statement : fetch_recs_sort(undefined , StmtResult , { self ( ) , make_ref ( ) } , 1000 , false ) .
imem_statement : close(SKey , StmtRefs ) .
% rr(imem_statement).
CsvFileName = < < " " > > .
file : write_file(CsvFileName , < < " Col1\tCol2\r\nA1\t1\r\nA2\t2\r\n " > > ) .
{ RetCode , StmtResult } = imem_sql : exec(undefined , " SELECT * FROM csv$.\"CsvTestFileName123abc.txt\ " " , 100 , [ ] , false ) .
# stmtResults{stmtRefs = StmtRefs , rowCols = RowCols , rowFun = RowFun } = StmtResult .
List = imem_statement : fetch_recs_sort(undefined , StmtResult , { self ( ) , make_ref ( ) } , 1000 , false ) .
imem_statement : close(SKey , StmtRefs ) .
% rr(imem_statement).
Sql3p1 = " select item from dual , atom where is_member(item , mfa('imem_sql_funs','filter_funs ' , ' [ ] ' ) ) and item like ' list% ' " .
{ RetCode , StmtResult } = imem_sql : exec(undefined , Sql3p1 , 100 , [ ] , false ) .
# stmtResults{stmtRefs = StmtRefs , rowCols = RowCols , rowFun = RowFun } = StmtResult .
List = imem_statement : fetch_recs_sort(undefined , StmtResult , { self ( ) , make_ref ( ) } , 1000 , false ) .
imem_statement : close(SKey , StmtRefs ) .
exec(SKey, Sql, BlockSize, Opts, IsSec) ->
case sqlparse:parsetree(Sql) of
{ok, [{ParseTree,_}|_]} ->
Params = params_from_opts(Opts, ParseTree),
ParamRec = [imem_datatype:io_to_db(N,undefined,T,0,P,undefined,false,Value) || {N,T,P,[Value|_]} <- Params],
exec(SKey, element(1,ParseTree), ParseTree,
#statement{stmtStr=Sql, stmtParse=ParseTree, stmtParams=Params, stmtParamRec=ParamRec, blockSize=BlockSize},
Opts, IsSec);
{lex_error, Error} -> ?ClientError({"SQL lexer error", Error});
{parse_error, Error} -> ?ClientError({"SQL parser error", Error})
end.
exec(SKey, select, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, union, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'union all', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, minus, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, intersect, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, insert, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_insert:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create user', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'alter user', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop user', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create role', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop role', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'grant', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'revoke', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create table', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_table:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop table', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_table:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'truncate table', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_table:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create index', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_index:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop index', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_index:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, Command, ParseTree, _Stmt, _Opts, _IsSec) ->
?UnimplementedException({"SQL command unimplemented", {SKey, Command, ParseTree}}).
escape_sql(Str) when is_list(Str) ->
re:replace(Str, "(')", "''", [global, {return, list}]);
escape_sql(Bin) when is_binary(Bin) ->
re:replace(Bin, "(')", "''", [global, {return, binary}]).
un_escape_sql(Str) when is_list(Str) ->
re:replace(Str, "('')", "'", [global, {return, list}]);
un_escape_sql(Bin) when is_binary(Bin) ->
re:replace(Bin, "('')", "'", [global, {return, binary}]).
meta_rec(IsSec, SKey, MetaFields, ParamRec) ->
dynamic
MetaRec = [if_call_mfa(IsSec, meta_field_value, [SKey, N]) || N <- MetaFields],
list_to_tuple(MetaRec ++ ParamRec).
--Interface functions ( calling , not exported ) ---------
if_call_mfa(IsSec,Fun,Args) ->
case IsSec of
true -> apply(imem_sec,Fun,Args);
_ -> apply(imem_meta, Fun, lists:nthtail(1, Args))
end.
%% ----- TESTS ------------------------------------------------
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
statement_class_test_() ->
[ {"R_1", ?_assertEqual("R", statement_class("ddTest@007"))}
, {"R_2", ?_assertEqual("R", statement_class(<<"ddTest@007">>))}
, {"R_3", ?_assertEqual("R", statement_class(ddTest@007))}
, {"R_4", ?_assertEqual("R", statement_class({imem_meta:schema(),ddTest@007}))}
, {"R_5", ?_assertEqual("R", statement_class({as,ddTest@007,<<"TEST">>}))}
, {"L_1", ?_assertEqual("L", statement_class("ddTest"))}
, {"L_2", ?_assertEqual("L", statement_class(<<"ddTest@local">>))}
, {"L_3", ?_assertEqual("L", statement_class(ddTest))}
, {"L_4", ?_assertEqual("L", statement_class({imem_meta:schema(),ddTest@_}))}
, {"L_5", ?_assertEqual("L", statement_class({as,ddTest,<<"TEST">>}))}
, {"L_6", ?_assertEqual("L", statement_class({as,ddTest_1234567890@local,<<"TEST">>}))}
, {"P_1", ?_assertEqual("P", statement_class("ddTest_1234@local"))}
, {"P_2", ?_assertEqual("P", statement_class(<<"ddTest_1234@_">>))}
, {"P_3", ?_assertEqual("P", statement_class(ddTest_1234@local))}
, {"P_4", ?_assertEqual("P", statement_class({imem_meta:schema(),ddTest_1234@_}))}
, {"P_5", ?_assertEqual("P", statement_class({as,ddTest_1234@local,<<"TEST">>}))}
, {"C_1", ?_assertEqual("C", statement_class("ddTest@"))}
, {"C_2", ?_assertEqual("C", statement_class(<<"ddTest@">>))}
, {"C_3", ?_assertEqual("C", statement_class(ddTest@))}
, {"C_4", ?_assertEqual("C", statement_class({imem_meta:schema(),ddTest@}))}
, {"C_5", ?_assertEqual("C", statement_class({as,ddTest@,<<"TEST">>}))}
, {"C_6", ?_assertEqual("C", statement_class(<<"ddTest_1234567890@">>))}
, {"PC_1", ?_assertEqual("CP",statement_class("ddTest_1234@"))}
, {"PC_2", ?_assertEqual("CP",statement_class(<<"ddTest_1234@">>))}
, {"PC_3", ?_assertEqual("CP",statement_class(ddTest_1234@))}
, {"PC_4", ?_assertEqual("CP",statement_class({imem_meta:schema(),ddTest_1234@}))}
, {"PC_5", ?_assertEqual("CP",statement_class({as,ddTest_1234@,<<"TEST">>}))}
, {"PR_1", ?_assertEqual("RP", statement_class("ddTest_1234@007"))}
, {"PR_2", ?_assertEqual("RP", statement_class(<<"ddTest_1234@007">>))}
, {"PR_3", ?_assertEqual("RP", statement_class(ddTest_1234@007))}
, {"PR_4", ?_assertEqual("RP", statement_class({imem_meta:schema(),ddTest_1234@007}))}
, {"PR_5", ?_assertEqual("RP", statement_class({as,ddTest_1234@007,<<"TEST">>}))}
].
parse_sql_name_test_() ->
[ {"simple", ?_assertEqual({"","Simple_Name"}, parse_sql_name("Simple_Name"))}
, {"schema", ?_assertEqual({"Schema","Name"}, parse_sql_name("Schema.Name"))}
, {"complex", ?_assertEqual({"","\"Complex.$@#Name\""}, parse_sql_name("\"Complex.$@#Name\""))}
, {"mixed", ?_assertEqual({"Schema","\"Complex.$@#Name\""}, parse_sql_name("Schema.\"Complex.$@#Name\""))}
, {"double", ?_assertEqual({"\"Schema.1\"","\"Complex.$@#Name\""}, parse_sql_name("\"Schema.1\".\"Complex.$@#Name\""))}
].
-endif. | null | https://raw.githubusercontent.com/K2InformaticsGmbH/imem/602b6cd31ea1af00041a9318119ab0c3e4d5b59a/src/imem_sql.erl | erlang | remote query of a simple table/partition on another node
local query (mapped to "" in GUI)
cluster sharded query, simple table/partition across all nodes
remote partitioned, time partitions on another node
partitioned, time partitions on local node
cluster partitioned, all partitions on all nodes
rr(imem_statement).
rr(imem_statement).
----- TESTS ------------------------------------------------ | -module(imem_sql).
-include("imem_sql.hrl").
-define(MaxChar,16#FFFFFF).
-export([ exec/5
, parse/1
, prune_fields/2
]).
-export([ escape_sql/1
, un_escape_sql/1
, meta_rec/4
, params_from_opts/2
, statement_class/1
, parse_sql_name/1
, physical_table_names/1
, cluster_table_names/1
]).
physical_table_names({as, TableName, _Alias}) -> physical_table_names(TableName);
physical_table_names(TableName) -> imem_meta:physical_table_names(TableName).
cluster_table_names({as, TableName, _Alias}) -> cluster_table_names(TableName);
cluster_table_names(TableName) -> imem_meta:cluster_table_names(TableName).
statement_class({as, TableName, _Alias}) -> statement_class(TableName);
statement_class(TableAlias) ->
case { imem_meta:is_time_partitioned_alias(TableAlias)
, imem_meta:is_node_sharded_alias(TableAlias)
, imem_meta:is_local_alias(TableAlias)
} of
end.
-spec parse_sql_name(ddString()) -> tuple().
parse_sql_name(SqlName) ->
case parse_sql_name(SqlName,0,[],[]) of
[N] -> {"",N};
[S,N] -> {S,N};
Other -> ?ClientError({"Bad SQL name", Other})
end.
parse_sql_name([], _, Temp, Acc) ->
lists:reverse([lists:reverse(Temp)|Acc]);
parse_sql_name([$.|Rest], L, Temp, Acc) when L rem 2 == 0 ->
parse_sql_name(Rest, L, [], [lists:reverse(Temp)|Acc]);
parse_sql_name([$"|Rest], L, Temp, Acc) ->
parse_sql_name(Rest, L+1, [$"|Temp], Acc);
parse_sql_name([Ch|Rest], L, Temp, Acc) ->
parse_sql_name(Rest, L, [Ch|Temp], Acc).
parse(Sql) ->
case sqlparse:parsetree(Sql) of
{ok, [{ParseTree,_}|_]} -> ParseTree;
{lex_error, Error} -> ?ClientError({"SQL lexer error", Error});
{parse_error, Error} -> ?ClientError({"SQL parser error", Error})
end.
prune_fields(InFields, ParseTree) ->
imem_prune_fields:match(ParseTree, InFields).
params_from_opts(Opts,ParseTree) when is_list(Opts) ->
case lists:keyfind(params, 1, Opts) of
false ->
[];
{_, Params} ->
SortedTriples = lists:sort(Params),
Names = [element(1,T) || T <- SortedTriples],
case imem_sql:prune_fields(Names,ParseTree) of
Names -> SortedTriples;
Less -> ?ClientError({"Unused statement parameter(s)",{Names -- Less}})
end
end.
{ RetCode , StmtResult } = imem_sql : exec(undefined , " SELECT * FROM ddAccount " , 100 , [ ] , false ) .
# stmtResults{stmtRefs = StmtRefs , rowCols = RowCols , rowFun = RowFun } = StmtResult .
List = imem_statement : fetch_recs_sort(undefined , StmtResult , { self ( ) , make_ref ( ) } , 1000 , false ) .
imem_statement : close(SKey , StmtRefs ) .
CsvFileName = < < " " > > .
file : write_file(CsvFileName , < < " Col1\tCol2\r\nA1\t1\r\nA2\t2\r\n " > > ) .
{ RetCode , StmtResult } = imem_sql : exec(undefined , " SELECT * FROM csv$.\"CsvTestFileName123abc.txt\ " " , 100 , [ ] , false ) .
# stmtResults{stmtRefs = StmtRefs , rowCols = RowCols , rowFun = RowFun } = StmtResult .
List = imem_statement : fetch_recs_sort(undefined , StmtResult , { self ( ) , make_ref ( ) } , 1000 , false ) .
imem_statement : close(SKey , StmtRefs ) .
Sql3p1 = " select item from dual , atom where is_member(item , mfa('imem_sql_funs','filter_funs ' , ' [ ] ' ) ) and item like ' list% ' " .
{ RetCode , StmtResult } = imem_sql : exec(undefined , Sql3p1 , 100 , [ ] , false ) .
# stmtResults{stmtRefs = StmtRefs , rowCols = RowCols , rowFun = RowFun } = StmtResult .
List = imem_statement : fetch_recs_sort(undefined , StmtResult , { self ( ) , make_ref ( ) } , 1000 , false ) .
imem_statement : close(SKey , StmtRefs ) .
exec(SKey, Sql, BlockSize, Opts, IsSec) ->
case sqlparse:parsetree(Sql) of
{ok, [{ParseTree,_}|_]} ->
Params = params_from_opts(Opts, ParseTree),
ParamRec = [imem_datatype:io_to_db(N,undefined,T,0,P,undefined,false,Value) || {N,T,P,[Value|_]} <- Params],
exec(SKey, element(1,ParseTree), ParseTree,
#statement{stmtStr=Sql, stmtParse=ParseTree, stmtParams=Params, stmtParamRec=ParamRec, blockSize=BlockSize},
Opts, IsSec);
{lex_error, Error} -> ?ClientError({"SQL lexer error", Error});
{parse_error, Error} -> ?ClientError({"SQL parser error", Error})
end.
exec(SKey, select, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, union, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'union all', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, minus, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, intersect, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_select:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, insert, ParseTree, Stmt, Opts, IsSec) ->
imem_sql_insert:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create user', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'alter user', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop user', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create role', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop role', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'grant', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'revoke', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_account:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create table', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_table:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop table', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_table:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'truncate table', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_table:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'create index', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_index:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, 'drop index', ParseTree, Stmt, Opts, IsSec) ->
imem_sql_index:exec(SKey, ParseTree, Stmt, Opts, IsSec);
exec(SKey, Command, ParseTree, _Stmt, _Opts, _IsSec) ->
?UnimplementedException({"SQL command unimplemented", {SKey, Command, ParseTree}}).
escape_sql(Str) when is_list(Str) ->
re:replace(Str, "(')", "''", [global, {return, list}]);
escape_sql(Bin) when is_binary(Bin) ->
re:replace(Bin, "(')", "''", [global, {return, binary}]).
un_escape_sql(Str) when is_list(Str) ->
re:replace(Str, "('')", "'", [global, {return, list}]);
un_escape_sql(Bin) when is_binary(Bin) ->
re:replace(Bin, "('')", "'", [global, {return, binary}]).
meta_rec(IsSec, SKey, MetaFields, ParamRec) ->
dynamic
MetaRec = [if_call_mfa(IsSec, meta_field_value, [SKey, N]) || N <- MetaFields],
list_to_tuple(MetaRec ++ ParamRec).
--Interface functions ( calling , not exported ) ---------
if_call_mfa(IsSec,Fun,Args) ->
case IsSec of
true -> apply(imem_sec,Fun,Args);
_ -> apply(imem_meta, Fun, lists:nthtail(1, Args))
end.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
statement_class_test_() ->
[ {"R_1", ?_assertEqual("R", statement_class("ddTest@007"))}
, {"R_2", ?_assertEqual("R", statement_class(<<"ddTest@007">>))}
, {"R_3", ?_assertEqual("R", statement_class(ddTest@007))}
, {"R_4", ?_assertEqual("R", statement_class({imem_meta:schema(),ddTest@007}))}
, {"R_5", ?_assertEqual("R", statement_class({as,ddTest@007,<<"TEST">>}))}
, {"L_1", ?_assertEqual("L", statement_class("ddTest"))}
, {"L_2", ?_assertEqual("L", statement_class(<<"ddTest@local">>))}
, {"L_3", ?_assertEqual("L", statement_class(ddTest))}
, {"L_4", ?_assertEqual("L", statement_class({imem_meta:schema(),ddTest@_}))}
, {"L_5", ?_assertEqual("L", statement_class({as,ddTest,<<"TEST">>}))}
, {"L_6", ?_assertEqual("L", statement_class({as,ddTest_1234567890@local,<<"TEST">>}))}
, {"P_1", ?_assertEqual("P", statement_class("ddTest_1234@local"))}
, {"P_2", ?_assertEqual("P", statement_class(<<"ddTest_1234@_">>))}
, {"P_3", ?_assertEqual("P", statement_class(ddTest_1234@local))}
, {"P_4", ?_assertEqual("P", statement_class({imem_meta:schema(),ddTest_1234@_}))}
, {"P_5", ?_assertEqual("P", statement_class({as,ddTest_1234@local,<<"TEST">>}))}
, {"C_1", ?_assertEqual("C", statement_class("ddTest@"))}
, {"C_2", ?_assertEqual("C", statement_class(<<"ddTest@">>))}
, {"C_3", ?_assertEqual("C", statement_class(ddTest@))}
, {"C_4", ?_assertEqual("C", statement_class({imem_meta:schema(),ddTest@}))}
, {"C_5", ?_assertEqual("C", statement_class({as,ddTest@,<<"TEST">>}))}
, {"C_6", ?_assertEqual("C", statement_class(<<"ddTest_1234567890@">>))}
, {"PC_1", ?_assertEqual("CP",statement_class("ddTest_1234@"))}
, {"PC_2", ?_assertEqual("CP",statement_class(<<"ddTest_1234@">>))}
, {"PC_3", ?_assertEqual("CP",statement_class(ddTest_1234@))}
, {"PC_4", ?_assertEqual("CP",statement_class({imem_meta:schema(),ddTest_1234@}))}
, {"PC_5", ?_assertEqual("CP",statement_class({as,ddTest_1234@,<<"TEST">>}))}
, {"PR_1", ?_assertEqual("RP", statement_class("ddTest_1234@007"))}
, {"PR_2", ?_assertEqual("RP", statement_class(<<"ddTest_1234@007">>))}
, {"PR_3", ?_assertEqual("RP", statement_class(ddTest_1234@007))}
, {"PR_4", ?_assertEqual("RP", statement_class({imem_meta:schema(),ddTest_1234@007}))}
, {"PR_5", ?_assertEqual("RP", statement_class({as,ddTest_1234@007,<<"TEST">>}))}
].
parse_sql_name_test_() ->
[ {"simple", ?_assertEqual({"","Simple_Name"}, parse_sql_name("Simple_Name"))}
, {"schema", ?_assertEqual({"Schema","Name"}, parse_sql_name("Schema.Name"))}
, {"complex", ?_assertEqual({"","\"Complex.$@#Name\""}, parse_sql_name("\"Complex.$@#Name\""))}
, {"mixed", ?_assertEqual({"Schema","\"Complex.$@#Name\""}, parse_sql_name("Schema.\"Complex.$@#Name\""))}
, {"double", ?_assertEqual({"\"Schema.1\"","\"Complex.$@#Name\""}, parse_sql_name("\"Schema.1\".\"Complex.$@#Name\""))}
].
-endif. |
fd71e21d39702c9c70e1c7e5b921806dd3bf713defe3408814e1e519711eda53 | xh4/web-toolkit | wrapper-example.lisp | (in-package #:cffi-example)
(defwrapper* "b0" :long ((x :long)) "return x;")
(defwrapper* "b1" :long ((x :long)) "return x;")
(defwrapper* "b2" :long ((x :long)) "return x;")
(defwrapper* "b3" :long ((x :long)) "return x;")
(defwrapper* "b4" :long ((x :long)) "return x;")
(define "b0_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(define "b1_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(define "b2_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
;;(define "b3_cffi_wrap(x)"
;; "b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
( define ) "
;; "b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(defwrapper* "bn" :long ((x :long)) "return b0_cffi_wrap(x);")
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/cffi_0.20.1/examples/wrapper-example.lisp | lisp | (define "b3_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))") | (in-package #:cffi-example)
(defwrapper* "b0" :long ((x :long)) "return x;")
(defwrapper* "b1" :long ((x :long)) "return x;")
(defwrapper* "b2" :long ((x :long)) "return x;")
(defwrapper* "b3" :long ((x :long)) "return x;")
(defwrapper* "b4" :long ((x :long)) "return x;")
(define "b0_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(define "b1_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
(define "b2_cffi_wrap(x)"
"b0_cffi_wrap(b1_cffi_wrap(b2_cffi_wrap(b3_cffi_wrap(b4_cffi_wrap(+x+x)))))")
( define ) "
(defwrapper* "bn" :long ((x :long)) "return b0_cffi_wrap(x);")
|
9b29f5289ca8a58e7c0df1e752c23bf88de36895f370b154310ac778b7a3e5a5 | dongcarl/guix | monitoring.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2016 , 2021 , 2021 < >
Copyright © 2018 < >
Copyright © 2017 , 2018 , 2019 , 2020 < >
Copyright © 2018 , 2020 , 2021 < >
Copyright © 2018 < >
Copyright © 2018 , 2019 , 2020 < >
Copyright © 2020 < >
Copyright © 2020 < >
Copyright © 2021 < >
Copyright © 2021 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages monitoring)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix build-system perl)
#:use-module (guix build-system python)
#:use-module (guix build-system gnu)
#:use-module (guix build-system go)
#:use-module (guix utils)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages curl)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages databases)
#:use-module (gnu packages django)
#:use-module (gnu packages gd)
#:use-module (gnu packages gettext)
#:use-module (gnu packages image)
#:use-module (gnu packages mail)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages networking)
#:use-module (gnu packages libevent)
#:use-module (gnu packages pcre)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-web)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages rrdtool)
#:use-module (gnu packages time)
#:use-module (gnu packages tls)
#:use-module (gnu packages web))
(define-public nagios
(package
(name "nagios")
(version "4.4.6")
;; XXX: Nagios 4.2.x and later bundle a copy of AngularJS.
(source (origin
(method url-fetch)
(uri (string-append
"mirror-4.x/nagios-"
version "/nagios-" version ".tar.gz"))
(sha256
(base32
"1x5hb97zbvkm73q53ydp1gwj8nnznm72q9c4rm6ny7phr995l3db"))
(modules '((guix build utils)))
(snippet
;; Ensure reproducibility.
'(begin
(substitute* (find-files "cgi" "\\.c$")
(("__DATE__") "\"1970-01-01\"")
(("__TIME__") "\"00:00:00\""))
#t))))
(build-system gnu-build-system)
(native-inputs
`(("unzip" ,unzip)))
(inputs
`(("zlib" ,zlib)
("libpng-apng" ,libpng)
("gd" ,gd)
("perl" ,perl)
("mailutils" ,mailutils)))
(arguments
'(#:configure-flags (list "--sysconfdir=/etc"
;; 'include/locations.h.in' defines file
;; locations, and many things go directly under
;; LOCALSTATEDIR, hence the extra '/nagios'.
"--localstatedir=/var/nagios"
(string-append
"--with-mail="
(assoc-ref %build-inputs "mailutils")
"/bin/mail"))
#:make-flags '("all")
#:phases (modify-phases %standard-phases
(add-before 'build 'do-not-chown-to-nagios
(lambda _
;; Makefiles do 'install -o nagios -g nagios', which
;; doesn't work for us.
(substitute* (find-files "." "^Makefile$")
(("-o nagios -g nagios")
""))
#t))
(add-before 'build 'do-not-create-sysconfdir
(lambda _
;; Don't try to create /var upon 'make install'.
(substitute* "Makefile"
(("\\$\\(INSTALL\\).*\\$\\(LOGDIR\\).*$" all)
(string-append "# " all))
(("\\$\\(INSTALL\\).*\\$\\(CHECKRESULTDIR\\).*$" all)
(string-append "# " all))
(("chmod g\\+s.*" all)
(string-append "# " all)))
#t))
(add-before 'build 'set-html/php-directory
(lambda _
;; Install HTML and PHP files under 'share/nagios/html'
;; instead of just 'share/'.
(substitute* '("html/Makefile" "Makefile")
(("HTMLDIR=.*$")
"HTMLDIR = $(datarootdir)/nagios/html\n"))
#t)))
#:tests? #f)) ;no 'check' target or similar
(home-page "/")
(synopsis "Host, service, and network monitoring program")
(description
"Nagios is a host, service, and network monitoring program written in C.
CGI programs are included to allow you to view the current status, history,
etc. via a Web interface. Features include:
@itemize
@item Monitoring of network services (via SMTP, POP3, HTTP, PING, etc).
@item Monitoring of host resources (processor load, disk usage, etc.).
@item A plugin interface to allow for user-developed service monitoring
methods.
@item Ability to define network host hierarchy using \"parent\" hosts,
allowing detection of and distinction between hosts that are down
and those that are unreachable.
@item Notifications when problems occur and get resolved (via email,
pager, or user-defined method).
@item Ability to define event handlers for proactive problem resolution.
@item Automatic log file rotation/archiving.
@item Optional web interface for viewing current network status,
notification and problem history, log file, etc.
@end itemize\n")
(license license:gpl2)))
(define-public zabbix-agentd
(package
(name "zabbix-agentd")
(version "5.2.6")
(source
(origin
(method url-fetch)
(uri (string-append
"/"
(version-major+minor version) "/zabbix-" version ".tar.gz"))
(sha256
(base32 "100n1rv7r4pqagxxifzpcza5bhrr2fklzx7gndxwiyq4597p1jvn"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags
(list "--enable-agent"
"--enable-ipv6"
(string-append "--with-iconv="
(assoc-ref %build-inputs "libiconv"))
(string-append "--with-libpcre="
(assoc-ref %build-inputs "pcre")))))
(inputs
`(("libiconv" ,libiconv)
("pcre" ,pcre)))
(home-page "/")
(synopsis "Distributed monitoring solution (client-side agent)")
(description "This package provides a distributed monitoring
solution (client-side agent)")
(license license:gpl2)))
(define-public zabbix-server
(package
(inherit zabbix-agentd)
(name "zabbix-server")
(outputs '("out" "front-end" "schema"))
(arguments
(substitute-keyword-arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'install 'install-front-end
(lambda* (#:key outputs #:allow-other-keys)
(let* ((php (string-append (assoc-ref outputs "front-end")
"/share/zabbix/php"))
(front-end-conf (string-append php "/conf"))
(etc (string-append php "/etc")))
(mkdir-p php)
(copy-recursively "ui" php)
;; Make front-end write config to ‘/etc/zabbix’ directory.
(rename-file front-end-conf
(string-append front-end-conf "-example"))
(symlink "/etc/zabbix" front-end-conf))
#t))
(add-after 'install 'install-schema
(lambda* (#:key outputs #:allow-other-keys)
(let ((database-directory
(string-append (assoc-ref outputs "schema")
"/database")))
(for-each delete-file
(find-files "database" "Makefile\\.in|\\.am$"))
(mkdir-p database-directory)
(copy-recursively "database" database-directory))
#t)))
,@(package-arguments zabbix-agentd))
((#:configure-flags flags)
`(cons* "--enable-server"
"--with-postgresql"
(string-append "--with-libevent="
(assoc-ref %build-inputs "libevent"))
"--with-net-snmp"
(string-append "--with-gnutls="
(assoc-ref %build-inputs "gnutls"))
"--with-libcurl"
(string-append "--with-zlib="
(assoc-ref %build-inputs "zlib"))
,flags))))
(inputs
`(("curl" ,curl)
("libevent" ,libevent)
("gnutls" ,gnutls)
("postgresql" ,postgresql)
("zlib" ,zlib)
("net-snmp" ,net-snmp)
("curl" ,curl)
,@(package-inputs zabbix-agentd)))
(synopsis "Distributed monitoring solution (server-side)")
(description "This package provides a distributed monitoring
solution (server-side)")))
(define-public zabbix-cli
(package
(name "zabbix-cli")
(version "2.2.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "-cli")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"0wzmrn8p09ksqhhgawr179c4az7p2liqr0l4q2dra62bxliawyqz"))))
(build-system python-build-system)
(arguments
'(#:phases (modify-phases %standard-phases
(add-after 'unpack 'use-absolute-ncurses
(lambda _
(substitute* "bin/zabbix-cli"
(("'clear'")
(string-append "'" (which "clear") "'")))))
(add-after 'unpack 'patch-setup.py
(lambda _
;; Install data_files to $out/share instead of /usr/share.
(substitute* "setup.py"
(("/usr/") "")))))))
(inputs
`(("clear" ,ncurses)
("python-requests" ,python-requests)))
(home-page "-cli")
(synopsis "Command-line interface to Zabbix")
(description
"@command{zabbix-cli} is a command-line client for the Zabbix
monitoring system. It can configure and display various aspects of Zabbix
through a text-based interface.")
(license license:gpl3+)))
(define-public python-pyzabbix
(package
(name "python-pyzabbix")
(version "0.8.2")
(home-page "")
No tests on PyPI , use the git checkout .
(source
(origin
(method git-fetch)
(uri (git-reference (url home-page) (commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"15rrnpkv94wx6748hh4sd120v6x25rkbd6vlz6hfrhvjwxz5lgjl"))))
(build-system python-build-system)
(arguments
'(#:phases (modify-phases %standard-phases
(add-after 'unpack 'patch
(lambda _
Permit newer versions of httpretty .
(substitute* "setup.py"
(("httpretty<0\\.8\\.7")
"httpretty"))))
(replace 'check
(lambda* (#:key tests? #:allow-other-keys)
(if tests?
(invoke "python" "setup.py" "nosetests")
(format #t "test suite not run~")))))))
(native-inputs
`(;; For tests.
("python-httpretty" ,python-httpretty)
("python-nose" ,python-nose)))
(propagated-inputs
`(("python-requests" ,python-requests)))
(synopsis "Python interface to the Zabbix API")
(description
"@code{pyzabbix} is a Python module for working with the Zabbix API.")
(license license:lgpl2.1+)))
(define-public darkstat
(package
(name "darkstat")
(version "3.0.719")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"1mzddlim6dhd7jhr4smh0n2fa511nvyjhlx76b03vx7phnar1bxf"))))
(build-system gnu-build-system)
(arguments '(#:tests? #f)) ; no tests
(inputs
`(("libpcap" ,libpcap)
("zlib" ,zlib)))
(home-page "/")
(synopsis "Network statistics gatherer")
(description
"@command{darkstat} is a packet sniffer that runs as a background process,
gathers all sorts of statistics about network usage, and serves them over
HTTP. Features:
@itemize
@item Traffic graphs, reports per host, shows ports for each host.
@item Embedded web-server with deflate compression.
@item Asynchronous reverse DNS resolution using a child process.
@item Small. Portable. Single-threaded. Efficient.
@item Supports IPv6.
@end itemize")
(license license:gpl2)))
(define-public python-whisper
(package
(name "python-whisper")
(version "1.0.2")
(source
(origin
(method url-fetch)
(uri (pypi-uri "whisper" version))
(sha256
(base32
"1v1bi3fl1i6p4z4ki692bykrkw6907dn3mfq0151f70lvi3zpns3"))))
(build-system python-build-system)
(home-page "/")
(synopsis "Fixed size round-robin style database for Graphite")
(description "Whisper is one of three components within the Graphite
project. Whisper is a fixed-size database, similar in design and purpose to
RRD (round-robin-database). It provides fast, reliable storage of numeric
data over time. Whisper allows for higher resolution (seconds per point) of
recent data to degrade into lower resolutions for long-term retention of
historical data.")
(license license:asl2.0)))
(define-public python2-whisper
(package-with-python2 python-whisper))
(define-public python2-carbon
(package
(name "python2-carbon")
(version "1.0.2")
(source
(origin
(method url-fetch)
(uri (pypi-uri "carbon" version))
(sha256
(base32
"142smpmgbnjinvfb6s4ijazish4vfgzyd8zcmdkh55y051fkixkn"))))
(build-system python-build-system)
(arguments
only supports Python 2
#:phases
(modify-phases %standard-phases
;; Don't install to /opt
(add-after 'unpack 'do-not-install-to-/opt
(lambda _ (setenv "GRAPHITE_NO_PREFIX" "1") #t)))))
(propagated-inputs
`(("python2-whisper" ,python2-whisper)
("python2-configparser" ,python2-configparser)
("python2-txamqp" ,python2-txamqp)))
(home-page "/")
(synopsis "Backend data caching and persistence daemon for Graphite")
(description "Carbon is a backend data caching and persistence daemon for
Graphite. Carbon is responsible for receiving metrics over the network,
caching them in memory for \"hot queries\" from the Graphite-Web application,
and persisting them to disk using the Whisper time-series library.")
(license license:asl2.0)))
(define-public graphite-web
(package
(name "graphite-web")
(version "1.1.7")
(source
(origin
(method url-fetch)
(uri (pypi-uri "graphite-web" version))
(sha256
(base32
"1l5a5rry9cakqxamvlx4xq63jifmncb6815bg9vy7fg1zyd3pjxk"))))
(build-system python-build-system)
(arguments
XXX : not in PyPI release & requires database
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'relax-requirements
(lambda _
(substitute* "setup.py"
;; Allow newer versions of django-tagging.
(("django-tagging==")
"django-tagging>="))
#t))
;; Don't install to /opt
(add-after 'unpack 'do-not-install-to-/opt
(lambda _ (setenv "GRAPHITE_NO_PREFIX" "1") #t)))))
(propagated-inputs
`(("python-cairocffi" ,python-cairocffi)
("python-pytz" ,python-pytz)
("python-whisper" ,python-whisper)
("python-django" ,python-django-2.2)
("python-django-tagging" ,python-django-tagging)
("python-scandir" ,python-scandir)
("python-urllib3" ,python-urllib3)
("python-pyparsing" ,python-pyparsing)
("python-txamqp" ,python-txamqp)))
(home-page "/")
(synopsis "Scalable realtime graphing system")
(description "Graphite is a scalable real-time graphing system that does
two things: store numeric time-series data, and render graphs of this data on
demand.")
(license license:asl2.0)))
(define-public python2-graphite-web
(deprecated-package "python2-graphite-web" graphite-web))
(define-public python-prometheus-client
(package
(name "python-prometheus-client")
(version "0.7.1")
(source
(origin
(method url-fetch)
(uri (pypi-uri "prometheus_client" version))
(sha256
(base32 "1ni2yv4ixwz32nz39ckia76lvggi7m19y5f702w5qczbnfi29kbi"))))
(build-system python-build-system)
(arguments
'(;; No included tests.
#:tests? #f))
(propagated-inputs
`(("python-twisted" ,python-twisted)))
(home-page
"")
(synopsis "Python client for the Prometheus monitoring system")
(description
"The @code{prometheus_client} package supports exposing metrics from
software written in Python, so that they can be scraped by a Prometheus
service.
Metrics can be exposed through a standalone web server, or through Twisted,
WSGI and the node exporter textfile collector.")
(license license:asl2.0)))
(define-public python2-prometheus-client
(package-with-python2 python-prometheus-client))
(define-public go-github-com-prometheus-node-exporter
(package
(name "go-github-com-prometheus-node-exporter")
(version "0.18.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"0s3sp1gj86p7npxl38hkgs6ymd3wjjmc5hydyg1b5wh0x3yvpx07"))))
(build-system go-build-system)
(arguments
'(#:import-path "github.com/prometheus/node_exporter"))
(synopsis "Prometheus exporter for hardware and OS metrics")
(description "Prometheus exporter for metrics exposed by *NIX kernels,
written in Go with pluggable metric collectors.")
(home-page "")
(license license:asl2.0)))
(define-public temper-exporter
(let ((commit "a87bbab19c05609d62d9e4c7941178700c1ef84d")
(revision "0"))
(package
(name "temper-exporter")
(version (git-version "0" revision commit))
(source (origin
(method git-fetch)
(uri (git-reference
(url "-exporter")
(commit commit)))
(file-name (git-file-name name version))
(sha256
(base32
"0jk3ydi8s14q5kyl9j3gm2zrnwlb1jwjqpg5vqrgkbm9jrldrabc"))))
(build-system python-build-system)
(arguments
One test failure :
test / :
AssertionError
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-setup.py
(lambda _
(substitute* "setup.py"
(("git_ref = .*\n") "git_ref = ''\n"))
#t))
(add-after 'install 'install-udev-rules
(lambda* (#:key outputs #:allow-other-keys)
(install-file "debian/prometheus-temper-exporter.udev"
(string-append (assoc-ref outputs "out")
"/lib/udev/rules.d"))
#t)))))
(inputs
`(("python-prometheus-client" ,python-prometheus-client)
("python-pyudev" ,python-pyudev)))
(native-inputs
`(("python-pytest" ,python-pytest)
("python-pytest-mock" ,python-pytest-mock)
("python-pytest-runner" ,python-pytest-runner)))
(home-page "-exporter")
(synopsis "Prometheus exporter for PCSensor TEMPer sensor devices")
(description
"This package contains a Prometheus exporter for the TEMPer sensor
devices.")
(license license:expat))))
(define-public fswatch
(package
(name "fswatch")
(version "1.15.0")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"1yz65jsbgdx4cmy16x24wz5di352lvyi7fp6jm90bhgl1vpzxlsx"))))
(build-system gnu-build-system)
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("gettext" ,gettext-minimal)
("libtool" ,libtool)))
(synopsis "File system monitor")
(description "This package provides a file system monitor.")
(home-page "")
(license license:gpl3+)))
(define-public collectd
(package
(name "collectd")
(version "5.12.0")
(source (origin
(method url-fetch)
(uri (string-append
"-tarballs/collectd-"
version
".tar.bz2"))
(sha256
(base32
"1mh97afgq6qgmpvpr84zngh58m0sl1b4wimqgvvk376188q09bjv"))
(patches (search-patches "collectd-5.11.0-noinstallvar.patch"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags (list "--localstatedir=/var" "--sysconfdir=/etc")
#:phases (modify-phases %standard-phases
(add-before 'configure 'autoreconf
(lambda _
;; Required because of patched sources.
(invoke "autoreconf" "-vfi"))))))
(inputs
`(("rrdtool" ,rrdtool)
("curl" ,curl)
("libyajl" ,libyajl)))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Collect system and application performance metrics periodically")
(description
"collectd gathers metrics from various sources such as the operating system,
applications, log files and external devices, and stores this information or
makes it available over the network. Those statistics can be used to monitor
systems, find performance bottlenecks (i.e., performance analysis) and predict
future system load (i.e., capacity planning).")
;; license:expat for the daemon in src/daemon/ and some plugins,
;; license:gpl2 for other plugins
(license (list license:expat license:gpl2))))
(define-public hostscope
(package
(name "hostscope")
(version "8.0")
(source (origin
(method url-fetch)
(uri (string-append
"-komor.de/hostscope/hostscope-V"
version ".tgz"))
(sha256
(base32
"0jw6yij8va0f292g4xkf9lp9sxkzfgv67ajw49g3vq42q47ld7cv"))))
(build-system gnu-build-system)
(inputs `(("ncurses" ,ncurses)))
(arguments '(#:tests? #f)) ;; No included tests.
(home-page "-komor.de/hostscope.html")
(properties `((release-monitoring-url . ,home-page)))
(synopsis
"System monitoring tool for multiple hosts")
(description
"HostScope displays key system metrics of Linux hosts, such as detailed
CPU load, speed and temperature, I/O rates of network interfaces, I/O rates of
disks, and user process summary information. All metrics are multicast on the
LAN, if wanted, and clients can switch between multiple hosts on the network.
Hostscope features a bridge to Influx DB. So Grafana can be used to visualize
the recorded data over time.")
(license license:gpl3+)))
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/monitoring.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
XXX: Nagios 4.2.x and later bundle a copy of AngularJS.
Ensure reproducibility.
'include/locations.h.in' defines file
locations, and many things go directly under
LOCALSTATEDIR, hence the extra '/nagios'.
Makefiles do 'install -o nagios -g nagios', which
doesn't work for us.
Don't try to create /var upon 'make install'.
Install HTML and PHP files under 'share/nagios/html'
instead of just 'share/'.
no 'check' target or similar
Make front-end write config to ‘/etc/zabbix’ directory.
Install data_files to $out/share instead of /usr/share.
For tests.
no tests
Don't install to /opt
Allow newer versions of django-tagging.
Don't install to /opt
No included tests.
Required because of patched sources.
license:expat for the daemon in src/daemon/ and some plugins,
license:gpl2 for other plugins
No included tests. | Copyright © 2016 , 2021 , 2021 < >
Copyright © 2018 < >
Copyright © 2017 , 2018 , 2019 , 2020 < >
Copyright © 2018 , 2020 , 2021 < >
Copyright © 2018 < >
Copyright © 2018 , 2019 , 2020 < >
Copyright © 2020 < >
Copyright © 2020 < >
Copyright © 2021 < >
Copyright © 2021 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages monitoring)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix build-system perl)
#:use-module (guix build-system python)
#:use-module (guix build-system gnu)
#:use-module (guix build-system go)
#:use-module (guix utils)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages curl)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages databases)
#:use-module (gnu packages django)
#:use-module (gnu packages gd)
#:use-module (gnu packages gettext)
#:use-module (gnu packages image)
#:use-module (gnu packages mail)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages networking)
#:use-module (gnu packages libevent)
#:use-module (gnu packages pcre)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-web)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages rrdtool)
#:use-module (gnu packages time)
#:use-module (gnu packages tls)
#:use-module (gnu packages web))
(define-public nagios
(package
(name "nagios")
(version "4.4.6")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-4.x/nagios-"
version "/nagios-" version ".tar.gz"))
(sha256
(base32
"1x5hb97zbvkm73q53ydp1gwj8nnznm72q9c4rm6ny7phr995l3db"))
(modules '((guix build utils)))
(snippet
'(begin
(substitute* (find-files "cgi" "\\.c$")
(("__DATE__") "\"1970-01-01\"")
(("__TIME__") "\"00:00:00\""))
#t))))
(build-system gnu-build-system)
(native-inputs
`(("unzip" ,unzip)))
(inputs
`(("zlib" ,zlib)
("libpng-apng" ,libpng)
("gd" ,gd)
("perl" ,perl)
("mailutils" ,mailutils)))
(arguments
'(#:configure-flags (list "--sysconfdir=/etc"
"--localstatedir=/var/nagios"
(string-append
"--with-mail="
(assoc-ref %build-inputs "mailutils")
"/bin/mail"))
#:make-flags '("all")
#:phases (modify-phases %standard-phases
(add-before 'build 'do-not-chown-to-nagios
(lambda _
(substitute* (find-files "." "^Makefile$")
(("-o nagios -g nagios")
""))
#t))
(add-before 'build 'do-not-create-sysconfdir
(lambda _
(substitute* "Makefile"
(("\\$\\(INSTALL\\).*\\$\\(LOGDIR\\).*$" all)
(string-append "# " all))
(("\\$\\(INSTALL\\).*\\$\\(CHECKRESULTDIR\\).*$" all)
(string-append "# " all))
(("chmod g\\+s.*" all)
(string-append "# " all)))
#t))
(add-before 'build 'set-html/php-directory
(lambda _
(substitute* '("html/Makefile" "Makefile")
(("HTMLDIR=.*$")
"HTMLDIR = $(datarootdir)/nagios/html\n"))
#t)))
(home-page "/")
(synopsis "Host, service, and network monitoring program")
(description
"Nagios is a host, service, and network monitoring program written in C.
CGI programs are included to allow you to view the current status, history,
etc. via a Web interface. Features include:
@itemize
@item Monitoring of network services (via SMTP, POP3, HTTP, PING, etc).
@item Monitoring of host resources (processor load, disk usage, etc.).
@item A plugin interface to allow for user-developed service monitoring
methods.
@item Ability to define network host hierarchy using \"parent\" hosts,
allowing detection of and distinction between hosts that are down
and those that are unreachable.
@item Notifications when problems occur and get resolved (via email,
pager, or user-defined method).
@item Ability to define event handlers for proactive problem resolution.
@item Automatic log file rotation/archiving.
@item Optional web interface for viewing current network status,
notification and problem history, log file, etc.
@end itemize\n")
(license license:gpl2)))
(define-public zabbix-agentd
(package
(name "zabbix-agentd")
(version "5.2.6")
(source
(origin
(method url-fetch)
(uri (string-append
"/"
(version-major+minor version) "/zabbix-" version ".tar.gz"))
(sha256
(base32 "100n1rv7r4pqagxxifzpcza5bhrr2fklzx7gndxwiyq4597p1jvn"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags
(list "--enable-agent"
"--enable-ipv6"
(string-append "--with-iconv="
(assoc-ref %build-inputs "libiconv"))
(string-append "--with-libpcre="
(assoc-ref %build-inputs "pcre")))))
(inputs
`(("libiconv" ,libiconv)
("pcre" ,pcre)))
(home-page "/")
(synopsis "Distributed monitoring solution (client-side agent)")
(description "This package provides a distributed monitoring
solution (client-side agent)")
(license license:gpl2)))
(define-public zabbix-server
(package
(inherit zabbix-agentd)
(name "zabbix-server")
(outputs '("out" "front-end" "schema"))
(arguments
(substitute-keyword-arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'install 'install-front-end
(lambda* (#:key outputs #:allow-other-keys)
(let* ((php (string-append (assoc-ref outputs "front-end")
"/share/zabbix/php"))
(front-end-conf (string-append php "/conf"))
(etc (string-append php "/etc")))
(mkdir-p php)
(copy-recursively "ui" php)
(rename-file front-end-conf
(string-append front-end-conf "-example"))
(symlink "/etc/zabbix" front-end-conf))
#t))
(add-after 'install 'install-schema
(lambda* (#:key outputs #:allow-other-keys)
(let ((database-directory
(string-append (assoc-ref outputs "schema")
"/database")))
(for-each delete-file
(find-files "database" "Makefile\\.in|\\.am$"))
(mkdir-p database-directory)
(copy-recursively "database" database-directory))
#t)))
,@(package-arguments zabbix-agentd))
((#:configure-flags flags)
`(cons* "--enable-server"
"--with-postgresql"
(string-append "--with-libevent="
(assoc-ref %build-inputs "libevent"))
"--with-net-snmp"
(string-append "--with-gnutls="
(assoc-ref %build-inputs "gnutls"))
"--with-libcurl"
(string-append "--with-zlib="
(assoc-ref %build-inputs "zlib"))
,flags))))
(inputs
`(("curl" ,curl)
("libevent" ,libevent)
("gnutls" ,gnutls)
("postgresql" ,postgresql)
("zlib" ,zlib)
("net-snmp" ,net-snmp)
("curl" ,curl)
,@(package-inputs zabbix-agentd)))
(synopsis "Distributed monitoring solution (server-side)")
(description "This package provides a distributed monitoring
solution (server-side)")))
(define-public zabbix-cli
(package
(name "zabbix-cli")
(version "2.2.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "-cli")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"0wzmrn8p09ksqhhgawr179c4az7p2liqr0l4q2dra62bxliawyqz"))))
(build-system python-build-system)
(arguments
'(#:phases (modify-phases %standard-phases
(add-after 'unpack 'use-absolute-ncurses
(lambda _
(substitute* "bin/zabbix-cli"
(("'clear'")
(string-append "'" (which "clear") "'")))))
(add-after 'unpack 'patch-setup.py
(lambda _
(substitute* "setup.py"
(("/usr/") "")))))))
(inputs
`(("clear" ,ncurses)
("python-requests" ,python-requests)))
(home-page "-cli")
(synopsis "Command-line interface to Zabbix")
(description
"@command{zabbix-cli} is a command-line client for the Zabbix
monitoring system. It can configure and display various aspects of Zabbix
through a text-based interface.")
(license license:gpl3+)))
(define-public python-pyzabbix
(package
(name "python-pyzabbix")
(version "0.8.2")
(home-page "")
No tests on PyPI , use the git checkout .
(source
(origin
(method git-fetch)
(uri (git-reference (url home-page) (commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"15rrnpkv94wx6748hh4sd120v6x25rkbd6vlz6hfrhvjwxz5lgjl"))))
(build-system python-build-system)
(arguments
'(#:phases (modify-phases %standard-phases
(add-after 'unpack 'patch
(lambda _
Permit newer versions of httpretty .
(substitute* "setup.py"
(("httpretty<0\\.8\\.7")
"httpretty"))))
(replace 'check
(lambda* (#:key tests? #:allow-other-keys)
(if tests?
(invoke "python" "setup.py" "nosetests")
(format #t "test suite not run~")))))))
(native-inputs
("python-httpretty" ,python-httpretty)
("python-nose" ,python-nose)))
(propagated-inputs
`(("python-requests" ,python-requests)))
(synopsis "Python interface to the Zabbix API")
(description
"@code{pyzabbix} is a Python module for working with the Zabbix API.")
(license license:lgpl2.1+)))
(define-public darkstat
(package
(name "darkstat")
(version "3.0.719")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"1mzddlim6dhd7jhr4smh0n2fa511nvyjhlx76b03vx7phnar1bxf"))))
(build-system gnu-build-system)
(inputs
`(("libpcap" ,libpcap)
("zlib" ,zlib)))
(home-page "/")
(synopsis "Network statistics gatherer")
(description
"@command{darkstat} is a packet sniffer that runs as a background process,
gathers all sorts of statistics about network usage, and serves them over
HTTP. Features:
@itemize
@item Traffic graphs, reports per host, shows ports for each host.
@item Embedded web-server with deflate compression.
@item Asynchronous reverse DNS resolution using a child process.
@item Small. Portable. Single-threaded. Efficient.
@item Supports IPv6.
@end itemize")
(license license:gpl2)))
(define-public python-whisper
(package
(name "python-whisper")
(version "1.0.2")
(source
(origin
(method url-fetch)
(uri (pypi-uri "whisper" version))
(sha256
(base32
"1v1bi3fl1i6p4z4ki692bykrkw6907dn3mfq0151f70lvi3zpns3"))))
(build-system python-build-system)
(home-page "/")
(synopsis "Fixed size round-robin style database for Graphite")
(description "Whisper is one of three components within the Graphite
project. Whisper is a fixed-size database, similar in design and purpose to
RRD (round-robin-database). It provides fast, reliable storage of numeric
data over time. Whisper allows for higher resolution (seconds per point) of
recent data to degrade into lower resolutions for long-term retention of
historical data.")
(license license:asl2.0)))
(define-public python2-whisper
(package-with-python2 python-whisper))
(define-public python2-carbon
(package
(name "python2-carbon")
(version "1.0.2")
(source
(origin
(method url-fetch)
(uri (pypi-uri "carbon" version))
(sha256
(base32
"142smpmgbnjinvfb6s4ijazish4vfgzyd8zcmdkh55y051fkixkn"))))
(build-system python-build-system)
(arguments
only supports Python 2
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'do-not-install-to-/opt
(lambda _ (setenv "GRAPHITE_NO_PREFIX" "1") #t)))))
(propagated-inputs
`(("python2-whisper" ,python2-whisper)
("python2-configparser" ,python2-configparser)
("python2-txamqp" ,python2-txamqp)))
(home-page "/")
(synopsis "Backend data caching and persistence daemon for Graphite")
(description "Carbon is a backend data caching and persistence daemon for
Graphite. Carbon is responsible for receiving metrics over the network,
caching them in memory for \"hot queries\" from the Graphite-Web application,
and persisting them to disk using the Whisper time-series library.")
(license license:asl2.0)))
(define-public graphite-web
(package
(name "graphite-web")
(version "1.1.7")
(source
(origin
(method url-fetch)
(uri (pypi-uri "graphite-web" version))
(sha256
(base32
"1l5a5rry9cakqxamvlx4xq63jifmncb6815bg9vy7fg1zyd3pjxk"))))
(build-system python-build-system)
(arguments
XXX : not in PyPI release & requires database
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'relax-requirements
(lambda _
(substitute* "setup.py"
(("django-tagging==")
"django-tagging>="))
#t))
(add-after 'unpack 'do-not-install-to-/opt
(lambda _ (setenv "GRAPHITE_NO_PREFIX" "1") #t)))))
(propagated-inputs
`(("python-cairocffi" ,python-cairocffi)
("python-pytz" ,python-pytz)
("python-whisper" ,python-whisper)
("python-django" ,python-django-2.2)
("python-django-tagging" ,python-django-tagging)
("python-scandir" ,python-scandir)
("python-urllib3" ,python-urllib3)
("python-pyparsing" ,python-pyparsing)
("python-txamqp" ,python-txamqp)))
(home-page "/")
(synopsis "Scalable realtime graphing system")
(description "Graphite is a scalable real-time graphing system that does
two things: store numeric time-series data, and render graphs of this data on
demand.")
(license license:asl2.0)))
(define-public python2-graphite-web
(deprecated-package "python2-graphite-web" graphite-web))
(define-public python-prometheus-client
(package
(name "python-prometheus-client")
(version "0.7.1")
(source
(origin
(method url-fetch)
(uri (pypi-uri "prometheus_client" version))
(sha256
(base32 "1ni2yv4ixwz32nz39ckia76lvggi7m19y5f702w5qczbnfi29kbi"))))
(build-system python-build-system)
(arguments
#:tests? #f))
(propagated-inputs
`(("python-twisted" ,python-twisted)))
(home-page
"")
(synopsis "Python client for the Prometheus monitoring system")
(description
"The @code{prometheus_client} package supports exposing metrics from
software written in Python, so that they can be scraped by a Prometheus
service.
Metrics can be exposed through a standalone web server, or through Twisted,
WSGI and the node exporter textfile collector.")
(license license:asl2.0)))
(define-public python2-prometheus-client
(package-with-python2 python-prometheus-client))
(define-public go-github-com-prometheus-node-exporter
(package
(name "go-github-com-prometheus-node-exporter")
(version "0.18.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"0s3sp1gj86p7npxl38hkgs6ymd3wjjmc5hydyg1b5wh0x3yvpx07"))))
(build-system go-build-system)
(arguments
'(#:import-path "github.com/prometheus/node_exporter"))
(synopsis "Prometheus exporter for hardware and OS metrics")
(description "Prometheus exporter for metrics exposed by *NIX kernels,
written in Go with pluggable metric collectors.")
(home-page "")
(license license:asl2.0)))
(define-public temper-exporter
(let ((commit "a87bbab19c05609d62d9e4c7941178700c1ef84d")
(revision "0"))
(package
(name "temper-exporter")
(version (git-version "0" revision commit))
(source (origin
(method git-fetch)
(uri (git-reference
(url "-exporter")
(commit commit)))
(file-name (git-file-name name version))
(sha256
(base32
"0jk3ydi8s14q5kyl9j3gm2zrnwlb1jwjqpg5vqrgkbm9jrldrabc"))))
(build-system python-build-system)
(arguments
One test failure :
test / :
AssertionError
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-setup.py
(lambda _
(substitute* "setup.py"
(("git_ref = .*\n") "git_ref = ''\n"))
#t))
(add-after 'install 'install-udev-rules
(lambda* (#:key outputs #:allow-other-keys)
(install-file "debian/prometheus-temper-exporter.udev"
(string-append (assoc-ref outputs "out")
"/lib/udev/rules.d"))
#t)))))
(inputs
`(("python-prometheus-client" ,python-prometheus-client)
("python-pyudev" ,python-pyudev)))
(native-inputs
`(("python-pytest" ,python-pytest)
("python-pytest-mock" ,python-pytest-mock)
("python-pytest-runner" ,python-pytest-runner)))
(home-page "-exporter")
(synopsis "Prometheus exporter for PCSensor TEMPer sensor devices")
(description
"This package contains a Prometheus exporter for the TEMPer sensor
devices.")
(license license:expat))))
(define-public fswatch
(package
(name "fswatch")
(version "1.15.0")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"1yz65jsbgdx4cmy16x24wz5di352lvyi7fp6jm90bhgl1vpzxlsx"))))
(build-system gnu-build-system)
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("gettext" ,gettext-minimal)
("libtool" ,libtool)))
(synopsis "File system monitor")
(description "This package provides a file system monitor.")
(home-page "")
(license license:gpl3+)))
(define-public collectd
(package
(name "collectd")
(version "5.12.0")
(source (origin
(method url-fetch)
(uri (string-append
"-tarballs/collectd-"
version
".tar.bz2"))
(sha256
(base32
"1mh97afgq6qgmpvpr84zngh58m0sl1b4wimqgvvk376188q09bjv"))
(patches (search-patches "collectd-5.11.0-noinstallvar.patch"))))
(build-system gnu-build-system)
(arguments
`(#:configure-flags (list "--localstatedir=/var" "--sysconfdir=/etc")
#:phases (modify-phases %standard-phases
(add-before 'configure 'autoreconf
(lambda _
(invoke "autoreconf" "-vfi"))))))
(inputs
`(("rrdtool" ,rrdtool)
("curl" ,curl)
("libyajl" ,libyajl)))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Collect system and application performance metrics periodically")
(description
"collectd gathers metrics from various sources such as the operating system,
applications, log files and external devices, and stores this information or
makes it available over the network. Those statistics can be used to monitor
systems, find performance bottlenecks (i.e., performance analysis) and predict
future system load (i.e., capacity planning).")
(license (list license:expat license:gpl2))))
(define-public hostscope
(package
(name "hostscope")
(version "8.0")
(source (origin
(method url-fetch)
(uri (string-append
"-komor.de/hostscope/hostscope-V"
version ".tgz"))
(sha256
(base32
"0jw6yij8va0f292g4xkf9lp9sxkzfgv67ajw49g3vq42q47ld7cv"))))
(build-system gnu-build-system)
(inputs `(("ncurses" ,ncurses)))
(home-page "-komor.de/hostscope.html")
(properties `((release-monitoring-url . ,home-page)))
(synopsis
"System monitoring tool for multiple hosts")
(description
"HostScope displays key system metrics of Linux hosts, such as detailed
CPU load, speed and temperature, I/O rates of network interfaces, I/O rates of
disks, and user process summary information. All metrics are multicast on the
LAN, if wanted, and clients can switch between multiple hosts on the network.
Hostscope features a bridge to Influx DB. So Grafana can be used to visualize
the recorded data over time.")
(license license:gpl3+)))
|
6c121947f139a1afa7fc349974eab16491925358f64c3b2486a7caae06603c0c | mbj/stratosphere | Table.hs | module Stratosphere.Timestream.Table (
module Exports, Table(..), mkTable
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.Timestream.Table.MagneticStoreWritePropertiesProperty as Exports
import {-# SOURCE #-} Stratosphere.Timestream.Table.RetentionPropertiesProperty as Exports
import Stratosphere.ResourceProperties
import Stratosphere.Tag
import Stratosphere.Value
data Table
= Table {databaseName :: (Value Prelude.Text),
magneticStoreWriteProperties :: (Prelude.Maybe MagneticStoreWritePropertiesProperty),
retentionProperties :: (Prelude.Maybe RetentionPropertiesProperty),
tableName :: (Prelude.Maybe (Value Prelude.Text)),
tags :: (Prelude.Maybe [Tag])}
mkTable :: Value Prelude.Text -> Table
mkTable databaseName
= Table
{databaseName = databaseName,
magneticStoreWriteProperties = Prelude.Nothing,
retentionProperties = Prelude.Nothing, tableName = Prelude.Nothing,
tags = Prelude.Nothing}
instance ToResourceProperties Table where
toResourceProperties Table {..}
= ResourceProperties
{awsType = "AWS::Timestream::Table", supportsTags = Prelude.True,
properties = Prelude.fromList
((Prelude.<>)
["DatabaseName" JSON..= databaseName]
(Prelude.catMaybes
[(JSON..=) "MagneticStoreWriteProperties"
Prelude.<$> magneticStoreWriteProperties,
(JSON..=) "RetentionProperties" Prelude.<$> retentionProperties,
(JSON..=) "TableName" Prelude.<$> tableName,
(JSON..=) "Tags" Prelude.<$> tags]))}
instance JSON.ToJSON Table where
toJSON Table {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["DatabaseName" JSON..= databaseName]
(Prelude.catMaybes
[(JSON..=) "MagneticStoreWriteProperties"
Prelude.<$> magneticStoreWriteProperties,
(JSON..=) "RetentionProperties" Prelude.<$> retentionProperties,
(JSON..=) "TableName" Prelude.<$> tableName,
(JSON..=) "Tags" Prelude.<$> tags])))
instance Property "DatabaseName" Table where
type PropertyType "DatabaseName" Table = Value Prelude.Text
set newValue Table {..} = Table {databaseName = newValue, ..}
instance Property "MagneticStoreWriteProperties" Table where
type PropertyType "MagneticStoreWriteProperties" Table = MagneticStoreWritePropertiesProperty
set newValue Table {..}
= Table {magneticStoreWriteProperties = Prelude.pure newValue, ..}
instance Property "RetentionProperties" Table where
type PropertyType "RetentionProperties" Table = RetentionPropertiesProperty
set newValue Table {..}
= Table {retentionProperties = Prelude.pure newValue, ..}
instance Property "TableName" Table where
type PropertyType "TableName" Table = Value Prelude.Text
set newValue Table {..}
= Table {tableName = Prelude.pure newValue, ..}
instance Property "Tags" Table where
type PropertyType "Tags" Table = [Tag]
set newValue Table {..} = Table {tags = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/timestream/gen/Stratosphere/Timestream/Table.hs | haskell | # SOURCE #
# SOURCE # | module Stratosphere.Timestream.Table (
module Exports, Table(..), mkTable
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Tag
import Stratosphere.Value
data Table
= Table {databaseName :: (Value Prelude.Text),
magneticStoreWriteProperties :: (Prelude.Maybe MagneticStoreWritePropertiesProperty),
retentionProperties :: (Prelude.Maybe RetentionPropertiesProperty),
tableName :: (Prelude.Maybe (Value Prelude.Text)),
tags :: (Prelude.Maybe [Tag])}
mkTable :: Value Prelude.Text -> Table
mkTable databaseName
= Table
{databaseName = databaseName,
magneticStoreWriteProperties = Prelude.Nothing,
retentionProperties = Prelude.Nothing, tableName = Prelude.Nothing,
tags = Prelude.Nothing}
instance ToResourceProperties Table where
toResourceProperties Table {..}
= ResourceProperties
{awsType = "AWS::Timestream::Table", supportsTags = Prelude.True,
properties = Prelude.fromList
((Prelude.<>)
["DatabaseName" JSON..= databaseName]
(Prelude.catMaybes
[(JSON..=) "MagneticStoreWriteProperties"
Prelude.<$> magneticStoreWriteProperties,
(JSON..=) "RetentionProperties" Prelude.<$> retentionProperties,
(JSON..=) "TableName" Prelude.<$> tableName,
(JSON..=) "Tags" Prelude.<$> tags]))}
instance JSON.ToJSON Table where
toJSON Table {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["DatabaseName" JSON..= databaseName]
(Prelude.catMaybes
[(JSON..=) "MagneticStoreWriteProperties"
Prelude.<$> magneticStoreWriteProperties,
(JSON..=) "RetentionProperties" Prelude.<$> retentionProperties,
(JSON..=) "TableName" Prelude.<$> tableName,
(JSON..=) "Tags" Prelude.<$> tags])))
instance Property "DatabaseName" Table where
type PropertyType "DatabaseName" Table = Value Prelude.Text
set newValue Table {..} = Table {databaseName = newValue, ..}
instance Property "MagneticStoreWriteProperties" Table where
type PropertyType "MagneticStoreWriteProperties" Table = MagneticStoreWritePropertiesProperty
set newValue Table {..}
= Table {magneticStoreWriteProperties = Prelude.pure newValue, ..}
instance Property "RetentionProperties" Table where
type PropertyType "RetentionProperties" Table = RetentionPropertiesProperty
set newValue Table {..}
= Table {retentionProperties = Prelude.pure newValue, ..}
instance Property "TableName" Table where
type PropertyType "TableName" Table = Value Prelude.Text
set newValue Table {..}
= Table {tableName = Prelude.pure newValue, ..}
instance Property "Tags" Table where
type PropertyType "Tags" Table = [Tag]
set newValue Table {..} = Table {tags = Prelude.pure newValue, ..} |
292f8c954a8c5c56b0f0fcb1c58cffec863444ba0e9d142a5e024326097efa80 | reactiveml/rml | lk_ast.ml | (**********************************************************************)
(* *)
(* ReactiveML *)
(* *)
(* *)
(* *)
(* Louis Mandel *)
(* *)
Copyright 2002 , 2007 . All rights reserved .
(* This file is distributed under the terms of the Q Public License *)
version 1.0 .
(* *)
(* ReactiveML has been done in the following labs: *)
- theme SPI , Laboratoire d'Informatique de Paris 6 ( 2002 - 2005 )
- Verimag , CNRS Grenoble ( 2005 - 2006 )
- projet , ( 2006 - 2007 )
(* *)
(**********************************************************************)
file :
created : 2005 - 08 - 09
author :
$ Id$
(* The abstract syntax for the Lk language (cf. thesis) *)
open Rml_asttypes
open Def_types
type ident = Rml_ident.t
type 'a global = 'a Global.global
(* Expressions *)
(* ML expressions *)
type expression =
{ kexpr_desc: expression_desc;
kexpr_loc: Location.t; }
and expression_desc =
| Kexpr_local of ident
| Kexpr_global of value_type_description global
| Kexpr_constant of immediate
| Kexpr_let of rec_flag * (pattern * expression) list * expression
| Kexpr_function of (pattern * expression option * expression) list
| Kexpr_apply of expression * expression list
| Kexpr_tuple of expression list
| Kexpr_construct of constructor_type_description global * expression option
| Kexpr_array of expression list
| Kexpr_record of (label_type_description global * expression) list
| Kexpr_record_access of expression * label_type_description global
| Kexpr_record_with of
expression * (label_type_description global * expression) list
| Kexpr_record_update of
expression * label_type_description global * expression
| Kexpr_constraint of expression * type_expression
| Kexpr_trywith of
expression * (pattern * expression option * expression) list
| Kexpr_assert of expression
| Kexpr_ifthenelse of expression * expression * expression
| Kexpr_match of expression * (pattern * expression option * expression) list
| Kexpr_while of expression * expression
| Kexpr_for of
ident * expression * expression * direction_flag * expression
| Kexpr_seq of expression * expression
| Kexpr_process of ident * ident * process
| Kexpr_pre of pre_kind * expression
| Kexpr_last of expression
| Kexpr_default of expression
| Kexpr_emit of expression
| Kexpr_emit_val of expression * expression
| Kexpr_signal of
(ident * type_expression option)
* (signal_kind * expression * expression) option * expression
| Kexpr_exec of expression
(* Process expressions *)
and process =
{ kproc_desc: process_desc;
kproc_loc: Location.t;}
and process_desc =
| Kproc_pause of continue_begin_of_instant * process * ident
| Kproc_halt of continue_begin_of_instant
| Kproc_compute of expression * process
| Kproc_seq of expression * process
| Kproc_emit of expression * process
| Kproc_emit_val of expression * expression * process
| Kproc_loop of ident * process
| Kproc_loop_n of ident * expression * process * process
| Kproc_while of expression * (ident * process) * process
| Kproc_for of
ident * expression * expression * direction_flag *
(ident * process) * process
| Kproc_fordopar of
ident * expression * expression * direction_flag *
(ident * process) * process
| Kproc_split_def of
ident * (ident * Def_types.type_expression) list * ident * process list
| Kproc_join_def of ident * ident * ident * process
(* | Kproc_split_par of ident * process list *)
| Kproc_split_par of ident * pattern * process * process list
| Kproc_join_par of ident * process
(* | Kproc_merge of process * process *)
| Kproc_signal of
(ident * type_expression option)
* (signal_kind * expression * expression) option * process
| Kproc_def of rec_flag * (pattern * expression) list * process
| Kproc_def_dyn of pattern * process
| Kproc_def_and_dyn of pattern list * process
| Kproc_run of expression * process * ident
| Kproc_start_until of
ident (* ctrl father *) *
event_config * expression option * (ident * process) * (pattern * process)
| Kproc_end_until of ident * process
| Kproc_start_when of
ident * event_config * (ident * process)
(* | Kproc_when of ident * expression * ident *)
| Kproc_end_when of ident * process
| Kproc_start_control of
ident * event_config * (ident * process)
| Kproc_end_control of ident * process
| Kproc_get of expression * pattern * process * ident
| Kproc_present of ident * event_config * process * process
| Kproc_ifthenelse of expression * process * process
| Kproc_match of expression * (pattern * expression option * process) list
| Kproc_await of immediate_flag * event_config * process * ident
| Kproc_await_val of
immediate_flag * await_kind * expression * pattern * expression option *
process * ident
| Kproc_bind of
pattern * process * process
| Kproc_var of ident
(* event configuration *)
and event_config =
{ kconf_desc: event_config_desc;
kconf_loc: Location.t; }
and event_config_desc =
| Kconf_present of expression
| Kconf_and of event_config * event_config
| Kconf_or of event_config * event_config
(* Patterns *)
and pattern =
{ kpatt_desc: pattern_desc;
kpatt_loc: Location.t; }
and pattern_desc =
| Kpatt_any
| Kpatt_var of varpatt
| Kpatt_alias of pattern * varpatt
| Kpatt_constant of immediate
| Kpatt_tuple of pattern list
| Kpatt_construct of constructor_type_description global * pattern option
| Kpatt_or of pattern * pattern
| Kpatt_record of (label_type_description global * pattern) list
| Kpatt_array of pattern list
| Kpatt_constraint of pattern * type_expression
and varpatt =
| Kvarpatt_local of ident
| Kvarpatt_global of value_type_description global
(* Types *)
and type_expression =
{ kte_desc: type_expression_desc;
kte_loc: Location.t}
and type_expression_desc =
Ktype_var of string
| Ktype_arrow of type_expression * type_expression
| Ktype_product of type_expression list
| Ktype_constr of type_description global * type_expression list
| Ktype_process of type_expression
and type_declaration =
| Ktype_abstract
| Ktype_rebind of type_expression
| Ktype_variant of
(constructor_type_description global * type_expression option) list
| Ktype_record of
(label_type_description global * mutable_flag * type_expression) list
(* Structure *)
type impl_item =
{ kimpl_desc: impl_desc;
kimpl_loc: Location.t;}
and impl_desc =
| Kimpl_expr of expression
| Kimpl_let of rec_flag * (pattern * expression) list
| Kimpl_signal of
((value_type_description global * type_expression option)
* (signal_kind * expression * expression) option) list
| Kimpl_type of
(type_description global * string list * type_declaration) list
| Kimpl_exn of
constructor_type_description global * type_expression option
| Kimpl_exn_rebind of
constructor_type_description global * constructor_type_description global
| Kimpl_open of string
Signature
type intf_item =
{kintf_desc: intf_desc;
kintf_loc: Location.t;}
and intf_desc =
| Kintf_val of value_type_description global * type_expression
| Kintf_type of
(type_description global * string list * type_declaration) list
| Kintf_exn of
constructor_type_description global * type_expression option
| Kintf_open of string
| null | https://raw.githubusercontent.com/reactiveml/rml/d3ac141bd9c6e3333b678716166d988ce04b5c80/compiler/lk/lk_ast.ml | ocaml | ********************************************************************
ReactiveML
Louis Mandel
This file is distributed under the terms of the Q Public License
ReactiveML has been done in the following labs:
********************************************************************
The abstract syntax for the Lk language (cf. thesis)
Expressions
ML expressions
Process expressions
| Kproc_split_par of ident * process list
| Kproc_merge of process * process
ctrl father
| Kproc_when of ident * expression * ident
event configuration
Patterns
Types
Structure | Copyright 2002 , 2007 . All rights reserved .
version 1.0 .
- theme SPI , Laboratoire d'Informatique de Paris 6 ( 2002 - 2005 )
- Verimag , CNRS Grenoble ( 2005 - 2006 )
- projet , ( 2006 - 2007 )
file :
created : 2005 - 08 - 09
author :
$ Id$
open Rml_asttypes
open Def_types
type ident = Rml_ident.t
type 'a global = 'a Global.global
type expression =
{ kexpr_desc: expression_desc;
kexpr_loc: Location.t; }
and expression_desc =
| Kexpr_local of ident
| Kexpr_global of value_type_description global
| Kexpr_constant of immediate
| Kexpr_let of rec_flag * (pattern * expression) list * expression
| Kexpr_function of (pattern * expression option * expression) list
| Kexpr_apply of expression * expression list
| Kexpr_tuple of expression list
| Kexpr_construct of constructor_type_description global * expression option
| Kexpr_array of expression list
| Kexpr_record of (label_type_description global * expression) list
| Kexpr_record_access of expression * label_type_description global
| Kexpr_record_with of
expression * (label_type_description global * expression) list
| Kexpr_record_update of
expression * label_type_description global * expression
| Kexpr_constraint of expression * type_expression
| Kexpr_trywith of
expression * (pattern * expression option * expression) list
| Kexpr_assert of expression
| Kexpr_ifthenelse of expression * expression * expression
| Kexpr_match of expression * (pattern * expression option * expression) list
| Kexpr_while of expression * expression
| Kexpr_for of
ident * expression * expression * direction_flag * expression
| Kexpr_seq of expression * expression
| Kexpr_process of ident * ident * process
| Kexpr_pre of pre_kind * expression
| Kexpr_last of expression
| Kexpr_default of expression
| Kexpr_emit of expression
| Kexpr_emit_val of expression * expression
| Kexpr_signal of
(ident * type_expression option)
* (signal_kind * expression * expression) option * expression
| Kexpr_exec of expression
and process =
{ kproc_desc: process_desc;
kproc_loc: Location.t;}
and process_desc =
| Kproc_pause of continue_begin_of_instant * process * ident
| Kproc_halt of continue_begin_of_instant
| Kproc_compute of expression * process
| Kproc_seq of expression * process
| Kproc_emit of expression * process
| Kproc_emit_val of expression * expression * process
| Kproc_loop of ident * process
| Kproc_loop_n of ident * expression * process * process
| Kproc_while of expression * (ident * process) * process
| Kproc_for of
ident * expression * expression * direction_flag *
(ident * process) * process
| Kproc_fordopar of
ident * expression * expression * direction_flag *
(ident * process) * process
| Kproc_split_def of
ident * (ident * Def_types.type_expression) list * ident * process list
| Kproc_join_def of ident * ident * ident * process
| Kproc_split_par of ident * pattern * process * process list
| Kproc_join_par of ident * process
| Kproc_signal of
(ident * type_expression option)
* (signal_kind * expression * expression) option * process
| Kproc_def of rec_flag * (pattern * expression) list * process
| Kproc_def_dyn of pattern * process
| Kproc_def_and_dyn of pattern list * process
| Kproc_run of expression * process * ident
| Kproc_start_until of
event_config * expression option * (ident * process) * (pattern * process)
| Kproc_end_until of ident * process
| Kproc_start_when of
ident * event_config * (ident * process)
| Kproc_end_when of ident * process
| Kproc_start_control of
ident * event_config * (ident * process)
| Kproc_end_control of ident * process
| Kproc_get of expression * pattern * process * ident
| Kproc_present of ident * event_config * process * process
| Kproc_ifthenelse of expression * process * process
| Kproc_match of expression * (pattern * expression option * process) list
| Kproc_await of immediate_flag * event_config * process * ident
| Kproc_await_val of
immediate_flag * await_kind * expression * pattern * expression option *
process * ident
| Kproc_bind of
pattern * process * process
| Kproc_var of ident
and event_config =
{ kconf_desc: event_config_desc;
kconf_loc: Location.t; }
and event_config_desc =
| Kconf_present of expression
| Kconf_and of event_config * event_config
| Kconf_or of event_config * event_config
and pattern =
{ kpatt_desc: pattern_desc;
kpatt_loc: Location.t; }
and pattern_desc =
| Kpatt_any
| Kpatt_var of varpatt
| Kpatt_alias of pattern * varpatt
| Kpatt_constant of immediate
| Kpatt_tuple of pattern list
| Kpatt_construct of constructor_type_description global * pattern option
| Kpatt_or of pattern * pattern
| Kpatt_record of (label_type_description global * pattern) list
| Kpatt_array of pattern list
| Kpatt_constraint of pattern * type_expression
and varpatt =
| Kvarpatt_local of ident
| Kvarpatt_global of value_type_description global
and type_expression =
{ kte_desc: type_expression_desc;
kte_loc: Location.t}
and type_expression_desc =
Ktype_var of string
| Ktype_arrow of type_expression * type_expression
| Ktype_product of type_expression list
| Ktype_constr of type_description global * type_expression list
| Ktype_process of type_expression
and type_declaration =
| Ktype_abstract
| Ktype_rebind of type_expression
| Ktype_variant of
(constructor_type_description global * type_expression option) list
| Ktype_record of
(label_type_description global * mutable_flag * type_expression) list
type impl_item =
{ kimpl_desc: impl_desc;
kimpl_loc: Location.t;}
and impl_desc =
| Kimpl_expr of expression
| Kimpl_let of rec_flag * (pattern * expression) list
| Kimpl_signal of
((value_type_description global * type_expression option)
* (signal_kind * expression * expression) option) list
| Kimpl_type of
(type_description global * string list * type_declaration) list
| Kimpl_exn of
constructor_type_description global * type_expression option
| Kimpl_exn_rebind of
constructor_type_description global * constructor_type_description global
| Kimpl_open of string
Signature
type intf_item =
{kintf_desc: intf_desc;
kintf_loc: Location.t;}
and intf_desc =
| Kintf_val of value_type_description global * type_expression
| Kintf_type of
(type_description global * string list * type_declaration) list
| Kintf_exn of
constructor_type_description global * type_expression option
| Kintf_open of string
|
8e15ac4c455cf532027698220c5b4547fe250e3cba7682a1ce1ce90f0c5c9a5e | docker-in-aws/docker-in-aws | form_configs.cljs | (ns swarmpit.component.service.form-configs
(:require [material.component :as comp]
[material.component.form :as form]
[material.component.list-table-form :as list]
[swarmpit.component.state :as state]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[clojure.string :as str]
[rum.core :as rum]))
(enable-console-print!)
(def form-value-cursor (conj state/form-value-cursor :configs))
(def form-state-cursor (conj state/form-state-cursor :configs))
(def headers [{:name "Name"
:width "35%"}
{:name "Target"
:width "35%"}])
(def undefined-info
(form/value
[:span "No configs found. Create new "
[:a {:href (routes/path-for-frontend :config-create)} "config."]]))
(defn- form-config [value index configs-list]
(list/selectfield
{:name (str "form-config-select-" index)
:key (str "form-config-select-" index)
:value value
:onChange (fn [_ _ v]
(state/update-item index :configName v form-value-cursor))}
(->> configs-list
(map #(comp/menu-item
{:name (str "form-config-item-" (:configName %))
:key (str "form-config-item-" (:configName %))
:value (:configName %)
:primaryText (:configName %)})))))
(defn- form-config-target [value name index]
(list/textfield
{:name (str "form-config-target-" index)
:key (str "form-config-target-" index)
:hintText (when (str/blank? value)
name)
:value value
:onChange (fn [_ v]
(state/update-item index :configTarget v form-value-cursor))}))
(defn- render-configs
[item index data]
(let [{:keys [configName configTarget]} item]
[(form-config configName index data)
(form-config-target configTarget configName index)]))
(defn- form-table
[configs configs-list]
(form/form
{}
(list/table-raw headers
configs
configs-list
render-configs
(fn [index] (state/remove-item index form-value-cursor)))))
(defn- add-item
[]
(state/add-item {:configName ""
:configTarget ""} form-value-cursor))
(defn configs-handler
[]
(ajax/get
(routes/path-for-backend :configs)
{:on-success (fn [{:keys [response]}]
(state/update-value [:list] response form-state-cursor))}))
(rum/defc form < rum/reactive []
(let [{:keys [list]} (state/react form-state-cursor)
configs (state/react form-value-cursor)]
(if (empty? configs)
(form/value "No configs defined for the service.")
(if (empty? list)
undefined-info
(form-table configs list))))) | null | https://raw.githubusercontent.com/docker-in-aws/docker-in-aws/bfc7e82ac82ea158bfb03445da6aec167b1a14a3/ch16/swarmpit/src/cljs/swarmpit/component/service/form_configs.cljs | clojure | (ns swarmpit.component.service.form-configs
(:require [material.component :as comp]
[material.component.form :as form]
[material.component.list-table-form :as list]
[swarmpit.component.state :as state]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[clojure.string :as str]
[rum.core :as rum]))
(enable-console-print!)
(def form-value-cursor (conj state/form-value-cursor :configs))
(def form-state-cursor (conj state/form-state-cursor :configs))
(def headers [{:name "Name"
:width "35%"}
{:name "Target"
:width "35%"}])
(def undefined-info
(form/value
[:span "No configs found. Create new "
[:a {:href (routes/path-for-frontend :config-create)} "config."]]))
(defn- form-config [value index configs-list]
(list/selectfield
{:name (str "form-config-select-" index)
:key (str "form-config-select-" index)
:value value
:onChange (fn [_ _ v]
(state/update-item index :configName v form-value-cursor))}
(->> configs-list
(map #(comp/menu-item
{:name (str "form-config-item-" (:configName %))
:key (str "form-config-item-" (:configName %))
:value (:configName %)
:primaryText (:configName %)})))))
(defn- form-config-target [value name index]
(list/textfield
{:name (str "form-config-target-" index)
:key (str "form-config-target-" index)
:hintText (when (str/blank? value)
name)
:value value
:onChange (fn [_ v]
(state/update-item index :configTarget v form-value-cursor))}))
(defn- render-configs
[item index data]
(let [{:keys [configName configTarget]} item]
[(form-config configName index data)
(form-config-target configTarget configName index)]))
(defn- form-table
[configs configs-list]
(form/form
{}
(list/table-raw headers
configs
configs-list
render-configs
(fn [index] (state/remove-item index form-value-cursor)))))
(defn- add-item
[]
(state/add-item {:configName ""
:configTarget ""} form-value-cursor))
(defn configs-handler
[]
(ajax/get
(routes/path-for-backend :configs)
{:on-success (fn [{:keys [response]}]
(state/update-value [:list] response form-state-cursor))}))
(rum/defc form < rum/reactive []
(let [{:keys [list]} (state/react form-state-cursor)
configs (state/react form-value-cursor)]
(if (empty? configs)
(form/value "No configs defined for the service.")
(if (empty? list)
undefined-info
(form-table configs list))))) | |
5c139ab2f948c414d7a32a9f296947fcd36fc09e43f607694d8a8b4f3c915fb4 | CryptoKami/cryptokami-core | Lang.hs | -- | Language.
# OPTIONS_GHC -F -pgmF autoexporter #
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/auxx/src/Lang.hs | haskell | | Language. |
# OPTIONS_GHC -F -pgmF autoexporter #
|
7b84e38b9a3b2a423d395f008d3ed2b96bf9d154526fccc4dd93cb948338ded3 | airalab/hs-web3 | Engine.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : Network.Polkadot.Rpc.Engine
Copyright : 2016 - 2021
-- License : Apache-2.0
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Polkadot RPC methods with `engine` prefix.
--
module Network.Polkadot.Rpc.Engine where
import Data.ByteArray.HexString (HexString)
import Network.JsonRpc.TinyClient (JsonRpc (..))
import Network.Polkadot.Rpc.Types (CreatedBlock)
-- | Instructs the manual-seal authorship task to create a new block.
createBlock :: JsonRpc m
=> Bool
-- ^ Create empty
-> Bool
-- ^ Finalize
-> Maybe HexString
-- ^ Parent hash
-> m CreatedBlock
# INLINE createBlock #
createBlock = remote "engine_createBlock"
-- | Instructs the manual-seal authorship task to finalize a block.
finalizeBlock :: JsonRpc m
=> HexString
-- ^ Block hash
-> Maybe HexString
-- ^ Justification
-> m Bool
# INLINE finalizeBlock #
finalizeBlock = remote "engine_finalizeBlock"
| null | https://raw.githubusercontent.com/airalab/hs-web3/c03b86eb621f963886a78c39ee18bcec753f17ac/packages/polkadot/src/Network/Polkadot/Rpc/Engine.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : Network.Polkadot.Rpc.Engine
License : Apache-2.0
Maintainer :
Stability : experimental
Portability : portable
Polkadot RPC methods with `engine` prefix.
| Instructs the manual-seal authorship task to create a new block.
^ Create empty
^ Finalize
^ Parent hash
| Instructs the manual-seal authorship task to finalize a block.
^ Block hash
^ Justification | # LANGUAGE FlexibleContexts #
Copyright : 2016 - 2021
module Network.Polkadot.Rpc.Engine where
import Data.ByteArray.HexString (HexString)
import Network.JsonRpc.TinyClient (JsonRpc (..))
import Network.Polkadot.Rpc.Types (CreatedBlock)
createBlock :: JsonRpc m
=> Bool
-> Bool
-> Maybe HexString
-> m CreatedBlock
# INLINE createBlock #
createBlock = remote "engine_createBlock"
finalizeBlock :: JsonRpc m
=> HexString
-> Maybe HexString
-> m Bool
# INLINE finalizeBlock #
finalizeBlock = remote "engine_finalizeBlock"
|
f8769a544de555126fd5bcae57688e254c56215a6be00b3acca9e72d0b1438d1 | lsrcz/grisette | SimpleMergeable.hs | # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE PatternSynonyms #
# LANGUAGE QuantifiedConstraints #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE Trustworthy #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
-- |
Module : . Core . Data . Class . SimpleMergeable
Copyright : ( c ) 2021 - 2023
-- License : BSD-3-Clause (see the LICENSE file)
--
-- Maintainer :
-- Stability : Experimental
Portability : GHC only
module Grisette.Core.Data.Class.SimpleMergeable
( -- * Simple mergeable types
SimpleMergeable (..),
SimpleMergeable1 (..),
mrgIte1,
SimpleMergeable2 (..),
mrgIte2,
-- * UnionLike operations
UnionLike (..),
mrgIf,
merge,
mrgSingle,
UnionPrjOp (..),
pattern SingleU,
pattern IfU,
simpleMerge,
onUnion,
onUnion2,
onUnion3,
onUnion4,
(#~),
)
where
import Control.Monad.Except
import Control.Monad.Identity
import qualified Control.Monad.RWS.Lazy as RWSLazy
import qualified Control.Monad.RWS.Strict as RWSStrict
import Control.Monad.Reader
import qualified Control.Monad.State.Lazy as StateLazy
import qualified Control.Monad.State.Strict as StateStrict
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Maybe
import qualified Control.Monad.Writer.Lazy as WriterLazy
import qualified Control.Monad.Writer.Strict as WriterStrict
import Data.Kind
import GHC.Generics
import GHC.TypeNats
import Generics.Deriving
import Grisette.Core.Data.Class.Bool
import Grisette.Core.Data.Class.Function
import Grisette.Core.Data.Class.Mergeable
import Grisette.IR.SymPrim.Data.Prim.InternedTerm.Term
import {-# SOURCE #-} Grisette.IR.SymPrim.Data.SymPrim
-- $setup
> > > import . Core
> > > import . IR.SymPrim
> > > import Control . Monad . Identity
-- | Auxiliary class for the generic derivation for the 'SimpleMergeable' class.
class SimpleMergeable' f where
mrgIte' :: SymBool -> f a -> f a -> f a
instance (SimpleMergeable' U1) where
mrgIte' _ t _ = t
# INLINE mrgIte ' #
instance (SimpleMergeable' V1) where
mrgIte' _ t _ = t
# INLINE mrgIte ' #
instance (SimpleMergeable c) => (SimpleMergeable' (K1 i c)) where
mrgIte' cond (K1 a) (K1 b) = K1 $ mrgIte cond a b
# INLINE mrgIte ' #
instance (SimpleMergeable' a) => (SimpleMergeable' (M1 i c a)) where
mrgIte' cond (M1 a) (M1 b) = M1 $ mrgIte' cond a b
# INLINE mrgIte ' #
instance (SimpleMergeable' a, SimpleMergeable' b) => (SimpleMergeable' (a :*: b)) where
mrgIte' cond (a1 :*: a2) (b1 :*: b2) = mrgIte' cond a1 b1 :*: mrgIte' cond a2 b2
# INLINE mrgIte ' #
-- | This class indicates that a type has a simple root merge strategy.
--
-- __Note:__ This type class can be derived for algebraic data types.
You may need the @DerivingVia@ and @DerivingStrategies@ extensions .
--
-- > data X = ...
> deriving Generic
> deriving ( , SimpleMergeable ) via ( Default X )
class Mergeable a => SimpleMergeable a where
-- | Performs if-then-else with the simple root merge strategy.
--
-- >>> mrgIte "a" "b" "c" :: SymInteger
( ite a b c )
mrgIte :: SymBool -> a -> a -> a
instance (Generic a, Mergeable' (Rep a), SimpleMergeable' (Rep a)) => SimpleMergeable (Default a) where
mrgIte cond (Default a) (Default b) = Default $ to $ mrgIte' cond (from a) (from b)
# INLINE mrgIte #
-- | Lifting of the 'SimpleMergeable' class to unary type constructors.
class SimpleMergeable1 u where
-- | Lift 'mrgIte' through the type constructor.
--
> > > liftMrgIte mrgIte " a " ( Identity " b " ) ( Identity " c " ) : :
-- Identity (ite a b c)
liftMrgIte :: (SymBool -> a -> a -> a) -> SymBool -> u a -> u a -> u a
| Lift the standard ' mrgIte ' function through the type constructor .
--
> > > mrgIte1 " a " ( Identity " b " ) ( Identity " c " ) : :
-- Identity (ite a b c)
mrgIte1 :: (SimpleMergeable1 u, SimpleMergeable a) => SymBool -> u a -> u a -> u a
mrgIte1 = liftMrgIte mrgIte
# INLINE mrgIte1 #
-- | Lifting of the 'SimpleMergeable' class to binary type constructors.
class (Mergeable2 u) => SimpleMergeable2 u where
-- | Lift 'mrgIte' through the type constructor.
--
> > > liftMrgIte2 mrgIte mrgIte " a " ( " b " , " c " ) ( " d " , " e " ) : : ( SymInteger , SymBool )
( ( ite a b d),(ite a c e ) )
liftMrgIte2 :: (SymBool -> a -> a -> a) -> (SymBool -> b -> b -> b) -> SymBool -> u a b -> u a b -> u a b
| Lift the standard ' mrgIte ' function through the type constructor .
--
> > > mrgIte2 " a " ( " b " , " c " ) ( " d " , " e " ) : : ( SymInteger , SymBool )
( ( ite a b d),(ite a c e ) )
mrgIte2 :: (SimpleMergeable2 u, SimpleMergeable a, SimpleMergeable b) => SymBool -> u a b -> u a b -> u a b
mrgIte2 = liftMrgIte2 mrgIte mrgIte
# INLINE mrgIte2 #
-- | Special case of the 'Mergeable1' and 'SimpleMergeable1' class for type
constructors that are ' SimpleMergeable ' when applied to any ' '
-- types.
--
-- This type class is used to generalize the 'mrgIf' function to other
containers , for example , monad transformer transformed Unions .
class (SimpleMergeable1 u, Mergeable1 u) => UnionLike u where
-- | Wrap a single value in the union.
--
Note that this function can not propagate the ' ' knowledge .
--
> > > single " a " : :
-- <a>
> > > mrgSingle " a " : :
-- {a}
single :: a -> u a
| If - then - else on two union values .
--
Note that this function can not capture the ' ' knowledge . However ,
-- it may use the merging strategy from the branches to merge the results.
--
> > > unionIf " a " ( single " b " ) ( single " c " ) : :
-- <If a b c>
> > > unionIf " a " ( mrgSingle " b " ) ( single " c " ) : :
{ ( ite a b c ) }
unionIf :: SymBool -> u a -> u a -> u a
-- | Merge the contents with some merge strategy.
--
> > > mergeWithStrategy $ unionIf " a " ( single " b " ) ( single " c " ) : :
{ ( ite a b c ) }
--
-- __Note:__ Be careful to call this directly in your code.
-- The supplied merge strategy should be consistent with the type's root merge strategy,
-- or some internal invariants would be broken and the program can crash.
--
This function is to be called when the ' ' constraint can not be resolved ,
-- e.g., the merge strategy for the contained type is given with 'Mergeable1'.
-- In other cases, 'merge' is usually a better alternative.
mergeWithStrategy :: MergingStrategy a -> u a -> u a
-- | Symbolic @if@ control flow with the result merged with some merge strategy.
--
> > > mrgIfWithStrategy rootStrategy " a " ( mrgSingle " b " ) ( single " c " ) : :
{ ( ite a b c ) }
--
-- __Note:__ Be careful to call this directly in your code.
-- The supplied merge strategy should be consistent with the type's root merge strategy,
-- or some internal invariants would be broken and the program can crash.
--
This function is to be called when the ' ' constraint can not be resolved ,
-- e.g., the merge strategy for the contained type is given with 'Mergeable1'.
-- In other cases, 'mrgIf' is usually a better alternative.
mrgIfWithStrategy :: MergingStrategy a -> SymBool -> u a -> u a -> u a
mrgIfWithStrategy s cond l r = mergeWithStrategy s $ unionIf cond l r
# INLINE mrgIfWithStrategy #
| Wrap a single value in the union and capture the ' ' knowledge .
--
> > > mrgSingleWithStrategy " a " : :
-- {a}
--
-- __Note:__ Be careful to call this directly in your code.
-- The supplied merge strategy should be consistent with the type's root merge strategy,
-- or some internal invariants would be broken and the program can crash.
--
This function is to be called when the ' ' constraint can not be resolved ,
-- e.g., the merge strategy for the contained type is given with 'Mergeable1'.
-- In other cases, 'mrgSingle' is usually a better alternative.
mrgSingleWithStrategy :: MergingStrategy a -> a -> u a
mrgSingleWithStrategy s = mergeWithStrategy s . single
# INLINE mrgSingleWithStrategy #
-- | Symbolic @if@ control flow with the result merged with the type's root merge strategy.
--
Equivalent to ' ' rootStrategy'@.
--
> > > mrgIf " a " ( single " b " ) ( single " c " ) : :
{ ( ite a b c ) }
mrgIf :: (UnionLike u, Mergeable a) => SymBool -> u a -> u a -> u a
mrgIf = mrgIfWithStrategy rootStrategy
# INLINE mrgIf #
-- | Merge the contents with the type's root merge strategy.
--
Equivalent to @'mergeWithStrategy ' ' rootStrategy'@.
--
> > > merge $ unionIf " a " ( single " b " ) ( single " c " ) : :
{ ( ite a b c ) }
merge :: (UnionLike u, Mergeable a) => u a -> u a
merge = mergeWithStrategy rootStrategy
# INLINE merge #
-- | Wrap a single value in the type and propagate the type's root merge strategy.
--
-- Equivalent to @'mrgSingleWithStrategy' 'rootStrategy'@.
--
> > > mrgSingle " a " : :
-- {a}
mrgSingle :: (UnionLike u, Mergeable a) => a -> u a
mrgSingle = mrgSingleWithStrategy rootStrategy
# INLINE mrgSingle #
instance SimpleMergeable () where
mrgIte _ t _ = t
# INLINE mrgIte #
instance (SimpleMergeable a, SimpleMergeable b) => SimpleMergeable (a, b) where
mrgIte cond (a1, b1) (a2, b2) = (mrgIte cond a1 a2, mrgIte cond b1 b2)
# INLINE mrgIte #
instance (SimpleMergeable a) => SimpleMergeable1 ((,) a) where
liftMrgIte mb cond (a1, b1) (a2, b2) = (mrgIte cond a1 a2, mb cond b1 b2)
# INLINE liftMrgIte #
instance SimpleMergeable2 (,) where
liftMrgIte2 ma mb cond (a1, b1) (a2, b2) = (ma cond a1 a2, mb cond b1 b2)
# INLINE liftMrgIte2 #
instance
(SimpleMergeable a, SimpleMergeable b, SimpleMergeable c) =>
SimpleMergeable (a, b, c)
where
mrgIte cond (a1, b1, c1) (a2, b2, c2) = (mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d
) =>
SimpleMergeable (a, b, c, d)
where
mrgIte cond (a1, b1, c1, d1) (a2, b2, c2, d2) =
(mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2, mrgIte cond d1 d2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e
) =>
SimpleMergeable (a, b, c, d, e)
where
mrgIte cond (a1, b1, c1, d1, e1) (a2, b2, c2, d2, e2) =
(mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2, mrgIte cond d1 d2, mrgIte cond e1 e2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e,
SimpleMergeable f
) =>
SimpleMergeable (a, b, c, d, e, f)
where
mrgIte cond (a1, b1, c1, d1, e1, f1) (a2, b2, c2, d2, e2, f2) =
(mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2, mrgIte cond d1 d2, mrgIte cond e1 e2, mrgIte cond f1 f2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e,
SimpleMergeable f,
SimpleMergeable g
) =>
SimpleMergeable (a, b, c, d, e, f, g)
where
mrgIte cond (a1, b1, c1, d1, e1, f1, g1) (a2, b2, c2, d2, e2, f2, g2) =
( mrgIte cond a1 a2,
mrgIte cond b1 b2,
mrgIte cond c1 c2,
mrgIte cond d1 d2,
mrgIte cond e1 e2,
mrgIte cond f1 f2,
mrgIte cond g1 g2
)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e,
SimpleMergeable f,
SimpleMergeable g,
SimpleMergeable h
) =>
SimpleMergeable (a, b, c, d, e, f, g, h)
where
mrgIte cond (a1, b1, c1, d1, e1, f1, g1, h1) (a2, b2, c2, d2, e2, f2, g2, h2) =
( mrgIte cond a1 a2,
mrgIte cond b1 b2,
mrgIte cond c1 c2,
mrgIte cond d1 d2,
mrgIte cond e1 e2,
mrgIte cond f1 f2,
mrgIte cond g1 g2,
mrgIte cond h1 h2
)
# INLINE mrgIte #
instance SimpleMergeable b => SimpleMergeable (a -> b) where
mrgIte = mrgIte1
# INLINE mrgIte #
instance SimpleMergeable1 ((->) a) where
liftMrgIte ms cond t f v = ms cond (t v) (f v)
# INLINE liftMrgIte #
instance (UnionLike m, Mergeable a) => SimpleMergeable (MaybeT m a) where
mrgIte = mrgIf
# INLINE mrgIte #
instance (UnionLike m) => SimpleMergeable1 (MaybeT m) where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance (UnionLike m) => UnionLike (MaybeT m) where
mergeWithStrategy s (MaybeT v) = MaybeT $ mergeWithStrategy (liftRootStrategy s) v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (MaybeT t) (MaybeT f) = MaybeT $ mrgIfWithStrategy (liftRootStrategy s) cond t f
# INLINE mrgIfWithStrategy #
single = MaybeT . single . return
# INLINE single #
unionIf cond (MaybeT l) (MaybeT r) = MaybeT $ unionIf cond l r
# INLINE unionIf #
instance
(UnionLike m, Mergeable e, Mergeable a) =>
SimpleMergeable (ExceptT e m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(UnionLike m, Mergeable e) =>
SimpleMergeable1 (ExceptT e m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(UnionLike m, Mergeable e) =>
UnionLike (ExceptT e m)
where
mergeWithStrategy s (ExceptT v) = ExceptT $ mergeWithStrategy (liftRootStrategy s) v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (ExceptT t) (ExceptT f) = ExceptT $ mrgIfWithStrategy (liftRootStrategy s) cond t f
# INLINE mrgIfWithStrategy #
single = ExceptT . single . return
# INLINE single #
unionIf cond (ExceptT l) (ExceptT r) = ExceptT $ unionIf cond l r
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m) =>
SimpleMergeable (StateLazy.StateT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m) =>
SimpleMergeable1 (StateLazy.StateT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m) =>
UnionLike (StateLazy.StateT s m)
where
mergeWithStrategy ms (StateLazy.StateT f) =
StateLazy.StateT $ \v -> mergeWithStrategy (liftRootStrategy2 ms rootStrategy) $ f v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (StateLazy.StateT t) (StateLazy.StateT f) =
StateLazy.StateT $ \v -> mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond (t v) (f v)
# INLINE mrgIfWithStrategy #
single x = StateLazy.StateT $ \s -> single (x, s)
# INLINE single #
unionIf cond (StateLazy.StateT l) (StateLazy.StateT r) =
StateLazy.StateT $ \s -> unionIf cond (l s) (r s)
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m) =>
SimpleMergeable (StateStrict.StateT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m) =>
SimpleMergeable1 (StateStrict.StateT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m) =>
UnionLike (StateStrict.StateT s m)
where
mergeWithStrategy ms (StateStrict.StateT f) =
StateStrict.StateT $ \v -> mergeWithStrategy (liftRootStrategy2 ms rootStrategy) $ f v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (StateStrict.StateT t) (StateStrict.StateT f) =
StateStrict.StateT $ \v -> mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond (t v) (f v)
# INLINE mrgIfWithStrategy #
single x = StateStrict.StateT $ \s -> single (x, s)
# INLINE single #
unionIf cond (StateStrict.StateT l) (StateStrict.StateT r) =
StateStrict.StateT $ \s -> unionIf cond (l s) (r s)
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m, Monoid s) =>
SimpleMergeable (WriterLazy.WriterT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
SimpleMergeable1 (WriterLazy.WriterT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
UnionLike (WriterLazy.WriterT s m)
where
mergeWithStrategy ms (WriterLazy.WriterT f) = WriterLazy.WriterT $ mergeWithStrategy (liftRootStrategy2 ms rootStrategy) f
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (WriterLazy.WriterT t) (WriterLazy.WriterT f) =
WriterLazy.WriterT $ mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond t f
# INLINE mrgIfWithStrategy #
single x = WriterLazy.WriterT $ single (x, mempty)
# INLINE single #
unionIf cond (WriterLazy.WriterT l) (WriterLazy.WriterT r) =
WriterLazy.WriterT $ unionIf cond l r
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m, Monoid s) =>
SimpleMergeable (WriterStrict.WriterT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
SimpleMergeable1 (WriterStrict.WriterT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
UnionLike (WriterStrict.WriterT s m)
where
mergeWithStrategy ms (WriterStrict.WriterT f) = WriterStrict.WriterT $ mergeWithStrategy (liftRootStrategy2 ms rootStrategy) f
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (WriterStrict.WriterT t) (WriterStrict.WriterT f) =
WriterStrict.WriterT $ mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond t f
# INLINE mrgIfWithStrategy #
single x = WriterStrict.WriterT $ single (x, mempty)
# INLINE single #
unionIf cond (WriterStrict.WriterT l) (WriterStrict.WriterT r) =
WriterStrict.WriterT $ unionIf cond l r
# INLINE unionIf #
instance
(Mergeable a, UnionLike m) =>
SimpleMergeable (ReaderT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(UnionLike m) =>
SimpleMergeable1 (ReaderT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(UnionLike m) =>
UnionLike (ReaderT s m)
where
mergeWithStrategy ms (ReaderT f) = ReaderT $ \v -> mergeWithStrategy ms $ f v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (ReaderT t) (ReaderT f) =
ReaderT $ \v -> mrgIfWithStrategy s cond (t v) (f v)
# INLINE mrgIfWithStrategy #
single x = ReaderT $ \_ -> single x
# INLINE single #
unionIf cond (ReaderT l) (ReaderT r) = ReaderT $ \s -> unionIf cond (l s) (r s)
# INLINE unionIf #
instance (SimpleMergeable a) => SimpleMergeable (Identity a) where
mrgIte cond (Identity l) (Identity r) = Identity $ mrgIte cond l r
# INLINE mrgIte #
instance SimpleMergeable1 Identity where
liftMrgIte mite cond (Identity l) (Identity r) = Identity $ mite cond l r
# INLINE liftMrgIte #
instance (UnionLike m, Mergeable a) => SimpleMergeable (IdentityT m a) where
mrgIte = mrgIf
# INLINE mrgIte #
instance (UnionLike m) => SimpleMergeable1 (IdentityT m) where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance (UnionLike m) => UnionLike (IdentityT m) where
mergeWithStrategy ms (IdentityT f) =
IdentityT $ mergeWithStrategy ms f
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (IdentityT l) (IdentityT r) = IdentityT $ mrgIfWithStrategy s cond l r
# INLINE mrgIfWithStrategy #
single x = IdentityT $ single x
# INLINE single #
unionIf cond (IdentityT l) (IdentityT r) = IdentityT $ unionIf cond l r
# INLINE unionIf #
instance (UnionLike m, Mergeable r) => SimpleMergeable (ContT r m a) where
mrgIte cond (ContT l) (ContT r) = ContT $ \c -> mrgIf cond (l c) (r c)
# INLINE mrgIte #
instance (UnionLike m, Mergeable r) => SimpleMergeable1 (ContT r m) where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance (UnionLike m, Mergeable r) => UnionLike (ContT r m) where
mergeWithStrategy _ (ContT f) = ContT $ \c -> merge (f c)
# INLINE mergeWithStrategy #
mrgIfWithStrategy _ cond (ContT l) (ContT r) = ContT $ \c -> mrgIf cond (l c) (r c)
# INLINE mrgIfWithStrategy #
single x = ContT $ \c -> c x
# INLINE single #
unionIf cond (ContT l) (ContT r) = ContT $ \c -> unionIf cond (l c) (r c)
# INLINE unionIf #
instance
(Mergeable s, Mergeable w, Monoid w, Mergeable a, UnionLike m) =>
SimpleMergeable (RWSLazy.RWST r w s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
SimpleMergeable1 (RWSLazy.RWST r w s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
UnionLike (RWSLazy.RWST r w s m)
where
mergeWithStrategy ms (RWSLazy.RWST f) =
RWSLazy.RWST $ \r s -> mergeWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) $ f r s
# INLINE mergeWithStrategy #
mrgIfWithStrategy ms cond (RWSLazy.RWST t) (RWSLazy.RWST f) =
RWSLazy.RWST $ \r s -> mrgIfWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) cond (t r s) (f r s)
# INLINE mrgIfWithStrategy #
single x = RWSLazy.RWST $ \_ s -> single (x, s, mempty)
# INLINE single #
unionIf cond (RWSLazy.RWST t) (RWSLazy.RWST f) =
RWSLazy.RWST $ \r s -> unionIf cond (t r s) (f r s)
# INLINE unionIf #
instance
(Mergeable s, Mergeable w, Monoid w, Mergeable a, UnionLike m) =>
SimpleMergeable (RWSStrict.RWST r w s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
SimpleMergeable1 (RWSStrict.RWST r w s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
UnionLike (RWSStrict.RWST r w s m)
where
mergeWithStrategy ms (RWSStrict.RWST f) =
RWSStrict.RWST $ \r s -> mergeWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) $ f r s
# INLINE mergeWithStrategy #
mrgIfWithStrategy ms cond (RWSStrict.RWST t) (RWSStrict.RWST f) =
RWSStrict.RWST $ \r s -> mrgIfWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) cond (t r s) (f r s)
# INLINE mrgIfWithStrategy #
single x = RWSStrict.RWST $ \_ s -> single (x, s, mempty)
# INLINE single #
unionIf cond (RWSStrict.RWST t) (RWSStrict.RWST f) =
RWSStrict.RWST $ \r s -> unionIf cond (t r s) (f r s)
# INLINE unionIf #
-- | Union containers that can be projected back into single value or
-- if-guarded values.
class (UnionLike u) => UnionPrjOp (u :: Type -> Type) where
-- | Pattern match to extract single values.
--
> > > singleView ( single 1 : : )
-- Just 1
> > > singleView ( unionIf " a " ( single 1 ) ( single 2 ) : : )
-- Nothing
singleView :: u a -> Maybe a
-- | Pattern match to extract if values.
--
> > > ifView ( single 1 : : )
-- Nothing
> > > ifView ( unionIf " a " ( single 1 ) ( single 2 ) : : )
-- Just (a,<1>,<2>)
> > > ifView ( mrgIf " a " ( single 1 ) ( single 2 ) : : )
-- Just (a,{1},{2})
ifView :: u a -> Maybe (SymBool, u a, u a)
-- | The leftmost value in the union.
--
> > > leftMost ( unionIf " a " ( single 1 ) ( single 2 ) : : )
1
leftMost :: u a -> a
-- | Pattern match to extract single values with 'singleView'.
--
> > > case ( single 1 : : ) of SingleU v - > v
1
pattern SingleU :: UnionPrjOp u => a -> u a
pattern SingleU x <-
(singleView -> Just x)
where
SingleU x = single x
-- | Pattern match to extract guard values with 'ifView'
> > > case ( unionIf " a " ( single 1 ) ( single 2 ) : : ) of c t f - > ( c , t , f )
-- (a,<1>,<2>)
pattern IfU :: UnionPrjOp u => SymBool -> u a -> u a -> u a
pattern IfU c t f <-
(ifView -> Just (c, t, f))
where
IfU c t f = unionIf c t f
-- | Merge the simply mergeable values in a union, and extract the merged value.
--
-- In the following example, 'unionIf' will not merge the results, and
-- 'simpleMerge' will merge it and extract the single merged value.
--
-- >>> unionIf (ssym "a") (return $ ssym "b") (return $ ssym "c") :: UnionM SymBool
-- <If a b c>
-- >>> simpleMerge $ (unionIf (ssym "a") (return $ ssym "b") (return $ ssym "c") :: UnionM SymBool)
( ite a b c )
simpleMerge :: forall bool u a. (SimpleMergeable a, UnionLike u, UnionPrjOp u) => u a -> a
simpleMerge u = case merge u of
SingleU x -> x
_ -> error "Should not happen"
# INLINE simpleMerge #
-- | Lift a function to work on union values.
--
-- >>> sumU = onUnion sum
-- >>> sumU (unionIf "cond" (return ["a"]) (return ["b","c"]) :: UnionM [SymInteger])
( ite cond a ( + b c ) )
onUnion ::
forall bool u a r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> r) ->
(u a -> r)
onUnion f = simpleMerge . fmap f
-- | Lift a function to work on union values.
onUnion2 ::
forall bool u a b r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> b -> r) ->
(u a -> u b -> r)
onUnion2 f ua ub = simpleMerge $ f <$> ua <*> ub
-- | Lift a function to work on union values.
onUnion3 ::
forall bool u a b c r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> b -> c -> r) ->
(u a -> u b -> u c -> r)
onUnion3 f ua ub uc = simpleMerge $ f <$> ua <*> ub <*> uc
-- | Lift a function to work on union values.
onUnion4 ::
forall bool u a b c d r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> b -> c -> d -> r) ->
(u a -> u b -> u c -> u d -> r)
onUnion4 f ua ub uc ud = simpleMerge $ f <$> ua <*> ub <*> uc <*> ud
| Helper for applying functions on ' UnionPrjOp ' and ' SimpleMergeable ' .
--
> > > let f : : Integer - > UnionM Integer = \x - > mrgIf ( ssym " a " ) ( mrgSingle $ x + 1 ) ( mrgSingle $ x + 2 )
> > > f # ~ ( mrgIf ( ssym " b " : : SymBool ) ( mrgSingle 0 ) ( mrgSingle 2 ) : : )
{ If ( & & b a ) 1 ( If b 2 ( If a 3 4 ) ) }
(#~) ::
(Function f, SimpleMergeable (Ret f), UnionPrjOp u, Functor u) =>
f ->
u (Arg f) ->
Ret f
(#~) f u = simpleMerge $ fmap (f #) u
# INLINE ( # ~ ) #
infixl 9 #~
#define SIMPLE_MERGEABLE_SIMPLE(symtype) \
instance SimpleMergeable symtype where \
mrgIte = ites; \
# INLINE mrgIte #
#define SIMPLE_MERGEABLE_BV(symtype) \
instance (KnownNat n, 1 <= n) => SimpleMergeable (symtype n) where \
mrgIte = ites; \
# INLINE mrgIte #
#define SIMPLE_MERGEABLE_SOME_BV(symtype, bf) \
instance SimpleMergeable symtype where \
mrgIte c = bf (ites c) "mrgIte"; \
# INLINE mrgIte #
#define SIMPLE_MERGEABLE_FUN(op) \
instance (SupportedPrim ca, SupportedPrim cb, LinkedRep ca sa, LinkedRep cb sb) => SimpleMergeable (sa op sb) where \
mrgIte = ites; \
# INLINE mrgIte #
#if 1
SIMPLE_MERGEABLE_SIMPLE(SymBool)
SIMPLE_MERGEABLE_SIMPLE(SymInteger)
SIMPLE_MERGEABLE_BV(SymIntN)
SIMPLE_MERGEABLE_BV(SymWordN)
SIMPLE_MERGEABLE_SOME_BV(SomeSymIntN, binSomeSymIntNR1)
SIMPLE_MERGEABLE_SOME_BV(SomeSymWordN, binSomeSymWordNR1)
SIMPLE_MERGEABLE_FUN(=~>)
SIMPLE_MERGEABLE_FUN(-~>)
#endif
| null | https://raw.githubusercontent.com/lsrcz/grisette/a6de4acb2ffd43315b6a34def85860e4cd8c7c8a/src/Grisette/Core/Data/Class/SimpleMergeable.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
|
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : Experimental
* Simple mergeable types
* UnionLike operations
# SOURCE #
$setup
| Auxiliary class for the generic derivation for the 'SimpleMergeable' class.
| This class indicates that a type has a simple root merge strategy.
__Note:__ This type class can be derived for algebraic data types.
> data X = ...
| Performs if-then-else with the simple root merge strategy.
>>> mrgIte "a" "b" "c" :: SymInteger
| Lifting of the 'SimpleMergeable' class to unary type constructors.
| Lift 'mrgIte' through the type constructor.
Identity (ite a b c)
Identity (ite a b c)
| Lifting of the 'SimpleMergeable' class to binary type constructors.
| Lift 'mrgIte' through the type constructor.
| Special case of the 'Mergeable1' and 'SimpleMergeable1' class for type
types.
This type class is used to generalize the 'mrgIf' function to other
| Wrap a single value in the union.
<a>
{a}
it may use the merging strategy from the branches to merge the results.
<If a b c>
| Merge the contents with some merge strategy.
__Note:__ Be careful to call this directly in your code.
The supplied merge strategy should be consistent with the type's root merge strategy,
or some internal invariants would be broken and the program can crash.
e.g., the merge strategy for the contained type is given with 'Mergeable1'.
In other cases, 'merge' is usually a better alternative.
| Symbolic @if@ control flow with the result merged with some merge strategy.
__Note:__ Be careful to call this directly in your code.
The supplied merge strategy should be consistent with the type's root merge strategy,
or some internal invariants would be broken and the program can crash.
e.g., the merge strategy for the contained type is given with 'Mergeable1'.
In other cases, 'mrgIf' is usually a better alternative.
{a}
__Note:__ Be careful to call this directly in your code.
The supplied merge strategy should be consistent with the type's root merge strategy,
or some internal invariants would be broken and the program can crash.
e.g., the merge strategy for the contained type is given with 'Mergeable1'.
In other cases, 'mrgSingle' is usually a better alternative.
| Symbolic @if@ control flow with the result merged with the type's root merge strategy.
| Merge the contents with the type's root merge strategy.
| Wrap a single value in the type and propagate the type's root merge strategy.
Equivalent to @'mrgSingleWithStrategy' 'rootStrategy'@.
{a}
| Union containers that can be projected back into single value or
if-guarded values.
| Pattern match to extract single values.
Just 1
Nothing
| Pattern match to extract if values.
Nothing
Just (a,<1>,<2>)
Just (a,{1},{2})
| The leftmost value in the union.
| Pattern match to extract single values with 'singleView'.
| Pattern match to extract guard values with 'ifView'
(a,<1>,<2>)
| Merge the simply mergeable values in a union, and extract the merged value.
In the following example, 'unionIf' will not merge the results, and
'simpleMerge' will merge it and extract the single merged value.
>>> unionIf (ssym "a") (return $ ssym "b") (return $ ssym "c") :: UnionM SymBool
<If a b c>
>>> simpleMerge $ (unionIf (ssym "a") (return $ ssym "b") (return $ ssym "c") :: UnionM SymBool)
| Lift a function to work on union values.
>>> sumU = onUnion sum
>>> sumU (unionIf "cond" (return ["a"]) (return ["b","c"]) :: UnionM [SymInteger])
| Lift a function to work on union values.
| Lift a function to work on union values.
| Lift a function to work on union values.
| # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE KindSignatures #
# LANGUAGE PatternSynonyms #
# LANGUAGE QuantifiedConstraints #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE Trustworthy #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
Module : . Core . Data . Class . SimpleMergeable
Copyright : ( c ) 2021 - 2023
Portability : GHC only
module Grisette.Core.Data.Class.SimpleMergeable
SimpleMergeable (..),
SimpleMergeable1 (..),
mrgIte1,
SimpleMergeable2 (..),
mrgIte2,
UnionLike (..),
mrgIf,
merge,
mrgSingle,
UnionPrjOp (..),
pattern SingleU,
pattern IfU,
simpleMerge,
onUnion,
onUnion2,
onUnion3,
onUnion4,
(#~),
)
where
import Control.Monad.Except
import Control.Monad.Identity
import qualified Control.Monad.RWS.Lazy as RWSLazy
import qualified Control.Monad.RWS.Strict as RWSStrict
import Control.Monad.Reader
import qualified Control.Monad.State.Lazy as StateLazy
import qualified Control.Monad.State.Strict as StateStrict
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Maybe
import qualified Control.Monad.Writer.Lazy as WriterLazy
import qualified Control.Monad.Writer.Strict as WriterStrict
import Data.Kind
import GHC.Generics
import GHC.TypeNats
import Generics.Deriving
import Grisette.Core.Data.Class.Bool
import Grisette.Core.Data.Class.Function
import Grisette.Core.Data.Class.Mergeable
import Grisette.IR.SymPrim.Data.Prim.InternedTerm.Term
> > > import . Core
> > > import . IR.SymPrim
> > > import Control . Monad . Identity
class SimpleMergeable' f where
mrgIte' :: SymBool -> f a -> f a -> f a
instance (SimpleMergeable' U1) where
mrgIte' _ t _ = t
# INLINE mrgIte ' #
instance (SimpleMergeable' V1) where
mrgIte' _ t _ = t
# INLINE mrgIte ' #
instance (SimpleMergeable c) => (SimpleMergeable' (K1 i c)) where
mrgIte' cond (K1 a) (K1 b) = K1 $ mrgIte cond a b
# INLINE mrgIte ' #
instance (SimpleMergeable' a) => (SimpleMergeable' (M1 i c a)) where
mrgIte' cond (M1 a) (M1 b) = M1 $ mrgIte' cond a b
# INLINE mrgIte ' #
instance (SimpleMergeable' a, SimpleMergeable' b) => (SimpleMergeable' (a :*: b)) where
mrgIte' cond (a1 :*: a2) (b1 :*: b2) = mrgIte' cond a1 b1 :*: mrgIte' cond a2 b2
# INLINE mrgIte ' #
You may need the @DerivingVia@ and @DerivingStrategies@ extensions .
> deriving Generic
> deriving ( , SimpleMergeable ) via ( Default X )
class Mergeable a => SimpleMergeable a where
( ite a b c )
mrgIte :: SymBool -> a -> a -> a
instance (Generic a, Mergeable' (Rep a), SimpleMergeable' (Rep a)) => SimpleMergeable (Default a) where
mrgIte cond (Default a) (Default b) = Default $ to $ mrgIte' cond (from a) (from b)
# INLINE mrgIte #
class SimpleMergeable1 u where
> > > liftMrgIte mrgIte " a " ( Identity " b " ) ( Identity " c " ) : :
liftMrgIte :: (SymBool -> a -> a -> a) -> SymBool -> u a -> u a -> u a
| Lift the standard ' mrgIte ' function through the type constructor .
> > > mrgIte1 " a " ( Identity " b " ) ( Identity " c " ) : :
mrgIte1 :: (SimpleMergeable1 u, SimpleMergeable a) => SymBool -> u a -> u a -> u a
mrgIte1 = liftMrgIte mrgIte
# INLINE mrgIte1 #
class (Mergeable2 u) => SimpleMergeable2 u where
> > > liftMrgIte2 mrgIte mrgIte " a " ( " b " , " c " ) ( " d " , " e " ) : : ( SymInteger , SymBool )
( ( ite a b d),(ite a c e ) )
liftMrgIte2 :: (SymBool -> a -> a -> a) -> (SymBool -> b -> b -> b) -> SymBool -> u a b -> u a b -> u a b
| Lift the standard ' mrgIte ' function through the type constructor .
> > > mrgIte2 " a " ( " b " , " c " ) ( " d " , " e " ) : : ( SymInteger , SymBool )
( ( ite a b d),(ite a c e ) )
mrgIte2 :: (SimpleMergeable2 u, SimpleMergeable a, SimpleMergeable b) => SymBool -> u a b -> u a b -> u a b
mrgIte2 = liftMrgIte2 mrgIte mrgIte
# INLINE mrgIte2 #
constructors that are ' SimpleMergeable ' when applied to any ' '
containers , for example , monad transformer transformed Unions .
class (SimpleMergeable1 u, Mergeable1 u) => UnionLike u where
Note that this function can not propagate the ' ' knowledge .
> > > single " a " : :
> > > mrgSingle " a " : :
single :: a -> u a
| If - then - else on two union values .
Note that this function can not capture the ' ' knowledge . However ,
> > > unionIf " a " ( single " b " ) ( single " c " ) : :
> > > unionIf " a " ( mrgSingle " b " ) ( single " c " ) : :
{ ( ite a b c ) }
unionIf :: SymBool -> u a -> u a -> u a
> > > mergeWithStrategy $ unionIf " a " ( single " b " ) ( single " c " ) : :
{ ( ite a b c ) }
This function is to be called when the ' ' constraint can not be resolved ,
mergeWithStrategy :: MergingStrategy a -> u a -> u a
> > > mrgIfWithStrategy rootStrategy " a " ( mrgSingle " b " ) ( single " c " ) : :
{ ( ite a b c ) }
This function is to be called when the ' ' constraint can not be resolved ,
mrgIfWithStrategy :: MergingStrategy a -> SymBool -> u a -> u a -> u a
mrgIfWithStrategy s cond l r = mergeWithStrategy s $ unionIf cond l r
# INLINE mrgIfWithStrategy #
| Wrap a single value in the union and capture the ' ' knowledge .
> > > mrgSingleWithStrategy " a " : :
This function is to be called when the ' ' constraint can not be resolved ,
mrgSingleWithStrategy :: MergingStrategy a -> a -> u a
mrgSingleWithStrategy s = mergeWithStrategy s . single
# INLINE mrgSingleWithStrategy #
Equivalent to ' ' rootStrategy'@.
> > > mrgIf " a " ( single " b " ) ( single " c " ) : :
{ ( ite a b c ) }
mrgIf :: (UnionLike u, Mergeable a) => SymBool -> u a -> u a -> u a
mrgIf = mrgIfWithStrategy rootStrategy
# INLINE mrgIf #
Equivalent to @'mergeWithStrategy ' ' rootStrategy'@.
> > > merge $ unionIf " a " ( single " b " ) ( single " c " ) : :
{ ( ite a b c ) }
merge :: (UnionLike u, Mergeable a) => u a -> u a
merge = mergeWithStrategy rootStrategy
# INLINE merge #
> > > mrgSingle " a " : :
mrgSingle :: (UnionLike u, Mergeable a) => a -> u a
mrgSingle = mrgSingleWithStrategy rootStrategy
# INLINE mrgSingle #
instance SimpleMergeable () where
mrgIte _ t _ = t
# INLINE mrgIte #
instance (SimpleMergeable a, SimpleMergeable b) => SimpleMergeable (a, b) where
mrgIte cond (a1, b1) (a2, b2) = (mrgIte cond a1 a2, mrgIte cond b1 b2)
# INLINE mrgIte #
instance (SimpleMergeable a) => SimpleMergeable1 ((,) a) where
liftMrgIte mb cond (a1, b1) (a2, b2) = (mrgIte cond a1 a2, mb cond b1 b2)
# INLINE liftMrgIte #
instance SimpleMergeable2 (,) where
liftMrgIte2 ma mb cond (a1, b1) (a2, b2) = (ma cond a1 a2, mb cond b1 b2)
# INLINE liftMrgIte2 #
instance
(SimpleMergeable a, SimpleMergeable b, SimpleMergeable c) =>
SimpleMergeable (a, b, c)
where
mrgIte cond (a1, b1, c1) (a2, b2, c2) = (mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d
) =>
SimpleMergeable (a, b, c, d)
where
mrgIte cond (a1, b1, c1, d1) (a2, b2, c2, d2) =
(mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2, mrgIte cond d1 d2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e
) =>
SimpleMergeable (a, b, c, d, e)
where
mrgIte cond (a1, b1, c1, d1, e1) (a2, b2, c2, d2, e2) =
(mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2, mrgIte cond d1 d2, mrgIte cond e1 e2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e,
SimpleMergeable f
) =>
SimpleMergeable (a, b, c, d, e, f)
where
mrgIte cond (a1, b1, c1, d1, e1, f1) (a2, b2, c2, d2, e2, f2) =
(mrgIte cond a1 a2, mrgIte cond b1 b2, mrgIte cond c1 c2, mrgIte cond d1 d2, mrgIte cond e1 e2, mrgIte cond f1 f2)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e,
SimpleMergeable f,
SimpleMergeable g
) =>
SimpleMergeable (a, b, c, d, e, f, g)
where
mrgIte cond (a1, b1, c1, d1, e1, f1, g1) (a2, b2, c2, d2, e2, f2, g2) =
( mrgIte cond a1 a2,
mrgIte cond b1 b2,
mrgIte cond c1 c2,
mrgIte cond d1 d2,
mrgIte cond e1 e2,
mrgIte cond f1 f2,
mrgIte cond g1 g2
)
# INLINE mrgIte #
instance
( SimpleMergeable a,
SimpleMergeable b,
SimpleMergeable c,
SimpleMergeable d,
SimpleMergeable e,
SimpleMergeable f,
SimpleMergeable g,
SimpleMergeable h
) =>
SimpleMergeable (a, b, c, d, e, f, g, h)
where
mrgIte cond (a1, b1, c1, d1, e1, f1, g1, h1) (a2, b2, c2, d2, e2, f2, g2, h2) =
( mrgIte cond a1 a2,
mrgIte cond b1 b2,
mrgIte cond c1 c2,
mrgIte cond d1 d2,
mrgIte cond e1 e2,
mrgIte cond f1 f2,
mrgIte cond g1 g2,
mrgIte cond h1 h2
)
# INLINE mrgIte #
instance SimpleMergeable b => SimpleMergeable (a -> b) where
mrgIte = mrgIte1
# INLINE mrgIte #
instance SimpleMergeable1 ((->) a) where
liftMrgIte ms cond t f v = ms cond (t v) (f v)
# INLINE liftMrgIte #
instance (UnionLike m, Mergeable a) => SimpleMergeable (MaybeT m a) where
mrgIte = mrgIf
# INLINE mrgIte #
instance (UnionLike m) => SimpleMergeable1 (MaybeT m) where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance (UnionLike m) => UnionLike (MaybeT m) where
mergeWithStrategy s (MaybeT v) = MaybeT $ mergeWithStrategy (liftRootStrategy s) v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (MaybeT t) (MaybeT f) = MaybeT $ mrgIfWithStrategy (liftRootStrategy s) cond t f
# INLINE mrgIfWithStrategy #
single = MaybeT . single . return
# INLINE single #
unionIf cond (MaybeT l) (MaybeT r) = MaybeT $ unionIf cond l r
# INLINE unionIf #
instance
(UnionLike m, Mergeable e, Mergeable a) =>
SimpleMergeable (ExceptT e m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(UnionLike m, Mergeable e) =>
SimpleMergeable1 (ExceptT e m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(UnionLike m, Mergeable e) =>
UnionLike (ExceptT e m)
where
mergeWithStrategy s (ExceptT v) = ExceptT $ mergeWithStrategy (liftRootStrategy s) v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (ExceptT t) (ExceptT f) = ExceptT $ mrgIfWithStrategy (liftRootStrategy s) cond t f
# INLINE mrgIfWithStrategy #
single = ExceptT . single . return
# INLINE single #
unionIf cond (ExceptT l) (ExceptT r) = ExceptT $ unionIf cond l r
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m) =>
SimpleMergeable (StateLazy.StateT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m) =>
SimpleMergeable1 (StateLazy.StateT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m) =>
UnionLike (StateLazy.StateT s m)
where
mergeWithStrategy ms (StateLazy.StateT f) =
StateLazy.StateT $ \v -> mergeWithStrategy (liftRootStrategy2 ms rootStrategy) $ f v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (StateLazy.StateT t) (StateLazy.StateT f) =
StateLazy.StateT $ \v -> mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond (t v) (f v)
# INLINE mrgIfWithStrategy #
single x = StateLazy.StateT $ \s -> single (x, s)
# INLINE single #
unionIf cond (StateLazy.StateT l) (StateLazy.StateT r) =
StateLazy.StateT $ \s -> unionIf cond (l s) (r s)
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m) =>
SimpleMergeable (StateStrict.StateT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m) =>
SimpleMergeable1 (StateStrict.StateT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m) =>
UnionLike (StateStrict.StateT s m)
where
mergeWithStrategy ms (StateStrict.StateT f) =
StateStrict.StateT $ \v -> mergeWithStrategy (liftRootStrategy2 ms rootStrategy) $ f v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (StateStrict.StateT t) (StateStrict.StateT f) =
StateStrict.StateT $ \v -> mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond (t v) (f v)
# INLINE mrgIfWithStrategy #
single x = StateStrict.StateT $ \s -> single (x, s)
# INLINE single #
unionIf cond (StateStrict.StateT l) (StateStrict.StateT r) =
StateStrict.StateT $ \s -> unionIf cond (l s) (r s)
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m, Monoid s) =>
SimpleMergeable (WriterLazy.WriterT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
SimpleMergeable1 (WriterLazy.WriterT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
UnionLike (WriterLazy.WriterT s m)
where
mergeWithStrategy ms (WriterLazy.WriterT f) = WriterLazy.WriterT $ mergeWithStrategy (liftRootStrategy2 ms rootStrategy) f
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (WriterLazy.WriterT t) (WriterLazy.WriterT f) =
WriterLazy.WriterT $ mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond t f
# INLINE mrgIfWithStrategy #
single x = WriterLazy.WriterT $ single (x, mempty)
# INLINE single #
unionIf cond (WriterLazy.WriterT l) (WriterLazy.WriterT r) =
WriterLazy.WriterT $ unionIf cond l r
# INLINE unionIf #
instance
(Mergeable s, Mergeable a, UnionLike m, Monoid s) =>
SimpleMergeable (WriterStrict.WriterT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
SimpleMergeable1 (WriterStrict.WriterT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, UnionLike m, Monoid s) =>
UnionLike (WriterStrict.WriterT s m)
where
mergeWithStrategy ms (WriterStrict.WriterT f) = WriterStrict.WriterT $ mergeWithStrategy (liftRootStrategy2 ms rootStrategy) f
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (WriterStrict.WriterT t) (WriterStrict.WriterT f) =
WriterStrict.WriterT $ mrgIfWithStrategy (liftRootStrategy2 s rootStrategy) cond t f
# INLINE mrgIfWithStrategy #
single x = WriterStrict.WriterT $ single (x, mempty)
# INLINE single #
unionIf cond (WriterStrict.WriterT l) (WriterStrict.WriterT r) =
WriterStrict.WriterT $ unionIf cond l r
# INLINE unionIf #
instance
(Mergeable a, UnionLike m) =>
SimpleMergeable (ReaderT s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(UnionLike m) =>
SimpleMergeable1 (ReaderT s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(UnionLike m) =>
UnionLike (ReaderT s m)
where
mergeWithStrategy ms (ReaderT f) = ReaderT $ \v -> mergeWithStrategy ms $ f v
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (ReaderT t) (ReaderT f) =
ReaderT $ \v -> mrgIfWithStrategy s cond (t v) (f v)
# INLINE mrgIfWithStrategy #
single x = ReaderT $ \_ -> single x
# INLINE single #
unionIf cond (ReaderT l) (ReaderT r) = ReaderT $ \s -> unionIf cond (l s) (r s)
# INLINE unionIf #
instance (SimpleMergeable a) => SimpleMergeable (Identity a) where
mrgIte cond (Identity l) (Identity r) = Identity $ mrgIte cond l r
# INLINE mrgIte #
instance SimpleMergeable1 Identity where
liftMrgIte mite cond (Identity l) (Identity r) = Identity $ mite cond l r
# INLINE liftMrgIte #
instance (UnionLike m, Mergeable a) => SimpleMergeable (IdentityT m a) where
mrgIte = mrgIf
# INLINE mrgIte #
instance (UnionLike m) => SimpleMergeable1 (IdentityT m) where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance (UnionLike m) => UnionLike (IdentityT m) where
mergeWithStrategy ms (IdentityT f) =
IdentityT $ mergeWithStrategy ms f
# INLINE mergeWithStrategy #
mrgIfWithStrategy s cond (IdentityT l) (IdentityT r) = IdentityT $ mrgIfWithStrategy s cond l r
# INLINE mrgIfWithStrategy #
single x = IdentityT $ single x
# INLINE single #
unionIf cond (IdentityT l) (IdentityT r) = IdentityT $ unionIf cond l r
# INLINE unionIf #
instance (UnionLike m, Mergeable r) => SimpleMergeable (ContT r m a) where
mrgIte cond (ContT l) (ContT r) = ContT $ \c -> mrgIf cond (l c) (r c)
# INLINE mrgIte #
instance (UnionLike m, Mergeable r) => SimpleMergeable1 (ContT r m) where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance (UnionLike m, Mergeable r) => UnionLike (ContT r m) where
mergeWithStrategy _ (ContT f) = ContT $ \c -> merge (f c)
# INLINE mergeWithStrategy #
mrgIfWithStrategy _ cond (ContT l) (ContT r) = ContT $ \c -> mrgIf cond (l c) (r c)
# INLINE mrgIfWithStrategy #
single x = ContT $ \c -> c x
# INLINE single #
unionIf cond (ContT l) (ContT r) = ContT $ \c -> unionIf cond (l c) (r c)
# INLINE unionIf #
instance
(Mergeable s, Mergeable w, Monoid w, Mergeable a, UnionLike m) =>
SimpleMergeable (RWSLazy.RWST r w s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
SimpleMergeable1 (RWSLazy.RWST r w s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
UnionLike (RWSLazy.RWST r w s m)
where
mergeWithStrategy ms (RWSLazy.RWST f) =
RWSLazy.RWST $ \r s -> mergeWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) $ f r s
# INLINE mergeWithStrategy #
mrgIfWithStrategy ms cond (RWSLazy.RWST t) (RWSLazy.RWST f) =
RWSLazy.RWST $ \r s -> mrgIfWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) cond (t r s) (f r s)
# INLINE mrgIfWithStrategy #
single x = RWSLazy.RWST $ \_ s -> single (x, s, mempty)
# INLINE single #
unionIf cond (RWSLazy.RWST t) (RWSLazy.RWST f) =
RWSLazy.RWST $ \r s -> unionIf cond (t r s) (f r s)
# INLINE unionIf #
instance
(Mergeable s, Mergeable w, Monoid w, Mergeable a, UnionLike m) =>
SimpleMergeable (RWSStrict.RWST r w s m a)
where
mrgIte = mrgIf
# INLINE mrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
SimpleMergeable1 (RWSStrict.RWST r w s m)
where
liftMrgIte m = mrgIfWithStrategy (SimpleStrategy m)
# INLINE liftMrgIte #
instance
(Mergeable s, Mergeable w, Monoid w, UnionLike m) =>
UnionLike (RWSStrict.RWST r w s m)
where
mergeWithStrategy ms (RWSStrict.RWST f) =
RWSStrict.RWST $ \r s -> mergeWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) $ f r s
# INLINE mergeWithStrategy #
mrgIfWithStrategy ms cond (RWSStrict.RWST t) (RWSStrict.RWST f) =
RWSStrict.RWST $ \r s -> mrgIfWithStrategy (liftRootStrategy3 ms rootStrategy rootStrategy) cond (t r s) (f r s)
# INLINE mrgIfWithStrategy #
single x = RWSStrict.RWST $ \_ s -> single (x, s, mempty)
# INLINE single #
unionIf cond (RWSStrict.RWST t) (RWSStrict.RWST f) =
RWSStrict.RWST $ \r s -> unionIf cond (t r s) (f r s)
# INLINE unionIf #
class (UnionLike u) => UnionPrjOp (u :: Type -> Type) where
> > > singleView ( single 1 : : )
> > > singleView ( unionIf " a " ( single 1 ) ( single 2 ) : : )
singleView :: u a -> Maybe a
> > > ifView ( single 1 : : )
> > > ifView ( unionIf " a " ( single 1 ) ( single 2 ) : : )
> > > ifView ( mrgIf " a " ( single 1 ) ( single 2 ) : : )
ifView :: u a -> Maybe (SymBool, u a, u a)
> > > leftMost ( unionIf " a " ( single 1 ) ( single 2 ) : : )
1
leftMost :: u a -> a
> > > case ( single 1 : : ) of SingleU v - > v
1
pattern SingleU :: UnionPrjOp u => a -> u a
pattern SingleU x <-
(singleView -> Just x)
where
SingleU x = single x
> > > case ( unionIf " a " ( single 1 ) ( single 2 ) : : ) of c t f - > ( c , t , f )
pattern IfU :: UnionPrjOp u => SymBool -> u a -> u a -> u a
pattern IfU c t f <-
(ifView -> Just (c, t, f))
where
IfU c t f = unionIf c t f
( ite a b c )
simpleMerge :: forall bool u a. (SimpleMergeable a, UnionLike u, UnionPrjOp u) => u a -> a
simpleMerge u = case merge u of
SingleU x -> x
_ -> error "Should not happen"
# INLINE simpleMerge #
( ite cond a ( + b c ) )
onUnion ::
forall bool u a r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> r) ->
(u a -> r)
onUnion f = simpleMerge . fmap f
onUnion2 ::
forall bool u a b r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> b -> r) ->
(u a -> u b -> r)
onUnion2 f ua ub = simpleMerge $ f <$> ua <*> ub
onUnion3 ::
forall bool u a b c r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> b -> c -> r) ->
(u a -> u b -> u c -> r)
onUnion3 f ua ub uc = simpleMerge $ f <$> ua <*> ub <*> uc
onUnion4 ::
forall bool u a b c d r.
(SimpleMergeable r, UnionLike u, UnionPrjOp u, Monad u) =>
(a -> b -> c -> d -> r) ->
(u a -> u b -> u c -> u d -> r)
onUnion4 f ua ub uc ud = simpleMerge $ f <$> ua <*> ub <*> uc <*> ud
| Helper for applying functions on ' UnionPrjOp ' and ' SimpleMergeable ' .
> > > let f : : Integer - > UnionM Integer = \x - > mrgIf ( ssym " a " ) ( mrgSingle $ x + 1 ) ( mrgSingle $ x + 2 )
> > > f # ~ ( mrgIf ( ssym " b " : : SymBool ) ( mrgSingle 0 ) ( mrgSingle 2 ) : : )
{ If ( & & b a ) 1 ( If b 2 ( If a 3 4 ) ) }
(#~) ::
(Function f, SimpleMergeable (Ret f), UnionPrjOp u, Functor u) =>
f ->
u (Arg f) ->
Ret f
(#~) f u = simpleMerge $ fmap (f #) u
# INLINE ( # ~ ) #
infixl 9 #~
#define SIMPLE_MERGEABLE_SIMPLE(symtype) \
instance SimpleMergeable symtype where \
mrgIte = ites; \
# INLINE mrgIte #
#define SIMPLE_MERGEABLE_BV(symtype) \
instance (KnownNat n, 1 <= n) => SimpleMergeable (symtype n) where \
mrgIte = ites; \
# INLINE mrgIte #
#define SIMPLE_MERGEABLE_SOME_BV(symtype, bf) \
instance SimpleMergeable symtype where \
mrgIte c = bf (ites c) "mrgIte"; \
# INLINE mrgIte #
#define SIMPLE_MERGEABLE_FUN(op) \
instance (SupportedPrim ca, SupportedPrim cb, LinkedRep ca sa, LinkedRep cb sb) => SimpleMergeable (sa op sb) where \
mrgIte = ites; \
# INLINE mrgIte #
#if 1
SIMPLE_MERGEABLE_SIMPLE(SymBool)
SIMPLE_MERGEABLE_SIMPLE(SymInteger)
SIMPLE_MERGEABLE_BV(SymIntN)
SIMPLE_MERGEABLE_BV(SymWordN)
SIMPLE_MERGEABLE_SOME_BV(SomeSymIntN, binSomeSymIntNR1)
SIMPLE_MERGEABLE_SOME_BV(SomeSymWordN, binSomeSymWordNR1)
SIMPLE_MERGEABLE_FUN(=~>)
SIMPLE_MERGEABLE_FUN(-~>)
#endif
|
0b019f2fc29e9d0860256b642f150f0aacba4ad52c2bb3dbd754cc8f26119b86 | ryzhyk/cocoon | Parse.hs |
Copyrights ( c ) 2016 . Samsung Electronics Ltd. All right reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyrights (c) 2016. Samsung Electronics Ltd. All right reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
# LANGUAGE FlexibleContexts #
module Parse ( cocoonGrammar
, cfgGrammar) where
import Control.Applicative hiding (many,optional,Const)
import Text.Parsec hiding ((<|>))
import Text.Parsec.Expr
import Text.Parsec.Language
import qualified Text.Parsec.Token as T
import Data.Maybe
import Numeric
import Syntax
import Pos
import Util
reservedOpNames = ["?", "!", "|", "==", "=", ":=", "%", "+", "-", ".", "=>", "<=", "<=>", ">=", "<", ">", "!=", ">>", "<<"]
reservedNames = ["and",
"assume",
"bool",
"case",
"default",
"else",
"false",
"filter",
"fork",
"function",
"host",
"havoc",
"if",
"let",
"not",
"or",
"pkt",
"refine",
"role",
"send",
"struct",
"switch",
"then",
"true",
"typedef",
"uint"]
lexer = T.makeTokenParser (emptyDef {T.commentStart = "(*"
,T.commentEnd = "*)"
,T.nestedComments = True
,T.identStart = letter <|> char '_'
,T.identLetter = alphaNum <|> char '_'
,T.reservedOpNames = reservedOpNames
,T.reservedNames = reservedNames
,T.opLetter = oneOf ":%*+./=|"
,T.caseSensitive = True})
reservedOp = T.reservedOp lexer
reserved = T.reserved lexer
identifier = T.identifier lexer
--semiSep = T.semiSep lexer
--semiSep1 = T.semiSep1 lexer
colon = T.colon lexer
commaSep = T.commaSep lexer
commaSep1 = T.commaSep1 lexer
symbol = T.symbol lexer
semi = T.semi lexer
comma = T.comma lexer
braces = T.braces lexer
parens = T.parens lexer
angles = T.angles lexer
brackets = T.brackets lexer
natural = T.natural lexer
decimal = T.decimal lexer
integer = T.integer
whiteSpace = T.whiteSpace lexer
lexeme = T.lexeme lexer
dot = T.dot lexer
--stringLit = T.stringLiteral lexer
--charLit = T.charLiteral lexer
removeTabs = do s <- getInput
let s' = map (\c -> if c == '\t' then ' ' else c ) s
setInput s'
withPos x = (\s a e -> atPos a (s,e)) <$> getPosition <*> x <*> getPosition
data SpecItem = SpType TypeDef
| SpFunc Function
| SpRole Role
| SpAssume Assume
| SpNode Node
cocoonGrammar = Spec <$ removeTabs <*> ((optional whiteSpace) *> spec <* eof)
cfgGrammar = removeTabs *> ((optional whiteSpace) *> (many func) <* eof)
spec = (\r rs -> r:rs) <$> (withPos $ mkRefine [] <$> (many decl)) <*> (many refine)
mkRefine :: [String] -> [SpecItem] -> Refine
mkRefine targets items = Refine nopos targets types funcs roles assumes nodes
where types = mapMaybe (\i -> case i of
SpType t -> Just t
_ -> Nothing) items
funcs = mapMaybe (\i -> case i of
SpFunc f -> Just f
_ -> Nothing) items
roles = mapMaybe (\i -> case i of
SpRole r -> Just r
_ -> Nothing) items
assumes = mapMaybe (\i -> case i of
SpAssume a -> Just a
_ -> Nothing) items
nodes = mapMaybe (\i -> case i of
SpNode n -> Just n
_ -> Nothing) items
refine = withPos $ mkRefine <$ reserved "refine"
<*> (commaSep identifier)
<*> (braces $ many decl)
decl = (SpType <$> typeDef)
<|> (SpFunc <$> func)
<|> (SpRole <$> role)
<|> (SpAssume <$> assume)
<|> (SpNode <$> node)
typeDef = withPos $ (flip $ TypeDef nopos) <$ reserved "typedef" <*> typeSpec <*> identifier
func = withPos $ Function nopos <$ reserved "function"
<*> identifier
<*> (parens $ commaSep arg)
<*> (colon *> typeSpecSimple)
<*> (option (EBool nopos True) (reservedOp "|" *> expr))
<*> (optionMaybe (reservedOp "=" *> expr))
role = withPos $ Role nopos <$ reserved "role"
<*> identifier
<*> (brackets $ commaSep arg)
<*> (option (EBool nopos True) (reservedOp "|" *> expr))
<*> (option (EBool nopos True) (reservedOp "/" *> expr))
<*> (reservedOp "=" *> stat)
assume = withPos $ Assume nopos <$ reserved "assume" <*> (parens $ commaSep arg) <*> expr
node = withPos $ Node nopos <$> ((NodeSwitch <$ reserved "switch") <|> (NodeHost <$ reserved "host"))
<*> identifier
<*> (parens $ commaSep1 $ parens $ (,) <$> identifier <* comma <*> identifier)
arg = withPos $ flip (Field nopos) <$> typeSpecSimple <*> identifier
typeSpec = withPos $
arrType
<|> uintType
<|> boolType
<|> userType
<|> structType
typeSpecSimple = withPos $
arrType
<|> uintType
<|> boolType
<|> userType
uintType = TUInt nopos <$ reserved "uint" <*> (fromIntegral <$> angles decimal)
boolType = TBool nopos <$ reserved "bool"
userType = TUser nopos <$> identifier
arrType = brackets $ TArray nopos <$> typeSpecSimple <* semi <*> (fromIntegral <$> decimal)
structType = TStruct nopos <$ reserved "struct" <*> (braces $ commaSep1 arg)
expr = buildExpressionParser etable term
<?> "expression"
term = parens expr <|> term'
term' = withPos $
estruct
<|> ebuiltin
<|> eapply
<|> eloc
<|> eint
<|> ebool
<|> epacket
<|> evar
<|> edotvar
<|> econd
eapply = EApply nopos <$ isapply <*> identifier <*> (parens $ commaSep expr)
where isapply = try $ lookAhead $ identifier *> symbol "("
ebuiltin = EBuiltin nopos <$ isbuiltin <*> (identifier <* char '!') <*> (parens $ commaSep expr)
where isbuiltin = try $ lookAhead $ (identifier *> char '!') *> symbol "("
eloc = ELocation nopos <$ isloc <*> identifier <*> (brackets $ commaSep expr)
where isloc = try $ lookAhead $ identifier *> (brackets $ commaSep expr)
ebool = EBool nopos <$> ((True <$ reserved "true") <|> (False <$ reserved "false"))
epacket = EPacket nopos <$ reserved "pkt"
evar = EVar nopos <$> identifier
edotvar = EDotVar nopos <$ reservedOp "." <*> identifier
econd = (fmap uncurry (ECond nopos <$ reserved "case"))
<*> (braces $ (,) <$> (many $ (,) <$> expr <* colon <*> expr <* semi)
<*> (reserved "default" *> colon *> expr <* semi))
eint = EInt < $ > ( fromIntegral < $ > decimal )
eint = lexeme eint'
estruct = EStruct nopos <$ isstruct <*> identifier <*> (braces $ commaSep1 expr)
where isstruct = try $ lookAhead $ identifier *> symbol "{"
eint' = (lookAhead $ char '\'' <|> digit) *> (do w <- width
v <- sradval
mkLit w v)
width = optionMaybe (try $ ((fmap fromIntegral parseDec) <* (lookAhead $ char '\'')))
sradval = ((try $ string "'b") *> parseBin)
<|> ((try $ string "'o") *> parseOct)
<|> ((try $ string "'d") *> parseDec)
<|> ((try $ string "'h") *> parseHex)
<|> parseDec
parseBin :: Stream s m Char => ParsecT s u m Integer
parseBin = readBin <$> (many1 $ (char '0') <|> (char '1'))
parseOct :: Stream s m Char => ParsecT s u m Integer
parseOct = (fst . head . readOct) <$> many1 octDigit
parseDec :: Stream s m Char => ParsecT s u m Integer
parseDec = (fst . head . readDec) <$> many1 digit
parseSDec = ( \m v - > m * v )
< $ > ( option 1 ( ( -1 ) < $ reservedOp " - " ) )
-- <*> ((fst . head . readDec) <$> many1 digit)
parseHex :: Stream s m Char => ParsecT s u m Integer
parseHex = (fst . head . readHex) <$> many1 hexDigit
mkLit :: Maybe Int -> Integer -> ParsecT s u m Expr
mkLit Nothing v = return $ EInt nopos (msb v + 1) v
mkLit (Just w) v | w == 0 = fail "Unsigned literals must have width >0"
| msb v < w = return $ EInt nopos w v
| otherwise = fail "Value exceeds specified width"
etable = [[postf $ choice [postSlice, postField]]
,[pref $ choice [prefix "not" Not]]
,[binary "%" Mod AssocLeft]
,[binary "+" Plus AssocLeft,
binary "-" Minus AssocLeft]
,[binary ">>" ShiftR AssocLeft,
binary "<<" ShiftL AssocLeft]
,[binary "++" Concat AssocLeft]
,[binary "==" Eq AssocLeft,
binary "!=" Neq AssocLeft,
binary "<" Lt AssocNone,
binary "<=" Lte AssocNone,
binary ">" Gt AssocNone,
binary ">=" Gte AssocNone]
,[binary "and" And AssocLeft]
,[binary "or" Or AssocLeft]
,[binary "=>" Impl AssocLeft]
]
pref p = Prefix . chainl1 p $ return (.)
postf p = Postfix . chainl1 p $ return (flip (.))
postField = (\f end e -> EField (fst $ pos e, end) e f) <$> field <*> getPosition
postSlice = try $ (\(h,l) end e -> ESlice (fst $ pos e, end) e h l) <$> slice <*> getPosition
slice = brackets $ (\h l -> (fromInteger h, fromInteger l)) <$> natural <*> (colon *> natural)
field = dot *> identifier
prefix n fun = (\start e -> EUnOp (start, snd $ pos e) fun e) <$> getPosition <* reservedOp n
binary n fun = Infix $ (\le re -> EBinOp (fst $ pos le, snd $ pos re) fun le re) <$ reservedOp n
stat = buildExpressionParser stable stat'
<?> "statement"
stat' = braces stat
<|> parens stat
<|> simpleStat
simpleStat = withPos $
stest
<|> site
<|> ssendnd
<|> ssend
<|> sset
<|> shavoc
<|> sassume
<|> slet
<|> sfork
stest = STest nopos <$ reserved "filter" <*> expr
ssendnd = SSendND nopos <$ reservedOp "?" <* reserved "send" <*> identifier <*> (brackets expr)
ssend = SSend nopos <$ reserved "send" <*> expr
sset = SSet nopos <$> expr <*> (reservedOp ":=" *> expr)
site = SITE nopos <$ reserved "if" <*> expr <*> (reserved "then" *> stat') <*> (optionMaybe $ reserved "else" *> stat')
shavoc = SHavoc nopos <$ reserved "havoc" <*> expr
sassume = SAssume nopos <$ reserved "assume" <*> expr
slet = SLet nopos <$ reserved "let" <*> typeSpec <*> identifier <*> (reservedOp "=" *> expr)
sfork = (\(vs,c) st -> SFork nopos vs c st) <$ reserved "fork" <*> (parens $ (,) <$> (commaSep1 arg) <*> (reservedOp "|" *> expr)) <*> stat'
stable = [ [sbinary ";" SSeq AssocRight]
, [sbinary "|" SPar AssocRight]
]
sbinary n fun = Infix $ (\l r -> fun (fst $ pos l, snd $ pos r) l r) <$ reservedOp n
| null | https://raw.githubusercontent.com/ryzhyk/cocoon/409d10b848a4512e7cf653d5b6cf6ecf247eb794/cocoon/Parse.hs | haskell | semiSep = T.semiSep lexer
semiSep1 = T.semiSep1 lexer
stringLit = T.stringLiteral lexer
charLit = T.charLiteral lexer
<*> ((fst . head . readDec) <$> many1 digit) |
Copyrights ( c ) 2016 . Samsung Electronics Ltd. All right reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyrights (c) 2016. Samsung Electronics Ltd. All right reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
# LANGUAGE FlexibleContexts #
module Parse ( cocoonGrammar
, cfgGrammar) where
import Control.Applicative hiding (many,optional,Const)
import Text.Parsec hiding ((<|>))
import Text.Parsec.Expr
import Text.Parsec.Language
import qualified Text.Parsec.Token as T
import Data.Maybe
import Numeric
import Syntax
import Pos
import Util
reservedOpNames = ["?", "!", "|", "==", "=", ":=", "%", "+", "-", ".", "=>", "<=", "<=>", ">=", "<", ">", "!=", ">>", "<<"]
reservedNames = ["and",
"assume",
"bool",
"case",
"default",
"else",
"false",
"filter",
"fork",
"function",
"host",
"havoc",
"if",
"let",
"not",
"or",
"pkt",
"refine",
"role",
"send",
"struct",
"switch",
"then",
"true",
"typedef",
"uint"]
lexer = T.makeTokenParser (emptyDef {T.commentStart = "(*"
,T.commentEnd = "*)"
,T.nestedComments = True
,T.identStart = letter <|> char '_'
,T.identLetter = alphaNum <|> char '_'
,T.reservedOpNames = reservedOpNames
,T.reservedNames = reservedNames
,T.opLetter = oneOf ":%*+./=|"
,T.caseSensitive = True})
reservedOp = T.reservedOp lexer
reserved = T.reserved lexer
identifier = T.identifier lexer
colon = T.colon lexer
commaSep = T.commaSep lexer
commaSep1 = T.commaSep1 lexer
symbol = T.symbol lexer
semi = T.semi lexer
comma = T.comma lexer
braces = T.braces lexer
parens = T.parens lexer
angles = T.angles lexer
brackets = T.brackets lexer
natural = T.natural lexer
decimal = T.decimal lexer
integer = T.integer
whiteSpace = T.whiteSpace lexer
lexeme = T.lexeme lexer
dot = T.dot lexer
removeTabs = do s <- getInput
let s' = map (\c -> if c == '\t' then ' ' else c ) s
setInput s'
withPos x = (\s a e -> atPos a (s,e)) <$> getPosition <*> x <*> getPosition
data SpecItem = SpType TypeDef
| SpFunc Function
| SpRole Role
| SpAssume Assume
| SpNode Node
cocoonGrammar = Spec <$ removeTabs <*> ((optional whiteSpace) *> spec <* eof)
cfgGrammar = removeTabs *> ((optional whiteSpace) *> (many func) <* eof)
spec = (\r rs -> r:rs) <$> (withPos $ mkRefine [] <$> (many decl)) <*> (many refine)
mkRefine :: [String] -> [SpecItem] -> Refine
mkRefine targets items = Refine nopos targets types funcs roles assumes nodes
where types = mapMaybe (\i -> case i of
SpType t -> Just t
_ -> Nothing) items
funcs = mapMaybe (\i -> case i of
SpFunc f -> Just f
_ -> Nothing) items
roles = mapMaybe (\i -> case i of
SpRole r -> Just r
_ -> Nothing) items
assumes = mapMaybe (\i -> case i of
SpAssume a -> Just a
_ -> Nothing) items
nodes = mapMaybe (\i -> case i of
SpNode n -> Just n
_ -> Nothing) items
refine = withPos $ mkRefine <$ reserved "refine"
<*> (commaSep identifier)
<*> (braces $ many decl)
decl = (SpType <$> typeDef)
<|> (SpFunc <$> func)
<|> (SpRole <$> role)
<|> (SpAssume <$> assume)
<|> (SpNode <$> node)
typeDef = withPos $ (flip $ TypeDef nopos) <$ reserved "typedef" <*> typeSpec <*> identifier
func = withPos $ Function nopos <$ reserved "function"
<*> identifier
<*> (parens $ commaSep arg)
<*> (colon *> typeSpecSimple)
<*> (option (EBool nopos True) (reservedOp "|" *> expr))
<*> (optionMaybe (reservedOp "=" *> expr))
role = withPos $ Role nopos <$ reserved "role"
<*> identifier
<*> (brackets $ commaSep arg)
<*> (option (EBool nopos True) (reservedOp "|" *> expr))
<*> (option (EBool nopos True) (reservedOp "/" *> expr))
<*> (reservedOp "=" *> stat)
assume = withPos $ Assume nopos <$ reserved "assume" <*> (parens $ commaSep arg) <*> expr
node = withPos $ Node nopos <$> ((NodeSwitch <$ reserved "switch") <|> (NodeHost <$ reserved "host"))
<*> identifier
<*> (parens $ commaSep1 $ parens $ (,) <$> identifier <* comma <*> identifier)
arg = withPos $ flip (Field nopos) <$> typeSpecSimple <*> identifier
typeSpec = withPos $
arrType
<|> uintType
<|> boolType
<|> userType
<|> structType
typeSpecSimple = withPos $
arrType
<|> uintType
<|> boolType
<|> userType
uintType = TUInt nopos <$ reserved "uint" <*> (fromIntegral <$> angles decimal)
boolType = TBool nopos <$ reserved "bool"
userType = TUser nopos <$> identifier
arrType = brackets $ TArray nopos <$> typeSpecSimple <* semi <*> (fromIntegral <$> decimal)
structType = TStruct nopos <$ reserved "struct" <*> (braces $ commaSep1 arg)
expr = buildExpressionParser etable term
<?> "expression"
term = parens expr <|> term'
term' = withPos $
estruct
<|> ebuiltin
<|> eapply
<|> eloc
<|> eint
<|> ebool
<|> epacket
<|> evar
<|> edotvar
<|> econd
eapply = EApply nopos <$ isapply <*> identifier <*> (parens $ commaSep expr)
where isapply = try $ lookAhead $ identifier *> symbol "("
ebuiltin = EBuiltin nopos <$ isbuiltin <*> (identifier <* char '!') <*> (parens $ commaSep expr)
where isbuiltin = try $ lookAhead $ (identifier *> char '!') *> symbol "("
eloc = ELocation nopos <$ isloc <*> identifier <*> (brackets $ commaSep expr)
where isloc = try $ lookAhead $ identifier *> (brackets $ commaSep expr)
ebool = EBool nopos <$> ((True <$ reserved "true") <|> (False <$ reserved "false"))
epacket = EPacket nopos <$ reserved "pkt"
evar = EVar nopos <$> identifier
edotvar = EDotVar nopos <$ reservedOp "." <*> identifier
econd = (fmap uncurry (ECond nopos <$ reserved "case"))
<*> (braces $ (,) <$> (many $ (,) <$> expr <* colon <*> expr <* semi)
<*> (reserved "default" *> colon *> expr <* semi))
eint = EInt < $ > ( fromIntegral < $ > decimal )
eint = lexeme eint'
estruct = EStruct nopos <$ isstruct <*> identifier <*> (braces $ commaSep1 expr)
where isstruct = try $ lookAhead $ identifier *> symbol "{"
eint' = (lookAhead $ char '\'' <|> digit) *> (do w <- width
v <- sradval
mkLit w v)
width = optionMaybe (try $ ((fmap fromIntegral parseDec) <* (lookAhead $ char '\'')))
sradval = ((try $ string "'b") *> parseBin)
<|> ((try $ string "'o") *> parseOct)
<|> ((try $ string "'d") *> parseDec)
<|> ((try $ string "'h") *> parseHex)
<|> parseDec
parseBin :: Stream s m Char => ParsecT s u m Integer
parseBin = readBin <$> (many1 $ (char '0') <|> (char '1'))
parseOct :: Stream s m Char => ParsecT s u m Integer
parseOct = (fst . head . readOct) <$> many1 octDigit
parseDec :: Stream s m Char => ParsecT s u m Integer
parseDec = (fst . head . readDec) <$> many1 digit
parseSDec = ( \m v - > m * v )
< $ > ( option 1 ( ( -1 ) < $ reservedOp " - " ) )
parseHex :: Stream s m Char => ParsecT s u m Integer
parseHex = (fst . head . readHex) <$> many1 hexDigit
mkLit :: Maybe Int -> Integer -> ParsecT s u m Expr
mkLit Nothing v = return $ EInt nopos (msb v + 1) v
mkLit (Just w) v | w == 0 = fail "Unsigned literals must have width >0"
| msb v < w = return $ EInt nopos w v
| otherwise = fail "Value exceeds specified width"
etable = [[postf $ choice [postSlice, postField]]
,[pref $ choice [prefix "not" Not]]
,[binary "%" Mod AssocLeft]
,[binary "+" Plus AssocLeft,
binary "-" Minus AssocLeft]
,[binary ">>" ShiftR AssocLeft,
binary "<<" ShiftL AssocLeft]
,[binary "++" Concat AssocLeft]
,[binary "==" Eq AssocLeft,
binary "!=" Neq AssocLeft,
binary "<" Lt AssocNone,
binary "<=" Lte AssocNone,
binary ">" Gt AssocNone,
binary ">=" Gte AssocNone]
,[binary "and" And AssocLeft]
,[binary "or" Or AssocLeft]
,[binary "=>" Impl AssocLeft]
]
pref p = Prefix . chainl1 p $ return (.)
postf p = Postfix . chainl1 p $ return (flip (.))
postField = (\f end e -> EField (fst $ pos e, end) e f) <$> field <*> getPosition
postSlice = try $ (\(h,l) end e -> ESlice (fst $ pos e, end) e h l) <$> slice <*> getPosition
slice = brackets $ (\h l -> (fromInteger h, fromInteger l)) <$> natural <*> (colon *> natural)
field = dot *> identifier
prefix n fun = (\start e -> EUnOp (start, snd $ pos e) fun e) <$> getPosition <* reservedOp n
binary n fun = Infix $ (\le re -> EBinOp (fst $ pos le, snd $ pos re) fun le re) <$ reservedOp n
stat = buildExpressionParser stable stat'
<?> "statement"
stat' = braces stat
<|> parens stat
<|> simpleStat
simpleStat = withPos $
stest
<|> site
<|> ssendnd
<|> ssend
<|> sset
<|> shavoc
<|> sassume
<|> slet
<|> sfork
stest = STest nopos <$ reserved "filter" <*> expr
ssendnd = SSendND nopos <$ reservedOp "?" <* reserved "send" <*> identifier <*> (brackets expr)
ssend = SSend nopos <$ reserved "send" <*> expr
sset = SSet nopos <$> expr <*> (reservedOp ":=" *> expr)
site = SITE nopos <$ reserved "if" <*> expr <*> (reserved "then" *> stat') <*> (optionMaybe $ reserved "else" *> stat')
shavoc = SHavoc nopos <$ reserved "havoc" <*> expr
sassume = SAssume nopos <$ reserved "assume" <*> expr
slet = SLet nopos <$ reserved "let" <*> typeSpec <*> identifier <*> (reservedOp "=" *> expr)
sfork = (\(vs,c) st -> SFork nopos vs c st) <$ reserved "fork" <*> (parens $ (,) <$> (commaSep1 arg) <*> (reservedOp "|" *> expr)) <*> stat'
stable = [ [sbinary ";" SSeq AssocRight]
, [sbinary "|" SPar AssocRight]
]
sbinary n fun = Infix $ (\l r -> fun (fst $ pos l, snd $ pos r) l r) <$ reservedOp n
|
39d0d0a463047837bdbe5a838902e895a1231e6462a62cb02d75cc5521e1f7c6 | ranjitjhala/sprite-lang | Prims.hs | {-# LANGUAGE OverloadedStrings #-}
module Language.Sprite.L3.Prims where
import qualified Data.Maybe as Mb
import qualified Data.Map as M
import qualified Language.Fixpoint.Types as F
import qualified Language.Sprite.Common.UX as UX
import qualified Language . Sprite . Common . Misc as Misc
import Language.Sprite.L3.Types
import Language.Sprite.L3.Parse
-- | Primitive Types --------------------------------------------------
constTy :: F.SrcSpan -> Prim -> RType
constTy _ (PInt n) = TBase TInt (known $ F.exprReft (F.expr n))
constTy _ (PBool True) = TBase TBool (known $ F.propReft F.PTrue)
constTy _ (PBool False) = TBase TBool (known $ F.propReft F.PFalse)
constTy l (PBin o) = binOpTy l o
binOpTy :: F.SrcSpan -> PrimOp -> RType
binOpTy l o = Mb.fromMaybe err (M.lookup o binOpEnv)
where
err = UX.panicS ("Unknown PrimOp: " ++ show o) l
bTrue :: Base -> RType
bTrue b = TBase b mempty
binOpEnv :: M.Map PrimOp RType
binOpEnv = M.fromList
[ (BPlus , mkTy "x:int => y:int => int[v|v=x+y]")
, (BMinus, mkTy "x:int => y:int => int[v|v=x-y]")
, (BTimes, mkTy "x:int => y:int => int[v|v=x*y]")
, (BLt , mkTy "x:int => y:int => bool[v|v <=> (x < y)]")
, (BLe , mkTy "x:int => y:int => bool[v|v <=> (x <= y)]")
, (BGt , mkTy "x:int => y:int => bool[v|v <=> (x > y)]")
, (BGe , mkTy "x:int => y:int => bool[v|v <=> (x >= y)]")
, (BEq , mkTy "x:int => y:int => bool[v|v <=> (x == y)]")
, (BAnd , mkTy "x:bool => y:bool => bool[v|v <=> (x && y)]")
, (BOr , mkTy "x:bool => y:bool => bool[v|v <=> (x || y)]")
, (BNot , mkTy "x:bool => bool[v|v <=> not x]")
]
mkTy :: String -> RType
mkTy = {- Misc.traceShow "mkTy" . -} rebind . parseWith rtype "prims"
rebind :: RType -> RType
rebind t@(TBase {}) = t
rebind (TFun x s t) = TFun x' s' t'
where
x' = F.mappendSym "spec#" x
s' = subst (rebind s) x x'
t' = subst (rebind t) x x' | null | https://raw.githubusercontent.com/ranjitjhala/sprite-lang/bebfa8a8de6d558853145cbed8c511daa9bda3c7/src/Language/Sprite/L3/Prims.hs | haskell | # LANGUAGE OverloadedStrings #
| Primitive Types --------------------------------------------------
Misc.traceShow "mkTy" . |
module Language.Sprite.L3.Prims where
import qualified Data.Maybe as Mb
import qualified Data.Map as M
import qualified Language.Fixpoint.Types as F
import qualified Language.Sprite.Common.UX as UX
import qualified Language . Sprite . Common . Misc as Misc
import Language.Sprite.L3.Types
import Language.Sprite.L3.Parse
constTy :: F.SrcSpan -> Prim -> RType
constTy _ (PInt n) = TBase TInt (known $ F.exprReft (F.expr n))
constTy _ (PBool True) = TBase TBool (known $ F.propReft F.PTrue)
constTy _ (PBool False) = TBase TBool (known $ F.propReft F.PFalse)
constTy l (PBin o) = binOpTy l o
binOpTy :: F.SrcSpan -> PrimOp -> RType
binOpTy l o = Mb.fromMaybe err (M.lookup o binOpEnv)
where
err = UX.panicS ("Unknown PrimOp: " ++ show o) l
bTrue :: Base -> RType
bTrue b = TBase b mempty
binOpEnv :: M.Map PrimOp RType
binOpEnv = M.fromList
[ (BPlus , mkTy "x:int => y:int => int[v|v=x+y]")
, (BMinus, mkTy "x:int => y:int => int[v|v=x-y]")
, (BTimes, mkTy "x:int => y:int => int[v|v=x*y]")
, (BLt , mkTy "x:int => y:int => bool[v|v <=> (x < y)]")
, (BLe , mkTy "x:int => y:int => bool[v|v <=> (x <= y)]")
, (BGt , mkTy "x:int => y:int => bool[v|v <=> (x > y)]")
, (BGe , mkTy "x:int => y:int => bool[v|v <=> (x >= y)]")
, (BEq , mkTy "x:int => y:int => bool[v|v <=> (x == y)]")
, (BAnd , mkTy "x:bool => y:bool => bool[v|v <=> (x && y)]")
, (BOr , mkTy "x:bool => y:bool => bool[v|v <=> (x || y)]")
, (BNot , mkTy "x:bool => bool[v|v <=> not x]")
]
mkTy :: String -> RType
rebind :: RType -> RType
rebind t@(TBase {}) = t
rebind (TFun x s t) = TFun x' s' t'
where
x' = F.mappendSym "spec#" x
s' = subst (rebind s) x x'
t' = subst (rebind t) x x' |
2e6b6173357d3b0dbb0e0cff7f21d3ea4042a317ec66d3328ffe791a11d2710e | BillHallahan/G2 | LetFloating5.hs | module LetFloating4 where
f :: Int -> Int -> Int
f x y = x + g y
where
# NOINLINE g #
g :: Int -> Int
g z =
let
# NOINLINE h #
h = \q -> q + 1
in
z + h z
output19 :: Int -> Int -> Int -> Bool
output19 _ _ = (19 ==)
| null | https://raw.githubusercontent.com/BillHallahan/G2/dfd377793dcccdc7126a9f4a65b58249673e8a70/tests/TestFiles/LetFloating/LetFloating5.hs | haskell | module LetFloating4 where
f :: Int -> Int -> Int
f x y = x + g y
where
# NOINLINE g #
g :: Int -> Int
g z =
let
# NOINLINE h #
h = \q -> q + 1
in
z + h z
output19 :: Int -> Int -> Int -> Bool
output19 _ _ = (19 ==)
| |
dda83b551cf1dab83c9500c22cbe044ddb422d0c126e852a1acfd53710dd2198 | owlbarn/owl_ode | ode.ml |
* OWL - OCaml Scientific and Engineering Computing
* OWL - ODE - Ordinary Differential Equation Solvers
*
* Copyright ( c ) 2019 >
* Copyright ( c ) 2019 < >
* OWL - OCaml Scientific and Engineering Computing
* OWL-ODE - Ordinary Differential Equation Solvers
*
* Copyright (c) 2019 Ta-Chu Kao <>
* Copyright (c) 2019 Marcello Seri <>
*)
open Types
let step
(type a b c d)
(module Solver : Solver
with type f = a
and type solve_output = b
and type state = c
and type step_output = d)
(f : a)
~(dt : float)
(y0 : c)
(t0 : float)
=
Solver.step f ~dt y0 t0
let odeint
(type a b c d)
(module Solver : Solver
with type f = a
and type solve_output = b
and type state = c
and type step_output = d)
(f : a)
(y0 : c)
(tspec : tspec)
=
Solver.solve f y0 tspec
| null | https://raw.githubusercontent.com/owlbarn/owl_ode/5d934fbff87eea9f060d6c949bf78467024d8791/src/base/ode.ml | ocaml |
* OWL - OCaml Scientific and Engineering Computing
* OWL - ODE - Ordinary Differential Equation Solvers
*
* Copyright ( c ) 2019 >
* Copyright ( c ) 2019 < >
* OWL - OCaml Scientific and Engineering Computing
* OWL-ODE - Ordinary Differential Equation Solvers
*
* Copyright (c) 2019 Ta-Chu Kao <>
* Copyright (c) 2019 Marcello Seri <>
*)
open Types
let step
(type a b c d)
(module Solver : Solver
with type f = a
and type solve_output = b
and type state = c
and type step_output = d)
(f : a)
~(dt : float)
(y0 : c)
(t0 : float)
=
Solver.step f ~dt y0 t0
let odeint
(type a b c d)
(module Solver : Solver
with type f = a
and type solve_output = b
and type state = c
and type step_output = d)
(f : a)
(y0 : c)
(tspec : tspec)
=
Solver.solve f y0 tspec
| |
a7f3cbdd2cf34f58b6d5e4bf53dd05aebffbf2eb75ad74995240bf9b64fb123b | metabase/hawk | parallel.clj | (ns mb.hawk.parallel
"Code related to running parallel tests, and utilities for disallowing dangerous stuff inside them."
(:require
[clojure.test :as t]
[eftest.runner]))
(defn parallel?
"Whether `test-var` can be ran in parallel with other parallel tests."
[test-var]
(let [metta (meta test-var)]
(or (:parallel metta)
(:parallel (-> metta :ns meta)))))
(def ^:private synchronized? (complement parallel?))
(alter-var-root #'eftest.runner/synchronized? (constantly synchronized?))
(def ^:dynamic *parallel?*
"Whether test currently being ran is being ran in parallel."
nil)
(defn assert-test-is-not-parallel
"Throw an exception if we are inside a `^:parallel` test."
[disallowed-message]
(when *parallel?*
(let [e (ex-info (format "%s is not allowed inside parallel tests." disallowed-message) {})]
(t/is (throw e)))))
| null | https://raw.githubusercontent.com/metabase/hawk/47e3abf80d04d12f229aabffcf496f02cd9fffd5/src/mb/hawk/parallel.clj | clojure | (ns mb.hawk.parallel
"Code related to running parallel tests, and utilities for disallowing dangerous stuff inside them."
(:require
[clojure.test :as t]
[eftest.runner]))
(defn parallel?
"Whether `test-var` can be ran in parallel with other parallel tests."
[test-var]
(let [metta (meta test-var)]
(or (:parallel metta)
(:parallel (-> metta :ns meta)))))
(def ^:private synchronized? (complement parallel?))
(alter-var-root #'eftest.runner/synchronized? (constantly synchronized?))
(def ^:dynamic *parallel?*
"Whether test currently being ran is being ran in parallel."
nil)
(defn assert-test-is-not-parallel
"Throw an exception if we are inside a `^:parallel` test."
[disallowed-message]
(when *parallel?*
(let [e (ex-info (format "%s is not allowed inside parallel tests." disallowed-message) {})]
(t/is (throw e)))))
| |
e24de364621265d5e585039fa5fbfa866bfaeeefdf72d6ec9bf072ace69b069a | huangz1990/SICP-answers | 60-intersection-set.scm | ;;; 60-intersection-set.scm
(load "p103-element-of-set.scm")
(define (intersection-set set another)
(define (iter set result)
(if (or (null? set) (null? another))
(reverse result)
(let ((current-element (car set))
(remain-element (cdr set)))
(if (and (element-of-set? current-element another)
(not (element-of-set? current-element result)))
(iter remain-element
(cons current-element result))
(iter remain-element result)))))
(iter set '()))
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/60-intersection-set.scm | scheme | 60-intersection-set.scm |
(load "p103-element-of-set.scm")
(define (intersection-set set another)
(define (iter set result)
(if (or (null? set) (null? another))
(reverse result)
(let ((current-element (car set))
(remain-element (cdr set)))
(if (and (element-of-set? current-element another)
(not (element-of-set? current-element result)))
(iter remain-element
(cons current-element result))
(iter remain-element result)))))
(iter set '()))
|
8e24610eef2d1ae402f588cf88bf8af80d3be607dce550addd77e4a1ad6b9ae7 | facebook/duckling | Tests.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Ordinal.MN.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.MN.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "MN Tests"
[ makeCorpusTest [Seal Ordinal] corpus
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/Ordinal/MN/Tests.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Ordinal.MN.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.MN.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "MN Tests"
[ makeCorpusTest [Seal Ordinal] corpus
]
|
bc2993f8659d44f677500bd76523f9e7f8b836352efae4ff85dc2c25d60cb9fd | informatimago/lisp | manifest.lisp | -*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE : manifest.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; Check the licenses of the dependencies, write a manifest.
;;;;
< PJB > < >
MODIFICATIONS
2012 - 03 - 14 < PJB > Extracted from generate-cli.lisp
2014 - 02 - 21 < PJB > Exported print - manifest .
;;;;LEGAL
AGPL3
;;;;
Copyright 2012 - 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)))
(in-package "COMMON-LISP-USER")
(declaim (declaration also-use-packages))
(declaim (also-use-packages "ASDF"))
(defpackage "COM.INFORMATIMAGO.TOOLS.MANIFEST"
(:use "COMMON-LISP"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.VERSION"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"
"COM.INFORMATIMAGO.CLEXT.SHELL")
(:export "ASDF-SYSTEM-NAME"
"ASDF-SYSTEM-LICENSE"
"SYSTEM-DEPENDS-ON"
"SYSTEM-DEPENDS-ON/RECURSIVE"
"LISP-IMPLEMENTATION-TYPE-KEYWORD"
"VERSION"
"MACHINE-TYPE-KEYWORD"
"DISTRIBUTION"
"EXECUTABLE-NAME"
"EXECUTABLE-FILENAME"
"PRINT-MANIFEST"
"WRITE-MANIFEST"
"PRINT-BUG-REPORT-INFO"))
(in-package "COM.INFORMATIMAGO.TOOLS.MANIFEST")
(defparameter *system-licenses*
'(("cl-ppcre" . "BSD-2")
("split-sequence" . :unknown)
("terminfo" . "MIT")
("closer-mop" . "MIT")))
(defun asdf-system-name (system)
(slot-value system 'asdf::name))
(defun asdf-system-license (system-name)
(let ((system (asdf:find-system system-name)))
(or (cdr (assoc system-name *system-licenses* :test 'string-equal))
(and (slot-boundp system 'asdf::licence)
(slot-value system 'asdf::licence))
:unknown)))
#+mocl
(defun system-depends-on (system)
'())
#-mocl
(defun system-depends-on (system)
(delete (string-downcase system)
(delete-duplicates
(mapcar (lambda (dependency)
(etypecase dependency
(asdf:system (asdf:component-name dependency))
(string dependency)
(symbol (string-downcase dependency))
(: version " asdf " " 3.1.2 " )
(second dependency))))
(asdf:system-depends-on (asdf:find-system system)))
:test 'string=)
:test 'string=))
(defun system-depends-on/recursive (system)
(delete-duplicates
(transitive-closure
(function system-depends-on)
(list (string-downcase system)))
:test 'string=))
kuiper Linux kuiper 2.6.38 - gentoo - r6 - pjb - c9 # 2 SMP We d Jul 13 00:23:08 CEST 2011 x86_64 Intel(R ) Core(TM ) i7 CPU 950 @ GNU / Linux
hubble Linux hubble 2.6.34 - gentoo - r1 - d3 # 5 SMP PREEMPT Mon Sep 6 13:17:41 CEST 2010 i686 QEMU Virtual CPU version 0.13.0 GenuineIntel GNU / Linux
voyager Linux voyager.informatimago.com 2.6.18 - 6 - k7 # 1 SMP Mon Oct 13 16:52:47 UTC 2008 i686 GNU / Linux
triton 10.5.8 triton.lan.informatimago.com 9.8.0 Version 9.8.0 : We d Jul 15 16:57:01 PDT 2009 ; root : xnu-1228.15.4~1 / RELEASE_PPC Power Macintosh powerpc PowerBook6,8
neuron 10.5.8 neuron.intergruas.com 9.8.0 Version 9.8.0 : We d Jul 15 16:55:01 PDT 2009 ; root : xnu-1228.15.4~1 / RELEASE_I386 i386
galatea galatea.lan.informatimago.com 11.3.0 Version 11.3.0 : Thu Jan 12 18:48:32 PST 2012 ; root : xnu-1699.24.23~1 / RELEASE_I386 i386
galatea 10.7.5 Darwin galatea.lan.informatimago.com 11.4.2 Version 11.4.2 : Thu Aug 23 16:26:45 PDT 2012 ; root : xnu-1699.32.7~1 / RELEASE_I386 i386
despina 10.8 Darwin despina.home 12.5.0 Version 12.5.0 : Sun Sep 29 13:33:47 PDT 2013 ; root : xnu-2050.48.12~1 / RELEASE_X86_64 x86_64
10.9.2 larissa.home 13.1.0 Version 13.1.0 : Thu Jan 16 19:40:37 PST 2014 ; root : xnu-2422.90.20~2 / RELEASE_X86_64 x86_64 i386 MacBookAir6,2
(defun prepare-options (options)
(mapcar (lambda (option)
(typecase option
(keyword (format nil "-~(~A~)" option))
(symbol (string-downcase option))
(string option)
(t (prin1-to-string option))))
options))
(declaim (inline trim))
(defun trim (string)
(and string (string-trim #(#\space #\tab #\newline) string)))
(defun uname (&rest options)
"Without OPTIONS, return a keyword naming the system (:LINUX, :DARWIN, etc).
With options, returns the first line output by uname(1)."
(flet ((first-line (text) (subseq text 0 (position #\newline text))))
(let ((uname (shell-command-to-string "uname ~{~A~^ ~}" (prepare-options options))))
(if (and uname (plusp (length (trim uname))))
(values (if options
(first-line uname)
(intern (string-upcase (first-line uname))
"KEYWORD")))
:unknown))))
(defun distribution ()
"Return a list identifying the system, distribution and release.
RETURN: (system distrib release)
System and distrib are keywords, release is a string."
(flet ((words (string) (split-sequence-if (lambda (ch) (find ch #(#\space #\tab)))
string :remove-empty-subseqs t)))
(let ((system (or #+windows :windows
;; #+(and ccl windows-target)
' (: : unknown " 1.7.11,0.260,5,3 " )
#+linux :linux
#+darwin :darwin
#+(and unix (not (or linux darwin))) (uname)
:unknown))
(distrib :unknown)
(release :unknown))
(case system
#+(or unix linux)
(:linux
(cond
Checked with Linux 6.1
((with-open-file (inp "/etc/mandrake-release"
:if-does-not-exist nil)
(when inp
(setf release (fourth (words (read-line inp)))
distrib :mandrake))))
Checked with Linux RedHat 6.1 , 6.2 , 7.0
Checked with Linux Immunix 6.2 .
;; There seems to be no way to differenciate
;; a RedHat 6.2 from an Immunix 6.2.
((with-open-file (inp "/etc/redhat-release"
:if-does-not-exist nil)
(when inp
(setf release (fourth (words (read-line inp)))
distrib :redhat))))
Checked with Linux Conectiva 6.5
((with-open-file (inp "/etc/conectiva-release"
:if-does-not-exist nil)
(when inp
(setf release (third (words (read-line inp)))
distrib :conectiva))))
Checked with Linux SuSE 7.0 , 7.1
((with-open-file (inp "/etc/SuSE-release"
:if-does-not-exist nil)
(when inp
(setf release (loop
:for line = (read-line inp nil nil)
:while line
:when (search "VERSION" line)
:return (subseq line (let ((p (position #\= line)))
(if p (1+ p) 0)))
:finally (return :unknown))
distrib :suse))))
;; Checked with Linux DebIan 5.0.4
((with-open-file (inp "/etc/debian_version"
:if-does-not-exist nil)
(when inp
(setf release (read-line inp)
distrib :debian))))
Checked with Linux gentoo 1.12.9 , 1.12.13 , 2.0.3
((with-open-file (inp "/etc/gentoo-release"
:if-does-not-exist nil)
(when inp
(setf release (first (last (words (read-line inp))))
distrib :gentoo))))))
#+(or unix)
(:nextstep
(setf distrib :next)
(setf release (trim (shell-command-to-string "uname -r")))
(setf release (or release :unknown)))
#+(or unix darwin)
(:darwin
(when (probe-file "/System/Library/Frameworks/AppKit.framework/AppKit")
(setf distrib :apple))
(setf release (string-trim #(#\newline) (shell-command-to-string "sw_vers -productVersion"))))
#-(or linux darwin window)
(:unknown
(let ((host (trim (shell-command-to-string "hostinfo"))))
(cond
((prefixp "Mach" host)
(let ((words (words host)))
(setf distrib (fourth words)
release (sixth words))))))))
(list system distrib release))))
(defun lisp-implementation-type-keyword ()
"Return the keyword specific to each implementation (as found in *features*),
or else interns the (lisp-implementation-type), with space substituted by dashes
into the keyword package."
(or (cdr (assoc (lisp-implementation-type)
'(("Armed Bear Common Lisp" . :abcl)
("International Allegro CL Free Express Edition" . :allegro-cl-express)
("Clozure Common Lisp" . :ccl)
("CLISP" . :clisp)
("CMU Common Lisp" . :cmu)
("ECL" . :ecl)
("SBCL" . :sbcl))
:test (function string-equal)))
(intern (substitute #\- #\space (lisp-implementation-type)) "KEYWORD")))
(defun machine-type-keyword ()
"Return the keyword specific to machine type (as found in *features*),
or else interns the (machine-type), with space substituted by dashes
into the keyword package."
(or (cdr (assoc (machine-type)
'(("Power Macintosh" . :ppc)
("x86-64" . :x86-64)
("x86_64" . :x86-64)
("x64" . :x86-64)
("x86" . :x86)
("i686" . :i686)
("i386" . :i386))
:test (function string-equal)))
(intern (substitute #\- #\space (machine-type)) "KEYWORD")))
(defun lisp-version ()
(let ((v (lisp-implementation-version)))
(when (prefixp "Version " v)
(setf v (subseq v (length "Version "))))
(with-output-to-string (out)
(with-input-from-string (inp v)
(loop
:with state = :normal
:for ch = (read-char inp nil nil)
:while ch
:do (if (char= ch #\space)
(when (eq state :normal)
(setf state :space)
(write-char #\_ out))
(progn
(setf state :normal)
(case ch
((#\( #\))) ; deleted characters
((#\-) ; substituted characters
(write-char #\_ out))
(otherwise ; plain characters
(write-char ch out))))))))))
;; (list (lisp-implementation-version) (lisp-version))
(defun executable-name (base)
(format nil "~(~A-~A-~A-~{~A-~A-~A~}-~A~)"
base
(or (lisp-implementation-type-keyword) "unknown")
(lisp-version)
(distribution)
(or (machine-type-keyword) "unknown")))
(defun executable-filename (base)
(format nil "~A~A" (executable-name base)
#+(or windows win32) ".exe"
#-(or windows win32) ""))
(defun date ()
(multiple-value-bind (se mi ho da mo ye dow dls tz)
(decode-universal-time (get-universal-time))
(declare (ignore dow dls))
(format nil "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D ~:[+~;-~]~4,'0:D"
ye mo da ho mi se (minusp tz) (abs (* 100 tz)))))
(defun print-manifest (&optional system)
(let* ((entries '(date
lisp-implementation-type
lisp-implementation-version
machine-type
machine-version
machine-instance
distribution))
(width (reduce 'max entries :key (lambda (x) (length (string x))))))
(dolist (fun entries)
(format t "~(~VA~) : ~A~%" width fun (funcall fun))))
(terpri)
(when system
(let* ((entries (sort (mapcar (lambda (system)
(list system (asdf-system-license system)))
(system-depends-on/recursive system))
'string< :key 'first))
(system-width (reduce 'max entries :key (lambda (x) (length (first x)))))
(license-width (reduce 'max entries :key (lambda (x) (length (string (second x)))))))
(format t "~:(~VA~) ~:(~A~)~%~V,,,'-<~> ~V,,,'-<~>~%"
system-width 'system "license"
system-width license-width)
(loop
:for (system license) :in entries
:do (format t "~VA ~A~%" system-width system license))
(format t "~V,,,'-<~> ~V,,,'-<~>~%" system-width license-width))))
(defun write-manifest (program-name system)
"
DO: write a {program-name}-{distribution}.manifest file for the given SYSTEM.
RETURN: the pathname of the manifest file written.
"
(let* ((base (executable-name program-name))
(exec (executable-filename program-name))
(manifest-pathname (merge-pathnames (format nil "~A.manifest" base)
*default-pathname-defaults*)))
(with-open-file (*standard-output*
;; Bug in ccl:
;; "Version 1.9-r15757 (LinuxX8664)"
" Version 1.9 - r15759 ( DarwinX8664 ) "
;; doesn't use *default-pathname-defaults* :-(
manifest-pathname
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(format t "Manifest for ~A~%~V,,,'-<~>~2%" exec
(+ (length "Manifest for ") (length exec)))
(print-manifest system)
(terpri))
manifest-pathname))
;; TODO: see if we couldn't merge print-bug-report-info and print-manifest.
(defun print-bug-report-info ()
"Prints information for a bug report."
(let ((*print-pretty* t)
(*print-right-margin* 80))
(format t "~2%~{~28A ~S~%~}~2%"
(list "LISP-IMPLEMENTATION-TYPE" (lisp-implementation-type)
"LISP-IMPLEMENTATION-VERSION" (lisp-implementation-version)
"SOFTWARE-TYPE" (software-type)
"SOFTWARE-VERSION" (software-version)
"MACHINE-INSTANCE" (machine-instance)
"MACHINE-TYPE" (machine-type)
"MACHINE-VERSION" (machine-version)
"distribution" (distribution)
"uname -a" (ignore-errors (uname :a))
"*FEATURES*" *features*)))
(let ((cpuinfo (text-file-contents "/proc/cpuinfo" :if-does-not-exist nil)))
(when cpuinfo
(format t "~2%/proc/cpuinfo~%-------------~2%")
(write-string cpuinfo)
(terpri)))
#+clisp (with-open-stream (input (ext:run-program "uname" :arguments '("-a") :output :stream))
(format t ";;; uname -a~%")
(loop :for line = (read-line input nil nil) :while line :do (format t "~A~%" line)))
#+clisp (format t ";;; (EXT:ARGV)~%~S~%" (ext:argv))
#+clisp (ignore-errors
(let ((path (make-pathname
:type nil
:defaults (merge-pathnames
(make-pathname
:directory '(:relative :up :up :up "bin")
:name "clisp" :type nil :version nil)
(aref (ext:argv) 0) nil))))
(with-open-stream (input (ext:run-program path
:arguments '("--version")
:output :stream))
(format t ";;; ~A --version~%" path)
(loop :for line = (read-line input nil nil)
:while line
:do (format t "~A~%" line)))))
(values))
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/tools/manifest.lisp | lisp | coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
Check the licenses of the dependencies, write a manifest.
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
**************************************************************************
root : xnu-1228.15.4~1 / RELEASE_PPC Power Macintosh powerpc PowerBook6,8
root : xnu-1228.15.4~1 / RELEASE_I386 i386
root : xnu-1699.24.23~1 / RELEASE_I386 i386
root : xnu-1699.32.7~1 / RELEASE_I386 i386
root : xnu-2050.48.12~1 / RELEASE_X86_64 x86_64
root : xnu-2422.90.20~2 / RELEASE_X86_64 x86_64 i386 MacBookAir6,2
#+(and ccl windows-target)
There seems to be no way to differenciate
a RedHat 6.2 from an Immunix 6.2.
Checked with Linux DebIan 5.0.4
deleted characters
substituted characters
plain characters
(list (lisp-implementation-version) (lisp-version))
Bug in ccl:
"Version 1.9-r15757 (LinuxX8664)"
doesn't use *default-pathname-defaults* :-(
TODO: see if we couldn't merge print-bug-report-info and print-manifest.
THE END ;;;; | FILE : manifest.lisp
USER - INTERFACE :
< PJB > < >
MODIFICATIONS
2012 - 03 - 14 < PJB > Extracted from generate-cli.lisp
2014 - 02 - 21 < PJB > Exported print - manifest .
AGPL3
Copyright 2012 - 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
along with this program . If not , see /
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(declaim (declaration also-use-packages))
(declaim (also-use-packages "ASDF"))
(defpackage "COM.INFORMATIMAGO.TOOLS.MANIFEST"
(:use "COMMON-LISP"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.VERSION"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"
"COM.INFORMATIMAGO.CLEXT.SHELL")
(:export "ASDF-SYSTEM-NAME"
"ASDF-SYSTEM-LICENSE"
"SYSTEM-DEPENDS-ON"
"SYSTEM-DEPENDS-ON/RECURSIVE"
"LISP-IMPLEMENTATION-TYPE-KEYWORD"
"VERSION"
"MACHINE-TYPE-KEYWORD"
"DISTRIBUTION"
"EXECUTABLE-NAME"
"EXECUTABLE-FILENAME"
"PRINT-MANIFEST"
"WRITE-MANIFEST"
"PRINT-BUG-REPORT-INFO"))
(in-package "COM.INFORMATIMAGO.TOOLS.MANIFEST")
(defparameter *system-licenses*
'(("cl-ppcre" . "BSD-2")
("split-sequence" . :unknown)
("terminfo" . "MIT")
("closer-mop" . "MIT")))
(defun asdf-system-name (system)
(slot-value system 'asdf::name))
(defun asdf-system-license (system-name)
(let ((system (asdf:find-system system-name)))
(or (cdr (assoc system-name *system-licenses* :test 'string-equal))
(and (slot-boundp system 'asdf::licence)
(slot-value system 'asdf::licence))
:unknown)))
#+mocl
(defun system-depends-on (system)
'())
#-mocl
(defun system-depends-on (system)
(delete (string-downcase system)
(delete-duplicates
(mapcar (lambda (dependency)
(etypecase dependency
(asdf:system (asdf:component-name dependency))
(string dependency)
(symbol (string-downcase dependency))
(: version " asdf " " 3.1.2 " )
(second dependency))))
(asdf:system-depends-on (asdf:find-system system)))
:test 'string=)
:test 'string=))
(defun system-depends-on/recursive (system)
(delete-duplicates
(transitive-closure
(function system-depends-on)
(list (string-downcase system)))
:test 'string=))
kuiper Linux kuiper 2.6.38 - gentoo - r6 - pjb - c9 # 2 SMP We d Jul 13 00:23:08 CEST 2011 x86_64 Intel(R ) Core(TM ) i7 CPU 950 @ GNU / Linux
hubble Linux hubble 2.6.34 - gentoo - r1 - d3 # 5 SMP PREEMPT Mon Sep 6 13:17:41 CEST 2010 i686 QEMU Virtual CPU version 0.13.0 GenuineIntel GNU / Linux
voyager Linux voyager.informatimago.com 2.6.18 - 6 - k7 # 1 SMP Mon Oct 13 16:52:47 UTC 2008 i686 GNU / Linux
(defun prepare-options (options)
(mapcar (lambda (option)
(typecase option
(keyword (format nil "-~(~A~)" option))
(symbol (string-downcase option))
(string option)
(t (prin1-to-string option))))
options))
(declaim (inline trim))
(defun trim (string)
(and string (string-trim #(#\space #\tab #\newline) string)))
(defun uname (&rest options)
"Without OPTIONS, return a keyword naming the system (:LINUX, :DARWIN, etc).
With options, returns the first line output by uname(1)."
(flet ((first-line (text) (subseq text 0 (position #\newline text))))
(let ((uname (shell-command-to-string "uname ~{~A~^ ~}" (prepare-options options))))
(if (and uname (plusp (length (trim uname))))
(values (if options
(first-line uname)
(intern (string-upcase (first-line uname))
"KEYWORD")))
:unknown))))
(defun distribution ()
"Return a list identifying the system, distribution and release.
RETURN: (system distrib release)
System and distrib are keywords, release is a string."
(flet ((words (string) (split-sequence-if (lambda (ch) (find ch #(#\space #\tab)))
string :remove-empty-subseqs t)))
(let ((system (or #+windows :windows
' (: : unknown " 1.7.11,0.260,5,3 " )
#+linux :linux
#+darwin :darwin
#+(and unix (not (or linux darwin))) (uname)
:unknown))
(distrib :unknown)
(release :unknown))
(case system
#+(or unix linux)
(:linux
(cond
Checked with Linux 6.1
((with-open-file (inp "/etc/mandrake-release"
:if-does-not-exist nil)
(when inp
(setf release (fourth (words (read-line inp)))
distrib :mandrake))))
Checked with Linux RedHat 6.1 , 6.2 , 7.0
Checked with Linux Immunix 6.2 .
((with-open-file (inp "/etc/redhat-release"
:if-does-not-exist nil)
(when inp
(setf release (fourth (words (read-line inp)))
distrib :redhat))))
Checked with Linux Conectiva 6.5
((with-open-file (inp "/etc/conectiva-release"
:if-does-not-exist nil)
(when inp
(setf release (third (words (read-line inp)))
distrib :conectiva))))
Checked with Linux SuSE 7.0 , 7.1
((with-open-file (inp "/etc/SuSE-release"
:if-does-not-exist nil)
(when inp
(setf release (loop
:for line = (read-line inp nil nil)
:while line
:when (search "VERSION" line)
:return (subseq line (let ((p (position #\= line)))
(if p (1+ p) 0)))
:finally (return :unknown))
distrib :suse))))
((with-open-file (inp "/etc/debian_version"
:if-does-not-exist nil)
(when inp
(setf release (read-line inp)
distrib :debian))))
Checked with Linux gentoo 1.12.9 , 1.12.13 , 2.0.3
((with-open-file (inp "/etc/gentoo-release"
:if-does-not-exist nil)
(when inp
(setf release (first (last (words (read-line inp))))
distrib :gentoo))))))
#+(or unix)
(:nextstep
(setf distrib :next)
(setf release (trim (shell-command-to-string "uname -r")))
(setf release (or release :unknown)))
#+(or unix darwin)
(:darwin
(when (probe-file "/System/Library/Frameworks/AppKit.framework/AppKit")
(setf distrib :apple))
(setf release (string-trim #(#\newline) (shell-command-to-string "sw_vers -productVersion"))))
#-(or linux darwin window)
(:unknown
(let ((host (trim (shell-command-to-string "hostinfo"))))
(cond
((prefixp "Mach" host)
(let ((words (words host)))
(setf distrib (fourth words)
release (sixth words))))))))
(list system distrib release))))
(defun lisp-implementation-type-keyword ()
"Return the keyword specific to each implementation (as found in *features*),
or else interns the (lisp-implementation-type), with space substituted by dashes
into the keyword package."
(or (cdr (assoc (lisp-implementation-type)
'(("Armed Bear Common Lisp" . :abcl)
("International Allegro CL Free Express Edition" . :allegro-cl-express)
("Clozure Common Lisp" . :ccl)
("CLISP" . :clisp)
("CMU Common Lisp" . :cmu)
("ECL" . :ecl)
("SBCL" . :sbcl))
:test (function string-equal)))
(intern (substitute #\- #\space (lisp-implementation-type)) "KEYWORD")))
(defun machine-type-keyword ()
"Return the keyword specific to machine type (as found in *features*),
or else interns the (machine-type), with space substituted by dashes
into the keyword package."
(or (cdr (assoc (machine-type)
'(("Power Macintosh" . :ppc)
("x86-64" . :x86-64)
("x86_64" . :x86-64)
("x64" . :x86-64)
("x86" . :x86)
("i686" . :i686)
("i386" . :i386))
:test (function string-equal)))
(intern (substitute #\- #\space (machine-type)) "KEYWORD")))
(defun lisp-version ()
(let ((v (lisp-implementation-version)))
(when (prefixp "Version " v)
(setf v (subseq v (length "Version "))))
(with-output-to-string (out)
(with-input-from-string (inp v)
(loop
:with state = :normal
:for ch = (read-char inp nil nil)
:while ch
:do (if (char= ch #\space)
(when (eq state :normal)
(setf state :space)
(write-char #\_ out))
(progn
(setf state :normal)
(case ch
(write-char #\_ out))
(write-char ch out))))))))))
(defun executable-name (base)
(format nil "~(~A-~A-~A-~{~A-~A-~A~}-~A~)"
base
(or (lisp-implementation-type-keyword) "unknown")
(lisp-version)
(distribution)
(or (machine-type-keyword) "unknown")))
(defun executable-filename (base)
(format nil "~A~A" (executable-name base)
#+(or windows win32) ".exe"
#-(or windows win32) ""))
(defun date ()
(multiple-value-bind (se mi ho da mo ye dow dls tz)
(decode-universal-time (get-universal-time))
(declare (ignore dow dls))
(format nil "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D ~:[+~;-~]~4,'0:D"
ye mo da ho mi se (minusp tz) (abs (* 100 tz)))))
(defun print-manifest (&optional system)
(let* ((entries '(date
lisp-implementation-type
lisp-implementation-version
machine-type
machine-version
machine-instance
distribution))
(width (reduce 'max entries :key (lambda (x) (length (string x))))))
(dolist (fun entries)
(format t "~(~VA~) : ~A~%" width fun (funcall fun))))
(terpri)
(when system
(let* ((entries (sort (mapcar (lambda (system)
(list system (asdf-system-license system)))
(system-depends-on/recursive system))
'string< :key 'first))
(system-width (reduce 'max entries :key (lambda (x) (length (first x)))))
(license-width (reduce 'max entries :key (lambda (x) (length (string (second x)))))))
(format t "~:(~VA~) ~:(~A~)~%~V,,,'-<~> ~V,,,'-<~>~%"
system-width 'system "license"
system-width license-width)
(loop
:for (system license) :in entries
:do (format t "~VA ~A~%" system-width system license))
(format t "~V,,,'-<~> ~V,,,'-<~>~%" system-width license-width))))
(defun write-manifest (program-name system)
"
DO: write a {program-name}-{distribution}.manifest file for the given SYSTEM.
RETURN: the pathname of the manifest file written.
"
(let* ((base (executable-name program-name))
(exec (executable-filename program-name))
(manifest-pathname (merge-pathnames (format nil "~A.manifest" base)
*default-pathname-defaults*)))
(with-open-file (*standard-output*
" Version 1.9 - r15759 ( DarwinX8664 ) "
manifest-pathname
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(format t "Manifest for ~A~%~V,,,'-<~>~2%" exec
(+ (length "Manifest for ") (length exec)))
(print-manifest system)
(terpri))
manifest-pathname))
(defun print-bug-report-info ()
"Prints information for a bug report."
(let ((*print-pretty* t)
(*print-right-margin* 80))
(format t "~2%~{~28A ~S~%~}~2%"
(list "LISP-IMPLEMENTATION-TYPE" (lisp-implementation-type)
"LISP-IMPLEMENTATION-VERSION" (lisp-implementation-version)
"SOFTWARE-TYPE" (software-type)
"SOFTWARE-VERSION" (software-version)
"MACHINE-INSTANCE" (machine-instance)
"MACHINE-TYPE" (machine-type)
"MACHINE-VERSION" (machine-version)
"distribution" (distribution)
"uname -a" (ignore-errors (uname :a))
"*FEATURES*" *features*)))
(let ((cpuinfo (text-file-contents "/proc/cpuinfo" :if-does-not-exist nil)))
(when cpuinfo
(format t "~2%/proc/cpuinfo~%-------------~2%")
(write-string cpuinfo)
(terpri)))
#+clisp (with-open-stream (input (ext:run-program "uname" :arguments '("-a") :output :stream))
(format t ";;; uname -a~%")
(loop :for line = (read-line input nil nil) :while line :do (format t "~A~%" line)))
#+clisp (format t ";;; (EXT:ARGV)~%~S~%" (ext:argv))
#+clisp (ignore-errors
(let ((path (make-pathname
:type nil
:defaults (merge-pathnames
(make-pathname
:directory '(:relative :up :up :up "bin")
:name "clisp" :type nil :version nil)
(aref (ext:argv) 0) nil))))
(with-open-stream (input (ext:run-program path
:arguments '("--version")
:output :stream))
(format t ";;; ~A --version~%" path)
(loop :for line = (read-line input nil nil)
:while line
:do (format t "~A~%" line)))))
(values))
|
2022911ed675954c68f8b8e92b2a1ab5da947befdc2d4adcfcbbe25b6c5042ff | dfordivam/tenjinreader | TopWidget.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecursiveDo #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE CPP #
module TopWidget
(topWidget
, readable_bootstrap_css
, custom_css)
where
import FrontendCommon
import SrsWidget
import KanjiBrowser
import TextReader
import ImportWidget
-- from package common
import Common
import Message
import qualified Data.Map as Map
import qualified Data.Text as T
import qualified Data.Set as Set
import Control.Lens.Indexed
import Reflex.Dom.Location
import Data.FileEmbed
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString as BS
import qualified Data.Text as T
import GHCJS.DOM
import GHCJS.DOM.Document
import GHCJS.DOM.Element
import qualified Language.Javascript.JSaddle.Types as X
topWidget :: MonadWidget t m => m ()
topWidget = do
urlPath <- getLocationPath
urlHost <- getLocationHost
proto <- getLocationProtocol
let
url = ws <> host <> path
path = (fst $ T.breakOn "static" urlPath) <> "websocket"
host = if T.isPrefixOf "localhost" urlHost
then "localhost:3000"
else urlHost
ws = case proto of
"http:" -> "ws://"
_ -> "wss://"
(_,wsConn) <- withWSConnection
url
never -- close event
True -- reconnect
widget
#if defined (DEBUG)
let resp = traceEvent ("Response") (_webSocket_recv wsConn)
d <- holdDyn "" resp
dynText ((tshow . BS.length) <$> d)
#endif
return ()
widget :: AppMonad t m => AppMonadT t m ()
widget = divClass "container" $ do
-- navigation with visibility control
tabDisplayUI wrapper "nav navbar-nav" "active" "" $
Map.fromList [
#if !defined (ONLY_READER) && !defined (ONLY_SRS)
(2, ("Sentence", sentenceWidget))
, (3, ("Vocab", vocabSearchWidget))
, (4, ("Kanji", kanjiBrowseWidget))
, (5, ("Import", importWidgetTop))
,
#endif
#if !defined (ONLY_SRS)
(0, ("Reader", textReaderTop))
#endif
#if !defined (ONLY_READER) && !defined (ONLY_SRS)
,
#endif
#if !defined (ONLY_READER)
(1, ("SRS", srsWidget))
#endif
]
wrapper m = elClass "nav" "navbar navbar-default" $
divClass "container-fluid" $ do
divClass "navbar-header" $
elClass "a" "navbar-brand" $ text "てんじん"
a <- m
elClass "ul" "nav navbar-nav navbar-right" $ do
el "li" $ elAttr "a" ("href" =: "")
$ text "Logout"
ev <- el "li" $ btn "navbar-btn btn-default" "Theme"
toggleTheme ev
return a
readable_bootstrap_css = $(embedFile "src/readable_bootstrap.min.css")
custom_css = $(embedFile "src/custom.css")
slate_bootstrap_css = $(embedFile "src/slate_bootstrap.min.css")
toggleTheme :: AppMonad t m
=> Event t ()
-> AppMonadT t m ()
toggleTheme ev = do
rec
d <- holdDyn False (not <$> (tag (current d) ev))
let
toggleW b = X.liftJSM $ do
let css = custom_css <> if b
then slate_bootstrap_css
else readable_bootstrap_css
doc <- currentDocumentUnchecked
headElement <- getHeadUnchecked doc
setInnerHTML headElement $
"<style>" <> T.unpack (decodeUtf8 css)
<> "</style>" --TODO: Fix this
void $ widgetHold (return ())
(toggleW <$> updated d)
| null | https://raw.githubusercontent.com/dfordivam/tenjinreader/894a6f6b23d52c9c048740c0ea62f4c0f47d9561/frontend/src/TopWidget.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE ConstraintKinds #
# LANGUAGE RankNTypes #
from package common
close event
reconnect
navigation with visibility control
TODO: Fix this | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecursiveDo #
# LANGUAGE CPP #
module TopWidget
(topWidget
, readable_bootstrap_css
, custom_css)
where
import FrontendCommon
import SrsWidget
import KanjiBrowser
import TextReader
import ImportWidget
import Common
import Message
import qualified Data.Map as Map
import qualified Data.Text as T
import qualified Data.Set as Set
import Control.Lens.Indexed
import Reflex.Dom.Location
import Data.FileEmbed
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString as BS
import qualified Data.Text as T
import GHCJS.DOM
import GHCJS.DOM.Document
import GHCJS.DOM.Element
import qualified Language.Javascript.JSaddle.Types as X
topWidget :: MonadWidget t m => m ()
topWidget = do
urlPath <- getLocationPath
urlHost <- getLocationHost
proto <- getLocationProtocol
let
url = ws <> host <> path
path = (fst $ T.breakOn "static" urlPath) <> "websocket"
host = if T.isPrefixOf "localhost" urlHost
then "localhost:3000"
else urlHost
ws = case proto of
"http:" -> "ws://"
_ -> "wss://"
(_,wsConn) <- withWSConnection
url
widget
#if defined (DEBUG)
let resp = traceEvent ("Response") (_webSocket_recv wsConn)
d <- holdDyn "" resp
dynText ((tshow . BS.length) <$> d)
#endif
return ()
widget :: AppMonad t m => AppMonadT t m ()
widget = divClass "container" $ do
tabDisplayUI wrapper "nav navbar-nav" "active" "" $
Map.fromList [
#if !defined (ONLY_READER) && !defined (ONLY_SRS)
(2, ("Sentence", sentenceWidget))
, (3, ("Vocab", vocabSearchWidget))
, (4, ("Kanji", kanjiBrowseWidget))
, (5, ("Import", importWidgetTop))
,
#endif
#if !defined (ONLY_SRS)
(0, ("Reader", textReaderTop))
#endif
#if !defined (ONLY_READER) && !defined (ONLY_SRS)
,
#endif
#if !defined (ONLY_READER)
(1, ("SRS", srsWidget))
#endif
]
wrapper m = elClass "nav" "navbar navbar-default" $
divClass "container-fluid" $ do
divClass "navbar-header" $
elClass "a" "navbar-brand" $ text "てんじん"
a <- m
elClass "ul" "nav navbar-nav navbar-right" $ do
el "li" $ elAttr "a" ("href" =: "")
$ text "Logout"
ev <- el "li" $ btn "navbar-btn btn-default" "Theme"
toggleTheme ev
return a
readable_bootstrap_css = $(embedFile "src/readable_bootstrap.min.css")
custom_css = $(embedFile "src/custom.css")
slate_bootstrap_css = $(embedFile "src/slate_bootstrap.min.css")
toggleTheme :: AppMonad t m
=> Event t ()
-> AppMonadT t m ()
toggleTheme ev = do
rec
d <- holdDyn False (not <$> (tag (current d) ev))
let
toggleW b = X.liftJSM $ do
let css = custom_css <> if b
then slate_bootstrap_css
else readable_bootstrap_css
doc <- currentDocumentUnchecked
headElement <- getHeadUnchecked doc
setInnerHTML headElement $
"<style>" <> T.unpack (decodeUtf8 css)
void $ widgetHold (return ())
(toggleW <$> updated d)
|
7ae0cd87b5b62e8df5879f799457d1768dd256ec487478ba5005c641fd0ab824 | potetm/tire-iron | browser_other.cljs | (ns com.potetm.browser-other)
(defn my-fun []
(println "FUN"))
| null | https://raw.githubusercontent.com/potetm/tire-iron/f26e3f68c137ea10e42645ea2977e9c755558b08/src/dev/browser/com/potetm/browser_other.cljs | clojure | (ns com.potetm.browser-other)
(defn my-fun []
(println "FUN"))
| |
5bf9afff47716dc6fbcd359bff2cf2d8f1d93e4d7aca71bb1bf8455cc2be2796 | macourtney/drift | test_args.clj | (ns drift.test-args
(:use clojure.test drift.args))
(deftest test-split-args
(is (= (split-args ["foo" "-v" "bar" "baz"] #{"-v"} )
[["foo"] ["-v" "bar" "baz"]]))
(is (= (split-args ["foo" "bar" "baz"] #{"-v"} )
[["foo" "bar" "baz"] []])))
(deftest test-remove-opt
(is (= (remove-opt ["-v" "123" "foo" "bar"] {:key :version :matcher #{"-v"}})
[{:version "123"} ["foo" "bar"]]))
(is (= (remove-opt ["-v"] {:key :version :matcher #{"-v"}})
[{} ["-v"]]))
(is (= (remove-opt [] {:key :version :matcher #{"-v"}})
[{} []])))
(deftest test-parse-args
(is (= (parse-args ["foo" "-v" "10" "bar" "--config" "conf" "baz"]
[{:key :version :matcher #{"-v" "--version"}}
{:key :config :matcher #{"-v" "--config"}}])
[{:version "10" :config "conf"} ["foo" "bar" "baz"]])))
(deftest test-parse-migrate-args
(is (= (parse-migrate-args ["foo" "--other" "blah" "-v" "10" "bar" "--config" "conf" "baz"])
[{:version "10" :config 'conf} ["foo" "--other" "blah" "bar" "baz"]])))
(deftest test-parse-create-migration-args
(is (= (parse-create-migration-args ["foo" "--other" "blah" "-v" "10" "bar" "--config" "conf" "baz"])
[{:config 'conf} ["foo" "--other" "blah" "-v" "10" "bar" "baz"]])))
| null | https://raw.githubusercontent.com/macourtney/drift/b5cf735ab41ff2c95b0b1d9cf990faa342353171/test/drift/test_args.clj | clojure | (ns drift.test-args
(:use clojure.test drift.args))
(deftest test-split-args
(is (= (split-args ["foo" "-v" "bar" "baz"] #{"-v"} )
[["foo"] ["-v" "bar" "baz"]]))
(is (= (split-args ["foo" "bar" "baz"] #{"-v"} )
[["foo" "bar" "baz"] []])))
(deftest test-remove-opt
(is (= (remove-opt ["-v" "123" "foo" "bar"] {:key :version :matcher #{"-v"}})
[{:version "123"} ["foo" "bar"]]))
(is (= (remove-opt ["-v"] {:key :version :matcher #{"-v"}})
[{} ["-v"]]))
(is (= (remove-opt [] {:key :version :matcher #{"-v"}})
[{} []])))
(deftest test-parse-args
(is (= (parse-args ["foo" "-v" "10" "bar" "--config" "conf" "baz"]
[{:key :version :matcher #{"-v" "--version"}}
{:key :config :matcher #{"-v" "--config"}}])
[{:version "10" :config "conf"} ["foo" "bar" "baz"]])))
(deftest test-parse-migrate-args
(is (= (parse-migrate-args ["foo" "--other" "blah" "-v" "10" "bar" "--config" "conf" "baz"])
[{:version "10" :config 'conf} ["foo" "--other" "blah" "bar" "baz"]])))
(deftest test-parse-create-migration-args
(is (= (parse-create-migration-args ["foo" "--other" "blah" "-v" "10" "bar" "--config" "conf" "baz"])
[{:config 'conf} ["foo" "--other" "blah" "-v" "10" "bar" "baz"]])))
| |
f2d162743a722a7653d01ec1abc859baab9114a163ec8c6c931386d1b5e5bd71 | serokell/ariadne | Hspec.hs | | Wrappers around hspec functionality that uses ' Buildable ' instead of
' Show ' to better fit in with the rest of the Cardano codebase
--
Intended as a drop - in replacement for " Test . HSpec " .
module Util.Buildable.Hspec (
* Wrappers around Test . HSpec . Expectations
shouldSatisfy
, shouldBe
, shouldNotBe
, shouldReturn
, shouldMatchList
-- * Working with Validated
, valid
, shouldBeValidated
, shouldReturnValidated
-- * Re-exports
, H.Expectation
, H.Spec
, H.around
, H.describe
, H.hspec
, H.it
, H.xit
, H.beforeAll
, H.parallel
) where
import qualified Test.Hspec as H
import Util.Buildable
import Util.Validated
------------------------------------------------------------------------------
Wrappers around Test . HSpec . Expectations
------------------------------------------------------------------------------
Wrappers around Test.HSpec.Expectations
-------------------------------------------------------------------------------}
infix 1 `shouldSatisfy`, `shouldBe`, `shouldReturn`, `shouldMatchList`
shouldSatisfy :: (HasCallStack, Buildable a)
=> a -> (a -> Bool) -> H.Expectation
shouldSatisfy a f = H.shouldSatisfy (STB a) (f . unSTB)
shouldBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldBe a a' = H.shouldBe (STB a) (STB a')
shouldNotBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldNotBe a a' = H.shouldNotBe (STB a) (STB a')
shouldReturn :: (HasCallStack, Buildable a, Eq a)
=> IO a -> a -> H.Expectation
shouldReturn act a = H.shouldReturn (STB <$> act) (STB a)
shouldMatchList :: (HasCallStack, Buildable a, Eq a)
=> [a] -> [a] -> H.Expectation
shouldMatchList a b = H.shouldMatchList (map STB a) (map STB b)
{-------------------------------------------------------------------------------
Wrappers around Validated
-------------------------------------------------------------------------------}
valid :: (HasCallStack, Buildable e, Buildable a)
=> String -> Validated e a -> H.Spec
valid s = H.it s . shouldBeValidated
shouldBeValidated :: (HasCallStack, Buildable e, Buildable a)
=> Validated e a -> H.Expectation
shouldBeValidated ma = shouldSatisfy ma isValidated
shouldReturnValidated :: (HasCallStack, Buildable a, Buildable e)
=> IO (Validated e a) -> IO ()
shouldReturnValidated act = shouldBeValidated =<< act
| null | https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/test/backend/Util/Buildable/Hspec.hs | haskell |
* Working with Validated
* Re-exports
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
------------------------------------------------------------------------------
Wrappers around Validated
------------------------------------------------------------------------------ | | Wrappers around hspec functionality that uses ' Buildable ' instead of
' Show ' to better fit in with the rest of the Cardano codebase
Intended as a drop - in replacement for " Test . HSpec " .
module Util.Buildable.Hspec (
* Wrappers around Test . HSpec . Expectations
shouldSatisfy
, shouldBe
, shouldNotBe
, shouldReturn
, shouldMatchList
, valid
, shouldBeValidated
, shouldReturnValidated
, H.Expectation
, H.Spec
, H.around
, H.describe
, H.hspec
, H.it
, H.xit
, H.beforeAll
, H.parallel
) where
import qualified Test.Hspec as H
import Util.Buildable
import Util.Validated
Wrappers around Test . HSpec . Expectations
Wrappers around Test.HSpec.Expectations
infix 1 `shouldSatisfy`, `shouldBe`, `shouldReturn`, `shouldMatchList`
shouldSatisfy :: (HasCallStack, Buildable a)
=> a -> (a -> Bool) -> H.Expectation
shouldSatisfy a f = H.shouldSatisfy (STB a) (f . unSTB)
shouldBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldBe a a' = H.shouldBe (STB a) (STB a')
shouldNotBe :: (HasCallStack, Buildable a, Eq a)
=> a -> a -> H.Expectation
shouldNotBe a a' = H.shouldNotBe (STB a) (STB a')
shouldReturn :: (HasCallStack, Buildable a, Eq a)
=> IO a -> a -> H.Expectation
shouldReturn act a = H.shouldReturn (STB <$> act) (STB a)
shouldMatchList :: (HasCallStack, Buildable a, Eq a)
=> [a] -> [a] -> H.Expectation
shouldMatchList a b = H.shouldMatchList (map STB a) (map STB b)
valid :: (HasCallStack, Buildable e, Buildable a)
=> String -> Validated e a -> H.Spec
valid s = H.it s . shouldBeValidated
shouldBeValidated :: (HasCallStack, Buildable e, Buildable a)
=> Validated e a -> H.Expectation
shouldBeValidated ma = shouldSatisfy ma isValidated
shouldReturnValidated :: (HasCallStack, Buildable a, Buildable e)
=> IO (Validated e a) -> IO ()
shouldReturnValidated act = shouldBeValidated =<< act
|
016ac45066e966b46ae09fc74197550a90ee0dda044cb2107d3024c600a2bb8a | OtpChatBot/Ybot | talker_app_client.erl | %%%-----------------------------------------------------------------------------
%%% @author 0xAX <>
%%% @doc
Talkerapp transport client .
%%% @end
%%%-----------------------------------------------------------------------------
-module(talker_app_client).
-behaviour(gen_server).
-export([start_link/5]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
@doc Default port for Talkerapp .
-define(PORT, 8500).
%% @doc Internal state.
-record(state, {
% callback module with handler
callback :: pid(),
% connected socket
socket = null,
% user access token
token = <<>> :: binary(),
% Bot nick
bot_nick = <<>> :: binary(),
% talkerapp room
room = <<>> :: binary(),
% talkerapp reconnect timeout
reconnect_timeout = 0 :: integer()
}).
%%%=============================================================================
%%% API
%%%=============================================================================
start_link(Callback, BotNick, Room, Token, RecTimeout) ->
gen_server:start_link(?MODULE, [Callback, BotNick, Room, Token, RecTimeout], []).
%%%=============================================================================
%%% talker_app client callback
%%%=============================================================================
init([Callback, BotNick, Room, Token, RecTimeout]) ->
% start connection
gen_server:cast(self(), {connect, Token, Room}),
% init state and return
{ok, #state{bot_nick = BotNick, callback = Callback, token = Token, room = Room, reconnect_timeout = RecTimeout}}.
handle_call(_Request, _From, State) ->
{reply, ignored, State}.
%% @doc send message
handle_cast({send_message, _From, Message}, State) ->
% Make json message
JsonMessage = "{\"type\":\"message\",\"content\" :\"" ++ Message ++ "\"}",
% Send message
ssl:send(State#state.socket, JsonMessage),
% return state
{noreply, State};
%% @doc connect to talkerapp
handle_cast({connect, Token, Room}, State) ->
Connect to talkerapp.com
case ssl:connect("talkerapp.com", ?PORT, [{verify, 0}]) of
{ok, Socket} ->
AuthMessage = "{\"type\":\"connect\",\"room\":\"" ++ binary_to_list(Room) ++ "\",\"token\":\"" ++ binary_to_list(Token) ++ "\"}",
% Try to auth
ssl:send(Socket, AuthMessage),
% Send ping in loop
erlang:send_after(25000, self(), ping),
% save socket and return
{noreply, State#state{socket = Socket}};
{error, Reason} ->
% Some log
lager:error("Unable to connect to talkerapp server with reason ~s", [Reason]),
% return state
{noreply, State}
end;
handle_cast(_Msg, State) ->
{noreply, State}.
%% @doc Incoming message
handle_info({ssl, _Socket, Data}, State) ->
% Decode json data
{DecodeJson} = jiffy:decode(Data),
case lists:member({<<"type">>,<<"message">>}, DecodeJson) of
true ->
% Get user data
UserName = get_user_name(DecodeJson),
if UserName == State#state.bot_nick ->
% do nothing
pass;
true ->
% Send incoming message to handler
Message = get_message(DecodeJson),
State#state.callback ! {incoming_message, Message}
end;
false ->
% do nothing
pass
end,
% return
{noreply, State};
handle_info({ssl_closed, Reason}, State) ->
% Some log
lager:info("ssl_closed with reason: ~p~n", [Reason]),
% try reconnect
try_reconnect(State);
handle_info({ssl_error, _Socket, Reason}, State) ->
% Some log
lager:error("tcp_error: ~p~n", [Reason]),
% try reconnect
try_reconnect(State);
%% @doc send ping
handle_info(ping, State) ->
% Send ping
ssl:send(State#state.socket, "{\"type\":\"ping\"}"),
% Send ping in loop
erlang:send_after(25000, self(), ping),
% return
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%=============================================================================
Internal functions
%%%=============================================================================
get_user_name([H | Json]) ->
case H of
{<<"user">>, _UserData} ->
{<<"user">>, {Data}} = H,
[{<<"name">>, UserName}] = lists:flatten(lists:filter(fun(D) -> {Label, _} = D,
case Label of
<<"name">> -> true;
_ -> false
end
end, Data)),
UserName;
_ ->
get_user_name(Json)
end.
get_message([H | Json]) ->
case H of
{<<"content">>, Message} ->
Message;
_ ->
get_message(Json)
end.
%% @doc try reconnect
-spec try_reconnect(State :: #state{}) -> {normal, stop, State} | {noreply, State}.
try_reconnect(#state{reconnect_timeout = Timeout, token = Token, room = Room} = State) ->
case Timeout > 0 of
true ->
% no need in reconnect
{normal, stop, State};
false ->
% sleep
timer:sleep(Timeout),
% Try reconnect
gen_server:cast(self(), {connect, Token, Room}),
% return
{noreply, State}
end. | null | https://raw.githubusercontent.com/OtpChatBot/Ybot/5ce05fea0eb9001d1c0ff89702729f4c80743872/src/transport/talkerapp/talker_app_client.erl | erlang | -----------------------------------------------------------------------------
@author 0xAX <>
@doc
@end
-----------------------------------------------------------------------------
gen_server callbacks
@doc Internal state.
callback module with handler
connected socket
user access token
Bot nick
talkerapp room
talkerapp reconnect timeout
=============================================================================
API
=============================================================================
=============================================================================
talker_app client callback
=============================================================================
start connection
init state and return
@doc send message
Make json message
Send message
return state
@doc connect to talkerapp
Try to auth
Send ping in loop
save socket and return
Some log
return state
@doc Incoming message
Decode json data
Get user data
do nothing
Send incoming message to handler
do nothing
return
Some log
try reconnect
Some log
try reconnect
@doc send ping
Send ping
Send ping in loop
return
=============================================================================
=============================================================================
@doc try reconnect
no need in reconnect
sleep
Try reconnect
return | Talkerapp transport client .
-module(talker_app_client).
-behaviour(gen_server).
-export([start_link/5]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
@doc Default port for Talkerapp .
-define(PORT, 8500).
-record(state, {
callback :: pid(),
socket = null,
token = <<>> :: binary(),
bot_nick = <<>> :: binary(),
room = <<>> :: binary(),
reconnect_timeout = 0 :: integer()
}).
start_link(Callback, BotNick, Room, Token, RecTimeout) ->
gen_server:start_link(?MODULE, [Callback, BotNick, Room, Token, RecTimeout], []).
init([Callback, BotNick, Room, Token, RecTimeout]) ->
gen_server:cast(self(), {connect, Token, Room}),
{ok, #state{bot_nick = BotNick, callback = Callback, token = Token, room = Room, reconnect_timeout = RecTimeout}}.
handle_call(_Request, _From, State) ->
{reply, ignored, State}.
handle_cast({send_message, _From, Message}, State) ->
JsonMessage = "{\"type\":\"message\",\"content\" :\"" ++ Message ++ "\"}",
ssl:send(State#state.socket, JsonMessage),
{noreply, State};
handle_cast({connect, Token, Room}, State) ->
Connect to talkerapp.com
case ssl:connect("talkerapp.com", ?PORT, [{verify, 0}]) of
{ok, Socket} ->
AuthMessage = "{\"type\":\"connect\",\"room\":\"" ++ binary_to_list(Room) ++ "\",\"token\":\"" ++ binary_to_list(Token) ++ "\"}",
ssl:send(Socket, AuthMessage),
erlang:send_after(25000, self(), ping),
{noreply, State#state{socket = Socket}};
{error, Reason} ->
lager:error("Unable to connect to talkerapp server with reason ~s", [Reason]),
{noreply, State}
end;
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({ssl, _Socket, Data}, State) ->
{DecodeJson} = jiffy:decode(Data),
case lists:member({<<"type">>,<<"message">>}, DecodeJson) of
true ->
UserName = get_user_name(DecodeJson),
if UserName == State#state.bot_nick ->
pass;
true ->
Message = get_message(DecodeJson),
State#state.callback ! {incoming_message, Message}
end;
false ->
pass
end,
{noreply, State};
handle_info({ssl_closed, Reason}, State) ->
lager:info("ssl_closed with reason: ~p~n", [Reason]),
try_reconnect(State);
handle_info({ssl_error, _Socket, Reason}, State) ->
lager:error("tcp_error: ~p~n", [Reason]),
try_reconnect(State);
handle_info(ping, State) ->
ssl:send(State#state.socket, "{\"type\":\"ping\"}"),
erlang:send_after(25000, self(), ping),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
get_user_name([H | Json]) ->
case H of
{<<"user">>, _UserData} ->
{<<"user">>, {Data}} = H,
[{<<"name">>, UserName}] = lists:flatten(lists:filter(fun(D) -> {Label, _} = D,
case Label of
<<"name">> -> true;
_ -> false
end
end, Data)),
UserName;
_ ->
get_user_name(Json)
end.
get_message([H | Json]) ->
case H of
{<<"content">>, Message} ->
Message;
_ ->
get_message(Json)
end.
-spec try_reconnect(State :: #state{}) -> {normal, stop, State} | {noreply, State}.
try_reconnect(#state{reconnect_timeout = Timeout, token = Token, room = Room} = State) ->
case Timeout > 0 of
true ->
{normal, stop, State};
false ->
timer:sleep(Timeout),
gen_server:cast(self(), {connect, Token, Room}),
{noreply, State}
end. |
b2e5adbbc3015f5a74302cf124413c83038bce27e5c62a1f5b61cc959679af92 | vikram/lisplibraries | counter.lisp | ;; -*- lisp -*-
(in-package :it.bese.ucw-user)
First we 'll define the main component for our application . It
;;;; will hold the current value and a boolean specifying whether we
;;;; want to accept negative values or not.
(defcomponent counter (template-component)
two slots , both are backtracked .
((value :accessor value
:initarg :value
:initform 0)
(allow-negatives :accessor allow-negatives
:initarg :allow-negatives
:initform nil))
(:default-backtrack #'identity)
(:default-initargs :template-name "ucw/examples/counter.tal"))
;;;; This action will just increment the current value of the counter.
(defaction increment ((c counter))
(incf (value c)))
;;;; This action will decrement the counter. However if the user tries
;;;; to give the counter a negative value we ask for if they're
;;;; sure. We present them with the option of not asking this question
;;;; again (the :forever option).
(defaction decrement ((c counter))
(when (and (zerop (value c))
(not (allow-negatives c)))
;; the option-dialog component returns the value associated with
;; whatever answer the user chose.
(case (call 'option-dialog
:message "Do you really want to allow negative values?"
:options '((:once-only . "Yes, but just this time.")
(:forever . "Yes, now and forever.")
(:no . "No"))
:confirm t)
(:no ;; they don't really want to decrement, do nothing.
(return-from decrement nil))
(:forever ;; don't ask this question again
(setf (allow-negatives c) t))))
(decf (value c)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Copyright ( c ) 2003 - 2005
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are
;;; met:
;;;
;;; - Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; - Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
- Neither the name of , nor , 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 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.
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/ucw_dev/examples/counter.lisp | lisp | -*- lisp -*-
will hold the current value and a boolean specifying whether we
want to accept negative values or not.
This action will just increment the current value of the counter.
This action will decrement the counter. However if the user tries
to give the counter a negative value we ask for if they're
sure. We present them with the option of not asking this question
again (the :forever option).
the option-dialog component returns the value associated with
whatever answer the user chose.
they don't really want to decrement, do nothing.
don't ask this question again
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.
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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
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. |
(in-package :it.bese.ucw-user)
First we 'll define the main component for our application . It
(defcomponent counter (template-component)
two slots , both are backtracked .
((value :accessor value
:initarg :value
:initform 0)
(allow-negatives :accessor allow-negatives
:initarg :allow-negatives
:initform nil))
(:default-backtrack #'identity)
(:default-initargs :template-name "ucw/examples/counter.tal"))
(defaction increment ((c counter))
(incf (value c)))
(defaction decrement ((c counter))
(when (and (zerop (value c))
(not (allow-negatives c)))
(case (call 'option-dialog
:message "Do you really want to allow negative values?"
:options '((:once-only . "Yes, but just this time.")
(:forever . "Yes, now and forever.")
(:no . "No"))
:confirm t)
(return-from decrement nil))
(setf (allow-negatives c) t))))
(decf (value c)))
Copyright ( c ) 2003 - 2005
- Neither the name of , nor , nor the names
" 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
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
|
889754bbb113e4ba5bab9a9b2d6b6d6f6d44c37d1afd5ba2e106bea85f9366b6 | informatimago/lisp | sedit2.lisp | -*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE : sedit.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; A simple sexp editor.
;;;;
;;;; It is invoked as (sedit sexp), and returns the modified sexp.
;;;; (The sexp is modified destructively).
;;;;
;;;; (sedit (copy-tree '(an example)))
;;;;
;;;; At each interaction loop, it prints the whole sexp, showing the selected
;;;; sub-sexp, and query a command. The list of commands are:
;;;;
;;;; q quit to return the modified sexp from sedit.
;;;; i in to enter inside the selected list.
;;;; o out to select the list containing the selection.
;;;; f forward n next to select the sexp following the selection (or out).
b backward p previous to select the sexp preceding the selection ( or out ) .
;;;; s insert to insert a new sexp before the selection.
;;;; r replace to replace the selection with a new sexp.
;;;; a add to add a new sexp after the selection.
;;;; x cut to cut the selection into a *clipboard*.
;;;; c copy to copy the selection into a *clipboard*.
;;;; y paste to paste the *clipboard* replacing the selection.
;;;;
;;;; Notice: it uses the unicode characters LEFT_BLACK_LENTICULAR_BRACKET
;;;; and RIGHT_BLACK_LENTICULAR_BRACKET to show the selected sub-sexp.
;;;; This could be changed easily modifying SEDIT-PRINT-SELECTION.
;;;;
< PJB > < >
MODIFICATIONS
2010 - 09 - 08 < PJB > Created .
;;;;LEGAL
AGPL3
;;;;
Copyright 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details .
;;;;
You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see </>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT.2"
(:use "COMMON-LISP")
(:export "SEDIT"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT.2")
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (= char-code-limit 1114112)
(pushnew :unicode *features*)))
(defstruct selection
parent-list
sexp)
(defmethod print-object ((selection selection) stream)
(format stream #+unicode " 【~S】 "
#-unicode " [~S] "
(selection-sexp selection))
selection)
(defvar *clipboard* nil)
(defun find-cell (object list)
(cond
((eq (car list) object) list)
((null (cdr list)) nil)
((and (atom (cdr list))
(eq (cdr list) object)) list)
(t (find-cell object (cdr list)))))
(defun unselect (selection)
(let ((cell (find-cell selection (selection-parent-list selection))))
(when cell
(if (eq (car cell) selection)
(setf (car cell) (selection-sexp selection))
(setf (cdr cell) (selection-sexp selection))))))
(defun nth-cdr (n list)
(cond
((not (plusp n)) list)
((atom list) list)
(t (nth-cdr (1- n) (cdr list)))))
(defun select (selection parent index)
(cond
((atom parent)
(error "Cannot select from an atom."))
(t
(let ((cell (nth-cdr index parent)))
(cond
((null cell) (error "cannot select so far"))
((atom cell) (setf (selection-parent-list selection) parent
(selection-sexp selection) cell
(cdr (nth-cdr (1- index) parent)) selection))
(t (setf (selection-parent-list selection) parent
(selection-sexp selection) (car cell)
(car cell) selection)))))))
(defun sedit-find-object (sexp object)
"Return the cons cell of SEXP where the OBJECT is."
(cond
((atom sexp) nil)
((eq sexp object) nil)
((or (eq (car sexp) object)
(eq (cdr sexp) object)) sexp)
(t (or (sedit-find-object (car sexp) object)
(sedit-find-object (cdr sexp) object)))))
(defun sedit-in (root selection)
"When a non-empty list is selected, change the selection to the first element of the list."
(declare (ignore root))
(if (atom (selection-sexp selection))
(progn (princ "Cannot enter an atom.") (terpri))
(progn
(unselect selection)
(select selection (selection-sexp selection) 0))))
(defun sedit-out (root selection)
"Change the selection to the parent list of the current selection."
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(when gparent
(unselect selection)
(select selection gparent 0))))
(defun sedit-forward (root selection)
"Change the selection to the element following the current selection, or the parent if it's the last."
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index)
(<= (length (selection-parent-list selection)) (1+ index)))
(sedit-out root selection)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1+ index))))))
(defun sedit-backward (root selection)
"Change the selection to the element preceeding the current selection, or the parent if it's the first."
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index) (<= index 0))
(sedit-out root selection)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1- index))))))
(defun sedit-enlist (root selection)
"Put the selection in a new list."
(declare (ignore root))
(setf (selection-sexp selection) (list (selection-sexp selection))))
(defun ensure-list (x)
(if (listp x) x (list x)))
(defun sedit-splice (root selection)
"Splice the elements of the selection in the parent."
(let* ((parent (selection-parent-list selection))
(selected (selection-sexp selection))
(index (position selection parent)))
(sedit-out root selection)
(setf (selection-sexp selection)
(append (subseq parent 0 index)
(ensure-list selected)
(subseq parent (1+ index))))))
(defun sedit-slurp (root selection)
"Append to the selection the element following it."
(declare (ignore root))
(let ((index (position selection (selection-parent-list selection))))
(when (and index
(< (1+ index) (length (selection-parent-list selection))))
(setf (selection-sexp selection)
(append (ensure-list (selection-sexp selection))
(list (pop (cdr (nth-cdr index (selection-parent-list selection))))))))))
(defun sedit-barf (root selection)
"Split out the last element of the selection."
(declare (ignore root))
(let ((index (position selection (selection-parent-list selection))))
(when (and index (consp (selection-sexp selection)))
(let ((barfed (first (last (selection-sexp selection)))))
(setf (selection-sexp selection) (butlast (selection-sexp selection)))
(insert barfed (selection-parent-list selection) :after selection)))))
(defun sedit-cut (root selection)
"Save the selection to the *CLIPBOARD*, and remove it."
(setf *clipboard* (selection-sexp selection))
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (delete selection (selection-parent-list selection)))
(setf (cdr gparent) (delete selection (selection-parent-list selection))))
(select selection gparent 0)))
(defun sedit-copy (root selection)
"Save the selection to the *CLIPBOARD*."
(declare (ignore root))
(setf *clipboard* (copy-tree (selection-sexp selection))))
(defun sedit-paste (root selection)
"Replace the selection by the contents of teh *CLIPBOARD*."
(declare (ignore root))
(setf (selection-sexp selection) (copy-tree *clipboard*)))
(defun sedit-replace (root selection)
"Replace the selection by the expression input by the user."
(declare (ignore root))
(princ "replacement sexp: " *query-io*)
(setf (selection-sexp selection) (read *query-io*)))
(defun insert (object list where reference)
(ecase where
((:before)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq (car list) reference)
(setf (cdr list) (cons (car list) (cdr list))
(car list) object))
(t (insert object (cdr list) where reference))))
((:after)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq (car list) reference)
(push object (cdr list)))
(t (insert object (cdr list) where reference))))))
(defun sedit-insert (root selection)
"Insert the expression input by the user before the selection."
(princ "sexp to be inserted before: " *query-io*)
(let ((new-sexp (read *query-io*)))
(if (eq (first (selection-parent-list selection)) selection)
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(setf (selection-parent-list selection)
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (cons new-sexp (selection-parent-list selection)))
(setf (cdr gparent) (cons new-sexp (selection-parent-list selection))))))
(insert new-sexp (selection-parent-list selection) :before selection))))
(defun sedit-add (root selection)
"Insert the expression input by the user after the selection."
(declare (ignore root))
(princ "sexp to be inserted after: " *query-io*)
(let ((new-sexp (read *query-io*)))
(insert new-sexp (selection-parent-list selection) :after selection)))
(defun sedit (sexp)
"Edit the SEXP; return the new sexp."
(terpri)
(princ "Sexp Editor:")
(terpri)
(let* ((root (list sexp))
(selection (make-selection)))
(select selection root 0)
(setf (first root) selection)
(unwind-protect
(loop
(pprint root)
(terpri) (princ "> " *query-io*)
(let ((command (read *query-io*)))
(case command
((q quit) (return))
((i in) (sedit-in root selection))
((o out) (sedit-out root selection))
((f forward n next) (sedit-forward root selection))
((b backward p previous) (sedit-backward root selection))
((s insert) (sedit-insert root selection)) ; before
((r replace) (sedit-replace root selection)) ; in place
((a add) (sedit-add root selection)) ; after
((x cut) (sedit-cut root selection))
((c copy) (sedit-copy root selection))
((y paste) (sedit-paste root selection))
((l enlist) (sedit-enlist root selection))
((e splice) (sedit-splice root selection))
((u slurp) (sedit-slurp root selection))
((v barf) (sedit-barf root selection))
(otherwise
(princ "Please use one of these commands:")
(terpri)
(princ "quit, in, out, forward, backward, insert, replace, add, cut, copy, paste, slurp, barf.")
(terpri)))))
(unselect selection))
(first root)))
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/small-cl-pgms/sedit/sedit2.lisp | lisp | coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
A simple sexp editor.
It is invoked as (sedit sexp), and returns the modified sexp.
(The sexp is modified destructively).
(sedit (copy-tree '(an example)))
At each interaction loop, it prints the whole sexp, showing the selected
sub-sexp, and query a command. The list of commands are:
q quit to return the modified sexp from sedit.
i in to enter inside the selected list.
o out to select the list containing the selection.
f forward n next to select the sexp following the selection (or out).
s insert to insert a new sexp before the selection.
r replace to replace the selection with a new sexp.
a add to add a new sexp after the selection.
x cut to cut the selection into a *clipboard*.
c copy to copy the selection into a *clipboard*.
y paste to paste the *clipboard* replacing the selection.
Notice: it uses the unicode characters LEFT_BLACK_LENTICULAR_BRACKET
and RIGHT_BLACK_LENTICULAR_BRACKET to show the selected sub-sexp.
This could be changed easily modifying SEDIT-PRINT-SELECTION.
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 </>
**************************************************************************
before
in place
after
THE END ;;;; | FILE : sedit.lisp
USER - INTERFACE :
b backward p previous to select the sexp preceding the selection ( or out ) .
< PJB > < >
MODIFICATIONS
2010 - 09 - 08 < PJB > Created .
AGPL3
Copyright 2010 - 2016
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT.2"
(:use "COMMON-LISP")
(:export "SEDIT"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT.2")
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (= char-code-limit 1114112)
(pushnew :unicode *features*)))
(defstruct selection
parent-list
sexp)
(defmethod print-object ((selection selection) stream)
(format stream #+unicode " 【~S】 "
#-unicode " [~S] "
(selection-sexp selection))
selection)
(defvar *clipboard* nil)
(defun find-cell (object list)
(cond
((eq (car list) object) list)
((null (cdr list)) nil)
((and (atom (cdr list))
(eq (cdr list) object)) list)
(t (find-cell object (cdr list)))))
(defun unselect (selection)
(let ((cell (find-cell selection (selection-parent-list selection))))
(when cell
(if (eq (car cell) selection)
(setf (car cell) (selection-sexp selection))
(setf (cdr cell) (selection-sexp selection))))))
(defun nth-cdr (n list)
(cond
((not (plusp n)) list)
((atom list) list)
(t (nth-cdr (1- n) (cdr list)))))
(defun select (selection parent index)
(cond
((atom parent)
(error "Cannot select from an atom."))
(t
(let ((cell (nth-cdr index parent)))
(cond
((null cell) (error "cannot select so far"))
((atom cell) (setf (selection-parent-list selection) parent
(selection-sexp selection) cell
(cdr (nth-cdr (1- index) parent)) selection))
(t (setf (selection-parent-list selection) parent
(selection-sexp selection) (car cell)
(car cell) selection)))))))
(defun sedit-find-object (sexp object)
"Return the cons cell of SEXP where the OBJECT is."
(cond
((atom sexp) nil)
((eq sexp object) nil)
((or (eq (car sexp) object)
(eq (cdr sexp) object)) sexp)
(t (or (sedit-find-object (car sexp) object)
(sedit-find-object (cdr sexp) object)))))
(defun sedit-in (root selection)
"When a non-empty list is selected, change the selection to the first element of the list."
(declare (ignore root))
(if (atom (selection-sexp selection))
(progn (princ "Cannot enter an atom.") (terpri))
(progn
(unselect selection)
(select selection (selection-sexp selection) 0))))
(defun sedit-out (root selection)
"Change the selection to the parent list of the current selection."
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(when gparent
(unselect selection)
(select selection gparent 0))))
(defun sedit-forward (root selection)
"Change the selection to the element following the current selection, or the parent if it's the last."
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index)
(<= (length (selection-parent-list selection)) (1+ index)))
(sedit-out root selection)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1+ index))))))
(defun sedit-backward (root selection)
"Change the selection to the element preceeding the current selection, or the parent if it's the first."
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index) (<= index 0))
(sedit-out root selection)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1- index))))))
(defun sedit-enlist (root selection)
"Put the selection in a new list."
(declare (ignore root))
(setf (selection-sexp selection) (list (selection-sexp selection))))
(defun ensure-list (x)
(if (listp x) x (list x)))
(defun sedit-splice (root selection)
"Splice the elements of the selection in the parent."
(let* ((parent (selection-parent-list selection))
(selected (selection-sexp selection))
(index (position selection parent)))
(sedit-out root selection)
(setf (selection-sexp selection)
(append (subseq parent 0 index)
(ensure-list selected)
(subseq parent (1+ index))))))
(defun sedit-slurp (root selection)
"Append to the selection the element following it."
(declare (ignore root))
(let ((index (position selection (selection-parent-list selection))))
(when (and index
(< (1+ index) (length (selection-parent-list selection))))
(setf (selection-sexp selection)
(append (ensure-list (selection-sexp selection))
(list (pop (cdr (nth-cdr index (selection-parent-list selection))))))))))
(defun sedit-barf (root selection)
"Split out the last element of the selection."
(declare (ignore root))
(let ((index (position selection (selection-parent-list selection))))
(when (and index (consp (selection-sexp selection)))
(let ((barfed (first (last (selection-sexp selection)))))
(setf (selection-sexp selection) (butlast (selection-sexp selection)))
(insert barfed (selection-parent-list selection) :after selection)))))
(defun sedit-cut (root selection)
"Save the selection to the *CLIPBOARD*, and remove it."
(setf *clipboard* (selection-sexp selection))
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (delete selection (selection-parent-list selection)))
(setf (cdr gparent) (delete selection (selection-parent-list selection))))
(select selection gparent 0)))
(defun sedit-copy (root selection)
"Save the selection to the *CLIPBOARD*."
(declare (ignore root))
(setf *clipboard* (copy-tree (selection-sexp selection))))
(defun sedit-paste (root selection)
"Replace the selection by the contents of teh *CLIPBOARD*."
(declare (ignore root))
(setf (selection-sexp selection) (copy-tree *clipboard*)))
(defun sedit-replace (root selection)
"Replace the selection by the expression input by the user."
(declare (ignore root))
(princ "replacement sexp: " *query-io*)
(setf (selection-sexp selection) (read *query-io*)))
(defun insert (object list where reference)
(ecase where
((:before)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq (car list) reference)
(setf (cdr list) (cons (car list) (cdr list))
(car list) object))
(t (insert object (cdr list) where reference))))
((:after)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq (car list) reference)
(push object (cdr list)))
(t (insert object (cdr list) where reference))))))
(defun sedit-insert (root selection)
"Insert the expression input by the user before the selection."
(princ "sexp to be inserted before: " *query-io*)
(let ((new-sexp (read *query-io*)))
(if (eq (first (selection-parent-list selection)) selection)
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(setf (selection-parent-list selection)
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (cons new-sexp (selection-parent-list selection)))
(setf (cdr gparent) (cons new-sexp (selection-parent-list selection))))))
(insert new-sexp (selection-parent-list selection) :before selection))))
(defun sedit-add (root selection)
"Insert the expression input by the user after the selection."
(declare (ignore root))
(princ "sexp to be inserted after: " *query-io*)
(let ((new-sexp (read *query-io*)))
(insert new-sexp (selection-parent-list selection) :after selection)))
(defun sedit (sexp)
"Edit the SEXP; return the new sexp."
(terpri)
(princ "Sexp Editor:")
(terpri)
(let* ((root (list sexp))
(selection (make-selection)))
(select selection root 0)
(setf (first root) selection)
(unwind-protect
(loop
(pprint root)
(terpri) (princ "> " *query-io*)
(let ((command (read *query-io*)))
(case command
((q quit) (return))
((i in) (sedit-in root selection))
((o out) (sedit-out root selection))
((f forward n next) (sedit-forward root selection))
((b backward p previous) (sedit-backward root selection))
((x cut) (sedit-cut root selection))
((c copy) (sedit-copy root selection))
((y paste) (sedit-paste root selection))
((l enlist) (sedit-enlist root selection))
((e splice) (sedit-splice root selection))
((u slurp) (sedit-slurp root selection))
((v barf) (sedit-barf root selection))
(otherwise
(princ "Please use one of these commands:")
(terpri)
(princ "quit, in, out, forward, backward, insert, replace, add, cut, copy, paste, slurp, barf.")
(terpri)))))
(unselect selection))
(first root)))
|
fc1e39c046b6c5cbe5064612285d9dcd2f5bcf9207ab5f793e0078201bcbf1f8 | kadena-io/pact | Types.hs | # LANGUAGE DeriveFunctor #
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TemplateHaskell #-}
| Types related to parsing from ' Exp ' to ' Prop ' and ' Invariant ' .
module Pact.Analyze.Parse.Types where
import Control.Applicative (Alternative)
import Control.Lens (makeLenses, (<&>))
import Control.Monad.Except (MonadError (throwError))
import Control.Monad.Reader (ReaderT)
import Control.Monad.State.Strict (StateT)
import qualified Data.HashMap.Strict as HM
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Prelude hiding (exp)
import Pact.Types.Lang (AtomExp (..),
Exp (EAtom, ELiteral, ESeparator),
ListDelimiter (..), ListExp (..),
Literal (LString), LiteralExp (..),
Separator (..), SeparatorExp (..))
import qualified Pact.Types.Lang as Pact
import Pact.Types.Typecheck (UserType)
import Pact.Types.Pretty
import Pact.Analyze.Feature hiding (Doc, Type, Var, ks, obj,
str)
import Pact.Analyze.Types
@PreProp@ stands between @Exp@ and @Prop@.
--
The conversion from @Exp@ is light , handled in @expToPreProp@.
data PreProp
-- literals
= PreIntegerLit Integer
| PreStringLit Text
| PreDecimalLit Decimal
| PreTimeLit Time
| PreBoolLit Bool
| PreListLit [PreProp]
-- identifiers
| PreAbort
| PreSuccess
| PreGovPasses
| PreResult
-- In conversion from @Exp@ to @PreProp@ we maintain a distinction between
-- bound and unbound variables. Bound (@PreVar@) variables are bound inside
quantifiers . Unbound ( @PreGlobalVar@ ) variables either refer to a property
-- definition or a table.
| PreVar VarId Text
| PreGlobalVar Text
-- quantifiers
| PreForall VarId Text QType PreProp
| PreExists VarId Text QType PreProp
-- applications
| PreApp Text [PreProp]
| PreAt PreProp PreProp
| PrePropRead PreProp PreProp PreProp
| PreLiteralObject (Map Text PreProp)
deriving (Eq, Show)
| Find the set of global variables in a @PreProp@.
prePropGlobals :: PreProp -> Set Text
prePropGlobals = \case
PreListLit props -> Set.unions $ prePropGlobals <$> props
PreGlobalVar name -> Set.singleton name
PreForall _ _ _ prop -> prePropGlobals prop
PreExists _ _ _ prop -> prePropGlobals prop
PreApp _ props -> Set.unions $ prePropGlobals <$> props
PreAt p1 p2 -> prePropGlobals p1 `Set.union` prePropGlobals p2
PrePropRead p1 p2 p3 -> Set.unions $ prePropGlobals <$> [p1, p2, p3]
PreLiteralObject obj -> Set.unions $ prePropGlobals <$> Map.elems obj
_ -> Set.empty
instance Pretty PreProp where
pretty = \case
PreIntegerLit i -> pretty i
PreStringLit t -> dquotes $ pretty t
PreDecimalLit d -> pretty d
PreTimeLit t -> pretty (Pact.LTime (toPact timeIso t))
PreBoolLit True -> "true"
PreBoolLit False -> "false"
PreListLit lst -> commaBrackets $ fmap pretty lst
PreAbort -> pretty STransactionAborts
PreSuccess -> pretty STransactionSucceeds
PreGovPasses -> pretty SGovernancePasses
PreResult -> pretty SFunctionResult
PreVar _id name -> pretty name
PreGlobalVar name -> pretty name
PreForall _vid name qty prop ->
"(" <> pretty SUniversalQuantification <> " (" <> pretty name <> ":" <>
pretty qty <> ") " <> pretty prop <> ")"
PreExists _vid name qty prop ->
"(" <> pretty SExistentialQuantification <> " (" <> pretty name <> ":" <>
pretty qty <> ") " <> pretty prop <> ")"
PreApp name applicands ->
"(" <> pretty name <> " " <> hsep (map pretty applicands) <> ")"
PreAt objIx obj ->
"(" <> pretty SObjectProjection <> " " <> pretty objIx <> " " <>
pretty obj <> ")"
PrePropRead tn rk ba ->
"(" <> pretty SPropRead <> " '" <> pretty tn <> " " <> pretty rk <> " " <>
pretty ba <> ")"
PreLiteralObject obj -> commaBraces $ Map.toList obj <&> \(k, v) ->
pretty k <> " := " <> pretty v
throwErrorT :: MonadError String m => Text -> m a
throwErrorT = throwError . T.unpack
throwErrorD :: MonadError String m => Doc -> m a
throwErrorD = throwError . renderCompactString'
-- TODO(joel): add location info
throwErrorIn :: (MonadError String m, Pretty a) => a -> Doc -> m b
throwErrorIn exp msg = throwError $ renderCompactString' $
"in " <> pretty exp <> ", " <> msg
textToQuantifier
:: Text -> Maybe (VarId -> Text -> QType -> PreProp -> PreProp)
textToQuantifier = \case
SUniversalQuantification -> Just PreForall
SExistentialQuantification -> Just PreExists
_ -> Nothing
type TableEnv = TableMap (ColumnMap EType)
data PropCheckEnv = PropCheckEnv
{ _varTys :: Map VarId QType
, _tableEnv :: TableEnv
, _quantifiedTables :: Set TableName
, _quantifiedColumns :: Set ColumnName
-- User-defined properties
, _definedProps :: HM.HashMap Text (DefinedProperty PreProp)
Vars bound within a user - defined property
, _localVars :: HM.HashMap Text EProp
}
newtype EitherFail e a = EitherFail { _getEither :: Either e a }
deriving (Show, Eq, Ord, Functor, Applicative, Alternative, Monad, MonadError e)
type ParseEnv = Map Text VarId
type PropParse = ReaderT ParseEnv (StateT VarId (Either String))
type PropCheck = ReaderT PropCheckEnv (EitherFail String)
type InvariantParse = ReaderT [(Pact.Arg UserType, VarId)] (Either String)
makeLenses ''PropCheckEnv
pattern ParenList :: [Exp t] -> Exp t
pattern ParenList elems <- Pact.EList (ListExp elems Parens _i)
pattern BraceList :: [Exp t] -> Exp t
pattern BraceList elems <- Pact.EList (ListExp elems Braces _i)
pattern SquareList :: [Exp t] -> Exp t
pattern SquareList elems <- Pact.EList (ListExp elems Brackets _i)
pattern EAtom' :: Text -> Exp t
pattern EAtom' name <- EAtom (AtomExp name [] False _i)
pattern ELiteral' :: Literal -> Exp t
pattern ELiteral' lit <- ELiteral (LiteralExp lit _i)
pattern EStrLiteral' :: Text -> Exp t
pattern EStrLiteral' lit <- ELiteral (LiteralExp (LString lit) _i)
pattern Colon' :: Exp t
pattern Colon' <- ESeparator (SeparatorExp Colon _i)
| null | https://raw.githubusercontent.com/kadena-io/pact/e2f3dd1fd1952bb4f736042083769b52dbb2a819/src-tool/Pact/Analyze/Parse/Types.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE TemplateHaskell #
literals
identifiers
In conversion from @Exp@ to @PreProp@ we maintain a distinction between
bound and unbound variables. Bound (@PreVar@) variables are bound inside
definition or a table.
quantifiers
applications
TODO(joel): add location info
User-defined properties | # LANGUAGE DeriveFunctor #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
| Types related to parsing from ' Exp ' to ' Prop ' and ' Invariant ' .
module Pact.Analyze.Parse.Types where
import Control.Applicative (Alternative)
import Control.Lens (makeLenses, (<&>))
import Control.Monad.Except (MonadError (throwError))
import Control.Monad.Reader (ReaderT)
import Control.Monad.State.Strict (StateT)
import qualified Data.HashMap.Strict as HM
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Prelude hiding (exp)
import Pact.Types.Lang (AtomExp (..),
Exp (EAtom, ELiteral, ESeparator),
ListDelimiter (..), ListExp (..),
Literal (LString), LiteralExp (..),
Separator (..), SeparatorExp (..))
import qualified Pact.Types.Lang as Pact
import Pact.Types.Typecheck (UserType)
import Pact.Types.Pretty
import Pact.Analyze.Feature hiding (Doc, Type, Var, ks, obj,
str)
import Pact.Analyze.Types
@PreProp@ stands between @Exp@ and @Prop@.
The conversion from @Exp@ is light , handled in @expToPreProp@.
data PreProp
= PreIntegerLit Integer
| PreStringLit Text
| PreDecimalLit Decimal
| PreTimeLit Time
| PreBoolLit Bool
| PreListLit [PreProp]
| PreAbort
| PreSuccess
| PreGovPasses
| PreResult
quantifiers . Unbound ( @PreGlobalVar@ ) variables either refer to a property
| PreVar VarId Text
| PreGlobalVar Text
| PreForall VarId Text QType PreProp
| PreExists VarId Text QType PreProp
| PreApp Text [PreProp]
| PreAt PreProp PreProp
| PrePropRead PreProp PreProp PreProp
| PreLiteralObject (Map Text PreProp)
deriving (Eq, Show)
| Find the set of global variables in a @PreProp@.
prePropGlobals :: PreProp -> Set Text
prePropGlobals = \case
PreListLit props -> Set.unions $ prePropGlobals <$> props
PreGlobalVar name -> Set.singleton name
PreForall _ _ _ prop -> prePropGlobals prop
PreExists _ _ _ prop -> prePropGlobals prop
PreApp _ props -> Set.unions $ prePropGlobals <$> props
PreAt p1 p2 -> prePropGlobals p1 `Set.union` prePropGlobals p2
PrePropRead p1 p2 p3 -> Set.unions $ prePropGlobals <$> [p1, p2, p3]
PreLiteralObject obj -> Set.unions $ prePropGlobals <$> Map.elems obj
_ -> Set.empty
instance Pretty PreProp where
pretty = \case
PreIntegerLit i -> pretty i
PreStringLit t -> dquotes $ pretty t
PreDecimalLit d -> pretty d
PreTimeLit t -> pretty (Pact.LTime (toPact timeIso t))
PreBoolLit True -> "true"
PreBoolLit False -> "false"
PreListLit lst -> commaBrackets $ fmap pretty lst
PreAbort -> pretty STransactionAborts
PreSuccess -> pretty STransactionSucceeds
PreGovPasses -> pretty SGovernancePasses
PreResult -> pretty SFunctionResult
PreVar _id name -> pretty name
PreGlobalVar name -> pretty name
PreForall _vid name qty prop ->
"(" <> pretty SUniversalQuantification <> " (" <> pretty name <> ":" <>
pretty qty <> ") " <> pretty prop <> ")"
PreExists _vid name qty prop ->
"(" <> pretty SExistentialQuantification <> " (" <> pretty name <> ":" <>
pretty qty <> ") " <> pretty prop <> ")"
PreApp name applicands ->
"(" <> pretty name <> " " <> hsep (map pretty applicands) <> ")"
PreAt objIx obj ->
"(" <> pretty SObjectProjection <> " " <> pretty objIx <> " " <>
pretty obj <> ")"
PrePropRead tn rk ba ->
"(" <> pretty SPropRead <> " '" <> pretty tn <> " " <> pretty rk <> " " <>
pretty ba <> ")"
PreLiteralObject obj -> commaBraces $ Map.toList obj <&> \(k, v) ->
pretty k <> " := " <> pretty v
throwErrorT :: MonadError String m => Text -> m a
throwErrorT = throwError . T.unpack
throwErrorD :: MonadError String m => Doc -> m a
throwErrorD = throwError . renderCompactString'
throwErrorIn :: (MonadError String m, Pretty a) => a -> Doc -> m b
throwErrorIn exp msg = throwError $ renderCompactString' $
"in " <> pretty exp <> ", " <> msg
textToQuantifier
:: Text -> Maybe (VarId -> Text -> QType -> PreProp -> PreProp)
textToQuantifier = \case
SUniversalQuantification -> Just PreForall
SExistentialQuantification -> Just PreExists
_ -> Nothing
type TableEnv = TableMap (ColumnMap EType)
data PropCheckEnv = PropCheckEnv
{ _varTys :: Map VarId QType
, _tableEnv :: TableEnv
, _quantifiedTables :: Set TableName
, _quantifiedColumns :: Set ColumnName
, _definedProps :: HM.HashMap Text (DefinedProperty PreProp)
Vars bound within a user - defined property
, _localVars :: HM.HashMap Text EProp
}
newtype EitherFail e a = EitherFail { _getEither :: Either e a }
deriving (Show, Eq, Ord, Functor, Applicative, Alternative, Monad, MonadError e)
type ParseEnv = Map Text VarId
type PropParse = ReaderT ParseEnv (StateT VarId (Either String))
type PropCheck = ReaderT PropCheckEnv (EitherFail String)
type InvariantParse = ReaderT [(Pact.Arg UserType, VarId)] (Either String)
makeLenses ''PropCheckEnv
pattern ParenList :: [Exp t] -> Exp t
pattern ParenList elems <- Pact.EList (ListExp elems Parens _i)
pattern BraceList :: [Exp t] -> Exp t
pattern BraceList elems <- Pact.EList (ListExp elems Braces _i)
pattern SquareList :: [Exp t] -> Exp t
pattern SquareList elems <- Pact.EList (ListExp elems Brackets _i)
pattern EAtom' :: Text -> Exp t
pattern EAtom' name <- EAtom (AtomExp name [] False _i)
pattern ELiteral' :: Literal -> Exp t
pattern ELiteral' lit <- ELiteral (LiteralExp lit _i)
pattern EStrLiteral' :: Text -> Exp t
pattern EStrLiteral' lit <- ELiteral (LiteralExp (LString lit) _i)
pattern Colon' :: Exp t
pattern Colon' <- ESeparator (SeparatorExp Colon _i)
|
e28513f372a556203a6f02af0c19da458c1b2aefd5d21ff8d16bccd5b10f116b | modular-macros/ocaml-macros | t090-acc6.ml | open Lib;;
let x = true in
let y = false in
let z = false in
let a = false in
let b = false in
let c = false in
let d = false in
();
if not x then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 PUSHCONST0
16 PUSHCONST0
17 ACC6
18 BOOLNOT
19 BRANCHIFNOT 26
21 GETGLOBAL Not_found
23 MAKEBLOCK1 0
25 RAISE
26 POP 7
28 ATOM0
29 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 PUSHCONST0
16 PUSHCONST0
17 ACC6
18 BOOLNOT
19 BRANCHIFNOT 26
21 GETGLOBAL Not_found
23 MAKEBLOCK1 0
25 RAISE
26 POP 7
28 ATOM0
29 SETGLOBAL T090-acc6
31 STOP
**)
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/tool-ocaml/t090-acc6.ml | ocaml | open Lib;;
let x = true in
let y = false in
let z = false in
let a = false in
let b = false in
let c = false in
let d = false in
();
if not x then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 PUSHCONST0
16 PUSHCONST0
17 ACC6
18 BOOLNOT
19 BRANCHIFNOT 26
21 GETGLOBAL Not_found
23 MAKEBLOCK1 0
25 RAISE
26 POP 7
28 ATOM0
29 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST1
10 PUSHCONST0
11 PUSHCONST0
12 PUSHCONST0
13 PUSHCONST0
14 PUSHCONST0
15 PUSHCONST0
16 PUSHCONST0
17 ACC6
18 BOOLNOT
19 BRANCHIFNOT 26
21 GETGLOBAL Not_found
23 MAKEBLOCK1 0
25 RAISE
26 POP 7
28 ATOM0
29 SETGLOBAL T090-acc6
31 STOP
**)
| |
1559fb3726eff1a4ceb4ceeff9c2a9f51ff96806ed08e55497df5bc1b11b612b | bravit/hid-examples | STExcept.hs | {-# LANGUAGE DeriveAnyClass #-}
module STExcept where
import Data.Text (Text)
import Control.Monad.Catch
import Network.HTTP.Req
import qualified Network.HTTP.Client as NC
import Types
data RequestError = EmptyRequest | WrongDay Text
deriving Show
data SunInfoException = UnknownLocation Text
| UnknownTime GeoCoords
| FormatError RequestError
| ServiceAPIError String
| NetworkError SomeException
| ConfigError
deriving Exception
instance Show SunInfoException where
show (UnknownLocation _) = "Failed while determining coordinates"
show (UnknownTime _) = "Failed while determining sunrise/sunset times"
show (FormatError er) = show er
show (ServiceAPIError _) = "Error while communicating with external services"
show (NetworkError _) = "Network communication error"
show ConfigError = "Error parsing configuration file"
rethrowReqException :: MonadThrow m => HttpException -> m a
rethrowReqException (JsonHttpException s) = throwM (ServiceAPIError s)
rethrowReqException (VanillaHttpException (
NC.HttpExceptionRequest _
(NC.StatusCodeException resp _ ))) =
throwM (ServiceAPIError $ show $ NC.responseStatus resp)
rethrowReqException (VanillaHttpException e) = throwM (NetworkError $ toException e)
| null | https://raw.githubusercontent.com/bravit/hid-examples/913e116b7ee9c7971bba10fe70ae0b61bfb9391b/suntimes/STExcept.hs | haskell | # LANGUAGE DeriveAnyClass # |
module STExcept where
import Data.Text (Text)
import Control.Monad.Catch
import Network.HTTP.Req
import qualified Network.HTTP.Client as NC
import Types
data RequestError = EmptyRequest | WrongDay Text
deriving Show
data SunInfoException = UnknownLocation Text
| UnknownTime GeoCoords
| FormatError RequestError
| ServiceAPIError String
| NetworkError SomeException
| ConfigError
deriving Exception
instance Show SunInfoException where
show (UnknownLocation _) = "Failed while determining coordinates"
show (UnknownTime _) = "Failed while determining sunrise/sunset times"
show (FormatError er) = show er
show (ServiceAPIError _) = "Error while communicating with external services"
show (NetworkError _) = "Network communication error"
show ConfigError = "Error parsing configuration file"
rethrowReqException :: MonadThrow m => HttpException -> m a
rethrowReqException (JsonHttpException s) = throwM (ServiceAPIError s)
rethrowReqException (VanillaHttpException (
NC.HttpExceptionRequest _
(NC.StatusCodeException resp _ ))) =
throwM (ServiceAPIError $ show $ NC.responseStatus resp)
rethrowReqException (VanillaHttpException e) = throwM (NetworkError $ toException e)
|
3940c2cfd2bc75d0e249e8cabcc419f1ab53b0c62defd2e5afe38bf8afba9a92 | aumouvantsillage/Hydromel-lang | main.rkt | 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 /.
#lang racket
(require
"lib/expander.rkt"
"lib/checker.rkt"
"lib/std.rkt")
(provide
(all-from-out "lib/expander.rkt")
(all-from-out "lib/checker.rkt")
(all-from-out "lib/std.rkt"))
| null | https://raw.githubusercontent.com/aumouvantsillage/Hydromel-lang/e5416cdbdf07dd8f47cda48273f5ff2d0fee5007/hydromel/main.rkt | racket | 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 /.
#lang racket
(require
"lib/expander.rkt"
"lib/checker.rkt"
"lib/std.rkt")
(provide
(all-from-out "lib/expander.rkt")
(all-from-out "lib/checker.rkt")
(all-from-out "lib/std.rkt"))
| |
518b6c5cc20a406d98ddc3ff10928009b8fac9778531ff1b794229f8f2f68f5b | PuercoPop/Movitz | special-operators-cl.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
;;;;
;;;; Filename: special-operators-cl.lisp
;;;; Description: Special operators in the COMMON-LISP package.
Author : < >
Created at : Fri Nov 24 16:31:11 2000
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : special - operators - cl.lisp , v 1.55 2008 - 07 - 09 19:57:02 Exp $
;;;;
;;;;------------------------------------------------------------------
(in-package movitz)
(define-special-operator progn (&all all &form form &top-level-p top-level-p &result-mode result-mode)
(compiler-call #'compile-implicit-progn
:form (cdr form)
:forward all))
(defun expand-to-operator (operator form env)
"Attempt to compiler-macroexpand FORM to having operator OPERATOR."
(if (and (listp form) (eq operator (first form)))
form
(multiple-value-bind (expansion expanded-p)
(like-compile-macroexpand-form form env)
(if expanded-p
(expand-to-operator operator expansion env)
nil))))
(defun parse-let-var-specs (let-var-specs)
"Given a list of LET variable specifiers (i.e. either VAR or (VAR INIT-FORM)),~
return a list on the canonical form (VAR INIT-FORM)."
(loop for var-spec in let-var-specs
if (symbolp var-spec)
collect `(,var-spec nil)
else if (and (listp var-spec)
(= 1 (length var-spec)))
collect `(,(first var-spec) nil)
else do (assert (and (listp var-spec)
(= 2 (length var-spec))))
and collect var-spec))
(define-special-operator let (&all all &form form &funobj funobj &env env &result-mode result-mode)
"An extent-nested let is this: (let ((foo ..) (bar (.. (let ((zot ..)) ..)))))
where zot is not in foo's scope, but _is_ in foo's extent."
(destructuring-bind (operator let-var-specs &body forms)
form
(declare (ignore operator))
(multiple-value-bind (body declarations)
(parse-declarations-and-body forms)
(if (and (null let-var-specs)
(null declarations))
(compiler-call #'compile-implicit-progn
:forward all
:form body)
(let* ((let-modifies nil)
(let-vars (parse-let-var-specs let-var-specs))
(local-env (make-local-movitz-environment env funobj
:type 'let-env
:declarations declarations))
(init-env #+ignore env
(make-instance 'movitz-environment
:uplink env
:funobj funobj
:extent-uplink local-env))
(stack-used 0)
(binding-var-codes
(loop for (var init-form) in let-vars
if (movitz-env-get var 'special nil local-env)
special ... see losp / cl / run - time.lisp
collect
(list var
init-form
(append (if (= 0 (num-specials local-env)) ; first special? .. binding tail
`((:locally (:pushl (:edi (:edi-offset dynamic-env)))))
`((:pushl :esp)))
(compiler-call #'compile-form ; binding value
:with-stack-used (incf stack-used)
:env init-env
:defaults all
:form init-form
:modify-accumulate let-modifies
:result-mode :push)
`((:pushl :edi)) ; scratch
(compiler-call #'compile-form ; binding name
:with-stack-used (incf stack-used 2)
:env init-env
:defaults all
:form `(muerte.cl:quote ,var)
:result-mode :push)
(prog1 nil (incf stack-used)))
nil t)
and do (movitz-env-add-binding local-env (make-instance 'dynamic-binding
:name var))
and do (incf (num-specials local-env))
;; lexical...
else collect
(let ((binding (make-instance 'located-binding :name var)))
(movitz-env-add-binding local-env binding)
(compiler-values-bind (&code init-code &functional-p functional-p
&type type &returns init-register
&final-form final-form)
(compiler-call #'compile-form-unprotected
:result-mode binding
:env init-env
:extent local-env
:defaults all
:form init-form)
#+ignore
(compiler-call #'compile-form-to-register
:env init-env
:extent local-env
:defaults all
:form init-form
:modify-accumulate let-modifies)
(when (eq binding init-register)
(setf init-register nil))
;;; (warn "var ~S, type: ~S" var type)
( warn " var ~S init : ~S .. " var init - form )
;;; (warn "bind: ~S reg: ~S" binding init-register)
;;; (print-code 'init init-code)
(list var
init-form
init-code
functional-p
(let ((init-type (type-specifier-primary type)))
(assert init-type ()
"The init-form ~S yielded the empty primary type!" type)
init-type)
(case init-register
(:non-local-exit :edi)
(:multiple-values :eax)
(t init-register))
final-form))))))
(setf (stack-used local-env) stack-used)
(flet ((compile-body ()
(if (= 0 (num-specials local-env))
(compiler-call #'compile-implicit-progn
:defaults all
:form body
:env local-env)
(compiler-call #'compile-form
:result-mode (case result-mode
(:push :eax)
(:function :multiple-values)
(t result-mode))
:defaults all
:form `(muerte.cl:progn ,@body)
:modify-accumulate let-modifies
:env local-env))))
(compiler-values-bind (&all body-values &code body-code &returns body-returns)
(compile-body)
;; (print-code 'body body)
;; (print-code 'body-code body-code)
(let ((first-binding (movitz-binding (caar binding-var-codes) local-env nil)))
(cond
;; Is this (let ((#:foo <form>)) (setq bar #:foo)) ?
;; If so, make it into (setq bar <form>)
((and (= 1 (length binding-var-codes))
(typep first-binding 'lexical-binding)
(instruction-is (first body-code) :load-lexical)
(instruction-is (second body-code) :store-lexical)
(null (cddr body-code))
(eq first-binding ; same binding?
(second (first body-code)))
(eq (third (first body-code)) ; same register?
(third (second body-code))))
(let ((dest-binding (second (second body-code))))
(check-type dest-binding lexical-binding)
(compiler-call #'compile-form
:forward all
:extent local-env
:result-mode dest-binding
:form (second (first binding-var-codes)))))
#+ignore
((and (= 1 (length binding-var-codes))
(typep (movitz-binding (caar binding-var-codes) local-env nil)
'lexical-binding)
(member (movitz-binding (caar binding-var-codes) local-env nil)
(find-read-bindings (first body-code)))
(not (code-uses-binding-p (rest body-code) (second (first body-code))
:load t :store nil)))
(let ((tmp-binding (second (first body-code))))
(print-code 'body body-code)
(break "Yuhu: tmp ~S" tmp-binding)
))
(t (let ((code
(append
(loop
for ((var init-form init-code functional-p type init-register
final-form)
. rest-codes)
on binding-var-codes
as binding = (movitz-binding var local-env nil)
;; for bb in binding-var-codes
;; do (warn "bind: ~S" bb)
do (assert type)
(assert (not (binding-lended-p binding)))
appending
(cond
((and (typep binding 'located-binding)
(not (binding-lended-p binding))
(typep final-form 'lexical-binding)
(let ((target-binding final-form))
(and (typep target-binding 'lexical-binding)
(eq (binding-funobj binding)
(binding-funobj target-binding))
#+ignore
(sub-env-p (binding-env binding)
(binding-env target-binding))
(or (and (not (code-uses-binding-p body-code
binding
:load nil
:store t))
(not (code-uses-binding-p body-code
target-binding
:load nil
:store t)))
(and (= 1 (length body-code))
(eq :add (caar body-code)))
(and (>= 1 (length body-code))
(warn "short let body: ~S" body-code))
;; This is the best we can do now to determine
;; if target-binding is ever used again.
(and (eq result-mode :function)
(not (and (bindingp body-returns)
(binding-eql target-binding
body-returns)))
(not (code-uses-binding-p body-code
target-binding
:load t
:store t))
(notany (lambda (code)
(code-uses-binding-p (third code)
target-binding
:load t
:store t))
rest-codes))))))
;; replace read-only binding with the outer binding
(compiler-values-bind (&code new-init-code &final-form target
&type type)
(compiler-call #'compile-form-unprotected
:extent local-env
:form init-form
:result-mode :ignore
:env init-env
:defaults all)
(check-type target lexical-binding)
(change-class binding 'forwarding-binding
:target-binding target)
(let ((btype (if (multiple-value-call #'encoded-allp
(type-specifier-encode
(type-specifier-primary type)))
target
(type-specifier-primary type))))
#+ignore (warn "forwarding ~S -[~S]> ~S"
binding btype target)
(append new-init-code
`((:init-lexvar
,binding
:init-with-register ,target
:init-with-type ,btype))))))
((and (typep binding 'located-binding)
(type-specifier-singleton type)
(not (code-uses-binding-p body-code binding
:load nil :store t)))
;; replace read-only lexical binding with
;; side-effect-free form
#+ignore
(warn "Constant binding: ~S => ~S => ~S"
(binding-name binding)
init-form
(car (type-specifier-singleton type)))
(change-class binding 'constant-object-binding
:object (car (type-specifier-singleton type)))
(if functional-p
nil ; only inject code if it's got side-effects.
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies)))
((typep binding 'lexical-binding)
(let ((init (type-specifier-singleton
(type-specifier-primary type))))
(cond
((and init (eq *movitz-nil* (car init)))
(append (if functional-p
nil
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies))
`((:init-lexvar ,binding
:init-with-register :edi
:init-with-type null))))
((and (typep final-form 'lexical-binding)
(eq (binding-funobj final-form)
funobj))
(compiler-values-bind (&code new-init-code
&type new-type
&final-form new-binding)
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies)
(append (if functional-p
nil
new-init-code)
(let ((ptype (type-specifier-primary new-type)))
`((:init-lexvar ,binding
:init-with-register ,new-binding
:init-with-type ,ptype
))))))
((typep final-form 'constant-object-binding)
#+ignore
(warn "type: ~S or ~S" final-form
(type-specifier-primary type))
(append (if functional-p
nil
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies))
`((:init-lexvar
,binding
:init-with-register ,final-form
:init-with-type ,(type-specifier-primary type)
))))
(t ;; (warn "for ~S ~S ~S" binding init-register final-form)
(append init-code
`((:init-lexvar
,binding
:init-with-register ,init-register
:init-with-type ,(type-specifier-primary type))))))))
(t init-code)))
(when (plusp (num-specials local-env))
`((:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-install))))
(:locally (:movl :esp (:edi (:edi-offset dynamic-env))))))
body-code
(when (and (plusp (num-specials local-env))
(not (eq :non-local-exit body-returns)))
#+ignore
(warn "let spec ret: ~S, want: ~S ~S"
body-returns result-mode let-var-specs)
`((:movl (:esp ,(+ -4 (* 16 (num-specials local-env)))) :edx)
(:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-uninstall))))
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp ,(* 16 (num-specials local-env))) :esp))))))
(compiler-values (body-values)
:returns body-returns
:producer (default-compiler-values-producer)
:functional-p (and (body-values :functional-p)
(every #'fourth binding-var-codes))
:modifies let-modifies
:code code))))))))))))
(define-special-operator symbol-macrolet (&all forward &form form &env env &funobj funobj)
(destructuring-bind (symbol-expansions &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let ((local-env (make-local-movitz-environment
env funobj
:type 'operator-env
:declarations declarations)))
(loop for symbol-expansion in symbol-expansions
do (destructuring-bind (symbol expansion)
symbol-expansion
(movitz-env-add-binding local-env (make-instance 'symbol-macro-binding
:name symbol
:expander #'(lambda (form env)
(declare (ignore form env))
expansion)))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env local-env
:top-level-p (forward :top-level-p))
(compiler-values (body-values)
:code body-code))))))
(define-special-operator macrolet (&all forward &form form &funobj funobj &env env)
(destructuring-bind (macrolet-specs &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let ((local-env (make-local-movitz-environment env funobj
:type 'operator-env
:declarations declarations)))
(loop for (name local-lambda-list . local-body-decl-doc) in macrolet-specs
as cl-local-lambda-list = (translate-program local-lambda-list :muerte.cl :cl)
as (local-body local-declarations) =
(multiple-value-list (parse-docstring-declarations-and-body local-body-decl-doc))
as cl-local-body = (translate-program local-body :muerte.cl :cl)
as cl-local-declarations = (translate-program local-declarations :muerte.cl :cl)
as expander = `(lambda (form env)
(declare (ignorable env))
(destructuring-bind ,cl-local-lambda-list
(translate-program (rest form) :muerte.cl :cl)
(declare ,@cl-local-declarations)
(translate-program (block ,name (let () ,@cl-local-body))
:cl :muerte.cl)))
do (movitz-env-add-binding
local-env
(make-instance 'macro-binding
:name name
:expander (movitz-macro-expander-make-function expander
:name name
:type :macrolet))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env local-env
:top-level-p (forward :top-level-p))
(compiler-values (body-values)
:code body-code))))))
(define-special-operator multiple-value-prog1 (&all all &form form &result-mode result-mode &env env)
(destructuring-bind (first-form &rest rest-forms)
(cdr form)
(compiler-values-bind (&code form1-code &returns form1-returns &type type)
(compiler-call #'compile-form-unprotected
:defaults all
:result-mode (case (result-mode-type result-mode)
((:boolean-branch-on-true :boolean-branch-on-false)
:eax)
(t result-mode))
:form first-form)
(compiler-call #'special-operator-with-cloak
;; :with-stack-used t
:forward all
:form `(muerte::with-cloak (,form1-returns ,form1-code t ,type)
,@rest-forms)))))
(define-special-operator multiple-value-call (&all all &form form &funobj funobj)
(destructuring-bind (function-form &rest subforms)
(cdr form)
(let* ((local-env (make-instance 'let-env
:uplink (all :env)
:funobj funobj
:stack-used t))
(numargs-binding (movitz-env-add-binding local-env
(make-instance 'located-binding
:name (gensym "m-v-numargs-"))))
(arg-code (loop for subform in subforms
collecting
(compiler-values-bind (&code subform-code &returns subform-returns)
(compiler-call #'compile-form-unprotected
:defaults all
:env local-env
:form subform
:result-mode :multiple-values)
(case subform-returns
(:multiple-values
`(:multiple
,@subform-code
,@(make-compiled-push-current-values)
(:load-lexical ,numargs-binding :eax)
(:addl :ecx :eax)
(:store-lexical ,numargs-binding :eax :type fixnum)))
(t (list :single ; marker, used below
subform))))))
(number-of-multiple-value-subforms (count :multiple arg-code :key #'car))
(number-of-single-value-subforms (count :single arg-code :key #'car)))
(cond
((= 0 number-of-multiple-value-subforms)
(compiler-call #'compile-form
:forward all
:form `(muerte.cl::funcall ,function-form ,@subforms)))
(t (compiler-values ()
:returns :multiple-values
:code (append `((:load-constant ,(1+ number-of-single-value-subforms) :eax)
(:store-lexical ,numargs-binding :eax :type fixnum))
(compiler-call #'compile-form
:defaults all
:env local-env
:form function-form
:result-mode :push)
(loop for ac in arg-code
append (ecase (car ac)
(:single
(compiler-call #'compile-form
:defaults all
:env local-env
:form (second ac)
:result-mode :push))
(:multiple
(cdr ac))))
`((:load-lexical ,numargs-binding :ecx)
;; (:store-lexical ,numargs-binding :ecx :type t)
(:movl (:esp (:ecx 1) -4) :eax)
(:movl (:esp (:ecx 1) -8) :ebx)
(:shrl ,+movitz-fixnum-shift+ :ecx)
(:load-constant muerte.cl::funcall :edx)
(:movl (:edx ,(slot-offset 'movitz-symbol 'function-value))
load new funobj from symbol into ESI
(:call (:esi ,(slot-offset 'movitz-funobj 'code-vector)))
(:load-lexical ,numargs-binding :edx)
Use so as not to modify CF
(:leal (:esp :edx) :esp)))))))))
(define-special-operator multiple-value-bind (&all forward &form form &env env &funobj funobj
&result-mode result-mode)
(destructuring-bind (variables values-form &body body-and-declarations)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body body-and-declarations)
(compiler-values-bind (&code values-code &returns values-returns &type values-type)
(compiler-call #'compile-form
:defaults forward
:form values-form
:result-mode :multiple-values #+ignore (list :values (length variables)))
( warn " mv - code : ~W ~W = > ~W ~W " values - form ( list : values ( length variables ) ) values - returns ( last values - code 10 ) )
(let* ((local-env (make-local-movitz-environment
env funobj
:type 'let-env
:declarations declarations))
(lexical-bindings
(loop for variable in variables
as new-binding = (make-instance 'located-binding
:name variable)
do (check-type variable symbol)
collect new-binding
do (cond
((movitz-env-get variable 'special nil env)
(let* ((shadowed-variable (gensym (format nil "m-v-bind-shadowed-~A"
variable))))
(movitz-env-add-binding local-env new-binding shadowed-variable)
(push (list variable shadowed-variable)
(special-variable-shadows local-env))))
(t (movitz-env-add-binding local-env new-binding)))))
(init-var-code
(case (first (operands values-returns))
(t (append
(make-result-and-returns-glue :multiple-values values-returns)
(case (length lexical-bindings)
(0 nil)
(1 `((:init-lexvar ,(first lexical-bindings)
:protect-carry nil
:protect-registers '(:eax))
(:store-lexical ,(first lexical-bindings) :eax
:type ,(type-specifier-primary values-type))))
(2 (let ((done-label (gensym "m-v-bind-done-")))
`((:init-lexvar ,(first lexical-bindings)
:protect-carry t
:protect-registers (:eax :ebx))
(:store-lexical ,(first lexical-bindings) :eax
:type ,(type-specifier-primary values-type)
:protect-registers (:ebx))
(:init-lexvar ,(second lexical-bindings)
:protect-carry t
:protect-registers (:ebx))
(:store-lexical ,(second lexical-bindings) :edi
:type null)
(:jnc ',done-label)
(:cmpl 1 :ecx)
(:jbe ',done-label)
(:store-lexical ,(second lexical-bindings) :ebx
:type ,(type-specifier-nth-value 1 values-type))
,done-label)))
(t (with-labels (m-v-bind (ecx-ok-label))
`((:jc ',ecx-ok-label)
,@(make-immediate-move 1 :ecx) ; CF=0 means arg-count=1
,ecx-ok-label
,@(loop for binding in lexical-bindings as pos upfrom 0
as skip-label = (gensym "m-v-bind-skip-")
as type = (type-specifier-nth-value pos values-type)
append
(case pos
(0 `((:init-lexvar ,binding
:protect-registers (:eax :ebx :ecx))
(:store-lexical ,binding :eax :type ,type
:protect-registers (:eax :ebx :ecx))))
(1 `((:init-lexvar ,binding
:protect-registers (:ebx :ecx))
(:store-lexical ,binding :edi :type null
:protect-registers (:ecx))
(:cmpl 1 :ecx)
(:jbe ',skip-label)
(:store-lexical ,binding :ebx :type ,type
:protect-registers (:ecx))
,skip-label))
(t (if *compiler-use-cmov-p*
`((:init-lexvar ,binding :protect-registers '(:ecx))
(:movl :edi :eax)
(:cmpl ,pos :ecx)
(:locally (:cmova (:edi (:edi-offset values
,(* 4 (- pos 2))))
:eax))
(:store-lexical ,binding :eax :type ,type
:protect-registers (:eax)))
`((:init-lexvar ,binding :protect-registers '(:ecx))
(:movl :edi :eax)
(:cmpl ,pos :ecx)
(:jbe ',skip-label)
(:locally (:movl (:edi (:edi-offset values
,(* 4 (- pos 2))))
:eax))
,skip-label
(:store-lexical ,binding :eax :type ,type
:protect-registers (:ecx))))))))))))))))
(compiler-values-bind (&code body-code &returns body-returns-mode)
(compiler-call #'compile-form-unprotected
:defaults forward
:form `(muerte.cl:let ,(special-variable-shadows local-env) ,@body)
:env local-env)
(compiler-values ()
:returns body-returns-mode
:code (append values-code
init-var-code
body-code))))))))
(define-special-operator setq (&all forward &form form &env env &funobj funobj &result-mode result-mode)
(let ((pairs (cdr form)))
(unless (evenp (length pairs))
(error "Odd list of SETQ pairs: ~S" pairs))
(let* ((last-returns :nothing)
(bindings ())
(code (loop
for (var value-form) on pairs by #'cddr
as binding = (movitz-binding var env)
as pos downfrom (- (length pairs) 2) by 2
as sub-result-mode = (if (zerop pos) result-mode :ignore)
do (pushnew binding bindings)
append
(typecase binding
(symbol-macro-binding
(compiler-values-bind (&code code &returns returns)
(compiler-call #'compile-form-unprotected
:defaults forward
:result-mode sub-result-mode
:form `(muerte.cl:setf ,var ,value-form))
(setf last-returns returns)
code))
(lexical-binding
(case (operator sub-result-mode)
(t ;; :ignore
( setf last - returns : nothing )
(compiler-values-bind (&code sub-code &returns sub-returns)
(compiler-call #'compile-form
:defaults forward
:form value-form
:result-mode binding)
(setf last-returns sub-returns)
;; (warn "sub-returns: ~S" sub-returns)
sub-code))
#+ignore
(t (let ((register (accept-register-mode sub-result-mode)))
(compiler-values-bind (&code code &type type)
(compiler-call #'compile-form
:defaults forward
:form value-form
:result-mode register)
(setf last-returns register)
(append code
`((:store-lexical ,binding ,register
:type ,(type-specifier-primary type)))))))))
(t (unless (movitz-env-get var 'special nil env)
(warn "Assuming destination variable ~S with binding ~S is special."
var binding))
(setf last-returns :ebx)
(append (compiler-call #'compile-form
:defaults forward
:form value-form
:result-mode :ebx)
`((:load-constant ,var :eax)
(:locally (:call (:edi (:edi-offset dynamic-variable-store)))))))))))
(compiler-values ()
:code code
:returns last-returns
:functional-p nil))))
(define-special-operator tagbody (&all forward &funobj funobj &form form &env env)
(let* ((save-esp-variable (gensym "tagbody-save-esp"))
(lexical-catch-tag-variable (gensym "tagbody-lexical-catch-tag-"))
(label-set-name (gensym "label-set-"))
(tagbody-env (make-instance 'tagbody-env
:uplink env
:funobj funobj
:save-esp-variable save-esp-variable
:lexical-catch-tag-variable lexical-catch-tag-variable
:exit-result-mode :ignore))
(save-esp-binding (make-instance 'located-binding
:name save-esp-variable))
(lexical-catch-tag-binding (make-instance 'located-binding
:name lexical-catch-tag-variable)))
(movitz-env-add-binding tagbody-env save-esp-binding)
(movitz-env-add-binding tagbody-env lexical-catch-tag-binding)
(movitz-env-load-declarations `((muerte.cl::ignorable ,save-esp-variable ,lexical-catch-tag-variable))
tagbody-env nil)
First generate an assembly - level label for each tag .
(let* ((label-set (loop with label-id = 0
for tag-or-statement in (cdr form)
as label = (when (or (symbolp tag-or-statement)
(integerp tag-or-statement))
(gensym (format nil "go-tag-~A-" tag-or-statement)))
when label
do (setf (movitz-env-get tag-or-statement 'go-tag nil tagbody-env)
label)
(setf (movitz-env-get tag-or-statement 'go-tag-label-id nil tagbody-env)
(post-incf label-id))
and collect label))
(tagbody-codes
(loop for tag-or-statement in (cdr form)
if (or (symbolp tag-or-statement) ; Tagbody tags are "compiled" into..
(integerp tag-or-statement)) ; ..their assembly-level labels.
collect (movitz-env-get tag-or-statement 'go-tag nil tagbody-env)
else collect
(compiler-call #'compile-form
:defaults forward
:form tag-or-statement
:env tagbody-env
:result-mode :ignore))))
(let* ((unlexical-target-p (some (lambda (code)
(when (listp code)
(code-uses-binding-p code save-esp-binding)))
tagbody-codes))
(maybe-store-esp-code
(when (or unlexical-target-p
(some (lambda (code)
(when (listp code)
(operators-present-in-code-p code '(:lexical-control-transfer) nil
:test (lambda (x)
(eq tagbody-env (fifth x))))))
tagbody-codes))
`((:init-lexvar ,save-esp-binding
:init-with-register :esp
:init-with-type t)))))
(if (not unlexical-target-p)
(compiler-values ()
:code (append maybe-store-esp-code
(loop for code in tagbody-codes
if (listp code)
append code
else append (list code)))
:returns :nothing)
(let ((code (append `((:declare-label-set ,label-set-name ,label-set)
;; catcher
(:locally (:pushl (:edi (:edi-offset dynamic-env))))
(:pushl ',label-set-name)
(:locally (:pushl (:edi (:edi-offset unbound-function))))
(:pushl :ebp)
(:locally (:movl :esp (:edi (:edi-offset dynamic-env)))))
maybe-store-esp-code
(loop for code in tagbody-codes
if (listp code)
append code
else append (list code '(:movl (:esp) :ebp)))
`((:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp))
)))
(setf (num-specials tagbody-env) 1
(stack-used tagbody-env) 4)
(compiler-values ()
:code code
:returns :nothing)))))))
(define-special-operator go (&all all &form form &env env &funobj funobj)
(destructuring-bind (operator tag)
form
(declare (ignore operator))
(multiple-value-bind (label tagbody-env)
(movitz-env-get tag 'go-tag nil env)
(assert (and label tagbody-env) ()
"Go-tag ~W is not visible." tag)
(multiple-value-bind (stack-distance num-dynamic-slots unwind-protects)
(stack-delta env tagbody-env)
(declare (ignore stack-distance))
(if (and (eq funobj (movitz-environment-funobj tagbody-env))
;; A well-known number of dynamic-slots?
(not (eq t num-dynamic-slots))
;; any unwind-protects between here and there?
(null unwind-protects))
(compiler-values ()
:returns :non-local-exit
:code `((:lexical-control-transfer nil :nothing ,env ,tagbody-env ,label)))
;; Perform a lexical "throw" to the tag. Just like a regular (dynamic) throw.
(let ((save-esp-binding (movitz-binding (save-esp-variable tagbody-env) env))
(label-id (movitz-env-get tag 'go-tag-label-id nil tagbody-env nil)))
(assert label-id)
(compiler-values ()
:returns :non-local-exit
:code `((:load-lexical ,save-esp-binding :edx)
(:movl :edx :eax)
,@(when (plusp label-id)
;; The target jumper points to the tagbody's label-set.
;; Now, install correct jumper within tagbody as target.
`((:addl ,(* 4 label-id) (:edx 8))))
(:locally (:call (:edi (:edi-offset dynamic-unwind-next))))
have next - continuation in EAX , final - continuation in EDX
(:locally (:movl :edx (:edi (:edi-offset raw-scratch0)))) ; final continuation
(:locally (:movl :eax (:edi (:edi-offset dynamic-env)))) ; new dynamic-env
(:movl :eax :edx)
(:clc)
(:locally (:call (:edi (:edi-offset dynamic-jump-next))))))))))))
(: locally (: : edx (: edi (: edi - offset dynamic - env ) ) ) ) ; exit to next - env
(: : edx : esp ) ; enter non - local jump stack mode .
(: (: esp ) : edx ) ; target stack - frame EBP
(: movl (: edx -4 ) : esi ) ; get target funobj into ESI
(: (: esp 8) : edx ) ; target jumper number
(: jmp (: esi : edx , ( slot - offset ' movitz - funobj ' ) ) ) ) ) ) ) ) ) ) )
(define-special-operator block (&all forward &funobj funobj &form form &env env
&result-mode result-mode)
(destructuring-bind (block-name &body body)
(cdr form)
(let* ((exit-block-label (gensym (format nil "exit-block-~A-" block-name)))
(save-esp-variable (gensym (format nil "block-~A-save-esp-" block-name)))
(lexical-catch-tag-variable (gensym (format nil "block-~A-lexical-catch-tag-" block-name)))
(block-result-mode (case result-mode
((:eax :eax :multiple-values :function :ebx :ecx :ignore)
result-mode)
(t :eax)))
(block-returns-mode (case (result-mode-type block-result-mode)
(:function :multiple-values)
(:ignore :nothing)
((:boolean-branch-on-true :boolean-branch-on-false) :eax)
(t block-result-mode)))
(block-env (make-instance 'lexical-exit-point-env
:uplink env
:funobj funobj
:save-esp-variable save-esp-variable
:lexical-catch-tag-variable lexical-catch-tag-variable
:exit-label exit-block-label
:exit-result-mode block-result-mode))
(save-esp-binding (make-instance 'located-binding
:name save-esp-variable)))
(movitz-env-add-binding block-env save-esp-binding)
(movitz-env-load-declarations `((muerte.cl::ignorable ,save-esp-variable))
block-env nil)
(setf (movitz-env-get block-name :block-name nil block-env)
block-env)
(compiler-values-bind (&code block-code &functional-p block-no-side-effects-p)
(compiler-call #'compile-form
:defaults forward
:result-mode (case block-result-mode
(:function :multiple-values) ; must restore stack
(t block-result-mode))
:form `(muerte.cl:progn ,@body)
:env block-env)
(let ((label-set-name (gensym "block-label-set-"))
(maybe-store-esp-code
(when (and #+ignore (not (eq block-result-mode :function))
(operators-present-in-code-p block-code '(:lexical-control-transfer) nil
:test (lambda (x) (eq block-env (fifth x)))))
`((:init-lexvar ,save-esp-binding
:init-with-register :esp
:init-with-type t)))))
(if (not (code-uses-binding-p block-code save-esp-binding))
(compiler-values ()
:code (append maybe-store-esp-code
block-code
(list exit-block-label))
:returns block-returns-mode
:functional-p block-no-side-effects-p)
(multiple-value-bind (new-code new-returns)
(make-result-and-returns-glue :multiple-values block-returns-mode block-code)
(assert (eq :multiple-values new-returns))
(incf (stack-used block-env) 4)
block - env now has one dynamic slot
(compiler-values ()
:code (append `((:declare-label-set ,label-set-name (,exit-block-label))
;; catcher
(:locally (:pushl (:edi (:edi-offset dynamic-env))))
(:pushl ',label-set-name)
(:locally (:pushl (:edi (:edi-offset unbound-function))))
(:pushl :ebp)
(:locally (:movl :esp (:edi (:edi-offset dynamic-env)))))
`((:init-lexvar ,save-esp-binding
:init-with-register :esp
:init-with-type t))
new-code
;; wrapped-code
`(,exit-block-label
(:movl (:esp 0) :ebp)
(:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp)))
:returns :multiple-values
:functional-p block-no-side-effects-p))))))))
(define-special-operator return-from (&all all &form form &env env &funobj funobj)
(destructuring-bind (block-name &optional result-form)
(cdr form)
(let ((block-env (movitz-env-get block-name :block-name nil env)))
(assert block-env (block-name)
"Block-name not found for return-from: ~S." block-name)
(multiple-value-bind (stack-distance num-dynamic-slots unwind-protects)
(stack-delta env block-env)
(declare (ignore stack-distance))
(cond
((and (eq funobj (movitz-environment-funobj block-env))
(not (eq t num-dynamic-slots))
(null unwind-protects))
(compiler-values-bind (&code return-code &returns return-mode)
(compiler-call #'compile-form
:forward all
:form result-form
:result-mode (exit-result-mode block-env))
(compiler-values ()
:returns :non-local-exit
:code (append return-code
`((:lexical-control-transfer nil ,return-mode ,env ,block-env))))))
((not (and (eq funobj (movitz-environment-funobj block-env))
(not (eq t num-dynamic-slots))
(null unwind-protects)))
(compiler-call #'compile-form-unprotected
:forward all
:form `(muerte::exact-throw ,(save-esp-variable block-env)
,result-form))))))))
(define-special-operator require (&form form)
(let ((*require-dependency-chain*
(and (boundp '*require-dependency-chain*)
(symbol-value '*require-dependency-chain*))))
(declare (special *require-dependency-chain*))
(destructuring-bind (module-name &optional path-spec)
(cdr form)
(declare (ignore path-spec))
(push module-name *require-dependency-chain*)
(unless (member module-name (image-movitz-modules *image*))
(when (member module-name (cdr *require-dependency-chain*))
(error "Circular Movitz module dependency chain: ~S"
(reverse (subseq *require-dependency-chain* 0
(1+ (position module-name *require-dependency-chain* :start 1))))))
(let* ((require-path (movitz-module-path form)))
(movitz-compile-file-internal require-path)
(unless (member module-name (image-movitz-modules *image*))
(error "Compiling file ~S didn't provide module ~S."
require-path module-name))))))
(compiler-values ()))
(define-special-operator provide (&form form &funobj funobj &top-level-p top-level-p)
(unless top-level-p
(warn "Provide form not at top-level."))
(destructuring-bind (module-name &key load-priority)
(cdr form)
(declare (special *default-load-priority*))
(pushnew module-name (image-movitz-modules *image*))
(when load-priority
(setf *default-load-priority* load-priority))
(let ((new-priority *default-load-priority*))
(let ((old-tf (member module-name (image-load-time-funobjs *image*) :key #'second)))
(cond
((and new-priority old-tf)
(setf (car old-tf) (list funobj module-name new-priority)))
((and new-priority (not old-tf))
(push (list funobj module-name new-priority)
(image-load-time-funobjs *image*)))
(old-tf
(setf (car old-tf) (list funobj module-name (third (car old-tf)))))
(t (warn "No existing or provided load-time priority for module ~S, will not be loaded!"
module-name))))))
(compiler-values ()))
(define-special-operator eval-when (&all forward &form form &top-level-p top-level-p)
(destructuring-bind (situations &body body)
(cdr form)
(multiple-value-prog1
(if (or (member :execute situations)
(and (member :load-toplevel situations)
top-level-p))
(compiler-call #'compile-implicit-progn
:defaults forward
:top-level-p top-level-p
:form body)
(compiler-values ()))
(when (and (member :compile-toplevel situations)
top-level-p)
(with-compilation-unit ()
(dolist (toplevel-form (translate-program body :muerte.cl :cl
:when :eval
:remove-double-quotes-p t))
(with-host-environment ()
(if *compiler-compile-eval-whens*
(funcall (compile () `(lambda () ,toplevel-form)))
(eval toplevel-form)))))))))
(define-special-operator function (&funobj funobj &form form &result-mode result-mode &env env)
(destructuring-bind (name)
(cdr form)
(flet ((function-of-symbol (name)
"Look up name in the local function namespace."
(let ((movitz-name (movitz-read name))
(register (case result-mode
((:ebx :ecx :edx) result-mode)
(t :eax))))
(compiler-values ()
:code `((:load-constant ,movitz-name ,register)
(:movl (,register ,(binary-types:slot-offset 'movitz-symbol 'function-value))
,register)
(:globally (:cmpl (:edi (:edi-offset unbound-function))
,register))
(:je '(:sub-program ()
(:load-constant ,movitz-name :edx)
(:int 98))))
:modifies nil
:functional-p t
:type 'function
:returns register))))
(etypecase name
(null (error "Can't compile (function nil)."))
(symbol
(multiple-value-bind (binding)
(movitz-operator-binding name env)
(etypecase binding
(null ; not lexically bound..
(function-of-symbol name))
(function-binding
(compiler-values ()
:code (make-compiled-lexical-load binding result-mode)
:type 'function
:returns result-mode
:functional-p t))
#+ignore
(funobj-binding
(let ((flet-funobj (funobj-binding-funobj binding)))
(assert (null (movitz-funobj-borrowed-bindings flet-funobj)))
(compiler-call #'compile-self-evaluating ; <name> is lexically fbound..
:env env
:funobj funobj
:result-mode result-mode
:form flet-funobj)))
#+ignore
((or closure-binding borrowed-binding)
(compiler-values ()
:code (make-compiled-lexical-load binding binding-env result-mode)
:type 'function
:returns result-mode
:functional-p t)))))
((cons (eql muerte.cl:setf))
(function-of-symbol (movitz-env-setf-operator-name
(muerte::translate-program (second name)
:cl :muerte.cl))))
((cons (eql muerte.cl:lambda))
(multiple-value-bind (lambda-forms lambda-declarations)
(parse-docstring-declarations-and-body (cddr name))
(let ((lambda-funobj
(make-compiled-funobj-pass1 '(muerte.cl:lambda)
(cadr name)
lambda-declarations
`(muerte.cl:progn ,@lambda-forms)
env nil)))
(let ((lambda-binding (make-instance 'lambda-binding
:name (gensym "anonymous-lambda-")
:parent-funobj funobj
:funobj lambda-funobj)))
(movitz-env-add-binding (find-function-env env funobj) lambda-binding)
(let ((lambda-result-mode (accept-register-mode result-mode)))
(compiler-values ()
:type 'function
:functional-p t
:returns lambda-result-mode
:modifies nil
:code `((:load-lambda ,lambda-binding ,lambda-result-mode ,env))))))))))))
(define-special-operator flet (&all forward &form form &env env &funobj funobj)
(destructuring-bind (flet-specs &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let* ((flet-env (make-local-movitz-environment env funobj
:type 'operator-env
:declarations declarations))
(init-code
(loop for (flet-name flet-lambda-list . flet-dd-body) in flet-specs
as flet-binding =
(multiple-value-bind (flet-body flet-declarations flet-docstring)
(parse-docstring-declarations-and-body flet-dd-body)
(declare (ignore flet-docstring))
(let ((flet-funobj
(make-compiled-funobj-pass1 (list 'muerte.cl::flet
(movitz-funobj-name funobj)
flet-name)
flet-lambda-list
flet-declarations
(list* 'muerte.cl:block
(compute-function-block-name flet-name)
flet-body)
env nil)))
(when (find-if (lambda (declaration)
(and (eq 'muerte.cl:dynamic-extent (car declaration))
(member `(muerte.cl:function ,flet-name)
(cdr declaration)
:test #'equal)))
declarations)
(setf (movitz-funobj-extent flet-funobj) :dynamic-extent)
(warn "dynamic-extent flet: ~S" flet-name))
(make-instance 'function-binding
:name flet-name
:parent-funobj funobj
:funobj flet-funobj)))
do (movitz-env-add-binding flet-env flet-binding)
collect `(:local-function-init ,flet-binding))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env flet-env)
(compiler-values (body-values)
:code (append init-code body-code)))))))
(define-special-operator progv (&all all &form form &funobj funobj &env env &result-mode result-mode)
(destructuring-bind (symbols-form values-form &body body)
(cdr form)
(compiler-values-bind (&code body-code &returns body-returns)
(let ((body-env (make-instance 'progv-env
:uplink env
:funobj funobj
:stack-used t
:num-specials t)))
;; amount of stack used and num-specials is not known until run-time.
(compiler-call #'compile-implicit-progn
:env body-env
:result-mode (case result-mode
(:push :eax)
(:function :multiple-values)
(t result-mode))
:form body
:forward all))
(compiler-values ()
:returns (if (eq :push body-returns) :eax body-returns)
:code (append (make-compiled-two-forms-into-registers symbols-form :ebx
values-form :eax
funobj env)
(with-labels (progv (no-more-symbols no-more-values loop zero-specials))
`((:xorl :ecx :ecx) ; count number of bindings (fixnum)
(:locally (:pushl (:edi (:edi-offset dynamic-env)))) ; first tail
(:cmpl :edi :ebx)
(:je '(:sub-program (,zero-specials)
;; Insert dummy binding
(:pushl :edi) ; biding value
(:pushl :edi) ; scratch
(:pushl :edi) ; binding name
(:pushl :esp)
(:addl 4 :ecx)
(:jmp ',no-more-symbols)))
,loop
(:cmpl :edi :ebx) ; (endp symbols)
(:je ',no-more-symbols) ; .. (go no-more-symbols)
(:globally (:movl (:edi (:edi-offset new-unbound-value)) :edx))
(:cmpl :edi :eax) ; (endp values)
(:je ',no-more-values) ; .. (go no-more-values)
(:movl (:eax -1) :edx)
(:movl (:eax 3) :eax) ; (pop values)
,no-more-values
(:pushl :edx) ; push (car values) [[ binding value ]]
(:pushl :edi) ; push binding scratch
(:pushl (:ebx -1)) ; push (car symbols) [[ binding name ]]
(:movl (:ebx 3) :ebx) ; (pop symbols)
(:addl 4 :ecx)
(:pushl :esp) ; push next tail
(:jmp ',loop)
,no-more-symbols
(:popl :eax) ; remove extra pre-pushed tail
(:movl :ecx :edx)
(:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-install))))
(:locally (:movl :esp (:edi (:edi-offset dynamic-env)))) ; install env
;; ecx = N/fixnum
(: shll 4 : ecx ) ; ecx = 16*N
(: (: esp : ecx -4 ) : eax ) ; eax = esp + 16*N - 4
(:pushl :edx) ; Save number of bindings.
push address of first binding 's tail
body-code
(when (eq body-returns :push)
`((:popl :eax))) ; glue :push => :eax
`((:movl (:esp) :edx) ; number of bindings
(:movl (:esp (:edx 4)) :edx) ; previous dynamic-env
(:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-uninstall))))
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:popl :edx) ; number of bindings
(:leal (:esp (:edx 4)) :esp)))))))
(define-special-operator labels (&all forward &form form &env env &funobj funobj)
(destructuring-bind (labels-specs &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let* ((labels-env (make-local-movitz-environment env funobj
:type 'operator-env
:declarations declarations))
(labels-bindings
(loop for (labels-name) in labels-specs
do (check-type labels-name symbol)
collecting
(movitz-env-add-binding labels-env (make-instance 'function-binding
:name labels-name
:funobj (make-instance 'movitz-funobj-pass1)
:parent-funobj funobj))))
(init-code
(loop for (labels-name labels-lambda-list . labels-dd-body) in labels-specs
as labels-binding in labels-bindings
do (multiple-value-bind (labels-body labels-declarations labels-docstring)
(parse-docstring-declarations-and-body labels-dd-body)
(declare (ignore labels-docstring))
(make-compiled-funobj-pass1 (list 'muerte.cl::labels
(movitz-funobj-name funobj)
labels-name)
labels-lambda-list
labels-declarations
(list* 'muerte.cl:block
(compute-function-block-name labels-name)
labels-body)
labels-env nil
:funobj (function-binding-funobj labels-binding)))
collect `(:local-function-init ,labels-binding))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env labels-env)
(compiler-values (body-values)
:code (append init-code body-code)))))))
(define-special-operator catch (&all forward &form form &funobj funobj &env env)
(destructuring-bind (tag &rest forms)
(cdr form)
(let ((catch-env (make-instance 'simple-dynamic-env :uplink env :funobj funobj)))
(compiler-values-bind (&all body-values &code body-code &returns body-returns)
(compiler-call #'compile-form
:env catch-env
:result-mode :multiple-values
:defaults forward
:form `(muerte.cl:progn ,@forms))
(multiple-value-bind (stack-used code)
(make-compiled-catch-wrapper tag funobj env body-returns body-code)
(incf (stack-used catch-env) stack-used)
(compiler-values (body-values)
:returns body-returns
:type '(values &rest t)
:code code))))))
(defun make-compiled-catch-wrapper (tag-form funobj env body-returns body-code)
(assert (member body-returns '(:multiple-values :non-local-exit)))
(values 4 ; stack-used, must be added to body-code's env.
(with-labels (catch (label-set exit-point))
(append `((:declare-label-set ,label-set (,exit-point))
(:locally (:pushl (:edi (:edi-offset dynamic-env)))) ; push dynamic-env
(:pushl ',label-set))
(compiler-call #'compile-form
:env env
:with-stack-used 2
:funobj funobj
:form tag-form
:result-mode :push)
`((:pushl :ebp) ; push stack frame
(:locally (:movl :esp (:edi (:edi-offset dynamic-env))))) ; install catch
body-code
`(,exit-point
(:movl (:esp) :ebp)
(:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp)
)))))
(define-special-operator unwind-protect (&all all &form form &env env)
(destructuring-bind (protected-form &body cleanup-forms)
(cdr form)
(if (null cleanup-forms)
(compiler-call #'compile-form-unprotected
:forward all
:form protected-form)
(let* ((continuation-env (make-instance 'let-env
:uplink env
:funobj (movitz-environment-funobj env)))
(next-continuation-step-binding
(movitz-env-add-binding continuation-env
(make-instance 'located-binding
:name (gensym "up-next-continuation-step-"))))
(unwind-protect-env (make-instance 'unwind-protect-env
:cleanup-form (cons 'muerte.cl:progn cleanup-forms)
:uplink continuation-env
:funobj (movitz-environment-funobj env))))
(with-labels (unwind-protect (cleanup-label cleanup-entry continue continue-label))
(compiler-values ()
:returns :multiple-values
:code (append
;; install default continuation dynamic-env..
`((:locally (:pushl (:edi (:edi-offset dynamic-env))))
(:declare-label-set ,cleanup-label (,cleanup-entry))
(:declare-label-set ,continue-label (,continue))
(:pushl ',cleanup-label) ; jumper index
(:globally (:pushl (:edi (:edi-offset unwind-protect-tag)))) ; tag
(:pushl :ebp) ; stack-frame
(:locally (:movl :esp (:edi (:edi-offset dynamic-env))))) ; install up-env
;; Execute protected form..
(compiler-call #'compile-form
:env unwind-protect-env
:with-stack-used t ;; XXX Not really true, is it?
:forward all
:result-mode :multiple-values
:form protected-form)
;; From now on, take care not to touch current-values from protected-form.
`((:locally (:movl :esp (:edi (:edi-offset raw-scratch0))))
,cleanup-entry
First , restore stack - frame in EBP
(:movl (:esp) :ebp)
;; Now, modify unwind-protect dyn-env-entry to be normal continuation
(:locally (:movl (:edi (:edi-offset unbound-function)) :edx))
(:movl :edx (:esp 4)) ; not unwind-protect-tag
(:movl ',continue-label (:esp 8)) ; new jumper index
(:locally (:pushl (:edi (:edi-offset raw-scratch0))))) ; push final-continuation
;; Execute cleanup-forms.
(compiler-call #'compile-form-unprotected
:forward all
:env continuation-env
:with-stack-used t
:result-mode :multiple-values
:form `(muerte::with-cloak (:multiple-values)
;; Inside here we don't have to mind current-values.
(muerte::with-inline-assembly (:returns :nothing)
First , save final - continuation across cleanup - forms .
(:locally (:pushl (:edi (:edi-offset raw-scratch0)))))
,@cleanup-forms
(muerte::with-inline-assembly (:returns :nothing)
;; Now, find next-continuation-step..
(:popl :eax) ; final-continuation
(:locally (:call (:edi (:edi-offset dynamic-unwind-next))))
(:locally (:bound (:edi (:edi-offset stack-bottom)) :eax))
(:store-lexical ,next-continuation-step-binding :eax :type t))))
`((:locally (:popl (:edi (:edi-offset raw-scratch0)))) ; pop final continuation
(:load-lexical ,next-continuation-step-binding :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:locally (:call (:edi (:edi-offset dynamic-jump-next))))
,continue
(:movl (:esp) :ebp)
(:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp)))))))))
(define-special-operator if (&all all &form form &env env &result-mode result-mode)
(destructuring-bind (test-form then-form &optional else-form)
(cdr form)
(compiler-values-bind (&all then)
(compiler-call #'compile-form-unprotected
:forward all
:form then-form)
(compiler-values-bind (&all else)
(compiler-call #'compile-form-unprotected
:forward all
:form else-form)
#+ignore (warn "p1: ~S/~S/~S, p2: ~S/~S/~S"
(then :producer) (then :final-form) (then :modifies)
(else :producer) (else :final-form) (else :modifies))
(cond
((and (eq result-mode :ignore)
(then :functional-p)
(else :functional-p))
(compiler-call #'compile-form-unprotected
:forward all
:form test-form))
#+ignore
((and (valid-finals (then :final-form) (else :final-form))
(equal (then :final-form) (else :final-form)))
(warn "if's then and else are equal: ~S both were ~S." form (then :final-form))
(compiler-call #'compile-form-unprotected
:forward all
:form `(muerte.cl:progn ,test-form ,then-form)))
;; ((
#+ignore
((and (typep (then :final-form) 'movitz-immediate-object)
(typep (else :final-form) 'movitz-immediate-object))
(let ((then-value (movitz-immediate-value (then :final-form)))
(else-value (movitz-immediate-value (else :final-form)))
(true-label (gensym "if-true-")))
(warn "immediate if: ~S vs. ~S"
then-value else-value)
(compiler-values-bind (&all test)
(compiler-call #'compile-form
:forward all
:form test-form
:result-mode (cons :boolean-branch-on-true true-label))
(compiler-values (test)
:code (append (test :code)
(make-immediate-move then-value :eax)
(make-immediate-move else-value :eax)
(list true-label))
:returns :eax))))
(t (compiler-call #'compile-form-unprotected
:forward all
:form `(muerte::compiled-cond
(,test-form ,then-form)
(muerte.cl::t ,else-form)))))))))
(define-special-operator the (&all all &form form)
(destructuring-bind (value-type sub-form)
(cdr form)
(compiler-values-bind (&all sub-form)
(compiler-call #'compile-form-unprotected
:forward all
:form sub-form)
(compiler-values (sub-form)
:type value-type))))
| null | https://raw.githubusercontent.com/PuercoPop/Movitz/7ffc41896c1e054aa43f44d64bbe9eaf3fcfa777/special-operators-cl.lisp | lisp | ------------------------------------------------------------------
Filename: special-operators-cl.lisp
Description: Special operators in the COMMON-LISP package.
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
first special? .. binding tail
binding value
scratch
binding name
lexical...
(warn "var ~S, type: ~S" var type)
(warn "bind: ~S reg: ~S" binding init-register)
(print-code 'init init-code)
(print-code 'body body)
(print-code 'body-code body-code)
Is this (let ((#:foo <form>)) (setq bar #:foo)) ?
If so, make it into (setq bar <form>)
same binding?
same register?
for bb in binding-var-codes
do (warn "bind: ~S" bb)
This is the best we can do now to determine
if target-binding is ever used again.
replace read-only binding with the outer binding
replace read-only lexical binding with
side-effect-free form
only inject code if it's got side-effects.
(warn "for ~S ~S ~S" binding init-register final-form)
:with-stack-used t
marker, used below
(:store-lexical ,numargs-binding :ecx :type t)
CF=0 means arg-count=1
:ignore
(warn "sub-returns: ~S" sub-returns)
Tagbody tags are "compiled" into..
..their assembly-level labels.
catcher
A well-known number of dynamic-slots?
any unwind-protects between here and there?
Perform a lexical "throw" to the tag. Just like a regular (dynamic) throw.
The target jumper points to the tagbody's label-set.
Now, install correct jumper within tagbody as target.
final continuation
new dynamic-env
exit to next - env
enter non - local jump stack mode .
target stack - frame EBP
get target funobj into ESI
target jumper number
must restore stack
catcher
wrapped-code
not lexically bound..
<name> is lexically fbound..
amount of stack used and num-specials is not known until run-time.
count number of bindings (fixnum)
first tail
Insert dummy binding
biding value
scratch
binding name
(endp symbols)
.. (go no-more-symbols)
(endp values)
.. (go no-more-values)
(pop values)
push (car values) [[ binding value ]]
push binding scratch
push (car symbols) [[ binding name ]]
(pop symbols)
push next tail
remove extra pre-pushed tail
install env
ecx = N/fixnum
ecx = 16*N
eax = esp + 16*N - 4
Save number of bindings.
glue :push => :eax
number of bindings
previous dynamic-env
number of bindings
stack-used, must be added to body-code's env.
push dynamic-env
push stack frame
install catch
install default continuation dynamic-env..
jumper index
tag
stack-frame
install up-env
Execute protected form..
XXX Not really true, is it?
From now on, take care not to touch current-values from protected-form.
Now, modify unwind-protect dyn-env-entry to be normal continuation
not unwind-protect-tag
new jumper index
push final-continuation
Execute cleanup-forms.
Inside here we don't have to mind current-values.
Now, find next-continuation-step..
final-continuation
pop final continuation
(( | Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
Author : < >
Created at : Fri Nov 24 16:31:11 2000
$ I d : special - operators - cl.lisp , v 1.55 2008 - 07 - 09 19:57:02 Exp $
(in-package movitz)
(define-special-operator progn (&all all &form form &top-level-p top-level-p &result-mode result-mode)
(compiler-call #'compile-implicit-progn
:form (cdr form)
:forward all))
(defun expand-to-operator (operator form env)
"Attempt to compiler-macroexpand FORM to having operator OPERATOR."
(if (and (listp form) (eq operator (first form)))
form
(multiple-value-bind (expansion expanded-p)
(like-compile-macroexpand-form form env)
(if expanded-p
(expand-to-operator operator expansion env)
nil))))
(defun parse-let-var-specs (let-var-specs)
"Given a list of LET variable specifiers (i.e. either VAR or (VAR INIT-FORM)),~
return a list on the canonical form (VAR INIT-FORM)."
(loop for var-spec in let-var-specs
if (symbolp var-spec)
collect `(,var-spec nil)
else if (and (listp var-spec)
(= 1 (length var-spec)))
collect `(,(first var-spec) nil)
else do (assert (and (listp var-spec)
(= 2 (length var-spec))))
and collect var-spec))
(define-special-operator let (&all all &form form &funobj funobj &env env &result-mode result-mode)
"An extent-nested let is this: (let ((foo ..) (bar (.. (let ((zot ..)) ..)))))
where zot is not in foo's scope, but _is_ in foo's extent."
(destructuring-bind (operator let-var-specs &body forms)
form
(declare (ignore operator))
(multiple-value-bind (body declarations)
(parse-declarations-and-body forms)
(if (and (null let-var-specs)
(null declarations))
(compiler-call #'compile-implicit-progn
:forward all
:form body)
(let* ((let-modifies nil)
(let-vars (parse-let-var-specs let-var-specs))
(local-env (make-local-movitz-environment env funobj
:type 'let-env
:declarations declarations))
(init-env #+ignore env
(make-instance 'movitz-environment
:uplink env
:funobj funobj
:extent-uplink local-env))
(stack-used 0)
(binding-var-codes
(loop for (var init-form) in let-vars
if (movitz-env-get var 'special nil local-env)
special ... see losp / cl / run - time.lisp
collect
(list var
init-form
`((:locally (:pushl (:edi (:edi-offset dynamic-env)))))
`((:pushl :esp)))
:with-stack-used (incf stack-used)
:env init-env
:defaults all
:form init-form
:modify-accumulate let-modifies
:result-mode :push)
:with-stack-used (incf stack-used 2)
:env init-env
:defaults all
:form `(muerte.cl:quote ,var)
:result-mode :push)
(prog1 nil (incf stack-used)))
nil t)
and do (movitz-env-add-binding local-env (make-instance 'dynamic-binding
:name var))
and do (incf (num-specials local-env))
else collect
(let ((binding (make-instance 'located-binding :name var)))
(movitz-env-add-binding local-env binding)
(compiler-values-bind (&code init-code &functional-p functional-p
&type type &returns init-register
&final-form final-form)
(compiler-call #'compile-form-unprotected
:result-mode binding
:env init-env
:extent local-env
:defaults all
:form init-form)
#+ignore
(compiler-call #'compile-form-to-register
:env init-env
:extent local-env
:defaults all
:form init-form
:modify-accumulate let-modifies)
(when (eq binding init-register)
(setf init-register nil))
( warn " var ~S init : ~S .. " var init - form )
(list var
init-form
init-code
functional-p
(let ((init-type (type-specifier-primary type)))
(assert init-type ()
"The init-form ~S yielded the empty primary type!" type)
init-type)
(case init-register
(:non-local-exit :edi)
(:multiple-values :eax)
(t init-register))
final-form))))))
(setf (stack-used local-env) stack-used)
(flet ((compile-body ()
(if (= 0 (num-specials local-env))
(compiler-call #'compile-implicit-progn
:defaults all
:form body
:env local-env)
(compiler-call #'compile-form
:result-mode (case result-mode
(:push :eax)
(:function :multiple-values)
(t result-mode))
:defaults all
:form `(muerte.cl:progn ,@body)
:modify-accumulate let-modifies
:env local-env))))
(compiler-values-bind (&all body-values &code body-code &returns body-returns)
(compile-body)
(let ((first-binding (movitz-binding (caar binding-var-codes) local-env nil)))
(cond
((and (= 1 (length binding-var-codes))
(typep first-binding 'lexical-binding)
(instruction-is (first body-code) :load-lexical)
(instruction-is (second body-code) :store-lexical)
(null (cddr body-code))
(second (first body-code)))
(third (second body-code))))
(let ((dest-binding (second (second body-code))))
(check-type dest-binding lexical-binding)
(compiler-call #'compile-form
:forward all
:extent local-env
:result-mode dest-binding
:form (second (first binding-var-codes)))))
#+ignore
((and (= 1 (length binding-var-codes))
(typep (movitz-binding (caar binding-var-codes) local-env nil)
'lexical-binding)
(member (movitz-binding (caar binding-var-codes) local-env nil)
(find-read-bindings (first body-code)))
(not (code-uses-binding-p (rest body-code) (second (first body-code))
:load t :store nil)))
(let ((tmp-binding (second (first body-code))))
(print-code 'body body-code)
(break "Yuhu: tmp ~S" tmp-binding)
))
(t (let ((code
(append
(loop
for ((var init-form init-code functional-p type init-register
final-form)
. rest-codes)
on binding-var-codes
as binding = (movitz-binding var local-env nil)
do (assert type)
(assert (not (binding-lended-p binding)))
appending
(cond
((and (typep binding 'located-binding)
(not (binding-lended-p binding))
(typep final-form 'lexical-binding)
(let ((target-binding final-form))
(and (typep target-binding 'lexical-binding)
(eq (binding-funobj binding)
(binding-funobj target-binding))
#+ignore
(sub-env-p (binding-env binding)
(binding-env target-binding))
(or (and (not (code-uses-binding-p body-code
binding
:load nil
:store t))
(not (code-uses-binding-p body-code
target-binding
:load nil
:store t)))
(and (= 1 (length body-code))
(eq :add (caar body-code)))
(and (>= 1 (length body-code))
(warn "short let body: ~S" body-code))
(and (eq result-mode :function)
(not (and (bindingp body-returns)
(binding-eql target-binding
body-returns)))
(not (code-uses-binding-p body-code
target-binding
:load t
:store t))
(notany (lambda (code)
(code-uses-binding-p (third code)
target-binding
:load t
:store t))
rest-codes))))))
(compiler-values-bind (&code new-init-code &final-form target
&type type)
(compiler-call #'compile-form-unprotected
:extent local-env
:form init-form
:result-mode :ignore
:env init-env
:defaults all)
(check-type target lexical-binding)
(change-class binding 'forwarding-binding
:target-binding target)
(let ((btype (if (multiple-value-call #'encoded-allp
(type-specifier-encode
(type-specifier-primary type)))
target
(type-specifier-primary type))))
#+ignore (warn "forwarding ~S -[~S]> ~S"
binding btype target)
(append new-init-code
`((:init-lexvar
,binding
:init-with-register ,target
:init-with-type ,btype))))))
((and (typep binding 'located-binding)
(type-specifier-singleton type)
(not (code-uses-binding-p body-code binding
:load nil :store t)))
#+ignore
(warn "Constant binding: ~S => ~S => ~S"
(binding-name binding)
init-form
(car (type-specifier-singleton type)))
(change-class binding 'constant-object-binding
:object (car (type-specifier-singleton type)))
(if functional-p
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies)))
((typep binding 'lexical-binding)
(let ((init (type-specifier-singleton
(type-specifier-primary type))))
(cond
((and init (eq *movitz-nil* (car init)))
(append (if functional-p
nil
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies))
`((:init-lexvar ,binding
:init-with-register :edi
:init-with-type null))))
((and (typep final-form 'lexical-binding)
(eq (binding-funobj final-form)
funobj))
(compiler-values-bind (&code new-init-code
&type new-type
&final-form new-binding)
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies)
(append (if functional-p
nil
new-init-code)
(let ((ptype (type-specifier-primary new-type)))
`((:init-lexvar ,binding
:init-with-register ,new-binding
:init-with-type ,ptype
))))))
((typep final-form 'constant-object-binding)
#+ignore
(warn "type: ~S or ~S" final-form
(type-specifier-primary type))
(append (if functional-p
nil
(compiler-call #'compile-form-unprotected
:extent local-env
:env init-env
:defaults all
:form init-form
:result-mode :ignore
:modify-accumulate let-modifies))
`((:init-lexvar
,binding
:init-with-register ,final-form
:init-with-type ,(type-specifier-primary type)
))))
(append init-code
`((:init-lexvar
,binding
:init-with-register ,init-register
:init-with-type ,(type-specifier-primary type))))))))
(t init-code)))
(when (plusp (num-specials local-env))
`((:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-install))))
(:locally (:movl :esp (:edi (:edi-offset dynamic-env))))))
body-code
(when (and (plusp (num-specials local-env))
(not (eq :non-local-exit body-returns)))
#+ignore
(warn "let spec ret: ~S, want: ~S ~S"
body-returns result-mode let-var-specs)
`((:movl (:esp ,(+ -4 (* 16 (num-specials local-env)))) :edx)
(:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-uninstall))))
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp ,(* 16 (num-specials local-env))) :esp))))))
(compiler-values (body-values)
:returns body-returns
:producer (default-compiler-values-producer)
:functional-p (and (body-values :functional-p)
(every #'fourth binding-var-codes))
:modifies let-modifies
:code code))))))))))))
(define-special-operator symbol-macrolet (&all forward &form form &env env &funobj funobj)
(destructuring-bind (symbol-expansions &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let ((local-env (make-local-movitz-environment
env funobj
:type 'operator-env
:declarations declarations)))
(loop for symbol-expansion in symbol-expansions
do (destructuring-bind (symbol expansion)
symbol-expansion
(movitz-env-add-binding local-env (make-instance 'symbol-macro-binding
:name symbol
:expander #'(lambda (form env)
(declare (ignore form env))
expansion)))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env local-env
:top-level-p (forward :top-level-p))
(compiler-values (body-values)
:code body-code))))))
(define-special-operator macrolet (&all forward &form form &funobj funobj &env env)
(destructuring-bind (macrolet-specs &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let ((local-env (make-local-movitz-environment env funobj
:type 'operator-env
:declarations declarations)))
(loop for (name local-lambda-list . local-body-decl-doc) in macrolet-specs
as cl-local-lambda-list = (translate-program local-lambda-list :muerte.cl :cl)
as (local-body local-declarations) =
(multiple-value-list (parse-docstring-declarations-and-body local-body-decl-doc))
as cl-local-body = (translate-program local-body :muerte.cl :cl)
as cl-local-declarations = (translate-program local-declarations :muerte.cl :cl)
as expander = `(lambda (form env)
(declare (ignorable env))
(destructuring-bind ,cl-local-lambda-list
(translate-program (rest form) :muerte.cl :cl)
(declare ,@cl-local-declarations)
(translate-program (block ,name (let () ,@cl-local-body))
:cl :muerte.cl)))
do (movitz-env-add-binding
local-env
(make-instance 'macro-binding
:name name
:expander (movitz-macro-expander-make-function expander
:name name
:type :macrolet))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env local-env
:top-level-p (forward :top-level-p))
(compiler-values (body-values)
:code body-code))))))
(define-special-operator multiple-value-prog1 (&all all &form form &result-mode result-mode &env env)
(destructuring-bind (first-form &rest rest-forms)
(cdr form)
(compiler-values-bind (&code form1-code &returns form1-returns &type type)
(compiler-call #'compile-form-unprotected
:defaults all
:result-mode (case (result-mode-type result-mode)
((:boolean-branch-on-true :boolean-branch-on-false)
:eax)
(t result-mode))
:form first-form)
(compiler-call #'special-operator-with-cloak
:forward all
:form `(muerte::with-cloak (,form1-returns ,form1-code t ,type)
,@rest-forms)))))
(define-special-operator multiple-value-call (&all all &form form &funobj funobj)
(destructuring-bind (function-form &rest subforms)
(cdr form)
(let* ((local-env (make-instance 'let-env
:uplink (all :env)
:funobj funobj
:stack-used t))
(numargs-binding (movitz-env-add-binding local-env
(make-instance 'located-binding
:name (gensym "m-v-numargs-"))))
(arg-code (loop for subform in subforms
collecting
(compiler-values-bind (&code subform-code &returns subform-returns)
(compiler-call #'compile-form-unprotected
:defaults all
:env local-env
:form subform
:result-mode :multiple-values)
(case subform-returns
(:multiple-values
`(:multiple
,@subform-code
,@(make-compiled-push-current-values)
(:load-lexical ,numargs-binding :eax)
(:addl :ecx :eax)
(:store-lexical ,numargs-binding :eax :type fixnum)))
subform))))))
(number-of-multiple-value-subforms (count :multiple arg-code :key #'car))
(number-of-single-value-subforms (count :single arg-code :key #'car)))
(cond
((= 0 number-of-multiple-value-subforms)
(compiler-call #'compile-form
:forward all
:form `(muerte.cl::funcall ,function-form ,@subforms)))
(t (compiler-values ()
:returns :multiple-values
:code (append `((:load-constant ,(1+ number-of-single-value-subforms) :eax)
(:store-lexical ,numargs-binding :eax :type fixnum))
(compiler-call #'compile-form
:defaults all
:env local-env
:form function-form
:result-mode :push)
(loop for ac in arg-code
append (ecase (car ac)
(:single
(compiler-call #'compile-form
:defaults all
:env local-env
:form (second ac)
:result-mode :push))
(:multiple
(cdr ac))))
`((:load-lexical ,numargs-binding :ecx)
(:movl (:esp (:ecx 1) -4) :eax)
(:movl (:esp (:ecx 1) -8) :ebx)
(:shrl ,+movitz-fixnum-shift+ :ecx)
(:load-constant muerte.cl::funcall :edx)
(:movl (:edx ,(slot-offset 'movitz-symbol 'function-value))
load new funobj from symbol into ESI
(:call (:esi ,(slot-offset 'movitz-funobj 'code-vector)))
(:load-lexical ,numargs-binding :edx)
Use so as not to modify CF
(:leal (:esp :edx) :esp)))))))))
(define-special-operator multiple-value-bind (&all forward &form form &env env &funobj funobj
&result-mode result-mode)
(destructuring-bind (variables values-form &body body-and-declarations)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body body-and-declarations)
(compiler-values-bind (&code values-code &returns values-returns &type values-type)
(compiler-call #'compile-form
:defaults forward
:form values-form
:result-mode :multiple-values #+ignore (list :values (length variables)))
( warn " mv - code : ~W ~W = > ~W ~W " values - form ( list : values ( length variables ) ) values - returns ( last values - code 10 ) )
(let* ((local-env (make-local-movitz-environment
env funobj
:type 'let-env
:declarations declarations))
(lexical-bindings
(loop for variable in variables
as new-binding = (make-instance 'located-binding
:name variable)
do (check-type variable symbol)
collect new-binding
do (cond
((movitz-env-get variable 'special nil env)
(let* ((shadowed-variable (gensym (format nil "m-v-bind-shadowed-~A"
variable))))
(movitz-env-add-binding local-env new-binding shadowed-variable)
(push (list variable shadowed-variable)
(special-variable-shadows local-env))))
(t (movitz-env-add-binding local-env new-binding)))))
(init-var-code
(case (first (operands values-returns))
(t (append
(make-result-and-returns-glue :multiple-values values-returns)
(case (length lexical-bindings)
(0 nil)
(1 `((:init-lexvar ,(first lexical-bindings)
:protect-carry nil
:protect-registers '(:eax))
(:store-lexical ,(first lexical-bindings) :eax
:type ,(type-specifier-primary values-type))))
(2 (let ((done-label (gensym "m-v-bind-done-")))
`((:init-lexvar ,(first lexical-bindings)
:protect-carry t
:protect-registers (:eax :ebx))
(:store-lexical ,(first lexical-bindings) :eax
:type ,(type-specifier-primary values-type)
:protect-registers (:ebx))
(:init-lexvar ,(second lexical-bindings)
:protect-carry t
:protect-registers (:ebx))
(:store-lexical ,(second lexical-bindings) :edi
:type null)
(:jnc ',done-label)
(:cmpl 1 :ecx)
(:jbe ',done-label)
(:store-lexical ,(second lexical-bindings) :ebx
:type ,(type-specifier-nth-value 1 values-type))
,done-label)))
(t (with-labels (m-v-bind (ecx-ok-label))
`((:jc ',ecx-ok-label)
,ecx-ok-label
,@(loop for binding in lexical-bindings as pos upfrom 0
as skip-label = (gensym "m-v-bind-skip-")
as type = (type-specifier-nth-value pos values-type)
append
(case pos
(0 `((:init-lexvar ,binding
:protect-registers (:eax :ebx :ecx))
(:store-lexical ,binding :eax :type ,type
:protect-registers (:eax :ebx :ecx))))
(1 `((:init-lexvar ,binding
:protect-registers (:ebx :ecx))
(:store-lexical ,binding :edi :type null
:protect-registers (:ecx))
(:cmpl 1 :ecx)
(:jbe ',skip-label)
(:store-lexical ,binding :ebx :type ,type
:protect-registers (:ecx))
,skip-label))
(t (if *compiler-use-cmov-p*
`((:init-lexvar ,binding :protect-registers '(:ecx))
(:movl :edi :eax)
(:cmpl ,pos :ecx)
(:locally (:cmova (:edi (:edi-offset values
,(* 4 (- pos 2))))
:eax))
(:store-lexical ,binding :eax :type ,type
:protect-registers (:eax)))
`((:init-lexvar ,binding :protect-registers '(:ecx))
(:movl :edi :eax)
(:cmpl ,pos :ecx)
(:jbe ',skip-label)
(:locally (:movl (:edi (:edi-offset values
,(* 4 (- pos 2))))
:eax))
,skip-label
(:store-lexical ,binding :eax :type ,type
:protect-registers (:ecx))))))))))))))))
(compiler-values-bind (&code body-code &returns body-returns-mode)
(compiler-call #'compile-form-unprotected
:defaults forward
:form `(muerte.cl:let ,(special-variable-shadows local-env) ,@body)
:env local-env)
(compiler-values ()
:returns body-returns-mode
:code (append values-code
init-var-code
body-code))))))))
(define-special-operator setq (&all forward &form form &env env &funobj funobj &result-mode result-mode)
(let ((pairs (cdr form)))
(unless (evenp (length pairs))
(error "Odd list of SETQ pairs: ~S" pairs))
(let* ((last-returns :nothing)
(bindings ())
(code (loop
for (var value-form) on pairs by #'cddr
as binding = (movitz-binding var env)
as pos downfrom (- (length pairs) 2) by 2
as sub-result-mode = (if (zerop pos) result-mode :ignore)
do (pushnew binding bindings)
append
(typecase binding
(symbol-macro-binding
(compiler-values-bind (&code code &returns returns)
(compiler-call #'compile-form-unprotected
:defaults forward
:result-mode sub-result-mode
:form `(muerte.cl:setf ,var ,value-form))
(setf last-returns returns)
code))
(lexical-binding
(case (operator sub-result-mode)
( setf last - returns : nothing )
(compiler-values-bind (&code sub-code &returns sub-returns)
(compiler-call #'compile-form
:defaults forward
:form value-form
:result-mode binding)
(setf last-returns sub-returns)
sub-code))
#+ignore
(t (let ((register (accept-register-mode sub-result-mode)))
(compiler-values-bind (&code code &type type)
(compiler-call #'compile-form
:defaults forward
:form value-form
:result-mode register)
(setf last-returns register)
(append code
`((:store-lexical ,binding ,register
:type ,(type-specifier-primary type)))))))))
(t (unless (movitz-env-get var 'special nil env)
(warn "Assuming destination variable ~S with binding ~S is special."
var binding))
(setf last-returns :ebx)
(append (compiler-call #'compile-form
:defaults forward
:form value-form
:result-mode :ebx)
`((:load-constant ,var :eax)
(:locally (:call (:edi (:edi-offset dynamic-variable-store)))))))))))
(compiler-values ()
:code code
:returns last-returns
:functional-p nil))))
(define-special-operator tagbody (&all forward &funobj funobj &form form &env env)
(let* ((save-esp-variable (gensym "tagbody-save-esp"))
(lexical-catch-tag-variable (gensym "tagbody-lexical-catch-tag-"))
(label-set-name (gensym "label-set-"))
(tagbody-env (make-instance 'tagbody-env
:uplink env
:funobj funobj
:save-esp-variable save-esp-variable
:lexical-catch-tag-variable lexical-catch-tag-variable
:exit-result-mode :ignore))
(save-esp-binding (make-instance 'located-binding
:name save-esp-variable))
(lexical-catch-tag-binding (make-instance 'located-binding
:name lexical-catch-tag-variable)))
(movitz-env-add-binding tagbody-env save-esp-binding)
(movitz-env-add-binding tagbody-env lexical-catch-tag-binding)
(movitz-env-load-declarations `((muerte.cl::ignorable ,save-esp-variable ,lexical-catch-tag-variable))
tagbody-env nil)
First generate an assembly - level label for each tag .
(let* ((label-set (loop with label-id = 0
for tag-or-statement in (cdr form)
as label = (when (or (symbolp tag-or-statement)
(integerp tag-or-statement))
(gensym (format nil "go-tag-~A-" tag-or-statement)))
when label
do (setf (movitz-env-get tag-or-statement 'go-tag nil tagbody-env)
label)
(setf (movitz-env-get tag-or-statement 'go-tag-label-id nil tagbody-env)
(post-incf label-id))
and collect label))
(tagbody-codes
(loop for tag-or-statement in (cdr form)
collect (movitz-env-get tag-or-statement 'go-tag nil tagbody-env)
else collect
(compiler-call #'compile-form
:defaults forward
:form tag-or-statement
:env tagbody-env
:result-mode :ignore))))
(let* ((unlexical-target-p (some (lambda (code)
(when (listp code)
(code-uses-binding-p code save-esp-binding)))
tagbody-codes))
(maybe-store-esp-code
(when (or unlexical-target-p
(some (lambda (code)
(when (listp code)
(operators-present-in-code-p code '(:lexical-control-transfer) nil
:test (lambda (x)
(eq tagbody-env (fifth x))))))
tagbody-codes))
`((:init-lexvar ,save-esp-binding
:init-with-register :esp
:init-with-type t)))))
(if (not unlexical-target-p)
(compiler-values ()
:code (append maybe-store-esp-code
(loop for code in tagbody-codes
if (listp code)
append code
else append (list code)))
:returns :nothing)
(let ((code (append `((:declare-label-set ,label-set-name ,label-set)
(:locally (:pushl (:edi (:edi-offset dynamic-env))))
(:pushl ',label-set-name)
(:locally (:pushl (:edi (:edi-offset unbound-function))))
(:pushl :ebp)
(:locally (:movl :esp (:edi (:edi-offset dynamic-env)))))
maybe-store-esp-code
(loop for code in tagbody-codes
if (listp code)
append code
else append (list code '(:movl (:esp) :ebp)))
`((:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp))
)))
(setf (num-specials tagbody-env) 1
(stack-used tagbody-env) 4)
(compiler-values ()
:code code
:returns :nothing)))))))
(define-special-operator go (&all all &form form &env env &funobj funobj)
(destructuring-bind (operator tag)
form
(declare (ignore operator))
(multiple-value-bind (label tagbody-env)
(movitz-env-get tag 'go-tag nil env)
(assert (and label tagbody-env) ()
"Go-tag ~W is not visible." tag)
(multiple-value-bind (stack-distance num-dynamic-slots unwind-protects)
(stack-delta env tagbody-env)
(declare (ignore stack-distance))
(if (and (eq funobj (movitz-environment-funobj tagbody-env))
(not (eq t num-dynamic-slots))
(null unwind-protects))
(compiler-values ()
:returns :non-local-exit
:code `((:lexical-control-transfer nil :nothing ,env ,tagbody-env ,label)))
(let ((save-esp-binding (movitz-binding (save-esp-variable tagbody-env) env))
(label-id (movitz-env-get tag 'go-tag-label-id nil tagbody-env nil)))
(assert label-id)
(compiler-values ()
:returns :non-local-exit
:code `((:load-lexical ,save-esp-binding :edx)
(:movl :edx :eax)
,@(when (plusp label-id)
`((:addl ,(* 4 label-id) (:edx 8))))
(:locally (:call (:edi (:edi-offset dynamic-unwind-next))))
have next - continuation in EAX , final - continuation in EDX
(:movl :eax :edx)
(:clc)
(:locally (:call (:edi (:edi-offset dynamic-jump-next))))))))))))
(: jmp (: esi : edx , ( slot - offset ' movitz - funobj ' ) ) ) ) ) ) ) ) ) ) )
(define-special-operator block (&all forward &funobj funobj &form form &env env
&result-mode result-mode)
(destructuring-bind (block-name &body body)
(cdr form)
(let* ((exit-block-label (gensym (format nil "exit-block-~A-" block-name)))
(save-esp-variable (gensym (format nil "block-~A-save-esp-" block-name)))
(lexical-catch-tag-variable (gensym (format nil "block-~A-lexical-catch-tag-" block-name)))
(block-result-mode (case result-mode
((:eax :eax :multiple-values :function :ebx :ecx :ignore)
result-mode)
(t :eax)))
(block-returns-mode (case (result-mode-type block-result-mode)
(:function :multiple-values)
(:ignore :nothing)
((:boolean-branch-on-true :boolean-branch-on-false) :eax)
(t block-result-mode)))
(block-env (make-instance 'lexical-exit-point-env
:uplink env
:funobj funobj
:save-esp-variable save-esp-variable
:lexical-catch-tag-variable lexical-catch-tag-variable
:exit-label exit-block-label
:exit-result-mode block-result-mode))
(save-esp-binding (make-instance 'located-binding
:name save-esp-variable)))
(movitz-env-add-binding block-env save-esp-binding)
(movitz-env-load-declarations `((muerte.cl::ignorable ,save-esp-variable))
block-env nil)
(setf (movitz-env-get block-name :block-name nil block-env)
block-env)
(compiler-values-bind (&code block-code &functional-p block-no-side-effects-p)
(compiler-call #'compile-form
:defaults forward
:result-mode (case block-result-mode
(t block-result-mode))
:form `(muerte.cl:progn ,@body)
:env block-env)
(let ((label-set-name (gensym "block-label-set-"))
(maybe-store-esp-code
(when (and #+ignore (not (eq block-result-mode :function))
(operators-present-in-code-p block-code '(:lexical-control-transfer) nil
:test (lambda (x) (eq block-env (fifth x)))))
`((:init-lexvar ,save-esp-binding
:init-with-register :esp
:init-with-type t)))))
(if (not (code-uses-binding-p block-code save-esp-binding))
(compiler-values ()
:code (append maybe-store-esp-code
block-code
(list exit-block-label))
:returns block-returns-mode
:functional-p block-no-side-effects-p)
(multiple-value-bind (new-code new-returns)
(make-result-and-returns-glue :multiple-values block-returns-mode block-code)
(assert (eq :multiple-values new-returns))
(incf (stack-used block-env) 4)
block - env now has one dynamic slot
(compiler-values ()
:code (append `((:declare-label-set ,label-set-name (,exit-block-label))
(:locally (:pushl (:edi (:edi-offset dynamic-env))))
(:pushl ',label-set-name)
(:locally (:pushl (:edi (:edi-offset unbound-function))))
(:pushl :ebp)
(:locally (:movl :esp (:edi (:edi-offset dynamic-env)))))
`((:init-lexvar ,save-esp-binding
:init-with-register :esp
:init-with-type t))
new-code
`(,exit-block-label
(:movl (:esp 0) :ebp)
(:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp)))
:returns :multiple-values
:functional-p block-no-side-effects-p))))))))
(define-special-operator return-from (&all all &form form &env env &funobj funobj)
(destructuring-bind (block-name &optional result-form)
(cdr form)
(let ((block-env (movitz-env-get block-name :block-name nil env)))
(assert block-env (block-name)
"Block-name not found for return-from: ~S." block-name)
(multiple-value-bind (stack-distance num-dynamic-slots unwind-protects)
(stack-delta env block-env)
(declare (ignore stack-distance))
(cond
((and (eq funobj (movitz-environment-funobj block-env))
(not (eq t num-dynamic-slots))
(null unwind-protects))
(compiler-values-bind (&code return-code &returns return-mode)
(compiler-call #'compile-form
:forward all
:form result-form
:result-mode (exit-result-mode block-env))
(compiler-values ()
:returns :non-local-exit
:code (append return-code
`((:lexical-control-transfer nil ,return-mode ,env ,block-env))))))
((not (and (eq funobj (movitz-environment-funobj block-env))
(not (eq t num-dynamic-slots))
(null unwind-protects)))
(compiler-call #'compile-form-unprotected
:forward all
:form `(muerte::exact-throw ,(save-esp-variable block-env)
,result-form))))))))
(define-special-operator require (&form form)
(let ((*require-dependency-chain*
(and (boundp '*require-dependency-chain*)
(symbol-value '*require-dependency-chain*))))
(declare (special *require-dependency-chain*))
(destructuring-bind (module-name &optional path-spec)
(cdr form)
(declare (ignore path-spec))
(push module-name *require-dependency-chain*)
(unless (member module-name (image-movitz-modules *image*))
(when (member module-name (cdr *require-dependency-chain*))
(error "Circular Movitz module dependency chain: ~S"
(reverse (subseq *require-dependency-chain* 0
(1+ (position module-name *require-dependency-chain* :start 1))))))
(let* ((require-path (movitz-module-path form)))
(movitz-compile-file-internal require-path)
(unless (member module-name (image-movitz-modules *image*))
(error "Compiling file ~S didn't provide module ~S."
require-path module-name))))))
(compiler-values ()))
(define-special-operator provide (&form form &funobj funobj &top-level-p top-level-p)
(unless top-level-p
(warn "Provide form not at top-level."))
(destructuring-bind (module-name &key load-priority)
(cdr form)
(declare (special *default-load-priority*))
(pushnew module-name (image-movitz-modules *image*))
(when load-priority
(setf *default-load-priority* load-priority))
(let ((new-priority *default-load-priority*))
(let ((old-tf (member module-name (image-load-time-funobjs *image*) :key #'second)))
(cond
((and new-priority old-tf)
(setf (car old-tf) (list funobj module-name new-priority)))
((and new-priority (not old-tf))
(push (list funobj module-name new-priority)
(image-load-time-funobjs *image*)))
(old-tf
(setf (car old-tf) (list funobj module-name (third (car old-tf)))))
(t (warn "No existing or provided load-time priority for module ~S, will not be loaded!"
module-name))))))
(compiler-values ()))
(define-special-operator eval-when (&all forward &form form &top-level-p top-level-p)
(destructuring-bind (situations &body body)
(cdr form)
(multiple-value-prog1
(if (or (member :execute situations)
(and (member :load-toplevel situations)
top-level-p))
(compiler-call #'compile-implicit-progn
:defaults forward
:top-level-p top-level-p
:form body)
(compiler-values ()))
(when (and (member :compile-toplevel situations)
top-level-p)
(with-compilation-unit ()
(dolist (toplevel-form (translate-program body :muerte.cl :cl
:when :eval
:remove-double-quotes-p t))
(with-host-environment ()
(if *compiler-compile-eval-whens*
(funcall (compile () `(lambda () ,toplevel-form)))
(eval toplevel-form)))))))))
(define-special-operator function (&funobj funobj &form form &result-mode result-mode &env env)
(destructuring-bind (name)
(cdr form)
(flet ((function-of-symbol (name)
"Look up name in the local function namespace."
(let ((movitz-name (movitz-read name))
(register (case result-mode
((:ebx :ecx :edx) result-mode)
(t :eax))))
(compiler-values ()
:code `((:load-constant ,movitz-name ,register)
(:movl (,register ,(binary-types:slot-offset 'movitz-symbol 'function-value))
,register)
(:globally (:cmpl (:edi (:edi-offset unbound-function))
,register))
(:je '(:sub-program ()
(:load-constant ,movitz-name :edx)
(:int 98))))
:modifies nil
:functional-p t
:type 'function
:returns register))))
(etypecase name
(null (error "Can't compile (function nil)."))
(symbol
(multiple-value-bind (binding)
(movitz-operator-binding name env)
(etypecase binding
(function-of-symbol name))
(function-binding
(compiler-values ()
:code (make-compiled-lexical-load binding result-mode)
:type 'function
:returns result-mode
:functional-p t))
#+ignore
(funobj-binding
(let ((flet-funobj (funobj-binding-funobj binding)))
(assert (null (movitz-funobj-borrowed-bindings flet-funobj)))
:env env
:funobj funobj
:result-mode result-mode
:form flet-funobj)))
#+ignore
((or closure-binding borrowed-binding)
(compiler-values ()
:code (make-compiled-lexical-load binding binding-env result-mode)
:type 'function
:returns result-mode
:functional-p t)))))
((cons (eql muerte.cl:setf))
(function-of-symbol (movitz-env-setf-operator-name
(muerte::translate-program (second name)
:cl :muerte.cl))))
((cons (eql muerte.cl:lambda))
(multiple-value-bind (lambda-forms lambda-declarations)
(parse-docstring-declarations-and-body (cddr name))
(let ((lambda-funobj
(make-compiled-funobj-pass1 '(muerte.cl:lambda)
(cadr name)
lambda-declarations
`(muerte.cl:progn ,@lambda-forms)
env nil)))
(let ((lambda-binding (make-instance 'lambda-binding
:name (gensym "anonymous-lambda-")
:parent-funobj funobj
:funobj lambda-funobj)))
(movitz-env-add-binding (find-function-env env funobj) lambda-binding)
(let ((lambda-result-mode (accept-register-mode result-mode)))
(compiler-values ()
:type 'function
:functional-p t
:returns lambda-result-mode
:modifies nil
:code `((:load-lambda ,lambda-binding ,lambda-result-mode ,env))))))))))))
(define-special-operator flet (&all forward &form form &env env &funobj funobj)
(destructuring-bind (flet-specs &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let* ((flet-env (make-local-movitz-environment env funobj
:type 'operator-env
:declarations declarations))
(init-code
(loop for (flet-name flet-lambda-list . flet-dd-body) in flet-specs
as flet-binding =
(multiple-value-bind (flet-body flet-declarations flet-docstring)
(parse-docstring-declarations-and-body flet-dd-body)
(declare (ignore flet-docstring))
(let ((flet-funobj
(make-compiled-funobj-pass1 (list 'muerte.cl::flet
(movitz-funobj-name funobj)
flet-name)
flet-lambda-list
flet-declarations
(list* 'muerte.cl:block
(compute-function-block-name flet-name)
flet-body)
env nil)))
(when (find-if (lambda (declaration)
(and (eq 'muerte.cl:dynamic-extent (car declaration))
(member `(muerte.cl:function ,flet-name)
(cdr declaration)
:test #'equal)))
declarations)
(setf (movitz-funobj-extent flet-funobj) :dynamic-extent)
(warn "dynamic-extent flet: ~S" flet-name))
(make-instance 'function-binding
:name flet-name
:parent-funobj funobj
:funobj flet-funobj)))
do (movitz-env-add-binding flet-env flet-binding)
collect `(:local-function-init ,flet-binding))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env flet-env)
(compiler-values (body-values)
:code (append init-code body-code)))))))
(define-special-operator progv (&all all &form form &funobj funobj &env env &result-mode result-mode)
(destructuring-bind (symbols-form values-form &body body)
(cdr form)
(compiler-values-bind (&code body-code &returns body-returns)
(let ((body-env (make-instance 'progv-env
:uplink env
:funobj funobj
:stack-used t
:num-specials t)))
(compiler-call #'compile-implicit-progn
:env body-env
:result-mode (case result-mode
(:push :eax)
(:function :multiple-values)
(t result-mode))
:form body
:forward all))
(compiler-values ()
:returns (if (eq :push body-returns) :eax body-returns)
:code (append (make-compiled-two-forms-into-registers symbols-form :ebx
values-form :eax
funobj env)
(with-labels (progv (no-more-symbols no-more-values loop zero-specials))
(:cmpl :edi :ebx)
(:je '(:sub-program (,zero-specials)
(:pushl :esp)
(:addl 4 :ecx)
(:jmp ',no-more-symbols)))
,loop
(:globally (:movl (:edi (:edi-offset new-unbound-value)) :edx))
(:movl (:eax -1) :edx)
,no-more-values
(:addl 4 :ecx)
(:jmp ',loop)
,no-more-symbols
(:movl :ecx :edx)
(:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-install))))
push address of first binding 's tail
body-code
(when (eq body-returns :push)
(:locally (:call (:edi ,(binary-types:slot-offset 'movitz-run-time-context
'dynamic-variable-uninstall))))
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp (:edx 4)) :esp)))))))
(define-special-operator labels (&all forward &form form &env env &funobj funobj)
(destructuring-bind (labels-specs &body declarations-and-body)
(cdr form)
(multiple-value-bind (body declarations)
(parse-declarations-and-body declarations-and-body)
(let* ((labels-env (make-local-movitz-environment env funobj
:type 'operator-env
:declarations declarations))
(labels-bindings
(loop for (labels-name) in labels-specs
do (check-type labels-name symbol)
collecting
(movitz-env-add-binding labels-env (make-instance 'function-binding
:name labels-name
:funobj (make-instance 'movitz-funobj-pass1)
:parent-funobj funobj))))
(init-code
(loop for (labels-name labels-lambda-list . labels-dd-body) in labels-specs
as labels-binding in labels-bindings
do (multiple-value-bind (labels-body labels-declarations labels-docstring)
(parse-docstring-declarations-and-body labels-dd-body)
(declare (ignore labels-docstring))
(make-compiled-funobj-pass1 (list 'muerte.cl::labels
(movitz-funobj-name funobj)
labels-name)
labels-lambda-list
labels-declarations
(list* 'muerte.cl:block
(compute-function-block-name labels-name)
labels-body)
labels-env nil
:funobj (function-binding-funobj labels-binding)))
collect `(:local-function-init ,labels-binding))))
(compiler-values-bind (&all body-values &code body-code)
(compiler-call #'compile-implicit-progn
:defaults forward
:form body
:env labels-env)
(compiler-values (body-values)
:code (append init-code body-code)))))))
(define-special-operator catch (&all forward &form form &funobj funobj &env env)
(destructuring-bind (tag &rest forms)
(cdr form)
(let ((catch-env (make-instance 'simple-dynamic-env :uplink env :funobj funobj)))
(compiler-values-bind (&all body-values &code body-code &returns body-returns)
(compiler-call #'compile-form
:env catch-env
:result-mode :multiple-values
:defaults forward
:form `(muerte.cl:progn ,@forms))
(multiple-value-bind (stack-used code)
(make-compiled-catch-wrapper tag funobj env body-returns body-code)
(incf (stack-used catch-env) stack-used)
(compiler-values (body-values)
:returns body-returns
:type '(values &rest t)
:code code))))))
(defun make-compiled-catch-wrapper (tag-form funobj env body-returns body-code)
(assert (member body-returns '(:multiple-values :non-local-exit)))
(with-labels (catch (label-set exit-point))
(append `((:declare-label-set ,label-set (,exit-point))
(:pushl ',label-set))
(compiler-call #'compile-form
:env env
:with-stack-used 2
:funobj funobj
:form tag-form
:result-mode :push)
body-code
`(,exit-point
(:movl (:esp) :ebp)
(:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp)
)))))
(define-special-operator unwind-protect (&all all &form form &env env)
(destructuring-bind (protected-form &body cleanup-forms)
(cdr form)
(if (null cleanup-forms)
(compiler-call #'compile-form-unprotected
:forward all
:form protected-form)
(let* ((continuation-env (make-instance 'let-env
:uplink env
:funobj (movitz-environment-funobj env)))
(next-continuation-step-binding
(movitz-env-add-binding continuation-env
(make-instance 'located-binding
:name (gensym "up-next-continuation-step-"))))
(unwind-protect-env (make-instance 'unwind-protect-env
:cleanup-form (cons 'muerte.cl:progn cleanup-forms)
:uplink continuation-env
:funobj (movitz-environment-funobj env))))
(with-labels (unwind-protect (cleanup-label cleanup-entry continue continue-label))
(compiler-values ()
:returns :multiple-values
:code (append
`((:locally (:pushl (:edi (:edi-offset dynamic-env))))
(:declare-label-set ,cleanup-label (,cleanup-entry))
(:declare-label-set ,continue-label (,continue))
(compiler-call #'compile-form
:env unwind-protect-env
:forward all
:result-mode :multiple-values
:form protected-form)
`((:locally (:movl :esp (:edi (:edi-offset raw-scratch0))))
,cleanup-entry
First , restore stack - frame in EBP
(:movl (:esp) :ebp)
(:locally (:movl (:edi (:edi-offset unbound-function)) :edx))
(compiler-call #'compile-form-unprotected
:forward all
:env continuation-env
:with-stack-used t
:result-mode :multiple-values
:form `(muerte::with-cloak (:multiple-values)
(muerte::with-inline-assembly (:returns :nothing)
First , save final - continuation across cleanup - forms .
(:locally (:pushl (:edi (:edi-offset raw-scratch0)))))
,@cleanup-forms
(muerte::with-inline-assembly (:returns :nothing)
(:locally (:call (:edi (:edi-offset dynamic-unwind-next))))
(:locally (:bound (:edi (:edi-offset stack-bottom)) :eax))
(:store-lexical ,next-continuation-step-binding :eax :type t))))
(:load-lexical ,next-continuation-step-binding :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:locally (:call (:edi (:edi-offset dynamic-jump-next))))
,continue
(:movl (:esp) :ebp)
(:movl (:esp 12) :edx)
(:locally (:movl :edx (:edi (:edi-offset dynamic-env))))
(:leal (:esp 16) :esp)))))))))
(define-special-operator if (&all all &form form &env env &result-mode result-mode)
(destructuring-bind (test-form then-form &optional else-form)
(cdr form)
(compiler-values-bind (&all then)
(compiler-call #'compile-form-unprotected
:forward all
:form then-form)
(compiler-values-bind (&all else)
(compiler-call #'compile-form-unprotected
:forward all
:form else-form)
#+ignore (warn "p1: ~S/~S/~S, p2: ~S/~S/~S"
(then :producer) (then :final-form) (then :modifies)
(else :producer) (else :final-form) (else :modifies))
(cond
((and (eq result-mode :ignore)
(then :functional-p)
(else :functional-p))
(compiler-call #'compile-form-unprotected
:forward all
:form test-form))
#+ignore
((and (valid-finals (then :final-form) (else :final-form))
(equal (then :final-form) (else :final-form)))
(warn "if's then and else are equal: ~S both were ~S." form (then :final-form))
(compiler-call #'compile-form-unprotected
:forward all
:form `(muerte.cl:progn ,test-form ,then-form)))
#+ignore
((and (typep (then :final-form) 'movitz-immediate-object)
(typep (else :final-form) 'movitz-immediate-object))
(let ((then-value (movitz-immediate-value (then :final-form)))
(else-value (movitz-immediate-value (else :final-form)))
(true-label (gensym "if-true-")))
(warn "immediate if: ~S vs. ~S"
then-value else-value)
(compiler-values-bind (&all test)
(compiler-call #'compile-form
:forward all
:form test-form
:result-mode (cons :boolean-branch-on-true true-label))
(compiler-values (test)
:code (append (test :code)
(make-immediate-move then-value :eax)
(make-immediate-move else-value :eax)
(list true-label))
:returns :eax))))
(t (compiler-call #'compile-form-unprotected
:forward all
:form `(muerte::compiled-cond
(,test-form ,then-form)
(muerte.cl::t ,else-form)))))))))
(define-special-operator the (&all all &form form)
(destructuring-bind (value-type sub-form)
(cdr form)
(compiler-values-bind (&all sub-form)
(compiler-call #'compile-form-unprotected
:forward all
:form sub-form)
(compiler-values (sub-form)
:type value-type))))
|
b22960ced858d27ff4e7991844e5047b8958fb06bc9a9c9fa506962a56646d84 | rvantonder/hack_parallel | hack_core_list.ml | module UnlabeledList = List
module List = StdLabels.List
module String = StdLabels.String
let invalid_argf = Hack_core_printf.invalid_argf
module T = struct
type 'a t = 'a list
end
include T
let of_list t = t
let range ?(stride=1) ?(start=`inclusive) ?(stop=`exclusive) start_i stop_i =
if stride = 0 then
invalid_arg "Core_list.range: stride must be non-zero";
(* Generate the range from the last element, so that we do not need to rev it *)
let rec loop last counter accum =
if counter <= 0 then accum
else loop (last - stride) (counter - 1) (last :: accum)
in
let stride_sign = if stride > 0 then 1 else -1 in
let start =
match start with
| `inclusive -> start_i
| `exclusive -> start_i + stride
in
let stop =
match stop with
| `inclusive -> stop_i + stride_sign
| `exclusive -> stop_i
in
let num_elts = (stop - start + stride - stride_sign) / stride in
loop (start + (stride * (num_elts - 1))) num_elts []
;;
(* Standard functions *)
let length = List.length
let hd_exn = List.hd
let tl_exn = List.tl
let hd t =
match t with
| [] -> None
| x :: _ -> Some x
;;
let tl t =
match t with
| [] -> None
| _ :: t' -> Some t'
;;
let nth t n =
if n < 0 then None else
let rec nth_aux t n =
match t with
| [] -> None
| a :: t -> if n = 0 then Some a else nth_aux t (n-1)
in nth_aux t n
;;
let nth_exn t n =
match nth t n with
| None ->
invalid_argf "List.nth_exn %d called on list of length %d"
n (length t) ()
| Some a -> a
;;
let rev_append = List.rev_append
let rev = function
| [] | [_] as res -> res
| x :: y :: rest -> rev_append rest [y; x]
let unordered_append l1 l2 =
match l1, l2 with
| [], l | l, [] -> l
| _ -> List.rev_append l1 l2
let rev_map t ~f = List.rev_map t ~f
exception Length_mismatch of string * int * int
let check_length2 name l1 l2 =
let n1 = length l1 in
let n2 = length l2 in
if n1 <> n2 then
raise (invalid_argf "length mismatch in %s: %d <> %d " name n1 n2 ())
;;
let check_length3 name l1 l2 l3 =
let n1 = length l1 in
let n2 = length l2 in
let n3 = length l3 in
if n1 <> n2 || n2 <> n3 then
raise (invalid_argf "length mismatch in %s: %d <> %d || %d <> %d"
name n1 n2 n2 n3 ())
;;
let iter2_exn l1 l2 ~f =
check_length2 "iter2_exn" l1 l2;
List.iter2 l1 l2 ~f;
;;
let rev_map2_exn l1 l2 ~f =
check_length2 "rev_map2_exn" l1 l2;
List.rev_map2 l1 l2 ~f;
;;
let fold2_exn l1 l2 ~init ~f =
check_length2 "fold2_exn" l1 l2;
List.fold_left2 l1 l2 ~init ~f;
;;
let for_all2_exn l1 l2 ~f =
check_length2 "for_all2_exn" l1 l2;
List.for_all2 l1 l2 ~f;
;;
let exists2_exn l1 l2 ~f =
check_length2 "exists2_exn" l1 l2;
List.exists2 l1 l2 ~f;
;;
let mem ?(equal = (=)) t a = List.exists t ~f:(equal a)
(* This is a copy of the standard library assq function. *)
let rec assq x = function
[] -> raise Not_found
| (a,b)::l -> if a == x then b else assq x l
This is a copy of the code from the standard library , with an extra eta - expansion to
avoid creating partial closures ( showed up for List.filter in profiling ) .
avoid creating partial closures (showed up for List.filter in profiling). *)
let rev_filter t ~f =
let rec find ~f accu = function
| [] -> accu
| x :: l -> if f x then find ~f (x :: accu) l else find ~f accu l
in
find ~f [] t
;;
let filter t ~f = rev (rev_filter t ~f)
let sort = List.sort
let stable_sort = List.stable_sort
let fast_sort = List.fast_sort
4.02 forgot to add sort_uniq to ListLabels , but it was added in 4.03 :
*)
let sort_uniq ~(cmp:'a -> 'a -> int) (lst:'a list) =
UnlabeledList.sort_uniq cmp lst
let find_map t ~f =
let rec loop = function
| [] -> None
| x :: l ->
match f x with
| None -> loop l
| Some _ as r -> r
in
loop t
;;
let find t ~f =
let rec loop = function
| [] -> None
| x :: l -> if f x then Some x else loop l
in
loop t
;;
let find_exn t ~f = List.find t ~f
let findi t ~f =
let rec loop i t =
match t with
| [] -> None
| x :: l -> if f i x then Some (i, x) else loop (i + 1) l
in
loop 0 t
;;
(** changing the order of arguments on some standard [List] functions. *)
let exists t ~f = List.exists t ~f
let for_all t ~f = List.for_all t ~f
let iter t ~f = List.iter t ~f
(** For the container interface. *)
let fold t ~init ~f = List.fold_left t ~f ~init
let fold_left = fold
let to_array = Hack_caml.Array.of_list
let to_list t = t
(** Tail recursive versions of standard [List] module *)
let slow_append l1 l2 = List.rev_append (List.rev l1) l2
There are a few optimized list operations here , including append and map . There are
basically two optimizations in play : loop unrolling , and dynamic switching between
stack and heap allocation .
The loop - unrolling is straightforward , we just unroll 5 levels of the loop . This makes
each iteration faster , and also reduces the number of stack frames consumed per list
element .
The dynamic switching is done by counting the number of stack frames , and then
switching to the " slow " implementation when we exceed a given limit . This means that
short lists use the fast stack - allocation method , and long lists use a slower one that
does n't require stack space .
basically two optimizations in play: loop unrolling, and dynamic switching between
stack and heap allocation.
The loop-unrolling is straightforward, we just unroll 5 levels of the loop. This makes
each iteration faster, and also reduces the number of stack frames consumed per list
element.
The dynamic switching is done by counting the number of stack frames, and then
switching to the "slow" implementation when we exceed a given limit. This means that
short lists use the fast stack-allocation method, and long lists use a slower one that
doesn't require stack space.
*)
let rec count_append l1 l2 count =
match l2 with
| [] -> l1
| _ ->
match l1 with
| [] -> l2
| [x1] -> x1 :: l2
| [x1; x2] -> x1 :: x2 :: l2
| [x1; x2; x3] -> x1 :: x2 :: x3 :: l2
| [x1; x2; x3; x4] -> x1 :: x2 :: x3 :: x4 :: l2
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
x1 :: x2 :: x3 :: x4 :: x5 ::
(if count > 1000
then slow_append tl l2
else count_append tl l2 (count + 1))
let append l1 l2 = count_append l1 l2 0
let map_slow l ~f = List.rev (List.rev_map ~f l)
let rec count_map ~f l ctr =
match l with
| [] -> []
| [x1] ->
let f1 = f x1 in
[f1]
| [x1; x2] ->
let f1 = f x1 in
let f2 = f x2 in
[f1; f2]
| [x1; x2; x3] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
[f1; f2; f3]
| [x1; x2; x3; x4] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
[f1; f2; f3; f4]
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
let f5 = f x5 in
f1 :: f2 :: f3 :: f4 :: f5 ::
(if ctr > 1000
then map_slow ~f tl
else count_map ~f tl (ctr + 1))
let map l ~f = count_map ~f l 0
let (>>|) l f = map l ~f
let map2_exn l1 l2 ~f = List.rev (rev_map2_exn l1 l2 ~f)
let rev_map3_exn l1 l2 l3 ~f =
check_length3 "rev_map3" l1 l2 l3;
let rec loop l1 l2 l3 ac =
match (l1, l2, l3) with
| ([], [], []) -> ac
| (x1 :: l1, x2 :: l2, x3 :: l3) -> loop l1 l2 l3 (f x1 x2 x3 :: ac)
| _ -> assert false
in
loop l1 l2 l3 []
;;
let map3_exn l1 l2 l3 ~f = List.rev (rev_map3_exn l1 l2 l3 ~f)
let rec rev_map_append l1 l2 ~f =
match l1 with
| [] -> l2
| h :: t -> rev_map_append ~f t (f h :: l2)
let fold_right l ~f ~init =
fold ~f:(fun a b -> f b a) ~init (List.rev l)
let unzip list =
let rec loop list l1 l2 =
match list with
| [] -> (List.rev l1, List.rev l2)
| (x, y) :: tl -> loop tl (x :: l1) (y :: l2)
in
loop list [] []
let zip_exn l1 l2 = map2_exn ~f:(fun a b -> (a, b)) l1 l2
let zip l1 l2 = try Some (zip_exn l1 l2) with _ -> None
(** Additional list operations *)
let rev_mapi l ~f =
let rec loop i acc = function
| [] -> acc
| h :: t -> loop (i + 1) (f i h :: acc) t
in
loop 0 [] l
let mapi l ~f = List.rev (rev_mapi l ~f)
let iteri l ~f =
ignore (fold l ~init:0 ~f:(fun i x -> f i x; i + 1));
;;
let foldi t ~f ~init =
snd (fold t ~init:(0, init) ~f:(fun (i, acc) v -> (i + 1, f i acc v)))
;;
let filteri l ~f =
List.rev (foldi l
~f:(fun pos acc x ->
if f pos x then x :: acc else acc)
~init:[])
let reduce l ~f = match l with
| [] -> None
| hd :: tl -> Some (fold ~init:hd ~f tl)
let reduce_exn l ~f =
match reduce l ~f with
| None -> raise (Invalid_argument "List.reduce_exn")
| Some v -> v
let groupi l ~break =
let groups =
foldi l ~init:[] ~f:(fun i acc x ->
match acc with
| [] -> [[x]]
| current_group :: tl ->
if break i (hd_exn current_group) x then
[x] :: current_group :: tl (* start new group *)
else
(x :: current_group) :: tl) (* extend current group *)
in
match groups with
| [] -> []
| l -> rev_map l ~f:rev
let group l ~break = groupi l ~break:(fun _ x y -> break x y)
let concat_map l ~f =
let rec aux acc = function
| [] -> List.rev acc
| hd :: tl -> aux (rev_append (f hd) acc) tl
in
aux [] l
let concat_mapi l ~f =
let rec aux cont acc = function
| [] -> List.rev acc
| hd :: tl -> aux (cont + 1) (rev_append (f cont hd) acc) tl
in
aux 0 [] l
let merge l1 l2 ~cmp =
let rec loop acc l1 l2 =
match l1,l2 with
| [], l2 -> rev_append acc l2
| l1, [] -> rev_append acc l1
| h1 :: t1, h2 :: t2 ->
if cmp h1 h2 <= 0
then loop (h1 :: acc) t1 l2
else loop (h2 :: acc) l1 t2
in
loop [] l1 l2
;;
include struct
We are explicit about what we import from the general Monad functor so that
* we do n't accidentally rebind more efficient list - specific functions .
* we don't accidentally rebind more efficient list-specific functions.
*)
module Monad = Hack_monad.Make (struct
type 'a t = 'a list
let bind x f = concat_map x ~f
let map = `Custom map
let return x = [x]
end)
open Monad
module Monad_infix = Monad_infix
let ignore = ignore
let join = join
let bind = bind
let (>>=) = bind
let return = return
let all = all
let all_ignore = all_ignore
end
(** returns final element of list *)
let rec last_exn list = match list with
| [x] -> x
| _ :: tl -> last_exn tl
| [] -> raise (Invalid_argument "Core_list.last")
(** optionally returns final element of list *)
let rec last list = match list with
| [x] -> Some x
| _ :: tl -> last tl
| [] -> None
let find_consecutive_duplicate t ~equal =
match t with
| [] -> None
| a1 :: t ->
let rec loop a1 t =
match t with
| [] -> None
| a2 :: t -> if equal a1 a2 then Some (a1, a2) else loop a2 t
in
loop a1 t
;;
(* returns list without adjacent duplicates *)
let remove_consecutive_duplicates list ~equal =
let rec loop list accum = match list with
| [] -> accum
| hd :: [] -> hd :: accum
| hd1 :: hd2 :: tl ->
if equal hd1 hd2
then loop (hd2 :: tl) accum
else loop (hd2 :: tl) (hd1 :: accum)
in
rev (loop list [])
(** returns sorted version of list with duplicates removed *)
let dedup ?(compare=Pervasives.compare) list =
match list with
| [] -> [] (* performance hack *)
| _ ->
let equal x x' = compare x x' = 0 in
let sorted = List.sort ~cmp:compare list in
remove_consecutive_duplicates ~equal sorted
let contains_dup ?compare lst = length (dedup ?compare lst) <> length lst
let find_a_dup ?(compare=Pervasives.compare) l =
let sorted = List.sort ~cmp:compare l in
let rec loop l = match l with
[] | [_] -> None
| hd1 :: hd2 :: tl ->
if compare hd1 hd2 = 0 then Some (hd1) else loop (hd2 :: tl)
in
loop sorted
let count t ~f = Hack_container.fold_count fold t ~f
let sum m t ~f = Hack_container.fold_sum m fold t ~f
let min_elt t ~cmp = Hack_container.fold_min fold t ~cmp
let max_elt t ~cmp = Hack_container.fold_max fold t ~cmp
let init n ~f =
if n < 0 then invalid_argf "List.init %d" n ();
let rec loop i accum =
assert (i >= 0);
if i = 0 then accum
else loop (i-1) (f (i-1) :: accum)
in
loop n []
;;
let rev_filter_map l ~f =
let rec loop l accum =
match l with
| [] -> accum
| hd :: tl ->
match f hd with
| Some x -> loop tl (x :: accum)
| None -> loop tl accum
in
loop l []
;;
let filter_map l ~f = List.rev (rev_filter_map l ~f)
let rev_filter_mapi l ~f =
let rec loop i l accum =
match l with
| [] -> accum
| hd :: tl ->
match f i hd with
| Some x -> loop (i + 1) tl (x :: accum)
| None -> loop (i + 1) tl accum
in
loop 0 l []
;;
let filter_mapi l ~f = List.rev (rev_filter_mapi l ~f)
let filter_opt l = filter_map l ~f:(fun x -> x)
let partition_map t ~f =
let rec loop t fst snd =
match t with
| [] -> (rev fst, rev snd)
| x :: t ->
match f x with
| `Fst y -> loop t (y :: fst) snd
| `Snd y -> loop t fst (y :: snd)
in
loop t [] []
;;
let partition_tf t ~f =
let f x = if f x then `Fst x else `Snd x in
partition_map t ~f
;;
module Assoc = struct
type ('a, 'b) t = ('a * 'b) list
let find t ?(equal=Hack_poly.equal) key =
match find t ~f:(fun (key', _) -> equal key key') with
| None -> None
| Some x -> Some (snd x)
let find_exn t ?(equal=Hack_poly.equal) key =
match find t key ~equal with
| None -> raise Not_found
| Some value -> value
let mem t ?(equal=Hack_poly.equal) key = (find t ~equal key) <> None
let remove t ?(equal=Hack_poly.equal) key =
filter t ~f:(fun (key', _) -> not (equal key key'))
let add t ?(equal=Hack_poly.equal) key value =
(* the remove doesn't change the map semantics, but keeps the list small *)
(key, value) :: remove t ~equal key
let inverse t = map t ~f:(fun (x, y) -> (y, x))
let map t ~f = List.map t ~f:(fun (key, value) -> (key, f value))
end
let sub l ~pos ~len =
(* We use [pos > length l - len] rather than [pos + len > length l] to avoid the
possibility of overflow. *)
if pos < 0 || len < 0 || pos > length l - len then invalid_arg "List.sub";
List.rev
(foldi l ~init:[]
~f:(fun i acc el ->
if i >= pos && i < (pos + len)
then el :: acc
else acc
)
)
;;
(*let slice a start stop =*)
Ordered_collection_common.slice ~length_fun : length ~sub_fun : sub
(*a start stop*)
let split_n t_orig n =
if n <= 0 then
([], t_orig)
else
let rec loop n t accum =
if n = 0 then
(List.rev accum, t)
else
match t with
in this case , t_orig = List.rev accum
| hd :: tl -> loop (n - 1) tl (hd :: accum)
in
loop n t_orig []
let take t n = fst (split_n t n)
let drop t n = snd (split_n t n)
let split_while xs ~f =
let rec loop acc = function
| hd :: tl when f hd -> loop (hd :: acc) tl
| t -> (rev acc, t)
in
loop [] xs
;;
let take_while t ~f = fst (split_while t ~f)
let drop_while t ~f = snd (split_while t ~f)
let cartesian_product list1 list2 =
if list2 = [] then [] else
let rec loop l1 l2 accum = match l1 with
| [] -> accum
| (hd :: tl) ->
loop tl l2
(List.rev_append
(map ~f:(fun x -> (hd,x)) l2)
accum)
in
List.rev (loop list1 list2 [])
let concat l = fold_right l ~init:[] ~f:append
let concat_no_order l = fold l ~init:[] ~f:(fun acc l -> rev_append l acc)
let cons x l = x :: l
let is_empty l = match l with [] -> true | _ -> false
let is_sorted l ~compare =
let rec loop l =
match l with
| [] | [_] -> true
| x1 :: ((x2 :: _) as rest) ->
compare x1 x2 <= 0 && loop rest
in loop l
let is_sorted_strictly l ~compare =
let rec loop l =
match l with
| [] | [_] -> true
| x1 :: ((x2 :: _) as rest) ->
compare x1 x2 < 0 && loop rest
in loop l
;;
module Infix = struct
let ( @ ) = append
end
let compare a b ~cmp =
let rec loop a b =
match a, b with
| [], [] -> 0
| [], _ -> -1
| _ , [] -> 1
| x :: xs, y :: ys ->
let n = cmp x y in
if n = 0 then loop xs ys
else n
in
loop a b
;;
let equal t1 t2 ~equal =
let rec loop t1 t2 =
match t1, t2 with
| [], [] -> true
| x1 :: t1, x2 :: t2 -> equal x1 x2 && loop t1 t2
| _ -> false
in
loop t1 t2
;;
let transpose =
let rec transpose_aux t rev_columns =
match partition_map t ~f:(function [] -> `Snd () | x :: xs -> `Fst (x, xs)) with
| (_ :: _, _ :: _) -> None
| ([], _) -> Some (rev_append rev_columns [])
| (heads_and_tails, []) ->
let (column, trimmed_rows) = unzip heads_and_tails in
transpose_aux trimmed_rows (column :: rev_columns)
in
fun t ->
transpose_aux t []
exception Transpose_got_lists_of_different_lengths of int list
let transpose_exn l =
match transpose l with
| Some l -> l
| None ->
raise (Transpose_got_lists_of_different_lengths (List.map l ~f:List.length))
let intersperse t ~sep =
match t with
| [] -> []
| x :: xs -> x :: fold_right xs ~init:[] ~f:(fun y acc -> sep :: y :: acc)
let rec replicate ~num x =
match num with
| 0 -> []
| n when n < 0 ->
invalid_argf "List.replicate was called with %d argument" n ()
| _ -> x :: replicate ~num:(num - 1) x
| null | https://raw.githubusercontent.com/rvantonder/hack_parallel/c9d0714785adc100345835c1989f7c657e01f629/src/third-party/hack_core/hack_core_list.ml | ocaml | Generate the range from the last element, so that we do not need to rev it
Standard functions
This is a copy of the standard library assq function.
* changing the order of arguments on some standard [List] functions.
* For the container interface.
* Tail recursive versions of standard [List] module
* Additional list operations
start new group
extend current group
* returns final element of list
* optionally returns final element of list
returns list without adjacent duplicates
* returns sorted version of list with duplicates removed
performance hack
the remove doesn't change the map semantics, but keeps the list small
We use [pos > length l - len] rather than [pos + len > length l] to avoid the
possibility of overflow.
let slice a start stop =
a start stop | module UnlabeledList = List
module List = StdLabels.List
module String = StdLabels.String
let invalid_argf = Hack_core_printf.invalid_argf
module T = struct
type 'a t = 'a list
end
include T
let of_list t = t
let range ?(stride=1) ?(start=`inclusive) ?(stop=`exclusive) start_i stop_i =
if stride = 0 then
invalid_arg "Core_list.range: stride must be non-zero";
let rec loop last counter accum =
if counter <= 0 then accum
else loop (last - stride) (counter - 1) (last :: accum)
in
let stride_sign = if stride > 0 then 1 else -1 in
let start =
match start with
| `inclusive -> start_i
| `exclusive -> start_i + stride
in
let stop =
match stop with
| `inclusive -> stop_i + stride_sign
| `exclusive -> stop_i
in
let num_elts = (stop - start + stride - stride_sign) / stride in
loop (start + (stride * (num_elts - 1))) num_elts []
;;
let length = List.length
let hd_exn = List.hd
let tl_exn = List.tl
let hd t =
match t with
| [] -> None
| x :: _ -> Some x
;;
let tl t =
match t with
| [] -> None
| _ :: t' -> Some t'
;;
let nth t n =
if n < 0 then None else
let rec nth_aux t n =
match t with
| [] -> None
| a :: t -> if n = 0 then Some a else nth_aux t (n-1)
in nth_aux t n
;;
let nth_exn t n =
match nth t n with
| None ->
invalid_argf "List.nth_exn %d called on list of length %d"
n (length t) ()
| Some a -> a
;;
let rev_append = List.rev_append
let rev = function
| [] | [_] as res -> res
| x :: y :: rest -> rev_append rest [y; x]
let unordered_append l1 l2 =
match l1, l2 with
| [], l | l, [] -> l
| _ -> List.rev_append l1 l2
let rev_map t ~f = List.rev_map t ~f
exception Length_mismatch of string * int * int
let check_length2 name l1 l2 =
let n1 = length l1 in
let n2 = length l2 in
if n1 <> n2 then
raise (invalid_argf "length mismatch in %s: %d <> %d " name n1 n2 ())
;;
let check_length3 name l1 l2 l3 =
let n1 = length l1 in
let n2 = length l2 in
let n3 = length l3 in
if n1 <> n2 || n2 <> n3 then
raise (invalid_argf "length mismatch in %s: %d <> %d || %d <> %d"
name n1 n2 n2 n3 ())
;;
let iter2_exn l1 l2 ~f =
check_length2 "iter2_exn" l1 l2;
List.iter2 l1 l2 ~f;
;;
let rev_map2_exn l1 l2 ~f =
check_length2 "rev_map2_exn" l1 l2;
List.rev_map2 l1 l2 ~f;
;;
let fold2_exn l1 l2 ~init ~f =
check_length2 "fold2_exn" l1 l2;
List.fold_left2 l1 l2 ~init ~f;
;;
let for_all2_exn l1 l2 ~f =
check_length2 "for_all2_exn" l1 l2;
List.for_all2 l1 l2 ~f;
;;
let exists2_exn l1 l2 ~f =
check_length2 "exists2_exn" l1 l2;
List.exists2 l1 l2 ~f;
;;
let mem ?(equal = (=)) t a = List.exists t ~f:(equal a)
let rec assq x = function
[] -> raise Not_found
| (a,b)::l -> if a == x then b else assq x l
This is a copy of the code from the standard library , with an extra eta - expansion to
avoid creating partial closures ( showed up for List.filter in profiling ) .
avoid creating partial closures (showed up for List.filter in profiling). *)
let rev_filter t ~f =
let rec find ~f accu = function
| [] -> accu
| x :: l -> if f x then find ~f (x :: accu) l else find ~f accu l
in
find ~f [] t
;;
let filter t ~f = rev (rev_filter t ~f)
let sort = List.sort
let stable_sort = List.stable_sort
let fast_sort = List.fast_sort
4.02 forgot to add sort_uniq to ListLabels , but it was added in 4.03 :
*)
let sort_uniq ~(cmp:'a -> 'a -> int) (lst:'a list) =
UnlabeledList.sort_uniq cmp lst
let find_map t ~f =
let rec loop = function
| [] -> None
| x :: l ->
match f x with
| None -> loop l
| Some _ as r -> r
in
loop t
;;
let find t ~f =
let rec loop = function
| [] -> None
| x :: l -> if f x then Some x else loop l
in
loop t
;;
let find_exn t ~f = List.find t ~f
let findi t ~f =
let rec loop i t =
match t with
| [] -> None
| x :: l -> if f i x then Some (i, x) else loop (i + 1) l
in
loop 0 t
;;
let exists t ~f = List.exists t ~f
let for_all t ~f = List.for_all t ~f
let iter t ~f = List.iter t ~f
let fold t ~init ~f = List.fold_left t ~f ~init
let fold_left = fold
let to_array = Hack_caml.Array.of_list
let to_list t = t
let slow_append l1 l2 = List.rev_append (List.rev l1) l2
There are a few optimized list operations here , including append and map . There are
basically two optimizations in play : loop unrolling , and dynamic switching between
stack and heap allocation .
The loop - unrolling is straightforward , we just unroll 5 levels of the loop . This makes
each iteration faster , and also reduces the number of stack frames consumed per list
element .
The dynamic switching is done by counting the number of stack frames , and then
switching to the " slow " implementation when we exceed a given limit . This means that
short lists use the fast stack - allocation method , and long lists use a slower one that
does n't require stack space .
basically two optimizations in play: loop unrolling, and dynamic switching between
stack and heap allocation.
The loop-unrolling is straightforward, we just unroll 5 levels of the loop. This makes
each iteration faster, and also reduces the number of stack frames consumed per list
element.
The dynamic switching is done by counting the number of stack frames, and then
switching to the "slow" implementation when we exceed a given limit. This means that
short lists use the fast stack-allocation method, and long lists use a slower one that
doesn't require stack space.
*)
let rec count_append l1 l2 count =
match l2 with
| [] -> l1
| _ ->
match l1 with
| [] -> l2
| [x1] -> x1 :: l2
| [x1; x2] -> x1 :: x2 :: l2
| [x1; x2; x3] -> x1 :: x2 :: x3 :: l2
| [x1; x2; x3; x4] -> x1 :: x2 :: x3 :: x4 :: l2
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
x1 :: x2 :: x3 :: x4 :: x5 ::
(if count > 1000
then slow_append tl l2
else count_append tl l2 (count + 1))
let append l1 l2 = count_append l1 l2 0
let map_slow l ~f = List.rev (List.rev_map ~f l)
let rec count_map ~f l ctr =
match l with
| [] -> []
| [x1] ->
let f1 = f x1 in
[f1]
| [x1; x2] ->
let f1 = f x1 in
let f2 = f x2 in
[f1; f2]
| [x1; x2; x3] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
[f1; f2; f3]
| [x1; x2; x3; x4] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
[f1; f2; f3; f4]
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
let f5 = f x5 in
f1 :: f2 :: f3 :: f4 :: f5 ::
(if ctr > 1000
then map_slow ~f tl
else count_map ~f tl (ctr + 1))
let map l ~f = count_map ~f l 0
let (>>|) l f = map l ~f
let map2_exn l1 l2 ~f = List.rev (rev_map2_exn l1 l2 ~f)
let rev_map3_exn l1 l2 l3 ~f =
check_length3 "rev_map3" l1 l2 l3;
let rec loop l1 l2 l3 ac =
match (l1, l2, l3) with
| ([], [], []) -> ac
| (x1 :: l1, x2 :: l2, x3 :: l3) -> loop l1 l2 l3 (f x1 x2 x3 :: ac)
| _ -> assert false
in
loop l1 l2 l3 []
;;
let map3_exn l1 l2 l3 ~f = List.rev (rev_map3_exn l1 l2 l3 ~f)
let rec rev_map_append l1 l2 ~f =
match l1 with
| [] -> l2
| h :: t -> rev_map_append ~f t (f h :: l2)
let fold_right l ~f ~init =
fold ~f:(fun a b -> f b a) ~init (List.rev l)
let unzip list =
let rec loop list l1 l2 =
match list with
| [] -> (List.rev l1, List.rev l2)
| (x, y) :: tl -> loop tl (x :: l1) (y :: l2)
in
loop list [] []
let zip_exn l1 l2 = map2_exn ~f:(fun a b -> (a, b)) l1 l2
let zip l1 l2 = try Some (zip_exn l1 l2) with _ -> None
let rev_mapi l ~f =
let rec loop i acc = function
| [] -> acc
| h :: t -> loop (i + 1) (f i h :: acc) t
in
loop 0 [] l
let mapi l ~f = List.rev (rev_mapi l ~f)
let iteri l ~f =
ignore (fold l ~init:0 ~f:(fun i x -> f i x; i + 1));
;;
let foldi t ~f ~init =
snd (fold t ~init:(0, init) ~f:(fun (i, acc) v -> (i + 1, f i acc v)))
;;
let filteri l ~f =
List.rev (foldi l
~f:(fun pos acc x ->
if f pos x then x :: acc else acc)
~init:[])
let reduce l ~f = match l with
| [] -> None
| hd :: tl -> Some (fold ~init:hd ~f tl)
let reduce_exn l ~f =
match reduce l ~f with
| None -> raise (Invalid_argument "List.reduce_exn")
| Some v -> v
let groupi l ~break =
let groups =
foldi l ~init:[] ~f:(fun i acc x ->
match acc with
| [] -> [[x]]
| current_group :: tl ->
if break i (hd_exn current_group) x then
else
in
match groups with
| [] -> []
| l -> rev_map l ~f:rev
let group l ~break = groupi l ~break:(fun _ x y -> break x y)
let concat_map l ~f =
let rec aux acc = function
| [] -> List.rev acc
| hd :: tl -> aux (rev_append (f hd) acc) tl
in
aux [] l
let concat_mapi l ~f =
let rec aux cont acc = function
| [] -> List.rev acc
| hd :: tl -> aux (cont + 1) (rev_append (f cont hd) acc) tl
in
aux 0 [] l
let merge l1 l2 ~cmp =
let rec loop acc l1 l2 =
match l1,l2 with
| [], l2 -> rev_append acc l2
| l1, [] -> rev_append acc l1
| h1 :: t1, h2 :: t2 ->
if cmp h1 h2 <= 0
then loop (h1 :: acc) t1 l2
else loop (h2 :: acc) l1 t2
in
loop [] l1 l2
;;
include struct
We are explicit about what we import from the general Monad functor so that
* we do n't accidentally rebind more efficient list - specific functions .
* we don't accidentally rebind more efficient list-specific functions.
*)
module Monad = Hack_monad.Make (struct
type 'a t = 'a list
let bind x f = concat_map x ~f
let map = `Custom map
let return x = [x]
end)
open Monad
module Monad_infix = Monad_infix
let ignore = ignore
let join = join
let bind = bind
let (>>=) = bind
let return = return
let all = all
let all_ignore = all_ignore
end
let rec last_exn list = match list with
| [x] -> x
| _ :: tl -> last_exn tl
| [] -> raise (Invalid_argument "Core_list.last")
let rec last list = match list with
| [x] -> Some x
| _ :: tl -> last tl
| [] -> None
let find_consecutive_duplicate t ~equal =
match t with
| [] -> None
| a1 :: t ->
let rec loop a1 t =
match t with
| [] -> None
| a2 :: t -> if equal a1 a2 then Some (a1, a2) else loop a2 t
in
loop a1 t
;;
let remove_consecutive_duplicates list ~equal =
let rec loop list accum = match list with
| [] -> accum
| hd :: [] -> hd :: accum
| hd1 :: hd2 :: tl ->
if equal hd1 hd2
then loop (hd2 :: tl) accum
else loop (hd2 :: tl) (hd1 :: accum)
in
rev (loop list [])
let dedup ?(compare=Pervasives.compare) list =
match list with
| _ ->
let equal x x' = compare x x' = 0 in
let sorted = List.sort ~cmp:compare list in
remove_consecutive_duplicates ~equal sorted
let contains_dup ?compare lst = length (dedup ?compare lst) <> length lst
let find_a_dup ?(compare=Pervasives.compare) l =
let sorted = List.sort ~cmp:compare l in
let rec loop l = match l with
[] | [_] -> None
| hd1 :: hd2 :: tl ->
if compare hd1 hd2 = 0 then Some (hd1) else loop (hd2 :: tl)
in
loop sorted
let count t ~f = Hack_container.fold_count fold t ~f
let sum m t ~f = Hack_container.fold_sum m fold t ~f
let min_elt t ~cmp = Hack_container.fold_min fold t ~cmp
let max_elt t ~cmp = Hack_container.fold_max fold t ~cmp
let init n ~f =
if n < 0 then invalid_argf "List.init %d" n ();
let rec loop i accum =
assert (i >= 0);
if i = 0 then accum
else loop (i-1) (f (i-1) :: accum)
in
loop n []
;;
let rev_filter_map l ~f =
let rec loop l accum =
match l with
| [] -> accum
| hd :: tl ->
match f hd with
| Some x -> loop tl (x :: accum)
| None -> loop tl accum
in
loop l []
;;
let filter_map l ~f = List.rev (rev_filter_map l ~f)
let rev_filter_mapi l ~f =
let rec loop i l accum =
match l with
| [] -> accum
| hd :: tl ->
match f i hd with
| Some x -> loop (i + 1) tl (x :: accum)
| None -> loop (i + 1) tl accum
in
loop 0 l []
;;
let filter_mapi l ~f = List.rev (rev_filter_mapi l ~f)
let filter_opt l = filter_map l ~f:(fun x -> x)
let partition_map t ~f =
let rec loop t fst snd =
match t with
| [] -> (rev fst, rev snd)
| x :: t ->
match f x with
| `Fst y -> loop t (y :: fst) snd
| `Snd y -> loop t fst (y :: snd)
in
loop t [] []
;;
let partition_tf t ~f =
let f x = if f x then `Fst x else `Snd x in
partition_map t ~f
;;
module Assoc = struct
type ('a, 'b) t = ('a * 'b) list
let find t ?(equal=Hack_poly.equal) key =
match find t ~f:(fun (key', _) -> equal key key') with
| None -> None
| Some x -> Some (snd x)
let find_exn t ?(equal=Hack_poly.equal) key =
match find t key ~equal with
| None -> raise Not_found
| Some value -> value
let mem t ?(equal=Hack_poly.equal) key = (find t ~equal key) <> None
let remove t ?(equal=Hack_poly.equal) key =
filter t ~f:(fun (key', _) -> not (equal key key'))
let add t ?(equal=Hack_poly.equal) key value =
(key, value) :: remove t ~equal key
let inverse t = map t ~f:(fun (x, y) -> (y, x))
let map t ~f = List.map t ~f:(fun (key, value) -> (key, f value))
end
let sub l ~pos ~len =
if pos < 0 || len < 0 || pos > length l - len then invalid_arg "List.sub";
List.rev
(foldi l ~init:[]
~f:(fun i acc el ->
if i >= pos && i < (pos + len)
then el :: acc
else acc
)
)
;;
Ordered_collection_common.slice ~length_fun : length ~sub_fun : sub
let split_n t_orig n =
if n <= 0 then
([], t_orig)
else
let rec loop n t accum =
if n = 0 then
(List.rev accum, t)
else
match t with
in this case , t_orig = List.rev accum
| hd :: tl -> loop (n - 1) tl (hd :: accum)
in
loop n t_orig []
let take t n = fst (split_n t n)
let drop t n = snd (split_n t n)
let split_while xs ~f =
let rec loop acc = function
| hd :: tl when f hd -> loop (hd :: acc) tl
| t -> (rev acc, t)
in
loop [] xs
;;
let take_while t ~f = fst (split_while t ~f)
let drop_while t ~f = snd (split_while t ~f)
let cartesian_product list1 list2 =
if list2 = [] then [] else
let rec loop l1 l2 accum = match l1 with
| [] -> accum
| (hd :: tl) ->
loop tl l2
(List.rev_append
(map ~f:(fun x -> (hd,x)) l2)
accum)
in
List.rev (loop list1 list2 [])
let concat l = fold_right l ~init:[] ~f:append
let concat_no_order l = fold l ~init:[] ~f:(fun acc l -> rev_append l acc)
let cons x l = x :: l
let is_empty l = match l with [] -> true | _ -> false
let is_sorted l ~compare =
let rec loop l =
match l with
| [] | [_] -> true
| x1 :: ((x2 :: _) as rest) ->
compare x1 x2 <= 0 && loop rest
in loop l
let is_sorted_strictly l ~compare =
let rec loop l =
match l with
| [] | [_] -> true
| x1 :: ((x2 :: _) as rest) ->
compare x1 x2 < 0 && loop rest
in loop l
;;
module Infix = struct
let ( @ ) = append
end
let compare a b ~cmp =
let rec loop a b =
match a, b with
| [], [] -> 0
| [], _ -> -1
| _ , [] -> 1
| x :: xs, y :: ys ->
let n = cmp x y in
if n = 0 then loop xs ys
else n
in
loop a b
;;
let equal t1 t2 ~equal =
let rec loop t1 t2 =
match t1, t2 with
| [], [] -> true
| x1 :: t1, x2 :: t2 -> equal x1 x2 && loop t1 t2
| _ -> false
in
loop t1 t2
;;
let transpose =
let rec transpose_aux t rev_columns =
match partition_map t ~f:(function [] -> `Snd () | x :: xs -> `Fst (x, xs)) with
| (_ :: _, _ :: _) -> None
| ([], _) -> Some (rev_append rev_columns [])
| (heads_and_tails, []) ->
let (column, trimmed_rows) = unzip heads_and_tails in
transpose_aux trimmed_rows (column :: rev_columns)
in
fun t ->
transpose_aux t []
exception Transpose_got_lists_of_different_lengths of int list
let transpose_exn l =
match transpose l with
| Some l -> l
| None ->
raise (Transpose_got_lists_of_different_lengths (List.map l ~f:List.length))
let intersperse t ~sep =
match t with
| [] -> []
| x :: xs -> x :: fold_right xs ~init:[] ~f:(fun y acc -> sep :: y :: acc)
let rec replicate ~num x =
match num with
| 0 -> []
| n when n < 0 ->
invalid_argf "List.replicate was called with %d argument" n ()
| _ -> x :: replicate ~num:(num - 1) x
|
46654541ce19d27dfbcaf878fc6c4d1661bee9c22694c07988d2970890e35656 | repl-electric/.sonic-pi | reverb.sps | #key: reverb
#point_line:1
#point_index:2
# --
with_fx(:reverb, room: 0.6, mix: 0.4, damp: 0.5) do |r_fx|
end
| null | https://raw.githubusercontent.com/repl-electric/.sonic-pi/a00c733f0a5fa1fa0aa65bf06fe7ab71654d2da9/snippets/reverb.sps | scheme | #key: reverb
#point_line:1
#point_index:2
# --
with_fx(:reverb, room: 0.6, mix: 0.4, damp: 0.5) do |r_fx|
end
| |
97819e5ef9133316c0d6d7b7009cddfe20753aadaaacd98e8cbf8b627e9a72ed | deverl-ide/deverl | deverl_lib_widgets.erl | %% =====================================================================
%% This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
%% (at your option) any later version.
%%
%% This program is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%% GNU General Public License for more details.
%%
You should have received a copy of the GNU General Public License
%% along with this program. If not, see </>.
%%
@author < >
@author < >
, 2014
%%
%% @doc This module contains library functions for this application.
%% @end
%% =====================================================================
-module(deverl_lib_widgets).
-include_lib("wx/include/wx.hrl").
-include("deverl.hrl").
-export([
rc_dir/1,
placeholder/2,
placeholder/3,
colour_shade/2,
datetime_to_string/1,
set_list_item_background/2
]).
-define(PANEL_FG, {160,160,160}).
-define(PANEL_BG, {252,252,252}).
%% =====================================================================
%% Client API
%% =====================================================================
%% =====================================================================
%% @doc Get the absolute path to the rsc (resource) directory.
rc_dir(File) ->
Dir = filename:dirname(code:which(?MODULE)),
filename:join([Dir,"../rc",File]).
%% =====================================================================
%% @doc Get a placeholder panel that displays some text within the parent
%% when the parent is otherwise empty.
-spec placeholder(wxWindow:wxWindow(), string()) -> wxPanel:wxPanel().
placeholder(Parent, Str) ->
placeholder(Parent, Str, []).
-spec placeholder(wxWindow:wxWindow(), string(), list()) -> wxPanel:wxPanel().
placeholder(Parent, Str, Options) ->
Linux ( Mint , at least ! ) needs an additional horizontal sizer ( seems like it
%% ignores {style, ?wxALIGN_CENTRE}).
Panel = wxPanel:new(Parent),
wxPanel:setBackgroundColour(Panel, ?PANEL_BG),
Sz = wxBoxSizer:new(?wxVERTICAL),
wxPanel:setSizer(Panel, Sz),
HSz = wxBoxSizer:new(?wxHORIZONTAL),
case os:type() of
{_, linux} ->
wxSizer:addStretchSpacer(HSz);
_ -> ok
end,
Text = wxStaticText:new(Panel, ?wxID_ANY, Str, [{style, ?wxALIGN_CENTRE}]),
wxSizer:add(HSz, Text, [{proportion, 1}, {flag, ?wxEXPAND}]),
case os:type() of
{_, linux} ->
wxSizer:addStretchSpacer(HSz);
_ -> ok
end,
Fg = case proplists:get_value(fgColour, Options) of
undefined -> ?PANEL_FG;
C -> C
end,
wxStaticText:setForegroundColour(Text, Fg),
wxSizer : , Text , [ { proportion , 1 } , { flag , ? wxEXPAND } ] ) ,
wxSizer:addStretchSpacer(Sz),
wxSizer:add(Sz, HSz, [{proportion, 1}, {flag, ?wxEXPAND}]),
wxSizer:addStretchSpacer(Sz),
Panel.
%% =====================================================================
%% @doc Get a new shade of Colour.
-spec colour_shade(RGB | RGBA, float()) -> RGB | RGBA when
RGB :: {integer(), integer(), integer()},
RGBA :: {integer(), integer(), integer(), integer()}.
colour_shade({R,G,B}, Scalar) ->
{get_shade(R, Scalar), get_shade(G, Scalar), get_shade(B, Scalar)};
colour_shade({R,G,B,A}, Scalar) ->
{get_shade(R, Scalar), get_shade(G, Scalar), get_shade(B, Scalar), A}.
%% =====================================================================
%% @doc Convert calender:datetime() to a string of the form
%% YYYY-MM-DD HH:MM:SS
-spec datetime_to_string(calender:datetime()) -> string().
datetime_to_string({{Y, M, D}, {H, Mi, S}}) ->
Args = [Y, M, D, H, Mi, S],
Str = io_lib:format("~B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", Args),
lists:flatten(Str).
%% =====================================================================
%% @doc Set the background colour for a single list item.
-spec set_list_item_background(wxListCtrl:wxListCtrl(), integer()) -> ok.
set_list_item_background(ListCtrl, Item) ->
case Item rem 2 of
0 ->
wxListCtrl:setItemBackgroundColour(ListCtrl, Item, ?ROW_BG_EVEN);
_ ->
wxListCtrl:setItemBackgroundColour(ListCtrl, Item, ?ROW_BG_ODD)
end.
%% =====================================================================
Internal functions
%% =====================================================================
%% =====================================================================
%% @doc
@private
-spec get_shade(integer(), float()) -> integer().
get_shade(V, Scalar) ->
Shade = round(V * Scalar),
case Shade of
N when N > 255 ->
255;
N when N < 0 ->
0;
N -> N
end. | null | https://raw.githubusercontent.com/deverl-ide/deverl/69216c7720ce2a32344711f5526c0eb9676bcae0/deverl/src/deverl_lib_widgets.erl | erlang | =====================================================================
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
@doc This module contains library functions for this application.
@end
=====================================================================
=====================================================================
Client API
=====================================================================
=====================================================================
@doc Get the absolute path to the rsc (resource) directory.
=====================================================================
@doc Get a placeholder panel that displays some text within the parent
when the parent is otherwise empty.
ignores {style, ?wxALIGN_CENTRE}).
=====================================================================
@doc Get a new shade of Colour.
=====================================================================
@doc Convert calender:datetime() to a string of the form
YYYY-MM-DD HH:MM:SS
=====================================================================
@doc Set the background colour for a single list item.
=====================================================================
=====================================================================
=====================================================================
@doc | it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
@author < >
@author < >
, 2014
-module(deverl_lib_widgets).
-include_lib("wx/include/wx.hrl").
-include("deverl.hrl").
-export([
rc_dir/1,
placeholder/2,
placeholder/3,
colour_shade/2,
datetime_to_string/1,
set_list_item_background/2
]).
-define(PANEL_FG, {160,160,160}).
-define(PANEL_BG, {252,252,252}).
rc_dir(File) ->
Dir = filename:dirname(code:which(?MODULE)),
filename:join([Dir,"../rc",File]).
-spec placeholder(wxWindow:wxWindow(), string()) -> wxPanel:wxPanel().
placeholder(Parent, Str) ->
placeholder(Parent, Str, []).
-spec placeholder(wxWindow:wxWindow(), string(), list()) -> wxPanel:wxPanel().
placeholder(Parent, Str, Options) ->
Linux ( Mint , at least ! ) needs an additional horizontal sizer ( seems like it
Panel = wxPanel:new(Parent),
wxPanel:setBackgroundColour(Panel, ?PANEL_BG),
Sz = wxBoxSizer:new(?wxVERTICAL),
wxPanel:setSizer(Panel, Sz),
HSz = wxBoxSizer:new(?wxHORIZONTAL),
case os:type() of
{_, linux} ->
wxSizer:addStretchSpacer(HSz);
_ -> ok
end,
Text = wxStaticText:new(Panel, ?wxID_ANY, Str, [{style, ?wxALIGN_CENTRE}]),
wxSizer:add(HSz, Text, [{proportion, 1}, {flag, ?wxEXPAND}]),
case os:type() of
{_, linux} ->
wxSizer:addStretchSpacer(HSz);
_ -> ok
end,
Fg = case proplists:get_value(fgColour, Options) of
undefined -> ?PANEL_FG;
C -> C
end,
wxStaticText:setForegroundColour(Text, Fg),
wxSizer : , Text , [ { proportion , 1 } , { flag , ? wxEXPAND } ] ) ,
wxSizer:addStretchSpacer(Sz),
wxSizer:add(Sz, HSz, [{proportion, 1}, {flag, ?wxEXPAND}]),
wxSizer:addStretchSpacer(Sz),
Panel.
-spec colour_shade(RGB | RGBA, float()) -> RGB | RGBA when
RGB :: {integer(), integer(), integer()},
RGBA :: {integer(), integer(), integer(), integer()}.
colour_shade({R,G,B}, Scalar) ->
{get_shade(R, Scalar), get_shade(G, Scalar), get_shade(B, Scalar)};
colour_shade({R,G,B,A}, Scalar) ->
{get_shade(R, Scalar), get_shade(G, Scalar), get_shade(B, Scalar), A}.
-spec datetime_to_string(calender:datetime()) -> string().
datetime_to_string({{Y, M, D}, {H, Mi, S}}) ->
Args = [Y, M, D, H, Mi, S],
Str = io_lib:format("~B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", Args),
lists:flatten(Str).
-spec set_list_item_background(wxListCtrl:wxListCtrl(), integer()) -> ok.
set_list_item_background(ListCtrl, Item) ->
case Item rem 2 of
0 ->
wxListCtrl:setItemBackgroundColour(ListCtrl, Item, ?ROW_BG_EVEN);
_ ->
wxListCtrl:setItemBackgroundColour(ListCtrl, Item, ?ROW_BG_ODD)
end.
Internal functions
@private
-spec get_shade(integer(), float()) -> integer().
get_shade(V, Scalar) ->
Shade = round(V * Scalar),
case Shade of
N when N > 255 ->
255;
N when N < 0 ->
0;
N -> N
end. |
28538ee17a94b0f03e49e75eaa17565247b9ccd15ef562a3b270870846338cae | metabase/metabase | query.cljc | (ns metabase.lib.query
(:require
[malli.core :as mc]
[metabase.lib.dispatch :as lib.dispatch]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.options :as lib.options]
[metabase.lib.schema :as lib.schema]
[metabase.lib.util :as lib.util]
[metabase.util.malli :as mu]))
(def ^:private Metadata
[:or
lib.metadata/DatabaseMetadata
lib.metadata/StageMetadata])
(defmulti ^:private ->query
"Implementation for [[query]]."
{:arglists '([metadata x])}
(fn [_metadata x]
(lib.dispatch/dispatch-value x)))
;;; for a native query.
(defmethod ->query :dispatch-type/string
[database-metadata table-name]
(mc/coerce lib.metadata/DatabaseMetadata database-metadata)
{:lib/type :mbql/query
:lib/metadata database-metadata
:database (:id database-metadata)
:type :pipeline
:stages [(let [table (lib.metadata/table-metadata database-metadata table-name)]
(-> {:lib/type :mbql.stage/mbql
:source-table (:id table)}
lib.options/ensure-uuid))]})
(defmethod ->query :dispatch-type/map
[metadata query]
(-> (lib.util/pipeline query)
(assoc :lib/metadata metadata
:lib/type :mbql/query)
(update :stages (fn [stages]
(mapv
lib.options/ensure-uuid
stages)))))
(mu/defn query :- ::lib.schema/query
"Create a new MBQL query from anything that could conceptually be an MBQL query, like a Database or Table or an
existing MBQL query or saved question or whatever. If the thing in question does not already include metadata, pass
it in separately -- metadata is needed for most query manipulation operations."
([x]
(->query nil x))
([metadata :- Metadata
x]
(->query metadata x)))
TODO -- the stuff below will probably change in the near future , please do n't read too much in to it .
(mu/defn native-query :- ::lib.schema/query
"Create a new native query.
Native in this sense means a pMBQL `:pipeline` query with a first stage that is a native query."
([database-metadata :- lib.metadata/DatabaseMetadata ; or results metadata?
query]
TODO -- should n't this be outputting a pipeline query right away ? I think this is wrong
{:lib/type :mbql/query
:lib/metadata database-metadata
:database (:id database-metadata)
:type :pipeline
:stages [(-> {:lib/type :mbql.stage/native
:native query}
lib.options/ensure-uuid)]})
([database-metadata :- lib.metadata/DatabaseMetadata
results-metadata :- lib.metadata/StageMetadata
query]
TODO -- in # 28717 we will probably change this so ` : lib / metadata ` is always DatabaseMetadata and the
` results - metadata ` is ` : lib / stage - metadata ` attached to the first stage
{:lib/type :mbql/query
:lib/metadata results-metadata
:database (:id database-metadata)
:type :pipeline
:stages [(-> {:lib/type :mbql.stage/native
:native query}
lib.options/ensure-uuid)]}))
TODO -- this needs database metadata passed in as well .
(mu/defn saved-question-query :- ::lib.schema/query
"Convenience for creating a query from a Saved Question (i.e., a Card)."
[{query :dataset_query, metadata :result_metadata}]
(->query metadata query))
(mu/defn metadata :- [:maybe Metadata]
"Get the metadata associated with a `query`, if any."
[query :- ::lib.schema/query]
(:lib/metadata query))
| null | https://raw.githubusercontent.com/metabase/metabase/02e9aa420ef910138b9b5e05f74c96e31286bcf2/src/metabase/lib/query.cljc | clojure | for a native query.
or results metadata? | (ns metabase.lib.query
(:require
[malli.core :as mc]
[metabase.lib.dispatch :as lib.dispatch]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.options :as lib.options]
[metabase.lib.schema :as lib.schema]
[metabase.lib.util :as lib.util]
[metabase.util.malli :as mu]))
(def ^:private Metadata
[:or
lib.metadata/DatabaseMetadata
lib.metadata/StageMetadata])
(defmulti ^:private ->query
"Implementation for [[query]]."
{:arglists '([metadata x])}
(fn [_metadata x]
(lib.dispatch/dispatch-value x)))
(defmethod ->query :dispatch-type/string
[database-metadata table-name]
(mc/coerce lib.metadata/DatabaseMetadata database-metadata)
{:lib/type :mbql/query
:lib/metadata database-metadata
:database (:id database-metadata)
:type :pipeline
:stages [(let [table (lib.metadata/table-metadata database-metadata table-name)]
(-> {:lib/type :mbql.stage/mbql
:source-table (:id table)}
lib.options/ensure-uuid))]})
(defmethod ->query :dispatch-type/map
[metadata query]
(-> (lib.util/pipeline query)
(assoc :lib/metadata metadata
:lib/type :mbql/query)
(update :stages (fn [stages]
(mapv
lib.options/ensure-uuid
stages)))))
(mu/defn query :- ::lib.schema/query
"Create a new MBQL query from anything that could conceptually be an MBQL query, like a Database or Table or an
existing MBQL query or saved question or whatever. If the thing in question does not already include metadata, pass
it in separately -- metadata is needed for most query manipulation operations."
([x]
(->query nil x))
([metadata :- Metadata
x]
(->query metadata x)))
TODO -- the stuff below will probably change in the near future , please do n't read too much in to it .
(mu/defn native-query :- ::lib.schema/query
"Create a new native query.
Native in this sense means a pMBQL `:pipeline` query with a first stage that is a native query."
query]
TODO -- should n't this be outputting a pipeline query right away ? I think this is wrong
{:lib/type :mbql/query
:lib/metadata database-metadata
:database (:id database-metadata)
:type :pipeline
:stages [(-> {:lib/type :mbql.stage/native
:native query}
lib.options/ensure-uuid)]})
([database-metadata :- lib.metadata/DatabaseMetadata
results-metadata :- lib.metadata/StageMetadata
query]
TODO -- in # 28717 we will probably change this so ` : lib / metadata ` is always DatabaseMetadata and the
` results - metadata ` is ` : lib / stage - metadata ` attached to the first stage
{:lib/type :mbql/query
:lib/metadata results-metadata
:database (:id database-metadata)
:type :pipeline
:stages [(-> {:lib/type :mbql.stage/native
:native query}
lib.options/ensure-uuid)]}))
TODO -- this needs database metadata passed in as well .
(mu/defn saved-question-query :- ::lib.schema/query
"Convenience for creating a query from a Saved Question (i.e., a Card)."
[{query :dataset_query, metadata :result_metadata}]
(->query metadata query))
(mu/defn metadata :- [:maybe Metadata]
"Get the metadata associated with a `query`, if any."
[query :- ::lib.schema/query]
(:lib/metadata query))
|
35e9d5486928ec3daf6cc991b8476711aadea98536c382ee9ba213633119b573 | vehicle-lang/vehicle | DeBruijn.hs | # LANGUAGE GeneralizedNewtypeDeriving #
module Vehicle.Expr.DeBruijn
( DBBinding,
DBIndex (..),
DBLevel (..),
DBBinder,
DBArg,
DBType,
DBExpr,
DBDecl,
DBProg,
DBTelescope,
Substitution,
substituteDB,
substDBInto,
substDBIntoAtLevel,
substDBAll,
liftDBIndices,
underDBBinder,
dbLevelToIndex,
shiftDBIndex,
)
where
import Control.DeepSeq (NFData)
import Control.Monad.Reader (MonadReader (..), local, runReader)
import Data.Aeson (ToJSON)
import Data.Bifunctor (Bifunctor (..))
import Data.Hashable (Hashable (..))
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
import Vehicle.Prelude
import Vehicle.Syntax.AST
--------------------------------------------------------------------------------
-- Definitions
| A index pointing to the binder that the variable refers to ,
-- counting from the variable position upwards.
newtype DBIndex = DBIndex
{ unIndex :: Int
}
deriving (Eq, Ord, Num, Show, Generic)
instance NFData DBIndex
instance Hashable DBIndex
instance ToJSON DBIndex
instance Serialize DBIndex
instance Pretty DBIndex where
pretty i = "𝓲" <> pretty (unIndex i)
| level - represents how many binders deep we currently are .
( e.g. . f ( \x . x ) ) the variable ` f ` is at level 0 and the variable ` x `
is at level 1 .
-- When used as a variable refers to the binder at that level.
newtype DBLevel = DBLevel
{ unLevel :: Int
}
deriving (Eq, Ord, Num, Enum, Show, Generic)
instance NFData DBLevel
instance Hashable DBLevel
instance ToJSON DBLevel
instance Serialize DBLevel
instance Pretty DBLevel where
pretty l = "𝓵" <> pretty (unLevel l)
| The type of the data DeBruijn notation stores at binding sites .
type DBBinding = ()
| Converts a ` DBLevel ` x to a ` DBIndex ` given that we 're currently at
-- level `l`.
dbLevelToIndex :: DBLevel -> DBLevel -> DBIndex
dbLevelToIndex l x = DBIndex (unLevel l - unLevel x - 1)
shiftDBIndex :: DBIndex -> DBLevel -> DBIndex
shiftDBIndex i l = DBIndex (unIndex i + unLevel l)
--------------------------------------------------------------------------------
-- Expressions
An expression that uses DeBruijn index scheme for both binders and variables .
type DBBinder builtin = Binder DBBinding DBIndex builtin
type DBArg builtin = Arg DBBinding DBIndex builtin
type DBType builtin = DBExpr builtin
type DBExpr builtin = Expr DBBinding DBIndex builtin
type DBDecl builtin = Decl DBBinding DBIndex builtin
type DBProg builtin = Prog DBBinding DBIndex builtin
type DBTelescope builtin = [DBBinder builtin]
--------------------------------------------------------------------------------
-- Substitution
type Substitution value = DBIndex -> Either DBIndex value
class Substitutable value target | target -> value where
subst :: MonadReader (DBLevel, Substitution value) m => target -> m target
instance Substitutable expr expr => Substitutable expr (GenericArg expr) where
subst = traverse subst
instance Substitutable expr expr => Substitutable expr (GenericBinder binder expr) where
subst = traverse subst
instance Substitutable (DBExpr builtin) (DBExpr builtin) where
subst expr = case expr of
BoundVar p i -> do
(d, s) <- ask
return $
if unIndex i < unLevel d
then BoundVar p i
else case s (shiftDBIndex i (-d)) of
Left i' -> BoundVar p (shiftDBIndex i' d)
Right v -> if d > 0 then liftDBIndices d v else v
Universe {} -> return expr
Meta {} -> return expr
Hole {} -> return expr
Builtin {} -> return expr
FreeVar {} -> return expr
Ann p term typ -> Ann p <$> subst term <*> subst typ
App p fun args -> normApp p <$> subst fun <*> traverse subst args
Pi p binder res -> Pi p <$> traverse subst binder <*> underDBBinder (subst res)
Let p e1 binder e2 -> Let p <$> subst e1 <*> traverse subst binder <*> underDBBinder (subst e2)
Lam p binder e -> Lam p <$> traverse subst binder <*> underDBBinder (subst e)
Temporarily go under a binder , increasing the binding depth by one
-- and shifting the current state.
underDBBinder :: MonadReader (DBLevel, c) m => m a -> m a
underDBBinder = local (first (+ 1))
--------------------------------------------------------------------------------
-- Concrete operations
substituteDB :: DBLevel -> Substitution (DBExpr builtin) -> DBExpr builtin -> DBExpr builtin
substituteDB depth sub e = runReader (subst e) (depth, sub)
| Lift all indices that refer to environment variables by the
-- provided depth.
liftDBIndices ::
-- | number of levels to lift by
DBLevel ->
-- | target term to lift
DBExpr builtin ->
-- | lifted term
DBExpr builtin
liftDBIndices l = substituteDB 0 (\i -> Left (shiftDBIndex i l))
| aware substitution of one expression into another
substDBIntoAtLevel ::
forall builtin.
-- | The index of the variable of which to substitute
DBIndex ->
-- | expression to substitute
DBExpr builtin ->
-- | term to substitute into
DBExpr builtin ->
-- | the result of the substitution
DBExpr builtin
substDBIntoAtLevel level value = substituteDB 0 substVar
where
substVar :: DBIndex -> Either DBIndex (DBExpr builtin)
substVar v
| v == level = Right value
| v > level = Left (v - 1)
| otherwise = Left v
| aware substitution of one expression into another
substDBInto ::
-- | expression to substitute
DBExpr builtin ->
-- | term to substitute into
DBExpr builtin ->
-- | the result of the substitution
DBExpr builtin
substDBInto = substDBIntoAtLevel 0
substDBAll ::
DBLevel ->
(DBIndex -> Maybe DBIndex) ->
DBExpr builtin ->
DBExpr builtin
substDBAll depth sub = substituteDB depth (\v -> maybe (Left v) Left (sub v))
| null | https://raw.githubusercontent.com/vehicle-lang/vehicle/3a3548f9b48c3969212ccb51e954d4d4556ea815/vehicle/src/Vehicle/Expr/DeBruijn.hs | haskell | ------------------------------------------------------------------------------
Definitions
counting from the variable position upwards.
When used as a variable refers to the binder at that level.
level `l`.
------------------------------------------------------------------------------
Expressions
------------------------------------------------------------------------------
Substitution
and shifting the current state.
------------------------------------------------------------------------------
Concrete operations
provided depth.
| number of levels to lift by
| target term to lift
| lifted term
| The index of the variable of which to substitute
| expression to substitute
| term to substitute into
| the result of the substitution
| expression to substitute
| term to substitute into
| the result of the substitution | # LANGUAGE GeneralizedNewtypeDeriving #
module Vehicle.Expr.DeBruijn
( DBBinding,
DBIndex (..),
DBLevel (..),
DBBinder,
DBArg,
DBType,
DBExpr,
DBDecl,
DBProg,
DBTelescope,
Substitution,
substituteDB,
substDBInto,
substDBIntoAtLevel,
substDBAll,
liftDBIndices,
underDBBinder,
dbLevelToIndex,
shiftDBIndex,
)
where
import Control.DeepSeq (NFData)
import Control.Monad.Reader (MonadReader (..), local, runReader)
import Data.Aeson (ToJSON)
import Data.Bifunctor (Bifunctor (..))
import Data.Hashable (Hashable (..))
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
import Vehicle.Prelude
import Vehicle.Syntax.AST
| A index pointing to the binder that the variable refers to ,
newtype DBIndex = DBIndex
{ unIndex :: Int
}
deriving (Eq, Ord, Num, Show, Generic)
instance NFData DBIndex
instance Hashable DBIndex
instance ToJSON DBIndex
instance Serialize DBIndex
instance Pretty DBIndex where
pretty i = "𝓲" <> pretty (unIndex i)
| level - represents how many binders deep we currently are .
( e.g. . f ( \x . x ) ) the variable ` f ` is at level 0 and the variable ` x `
is at level 1 .
newtype DBLevel = DBLevel
{ unLevel :: Int
}
deriving (Eq, Ord, Num, Enum, Show, Generic)
instance NFData DBLevel
instance Hashable DBLevel
instance ToJSON DBLevel
instance Serialize DBLevel
instance Pretty DBLevel where
pretty l = "𝓵" <> pretty (unLevel l)
| The type of the data DeBruijn notation stores at binding sites .
type DBBinding = ()
| Converts a ` DBLevel ` x to a ` DBIndex ` given that we 're currently at
dbLevelToIndex :: DBLevel -> DBLevel -> DBIndex
dbLevelToIndex l x = DBIndex (unLevel l - unLevel x - 1)
shiftDBIndex :: DBIndex -> DBLevel -> DBIndex
shiftDBIndex i l = DBIndex (unIndex i + unLevel l)
An expression that uses DeBruijn index scheme for both binders and variables .
type DBBinder builtin = Binder DBBinding DBIndex builtin
type DBArg builtin = Arg DBBinding DBIndex builtin
type DBType builtin = DBExpr builtin
type DBExpr builtin = Expr DBBinding DBIndex builtin
type DBDecl builtin = Decl DBBinding DBIndex builtin
type DBProg builtin = Prog DBBinding DBIndex builtin
type DBTelescope builtin = [DBBinder builtin]
type Substitution value = DBIndex -> Either DBIndex value
class Substitutable value target | target -> value where
subst :: MonadReader (DBLevel, Substitution value) m => target -> m target
instance Substitutable expr expr => Substitutable expr (GenericArg expr) where
subst = traverse subst
instance Substitutable expr expr => Substitutable expr (GenericBinder binder expr) where
subst = traverse subst
instance Substitutable (DBExpr builtin) (DBExpr builtin) where
subst expr = case expr of
BoundVar p i -> do
(d, s) <- ask
return $
if unIndex i < unLevel d
then BoundVar p i
else case s (shiftDBIndex i (-d)) of
Left i' -> BoundVar p (shiftDBIndex i' d)
Right v -> if d > 0 then liftDBIndices d v else v
Universe {} -> return expr
Meta {} -> return expr
Hole {} -> return expr
Builtin {} -> return expr
FreeVar {} -> return expr
Ann p term typ -> Ann p <$> subst term <*> subst typ
App p fun args -> normApp p <$> subst fun <*> traverse subst args
Pi p binder res -> Pi p <$> traverse subst binder <*> underDBBinder (subst res)
Let p e1 binder e2 -> Let p <$> subst e1 <*> traverse subst binder <*> underDBBinder (subst e2)
Lam p binder e -> Lam p <$> traverse subst binder <*> underDBBinder (subst e)
Temporarily go under a binder , increasing the binding depth by one
underDBBinder :: MonadReader (DBLevel, c) m => m a -> m a
underDBBinder = local (first (+ 1))
substituteDB :: DBLevel -> Substitution (DBExpr builtin) -> DBExpr builtin -> DBExpr builtin
substituteDB depth sub e = runReader (subst e) (depth, sub)
| Lift all indices that refer to environment variables by the
liftDBIndices ::
DBLevel ->
DBExpr builtin ->
DBExpr builtin
liftDBIndices l = substituteDB 0 (\i -> Left (shiftDBIndex i l))
| aware substitution of one expression into another
substDBIntoAtLevel ::
forall builtin.
DBIndex ->
DBExpr builtin ->
DBExpr builtin ->
DBExpr builtin
substDBIntoAtLevel level value = substituteDB 0 substVar
where
substVar :: DBIndex -> Either DBIndex (DBExpr builtin)
substVar v
| v == level = Right value
| v > level = Left (v - 1)
| otherwise = Left v
| aware substitution of one expression into another
substDBInto ::
DBExpr builtin ->
DBExpr builtin ->
DBExpr builtin
substDBInto = substDBIntoAtLevel 0
substDBAll ::
DBLevel ->
(DBIndex -> Maybe DBIndex) ->
DBExpr builtin ->
DBExpr builtin
substDBAll depth sub = substituteDB depth (\v -> maybe (Left v) Left (sub v))
|
c963e42d9b5158db2224f61ba6044a8e66d8091045335b681f309ae027d5ba98 | gebi/jungerl | prfNet.erl | %%%-------------------------------------------------------------------
%%% File : prfNet.erl
Author : Mats < locmacr@mwlx084 >
Description : prf collector of net_kernel info
%%%
Created : 18 Oct 2005 by Mats < locmacr@mwlx084 >
%%%-------------------------------------------------------------------
-module(prfNet).
-export([collect/1]).
-include("prf.hrl").
returns { State , Data }
collect(State) -> {State, {?MODULE, data()}}.
data() ->
case catch net_kernel:nodes_info() of
{ok,L} -> L;
_ -> []
end.
| null | https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/prf/src/prfNet.erl | erlang | -------------------------------------------------------------------
File : prfNet.erl
------------------------------------------------------------------- | Author : Mats < locmacr@mwlx084 >
Description : prf collector of net_kernel info
Created : 18 Oct 2005 by Mats < locmacr@mwlx084 >
-module(prfNet).
-export([collect/1]).
-include("prf.hrl").
returns { State , Data }
collect(State) -> {State, {?MODULE, data()}}.
data() ->
case catch net_kernel:nodes_info() of
{ok,L} -> L;
_ -> []
end.
|
662f063dd5d551084602416f9451febd2824409d95f0c590b8ffbb624a9a6243 | gethop-dev/hydrogen.duct-template | routes.cljs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
;; file, You can obtain one at /
{{=<< >>=}}
(ns <<namespace>>.client.routes
(:require-macros [secretary.core :refer [defroute]])
(:import goog.History)
(:require <<#hydrogen-session?>>[clojure.spec.alpha :as s]
<</hydrogen-session?>>[goog.events]
[goog.history.EventType :as EventType]
[re-frame.core :as rf]
[secretary.core :as secretary]
[<<namespace>>.client.home :as home]
[<<namespace>>.client.hydrogen-demo.shop :as hydrogen-demo.shop]
[<<namespace>>.client.hydrogen-demo.shop-item :as hydrogen-demo.shop-item]<<#hydrogen-session?>>
[<<namespace>>.client.landing :as landing]
[<<namespace>>.client.session :as session]
[<<namespace>>.client.user :as user]
[<<namespace>>.client.util :as util]<</hydrogen-session?>>
[<<namespace>>.client.navigation :as navigation]))
(defn hook-browser-navigation! []
(doto (History.)
(goog.events/listen EventType/NAVIGATE #(secretary/dispatch! (.-token %)))
(.setEnabled true)))
(defn- compose-nav-evt
[direction [view-key & argv]]
{:pre [(#{:enter :leave} direction)]}
(let [evt-key (if (namespace view-key)
(keyword
(namespace view-key)
(str (name view-key) "." (name direction)))
(keyword
(str (name view-key) "." (name direction))))]
(vec (cons evt-key argv))))<<#hydrogen-session?>>
(def ^:const access-config-defaults
{:allow-unauthenticated? false
:allow-authenticated? true})
(def ^:const default-number-retries 10)
(def ^:const default-delay-time 250)
(defn config-exists? [db]
(get db :config))
(defn- ensure-data-event-fx
[{:keys [db session] :as cofx} _]
{:pre [(contains? cofx :session)
(s/valid? ::session/session-cofx-spec session)]}
(let [jwt-token (:jwt-token session)]
{:dispatch-n [(when (and jwt-token
(not (get db :user)))
[::user/fetch-user-data])
(when (and jwt-token
(not (get db :jwt-token)))
[::session/set-token-and-schedule-refresh])]}))
(rf/reg-event-fx
::ensure-data
[(rf/inject-cofx :session)]
ensure-data-event-fx)
(defn- deny-access [access-config jwt-token fx]
(rf/console :warn "access denied"
#js {:access-config access-config
:jwt-token jwt-token
:fx fx})
fx)
(defn- go-to*-event-fx
[{:keys [db session] :as cofx} [_ new-view access-config]]
{:pre [(contains? cofx :session)
(s/valid? ::session/session-cofx-spec session)]}
(rf/console :log "go-to*" #js {:session session
:new-view new-view
:access-config access-config})
(let [jwt-token (:jwt-token session)
access-config (merge access-config-defaults access-config)]
(cond
(and (not (:allow-authenticated? access-config)) jwt-token)
(deny-access access-config jwt-token {:redirect "/#/home"})
(and (not (:allow-unauthenticated? access-config)) (not jwt-token))<<#hydrogen-session-keycloak?>>
(deny-access access-config jwt-token {:dispatch [::session/user-login]})<</hydrogen-session-keycloak?>><<#hydrogen-session-cognito?>>
(deny-access access-config jwt-token {:redirect "/#/landing"})<</hydrogen-session-cognito?>>
:else
;; This part takes a vector for new view to navigate to.
That vector has min . arity 1 - a keyword identifying a view .
;; By convention we recommend using a namespaced one with 'view' as a name (e.g. ::shop/view).
;; The optional remaining arguments of that view vector are arguments to the view.
;;
Then this handler composes up to two event handlers and dispatches them :
;; - New view always is composed into ::*/view.enter event
;; - Previously active view (if present) is composed into ::*/view.leave event
;;
That said , each namespace introducing a new view need to have both : : and : : view.leave
;; events defined.
(let [enter-evt (compose-nav-evt :enter new-view)
leave-evt (when-let [active-view (:active-view db)]
(compose-nav-evt :leave active-view))]
{:dispatch-n [[::ensure-data]
leave-evt
enter-evt]}))))
(rf/reg-event-fx
:go-to*
[(rf/inject-cofx :session)]
go-to*-event-fx)<<#hydrogen-session-keycloak?>>
(defn- go-to-handler
"This rf event handler is responsible for making sure that
user is eligible for accessing a view.
Two conditions need to be met for this handler to let through:
1) Config needs to exists in appdb.
It's the only way to know if user is authenticated
2) Keycloak process cannot be ongoing.
Finishing that process is trivial so it should finish in time before
this handler reaches its retrials limit.
(see :init-and-authenticate effect)
This handler accepts second, optional, parameter to tune it more:
:allow-authenticated? - if false then it will throw an error for authenticated users
(`true` by default)
:allow-unauthenticated? - if false then it will throw an error for unauthenticated users
(`false` by default)
:remaining-retries - how many times this handler can be debounced until it meets
obligatory conditions. This is internal data and you probably don't want to touch it."
[{:keys [db]}
[_ evt & [{:keys [remaining-retries]
:or {remaining-retries default-number-retries}
:as access-config}]]]
(cond
(and
(config-exists? db)
(not (session/keycloak-process-ongoing?)))
{:dispatch [:go-to* evt access-config]}
(> remaining-retries 0)
{:dispatch-later
[{:ms default-delay-time
:dispatch [:go-to evt
(assoc access-config :remaining-retries (dec remaining-retries))]}]}
:else
{:dispatch [::util/generic-error ::route-access-error]}))<</hydrogen-session-keycloak?>><<#hydrogen-session-cognito?>>
(defn- go-to-handler
"This rf event handler is responsible for making sure that
user is eligible for accessing a view.
For this handler to let through a config needs to exists in appdb.
It's the only way to know if user is authenticated
This handler accepts second, optional, parameter to tune it more:
:allow-authenticated? - if false then it will throw an error for authenticated users
(`true` by default)
:allow-unauthenticated? - if false then it will throw an error for unauthenticated users
(`false` by default)
:remaining-retries - how many times this handler can be debounced until it meets
obligatory conditions. This is internal data and you probably don't want to touch it."
[{:keys [db]}
[_ evt & [{:keys [remaining-retries]
:or {remaining-retries default-number-retries}
:as access-config}]]]
(cond
(config-exists? db)
{:dispatch [:go-to* evt access-config]}
(> remaining-retries 0)
{:dispatch-later
[{:ms default-delay-time
:dispatch [:go-to evt
(assoc access-config :remaining-retries (dec remaining-retries))]}]}
:else
{:dispatch [::util/generic-error ::route-access-error]}))<</hydrogen-session-cognito?>>
(rf/reg-event-fx :go-to go-to-handler)
(defn app-routes []
(secretary/set-config! :prefix "#")
;; --------------------
;; define routes here
(defroute "/landing" []
(rf/dispatch [:go-to [::landing/view]
{:allow-authenticated? false :allow-unauthenticated? true}]))
(defroute "/home" []
(rf/dispatch [:go-to [::home/view]]))
(defroute "/shop" []
(rf/dispatch [:go-to [::hydrogen-demo.shop/view]]))
(defroute "/shop/:item-id" [item-id]
(rf/dispatch [:go-to [::hydrogen-demo.shop-item/view item-id]]))
(defroute "*" []
(navigation/redirect! "/#/landing"))
;; --------------------
(hook-browser-navigation!))<</hydrogen-session?>><<^hydrogen-session?>>
(defn- go-to-handler
"This handler takes a vector for new view to navigate to.
That vector has min. arity 1 - a keyword identifying a view.
By convention we recommend using a namespaced one with 'view' as a name (e.g. ::shop/view).
The optional remaining arguments of that view vector are arguments to the view.
Then this handler composes up to two event handlers and dispatches them:
- New view always is composed into ::*/view.enter event
- Previously active view (if present) is composed into ::*/view.leave event
That said, each namespace introducing a new view need to have both ::view.enter and ::view.leave
events defined."
[{:keys [db]} [_ new-view]]
(let [enter-evt (compose-nav-evt :enter new-view)
leave-evt (when-let [active-view (:active-view db)]
(compose-nav-evt :leave active-view))]
{:dispatch-n [leave-evt
enter-evt]}))
(rf/reg-event-fx :go-to go-to-handler)
(defn app-routes []
(secretary/set-config! :prefix "#")
;; --------------------
;; define routes here
(defroute "/home" []
(rf/dispatch [:go-to [::home/view]]))
(defroute "/shop" []
(rf/dispatch [:go-to [::hydrogen-demo.shop/view]]))
(defroute "/shop/:item-id" [item-id]
(rf/dispatch [:go-to [::hydrogen-demo.shop-item/view item-id]]))
(defroute "*" []
(navigation/redirect! "/#/home"))
;; --------------------
(hook-browser-navigation!))<</hydrogen-session?>>
| null | https://raw.githubusercontent.com/gethop-dev/hydrogen.duct-template/34d56aa499af1e673d9587b7da0cca2b126ff106/resources/core/cljs/routes.cljs | clojure | file, You can obtain one at /
This part takes a vector for new view to navigate to.
By convention we recommend using a namespaced one with 'view' as a name (e.g. ::shop/view).
The optional remaining arguments of that view vector are arguments to the view.
- New view always is composed into ::*/view.enter event
- Previously active view (if present) is composed into ::*/view.leave event
events defined.
--------------------
define routes here
--------------------
--------------------
define routes here
-------------------- | 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
{{=<< >>=}}
(ns <<namespace>>.client.routes
(:require-macros [secretary.core :refer [defroute]])
(:import goog.History)
(:require <<#hydrogen-session?>>[clojure.spec.alpha :as s]
<</hydrogen-session?>>[goog.events]
[goog.history.EventType :as EventType]
[re-frame.core :as rf]
[secretary.core :as secretary]
[<<namespace>>.client.home :as home]
[<<namespace>>.client.hydrogen-demo.shop :as hydrogen-demo.shop]
[<<namespace>>.client.hydrogen-demo.shop-item :as hydrogen-demo.shop-item]<<#hydrogen-session?>>
[<<namespace>>.client.landing :as landing]
[<<namespace>>.client.session :as session]
[<<namespace>>.client.user :as user]
[<<namespace>>.client.util :as util]<</hydrogen-session?>>
[<<namespace>>.client.navigation :as navigation]))
(defn hook-browser-navigation! []
(doto (History.)
(goog.events/listen EventType/NAVIGATE #(secretary/dispatch! (.-token %)))
(.setEnabled true)))
(defn- compose-nav-evt
[direction [view-key & argv]]
{:pre [(#{:enter :leave} direction)]}
(let [evt-key (if (namespace view-key)
(keyword
(namespace view-key)
(str (name view-key) "." (name direction)))
(keyword
(str (name view-key) "." (name direction))))]
(vec (cons evt-key argv))))<<#hydrogen-session?>>
(def ^:const access-config-defaults
{:allow-unauthenticated? false
:allow-authenticated? true})
(def ^:const default-number-retries 10)
(def ^:const default-delay-time 250)
(defn config-exists? [db]
(get db :config))
(defn- ensure-data-event-fx
[{:keys [db session] :as cofx} _]
{:pre [(contains? cofx :session)
(s/valid? ::session/session-cofx-spec session)]}
(let [jwt-token (:jwt-token session)]
{:dispatch-n [(when (and jwt-token
(not (get db :user)))
[::user/fetch-user-data])
(when (and jwt-token
(not (get db :jwt-token)))
[::session/set-token-and-schedule-refresh])]}))
(rf/reg-event-fx
::ensure-data
[(rf/inject-cofx :session)]
ensure-data-event-fx)
(defn- deny-access [access-config jwt-token fx]
(rf/console :warn "access denied"
#js {:access-config access-config
:jwt-token jwt-token
:fx fx})
fx)
(defn- go-to*-event-fx
[{:keys [db session] :as cofx} [_ new-view access-config]]
{:pre [(contains? cofx :session)
(s/valid? ::session/session-cofx-spec session)]}
(rf/console :log "go-to*" #js {:session session
:new-view new-view
:access-config access-config})
(let [jwt-token (:jwt-token session)
access-config (merge access-config-defaults access-config)]
(cond
(and (not (:allow-authenticated? access-config)) jwt-token)
(deny-access access-config jwt-token {:redirect "/#/home"})
(and (not (:allow-unauthenticated? access-config)) (not jwt-token))<<#hydrogen-session-keycloak?>>
(deny-access access-config jwt-token {:dispatch [::session/user-login]})<</hydrogen-session-keycloak?>><<#hydrogen-session-cognito?>>
(deny-access access-config jwt-token {:redirect "/#/landing"})<</hydrogen-session-cognito?>>
:else
That vector has min . arity 1 - a keyword identifying a view .
Then this handler composes up to two event handlers and dispatches them :
That said , each namespace introducing a new view need to have both : : and : : view.leave
(let [enter-evt (compose-nav-evt :enter new-view)
leave-evt (when-let [active-view (:active-view db)]
(compose-nav-evt :leave active-view))]
{:dispatch-n [[::ensure-data]
leave-evt
enter-evt]}))))
(rf/reg-event-fx
:go-to*
[(rf/inject-cofx :session)]
go-to*-event-fx)<<#hydrogen-session-keycloak?>>
(defn- go-to-handler
"This rf event handler is responsible for making sure that
user is eligible for accessing a view.
Two conditions need to be met for this handler to let through:
1) Config needs to exists in appdb.
It's the only way to know if user is authenticated
2) Keycloak process cannot be ongoing.
Finishing that process is trivial so it should finish in time before
this handler reaches its retrials limit.
(see :init-and-authenticate effect)
This handler accepts second, optional, parameter to tune it more:
:allow-authenticated? - if false then it will throw an error for authenticated users
(`true` by default)
:allow-unauthenticated? - if false then it will throw an error for unauthenticated users
(`false` by default)
:remaining-retries - how many times this handler can be debounced until it meets
obligatory conditions. This is internal data and you probably don't want to touch it."
[{:keys [db]}
[_ evt & [{:keys [remaining-retries]
:or {remaining-retries default-number-retries}
:as access-config}]]]
(cond
(and
(config-exists? db)
(not (session/keycloak-process-ongoing?)))
{:dispatch [:go-to* evt access-config]}
(> remaining-retries 0)
{:dispatch-later
[{:ms default-delay-time
:dispatch [:go-to evt
(assoc access-config :remaining-retries (dec remaining-retries))]}]}
:else
{:dispatch [::util/generic-error ::route-access-error]}))<</hydrogen-session-keycloak?>><<#hydrogen-session-cognito?>>
(defn- go-to-handler
"This rf event handler is responsible for making sure that
user is eligible for accessing a view.
For this handler to let through a config needs to exists in appdb.
It's the only way to know if user is authenticated
This handler accepts second, optional, parameter to tune it more:
:allow-authenticated? - if false then it will throw an error for authenticated users
(`true` by default)
:allow-unauthenticated? - if false then it will throw an error for unauthenticated users
(`false` by default)
:remaining-retries - how many times this handler can be debounced until it meets
obligatory conditions. This is internal data and you probably don't want to touch it."
[{:keys [db]}
[_ evt & [{:keys [remaining-retries]
:or {remaining-retries default-number-retries}
:as access-config}]]]
(cond
(config-exists? db)
{:dispatch [:go-to* evt access-config]}
(> remaining-retries 0)
{:dispatch-later
[{:ms default-delay-time
:dispatch [:go-to evt
(assoc access-config :remaining-retries (dec remaining-retries))]}]}
:else
{:dispatch [::util/generic-error ::route-access-error]}))<</hydrogen-session-cognito?>>
(rf/reg-event-fx :go-to go-to-handler)
(defn app-routes []
(secretary/set-config! :prefix "#")
(defroute "/landing" []
(rf/dispatch [:go-to [::landing/view]
{:allow-authenticated? false :allow-unauthenticated? true}]))
(defroute "/home" []
(rf/dispatch [:go-to [::home/view]]))
(defroute "/shop" []
(rf/dispatch [:go-to [::hydrogen-demo.shop/view]]))
(defroute "/shop/:item-id" [item-id]
(rf/dispatch [:go-to [::hydrogen-demo.shop-item/view item-id]]))
(defroute "*" []
(navigation/redirect! "/#/landing"))
(hook-browser-navigation!))<</hydrogen-session?>><<^hydrogen-session?>>
(defn- go-to-handler
"This handler takes a vector for new view to navigate to.
That vector has min. arity 1 - a keyword identifying a view.
By convention we recommend using a namespaced one with 'view' as a name (e.g. ::shop/view).
The optional remaining arguments of that view vector are arguments to the view.
Then this handler composes up to two event handlers and dispatches them:
- New view always is composed into ::*/view.enter event
- Previously active view (if present) is composed into ::*/view.leave event
That said, each namespace introducing a new view need to have both ::view.enter and ::view.leave
events defined."
[{:keys [db]} [_ new-view]]
(let [enter-evt (compose-nav-evt :enter new-view)
leave-evt (when-let [active-view (:active-view db)]
(compose-nav-evt :leave active-view))]
{:dispatch-n [leave-evt
enter-evt]}))
(rf/reg-event-fx :go-to go-to-handler)
(defn app-routes []
(secretary/set-config! :prefix "#")
(defroute "/home" []
(rf/dispatch [:go-to [::home/view]]))
(defroute "/shop" []
(rf/dispatch [:go-to [::hydrogen-demo.shop/view]]))
(defroute "/shop/:item-id" [item-id]
(rf/dispatch [:go-to [::hydrogen-demo.shop-item/view item-id]]))
(defroute "*" []
(navigation/redirect! "/#/home"))
(hook-browser-navigation!))<</hydrogen-session?>>
|
1302cb563a3d39d10c390f46b96f8d2826321e7e5971a5e31d36947bebb646c0 | PLTools/OCanren | test_noinjected.mli | val addo : int * int * int [@@noinjected]
| null | https://raw.githubusercontent.com/PLTools/OCanren/1ead64bde16b0eb339a6bf790ea871e19bbaccd0/regression_ppx/test_noinjected.mli | ocaml | val addo : int * int * int [@@noinjected]
| |
42c580cccf01e0c83e62e67044db9780c76a77e02b2a03a6a2ef6ccc51261a54 | fishcakez/sbroker | sbroker_app.erl | %%-------------------------------------------------------------------
%%
Copyright ( c ) 2016 , < >
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License. You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%%-------------------------------------------------------------------
@private
-module(sbroker_app).
-behaviour(application).
%% application API
-export([start/2]).
-export([stop/1]).
%% application API
start(_, _) ->
sbroker_sup:start_link().
stop(_) ->
ok.
| null | https://raw.githubusercontent.com/fishcakez/sbroker/10f7e3970d0a296fbf08b1d1a94c88979a7deb5e/src/sbroker_app.erl | erlang | -------------------------------------------------------------------
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,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
application API
application API | Copyright ( c ) 2016 , < >
This file is provided to you under the Apache License ,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@private
-module(sbroker_app).
-behaviour(application).
-export([start/2]).
-export([stop/1]).
start(_, _) ->
sbroker_sup:start_link().
stop(_) ->
ok.
|
93f47bd9761f27dd7421664afa3eb79c149e925dbfa1b47d936cbf4ff8f493f0 | dwayne/eopl3 | parser.test.rkt | #lang racket
(require "./parser.rkt")
(require rackunit)
(check-equal?
(parse "1")
(a-program (const-exp 1)))
(check-equal?
(parse "x")
(a-program (var-exp 'x)))
(check-equal?
(parse "-(5, y)")
(a-program (diff-exp (const-exp 5) (var-exp 'y))))
(check-equal?
(parse "zero?(z)")
(a-program (zero?-exp (var-exp 'z))))
(check-equal?
(parse "if zero?(2) then 0 else 1")
(a-program (if-exp (zero?-exp (const-exp 2))
(const-exp 0)
(const-exp 1))))
(check-equal?
(parse "let n=10 in -(n, 1)")
(a-program (let-exp 'n
(const-exp 10)
(diff-exp (var-exp 'n) (const-exp 1)))))
(check-equal?
(parse "proc (x) -(x, 1)")
(a-program (proc-exp 'x (diff-exp (var-exp 'x)
(const-exp 1)))))
(check-equal?
(parse "letrec f(x) = a in b")
(a-program (letrec-exp '(f)
'(x)
(list (var-exp 'a))
(var-exp 'b))))
(check-equal?
(parse "letrec f(x) = (g x) g(y) = y in (f 2)")
(a-program (letrec-exp '(f g)
'(x y)
(list
(call-exp (var-exp 'g)
(var-exp 'x))
(var-exp 'y))
(call-exp (var-exp 'f)
(const-exp 2)))))
(check-equal?
(parse "(f x)")
(a-program (call-exp (var-exp 'f)
(var-exp 'x))))
(check-equal?
(parse "begin 5; 4; 3 end")
(a-program (begin-exp
(const-exp 5)
(list
(const-exp 4)
(const-exp 3)))))
(check-equal?
(parse "set x = 1")
(a-program (assign-exp 'x (const-exp 1))))
(check-equal?
(parse "setdynamic n=10 during -(n, 1)")
(a-program (setdynamic-exp 'n
(const-exp 10)
(diff-exp (var-exp 'n) (const-exp 1)))))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/04-ch4/interpreters/racket/IMPLICIT-REFS-4.21/parser.test.rkt | racket | #lang racket
(require "./parser.rkt")
(require rackunit)
(check-equal?
(parse "1")
(a-program (const-exp 1)))
(check-equal?
(parse "x")
(a-program (var-exp 'x)))
(check-equal?
(parse "-(5, y)")
(a-program (diff-exp (const-exp 5) (var-exp 'y))))
(check-equal?
(parse "zero?(z)")
(a-program (zero?-exp (var-exp 'z))))
(check-equal?
(parse "if zero?(2) then 0 else 1")
(a-program (if-exp (zero?-exp (const-exp 2))
(const-exp 0)
(const-exp 1))))
(check-equal?
(parse "let n=10 in -(n, 1)")
(a-program (let-exp 'n
(const-exp 10)
(diff-exp (var-exp 'n) (const-exp 1)))))
(check-equal?
(parse "proc (x) -(x, 1)")
(a-program (proc-exp 'x (diff-exp (var-exp 'x)
(const-exp 1)))))
(check-equal?
(parse "letrec f(x) = a in b")
(a-program (letrec-exp '(f)
'(x)
(list (var-exp 'a))
(var-exp 'b))))
(check-equal?
(parse "letrec f(x) = (g x) g(y) = y in (f 2)")
(a-program (letrec-exp '(f g)
'(x y)
(list
(call-exp (var-exp 'g)
(var-exp 'x))
(var-exp 'y))
(call-exp (var-exp 'f)
(const-exp 2)))))
(check-equal?
(parse "(f x)")
(a-program (call-exp (var-exp 'f)
(var-exp 'x))))
(check-equal?
(parse "begin 5; 4; 3 end")
(a-program (begin-exp
(const-exp 5)
(list
(const-exp 4)
(const-exp 3)))))
(check-equal?
(parse "set x = 1")
(a-program (assign-exp 'x (const-exp 1))))
(check-equal?
(parse "setdynamic n=10 during -(n, 1)")
(a-program (setdynamic-exp 'n
(const-exp 10)
(diff-exp (var-exp 'n) (const-exp 1)))))
| |
610e793593aa91fb1c7cb8d2bfe7c618c8b22621c390fa44fcc5a094491fe30e | dmitryvk/sbcl-win32-threads | compiler.pure-cload.lisp | ;;;; miscellaneous tests of compiling toplevel forms
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
(in-package :cl-user)
;;; Exercise a compiler bug (by causing a call to ERROR).
;;;
;;; This bug was in sbcl-0.6.11.6.
(let ((a 1) (b 1))
(declare (type (mod 1000) a b))
(let ((tmp (= 10 (+ (incf a) (incf a) (incf b) (incf b)))))
(or tmp (error "TMP not true"))))
;;; Exercise a (byte-)compiler bug by causing a call to ERROR, not
;;; because the symbol isn't defined as a variable, but because
TYPE - ERROR in SB - KERNEL::OBJECT - NOT - TYPE - ERROR - HANDLER :
;;; 0 is not of type (OR FUNCTION SB-KERNEL:FDEFN).
;;; Correct behavior is to warn at compile time because the symbol
;;; isn't declared as a variable, but to set its SYMBOL-VALUE anyway.
;;;
;;; This bug was in sbcl-0.6.11.13.
(print (setq improperly-declared-var '(1 2)))
(assert (equal (symbol-value 'improperly-declared-var) '(1 2)))
(makunbound 'improperly-declared-var)
;;; This is a slightly different way of getting the same symptoms out
;;; of the sbcl-0.6.11.13 byte compiler bug.
(print (setq *print-level* *print-level*))
;;; PROGV with different numbers of variables and values
(let ((a 1))
(declare (special a))
(assert (equal (list a (progv '(a b) '(:a :b :c)
(assert (eq (symbol-value 'nil) nil))
(list (symbol-value 'a) (symbol-value 'b)))
a)
'(1 (:a :b) 1)))
(assert (equal (list a (progv '(a b) '(:a :b)
(assert (eq (symbol-value 'nil) nil))
(list (symbol-value 'a) (symbol-value 'b)))
a)
'(1 (:a :b) 1)))
(assert (not (boundp 'b))))
(let ((a 1) (b 2))
(declare (special a b))
(assert (equal (list a b (progv '(a b) '(:a)
(assert (eq (symbol-value 'nil) nil))
(assert (not (boundp 'b)))
(symbol-value 'a))
a b)
'(1 2 :a 1 2))))
;;; bug in LOOP, reported by ??? on c.l.l
(flet ((foo (l)
(loop for x in l
when (symbolp x) return x
while (numberp x)
collect (list x))))
(assert (equal (foo '(1 2 #\a 3)) '((1) (2))))
(assert (equal (foo '(1 2 x 3)) 'x)))
compiler failure found by randomized tortuter
(defun #:foo (a b c d)
(declare (type (integer 240 100434465) a)
(optimize (speed 3) (safety 1) (debug 1)))
(logxor
(if (ldb-test (byte 27 4) d)
-1
(max 55546856 -431))
(logorc2
(if (>= 0 b)
(if (> b c) (logandc2 c d) (if (> d 224002) 0 d))
(signum (logior c b)))
(logior a -1))))
(defun #:foo (b c)
(declare (type (integer -23228343 2) b)
(type (integer -115581022 512244512) c)
(optimize (speed 3) (safety 1) (debug 1)))
(* (* (logorc2 3 (deposit-field 4667947 (byte 14 26) b))
(deposit-field b (byte 25 27) -30424886))
(dpb b (byte 23 29) c)))
(defun #:foo (x y)
(declare (type (integer -1 1000000000000000000000000) x y)
(optimize speed))
(* x (* y x)))
(defun #:foo (b)
(declare (type (integer -290488443 2) b)
(optimize (speed 3) (safety 1) (debug 1)))
(let ((v3 (min -1720 b))) (max v3 (logcount (if (= v3 b) b b)))))
(defun #:foo (d)
(let ((v7 (flet ((%f16 () (labels ((%f3 () -8)) (%f3))))
(labels ((%f7 () (%f16))) d))))
132887443))
;;; RESULT-FORM in DO is not contained in the implicit TAGBODY
(assert (eq (handler-case (eval `(do ((x '(1 2 3) (cdr x)))
((endp x) (go :loop))
:loop
(unless x (return :bad))))
(error () :good))
:good))
(assert (eq (handler-case (eval `(do* ((x '(1 2 3) (cdr x)))
((endp x) (go :loop))
:loop
(unless x (return :bad))))
(error () :good))
:good))
bug 282
;;;
;;; Verify type checking policy in full calls: the callee is supposed
;;; to perform check, but the results should not be used before the
;;; check will be actually performed.
(locally
(declare (optimize (safety 3)))
(flet ((bar (f a)
(declare (type (simple-array (unsigned-byte 32) (*)) a))
(declare (type (function (fixnum)) f))
(funcall f (aref a 0))))
#-x86-64
(assert
(eval `(let ((n (1+ most-positive-fixnum)))
(if (not (typep n '(unsigned-byte 32)))
(warn 'style-warning
"~@<This test is written for platforms with ~
~@<(proper-subtypep 'fixnum '(unsigned-byte 32))~:@>.~:@>")
(block nil
(funcall ,#'bar
(lambda (x) (when (eql x n) (return t)))
(make-array 1 :element-type '(unsigned-byte 32)
:initial-element n))
nil)))))))
bug 261
(let ((x (list (the (values &optional fixnum) (eval '(values))))))
(assert (equal x '(nil))))
Bug 125 , reported by : Python did not preserve identity
;;; of closures.
(flet ((test-case (test-pred x)
(let ((func (lambda () x)))
(list (eq func func)
(funcall test-pred func func)
(delete func (list func))))))
(assert (equal '(t t nil) (funcall (eval #'test-case) #'eq 3))))
compiler failure reported by :
MAYBE - INFER - ITERATION - VAR - TYPE did not deal with types ( REAL * ( n ) ) .
(let ((s (loop for x from (- pi) below (floor (* 2 pi)) by (/ pi 75) count t)))
(assert (= s 219)))
| null | https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/tests/compiler.pure-cload.lisp | lisp | miscellaneous tests of compiling toplevel forms
more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
Exercise a compiler bug (by causing a call to ERROR).
This bug was in sbcl-0.6.11.6.
Exercise a (byte-)compiler bug by causing a call to ERROR, not
because the symbol isn't defined as a variable, but because
0 is not of type (OR FUNCTION SB-KERNEL:FDEFN).
Correct behavior is to warn at compile time because the symbol
isn't declared as a variable, but to set its SYMBOL-VALUE anyway.
This bug was in sbcl-0.6.11.13.
This is a slightly different way of getting the same symptoms out
of the sbcl-0.6.11.13 byte compiler bug.
PROGV with different numbers of variables and values
bug in LOOP, reported by ??? on c.l.l
RESULT-FORM in DO is not contained in the implicit TAGBODY
Verify type checking policy in full calls: the callee is supposed
to perform check, but the results should not be used before the
check will be actually performed.
of closures. |
This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
(in-package :cl-user)
(let ((a 1) (b 1))
(declare (type (mod 1000) a b))
(let ((tmp (= 10 (+ (incf a) (incf a) (incf b) (incf b)))))
(or tmp (error "TMP not true"))))
TYPE - ERROR in SB - KERNEL::OBJECT - NOT - TYPE - ERROR - HANDLER :
(print (setq improperly-declared-var '(1 2)))
(assert (equal (symbol-value 'improperly-declared-var) '(1 2)))
(makunbound 'improperly-declared-var)
(print (setq *print-level* *print-level*))
(let ((a 1))
(declare (special a))
(assert (equal (list a (progv '(a b) '(:a :b :c)
(assert (eq (symbol-value 'nil) nil))
(list (symbol-value 'a) (symbol-value 'b)))
a)
'(1 (:a :b) 1)))
(assert (equal (list a (progv '(a b) '(:a :b)
(assert (eq (symbol-value 'nil) nil))
(list (symbol-value 'a) (symbol-value 'b)))
a)
'(1 (:a :b) 1)))
(assert (not (boundp 'b))))
(let ((a 1) (b 2))
(declare (special a b))
(assert (equal (list a b (progv '(a b) '(:a)
(assert (eq (symbol-value 'nil) nil))
(assert (not (boundp 'b)))
(symbol-value 'a))
a b)
'(1 2 :a 1 2))))
(flet ((foo (l)
(loop for x in l
when (symbolp x) return x
while (numberp x)
collect (list x))))
(assert (equal (foo '(1 2 #\a 3)) '((1) (2))))
(assert (equal (foo '(1 2 x 3)) 'x)))
compiler failure found by randomized tortuter
(defun #:foo (a b c d)
(declare (type (integer 240 100434465) a)
(optimize (speed 3) (safety 1) (debug 1)))
(logxor
(if (ldb-test (byte 27 4) d)
-1
(max 55546856 -431))
(logorc2
(if (>= 0 b)
(if (> b c) (logandc2 c d) (if (> d 224002) 0 d))
(signum (logior c b)))
(logior a -1))))
(defun #:foo (b c)
(declare (type (integer -23228343 2) b)
(type (integer -115581022 512244512) c)
(optimize (speed 3) (safety 1) (debug 1)))
(* (* (logorc2 3 (deposit-field 4667947 (byte 14 26) b))
(deposit-field b (byte 25 27) -30424886))
(dpb b (byte 23 29) c)))
(defun #:foo (x y)
(declare (type (integer -1 1000000000000000000000000) x y)
(optimize speed))
(* x (* y x)))
(defun #:foo (b)
(declare (type (integer -290488443 2) b)
(optimize (speed 3) (safety 1) (debug 1)))
(let ((v3 (min -1720 b))) (max v3 (logcount (if (= v3 b) b b)))))
(defun #:foo (d)
(let ((v7 (flet ((%f16 () (labels ((%f3 () -8)) (%f3))))
(labels ((%f7 () (%f16))) d))))
132887443))
(assert (eq (handler-case (eval `(do ((x '(1 2 3) (cdr x)))
((endp x) (go :loop))
:loop
(unless x (return :bad))))
(error () :good))
:good))
(assert (eq (handler-case (eval `(do* ((x '(1 2 3) (cdr x)))
((endp x) (go :loop))
:loop
(unless x (return :bad))))
(error () :good))
:good))
bug 282
(locally
(declare (optimize (safety 3)))
(flet ((bar (f a)
(declare (type (simple-array (unsigned-byte 32) (*)) a))
(declare (type (function (fixnum)) f))
(funcall f (aref a 0))))
#-x86-64
(assert
(eval `(let ((n (1+ most-positive-fixnum)))
(if (not (typep n '(unsigned-byte 32)))
(warn 'style-warning
"~@<This test is written for platforms with ~
~@<(proper-subtypep 'fixnum '(unsigned-byte 32))~:@>.~:@>")
(block nil
(funcall ,#'bar
(lambda (x) (when (eql x n) (return t)))
(make-array 1 :element-type '(unsigned-byte 32)
:initial-element n))
nil)))))))
bug 261
(let ((x (list (the (values &optional fixnum) (eval '(values))))))
(assert (equal x '(nil))))
Bug 125 , reported by : Python did not preserve identity
(flet ((test-case (test-pred x)
(let ((func (lambda () x)))
(list (eq func func)
(funcall test-pred func func)
(delete func (list func))))))
(assert (equal '(t t nil) (funcall (eval #'test-case) #'eq 3))))
compiler failure reported by :
MAYBE - INFER - ITERATION - VAR - TYPE did not deal with types ( REAL * ( n ) ) .
(let ((s (loop for x from (- pi) below (floor (* 2 pi)) by (/ pi 75) count t)))
(assert (= s 219)))
|
edfa5d435f33cabe0b8c39454bc2e797d7fc68aef2fbf520ef9523e3d69b0966 | hiredman/clojurebot | derby.clj | (ns clojurebot.triples.derby
(:require [clojure.java.jdbc :as sql]
[clojure.tools.logging]))
(defmacro with-c [db & body]
`(sql/with-connection ~db
~@body))
(defn derby [name]
{:classname "org.apache.derby.jdbc.EmbeddedDriver"
:create true
:subname name
:subprotocol "derby"})
(declare db-name)
(defn create-store
[name]
(with-c (derby (db-name))
(sql/create-table
:triples
[:id :int "PRIMARY KEY" "GENERATED ALWAYS AS IDENTITY"]
[:subject "varchar(32670)"]
[:predicate "varchar(32670)"]
[:object "varchar(32670)"]
[:upper_subject "varchar(32670)"]
[:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"])))
(defn store-triple [{:keys [s p o]}]
(with-c (derby (db-name))
(sql/transaction
(sql/insert-values
:triples
[:subject :predicate :object :upper_subject]
[(.trim (str s)) (.trim (str p)) (.trim (str o))
(.toUpperCase (.trim (str s)))]))))
(defmulti query
(fn [s p o]
(cond
(and (list? s) (keyword? p) (keyword? o))
::like_subject-_-_
(and (not (keyword? s)) (not (keyword? p)) (keyword? o))
::subject-predicate-_
(and (keyword? s) (keyword? p) (not (keyword? o)))
::_-_-object
(and (keyword? s) (not (keyword? p)) (keyword? o))
::_-predicate-_
(and (not (keyword? s)) (keyword? p) (keyword? o))
::subject-_-_
(and (keyword? s) (keyword? p) (keyword? o))
::_-_-_
(and (keyword? s) (not (keyword? p)) (not (keyword? o)))
::_-predicate-object
:else
::subject-predicate-object)))
(defmethod query ::subject-_-_ [s p o]
(try
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples WHERE upper_subject = ?" (.toUpperCase s)]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::like_subject-_-_ [s p o]
(try
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples WHERE upper_subject LIKE ?"
(.toUpperCase (first s))]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::_-predicate-_ [s p o]
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples WHERE predicate = ?" p]
(doall res))))
(defmethod query ::subject-predicate-object [s p o]
(try
(with-c (derby (db-name))
(sql/with-query-results res
[(str "SELECT * FROM triples WHERE "
"predicate = ? AND "
"upper_subject = ? AND "
"object = ?")
p (.toUpperCase s) o]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::subject-predicate-_ [s p o]
(clojure.tools.logging/info "QUERY" s p o)
(try
(with-c (derby (db-name))
(sql/with-query-results res
[(str "SELECT * FROM triples WHERE "
"predicate = ? AND "
"upper_subject = ?")
p (.toUpperCase s)]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::_-predicate-object [s p o]
(clojure.tools.logging/info "QUERY" s p o)
(with-c (derby (db-name))
(sql/with-query-results res
[(str "SELECT * FROM triples WHERE "
"predicate = ? AND "
"object = ?")
p o]
(doall res))))
(defmethod query ::_-_-_ [s p o]
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples"]
(doall res))))
(defn delete [s p o]
(doseq [id (map :id (query s p o))]
(with-c (derby (db-name))
(sql/delete-rows :triples ["id = ?" id]))))
(defn string [{:keys [subject predicate object]}]
(if (.startsWith object "<reply>")
(.trim (subs object 7))
(format "%s %s %s" subject predicate object)))
(defn import-file [db file]
(binding [*in* (-> file java.io.File. java.io.FileReader.
java.io.PushbackReader.)]
(-> (map (fn [[s o]] {:s s :o o :p "is"}) (read))
((partial mapcat
(fn [x]
(if (-> x :o vector?)
(map #(assoc x :o %) (:o x))
[x]))))
((partial map #(doto % prn)))
((partial map (partial store-triple db)))
doall)))
(defn db-name []
(let [name (or (System/getProperty "clojurebot.db")
(str (System/getProperty "user.dir")
"/bot.db"))]
(when-not (.exists (java.io.File. name))
(create-store name))
name))
| null | https://raw.githubusercontent.com/hiredman/clojurebot/1e8bde92f2dd45bb7928d4db17de8ec48557ead1/clojurebot-facts/src/clojurebot/triples/derby.clj | clojure | (ns clojurebot.triples.derby
(:require [clojure.java.jdbc :as sql]
[clojure.tools.logging]))
(defmacro with-c [db & body]
`(sql/with-connection ~db
~@body))
(defn derby [name]
{:classname "org.apache.derby.jdbc.EmbeddedDriver"
:create true
:subname name
:subprotocol "derby"})
(declare db-name)
(defn create-store
[name]
(with-c (derby (db-name))
(sql/create-table
:triples
[:id :int "PRIMARY KEY" "GENERATED ALWAYS AS IDENTITY"]
[:subject "varchar(32670)"]
[:predicate "varchar(32670)"]
[:object "varchar(32670)"]
[:upper_subject "varchar(32670)"]
[:created_at :timestamp "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"])))
(defn store-triple [{:keys [s p o]}]
(with-c (derby (db-name))
(sql/transaction
(sql/insert-values
:triples
[:subject :predicate :object :upper_subject]
[(.trim (str s)) (.trim (str p)) (.trim (str o))
(.toUpperCase (.trim (str s)))]))))
(defmulti query
(fn [s p o]
(cond
(and (list? s) (keyword? p) (keyword? o))
::like_subject-_-_
(and (not (keyword? s)) (not (keyword? p)) (keyword? o))
::subject-predicate-_
(and (keyword? s) (keyword? p) (not (keyword? o)))
::_-_-object
(and (keyword? s) (not (keyword? p)) (keyword? o))
::_-predicate-_
(and (not (keyword? s)) (keyword? p) (keyword? o))
::subject-_-_
(and (keyword? s) (keyword? p) (keyword? o))
::_-_-_
(and (keyword? s) (not (keyword? p)) (not (keyword? o)))
::_-predicate-object
:else
::subject-predicate-object)))
(defmethod query ::subject-_-_ [s p o]
(try
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples WHERE upper_subject = ?" (.toUpperCase s)]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::like_subject-_-_ [s p o]
(try
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples WHERE upper_subject LIKE ?"
(.toUpperCase (first s))]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::_-predicate-_ [s p o]
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples WHERE predicate = ?" p]
(doall res))))
(defmethod query ::subject-predicate-object [s p o]
(try
(with-c (derby (db-name))
(sql/with-query-results res
[(str "SELECT * FROM triples WHERE "
"predicate = ? AND "
"upper_subject = ? AND "
"object = ?")
p (.toUpperCase s) o]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::subject-predicate-_ [s p o]
(clojure.tools.logging/info "QUERY" s p o)
(try
(with-c (derby (db-name))
(sql/with-query-results res
[(str "SELECT * FROM triples WHERE "
"predicate = ? AND "
"upper_subject = ?")
p (.toUpperCase s)]
(doall res)))
(catch Exception e
(println (db-name) s p o)
(throw e))))
(defmethod query ::_-predicate-object [s p o]
(clojure.tools.logging/info "QUERY" s p o)
(with-c (derby (db-name))
(sql/with-query-results res
[(str "SELECT * FROM triples WHERE "
"predicate = ? AND "
"object = ?")
p o]
(doall res))))
(defmethod query ::_-_-_ [s p o]
(with-c (derby (db-name))
(sql/with-query-results res
["SELECT * FROM triples"]
(doall res))))
(defn delete [s p o]
(doseq [id (map :id (query s p o))]
(with-c (derby (db-name))
(sql/delete-rows :triples ["id = ?" id]))))
(defn string [{:keys [subject predicate object]}]
(if (.startsWith object "<reply>")
(.trim (subs object 7))
(format "%s %s %s" subject predicate object)))
(defn import-file [db file]
(binding [*in* (-> file java.io.File. java.io.FileReader.
java.io.PushbackReader.)]
(-> (map (fn [[s o]] {:s s :o o :p "is"}) (read))
((partial mapcat
(fn [x]
(if (-> x :o vector?)
(map #(assoc x :o %) (:o x))
[x]))))
((partial map #(doto % prn)))
((partial map (partial store-triple db)))
doall)))
(defn db-name []
(let [name (or (System/getProperty "clojurebot.db")
(str (System/getProperty "user.dir")
"/bot.db"))]
(when-not (.exists (java.io.File. name))
(create-store name))
name))
| |
aaedefa643a1ad68e3797710ff4bac19a502e1abec9a6183872ffd8bfcf25383 | adventuring/tootsville.net | redirect.lisp | ;;;; -*- lisp -*-
;;;
src / redirect.lisp is part of
;;;
Copyright © 2008 - 2017 Bruce - Robert Pocock ; © 2018 - 2021 The
Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) .
;;;
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
;;; </>.
;;;
;;; You can reach CIWTA at /, or write to us at:
;;;
PO Box 23095
Oakland Park , FL 33307 - 3095
USA
;;;; redirect.lisp — HTTP redirect
(in-package :Tootsville)
(defun redirect-to/html-body (uri)
"Returns an octet array that gives a simple redirection link.
This is a silly legacy thing for ancient browsers that don't follow
a 3xx redirection or want to display something while they're
redirecting. In real life, it's rarely encountered by a real browser,
but sometimes caught by tools like curl or wget with certain settings."
(check-type uri www-uri)
(assert (not (some (curry #'char= #\") uri)) (uri)
"Unsafe to redirect to an URI containing literal ~
#\\Quotation_Mark characters (~a)" uri)
(concatenate 'string
"<!DOCTYPE html><html><title>Redirect</title><a href="
(string #\quotation_mark)
uri
(string #\quotation_mark)
">Redirected to "
uri
"</a></html>"))
(defun redirect-to (uri &optional (status 307))
"Redirect to another URI. Status code 307 for temporary, 301 or 308
for permanent (typically). (:TEMPORARY and :PERMANENT are accepted
for readability.)
As a side effect, provides an extremely skeletal HTML redirection page
via `REDIRECT-TO/HTML/BODY'."
(check-type uri www-uri "A URL string")
(check-type status (member 301 307 308 :temporary :permanent)
"An HTTP status code from among 301, 307, or 308")
(let ((status (if (numberp status) status
(ecase status (:temporary 307) (:permanent 308)))))
(list
status
`(:location ,uri
:x-redirected-by ,(romance-ii-program-name/version)
:content-type "text/html")
(redirect-to/html-body uri))))
(defmethod on-exception (code)
"Return error with code CODE
CODE is allowed to be a string beginning with an HTTP error code.
CODE must be a valid HTTP status code number, or 501 will be used.
"
(cond
((consp code)
(render-json code))
((wants-json-p)
(render-json `((:error . ,code))))
(t (let ((code-number (typecase code
(number code)
(string (parse-integer code :junk-allowed t))
(t 501))))
(unless (typep code-number 'http-response-status-number)
(setf code-number 501))
(redirect-to (format nil "/error/~d" code-number) :temporary)))))
| null | https://raw.githubusercontent.com/adventuring/tootsville.net/985c11a91dd1a21b77d7378362d86cf1c031b22c/src/redirect.lisp | lisp | -*- lisp -*-
© 2018 - 2021 The
either version 3 of
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.
License along with this program. If not, see
</>.
You can reach CIWTA at /, or write to us at:
redirect.lisp — HTTP redirect | src / redirect.lisp is part of
Corporation for Inter - World Tourism and Adventuring ( ciwta.org ) .
This program is Free Software : you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License
the License , or ( at your option ) any later version .
You should have received a copy of the GNU Affero General Public
PO Box 23095
Oakland Park , FL 33307 - 3095
USA
(in-package :Tootsville)
(defun redirect-to/html-body (uri)
"Returns an octet array that gives a simple redirection link.
This is a silly legacy thing for ancient browsers that don't follow
a 3xx redirection or want to display something while they're
redirecting. In real life, it's rarely encountered by a real browser,
but sometimes caught by tools like curl or wget with certain settings."
(check-type uri www-uri)
(assert (not (some (curry #'char= #\") uri)) (uri)
"Unsafe to redirect to an URI containing literal ~
#\\Quotation_Mark characters (~a)" uri)
(concatenate 'string
"<!DOCTYPE html><html><title>Redirect</title><a href="
(string #\quotation_mark)
uri
(string #\quotation_mark)
">Redirected to "
uri
"</a></html>"))
(defun redirect-to (uri &optional (status 307))
"Redirect to another URI. Status code 307 for temporary, 301 or 308
for permanent (typically). (:TEMPORARY and :PERMANENT are accepted
for readability.)
As a side effect, provides an extremely skeletal HTML redirection page
via `REDIRECT-TO/HTML/BODY'."
(check-type uri www-uri "A URL string")
(check-type status (member 301 307 308 :temporary :permanent)
"An HTTP status code from among 301, 307, or 308")
(let ((status (if (numberp status) status
(ecase status (:temporary 307) (:permanent 308)))))
(list
status
`(:location ,uri
:x-redirected-by ,(romance-ii-program-name/version)
:content-type "text/html")
(redirect-to/html-body uri))))
(defmethod on-exception (code)
"Return error with code CODE
CODE is allowed to be a string beginning with an HTTP error code.
CODE must be a valid HTTP status code number, or 501 will be used.
"
(cond
((consp code)
(render-json code))
((wants-json-p)
(render-json `((:error . ,code))))
(t (let ((code-number (typecase code
(number code)
(string (parse-integer code :junk-allowed t))
(t 501))))
(unless (typep code-number 'http-response-status-number)
(setf code-number 501))
(redirect-to (format nil "/error/~d" code-number) :temporary)))))
|
c1a0c54183f8e91ff97092f76920730a8329c84bc197a88e607104129e6b0cf8 | AbstractMachinesLab/caramel | daemonize.mli | (** Start, stop and synchronize with a daemon *)
(** The daemonize function will fork a daemon running the given function,
guaranteeing that at most one instance will run at any given time. The
daemon has to call a given callback to indicate that it has successfully
started, unlocking all other potential start attempts. This callback can be
given [daemon_info] that can be retrieved by the starting process and other
start attempts, e.g. the endpoint to contact the daemon on. *)
(** Result of a daemonization *)
type status =
| Started of
{ daemon_info : string
; pid : Pid.t
}
(** The daemon was started in the background with the given [daemon_info]
and [pid]. *)
| Already_running of
{ daemon_info : string
; pid : Pid.t
}
(** The daemon is already running in the background with the given
[daemon_info] and [pid]. *)
| Finished (** The daemon was run synchronously and exited. *)
val daemonize :
* The path to chdir to
-> ?foreground:bool
(** Whether to fork a daemon or run synchronously (defaults to [true]) *)
-> Path.t (** The path to the beacon file *)
-> ((daemon_info:string -> unit) -> unit) (** The daemon main routine *)
-> (status, string) Result.t
val stop : Path.t -> (unit, string) Result.t
| null | https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/vendor/stdune/daemonize.mli | ocaml | * Start, stop and synchronize with a daemon
* The daemonize function will fork a daemon running the given function,
guaranteeing that at most one instance will run at any given time. The
daemon has to call a given callback to indicate that it has successfully
started, unlocking all other potential start attempts. This callback can be
given [daemon_info] that can be retrieved by the starting process and other
start attempts, e.g. the endpoint to contact the daemon on.
* Result of a daemonization
* The daemon was started in the background with the given [daemon_info]
and [pid].
* The daemon is already running in the background with the given
[daemon_info] and [pid].
* The daemon was run synchronously and exited.
* Whether to fork a daemon or run synchronously (defaults to [true])
* The path to the beacon file
* The daemon main routine |
type status =
| Started of
{ daemon_info : string
; pid : Pid.t
}
| Already_running of
{ daemon_info : string
; pid : Pid.t
}
val daemonize :
* The path to chdir to
-> ?foreground:bool
-> (status, string) Result.t
val stop : Path.t -> (unit, string) Result.t
|
4e58e69fd05d82e943a19f4b40c47a78e448fa5dfe5d88e6db05a225fec19a01 | neeraj9/hello-erlang-rump | helloer_loader.erl | %%%-------------------------------------------------------------------
@author nsharma
( C ) 2016 ,
%%% @doc
%%%
%%% @end
Copyright ( c ) 2016 , < > .
%%% 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
" 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.
%%%-------------------------------------------------------------------
-module(helloer_loader).
-author("nsharma").
%% API
% This interface is used for non-standard testing where
% manual loading is required. For standard test
% environment or production this function is never
% invoked.
-export([start/0]).
-spec(start() ->
ok).
start() ->
application:start(syntax_tools),
application:start(compiler),
crypto is required by cowby and must be started
%% irrespective of whether https is used or not
application:start(crypto),
application:start(goldrush),
application:start(lager),
application:start(ranch),
application:start(cowlib),
application:start(cowboy),
application:start(helloer),
ok.
| null | https://raw.githubusercontent.com/neeraj9/hello-erlang-rump/304d2f0faaef64677de22d9a3495297e08d90a3f/apps/helloer/src/helloer_loader.erl | erlang | -------------------------------------------------------------------
@doc
@end
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.
-------------------------------------------------------------------
API
This interface is used for non-standard testing where
manual loading is required. For standard test
environment or production this function is never
invoked.
irrespective of whether https is used or not | @author nsharma
( C ) 2016 ,
Copyright ( c ) 2016 , < > .
" 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
-module(helloer_loader).
-author("nsharma").
-export([start/0]).
-spec(start() ->
ok).
start() ->
application:start(syntax_tools),
application:start(compiler),
crypto is required by cowby and must be started
application:start(crypto),
application:start(goldrush),
application:start(lager),
application:start(ranch),
application:start(cowlib),
application:start(cowboy),
application:start(helloer),
ok.
|
6bf804a6bd71c3c248ed1156f355b4df30695f8e3db904cb5032209e3ecf4940 | hiroshi-unno/coar | affineTerm.ml | open Core
open Common.Ext
open LogicOld
let is_affine term =
Term.funsyms_of term
|> Set.Poly.for_all
~f:(function T_int.Add | T_int.Sub | T_int.Neg | T_int.Mult | T_int.Int _-> true | _ -> false)
let coeff_of is_v t =
let ret = ref (None) in
Term.iter_term t ~f:( fun t ->
if Option.is_none !ret then
match t with
| Term.FunApp (T_int.Neg, [t], _) when is_v t -> ret := Some (-1)
| Term.FunApp (T_int.Mult, [t1; t2], _) when is_v t2 ->
ret := Some (Z.to_int @@ Value.int_of @@ Evaluator.eval_term t1)
| _ -> ());
match !ret with | Some (i) -> i | None -> 1
let extract_term_from_affine is_unused_term affine =
let ret =
Term.map_term affine
~f:(fun t11 -> if is_unused_term t11 then T_int.zero () else t11)
in
print_endline @@ sprintf " affine after : % s " @@ Term.str_of ret ;
let coeff = coeff_of (is_unused_term) affine in
(if coeff = 1 then Some (T_int.mk_neg ret)
else if coeff = -1 then Some ret
else None)
|> (Option.map ~f:(Evaluator.simplify_term))
|> (Option.map ~f:(Normalizer.normalize_term))
let extract_affine_term_from is_unused_term phi =
match Normalizer.normalize phi with
| Formula.Atom (Atom.App (Predicate.Psym T_bool.Eq, [t1; _], _), _)
when T_int.is_sint t1 && is_affine t1 ->
(try extract_term_from_affine is_unused_term t1 with _ -> None)
| _ -> None | null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/ast/affineTerm.ml | ocaml | open Core
open Common.Ext
open LogicOld
let is_affine term =
Term.funsyms_of term
|> Set.Poly.for_all
~f:(function T_int.Add | T_int.Sub | T_int.Neg | T_int.Mult | T_int.Int _-> true | _ -> false)
let coeff_of is_v t =
let ret = ref (None) in
Term.iter_term t ~f:( fun t ->
if Option.is_none !ret then
match t with
| Term.FunApp (T_int.Neg, [t], _) when is_v t -> ret := Some (-1)
| Term.FunApp (T_int.Mult, [t1; t2], _) when is_v t2 ->
ret := Some (Z.to_int @@ Value.int_of @@ Evaluator.eval_term t1)
| _ -> ());
match !ret with | Some (i) -> i | None -> 1
let extract_term_from_affine is_unused_term affine =
let ret =
Term.map_term affine
~f:(fun t11 -> if is_unused_term t11 then T_int.zero () else t11)
in
print_endline @@ sprintf " affine after : % s " @@ Term.str_of ret ;
let coeff = coeff_of (is_unused_term) affine in
(if coeff = 1 then Some (T_int.mk_neg ret)
else if coeff = -1 then Some ret
else None)
|> (Option.map ~f:(Evaluator.simplify_term))
|> (Option.map ~f:(Normalizer.normalize_term))
let extract_affine_term_from is_unused_term phi =
match Normalizer.normalize phi with
| Formula.Atom (Atom.App (Predicate.Psym T_bool.Eq, [t1; _], _), _)
when T_int.is_sint t1 && is_affine t1 ->
(try extract_term_from_affine is_unused_term t1 with _ -> None)
| _ -> None | |
ffc108ecde12054d9f7ef533516dd723d6017f864699c3d66fab6bef0bd74ce7 | spurious/sagittarius-scheme-mirror | paraffins.scm | ;;; PARAFFINS -- Compute how many paraffins exist with N carbon atoms.
(define (gen n)
(let* ((n/2 (quotient n 2))
(radicals (make-vector (+ n/2 1) '(H))))
(define (rads-of-size n)
(let loop1 ((ps
(three-partitions (- n 1)))
(lst
'()))
(if (null? ps)
lst
(let* ((p (car ps))
(nc1 (vector-ref p 0))
(nc2 (vector-ref p 1))
(nc3 (vector-ref p 2)))
(let loop2 ((rads1
(vector-ref radicals nc1))
(lst
(loop1 (cdr ps)
lst)))
(if (null? rads1)
lst
(let loop3 ((rads2
(if (= nc1 nc2)
rads1
(vector-ref radicals nc2)))
(lst
(loop2 (cdr rads1)
lst)))
(if (null? rads2)
lst
(let loop4 ((rads3
(if (= nc2 nc3)
rads2
(vector-ref radicals nc3)))
(lst
(loop3 (cdr rads2)
lst)))
(if (null? rads3)
lst
(cons (vector 'C
(car rads1)
(car rads2)
(car rads3))
(loop4 (cdr rads3)
lst))))))))))))
(define (bcp-generator j)
(if (odd? j)
'()
(let loop1 ((rads1
(vector-ref radicals (quotient j 2)))
(lst
'()))
(if (null? rads1)
lst
(let loop2 ((rads2
rads1)
(lst
(loop1 (cdr rads1)
lst)))
(if (null? rads2)
lst
(cons (vector 'BCP
(car rads1)
(car rads2))
(loop2 (cdr rads2)
lst))))))))
(define (ccp-generator j)
(let loop1 ((ps
(four-partitions (- j 1)))
(lst
'()))
(if (null? ps)
lst
(let* ((p (car ps))
(nc1 (vector-ref p 0))
(nc2 (vector-ref p 1))
(nc3 (vector-ref p 2))
(nc4 (vector-ref p 3)))
(let loop2 ((rads1
(vector-ref radicals nc1))
(lst
(loop1 (cdr ps)
lst)))
(if (null? rads1)
lst
(let loop3 ((rads2
(if (= nc1 nc2)
rads1
(vector-ref radicals nc2)))
(lst
(loop2 (cdr rads1)
lst)))
(if (null? rads2)
lst
(let loop4 ((rads3
(if (= nc2 nc3)
rads2
(vector-ref radicals nc3)))
(lst
(loop3 (cdr rads2)
lst)))
(if (null? rads3)
lst
(let loop5 ((rads4
(if (= nc3 nc4)
rads3
(vector-ref radicals nc4)))
(lst
(loop4 (cdr rads3)
lst)))
(if (null? rads4)
lst
(cons (vector 'CCP
(car rads1)
(car rads2)
(car rads3)
(car rads4))
(loop5 (cdr rads4)
lst))))))))))))))
(let loop ((i 1))
(if (> i n/2)
(vector (bcp-generator n)
(ccp-generator n))
(begin
(vector-set! radicals i (rads-of-size i))
(loop (+ i 1)))))))
(define (three-partitions m)
(let loop1 ((lst '())
(nc1 (quotient m 3)))
(if (< nc1 0)
lst
(let loop2 ((lst lst)
(nc2 (quotient (- m nc1) 2)))
(if (< nc2 nc1)
(loop1 lst
(- nc1 1))
(loop2 (cons (vector nc1 nc2 (- m (+ nc1 nc2))) lst)
(- nc2 1)))))))
(define (four-partitions m)
(let loop1 ((lst '())
(nc1 (quotient m 4)))
(if (< nc1 0)
lst
(let loop2 ((lst lst)
(nc2 (quotient (- m nc1) 3)))
(if (< nc2 nc1)
(loop1 lst
(- nc1 1))
(let ((start (max nc2 (- (quotient (+ m 1) 2) (+ nc1 nc2)))))
(let loop3 ((lst lst)
(nc3 (quotient (- m (+ nc1 nc2)) 2)))
(if (< nc3 start)
(loop2 lst (- nc2 1))
(loop3 (cons (vector nc1 nc2 nc3 (- m (+ nc1 (+ nc2 nc3)))) lst)
(- nc3 1))))))))))
(define (nb n)
(let ((x (gen n)))
(+ (length (vector-ref x 0))
(length (vector-ref x 1)))))
(define (main . args)
(run-benchmark
"paraffins"
paraffins-iters
(lambda (result) (equal? result 24894))
(lambda (n) (lambda () (nb n)))
17))
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/bench/gambit-benchmarks/paraffins.scm | scheme | PARAFFINS -- Compute how many paraffins exist with N carbon atoms. |
(define (gen n)
(let* ((n/2 (quotient n 2))
(radicals (make-vector (+ n/2 1) '(H))))
(define (rads-of-size n)
(let loop1 ((ps
(three-partitions (- n 1)))
(lst
'()))
(if (null? ps)
lst
(let* ((p (car ps))
(nc1 (vector-ref p 0))
(nc2 (vector-ref p 1))
(nc3 (vector-ref p 2)))
(let loop2 ((rads1
(vector-ref radicals nc1))
(lst
(loop1 (cdr ps)
lst)))
(if (null? rads1)
lst
(let loop3 ((rads2
(if (= nc1 nc2)
rads1
(vector-ref radicals nc2)))
(lst
(loop2 (cdr rads1)
lst)))
(if (null? rads2)
lst
(let loop4 ((rads3
(if (= nc2 nc3)
rads2
(vector-ref radicals nc3)))
(lst
(loop3 (cdr rads2)
lst)))
(if (null? rads3)
lst
(cons (vector 'C
(car rads1)
(car rads2)
(car rads3))
(loop4 (cdr rads3)
lst))))))))))))
(define (bcp-generator j)
(if (odd? j)
'()
(let loop1 ((rads1
(vector-ref radicals (quotient j 2)))
(lst
'()))
(if (null? rads1)
lst
(let loop2 ((rads2
rads1)
(lst
(loop1 (cdr rads1)
lst)))
(if (null? rads2)
lst
(cons (vector 'BCP
(car rads1)
(car rads2))
(loop2 (cdr rads2)
lst))))))))
(define (ccp-generator j)
(let loop1 ((ps
(four-partitions (- j 1)))
(lst
'()))
(if (null? ps)
lst
(let* ((p (car ps))
(nc1 (vector-ref p 0))
(nc2 (vector-ref p 1))
(nc3 (vector-ref p 2))
(nc4 (vector-ref p 3)))
(let loop2 ((rads1
(vector-ref radicals nc1))
(lst
(loop1 (cdr ps)
lst)))
(if (null? rads1)
lst
(let loop3 ((rads2
(if (= nc1 nc2)
rads1
(vector-ref radicals nc2)))
(lst
(loop2 (cdr rads1)
lst)))
(if (null? rads2)
lst
(let loop4 ((rads3
(if (= nc2 nc3)
rads2
(vector-ref radicals nc3)))
(lst
(loop3 (cdr rads2)
lst)))
(if (null? rads3)
lst
(let loop5 ((rads4
(if (= nc3 nc4)
rads3
(vector-ref radicals nc4)))
(lst
(loop4 (cdr rads3)
lst)))
(if (null? rads4)
lst
(cons (vector 'CCP
(car rads1)
(car rads2)
(car rads3)
(car rads4))
(loop5 (cdr rads4)
lst))))))))))))))
(let loop ((i 1))
(if (> i n/2)
(vector (bcp-generator n)
(ccp-generator n))
(begin
(vector-set! radicals i (rads-of-size i))
(loop (+ i 1)))))))
(define (three-partitions m)
(let loop1 ((lst '())
(nc1 (quotient m 3)))
(if (< nc1 0)
lst
(let loop2 ((lst lst)
(nc2 (quotient (- m nc1) 2)))
(if (< nc2 nc1)
(loop1 lst
(- nc1 1))
(loop2 (cons (vector nc1 nc2 (- m (+ nc1 nc2))) lst)
(- nc2 1)))))))
(define (four-partitions m)
(let loop1 ((lst '())
(nc1 (quotient m 4)))
(if (< nc1 0)
lst
(let loop2 ((lst lst)
(nc2 (quotient (- m nc1) 3)))
(if (< nc2 nc1)
(loop1 lst
(- nc1 1))
(let ((start (max nc2 (- (quotient (+ m 1) 2) (+ nc1 nc2)))))
(let loop3 ((lst lst)
(nc3 (quotient (- m (+ nc1 nc2)) 2)))
(if (< nc3 start)
(loop2 lst (- nc2 1))
(loop3 (cons (vector nc1 nc2 nc3 (- m (+ nc1 (+ nc2 nc3)))) lst)
(- nc3 1))))))))))
(define (nb n)
(let ((x (gen n)))
(+ (length (vector-ref x 0))
(length (vector-ref x 1)))))
(define (main . args)
(run-benchmark
"paraffins"
paraffins-iters
(lambda (result) (equal? result 24894))
(lambda (n) (lambda () (nb n)))
17))
|
ef2802fa2990fddc85d84eebbe3934288a2debff5895344772d38ebfa3017f11 | the-language/zKanren | goal.rkt | : MicroKanren with Constraints and noto
Copyright ( C ) 2017
;; 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 </>.
#lang racket
(provide
(struct-out goal)
new-goal
run-goal
(struct-out goal+)
noto
)
Goal = U AGoal
StatePatch → Goal
(define-syntax-rule (new-goal x) (goal (delay x)))
Promise StatePatch → Goal
(struct goal (v))
#| Goal → StatePatch |#
(define (run-goal x)
(force (goal-v x)))
U Constraint Goal → U Constraint Goal → Goal+
(struct goal+ (s u))
#| Goal+ → Goal+ |#
(define (noto g) (goal+ (goal+-s g) (goal+-u g)))
| null | https://raw.githubusercontent.com/the-language/zKanren/98df0700cb8935d1bde417ccb7f00b0417e00f6b/goal.rkt | racket | This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
along with this program. If not, see </>.
Goal → StatePatch
Goal+ → Goal+ | : MicroKanren with Constraints and noto
Copyright ( C ) 2017
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
You should have received a copy of the GNU Affero General Public License
#lang racket
(provide
(struct-out goal)
new-goal
run-goal
(struct-out goal+)
noto
)
Goal = U AGoal
StatePatch → Goal
(define-syntax-rule (new-goal x) (goal (delay x)))
Promise StatePatch → Goal
(struct goal (v))
(define (run-goal x)
(force (goal-v x)))
U Constraint Goal → U Constraint Goal → Goal+
(struct goal+ (s u))
(define (noto g) (goal+ (goal+-s g) (goal+-u g)))
|
0342241b61e34fc966eb9fb8eca706565d317d43500ddfa427db3293e03f2503 | fold-lang/fold | Pratt.ml | open Pure
open Base
open Lex
module M = Map.Make(Token)
type error =
| Empty
| Unexpected_end of { expected : token }
| Unexpected_token of { expected : token; actual : token }
| Failed_satisfy of token
| With_message of string
let error_to_string e =
match e with
| Empty -> "empty"
| Unexpected_end { expected } ->
"expected `%s` but input terminated" % Token.show expected
| Unexpected_token { expected; actual } ->
"expected `%s` but got `%s`" % (Token.show expected, Token.show actual)
| Failed_satisfy token ->
"token `%s` did not satisfy predicate" % Token.show token
| With_message msg ->
msg
(* Base parser *)
type 'a parser = state -> ('a * state, error) result
and state =
{ lexer : Lexer.t;
token : Token.t }
and 'a grammar = {
name : string;
data : 'a scope list;
atom : Token.t -> 'a prefix;
form : Token.t -> 'a infix option;
join : 'a list -> 'a;
}
and 'a scope = {
prefix : 'a prefix M.t;
infix : 'a infix M.t;
}
and 'a prefix = ('a grammar -> 'a parser)
and 'a infix = ('a grammar -> 'a -> 'a parser) * int
type 'a denotation =
| Prefix of Token.t * 'a prefix
| Infix of Token.t * 'a infix
Monad instance
let pure x = fun s -> Ok (x, s)
let (>>=) p f =
fun s ->
match p s with
| Ok (x, s') -> let p'= f x in p' s'
| Error msg -> Error msg
(* Alternative *)
let empty = fun g -> fun _state -> Error Empty
let (<|>) p1 p2 = fun state ->
match p1 state with
| Ok value -> Ok value
| Error _ -> p2 state
let get = fun s -> Ok (s, s)
let put s = fun _ -> Ok ((), s)
let zero = fun s -> Ok ((), s)
let combine p1 p2 =
p1 >>= fun x ->
p2 >>= fun y -> pure (x, y)
let default default p =
p <|> pure default
let optional p =
p >>= (fun () -> pure ()) |> default ()
let rec many p =
default []
(p >>= fun x ->
many p >>= fun xs ->
pure (x :: xs))
let rec some p =
combine p (many p)
let error e =
fun _state -> Error e
let state f =
get >>= fun s ->
let (a, s') = f s in
put s' >>= fun () -> pure a
let modify f =
state (fun s -> ((), f s))
let satisfy pred =
get >>= fun {token} ->
if pred token then pure token
else error (Failed_satisfy token)
let expect expected =
get >>= fun {token} ->
match token with
| actual when actual = expected -> pure actual
| actual when actual = Lex.eof -> error (Unexpected_end { expected })
| actual -> error (Unexpected_token { expected; actual })
let advance = fun state ->
modify (fun state -> { state with token = Lexer.read state.lexer })
state
let consume tok =
expect tok >>= fun _ -> advance
let exactly x =
expect x >>= fun x -> advance >>= fun () -> pure x
let any = fun state ->
satisfy (const true)
state
let one_of list =
satisfy (fun x -> List.mem x list)
let none_of list =
satisfy (fun x -> not (List.mem x list))
module Grammar = struct
type 'a t = 'a grammar
let dump self =
let string_of_prefix _ = "<prefix>" in
let string_of_infix (_, p) = "<infix %d>" % p in
List.iteri (fun i { prefix; infix } ->
print ("prefix [%d]:" % i);
M.iter (fun k v -> print ("%s => %s" % (Token.to_string k, string_of_prefix v))) prefix;
print ("infix[%d]:" % i);
M.iter (fun k v -> print ("%s => %s" % (Token.to_string k, string_of_infix v))) infix;
print "")
self.data
let invalid_prefix token =
let parse g =
let msg = if token = Lex.eof
then "unexpected end of input"
else "%s cannot be used in prefix position" % Token.to_string token in
(error (With_message msg)) in
parse
let invalid_infix ?(lbp = 0) token =
let parse g left =
let msg = "%s cannot be used in infix position" % Token.to_string token in
(error (With_message msg)) in
Some (parse, lbp)
let empty = {
name = "";
data = [];
atom = invalid_prefix;
form = (fun token -> None);
join = (fun xs -> fail "invalid join");
}
let empty_scope = {
infix = M.empty;
prefix = M.empty;
}
let define_infix token pareselet self =
let first, rest =
match self.data with
| [] -> empty_scope, []
| first::rest -> first, rest in
let first' = { first with infix = M.add token pareselet first.infix } in
{ self with data = first'::rest }
let define_prefix token pareselet self =
let first, rest =
match self.data with
| [] -> empty_scope, []
| first::rest -> first, rest in
let first' = { first with prefix = M.add token pareselet first.prefix } in
{ self with data = first'::rest }
let define rule self =
match rule with
| Prefix (token, parselet) -> define_prefix token parselet self
| Infix (token, parselet) -> define_infix token parselet self
let lookup_prefix token self =
let rec loop data =
match data with
| s :: rest -> Option.(M.find token s.prefix <|> lazy (loop rest))
| [] -> None in
loop self.data
let lookup_infix token self =
let rec loop data =
match data with
| s :: rest -> Option.(M.find token s.infix <|> lazy (loop rest))
| [] -> None in
loop self.data
let push_scope scope self =
{ self with data = scope :: self.data }
let new_scope self =
push_scope empty_scope self
let pop_scope self =
match self.data with
| [] -> self
| _ :: rest -> { self with data = rest }
let scope_of_list rules =
List.fold_left
(fun scope -> function
| Prefix (token, parselet) -> { scope with prefix = M.add token parselet scope.prefix }
| Infix (token, parselet) -> { scope with infix = M.add token parselet scope.infix })
empty_scope
rules
let init
?(join = (fun xs -> fail "invalid join"))
?(atom = invalid_prefix)
?(form = invalid_infix ~lbp:90)
name rules =
let scope = scope_of_list rules in
{ data = [scope]; atom; form; join; name }
| > ( fun g - > error ( With_message " unexpected end of file " ) )
(* |> define_infix Lex.eof ((fun g left -> error Empty), 0) *)
end
let run parser state =
match parser state with
| Ok (expr, _) -> Ok expr
| Error e -> Error e
(* join :: List a -> a
*
* - parse many
* - get prefix for token
* - parse prefix
* -
*
let rec many p =
default []
(p >>= fun x ->
print "y";
many p >>= fun xs ->
print "n";
pure (x :: xs))
* *)
(*
a ==> a
f a ==> (f a)
a + b ==> (+ a b)
f a + b ==> (+ (f a) b)
*)
until ( fun { token } - > has_infix token grammar ) p
(* Lookup on advance to reduce cost *)
let has_infix grammar token =
is_some Option.(Grammar.lookup_infix token grammar <|> lazy (grammar.form token))
let unless pred p =
get >>= fun { token } ->
if pred token then p
else error (Failed_satisfy token)
let rec until pred p =
get >>= fun { token } ->
if pred token then
p >>= fun x ->
until pred p >>= fun xs ->
pure (x :: xs)
else pure []
let parse_prefix grammar =
get >>= fun { token } ->
let rule = Grammar.lookup_prefix token grammar or lazy (grammar.atom token) in
rule grammar
let rec nud grammar rbp =
until (fun token -> not (has_infix grammar token)) (parse_prefix grammar) >>= function
| [] -> parse_prefix grammar >>= led grammar rbp (* everything is a valid prefix *)
| [x] -> led grammar rbp x
| xs -> led grammar rbp (grammar.join xs)
and led grammar rbp left =
get >>= fun { token } ->
match Option.(Grammar.lookup_infix token grammar <|> lazy (grammar.form token)) with
| Some (rule, lbp) ->
if lbp > rbp then
rule grammar left >>= led grammar rbp
else
pure left
| None -> error (With_message ("invalid infix: %s" % Token.to_string token))
let parse grammar =
nud grammar 0
let singleton x g =
advance >>= fun () ->
pure x
let delimiter str =
let parse g _ = error (With_message "unexpected delimiter") in
Infix (`Symbol str, (parse, 0))
let infix precedence str f =
let p g x =
advance >>= fun () ->
nud g precedence >>= fun y ->
pure (f x y) in
Infix (`Symbol str, (p, precedence))
let infixr precedence str f =
let p g x =
advance >>= fun () ->
nud g (precedence - 1) >>= fun y ->
pure (f x y) in
Infix (`Symbol str, (p, precedence))
let prefix str f =
let p g =
advance >>= fun () ->
parse g >>= fun x ->
pure (f x) in
Prefix (`Symbol str, p)
let postfix precedence str f =
let p g x =
advance >>= fun () ->
pure (f x) in
Infix (`Symbol str, (p, precedence))
let between s e f =
let p g =
advance >>= fun () ->
parse g >>= fun x ->
consume (`Symbol e) >>= fun () ->
pure (f x) in
Prefix (`Symbol s, p)
let concat token f =
let precedence = 90 in
let parse g x =
nud g precedence >>= fun y ->
pure (f x y) in
(parse, precedence)
| null | https://raw.githubusercontent.com/fold-lang/fold/78720f6295aa1fc99e18d853f8f1576b974e707f/src/Pratt.ml | ocaml | Base parser
Alternative
|> define_infix Lex.eof ((fun g left -> error Empty), 0)
join :: List a -> a
*
* - parse many
* - get prefix for token
* - parse prefix
* -
*
let rec many p =
default []
(p >>= fun x ->
print "y";
many p >>= fun xs ->
print "n";
pure (x :: xs))
*
a ==> a
f a ==> (f a)
a + b ==> (+ a b)
f a + b ==> (+ (f a) b)
Lookup on advance to reduce cost
everything is a valid prefix | open Pure
open Base
open Lex
module M = Map.Make(Token)
type error =
| Empty
| Unexpected_end of { expected : token }
| Unexpected_token of { expected : token; actual : token }
| Failed_satisfy of token
| With_message of string
let error_to_string e =
match e with
| Empty -> "empty"
| Unexpected_end { expected } ->
"expected `%s` but input terminated" % Token.show expected
| Unexpected_token { expected; actual } ->
"expected `%s` but got `%s`" % (Token.show expected, Token.show actual)
| Failed_satisfy token ->
"token `%s` did not satisfy predicate" % Token.show token
| With_message msg ->
msg
type 'a parser = state -> ('a * state, error) result
and state =
{ lexer : Lexer.t;
token : Token.t }
and 'a grammar = {
name : string;
data : 'a scope list;
atom : Token.t -> 'a prefix;
form : Token.t -> 'a infix option;
join : 'a list -> 'a;
}
and 'a scope = {
prefix : 'a prefix M.t;
infix : 'a infix M.t;
}
and 'a prefix = ('a grammar -> 'a parser)
and 'a infix = ('a grammar -> 'a -> 'a parser) * int
type 'a denotation =
| Prefix of Token.t * 'a prefix
| Infix of Token.t * 'a infix
Monad instance
let pure x = fun s -> Ok (x, s)
let (>>=) p f =
fun s ->
match p s with
| Ok (x, s') -> let p'= f x in p' s'
| Error msg -> Error msg
let empty = fun g -> fun _state -> Error Empty
let (<|>) p1 p2 = fun state ->
match p1 state with
| Ok value -> Ok value
| Error _ -> p2 state
let get = fun s -> Ok (s, s)
let put s = fun _ -> Ok ((), s)
let zero = fun s -> Ok ((), s)
let combine p1 p2 =
p1 >>= fun x ->
p2 >>= fun y -> pure (x, y)
let default default p =
p <|> pure default
let optional p =
p >>= (fun () -> pure ()) |> default ()
let rec many p =
default []
(p >>= fun x ->
many p >>= fun xs ->
pure (x :: xs))
let rec some p =
combine p (many p)
let error e =
fun _state -> Error e
let state f =
get >>= fun s ->
let (a, s') = f s in
put s' >>= fun () -> pure a
let modify f =
state (fun s -> ((), f s))
let satisfy pred =
get >>= fun {token} ->
if pred token then pure token
else error (Failed_satisfy token)
let expect expected =
get >>= fun {token} ->
match token with
| actual when actual = expected -> pure actual
| actual when actual = Lex.eof -> error (Unexpected_end { expected })
| actual -> error (Unexpected_token { expected; actual })
let advance = fun state ->
modify (fun state -> { state with token = Lexer.read state.lexer })
state
let consume tok =
expect tok >>= fun _ -> advance
let exactly x =
expect x >>= fun x -> advance >>= fun () -> pure x
let any = fun state ->
satisfy (const true)
state
let one_of list =
satisfy (fun x -> List.mem x list)
let none_of list =
satisfy (fun x -> not (List.mem x list))
module Grammar = struct
type 'a t = 'a grammar
let dump self =
let string_of_prefix _ = "<prefix>" in
let string_of_infix (_, p) = "<infix %d>" % p in
List.iteri (fun i { prefix; infix } ->
print ("prefix [%d]:" % i);
M.iter (fun k v -> print ("%s => %s" % (Token.to_string k, string_of_prefix v))) prefix;
print ("infix[%d]:" % i);
M.iter (fun k v -> print ("%s => %s" % (Token.to_string k, string_of_infix v))) infix;
print "")
self.data
let invalid_prefix token =
let parse g =
let msg = if token = Lex.eof
then "unexpected end of input"
else "%s cannot be used in prefix position" % Token.to_string token in
(error (With_message msg)) in
parse
let invalid_infix ?(lbp = 0) token =
let parse g left =
let msg = "%s cannot be used in infix position" % Token.to_string token in
(error (With_message msg)) in
Some (parse, lbp)
let empty = {
name = "";
data = [];
atom = invalid_prefix;
form = (fun token -> None);
join = (fun xs -> fail "invalid join");
}
let empty_scope = {
infix = M.empty;
prefix = M.empty;
}
let define_infix token pareselet self =
let first, rest =
match self.data with
| [] -> empty_scope, []
| first::rest -> first, rest in
let first' = { first with infix = M.add token pareselet first.infix } in
{ self with data = first'::rest }
let define_prefix token pareselet self =
let first, rest =
match self.data with
| [] -> empty_scope, []
| first::rest -> first, rest in
let first' = { first with prefix = M.add token pareselet first.prefix } in
{ self with data = first'::rest }
let define rule self =
match rule with
| Prefix (token, parselet) -> define_prefix token parselet self
| Infix (token, parselet) -> define_infix token parselet self
let lookup_prefix token self =
let rec loop data =
match data with
| s :: rest -> Option.(M.find token s.prefix <|> lazy (loop rest))
| [] -> None in
loop self.data
let lookup_infix token self =
let rec loop data =
match data with
| s :: rest -> Option.(M.find token s.infix <|> lazy (loop rest))
| [] -> None in
loop self.data
let push_scope scope self =
{ self with data = scope :: self.data }
let new_scope self =
push_scope empty_scope self
let pop_scope self =
match self.data with
| [] -> self
| _ :: rest -> { self with data = rest }
let scope_of_list rules =
List.fold_left
(fun scope -> function
| Prefix (token, parselet) -> { scope with prefix = M.add token parselet scope.prefix }
| Infix (token, parselet) -> { scope with infix = M.add token parselet scope.infix })
empty_scope
rules
let init
?(join = (fun xs -> fail "invalid join"))
?(atom = invalid_prefix)
?(form = invalid_infix ~lbp:90)
name rules =
let scope = scope_of_list rules in
{ data = [scope]; atom; form; join; name }
| > ( fun g - > error ( With_message " unexpected end of file " ) )
end
let run parser state =
match parser state with
| Ok (expr, _) -> Ok expr
| Error e -> Error e
until ( fun { token } - > has_infix token grammar ) p
let has_infix grammar token =
is_some Option.(Grammar.lookup_infix token grammar <|> lazy (grammar.form token))
let unless pred p =
get >>= fun { token } ->
if pred token then p
else error (Failed_satisfy token)
let rec until pred p =
get >>= fun { token } ->
if pred token then
p >>= fun x ->
until pred p >>= fun xs ->
pure (x :: xs)
else pure []
let parse_prefix grammar =
get >>= fun { token } ->
let rule = Grammar.lookup_prefix token grammar or lazy (grammar.atom token) in
rule grammar
let rec nud grammar rbp =
until (fun token -> not (has_infix grammar token)) (parse_prefix grammar) >>= function
| [x] -> led grammar rbp x
| xs -> led grammar rbp (grammar.join xs)
and led grammar rbp left =
get >>= fun { token } ->
match Option.(Grammar.lookup_infix token grammar <|> lazy (grammar.form token)) with
| Some (rule, lbp) ->
if lbp > rbp then
rule grammar left >>= led grammar rbp
else
pure left
| None -> error (With_message ("invalid infix: %s" % Token.to_string token))
let parse grammar =
nud grammar 0
let singleton x g =
advance >>= fun () ->
pure x
let delimiter str =
let parse g _ = error (With_message "unexpected delimiter") in
Infix (`Symbol str, (parse, 0))
let infix precedence str f =
let p g x =
advance >>= fun () ->
nud g precedence >>= fun y ->
pure (f x y) in
Infix (`Symbol str, (p, precedence))
let infixr precedence str f =
let p g x =
advance >>= fun () ->
nud g (precedence - 1) >>= fun y ->
pure (f x y) in
Infix (`Symbol str, (p, precedence))
let prefix str f =
let p g =
advance >>= fun () ->
parse g >>= fun x ->
pure (f x) in
Prefix (`Symbol str, p)
let postfix precedence str f =
let p g x =
advance >>= fun () ->
pure (f x) in
Infix (`Symbol str, (p, precedence))
let between s e f =
let p g =
advance >>= fun () ->
parse g >>= fun x ->
consume (`Symbol e) >>= fun () ->
pure (f x) in
Prefix (`Symbol s, p)
let concat token f =
let precedence = 90 in
let parse g x =
nud g precedence >>= fun y ->
pure (f x y) in
(parse, precedence)
|
c38f9d952d70952b000f25366ff0cdf2b899429acf9b4d2358815a00d955358e | PrincetonUniversity/lucid | Span.mli | type t =
{ fname : string
; start : int
; finish : int
; spid : int
}
[@@deriving show, ord]
val extend : t -> t -> t
val default : t
val to_string : t -> string
| null | https://raw.githubusercontent.com/PrincetonUniversity/lucid/dc51a0f781e8f1edb7e9689203fdf57daa7ffd10/src/lib/frontend/datastructures/Span.mli | ocaml | type t =
{ fname : string
; start : int
; finish : int
; spid : int
}
[@@deriving show, ord]
val extend : t -> t -> t
val default : t
val to_string : t -> string
| |
1b78bc0d4539dc7a39ed7e9dd318c08142cf57d81c7aac1010e97991f2a79d88 | huangjs/cl | zhbmv.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(let* ((one (f2cl-lib:cmplx 1.0 0.0)) (zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) one)
(type (f2cl-lib:complex16) zero)
(ignorable one zero))
(defun zhbmv (uplo n k alpha a lda x incx beta y incy)
(declare (type (array f2cl-lib:complex16 (*)) y x a)
(type (f2cl-lib:complex16) beta alpha)
(type (f2cl-lib:integer4) incy incx lda k n)
(type (simple-array character (*)) uplo))
(f2cl-lib:with-multi-array-data
((uplo character uplo-%data% uplo-%offset%)
(a f2cl-lib:complex16 a-%data% a-%offset%)
(x f2cl-lib:complex16 x-%data% x-%offset%)
(y f2cl-lib:complex16 y-%data% y-%offset%))
(prog ((i 0) (info 0) (ix 0) (iy 0) (j 0) (jx 0) (jy 0) (kplus1 0) (kx 0)
(ky 0) (l 0) (temp1 #C(0.0 0.0)) (temp2 #C(0.0 0.0)))
(declare (type (f2cl-lib:integer4) i info ix iy j jx jy kplus1 kx ky l)
(type (f2cl-lib:complex16) temp1 temp2))
(setf info 0)
(cond
((and (not (lsame uplo "U")) (not (lsame uplo "L")))
(setf info 1))
((< n 0)
(setf info 2))
((< k 0)
(setf info 3))
((< lda (f2cl-lib:int-add k 1))
(setf info 6))
((= incx 0)
(setf info 8))
((= incy 0)
(setf info 11)))
(cond
((/= info 0)
(xerbla "ZHBMV " info)
(go end_label)))
(if (or (= n 0) (and (= alpha zero) (= beta one))) (go end_label))
(cond
((> incx 0)
(setf kx 1))
(t
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incx)))))
(cond
((> incy 0)
(setf ky 1))
(t
(setf ky
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incy)))))
(cond
((/= beta one)
(cond
((= incy 1)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
zero)
label10)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)))
label20)))))
(t
(setf iy ky)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
zero)
(setf iy (f2cl-lib:int-add iy incy))
label30)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)))
(setf iy (f2cl-lib:int-add iy incy))
label40))))))))
(if (= alpha zero) (go end_label))
(cond
((lsame uplo "U")
(setf kplus1 (f2cl-lib:int-add k 1))
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label50))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))
label60)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf ix kx)
(setf iy ky)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
label70))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
(cond
((> j k)
(setf kx (f2cl-lib:int-add kx incx))
(setf ky (f2cl-lib:int-add ky incy))))
label80)))))
(t
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%)))))
(setf l (f2cl-lib:int-sub 1 j))
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label90))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* alpha temp2)))
label100)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%)))))
(setf l (f2cl-lib:int-sub 1 j))
(setf ix jx)
(setf iy jy)
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
label110))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
label120))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zhbmv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-array character (1))
(fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
| null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/share/lapack/blas/zhbmv.lisp | lisp | Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
(in-package :blas)
(let* ((one (f2cl-lib:cmplx 1.0 0.0)) (zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) one)
(type (f2cl-lib:complex16) zero)
(ignorable one zero))
(defun zhbmv (uplo n k alpha a lda x incx beta y incy)
(declare (type (array f2cl-lib:complex16 (*)) y x a)
(type (f2cl-lib:complex16) beta alpha)
(type (f2cl-lib:integer4) incy incx lda k n)
(type (simple-array character (*)) uplo))
(f2cl-lib:with-multi-array-data
((uplo character uplo-%data% uplo-%offset%)
(a f2cl-lib:complex16 a-%data% a-%offset%)
(x f2cl-lib:complex16 x-%data% x-%offset%)
(y f2cl-lib:complex16 y-%data% y-%offset%))
(prog ((i 0) (info 0) (ix 0) (iy 0) (j 0) (jx 0) (jy 0) (kplus1 0) (kx 0)
(ky 0) (l 0) (temp1 #C(0.0 0.0)) (temp2 #C(0.0 0.0)))
(declare (type (f2cl-lib:integer4) i info ix iy j jx jy kplus1 kx ky l)
(type (f2cl-lib:complex16) temp1 temp2))
(setf info 0)
(cond
((and (not (lsame uplo "U")) (not (lsame uplo "L")))
(setf info 1))
((< n 0)
(setf info 2))
((< k 0)
(setf info 3))
((< lda (f2cl-lib:int-add k 1))
(setf info 6))
((= incx 0)
(setf info 8))
((= incy 0)
(setf info 11)))
(cond
((/= info 0)
(xerbla "ZHBMV " info)
(go end_label)))
(if (or (= n 0) (and (= alpha zero) (= beta one))) (go end_label))
(cond
((> incx 0)
(setf kx 1))
(t
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incx)))))
(cond
((> incy 0)
(setf ky 1))
(t
(setf ky
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incy)))))
(cond
((/= beta one)
(cond
((= incy 1)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
zero)
label10)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(i)
((1 *))
y-%offset%)))
label20)))))
(t
(setf iy ky)
(cond
((= beta zero)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
zero)
(setf iy (f2cl-lib:int-add iy incy))
label30)))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* beta
(f2cl-lib:fref y-%data%
(iy)
((1 *))
y-%offset%)))
(setf iy (f2cl-lib:int-add iy incy))
label40))))))))
(if (= alpha zero) (go end_label))
(cond
((lsame uplo "U")
(setf kplus1 (f2cl-lib:int-add k 1))
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label50))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))
label60)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf ix kx)
(setf iy ky)
(setf l (f2cl-lib:int-sub kplus1 j))
(f2cl-lib:fdo (i
(max (the f2cl-lib:integer4 1)
(the f2cl-lib:integer4
(f2cl-lib:int-add j
(f2cl-lib:int-sub
k))))
(f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
label70))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(kplus1 j)
((1 lda) (1 *))
a-%offset%)))
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
(cond
((> j k)
(setf kx (f2cl-lib:int-add kx incx))
(setf ky (f2cl-lib:int-add ky incy))))
label80)))))
(t
(cond
((and (= incx 1) (= incy 1))
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%)))))
(setf l (f2cl-lib:int-sub 1 j))
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
label90))
(setf (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (j) ((1 *)) y-%offset%)
(* alpha temp2)))
label100)))
(t
(setf jx kx)
(setf jy ky)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp1
(* alpha
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)))
(setf temp2 zero)
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:dble
(f2cl-lib:fref a-%data%
(1 j)
((1 lda) (1 *))
a-%offset%)))))
(setf l (f2cl-lib:int-sub 1 j))
(setf ix jx)
(setf iy jy)
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i
(min (the f2cl-lib:integer4 n)
(the f2cl-lib:integer4
(f2cl-lib:int-add j k))))
nil)
(tagbody
(setf ix (f2cl-lib:int-add ix incx))
(setf iy (f2cl-lib:int-add iy incy))
(setf (f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(+
(f2cl-lib:fref y-%data% (iy) ((1 *)) y-%offset%)
(* temp1
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))))
(setf temp2
(+ temp2
(*
(f2cl-lib:dconjg
(f2cl-lib:fref a-%data%
((f2cl-lib:int-add l i) j)
((1 lda) (1 *))
a-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
label110))
(setf (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(+ (f2cl-lib:fref y-%data% (jy) ((1 *)) y-%offset%)
(* alpha temp2)))
(setf jx (f2cl-lib:int-add jx incx))
(setf jy (f2cl-lib:int-add jy incy))
label120))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zhbmv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-array character (1))
(fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::complex16)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
|
c1f213619cd3ed2e66bd24c0ab93ac53e0bfccd461ca1739d2ab970f6793bd33 | skypher/cl-store | custom.lisp | -*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Base : 10 -*-
;; See the file LICENCE for licence information.
(in-package :cl-store)
; special floats
(defun create-float-values (value &rest codes)
"Returns a alist of special float to float code mappings."
(sb-int:with-float-traps-masked (:overflow :invalid)
(let ((neg-inf (expt value 3)))
(mapcar 'cons
(list (expt (abs value) 2)
neg-inf
(/ neg-inf neg-inf))
codes))))
;; Custom structure storing
(defstore-cl-store (obj structure-object stream)
(output-type-code +structure-object-code+ stream)
(store-type-object obj stream))
(defrestore-cl-store (structure-object stream)
(restore-type-object stream))
| null | https://raw.githubusercontent.com/skypher/cl-store/8fbdb07810fee42b1e8be3fe268a5ab9226befb9/sbcl/custom.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 -*-
See the file LICENCE for licence information.
special floats
Custom structure storing |
(in-package :cl-store)
(defun create-float-values (value &rest codes)
"Returns a alist of special float to float code mappings."
(sb-int:with-float-traps-masked (:overflow :invalid)
(let ((neg-inf (expt value 3)))
(mapcar 'cons
(list (expt (abs value) 2)
neg-inf
(/ neg-inf neg-inf))
codes))))
(defstore-cl-store (obj structure-object stream)
(output-type-code +structure-object-code+ stream)
(store-type-object obj stream))
(defrestore-cl-store (structure-object stream)
(restore-type-object stream))
|
43bf410b8c750bdad84436fb82aaa695899f890150d4ff7b3b25b1c81cfcc437 | toyokumo/tarayo | helper.clj | (ns helper
(:import
(com.dumbster.smtp
SimpleSmtpServer)))
(def test-message
{:from ""
:to ""
:subject "hello"
:body "world"})
(defmacro with-test-smtp-server
[[server-sym port-sym] & body]
`(with-open [~server-sym (SimpleSmtpServer/start SimpleSmtpServer/AUTO_SMTP_PORT)]
(let [~port-sym (.getPort ~server-sym)]
~@body)))
| null | https://raw.githubusercontent.com/toyokumo/tarayo/f9b10b85b7bc1a188d808c3955e258916cd0b38a/benchmark/helper/helper.clj | clojure | (ns helper
(:import
(com.dumbster.smtp
SimpleSmtpServer)))
(def test-message
{:from ""
:to ""
:subject "hello"
:body "world"})
(defmacro with-test-smtp-server
[[server-sym port-sym] & body]
`(with-open [~server-sym (SimpleSmtpServer/start SimpleSmtpServer/AUTO_SMTP_PORT)]
(let [~port-sym (.getPort ~server-sym)]
~@body)))
| |
59be4ba721417a0b6d6be7e92ca173040c83f1012ba562e2e6f7b148645a3c72 | naoiwata/sicp | q2.01.scm | ;;
;; @author naoiwata
SICP Chapter2
question 2.1
;;
(add-load-path "." :relative)
(load "pages/2.1.1.scm")
(define (make-rat n d)
(let
((g (gcd n d))
(s (if (< d 0) -1 1)))
(cons
(* s (/ n g))
(* s (/ d g)))))
; test
(define (test1) (make-rat -3 1))
(define (test2) (make-rat 1 -3))
(newline)
(print-rat (test1))
(print-rat (test2)) ; -1/3
; END | null | https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter2/q2.01.scm | scheme |
@author naoiwata
test
-1/3
END | SICP Chapter2
question 2.1
(add-load-path "." :relative)
(load "pages/2.1.1.scm")
(define (make-rat n d)
(let
((g (gcd n d))
(s (if (< d 0) -1 1)))
(cons
(* s (/ n g))
(* s (/ d g)))))
(define (test1) (make-rat -3 1))
(define (test2) (make-rat 1 -3))
(newline)
(print-rat (test1))
|
6d6aeffcfa0c71d924f59a4682f2ac5099775fcaca3dd9192f0fe1980df8ade2 | papachan/data-covid19-colombia | core.cljs | (ns frontend.core
(:require [re-frame.core :as re-frame]
[reagent.core :as reagent]
[reagent.dom :as rd]
[frontend.events :as events]
[frontend.views :as views :refer [home]]))
(defn ^:dev/after-load mount-root []
(re-frame/clear-subscription-cache!)
(let [root-el (.getElementById js/document "app")]
(rd/unmount-component-at-node root-el)
(rd/render [home] root-el)))
(defn stop []
;; stop is called before any code is reloaded
;; this is controlled by :before-load in the config
(.log js/console "stop"))
(defn ^:export init []
;; init is called ONCE when the page loads
;; this is called in the index.html and must be exported
;; so it is available even in :advanced release builds
(re-frame/dispatch-sync [::events/initialize-db])
(re-frame/dispatch-sync [::events/load-data])
(re-frame/dispatch-sync [::events/load-deaths])
(re-frame/dispatch-sync [::events/load-recovered])
(re-frame/dispatch-sync [::events/load-max-case])
(re-frame/dispatch-sync [::events/load-covid-tests])
(re-frame/dispatch-sync [::events/load-timeseries])
(mount-root))
| null | https://raw.githubusercontent.com/papachan/data-covid19-colombia/e7e8f72336a0ad9d7d0561332dd1ce8248bfe7e4/src/cljs/frontend/core.cljs | clojure | stop is called before any code is reloaded
this is controlled by :before-load in the config
init is called ONCE when the page loads
this is called in the index.html and must be exported
so it is available even in :advanced release builds | (ns frontend.core
(:require [re-frame.core :as re-frame]
[reagent.core :as reagent]
[reagent.dom :as rd]
[frontend.events :as events]
[frontend.views :as views :refer [home]]))
(defn ^:dev/after-load mount-root []
(re-frame/clear-subscription-cache!)
(let [root-el (.getElementById js/document "app")]
(rd/unmount-component-at-node root-el)
(rd/render [home] root-el)))
(defn stop []
(.log js/console "stop"))
(defn ^:export init []
(re-frame/dispatch-sync [::events/initialize-db])
(re-frame/dispatch-sync [::events/load-data])
(re-frame/dispatch-sync [::events/load-deaths])
(re-frame/dispatch-sync [::events/load-recovered])
(re-frame/dispatch-sync [::events/load-max-case])
(re-frame/dispatch-sync [::events/load-covid-tests])
(re-frame/dispatch-sync [::events/load-timeseries])
(mount-root))
|
b2087e2b51f36048a05aa4df4ca5f6f71c7030a03247063ff9b818153cc99807 | avik-das/garlic | let.scm | (define a 4)
(display
(let ((a 1)
(b 2))
(+ a b))) (newline)
(display a) (newline)
; The current binding should be available in its own definition in order to
; allow for recursion.
(display
(let ((fac (lambda (n) (if (= n 0) 1 (* n (fac (- n 1))) )) ))
(fac 5)) ) (newline)
; Again, we hoist definitions inside the let body, as well as multiple
; statements.
(let ((hello "hello"))
(display hello)
(display " ")
(display world)
(newline)
(define world "world"))
| null | https://raw.githubusercontent.com/avik-das/garlic/5545f5a70f33c2ff9ec449ef66e6acc7881419dc/test/success/let.scm | scheme | The current binding should be available in its own definition in order to
allow for recursion.
Again, we hoist definitions inside the let body, as well as multiple
statements. | (define a 4)
(display
(let ((a 1)
(b 2))
(+ a b))) (newline)
(display a) (newline)
(display
(let ((fac (lambda (n) (if (= n 0) 1 (* n (fac (- n 1))) )) ))
(fac 5)) ) (newline)
(let ((hello "hello"))
(display hello)
(display " ")
(display world)
(newline)
(define world "world"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.