_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
|
---|---|---|---|---|---|---|---|---|
625e1ac57f67eb82c17a627cb547a19e2c15baad1272f8312f222ef62f9b13bf | fisxoj/coo | plugin.lisp | (defpackage :coo.plugin
(:use :cl :alexandria)
(:export #:initialize-plugins
#:config
#:metadata-for-symbol))
(in-package :coo.plugin)
(defvar *plugin* nil
"The active plugin in hooks. A string.")
(defun initialize-plugins ()
(coo.config:get-value "plugins"))
(defun config (key &optional default)
(assert (not (null *plugin*)) nil "config called with *plugin* unbound.")
(when-let ((plugins (coo.config:get-value "plugins")))
(when-let ((plugin-config (gethash *plugin* plugins)))
(gethash key plugin-config default))))
(defun find-hook-in-plugin (hook)
(find-symbol hook (find-package (format nil "COO.PLUGINS.~:@(~a~)" *plugin*))))
(defun metadata-for-symbol (system node)
(when (coo.config:get-value "plugins")
(with-output-to-string (out)
(loop for plugin being the hash-key of (coo.config:get-value "plugins")
do (let ((*plugin* plugin))
(funcall (find-hook-in-plugin "METADATA") out system node))))))
| null | https://raw.githubusercontent.com/fisxoj/coo/ef43d6ddfa1749b850bd31b88eeddff680e7a2ca/src/plugin.lisp | lisp | (defpackage :coo.plugin
(:use :cl :alexandria)
(:export #:initialize-plugins
#:config
#:metadata-for-symbol))
(in-package :coo.plugin)
(defvar *plugin* nil
"The active plugin in hooks. A string.")
(defun initialize-plugins ()
(coo.config:get-value "plugins"))
(defun config (key &optional default)
(assert (not (null *plugin*)) nil "config called with *plugin* unbound.")
(when-let ((plugins (coo.config:get-value "plugins")))
(when-let ((plugin-config (gethash *plugin* plugins)))
(gethash key plugin-config default))))
(defun find-hook-in-plugin (hook)
(find-symbol hook (find-package (format nil "COO.PLUGINS.~:@(~a~)" *plugin*))))
(defun metadata-for-symbol (system node)
(when (coo.config:get-value "plugins")
(with-output-to-string (out)
(loop for plugin being the hash-key of (coo.config:get-value "plugins")
do (let ((*plugin* plugin))
(funcall (find-hook-in-plugin "METADATA") out system node))))))
|
|
a82f7face6c95a0356f288f25db70e689998a26a83afdca5cf5950cbe5c9655d | e-wrks/edh | Control.hs | module Language.Edh.Control where
import Control.Concurrent.STM
import Control.Exception
import Control.Monad.State.Strict (State)
import qualified Data.Char as Char
import Data.Dynamic (Dynamic, toDyn)
import qualified Data.HashMap.Strict as Map
import qualified Data.List as L
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Data.Void (Void)
import Text.Megaparsec
( ParseErrorBundle,
ParsecT,
SourcePos (sourceColumn, sourceLine, sourceName),
errorBundlePretty,
unPos,
)
import Prelude
type ModuleName = Text
type ModuleFile = Text
data OpSymSrc = OpSymSrc !OpSymbol !SrcRange
deriving (Eq)
instance Show OpSymSrc where
show (OpSymSrc sym _) = show sym
type OpSymbol = Text
data OpFixity = InfixL | InfixR | Infix
deriving (Eq)
instance Show OpFixity where
show InfixL = "infixl"
show InfixR = "infixr"
show Infix = "infix"
type Precedence = Int
type OpDeclLoc = Text
-- | Source document
--
-- absolute local (though possibly network mounted) file path if started with
' / ' , otherwise should be valid URI
newtype SrcDoc = SrcDoc Text
deriving (Eq, Show)
-- | Source position
in LSP convention , i.e. no document locator
data SrcPos = SrcPos
in LSP convention , i.e. zero based
src'line :: !Int,
in LSP convention , i.e. zero based
src'char :: !Int
}
deriving (Eq, Show)
instance Ord SrcPos where
compare (SrcPos !x'l !x'c) (SrcPos !y'l !y'c) = case compare x'l y'l of
EQ -> compare x'c y'c
!conclusion -> conclusion
beginningSrcPos :: SrcPos
beginningSrcPos = SrcPos 0 0
-- | Source range
in LSP convention , i.e. no document locator
data SrcRange = SrcRange
in LSP convention , i.e. zero based
src'start :: {-# UNPACK #-} !SrcPos,
in LSP convention , i.e. zero based
src'end :: {-# UNPACK #-} !SrcPos
}
deriving (Eq, Show)
-- | compare a position to a range, return 'EQ' when the position is within the
range , or ' LT ' when before it , ' GT ' when after it .
srcPosCmp2Range :: SrcPos -> SrcRange -> Ordering
srcPosCmp2Range !p (SrcRange !start !end) = case compare p start of
LT -> LT
EQ -> EQ
GT ->
if src'line end < 0
then EQ -- special infinite end
else case compare p end of
LT -> EQ
end position of a range is inclusive per VSCode word pick
GT -> GT
zeroSrcRange :: SrcRange
zeroSrcRange = SrcRange beginningSrcPos beginningSrcPos
noSrcRange :: SrcRange
noSrcRange = SrcRange (SrcPos (-1) (-1)) (SrcPos (-1) (-1))
prettySrcPos :: SrcDoc -> SrcPos -> Text
prettySrcPos (SrcDoc !file) (SrcPos !line !char)
| line <= 0 && char <= 0 =
file
| otherwise =
file <> ":" <> T.pack (show $ 1 + line) <> ":"
<> T.pack
(show $ 1 + char)
prettySrcRange :: SrcDoc -> SrcRange -> Text
prettySrcRange (SrcDoc !file) (SrcRange (SrcPos !start'line !start'char) (SrcPos !end'line !end'char))
| end'line <= 0 && end'char <= 0 =
file
| end'line == start'line && end'char == start'char =
file <> ":" <> T.pack (show $ 1 + start'line) <> ":"
<> T.pack
(show $ 1 + start'char)
| otherwise =
file
<> ":"
<> T.pack (show $ 1 + start'line)
<> ":"
<> T.pack (show $ 1 + start'char)
<> "-"
<> T.pack (show $ 1 + end'line)
<> ":"
<> T.pack (show $ 1 + end'char)
-- | Source location
data SrcLoc = SrcLoc
{ src'doc :: !SrcDoc,
src'range :: !SrcRange
}
deriving (Eq, Show)
prettySrcLoc :: SrcLoc -> Text
prettySrcLoc (SrcLoc !doc !range) = prettySrcRange doc range
lspSrcPosFromParsec :: SourcePos -> SrcPos
lspSrcPosFromParsec !sp =
SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1)
lspSrcLocFromParsec :: SourcePos -> SrcPos -> SrcLoc
lspSrcLocFromParsec !sp !end =
SrcLoc (SrcDoc $ T.pack $ sourceName sp) $
SrcRange
(SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1))
end
lspSrcRangeFromParsec :: SourcePos -> SrcPos -> SrcRange
lspSrcRangeFromParsec !sp !end =
SrcRange
(SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1))
end
lspSrcRangeFromParsec' :: SrcPos -> SourcePos -> SrcRange
lspSrcRangeFromParsec' !start !sp =
SrcRange
start
(SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1))
lspSrcRangeFromParsec'' :: SourcePos -> SourcePos -> SrcRange
lspSrcRangeFromParsec'' !start !end =
SrcRange
(SrcPos (unPos (sourceLine start) - 1) (unPos (sourceColumn start) - 1))
(SrcPos (unPos (sourceLine end) - 1) (unPos (sourceColumn end) - 1))
data EdhParserState = EdhParserState
{ -- global dict for operator info
edh'parser'op'dict :: !GlobalOpDict,
end of last lexeme
edh'parser'lexeme'end'pos :: !SrcPos,
edh'parser'lexeme'end'offset :: !Int
}
data GlobalOpDict = GlobalOpDict
{ -- | precedence & fixity of known operators
operator'declarations ::
Map.HashMap OpSymbol (OpFixity, Precedence, OpDeclLoc),
-- | operators with non-standard character(s) in their symbol
-- invariant: ascendingly sorted,
-- so parsing against this list should attempt in reverse order
quaint'operators :: [OpSymbol]
}
lookupOpFromDict ::
OpSymbol -> GlobalOpDict -> Maybe (OpFixity, Precedence, OpDeclLoc)
lookupOpFromDict !sym (GlobalOpDict !decls _) = Map.lookup sym decls
insertOpIntoDict ::
OpSymbol -> (OpFixity, Precedence, OpDeclLoc) -> GlobalOpDict -> GlobalOpDict
insertOpIntoDict !sym !decl (GlobalOpDict !decls !quaint'ops) =
GlobalOpDict (Map.insert sym decl decls) $
if contain'nonstd'op'char
then L.insert sym quaint'ops
else quaint'ops
where
contain'nonstd'op'char :: Bool
contain'nonstd'op'char = isJust $ T.find (not . isOperatorChar) sym
mergeOpDict :: TVar GlobalOpDict -> GlobalOpDict -> GlobalOpDict -> IO ()
mergeOpDict
godv
(GlobalOpDict !base'decls !base'quaint'ops)
(GlobalOpDict !decls !quaint'ops) =
if Map.null declUpds && L.null quaintUpds
shortcircuit without touching the TVar
else atomically $
modifyTVar' godv $ \(GlobalOpDict !curr'decls !curr'quaint'ops) ->
GlobalOpDict
( if Map.null declUpds
then curr'decls
else Map.union curr'decls declUpds
)
( if L.null quaintUpds
then curr'quaint'ops
else L.sort $ curr'quaint'ops ++ quaintUpds
)
where
declUpds = Map.difference decls base'decls
quaintUpds =
if L.length quaint'ops <= L.length base'quaint'ops
then [] -- shortcircuit since we know both are sorted and no removal
else quaint'ops L.\\ base'quaint'ops
isOperatorChar :: Char -> Bool
isOperatorChar !c =
if c < toEnum 128
then c `elem` ("=!@#$%^&|:<>?*+-/" :: [Char])
else case Char.generalCategory c of
Char.MathSymbol -> True
Char.CurrencySymbol -> True
Char.ModifierSymbol -> True
Char.OtherSymbol -> True
Char.DashPunctuation -> True
Char.OtherPunctuation -> True
_ -> False
isMeasurementUnitChar :: Char -> Bool
isMeasurementUnitChar !c =
if c < toEnum 128
then c `elem` ("'\"$%" :: [Char]) || Char.isAlpha c
else
Char.isAlpha c || case Char.generalCategory c of
Char.MathSymbol -> True
Char.CurrencySymbol -> True
Char.OtherSymbol -> True
_ -> False
-- no backtracking needed for precedence dict, so it
-- can live in the inner monad of 'ParsecT'.
type Parser = ParsecT Void Text (State EdhParserState)
-- so goes this simplified parsing err type name
type ParserError = ParseErrorBundle Text Void
TODO declare ` HasCallStack = > ` for each ctor ?
data EdhError
| thrown to halt the whole Edh program with a result
--
this is not recoverable by Edh code
--
-- caveat: never make this available to a sandboxed environment
ProgramHalt !Dynamic
| thrown when an Edh thread is terminated , usually incurred by { break }
-- from an event perceiver, but can also be thrown explicitly from normal
Edh code
--
this is not recoverable by Edh code
--
-- caveat: never make this available to a sandboxed environment
ThreadTerminate
| arbitrary realworld error happened in IO , propagated into the Edh
-- world
EdhIOError !SomeException
| -- | error occurred remotely, detailed text captured for display on the
-- throwing site
EdhPeerError !PeerSite !ErrDetails
| tagged error , with a msg and context information of the throwing Edh
-- thread
EdhError !EdhErrorTag !ErrMessage !Dynamic !ErrContext
type PeerSite = Text
type ErrDetails = Text
type ErrMessage = Text
type ErrContext = Text
instance Exception EdhError
instance Show EdhError where
show (ProgramHalt _) = "Edh⏹️Halt"
show ThreadTerminate = "Edh❎Terminate"
show (EdhIOError !ioe) = show ioe
show (EdhPeerError !peerSite !details) =
T.unpack $ "🏗️ traceback: " <> peerSite <> "\n" <> details
show (EdhError EdhException !msg _details !ctx) =
T.unpack $ "Đ traceback\n" <> ctx <> msg
show (EdhError PackageError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "📦 " <> msg
show (EdhError ParseError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "⛔ " <> msg
show (EdhError EvalError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "💣 " <> msg
show (EdhError UsageError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "🙈 " <> msg
show (EdhError UserCancel !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "🛑 " <> msg
data EdhErrorTag
for root class of custom Edh exceptions
| PackageError
| ParseError
| EvalError
| UsageError
| UserCancel
deriving (Eq, Show)
edhKnownError :: SomeException -> Maybe EdhError
edhKnownError exc = case fromException exc of
Just (err :: EdhError) -> Just err
Nothing -> case fromException exc of
Just (err :: ParserError) ->
Just $
EdhError
ParseError
(T.pack $ errorBundlePretty err)
(toDyn ())
"<parsing>"
Nothing -> Nothing
prettyParserError :: ParserError -> ErrMessage
prettyParserError = T.pack . errorBundlePretty
| Usually thrown from ` IO ` or ` STM ` monad without access to Edh scripting
context , will be re - wrapped into ` EdhError ` with Edh context added , by Edh
-- thread driver
data EdhHostError = EdhHostError !EdhErrorTag !ErrMessage !Dynamic
instance Exception EdhHostError
instance Show EdhHostError where
show (EdhHostError tag msg _details) = show tag <> ": " <> T.unpack msg
| null | https://raw.githubusercontent.com/e-wrks/edh/05b339ae6172770113f61f9584ac9792877853cb/elr/src/Language/Edh/Control.hs | haskell | | Source document
absolute local (though possibly network mounted) file path if started with
| Source position
| Source range
# UNPACK #
# UNPACK #
| compare a position to a range, return 'EQ' when the position is within the
special infinite end
| Source location
global dict for operator info
| precedence & fixity of known operators
| operators with non-standard character(s) in their symbol
invariant: ascendingly sorted,
so parsing against this list should attempt in reverse order
shortcircuit since we know both are sorted and no removal
no backtracking needed for precedence dict, so it
can live in the inner monad of 'ParsecT'.
so goes this simplified parsing err type name
caveat: never make this available to a sandboxed environment
from an event perceiver, but can also be thrown explicitly from normal
caveat: never make this available to a sandboxed environment
world
| error occurred remotely, detailed text captured for display on the
throwing site
thread
thread driver | module Language.Edh.Control where
import Control.Concurrent.STM
import Control.Exception
import Control.Monad.State.Strict (State)
import qualified Data.Char as Char
import Data.Dynamic (Dynamic, toDyn)
import qualified Data.HashMap.Strict as Map
import qualified Data.List as L
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import Data.Void (Void)
import Text.Megaparsec
( ParseErrorBundle,
ParsecT,
SourcePos (sourceColumn, sourceLine, sourceName),
errorBundlePretty,
unPos,
)
import Prelude
type ModuleName = Text
type ModuleFile = Text
data OpSymSrc = OpSymSrc !OpSymbol !SrcRange
deriving (Eq)
instance Show OpSymSrc where
show (OpSymSrc sym _) = show sym
type OpSymbol = Text
data OpFixity = InfixL | InfixR | Infix
deriving (Eq)
instance Show OpFixity where
show InfixL = "infixl"
show InfixR = "infixr"
show Infix = "infix"
type Precedence = Int
type OpDeclLoc = Text
' / ' , otherwise should be valid URI
newtype SrcDoc = SrcDoc Text
deriving (Eq, Show)
in LSP convention , i.e. no document locator
data SrcPos = SrcPos
in LSP convention , i.e. zero based
src'line :: !Int,
in LSP convention , i.e. zero based
src'char :: !Int
}
deriving (Eq, Show)
instance Ord SrcPos where
compare (SrcPos !x'l !x'c) (SrcPos !y'l !y'c) = case compare x'l y'l of
EQ -> compare x'c y'c
!conclusion -> conclusion
beginningSrcPos :: SrcPos
beginningSrcPos = SrcPos 0 0
in LSP convention , i.e. no document locator
data SrcRange = SrcRange
in LSP convention , i.e. zero based
in LSP convention , i.e. zero based
}
deriving (Eq, Show)
range , or ' LT ' when before it , ' GT ' when after it .
srcPosCmp2Range :: SrcPos -> SrcRange -> Ordering
srcPosCmp2Range !p (SrcRange !start !end) = case compare p start of
LT -> LT
EQ -> EQ
GT ->
if src'line end < 0
else case compare p end of
LT -> EQ
end position of a range is inclusive per VSCode word pick
GT -> GT
zeroSrcRange :: SrcRange
zeroSrcRange = SrcRange beginningSrcPos beginningSrcPos
noSrcRange :: SrcRange
noSrcRange = SrcRange (SrcPos (-1) (-1)) (SrcPos (-1) (-1))
prettySrcPos :: SrcDoc -> SrcPos -> Text
prettySrcPos (SrcDoc !file) (SrcPos !line !char)
| line <= 0 && char <= 0 =
file
| otherwise =
file <> ":" <> T.pack (show $ 1 + line) <> ":"
<> T.pack
(show $ 1 + char)
prettySrcRange :: SrcDoc -> SrcRange -> Text
prettySrcRange (SrcDoc !file) (SrcRange (SrcPos !start'line !start'char) (SrcPos !end'line !end'char))
| end'line <= 0 && end'char <= 0 =
file
| end'line == start'line && end'char == start'char =
file <> ":" <> T.pack (show $ 1 + start'line) <> ":"
<> T.pack
(show $ 1 + start'char)
| otherwise =
file
<> ":"
<> T.pack (show $ 1 + start'line)
<> ":"
<> T.pack (show $ 1 + start'char)
<> "-"
<> T.pack (show $ 1 + end'line)
<> ":"
<> T.pack (show $ 1 + end'char)
data SrcLoc = SrcLoc
{ src'doc :: !SrcDoc,
src'range :: !SrcRange
}
deriving (Eq, Show)
prettySrcLoc :: SrcLoc -> Text
prettySrcLoc (SrcLoc !doc !range) = prettySrcRange doc range
lspSrcPosFromParsec :: SourcePos -> SrcPos
lspSrcPosFromParsec !sp =
SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1)
lspSrcLocFromParsec :: SourcePos -> SrcPos -> SrcLoc
lspSrcLocFromParsec !sp !end =
SrcLoc (SrcDoc $ T.pack $ sourceName sp) $
SrcRange
(SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1))
end
lspSrcRangeFromParsec :: SourcePos -> SrcPos -> SrcRange
lspSrcRangeFromParsec !sp !end =
SrcRange
(SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1))
end
lspSrcRangeFromParsec' :: SrcPos -> SourcePos -> SrcRange
lspSrcRangeFromParsec' !start !sp =
SrcRange
start
(SrcPos (unPos (sourceLine sp) - 1) (unPos (sourceColumn sp) - 1))
lspSrcRangeFromParsec'' :: SourcePos -> SourcePos -> SrcRange
lspSrcRangeFromParsec'' !start !end =
SrcRange
(SrcPos (unPos (sourceLine start) - 1) (unPos (sourceColumn start) - 1))
(SrcPos (unPos (sourceLine end) - 1) (unPos (sourceColumn end) - 1))
data EdhParserState = EdhParserState
edh'parser'op'dict :: !GlobalOpDict,
end of last lexeme
edh'parser'lexeme'end'pos :: !SrcPos,
edh'parser'lexeme'end'offset :: !Int
}
data GlobalOpDict = GlobalOpDict
operator'declarations ::
Map.HashMap OpSymbol (OpFixity, Precedence, OpDeclLoc),
quaint'operators :: [OpSymbol]
}
lookupOpFromDict ::
OpSymbol -> GlobalOpDict -> Maybe (OpFixity, Precedence, OpDeclLoc)
lookupOpFromDict !sym (GlobalOpDict !decls _) = Map.lookup sym decls
insertOpIntoDict ::
OpSymbol -> (OpFixity, Precedence, OpDeclLoc) -> GlobalOpDict -> GlobalOpDict
insertOpIntoDict !sym !decl (GlobalOpDict !decls !quaint'ops) =
GlobalOpDict (Map.insert sym decl decls) $
if contain'nonstd'op'char
then L.insert sym quaint'ops
else quaint'ops
where
contain'nonstd'op'char :: Bool
contain'nonstd'op'char = isJust $ T.find (not . isOperatorChar) sym
mergeOpDict :: TVar GlobalOpDict -> GlobalOpDict -> GlobalOpDict -> IO ()
mergeOpDict
godv
(GlobalOpDict !base'decls !base'quaint'ops)
(GlobalOpDict !decls !quaint'ops) =
if Map.null declUpds && L.null quaintUpds
shortcircuit without touching the TVar
else atomically $
modifyTVar' godv $ \(GlobalOpDict !curr'decls !curr'quaint'ops) ->
GlobalOpDict
( if Map.null declUpds
then curr'decls
else Map.union curr'decls declUpds
)
( if L.null quaintUpds
then curr'quaint'ops
else L.sort $ curr'quaint'ops ++ quaintUpds
)
where
declUpds = Map.difference decls base'decls
quaintUpds =
if L.length quaint'ops <= L.length base'quaint'ops
else quaint'ops L.\\ base'quaint'ops
isOperatorChar :: Char -> Bool
isOperatorChar !c =
if c < toEnum 128
then c `elem` ("=!@#$%^&|:<>?*+-/" :: [Char])
else case Char.generalCategory c of
Char.MathSymbol -> True
Char.CurrencySymbol -> True
Char.ModifierSymbol -> True
Char.OtherSymbol -> True
Char.DashPunctuation -> True
Char.OtherPunctuation -> True
_ -> False
isMeasurementUnitChar :: Char -> Bool
isMeasurementUnitChar !c =
if c < toEnum 128
then c `elem` ("'\"$%" :: [Char]) || Char.isAlpha c
else
Char.isAlpha c || case Char.generalCategory c of
Char.MathSymbol -> True
Char.CurrencySymbol -> True
Char.OtherSymbol -> True
_ -> False
type Parser = ParsecT Void Text (State EdhParserState)
type ParserError = ParseErrorBundle Text Void
TODO declare ` HasCallStack = > ` for each ctor ?
data EdhError
| thrown to halt the whole Edh program with a result
this is not recoverable by Edh code
ProgramHalt !Dynamic
| thrown when an Edh thread is terminated , usually incurred by { break }
Edh code
this is not recoverable by Edh code
ThreadTerminate
| arbitrary realworld error happened in IO , propagated into the Edh
EdhIOError !SomeException
EdhPeerError !PeerSite !ErrDetails
| tagged error , with a msg and context information of the throwing Edh
EdhError !EdhErrorTag !ErrMessage !Dynamic !ErrContext
type PeerSite = Text
type ErrDetails = Text
type ErrMessage = Text
type ErrContext = Text
instance Exception EdhError
instance Show EdhError where
show (ProgramHalt _) = "Edh⏹️Halt"
show ThreadTerminate = "Edh❎Terminate"
show (EdhIOError !ioe) = show ioe
show (EdhPeerError !peerSite !details) =
T.unpack $ "🏗️ traceback: " <> peerSite <> "\n" <> details
show (EdhError EdhException !msg _details !ctx) =
T.unpack $ "Đ traceback\n" <> ctx <> msg
show (EdhError PackageError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "📦 " <> msg
show (EdhError ParseError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "⛔ " <> msg
show (EdhError EvalError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "💣 " <> msg
show (EdhError UsageError !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "🙈 " <> msg
show (EdhError UserCancel !msg _details !ctx) =
T.unpack $ "💔 traceback\n" <> ctx <> "🛑 " <> msg
data EdhErrorTag
for root class of custom Edh exceptions
| PackageError
| ParseError
| EvalError
| UsageError
| UserCancel
deriving (Eq, Show)
edhKnownError :: SomeException -> Maybe EdhError
edhKnownError exc = case fromException exc of
Just (err :: EdhError) -> Just err
Nothing -> case fromException exc of
Just (err :: ParserError) ->
Just $
EdhError
ParseError
(T.pack $ errorBundlePretty err)
(toDyn ())
"<parsing>"
Nothing -> Nothing
prettyParserError :: ParserError -> ErrMessage
prettyParserError = T.pack . errorBundlePretty
| Usually thrown from ` IO ` or ` STM ` monad without access to Edh scripting
context , will be re - wrapped into ` EdhError ` with Edh context added , by Edh
data EdhHostError = EdhHostError !EdhErrorTag !ErrMessage !Dynamic
instance Exception EdhHostError
instance Show EdhHostError where
show (EdhHostError tag msg _details) = show tag <> ": " <> T.unpack msg
|
962b73ad118ce9fcd824826a6c0fd739810e2e63630399c4905d43a3ee4c15fb | PEZ/rich4clojure | problem_102.clj | (ns rich4clojure.medium.problem-102
(:require [hyperfiddle.rcf :refer [tests]]))
= intoCamelCase =
;; By 4Clojure user: amalloy
;; Difficulty: Medium
;; Tags: [strings]
;;
When working with java , you often need to create an
;; object with fieldsLikeThis, but you'd rather work with
;; a hashmap that has :keys-like-this until it's time to
;; convert. Write a function which takes lower-case
;; hyphen-separated strings and converts them to
;; camel-case strings.
(def __ :tests-will-fail)
(comment
)
(tests
(__ "something") := "something"
(__ "multi-word-key") := "multiWordKey"
(__ "leaveMeAlone") := "leaveMeAlone")
;; Share your solution, and/or check how others did it:
;; | null | https://raw.githubusercontent.com/PEZ/rich4clojure/2ccfac041840e9b1550f0a69b9becbdb03f9525b/src/rich4clojure/medium/problem_102.clj | clojure | By 4Clojure user: amalloy
Difficulty: Medium
Tags: [strings]
object with fieldsLikeThis, but you'd rather work with
a hashmap that has :keys-like-this until it's time to
convert. Write a function which takes lower-case
hyphen-separated strings and converts them to
camel-case strings.
Share your solution, and/or check how others did it:
| (ns rich4clojure.medium.problem-102
(:require [hyperfiddle.rcf :refer [tests]]))
= intoCamelCase =
When working with java , you often need to create an
(def __ :tests-will-fail)
(comment
)
(tests
(__ "something") := "something"
(__ "multi-word-key") := "multiWordKey"
(__ "leaveMeAlone") := "leaveMeAlone")
|
7234ed4fecd78a5c58cd2d3e159a0c68d81dc8b63f30f88b692c2513904d9530 | ice1000/learn | recurrence-relations.hs | module FunctionEvaluator where
import qualified Data.Map.Strict as M
factorial i | i = = 0 = Left 1
-- | otherwise = Right ([i-1], (*i).head)
--
fibonacci i | i < 2 = Left i
-- | otherwise = Right ([i-1, i-2], sum)
--
coinchange ( a , i ) | a = = 0 = Left 1
-- | a < 0 || i == 0 = Left 0
-- | otherwise = Right ([(a, i-1), (a-coinlist!!(i-1), i)], sum)
--
coinlist = [ 1 , 3 , 5 , 10 ]
-- heigth (n, m) | m <= 0 || n <= 0 = Left 0
-- | otherwise = Right ([(n, m-1), (n-1, m-1)], (+1).sum)
--
foo i | i < = 2 = Left 1
| odd i = Right ( [ 6*i`div`7 , 2*i`div`3 ] , sum )
-- | otherwise = Right ([i-1, i-3], sum)
--
type MP = M.Map
evaluate :: Ord a => MP a b -> (a -> Either b ([a], [b] -> b)) -> a -> (MP a b, b)
evaluate m f a = case M.lookup a m of
(Just some) -> (m, some)
_ -> case f a of
(Left n) -> (M.insert a n m, n)
(Right (prm, fn)) -> let (m2, ls) = foldl fun (m, []) prm
b = fn ls in
(M.insert a b m2, b)
where fun = \(m, ls) a -> let (m1, b) = evaluate m f a in
(M.insert a b m1, b:ls)
--
evaluateFunction :: Ord a => (a -> Either b ([a], [b] -> b)) -> a -> b
evaluateFunction f n = snd $ evaluate M.empty f n
| null | https://raw.githubusercontent.com/ice1000/learn/4ce5ea1897c97f7b5b3aee46ccd994e3613a58dd/Haskell/CW-Kata/recurrence-relations.hs | haskell | | otherwise = Right ([i-1], (*i).head)
| otherwise = Right ([i-1, i-2], sum)
| a < 0 || i == 0 = Left 0
| otherwise = Right ([(a, i-1), (a-coinlist!!(i-1), i)], sum)
heigth (n, m) | m <= 0 || n <= 0 = Left 0
| otherwise = Right ([(n, m-1), (n-1, m-1)], (+1).sum)
| otherwise = Right ([i-1, i-3], sum)
| module FunctionEvaluator where
import qualified Data.Map.Strict as M
factorial i | i = = 0 = Left 1
fibonacci i | i < 2 = Left i
coinchange ( a , i ) | a = = 0 = Left 1
coinlist = [ 1 , 3 , 5 , 10 ]
foo i | i < = 2 = Left 1
| odd i = Right ( [ 6*i`div`7 , 2*i`div`3 ] , sum )
type MP = M.Map
evaluate :: Ord a => MP a b -> (a -> Either b ([a], [b] -> b)) -> a -> (MP a b, b)
evaluate m f a = case M.lookup a m of
(Just some) -> (m, some)
_ -> case f a of
(Left n) -> (M.insert a n m, n)
(Right (prm, fn)) -> let (m2, ls) = foldl fun (m, []) prm
b = fn ls in
(M.insert a b m2, b)
where fun = \(m, ls) a -> let (m1, b) = evaluate m f a in
(M.insert a b m1, b:ls)
evaluateFunction :: Ord a => (a -> Either b ([a], [b] -> b)) -> a -> b
evaluateFunction f n = snd $ evaluate M.empty f n
|
6a9da75fe21da5b6a3ad5235773dd614d9142763d024d3be414473d4d1b20171 | spl/ivy | sreadonly.ml | (*
* sreadonly.ml
*
* Static checking for the readonly type.
*
*)
open Cil
open Pretty
open Ivyoptions
open Sutil
open Sfunctions
module E = Errormsg
(* SREADONLY fields of SPRIVATE structs may be written *)
let isWritableReadonlyLval (lv : lval) : bool =
let hlv, lastoff = removeOffsetLval lv in
match lastoff with
| Field(fi,NoOffset)
when isPrivateType (sharCTypeOfLval hlv) -> true
| _ ->
E.log "not writable readonly lval %a of %a:%a\n"
sp_lval lv sp_lval hlv sp_type (sharCTypeOfLval hlv);
false
let chk_single_threaded loc =
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString lmsg in
Call(None,v2e sfuncs.chk_single_threaded,[msg],loc)
class readOnlyTypeCheckerClass (checks : bool ref) = object(self)
inherit nopCilVisitor
method vinst (i : instr) =
match i with
| Set(lv, _, loc)
when isReadonlyType (sharCTypeOfLval lv) &&
not(isWritableReadonlyLval lv) ->
E.error "Write to readonly lval %a at %a in %a"
sp_lval lv d_loc loc sp_instr i;
checks := false;
SkipChildren
| Call(Some lv,Lval(Var fv,NoOffset),[src],loc)
when isReadonlyType(sharCTypeOfLval lv) &&
fv.vname = "SINIT" || fv.vname = "SINIT_DOUBLE" ||
fv.vname = "SINIT_FLOAT" ->
SREADONLYs can be initialized when there is only
one thread running
one thread running *)
ChangeTo[chk_single_threaded loc;
Set(lv, src, loc)]
| Call(Some lv, _, _, loc)
when isReadonlyType(sharCTypeOfLval lv) &&
not(isWritableReadonlyLval lv) ->
E.error "Write to readonly lval %a at %a in %a"
sp_lval lv d_loc loc sp_instr i;
checks := false;
SkipChildren
| _ -> SkipChildren
method vblock (b : block) =
if hasAttribute "trusted" b.battrs
then SkipChildren
else DoChildren
end
let readOnlyTypeCheck (f : file) : unit =
let checks = ref true in
let vis = new readOnlyTypeCheckerClass checks in
visitCilFile vis f
| null | https://raw.githubusercontent.com/spl/ivy/b1b516484fba637eb24e83d27555d273495e622b/src/sharC/sreadonly.ml | ocaml |
* sreadonly.ml
*
* Static checking for the readonly type.
*
SREADONLY fields of SPRIVATE structs may be written |
open Cil
open Pretty
open Ivyoptions
open Sutil
open Sfunctions
module E = Errormsg
let isWritableReadonlyLval (lv : lval) : bool =
let hlv, lastoff = removeOffsetLval lv in
match lastoff with
| Field(fi,NoOffset)
when isPrivateType (sharCTypeOfLval hlv) -> true
| _ ->
E.log "not writable readonly lval %a of %a:%a\n"
sp_lval lv sp_lval hlv sp_type (sharCTypeOfLval hlv);
false
let chk_single_threaded loc =
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString lmsg in
Call(None,v2e sfuncs.chk_single_threaded,[msg],loc)
class readOnlyTypeCheckerClass (checks : bool ref) = object(self)
inherit nopCilVisitor
method vinst (i : instr) =
match i with
| Set(lv, _, loc)
when isReadonlyType (sharCTypeOfLval lv) &&
not(isWritableReadonlyLval lv) ->
E.error "Write to readonly lval %a at %a in %a"
sp_lval lv d_loc loc sp_instr i;
checks := false;
SkipChildren
| Call(Some lv,Lval(Var fv,NoOffset),[src],loc)
when isReadonlyType(sharCTypeOfLval lv) &&
fv.vname = "SINIT" || fv.vname = "SINIT_DOUBLE" ||
fv.vname = "SINIT_FLOAT" ->
SREADONLYs can be initialized when there is only
one thread running
one thread running *)
ChangeTo[chk_single_threaded loc;
Set(lv, src, loc)]
| Call(Some lv, _, _, loc)
when isReadonlyType(sharCTypeOfLval lv) &&
not(isWritableReadonlyLval lv) ->
E.error "Write to readonly lval %a at %a in %a"
sp_lval lv d_loc loc sp_instr i;
checks := false;
SkipChildren
| _ -> SkipChildren
method vblock (b : block) =
if hasAttribute "trusted" b.battrs
then SkipChildren
else DoChildren
end
let readOnlyTypeCheck (f : file) : unit =
let checks = ref true in
let vis = new readOnlyTypeCheckerClass checks in
visitCilFile vis f
|
8813ec31da7762054cafe0d059807d4bbd1780bc8f8208d920acfdf0fa999e63 | ProjectMAC/propagators | bridge-rectifier-test.scm | ;;; ----------------------------------------------------------------------
Copyright 2009 - 2010 .
;;; ----------------------------------------------------------------------
This file is part of Propagator Network Prototype .
;;;
Propagator Network Prototype 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.
;;;
Propagator Network Prototype 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 Propagator Network Prototype . If not , see
;;; </>.
;;; ----------------------------------------------------------------------
(in-test-group
bridge-rectifier
(define-test (consistent-state-test)
(interaction
(initialize-scheduler)
(define-cell victim)
(binary-amb victim)
(map-consistent-states
(lambda ()
(v&s-value (tms-query (content victim))))
victim)
(produces '(#t #f))))
(define-test (ideal-diode-test)
(interaction
(initialize-scheduler)
(define n0 (node 2))
(define n0t1 (car n0))
(define n0t2 (cadr n0))
(define n1 (node 2))
(define n1t1 (car n1))
(define n1t2 (cadr n1))
(define n2 (node 2))
(define n2t1 (car n2))
(define n2t2 (cadr n2))
(ground n0)
(define-cell Pv ((voltage-source 6) n1t1 n0t1))
(define-cell PR1 ((linear-resistor 3) n1t2 n2t1))
;; Diode allows current
(define-cell PD ((ideal-diode) n2t2 n0t2))
(define-cell power (e:+ Pv (e:+ PR1 PD)))
(run)
(v&s-value (tms-query (content (potential n2t1))))
(produces 0)
(v&s-value (tms-query (content (current n2t2))))
(produces 2)
(v&s-value (tms-query (content power)))
(produces 0)
))
(define-test (ideal-diode-test-2)
(interaction
(initialize-scheduler)
(define n0 (node 2))
(define n0t1 (car n0))
(define n0t2 (cadr n0))
(define n1 (node 2))
(define n1t1 (car n1))
(define n1t2 (cadr n1))
(define n2 (node 2))
(define n2t1 (car n2))
(define n2t2 (cadr n2))
(ground n0)
(define-cell Pv ((voltage-source 6) n1t1 n0t1))
(define-cell PR1 ((linear-resistor 3) n1t2 n2t1))
;; Diode disallows current
(define-cell PD ((ideal-diode) n0t2 n2t2))
(define-cell power (e:+ Pv (e:+ PR1 PD)))
(run)
(v&s-value (tms-query (content (potential n2t1))))
(produces 6)
(v&s-value (tms-query (content (current n2t2))))
(produces 0)
(v&s-value (tms-query (content power)))
(produces 0)
))
;; This test takes a very long time to run
#;
(define-test (plunking-rectifier)
(interaction
(initialize-scheduler)
(define n1 (node 3))
(define n1t1 (car n1))
(define n1t2 (cadr n1))
(define n1t3 (caddr n1))
(define n2 (node 3))
(define n2t1 (car n2))
(define n2t2 (cadr n2))
(define n2t3 (caddr n2))
(define n3 (node 3))
(define n3t1 (car n3))
(define n3t2 (cadr n3))
(define n3t3 (caddr n3))
(define n4 (node 3))
(define n4t1 (car n4))
(define n4t2 (cadr n4))
(define n4t3 (caddr n4))
(define Vs (voltage-source 6))
(define R1 (linear-resistor 3))
(define D12 (ideal-diode))
(define D42 (ideal-diode))
(define D31 (ideal-diode))
(define D34 (ideal-diode))
(define-cell P1 (Vs n1t1 n4t1))
(define-cell P2 (D12 n1t2 n2t1))
(define-cell P3 (D42 n4t2 n2t3))
(define-cell P4 (D31 n3t1 n1t3))
(define-cell P5 (D34 n3t3 n4t3))
(define-cell P6 (R1 n2t2 n3t2))
(ground n4)
(define-cell P (ce:+ (ce:+ (ce:+ P1 P2) (ce:+ P3 P4)) (ce:+ P5 P6)))
(define all-cells
(list (potential n1t1) (current n1t1)
(current n1t2) (current n1t3)
(potential n2t1) (current n2t1)
(current n2t2) (current n2t3)
(potential n3t1) (current n3t1)
(current n3t2) (current n3t3)
(potential n4t1) (current n4t1)
(current n4t2) (current n4t3)
P P1 P2 P3 P4 P5 P6))
(plunker (potential n2t2) 'x)
Note : Only one consistent state
(map-consistent-states
(lambda ()
(v&s-value (tms-query (content (current n2t2)))))
all-cells)
(produces
'(#(symbolic 2 #(metadata (x) (((= x 6) ())) ()))))))
)
| null | https://raw.githubusercontent.com/ProjectMAC/propagators/add671f009e62441e77735a88980b6b21fad7a79/examples/test/bridge-rectifier-test.scm | scheme | ----------------------------------------------------------------------
----------------------------------------------------------------------
you can
redistribute it and/or modify it under the terms of the GNU
any later version.
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.
</>.
----------------------------------------------------------------------
Diode allows current
Diode disallows current
This test takes a very long time to run
| Copyright 2009 - 2010 .
This file is part of Propagator Network Prototype .
General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
Propagator Network Prototype is distributed in the hope that it
You should have received a copy of the GNU General Public License
along with Propagator Network Prototype . If not , see
(in-test-group
bridge-rectifier
(define-test (consistent-state-test)
(interaction
(initialize-scheduler)
(define-cell victim)
(binary-amb victim)
(map-consistent-states
(lambda ()
(v&s-value (tms-query (content victim))))
victim)
(produces '(#t #f))))
(define-test (ideal-diode-test)
(interaction
(initialize-scheduler)
(define n0 (node 2))
(define n0t1 (car n0))
(define n0t2 (cadr n0))
(define n1 (node 2))
(define n1t1 (car n1))
(define n1t2 (cadr n1))
(define n2 (node 2))
(define n2t1 (car n2))
(define n2t2 (cadr n2))
(ground n0)
(define-cell Pv ((voltage-source 6) n1t1 n0t1))
(define-cell PR1 ((linear-resistor 3) n1t2 n2t1))
(define-cell PD ((ideal-diode) n2t2 n0t2))
(define-cell power (e:+ Pv (e:+ PR1 PD)))
(run)
(v&s-value (tms-query (content (potential n2t1))))
(produces 0)
(v&s-value (tms-query (content (current n2t2))))
(produces 2)
(v&s-value (tms-query (content power)))
(produces 0)
))
(define-test (ideal-diode-test-2)
(interaction
(initialize-scheduler)
(define n0 (node 2))
(define n0t1 (car n0))
(define n0t2 (cadr n0))
(define n1 (node 2))
(define n1t1 (car n1))
(define n1t2 (cadr n1))
(define n2 (node 2))
(define n2t1 (car n2))
(define n2t2 (cadr n2))
(ground n0)
(define-cell Pv ((voltage-source 6) n1t1 n0t1))
(define-cell PR1 ((linear-resistor 3) n1t2 n2t1))
(define-cell PD ((ideal-diode) n0t2 n2t2))
(define-cell power (e:+ Pv (e:+ PR1 PD)))
(run)
(v&s-value (tms-query (content (potential n2t1))))
(produces 6)
(v&s-value (tms-query (content (current n2t2))))
(produces 0)
(v&s-value (tms-query (content power)))
(produces 0)
))
(define-test (plunking-rectifier)
(interaction
(initialize-scheduler)
(define n1 (node 3))
(define n1t1 (car n1))
(define n1t2 (cadr n1))
(define n1t3 (caddr n1))
(define n2 (node 3))
(define n2t1 (car n2))
(define n2t2 (cadr n2))
(define n2t3 (caddr n2))
(define n3 (node 3))
(define n3t1 (car n3))
(define n3t2 (cadr n3))
(define n3t3 (caddr n3))
(define n4 (node 3))
(define n4t1 (car n4))
(define n4t2 (cadr n4))
(define n4t3 (caddr n4))
(define Vs (voltage-source 6))
(define R1 (linear-resistor 3))
(define D12 (ideal-diode))
(define D42 (ideal-diode))
(define D31 (ideal-diode))
(define D34 (ideal-diode))
(define-cell P1 (Vs n1t1 n4t1))
(define-cell P2 (D12 n1t2 n2t1))
(define-cell P3 (D42 n4t2 n2t3))
(define-cell P4 (D31 n3t1 n1t3))
(define-cell P5 (D34 n3t3 n4t3))
(define-cell P6 (R1 n2t2 n3t2))
(ground n4)
(define-cell P (ce:+ (ce:+ (ce:+ P1 P2) (ce:+ P3 P4)) (ce:+ P5 P6)))
(define all-cells
(list (potential n1t1) (current n1t1)
(current n1t2) (current n1t3)
(potential n2t1) (current n2t1)
(current n2t2) (current n2t3)
(potential n3t1) (current n3t1)
(current n3t2) (current n3t3)
(potential n4t1) (current n4t1)
(current n4t2) (current n4t3)
P P1 P2 P3 P4 P5 P6))
(plunker (potential n2t2) 'x)
Note : Only one consistent state
(map-consistent-states
(lambda ()
(v&s-value (tms-query (content (current n2t2)))))
all-cells)
(produces
'(#(symbolic 2 #(metadata (x) (((= x 6) ())) ()))))))
)
|
4f1a91daf0db742bd1ee328ab2c8a582871f56ea7423355d629fefd82f02f365 | 8thlight/hyperion | project.clj | (defproject hyperion/hyperion-postgres "3.7.1"
:description "Postgres Datastore for Hyperion"
:dependencies [[org.clojure/clojure "1.5.1"]
[hyperion/hyperion-api "3.7.1"]
[hyperion/hyperion-sql "3.7.1"]
[postgresql/postgresql "8.4-702.jdbc4"]]
:profiles {:dev {:dependencies [[speclj "2.7.5"]]}}
:test-paths ["spec/"]
:plugins [[speclj "2.7.5"]])
| null | https://raw.githubusercontent.com/8thlight/hyperion/b1b8f60a5ef013da854e98319220b97920727865/postgres/project.clj | clojure | (defproject hyperion/hyperion-postgres "3.7.1"
:description "Postgres Datastore for Hyperion"
:dependencies [[org.clojure/clojure "1.5.1"]
[hyperion/hyperion-api "3.7.1"]
[hyperion/hyperion-sql "3.7.1"]
[postgresql/postgresql "8.4-702.jdbc4"]]
:profiles {:dev {:dependencies [[speclj "2.7.5"]]}}
:test-paths ["spec/"]
:plugins [[speclj "2.7.5"]])
|
|
d9eb7d9d5a4d62b5c61c17b026745945a30a662a36542d32d8b77ec130b548cb | zadean/emojipoo | emojipoo_app.erl | %%%-------------------------------------------------------------------
%% @doc emojipoo public API
%% @end
%%%-------------------------------------------------------------------
-module(emojipoo_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%%====================================================================
%% API
%%====================================================================
start(_StartType, _StartArgs) ->
emojipoo_sup:start_link().
%%--------------------------------------------------------------------
stop(_State) ->
ok.
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/zadean/emojipoo/d4aea55747de038f1812d3b2d4ec8102dfa124b6/src/emojipoo_app.erl | erlang | -------------------------------------------------------------------
@doc emojipoo public API
@end
-------------------------------------------------------------------
Application callbacks
====================================================================
API
====================================================================
--------------------------------------------------------------------
====================================================================
==================================================================== |
-module(emojipoo_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
emojipoo_sup:start_link().
stop(_State) ->
ok.
Internal functions
|
b9bf8f93941f211db3a8f2bbeba11847cf35573b54d5da75876a1bef748cd4a2 | softlab-ntua/bencherl | master.erl | %% orbit-int master (controlling orbit computation)
%%
Author : < >
%%
-module(master).
-export([orbit/3,
get_gens/1, get_master/1, get_workers/1, get_spawn_img_comp/1,
get_global_table_size/1, get_idle_timeout/1,
set_idle_timeout/2, clear_spawn_img_comp/1,
now/0]).
-compile({no_auto_import, [now/0]}).
%% DATA
%% Static Machine Configuration:
%% {Gs, %list of generators
%% Master, %pid of master process
%% Workers, %list of Worker
GlobalTableSize , % size of global hash table
%% IdleTimeout, %milliseconds this worker idles before sending 'done'
%% SpawnImgComp} %true iff this worker spawns image computations
%%
%% Worker:
{ Pid , % pid of worker process
TableOffset , % offset (= index 0 ) of local table into global table
TableSize } % size of local hash table
%%
%% Host:
{ Node , % atom naming Erlang node
Procs , % number of processors
TableSize , % size of hash table per processor
%% IdleTimeout} %milliseconds a processor idles before sending 'done'
%%
%% Statistics:
List of pairs where the first component is an atom , the second
%% some data. Part of the data is the fill frequency of the table
%% (a list whose ith element indicates frequency of filling degree i).
%% MESSAGES
Master - > Worker : { init , StaticMachConf }
%%
Master / Worker - > Worker : { vertex , X , Slot , K }
%% %X is vertex
%% %Slot is slot of X on target worker
%% %K is atomic credit shipped with vertex
%%
%% Worker -> Master: {done, Cs}
% Cs is non - zero credit ( rep as list of ints )
%%
%% Master -> Worker: {dump}
%%
Worker - > Master : { result , Xs , Stats }
%% %Xs is list of found orbit vertices
%% %Stats is statistics about worker's table
compute orbit of elements in list under list of generators Gs ;
%% the argument Hosts is either an integer N, a triple {P, N, T}, or
%% a non-empty list [{H, P, N, T} | ...] of quadruples:
* N : run the sequential algorithm with table size N
%% * {P, N, T, S}: run the parallel algorithm on P processors
%% each with table size N, idle timeout T and
%% spawn image computation flag S;
%% * [{H, P, N, T, S} | ...]: run the distributed algorithm on the list of
%% hosts, where each quintuple {H, P, N, T, S}
%% specifies
* host name H ( ie . name of Erlang node ) ,
%% * number of processors P on H,
%% * table size N (per processor),
%% * idle timeout T, and
%% * spawn image computation flag S.
%% The function returns a pair consisting of the computed orbit and
a list of statistics , the first element of which reports overall statistics ,
%% and all remaining elements report statistics of some worker.
orbit(Gs, Xs, Hosts) ->
if
is_integer(Hosts) ->
TableSize = Hosts,
sequential:orbit(Gs, Xs, TableSize);
true ->
par_orbit(Gs, Xs, Hosts)
end.
par_orbit(Gs, Xs, Hosts) ->
% spawn workers on Hosts
{Workers, GlobTabSize} = start_workers(Hosts),
assemble StaticMachConf and distribute to Workers
StaticMachConf = mk_static_mach_conf(Gs, self(), Workers, GlobTabSize),
lists:foreach(fun({Pid, _, _}) -> Pid ! {init, StaticMachConf} end, Workers),
% start wall clock timer
StartTime = now(),
% distribute initial vertices to workers
Credit = worker:distribute_vertices(StaticMachConf, credit:one(), Xs),
% collect credit handed back by idle workers
collect_credit(Credit),
% measure elapsed time (in milliseconds)
ElapsedTime = now() - StartTime,
% tell all Workers to dump their tables
lists:foreach(fun({Pid, _, _}) -> Pid ! {dump} end, Workers),
% collect results from all workers and return them
collect_orbit(ElapsedTime, length(Workers)).
%% start_workers starts worker processes depending on the input Hosts:
%% * if Hosts is a quadruple {P, _, _, _} then P processes are forked on the
executing Erlang node ;
* if Hosts is a non - empty list { H1 , P1 , _ , _ , _ } , { H2 , P2 , _ , _ , _ } , ...
then P1 processes are forked on Erlang node H1 , P2 processes on node H2 ,
%% and so on.
%% The function returns a pair {Workers, GlobalTableSize}, where
%% * GlobalTableSize is the total number of slots of the global hash table, and
* Workers is a list of Worker , sorted wrt . TableOffset in ascending order .
start_workers({Procs, TabSize, TmOut, SpawnImgComp}) ->
{Workers, GlobalTableSize} = do_start_shm({Procs, TabSize, TmOut, SpawnImgComp}, {[], 0}),
{lists:reverse(Workers), GlobalTableSize};
start_workers([Host | Hosts]) ->
{Workers, GlobalTableSize} = do_start_dist([Host | Hosts], {[], 0}),
{lists:reverse(Workers), GlobalTableSize}.
do_start_shm({0, _, _, _}, Acc) ->
Acc;
do_start_shm({M, TabSize, TmOut, SpawnImgComp}, {Workers, GTabSize}) ->
Pid = spawn_link(worker, init, [TabSize, TmOut, SpawnImgComp]),
NewWorkers = [{Pid, GTabSize, TabSize} | Workers],
NewGTabSize = GTabSize + TabSize,
Acc = {NewWorkers, NewGTabSize},
do_start_shm({M - 1, TabSize, TmOut, SpawnImgComp}, Acc).
do_start_dist([], Acc) ->
Acc;
do_start_dist([{_, 0, _, _, _} | Hosts], Acc) ->
do_start_dist(Hosts, Acc);
do_start_dist([{Node, M, TabSize, TmOut, SpawnImgComp} | Hosts], {Workers, GTabSize}) ->
Pid = spawn_link(Node, worker, init, [TabSize, TmOut, SpawnImgComp]),
NewWorkers = [{Pid, GTabSize, TabSize} | Workers],
NewGTabSize = GTabSize + TabSize,
Acc = {NewWorkers, NewGTabSize},
do_start_dist([{Node, M - 1, TabSize, TmOut, SpawnImgComp} | Hosts], Acc).
%% collect_credit collects leftover credit from idle workers until
the credit adds up to 1 .
collect_credit(Credit) ->
case credit:is_one(Credit) of
true -> ok; %% break loop and return dummy atom
_Else ->
receive
{done, WorkersCredit} ->
CollectedCredit = credit:credit(WorkersCredit, Credit),
collect_credit(CollectedCredit)
end
end.
%% collect_orbit collects partial orbits and stats from N workers.
collect_orbit(ElapsedTime, N) ->
{PartOrbits, WorkerStats} = do_collect_orbit(N, [], []),
Orbit = lists:flatten(PartOrbits),
Stats = [master_stats(ElapsedTime, WorkerStats) | WorkerStats],
{Orbit, Stats}.
do_collect_orbit(0, PartOrbits, WorkerStats) -> {PartOrbits, WorkerStats};
do_collect_orbit(N, PartOrbits, WorkerStats) ->
receive
{result, PartOrbit, WorkerStat} ->
do_collect_orbit(N - 1, [PartOrbit|PartOrbits], [WorkerStat|WorkerStats])
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% auxiliary functions
functions operating on the StaticMachConf
mk_static_mach_conf(Gs, Master, Workers, GlobalTableSize) ->
{Gs, Master, Workers, GlobalTableSize, 0, true}.
get_gens(StaticMachConf) -> element(1, StaticMachConf).
get_master(StaticMachConf) -> element(2, StaticMachConf).
get_workers(StaticMachConf) -> element(3, StaticMachConf).
get_global_table_size(StaticMachConf) -> element(4, StaticMachConf).
get_idle_timeout(StaticMachConf) -> element(5, StaticMachConf).
get_spawn_img_comp(StaticMachConf) -> element(6, StaticMachConf).
set_idle_timeout(StaticMachConf, X) -> setelement(5, StaticMachConf, X).
clear_spawn_img_comp(StaticMachConf) -> setelement(6, StaticMachConf, false).
%% produce readable statistics
master_stats(ElapsedTime, WorkerStats) ->
Freq = table:sum_freqs([table:freq_from_stat(W) || W <- WorkerStats]),
VertsRecvd = lists:sum([worker:verts_recvd_from_stat(W) || W <- WorkerStats]),
CreditRetd = lists:sum([worker:credit_retd_from_stat(W) || W <- WorkerStats]),
MinAtomicCredit = lists:max([worker:min_atomic_credit_from_stat(W) || W <- WorkerStats]),
MaxInitIdle = lists:max([worker:init_idle_from_stat(W) || W <- WorkerStats]),
MaxIdle = lists:max([worker:max_idle_from_stat(W) || W <- WorkerStats]),
MaxTailIdle = lists:max([worker:tail_idle_from_stat(W) || W <- WorkerStats]),
[{wall_time, ElapsedTime},
{vertices_recvd, VertsRecvd},
{credit_retd, CreditRetd},
{min_atomic_credit, MinAtomicCredit},
{max_init_idle_time, MaxInitIdle},
{max_idle_time, MaxIdle},
{max_tail_idle_time, MaxTailIdle} | table:freq_to_stat(Freq)].
%% current wall clock time (in milliseconds since start of RTS)
now() -> element(1, statistics(wall_clock)).
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/bench/orbit_int/src/master.erl | erlang | orbit-int master (controlling orbit computation)
DATA
Static Machine Configuration:
{Gs, %list of generators
Master, %pid of master process
Workers, %list of Worker
size of global hash table
IdleTimeout, %milliseconds this worker idles before sending 'done'
SpawnImgComp} %true iff this worker spawns image computations
Worker:
pid of worker process
offset (= index 0 ) of local table into global table
size of local hash table
Host:
atom naming Erlang node
number of processors
size of hash table per processor
IdleTimeout} %milliseconds a processor idles before sending 'done'
Statistics:
some data. Part of the data is the fill frequency of the table
(a list whose ith element indicates frequency of filling degree i).
MESSAGES
%X is vertex
%Slot is slot of X on target worker
%K is atomic credit shipped with vertex
Worker -> Master: {done, Cs}
Cs is non - zero credit ( rep as list of ints )
Master -> Worker: {dump}
%Xs is list of found orbit vertices
%Stats is statistics about worker's table
the argument Hosts is either an integer N, a triple {P, N, T}, or
a non-empty list [{H, P, N, T} | ...] of quadruples:
* {P, N, T, S}: run the parallel algorithm on P processors
each with table size N, idle timeout T and
spawn image computation flag S;
* [{H, P, N, T, S} | ...]: run the distributed algorithm on the list of
hosts, where each quintuple {H, P, N, T, S}
specifies
* number of processors P on H,
* table size N (per processor),
* idle timeout T, and
* spawn image computation flag S.
The function returns a pair consisting of the computed orbit and
and all remaining elements report statistics of some worker.
spawn workers on Hosts
start wall clock timer
distribute initial vertices to workers
collect credit handed back by idle workers
measure elapsed time (in milliseconds)
tell all Workers to dump their tables
collect results from all workers and return them
start_workers starts worker processes depending on the input Hosts:
* if Hosts is a quadruple {P, _, _, _} then P processes are forked on the
and so on.
The function returns a pair {Workers, GlobalTableSize}, where
* GlobalTableSize is the total number of slots of the global hash table, and
collect_credit collects leftover credit from idle workers until
break loop and return dummy atom
collect_orbit collects partial orbits and stats from N workers.
auxiliary functions
produce readable statistics
current wall clock time (in milliseconds since start of RTS) | Author : < >
-module(master).
-export([orbit/3,
get_gens/1, get_master/1, get_workers/1, get_spawn_img_comp/1,
get_global_table_size/1, get_idle_timeout/1,
set_idle_timeout/2, clear_spawn_img_comp/1,
now/0]).
-compile({no_auto_import, [now/0]}).
List of pairs where the first component is an atom , the second
Master - > Worker : { init , StaticMachConf }
Master / Worker - > Worker : { vertex , X , Slot , K }
Worker - > Master : { result , Xs , Stats }
compute orbit of elements in list under list of generators Gs ;
* N : run the sequential algorithm with table size N
* host name H ( ie . name of Erlang node ) ,
a list of statistics , the first element of which reports overall statistics ,
orbit(Gs, Xs, Hosts) ->
if
is_integer(Hosts) ->
TableSize = Hosts,
sequential:orbit(Gs, Xs, TableSize);
true ->
par_orbit(Gs, Xs, Hosts)
end.
par_orbit(Gs, Xs, Hosts) ->
{Workers, GlobTabSize} = start_workers(Hosts),
assemble StaticMachConf and distribute to Workers
StaticMachConf = mk_static_mach_conf(Gs, self(), Workers, GlobTabSize),
lists:foreach(fun({Pid, _, _}) -> Pid ! {init, StaticMachConf} end, Workers),
StartTime = now(),
Credit = worker:distribute_vertices(StaticMachConf, credit:one(), Xs),
collect_credit(Credit),
ElapsedTime = now() - StartTime,
lists:foreach(fun({Pid, _, _}) -> Pid ! {dump} end, Workers),
collect_orbit(ElapsedTime, length(Workers)).
executing Erlang node ;
* if Hosts is a non - empty list { H1 , P1 , _ , _ , _ } , { H2 , P2 , _ , _ , _ } , ...
then P1 processes are forked on Erlang node H1 , P2 processes on node H2 ,
* Workers is a list of Worker , sorted wrt . TableOffset in ascending order .
start_workers({Procs, TabSize, TmOut, SpawnImgComp}) ->
{Workers, GlobalTableSize} = do_start_shm({Procs, TabSize, TmOut, SpawnImgComp}, {[], 0}),
{lists:reverse(Workers), GlobalTableSize};
start_workers([Host | Hosts]) ->
{Workers, GlobalTableSize} = do_start_dist([Host | Hosts], {[], 0}),
{lists:reverse(Workers), GlobalTableSize}.
do_start_shm({0, _, _, _}, Acc) ->
Acc;
do_start_shm({M, TabSize, TmOut, SpawnImgComp}, {Workers, GTabSize}) ->
Pid = spawn_link(worker, init, [TabSize, TmOut, SpawnImgComp]),
NewWorkers = [{Pid, GTabSize, TabSize} | Workers],
NewGTabSize = GTabSize + TabSize,
Acc = {NewWorkers, NewGTabSize},
do_start_shm({M - 1, TabSize, TmOut, SpawnImgComp}, Acc).
do_start_dist([], Acc) ->
Acc;
do_start_dist([{_, 0, _, _, _} | Hosts], Acc) ->
do_start_dist(Hosts, Acc);
do_start_dist([{Node, M, TabSize, TmOut, SpawnImgComp} | Hosts], {Workers, GTabSize}) ->
Pid = spawn_link(Node, worker, init, [TabSize, TmOut, SpawnImgComp]),
NewWorkers = [{Pid, GTabSize, TabSize} | Workers],
NewGTabSize = GTabSize + TabSize,
Acc = {NewWorkers, NewGTabSize},
do_start_dist([{Node, M - 1, TabSize, TmOut, SpawnImgComp} | Hosts], Acc).
the credit adds up to 1 .
collect_credit(Credit) ->
case credit:is_one(Credit) of
_Else ->
receive
{done, WorkersCredit} ->
CollectedCredit = credit:credit(WorkersCredit, Credit),
collect_credit(CollectedCredit)
end
end.
collect_orbit(ElapsedTime, N) ->
{PartOrbits, WorkerStats} = do_collect_orbit(N, [], []),
Orbit = lists:flatten(PartOrbits),
Stats = [master_stats(ElapsedTime, WorkerStats) | WorkerStats],
{Orbit, Stats}.
do_collect_orbit(0, PartOrbits, WorkerStats) -> {PartOrbits, WorkerStats};
do_collect_orbit(N, PartOrbits, WorkerStats) ->
receive
{result, PartOrbit, WorkerStat} ->
do_collect_orbit(N - 1, [PartOrbit|PartOrbits], [WorkerStat|WorkerStats])
end.
functions operating on the StaticMachConf
mk_static_mach_conf(Gs, Master, Workers, GlobalTableSize) ->
{Gs, Master, Workers, GlobalTableSize, 0, true}.
get_gens(StaticMachConf) -> element(1, StaticMachConf).
get_master(StaticMachConf) -> element(2, StaticMachConf).
get_workers(StaticMachConf) -> element(3, StaticMachConf).
get_global_table_size(StaticMachConf) -> element(4, StaticMachConf).
get_idle_timeout(StaticMachConf) -> element(5, StaticMachConf).
get_spawn_img_comp(StaticMachConf) -> element(6, StaticMachConf).
set_idle_timeout(StaticMachConf, X) -> setelement(5, StaticMachConf, X).
clear_spawn_img_comp(StaticMachConf) -> setelement(6, StaticMachConf, false).
master_stats(ElapsedTime, WorkerStats) ->
Freq = table:sum_freqs([table:freq_from_stat(W) || W <- WorkerStats]),
VertsRecvd = lists:sum([worker:verts_recvd_from_stat(W) || W <- WorkerStats]),
CreditRetd = lists:sum([worker:credit_retd_from_stat(W) || W <- WorkerStats]),
MinAtomicCredit = lists:max([worker:min_atomic_credit_from_stat(W) || W <- WorkerStats]),
MaxInitIdle = lists:max([worker:init_idle_from_stat(W) || W <- WorkerStats]),
MaxIdle = lists:max([worker:max_idle_from_stat(W) || W <- WorkerStats]),
MaxTailIdle = lists:max([worker:tail_idle_from_stat(W) || W <- WorkerStats]),
[{wall_time, ElapsedTime},
{vertices_recvd, VertsRecvd},
{credit_retd, CreditRetd},
{min_atomic_credit, MinAtomicCredit},
{max_init_idle_time, MaxInitIdle},
{max_idle_time, MaxIdle},
{max_tail_idle_time, MaxTailIdle} | table:freq_to_stat(Freq)].
now() -> element(1, statistics(wall_clock)).
|
5026a2298bc74070eebd4249c4bf0abca1927b8e3c904cd979e4113374bfdbca | chetmurthy/ensemble | rand.ml | (**************************************************************)
RAND.ML : Randomly multicast / send messages and fail
Author : , 6/95
(**************************************************************)
open Ensemble
open Trans
open Util
open Arge
open View
open Buf
open Appl_intf open New
(**************************************************************)
let name = Trace.file "RAND"
let failwith s = Trace.make_failwith name s
let log = Trace.log name
(**************************************************************)
let size = ref 100
let max_time = ref Time.zero
type program = With_iov | No_iov
type state = {
mutable max_ltime : ltime ;
mutable next_action : Time.t ;
mutable last_view : Time.t
}
(**************************************************************)
let dump (ls,vs) s =
eprintf "RAND:dump:%s\n" ls.name ;
eprintf " last_view=%s\n" (Time.to_string s.last_view) ;
eprintf " rank=%d, nmembers=%d\n" ls.rank ls.nmembers
(**************************************************************)
(* A test that uses only meta-data and sends no iovectors.
*)
module NO_IOV = struct
type action = | ALeave | ASuspect | ANone
let string_of_action = function
| ALeave -> "ALeave"
| ASuspect-> "ASuspect"
| ANone -> "ANone"
let policy my_rank nmembers thresh =
let next = Random.int 10000000 * nmembers in
let p = Random.int 100 in
let action =
if nmembers >= thresh then (
if p*nmembers < 10 then ALeave
else if p*nmembers < 20 then ASuspect
else ANone
) else
ANone
in
log (fun () -> string_of_action action);
(action,(Time.of_ints 0 next))
let interface alarm thresh on_exit time primary_views local_send =
log (fun () -> "NO_IOV.interface");
let s = {
max_ltime = 0 ;
last_view = time ;
next_action = Time.zero
} in
let install ((ls,vs) as vf) =
let rec choose_dest () =
if ls.nmembers = 1 then None
else
let r = Random.int ls.nmembers in
if r = ls.rank then choose_dest ()
else Some r
in
let heartbeat time =
max_time := max time !max_time ;
let acts = ref [] in
if Param.bool vs.params "top_dump_linger"
&& s.last_view <> Time.invalid
&& time >= Time.add s.last_view (Time.of_int 1000)
then (
printf "RAND: Error, the view lingered more than 1000 simulated seconds";
dump vf s ;
s.last_view <- time ;
acts := Control Dump :: !acts
) ;
(**)
if Time.ge time s.next_action then (
let (action,next) = policy ls.rank ls.nmembers thresh in
s.next_action <- Time.add time next ;
match action with
| ALeave ->
acts := Control Leave :: !acts ;
if !verbose then (
printf "RAND:%s:Leaving(nmembers=%d)\n" ls.name ls.nmembers
)
| ASuspect ->
begin match choose_dest () with
| None -> ()
| Some x -> acts := (Control(Suspect [x])) :: !acts
end
| ANone -> ()
) ;
Array.of_list !acts
in
let receive o bk cs msg = failwith "should not receive messages in this test"
in
let block () = [||]
in
let handlers = {
flow_block = (fun _ -> ());
receive = receive ;
block = block ;
heartbeat = heartbeat ;
disable = Util.ident
} in
s.last_view <- !max_time ;
s.max_ltime <- max s.max_ltime vs.ltime ;
s.next_action <- Time.zero ;
if (not !quiet)
&& (!verbose || ls.rank = 0) then
printf "RAND:%s:(time=%s) View=(xfer=%s;prim=%s)%s\n"
ls.name
(Time.to_string !max_time)
(string_of_bool vs.xfer_view)
(string_of_bool vs.primary)
(View.to_string vs.view);
[||],handlers
in
let exit () =
on_exit (succ s.max_ltime)
in
{
heartbeat_rate = Time.of_int 1 ;
install = install ;
exit = exit
}
end
(**************************************************************)
module WITH_IOV = struct
type action = ACast | ASend1 | ASend | ALeave | ANone
let string_of_action = function
| ACast -> "ACast"
| ASend1 -> "ASend1"
| ASend -> "ASend"
| ALeave -> "ALeave"
| ANone -> "ANone"
let policy my_rank nmembers thresh =
let next = Random.int 10000000 * nmembers in
let p = Random.int 100 in
let action =
if nmembers >= thresh then (
if p*nmembers*2 < 10 then ALeave
else if p < 40 then ACast
else if p < 70 then ASend
else ASend1
) else
ANone
in
if p < 10 then
log (fun () -> string_of_action action);
(action,(Time.of_ints 0 next))
(**************************************************************)
let digest iovl =
let md5 = Hsys.md5_init () in
Hsys.md5_update_iovl md5 iovl ;
Hsys.md5_final md5
let gen_msg () =
let len =
if !size > 0 then Random.int !size
else 0
in
let send_pool = Iovec.get_send_pool () in
log (fun () -> sprintf "gen_msg: len=%d" len );
let len = Buf.len_of_int len in
let iov = Iovec.alloc send_pool len in
let iov = Iovecl.of_iovec iov in
let d = digest iov in
let d = Iovec.of_buf send_pool (Buf.of_string d) len0 md5len in
let iovl = Iovecl.prependi d iov in
iovl
let check iovl =
let len = Iovecl.len iovl in
assert (len >= md5len) ;
let d_iovl = Iovecl.sub iovl len0 md5len in
let d_iov = Iovecl.flatten d_iovl in
let d = Iovec.buf_of d_iov in
Iovec.free d_iov ;
Iovecl.free d_iovl ;
let iovl = Iovecl.sub iovl md5len (len -|| md5len) in
let d' = Buf.of_string (digest iovl) in
Iovecl.free iovl ;
if d <> d' then
failwith "bad message"
(**************************************************************)
let interface alarm thresh on_exit time primary_views local_send =
log (fun () -> "WITH_IOV.interface");
let s = {
max_ltime = 0 ;
last_view = time ;
next_action = Time.zero
} in
let install ((ls,vs) as vf) =
let msg () = gen_msg () in
let rec choose_dest () =
if ls.nmembers = 1 then None
else
let r = Random.int ls.nmembers in
if local_send then Some r
else
if r = ls.rank then choose_dest ()
else Some r
in
let block_msg () =
if Random.int 2 = 0 then (
Cast(gen_msg ())
) else (
match choose_dest () with
| Some dest -> Send1(dest,gen_msg())
| None -> failwith "Sanity: could not choose a peer in the group, group size must be 1."
)
in
let heartbeat time =
max_time := max time !max_time ;
let acts = ref [] in
if Param.bool vs.params "top_dump_linger"
&& s.last_view <> Time.invalid
&& time >= Time.add s.last_view (Time.of_int 10000)
then (
printf "RAND: Error, the view lingered more than 10000 simulated seconds";
dump vf s ;
s.last_view <- time ;
acts := Control Dump :: !acts
) ;
(**)
if Time.ge time s.next_action then (
let (action,next) = policy ls.rank ls.nmembers thresh in
s.next_action <- Time.add time next ;
match action with
| ACast ->
(*
eprintf "RAND:%s:casting\n" ls.name ;
*)
acts := [Cast(msg())] @ !acts;
| ASend1 -> (
match choose_dest () with
None -> ()
| Some dest ->
acts := [Send1(dest, msg())] @ !acts;
)
| ASend -> (
let dest1 = choose_dest () in
let dest2 = choose_dest () in
match dest1,dest2 with
| Some dest1, Some dest2 ->
log (fun () -> sprintf "Send([%d;%d])" dest1 dest2);
acts := [Send([|dest1; dest2|], msg())] @ !acts;
| _ -> ()
)
| ALeave ->
acts := [Cast(msg()); Cast(msg()); Cast(msg()); Control(Leave)] @ !acts ;
if !verbose then (
printf "RAND:%s:Leaving(nmembers=%d)\n" ls.name ls.nmembers
)
| ANone -> ()
) ;
Array.of_list !acts
in
let receive o bk cs =
let handle msg =
if vs.ltime <> s.max_ltime then (
eprintf "RAND:received non-synchronized message\n" ;
eprintf "RAND:origin=%d blocked=%s type=%s\n"
o (string_of_blocked bk) (string_of_cs cs) ;
dump vf s ;
failwith "non-synchronized message"
) ;
check msg ;
Iovecl.free msg;
[||]
in handle
in
let block () =
if ls.nmembers > 1 then (
(*Array.init 5 (fun _ -> block_msg ())*) [||]
) else [||]
in
let handlers = {
flow_block = (fun _ -> ());
receive = receive ;
block = block ;
heartbeat = heartbeat ;
disable = Util.ident
} in
s.last_view <- !max_time ;
s.max_ltime <- max s.max_ltime vs.ltime ;
s.next_action <- Time.zero ;
if (not !quiet)
&& (!verbose || ls.rank = 0) then
printf "RAND:%s:(time=%s) View=(xfer=%s;prim=%s)%s\n"
ls.name
(Time.to_string !max_time)
(string_of_bool vs.xfer_view)
(string_of_bool vs.primary)
(View.to_string vs.view) ;
if vs.primary then (
let ltime = vs.ltime in
begin
try
let vs' = Hashtbl.find primary_views ltime in
if vs <> vs' then (
printf "Previous view state:\n%s\n" (View.string_of_state vs') ;
printf "Current view state:\n%s\n" (View.string_of_state vs) ;
printf " Previous view state:%s " ( View.string_of_id vs'.view_id ) ;
printf " Current view state:%s " ( View.string_of_id vs.view_id ) ;
printf "Previous view state:%s" (View.string_of_id vs'.view_id) ;
printf "Current view state:%s" (View.string_of_id vs.view_id) ;
*)
failwith "Two primary partitions have the same logical time !!" ;
)
with Not_found ->
Hashtbl.add primary_views ltime vs
end
) ;
let actions =
if vs.xfer_view then
[|Control XferDone|]
else
[|Cast (msg ())|]
in
actions,handlers
in
let exit () =
on_exit (succ s.max_ltime)
in
{
heartbeat_rate = Time.of_int 1 ;
install = install ;
exit = exit
}
end
(**************************************************************)
let thresh = ref 5
let nmembers = ref 7
let groupd_local = ref false
let ngroupds = ref 3
let local_send = ref false
let prog = ref "with_iov"
(**************************************************************)
let run () =
let primary_views = Hashtbl.create 503 in
let props = Property.Drop :: Property.Debug :: Property.vsync in
Param.default "top_dump_linger" (Param.Bool true) ;
Param.default "top_dump_fail" (Param.Bool true) ;
Arge.set alarm "Netsim" ;
Arge.set modes [Addr.Netsim] ;
Arge.set properties props ;
Arge.set short_names true ;
let undoc = ": undocumented" in
Arge.parse [
"-n", Arg.Int(fun i -> nmembers := i),undoc ;
"-t", Arg.Int(fun i -> thresh := i),undoc ;
"-s", Arg.Int(fun i -> size := i),undoc ;
"-groupd_local", Arg.Set(groupd_local),undoc ;
"-quiet", Arg.Set(quiet),undoc ;
"-ngroupds", Arg.Int (fun i -> ngroupds := i), "number of group-daemons" ;
"-local_send", Arg.Set(local_send), "test sends from an endpoint to itself";
"-prog", Arg.String (fun s -> prog :=s ), "which program: [with_iov|no_iov]"
] (Arge.badarg name)
"rand: random failure generation test program" ;
let prog = match !prog with
| "with_iov" -> With_iov
| "no_iov" -> No_iov
| _ -> failwith "no such program. Available: [with_iov|no_iov]"
in
Clear the iovec system for the No_iov test
begin match prog with
| With_iov -> ()
| No_iov -> Iovec.shutdown ()
end;
let alarm = Appl.alarm name in
if Arge.get Arge.modes = [Addr.Netsim] then (
Alarm.install_port (-2) ;
) ;
let gettime () =
let time = Alarm.gettime alarm in
if Time.is_zero !max_time then
max_time := time ;
time
in
let interface = match prog with
| With_iov -> WITH_IOV.interface
| No_iov -> NO_IOV.interface
in
let instance =
if not !groupd_local then (
let rec instance (ls,vs) ltime =
let ( ls , vs ) = " rand " in
let vs = View.set vs [Vs_ltime ltime] in
let ls = View.local name ls.endpt vs in
let time = gettime() in
let interface = interface alarm !thresh (instance (ls,vs)) time
primary_views !local_send
in
Appl.config_new interface (ls,vs)
in instance
) else (
(* Start up some number of local groupd daemons.
*)
let ngroupds = !ngroupds in
let groupds =
Arrayf.init ngroupds (fun _ ->
let vf = Appl.default_info "groupd" in
let handle,vf,interface = Manage.groupd_create alarm vf in
Appl.config_new interface vf ;
handle
)
in
(* Set this here so that the groupd endpoints don't
* use it.
*)
Arge.set groupd true ;
let rec instance (ls,vs) ltime =
let (ls,vs) = Appl.default_info "rand" in
let vs = View.set vs [Vs_ltime ltime] in
let ls = View.local name ls.endpt vs in
let time = gettime() in
let interface = WITH_IOV.interface alarm !thresh (instance (ls,vs)) time primary_views !local_send in
let groupd = Arrayf.get groupds (Random.int ngroupds) in
let glue = Arge.get Arge.glue in
let state = Layer.new_state interface in
let member = Stacke.config_full glue alarm Addr.default_ranking state in
let res = groupd (ls,vs) member in
res
in instance
)
in
for i = 1 to !nmembers do
let (ls,vs) = Appl.default_info name in
instance (ls,vs) 0
done ;
Sys.catch_break true ;
Appl.main_loop ()
let _ = Appl.exec ["rand"] run
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/prog/rand.ml | ocaml | ************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
A test that uses only meta-data and sends no iovectors.
************************************************************
************************************************************
************************************************************
eprintf "RAND:%s:casting\n" ls.name ;
Array.init 5 (fun _ -> block_msg ())
************************************************************
************************************************************
Start up some number of local groupd daemons.
Set this here so that the groupd endpoints don't
* use it.
************************************************************ | RAND.ML : Randomly multicast / send messages and fail
Author : , 6/95
open Ensemble
open Trans
open Util
open Arge
open View
open Buf
open Appl_intf open New
let name = Trace.file "RAND"
let failwith s = Trace.make_failwith name s
let log = Trace.log name
let size = ref 100
let max_time = ref Time.zero
type program = With_iov | No_iov
type state = {
mutable max_ltime : ltime ;
mutable next_action : Time.t ;
mutable last_view : Time.t
}
let dump (ls,vs) s =
eprintf "RAND:dump:%s\n" ls.name ;
eprintf " last_view=%s\n" (Time.to_string s.last_view) ;
eprintf " rank=%d, nmembers=%d\n" ls.rank ls.nmembers
module NO_IOV = struct
type action = | ALeave | ASuspect | ANone
let string_of_action = function
| ALeave -> "ALeave"
| ASuspect-> "ASuspect"
| ANone -> "ANone"
let policy my_rank nmembers thresh =
let next = Random.int 10000000 * nmembers in
let p = Random.int 100 in
let action =
if nmembers >= thresh then (
if p*nmembers < 10 then ALeave
else if p*nmembers < 20 then ASuspect
else ANone
) else
ANone
in
log (fun () -> string_of_action action);
(action,(Time.of_ints 0 next))
let interface alarm thresh on_exit time primary_views local_send =
log (fun () -> "NO_IOV.interface");
let s = {
max_ltime = 0 ;
last_view = time ;
next_action = Time.zero
} in
let install ((ls,vs) as vf) =
let rec choose_dest () =
if ls.nmembers = 1 then None
else
let r = Random.int ls.nmembers in
if r = ls.rank then choose_dest ()
else Some r
in
let heartbeat time =
max_time := max time !max_time ;
let acts = ref [] in
if Param.bool vs.params "top_dump_linger"
&& s.last_view <> Time.invalid
&& time >= Time.add s.last_view (Time.of_int 1000)
then (
printf "RAND: Error, the view lingered more than 1000 simulated seconds";
dump vf s ;
s.last_view <- time ;
acts := Control Dump :: !acts
) ;
if Time.ge time s.next_action then (
let (action,next) = policy ls.rank ls.nmembers thresh in
s.next_action <- Time.add time next ;
match action with
| ALeave ->
acts := Control Leave :: !acts ;
if !verbose then (
printf "RAND:%s:Leaving(nmembers=%d)\n" ls.name ls.nmembers
)
| ASuspect ->
begin match choose_dest () with
| None -> ()
| Some x -> acts := (Control(Suspect [x])) :: !acts
end
| ANone -> ()
) ;
Array.of_list !acts
in
let receive o bk cs msg = failwith "should not receive messages in this test"
in
let block () = [||]
in
let handlers = {
flow_block = (fun _ -> ());
receive = receive ;
block = block ;
heartbeat = heartbeat ;
disable = Util.ident
} in
s.last_view <- !max_time ;
s.max_ltime <- max s.max_ltime vs.ltime ;
s.next_action <- Time.zero ;
if (not !quiet)
&& (!verbose || ls.rank = 0) then
printf "RAND:%s:(time=%s) View=(xfer=%s;prim=%s)%s\n"
ls.name
(Time.to_string !max_time)
(string_of_bool vs.xfer_view)
(string_of_bool vs.primary)
(View.to_string vs.view);
[||],handlers
in
let exit () =
on_exit (succ s.max_ltime)
in
{
heartbeat_rate = Time.of_int 1 ;
install = install ;
exit = exit
}
end
module WITH_IOV = struct
type action = ACast | ASend1 | ASend | ALeave | ANone
let string_of_action = function
| ACast -> "ACast"
| ASend1 -> "ASend1"
| ASend -> "ASend"
| ALeave -> "ALeave"
| ANone -> "ANone"
let policy my_rank nmembers thresh =
let next = Random.int 10000000 * nmembers in
let p = Random.int 100 in
let action =
if nmembers >= thresh then (
if p*nmembers*2 < 10 then ALeave
else if p < 40 then ACast
else if p < 70 then ASend
else ASend1
) else
ANone
in
if p < 10 then
log (fun () -> string_of_action action);
(action,(Time.of_ints 0 next))
let digest iovl =
let md5 = Hsys.md5_init () in
Hsys.md5_update_iovl md5 iovl ;
Hsys.md5_final md5
let gen_msg () =
let len =
if !size > 0 then Random.int !size
else 0
in
let send_pool = Iovec.get_send_pool () in
log (fun () -> sprintf "gen_msg: len=%d" len );
let len = Buf.len_of_int len in
let iov = Iovec.alloc send_pool len in
let iov = Iovecl.of_iovec iov in
let d = digest iov in
let d = Iovec.of_buf send_pool (Buf.of_string d) len0 md5len in
let iovl = Iovecl.prependi d iov in
iovl
let check iovl =
let len = Iovecl.len iovl in
assert (len >= md5len) ;
let d_iovl = Iovecl.sub iovl len0 md5len in
let d_iov = Iovecl.flatten d_iovl in
let d = Iovec.buf_of d_iov in
Iovec.free d_iov ;
Iovecl.free d_iovl ;
let iovl = Iovecl.sub iovl md5len (len -|| md5len) in
let d' = Buf.of_string (digest iovl) in
Iovecl.free iovl ;
if d <> d' then
failwith "bad message"
let interface alarm thresh on_exit time primary_views local_send =
log (fun () -> "WITH_IOV.interface");
let s = {
max_ltime = 0 ;
last_view = time ;
next_action = Time.zero
} in
let install ((ls,vs) as vf) =
let msg () = gen_msg () in
let rec choose_dest () =
if ls.nmembers = 1 then None
else
let r = Random.int ls.nmembers in
if local_send then Some r
else
if r = ls.rank then choose_dest ()
else Some r
in
let block_msg () =
if Random.int 2 = 0 then (
Cast(gen_msg ())
) else (
match choose_dest () with
| Some dest -> Send1(dest,gen_msg())
| None -> failwith "Sanity: could not choose a peer in the group, group size must be 1."
)
in
let heartbeat time =
max_time := max time !max_time ;
let acts = ref [] in
if Param.bool vs.params "top_dump_linger"
&& s.last_view <> Time.invalid
&& time >= Time.add s.last_view (Time.of_int 10000)
then (
printf "RAND: Error, the view lingered more than 10000 simulated seconds";
dump vf s ;
s.last_view <- time ;
acts := Control Dump :: !acts
) ;
if Time.ge time s.next_action then (
let (action,next) = policy ls.rank ls.nmembers thresh in
s.next_action <- Time.add time next ;
match action with
| ACast ->
acts := [Cast(msg())] @ !acts;
| ASend1 -> (
match choose_dest () with
None -> ()
| Some dest ->
acts := [Send1(dest, msg())] @ !acts;
)
| ASend -> (
let dest1 = choose_dest () in
let dest2 = choose_dest () in
match dest1,dest2 with
| Some dest1, Some dest2 ->
log (fun () -> sprintf "Send([%d;%d])" dest1 dest2);
acts := [Send([|dest1; dest2|], msg())] @ !acts;
| _ -> ()
)
| ALeave ->
acts := [Cast(msg()); Cast(msg()); Cast(msg()); Control(Leave)] @ !acts ;
if !verbose then (
printf "RAND:%s:Leaving(nmembers=%d)\n" ls.name ls.nmembers
)
| ANone -> ()
) ;
Array.of_list !acts
in
let receive o bk cs =
let handle msg =
if vs.ltime <> s.max_ltime then (
eprintf "RAND:received non-synchronized message\n" ;
eprintf "RAND:origin=%d blocked=%s type=%s\n"
o (string_of_blocked bk) (string_of_cs cs) ;
dump vf s ;
failwith "non-synchronized message"
) ;
check msg ;
Iovecl.free msg;
[||]
in handle
in
let block () =
if ls.nmembers > 1 then (
) else [||]
in
let handlers = {
flow_block = (fun _ -> ());
receive = receive ;
block = block ;
heartbeat = heartbeat ;
disable = Util.ident
} in
s.last_view <- !max_time ;
s.max_ltime <- max s.max_ltime vs.ltime ;
s.next_action <- Time.zero ;
if (not !quiet)
&& (!verbose || ls.rank = 0) then
printf "RAND:%s:(time=%s) View=(xfer=%s;prim=%s)%s\n"
ls.name
(Time.to_string !max_time)
(string_of_bool vs.xfer_view)
(string_of_bool vs.primary)
(View.to_string vs.view) ;
if vs.primary then (
let ltime = vs.ltime in
begin
try
let vs' = Hashtbl.find primary_views ltime in
if vs <> vs' then (
printf "Previous view state:\n%s\n" (View.string_of_state vs') ;
printf "Current view state:\n%s\n" (View.string_of_state vs) ;
printf " Previous view state:%s " ( View.string_of_id vs'.view_id ) ;
printf " Current view state:%s " ( View.string_of_id vs.view_id ) ;
printf "Previous view state:%s" (View.string_of_id vs'.view_id) ;
printf "Current view state:%s" (View.string_of_id vs.view_id) ;
*)
failwith "Two primary partitions have the same logical time !!" ;
)
with Not_found ->
Hashtbl.add primary_views ltime vs
end
) ;
let actions =
if vs.xfer_view then
[|Control XferDone|]
else
[|Cast (msg ())|]
in
actions,handlers
in
let exit () =
on_exit (succ s.max_ltime)
in
{
heartbeat_rate = Time.of_int 1 ;
install = install ;
exit = exit
}
end
let thresh = ref 5
let nmembers = ref 7
let groupd_local = ref false
let ngroupds = ref 3
let local_send = ref false
let prog = ref "with_iov"
let run () =
let primary_views = Hashtbl.create 503 in
let props = Property.Drop :: Property.Debug :: Property.vsync in
Param.default "top_dump_linger" (Param.Bool true) ;
Param.default "top_dump_fail" (Param.Bool true) ;
Arge.set alarm "Netsim" ;
Arge.set modes [Addr.Netsim] ;
Arge.set properties props ;
Arge.set short_names true ;
let undoc = ": undocumented" in
Arge.parse [
"-n", Arg.Int(fun i -> nmembers := i),undoc ;
"-t", Arg.Int(fun i -> thresh := i),undoc ;
"-s", Arg.Int(fun i -> size := i),undoc ;
"-groupd_local", Arg.Set(groupd_local),undoc ;
"-quiet", Arg.Set(quiet),undoc ;
"-ngroupds", Arg.Int (fun i -> ngroupds := i), "number of group-daemons" ;
"-local_send", Arg.Set(local_send), "test sends from an endpoint to itself";
"-prog", Arg.String (fun s -> prog :=s ), "which program: [with_iov|no_iov]"
] (Arge.badarg name)
"rand: random failure generation test program" ;
let prog = match !prog with
| "with_iov" -> With_iov
| "no_iov" -> No_iov
| _ -> failwith "no such program. Available: [with_iov|no_iov]"
in
Clear the iovec system for the No_iov test
begin match prog with
| With_iov -> ()
| No_iov -> Iovec.shutdown ()
end;
let alarm = Appl.alarm name in
if Arge.get Arge.modes = [Addr.Netsim] then (
Alarm.install_port (-2) ;
) ;
let gettime () =
let time = Alarm.gettime alarm in
if Time.is_zero !max_time then
max_time := time ;
time
in
let interface = match prog with
| With_iov -> WITH_IOV.interface
| No_iov -> NO_IOV.interface
in
let instance =
if not !groupd_local then (
let rec instance (ls,vs) ltime =
let ( ls , vs ) = " rand " in
let vs = View.set vs [Vs_ltime ltime] in
let ls = View.local name ls.endpt vs in
let time = gettime() in
let interface = interface alarm !thresh (instance (ls,vs)) time
primary_views !local_send
in
Appl.config_new interface (ls,vs)
in instance
) else (
let ngroupds = !ngroupds in
let groupds =
Arrayf.init ngroupds (fun _ ->
let vf = Appl.default_info "groupd" in
let handle,vf,interface = Manage.groupd_create alarm vf in
Appl.config_new interface vf ;
handle
)
in
Arge.set groupd true ;
let rec instance (ls,vs) ltime =
let (ls,vs) = Appl.default_info "rand" in
let vs = View.set vs [Vs_ltime ltime] in
let ls = View.local name ls.endpt vs in
let time = gettime() in
let interface = WITH_IOV.interface alarm !thresh (instance (ls,vs)) time primary_views !local_send in
let groupd = Arrayf.get groupds (Random.int ngroupds) in
let glue = Arge.get Arge.glue in
let state = Layer.new_state interface in
let member = Stacke.config_full glue alarm Addr.default_ranking state in
let res = groupd (ls,vs) member in
res
in instance
)
in
for i = 1 to !nmembers do
let (ls,vs) = Appl.default_info name in
instance (ls,vs) 0
done ;
Sys.catch_break true ;
Appl.main_loop ()
let _ = Appl.exec ["rand"] run
|
086ae4ed3a1732afc09f891e96624b852fee0691d6854e9c9098c847833e2999 | monadbobo/ocaml-core | extended_hashtbl.mli | open Core.Std
module Access_control : sig
type ('key,'data,+'z) any
module Immutable : sig
type ('key,'data) t = ('key,'data,immutable) any
include Sexpable.S2 with type ('key,'data) t := ('key,'data) t
include Binable.S2 with type ('key,'data) t := ('key,'data) t
end
module Read_only : sig
type ('key,'data) t = ('key,'data,read_only) any
include Sexpable.S2 with type ('key,'data) t := ('key,'data) t
include Binable.S2 with type ('key,'data) t := ('key,'data) t
end
module Read_write : sig
type ('key,'data) t = ('key,'data, read_write) any
include Sexpable.S2 with type ('key,'data) t := ('key,'data) t
include Binable.S2 with type ('key,'data) t := ('key,'data) t
end
val of_hashtbl : ('key,'data) Hashtbl.t -> ('key,'data,_) any
val clear : (_, _) Read_write.t -> unit
val copy : ('a, 'b, _) any -> ('a, 'b, _) any
val fold :
('a, 'b,_) any -> init:'c -> f:(key:'a -> data:'b -> 'c -> 'c) -> 'c
val iter : ('a, 'b, _) any -> f:(key:'a -> data:'b -> unit) -> unit
val existsi : ('a, 'b, _) any -> f:(key: 'a -> data:'b -> bool) -> bool
val exists : ('a, 'b, _) any -> f:('b -> bool) -> bool
val length : (_, _, _) any -> int
val is_empty : (_, _, _) any -> bool
val mem : ('a, _, _) any -> 'a -> bool
val remove : ('a, _) Read_write.t -> 'a -> unit
val remove_one : ('a, _ list) Read_write.t -> 'a -> unit
val replace : ('a, 'b) Read_write.t -> key:'a -> data:'b -> unit
val set : ('a, 'b) Read_write.t -> key:'a -> data:'b -> unit
val add : ('a, 'b) Read_write.t -> key:'a -> data:'b -> [ `Ok | `Duplicate ]
val add_exn : ('a, 'b) Read_write.t -> key:'a -> data:'b -> unit
val change : ('a, 'b) Read_write.t -> 'a -> ('b option -> 'b option) -> unit
val add_multi : ('a, 'b list) Read_write.t -> key:'a -> data:'b -> unit
val map : ('a, 'b, _) any -> f:('b -> 'c) -> ('a, 'c, _) any
val mapi : ('a, 'b, _) any -> f:(key:'a -> data:'b -> 'c) -> ('a, 'c, _) any
val filter_map : ('a, 'b, _) any -> f:('b -> 'c option) -> ('a, 'c, _) any
val filter_mapi : ('a, 'b, _) any -> f:(key:'a -> data:'b -> 'c option) -> ('a, 'c, _) any
val filter : ('a, 'b, _) any -> f:('b -> bool) -> ('a, 'b, _) any
val filteri : ('a, 'b, _) any -> f:(key:'a -> data:'b -> bool) -> ('a, 'b, _) any
val find_or_add : ('a, 'b, _) any -> 'a -> default:(unit -> 'b) -> 'b
val find : ('a, 'b, _) any -> 'a -> 'b option
val find_exn : ('a, 'b, _) any -> 'a -> 'b
val iter_vals : ('a, 'b, _) any -> f:('b -> unit) -> unit
val merge :
('k, 'a, _) any
-> ('k, 'b, _) any
-> f:(key:'k -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option)
-> ('k, 'c, _) any
val merge_into:
f:(key:'a -> 'b -> 'b option -> 'b option)
-> src:('a, 'b, _) any
-> dst:('a, 'b) Read_write.t
-> unit
val keys : ('a, 'b, _) any -> 'a list
val data : ('a, 'b, _) any -> 'b list
val filter_inplace : ('a, 'b) Read_write.t -> f:('b -> bool) -> unit
val filteri_inplace : ('a, 'b) Read_write.t -> f:('a -> 'b -> bool) -> unit
val equal : ('a, 'b, _) any -> ('a, 'b, _) any -> ('b -> 'b -> bool) -> bool
val to_alist : ('a, 'b, _) any -> ('a * 'b) list
val incr : ?by:int -> ('a, int) Read_write.t -> 'a -> unit
end
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/extended_hashtbl.mli | ocaml | open Core.Std
module Access_control : sig
type ('key,'data,+'z) any
module Immutable : sig
type ('key,'data) t = ('key,'data,immutable) any
include Sexpable.S2 with type ('key,'data) t := ('key,'data) t
include Binable.S2 with type ('key,'data) t := ('key,'data) t
end
module Read_only : sig
type ('key,'data) t = ('key,'data,read_only) any
include Sexpable.S2 with type ('key,'data) t := ('key,'data) t
include Binable.S2 with type ('key,'data) t := ('key,'data) t
end
module Read_write : sig
type ('key,'data) t = ('key,'data, read_write) any
include Sexpable.S2 with type ('key,'data) t := ('key,'data) t
include Binable.S2 with type ('key,'data) t := ('key,'data) t
end
val of_hashtbl : ('key,'data) Hashtbl.t -> ('key,'data,_) any
val clear : (_, _) Read_write.t -> unit
val copy : ('a, 'b, _) any -> ('a, 'b, _) any
val fold :
('a, 'b,_) any -> init:'c -> f:(key:'a -> data:'b -> 'c -> 'c) -> 'c
val iter : ('a, 'b, _) any -> f:(key:'a -> data:'b -> unit) -> unit
val existsi : ('a, 'b, _) any -> f:(key: 'a -> data:'b -> bool) -> bool
val exists : ('a, 'b, _) any -> f:('b -> bool) -> bool
val length : (_, _, _) any -> int
val is_empty : (_, _, _) any -> bool
val mem : ('a, _, _) any -> 'a -> bool
val remove : ('a, _) Read_write.t -> 'a -> unit
val remove_one : ('a, _ list) Read_write.t -> 'a -> unit
val replace : ('a, 'b) Read_write.t -> key:'a -> data:'b -> unit
val set : ('a, 'b) Read_write.t -> key:'a -> data:'b -> unit
val add : ('a, 'b) Read_write.t -> key:'a -> data:'b -> [ `Ok | `Duplicate ]
val add_exn : ('a, 'b) Read_write.t -> key:'a -> data:'b -> unit
val change : ('a, 'b) Read_write.t -> 'a -> ('b option -> 'b option) -> unit
val add_multi : ('a, 'b list) Read_write.t -> key:'a -> data:'b -> unit
val map : ('a, 'b, _) any -> f:('b -> 'c) -> ('a, 'c, _) any
val mapi : ('a, 'b, _) any -> f:(key:'a -> data:'b -> 'c) -> ('a, 'c, _) any
val filter_map : ('a, 'b, _) any -> f:('b -> 'c option) -> ('a, 'c, _) any
val filter_mapi : ('a, 'b, _) any -> f:(key:'a -> data:'b -> 'c option) -> ('a, 'c, _) any
val filter : ('a, 'b, _) any -> f:('b -> bool) -> ('a, 'b, _) any
val filteri : ('a, 'b, _) any -> f:(key:'a -> data:'b -> bool) -> ('a, 'b, _) any
val find_or_add : ('a, 'b, _) any -> 'a -> default:(unit -> 'b) -> 'b
val find : ('a, 'b, _) any -> 'a -> 'b option
val find_exn : ('a, 'b, _) any -> 'a -> 'b
val iter_vals : ('a, 'b, _) any -> f:('b -> unit) -> unit
val merge :
('k, 'a, _) any
-> ('k, 'b, _) any
-> f:(key:'k -> [ `Left of 'a | `Right of 'b | `Both of 'a * 'b ] -> 'c option)
-> ('k, 'c, _) any
val merge_into:
f:(key:'a -> 'b -> 'b option -> 'b option)
-> src:('a, 'b, _) any
-> dst:('a, 'b) Read_write.t
-> unit
val keys : ('a, 'b, _) any -> 'a list
val data : ('a, 'b, _) any -> 'b list
val filter_inplace : ('a, 'b) Read_write.t -> f:('b -> bool) -> unit
val filteri_inplace : ('a, 'b) Read_write.t -> f:('a -> 'b -> bool) -> unit
val equal : ('a, 'b, _) any -> ('a, 'b, _) any -> ('b -> 'b -> bool) -> bool
val to_alist : ('a, 'b, _) any -> ('a * 'b) list
val incr : ?by:int -> ('a, int) Read_write.t -> 'a -> unit
end
|
|
0f7422646ba93b3c88b6a773619629b28d8cbe3038ece620dc3cd1b1f11cfd8b | destenson/ConsenSys--Fae | Exceptions.hs | module Blockchain.Fae.Internal.Exceptions
(
module Blockchain.Fae.Internal.Exceptions,
module Control.Exception.Safe
) where
import Blockchain.Fae.Internal.Types
import Control.Exception.Safe
import Control.Monad.IO.Class
import Data.Typeable
data EntryException =
NoCurrentEntry |
BadEntryID EntryID |
WrongFacet EntryID FacetID FacetID |
BadEntryArgType EntryID TypeRep TypeRep |
BadEntryValType EntryID TypeRep TypeRep
deriving (Typeable, Show)
data EscrowException =
BadEscrowID EntryID |
BadTokenType EntryID TypeRep TypeRep |
BadPublicType EntryID TypeRep TypeRep |
BadPrivateType EntryID TypeRep TypeRep
deriving (Typeable, Show)
data FacetException =
NotAFacet FacetID |
NotADependentFacet FacetID FacetID
deriving (Typeable, Show)
data TransactionException =
BadTransactionID TransactionID
deriving (Typeable, Show)
instance Exception EntryException
instance Exception EscrowException
instance Exception FacetException
instance Exception TransactionException
| null | https://raw.githubusercontent.com/destenson/ConsenSys--Fae/9ba10ed3299f517ac5e44836ea8ee984dd41d0f4/src/Blockchain/Fae/Internal/Exceptions.hs | haskell | module Blockchain.Fae.Internal.Exceptions
(
module Blockchain.Fae.Internal.Exceptions,
module Control.Exception.Safe
) where
import Blockchain.Fae.Internal.Types
import Control.Exception.Safe
import Control.Monad.IO.Class
import Data.Typeable
data EntryException =
NoCurrentEntry |
BadEntryID EntryID |
WrongFacet EntryID FacetID FacetID |
BadEntryArgType EntryID TypeRep TypeRep |
BadEntryValType EntryID TypeRep TypeRep
deriving (Typeable, Show)
data EscrowException =
BadEscrowID EntryID |
BadTokenType EntryID TypeRep TypeRep |
BadPublicType EntryID TypeRep TypeRep |
BadPrivateType EntryID TypeRep TypeRep
deriving (Typeable, Show)
data FacetException =
NotAFacet FacetID |
NotADependentFacet FacetID FacetID
deriving (Typeable, Show)
data TransactionException =
BadTransactionID TransactionID
deriving (Typeable, Show)
instance Exception EntryException
instance Exception EscrowException
instance Exception FacetException
instance Exception TransactionException
|
|
edcd8b2eaa9f00c407ac7bc70328f22713f6f089b146e828a97278295fa731eb | dvingo/dv.fulcro-template | global_styles.cljs | (ns {{namespace}}.client.ui.styles.global-styles)
(defn page-styles [theme]
{":root" {:box-sizing "border-box"}
"*, ::after, ::before" {:box-sizing "inherit"}
:body
;; use important here to override semantic ui styles
{:background-color (str (:bg theme) "!important")
:background-image (str (:bg-image theme) "!important")
:color (str (:fg theme) "!important")
:font-size "1.2rem"
:line-height 1.3
:font-family "helvetica, sans-serif"}})
(defn semantic-styles [{:keys [fg container-bg]}]
{".ui.segment.ui.segment"
{:color fg
:background-color container-bg}
".ui.header.ui.header,
.ui.form.ui.form .field>label,
.ui.secondary.menu .item"
{:color fg}})
(defn global-styles
[theme]
(merge
(page-styles theme)
(semantic-styles theme)))
| null | https://raw.githubusercontent.com/dvingo/dv.fulcro-template/3f143d9a06e00749ea7f33c16c002f416fe69415/resources/clj/new/dv.fulcro_template/src/main/app/client/ui/styles/global_styles.cljs | clojure | use important here to override semantic ui styles | (ns {{namespace}}.client.ui.styles.global-styles)
(defn page-styles [theme]
{":root" {:box-sizing "border-box"}
"*, ::after, ::before" {:box-sizing "inherit"}
:body
{:background-color (str (:bg theme) "!important")
:background-image (str (:bg-image theme) "!important")
:color (str (:fg theme) "!important")
:font-size "1.2rem"
:line-height 1.3
:font-family "helvetica, sans-serif"}})
(defn semantic-styles [{:keys [fg container-bg]}]
{".ui.segment.ui.segment"
{:color fg
:background-color container-bg}
".ui.header.ui.header,
.ui.form.ui.form .field>label,
.ui.secondary.menu .item"
{:color fg}})
(defn global-styles
[theme]
(merge
(page-styles theme)
(semantic-styles theme)))
|
75e8f60ddb0ef8155592f03eeba551f69adaecbc43a1662746eec9cde9199c3b | pascalpoizat/fbpmn | Spec.hs | # LANGUAGE QuasiQuotes #
import Test . Tasty . QuickCheck as QC
import Test . Tasty . SmallCheck as SC
import Data.Attoparsec.Text
import Examples
( g0,
g1,
)
import Fbpmn.Analysis.Tla.IO.Log
import Fbpmn.Analysis.Tla.Model
import Fbpmn.BpmnGraph.Model
import Fbpmn.Helper (parseIdentifier, parseInteger, parseString)
import NeatInterpolation (text)
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.Runners.Html
main :: IO ()
main = defaultMainWithIngredients (htmlRunner : defaultIngredients) test
test :: TestTree
test = testGroup "Tests" [mainTests]
mainTests :: TestTree
mainTests = testGroup "Main tests" [unittests]
unittests :: TestTree
unittests =
testGroup
"Unit tests"
[uIsValidGraph, uNodesT, uEdgesT, uInN, uOutN, uPredecessorEdges, uPre, uLog]
-- parse error (not enough input)
parseNEI :: Either String a
parseNEI = Left "not enough input"
-- parse error (not enough input, letter case)
-- parseLNEI :: Either String a
-- parseLNEI = Left "letter: not enough input"
-- parse error (not enough input, _ case)
parseUNEI :: Either String a
parseUNEI = Left "'_': not enough input"
-- parse error (correct string not found)
parseWS :: Either String a
parseWS = Left "string"
-- parse error (while using takeWhile1)
parseTW1 :: Either String a
parseTW1 = Left "Failed reading: takeWhile1"
state1 :: Text
state1 =
[text|
State 12: <Action line 177, col 1 to line 177, col 21 of module e037Comm>
/\ edgemarks = [MessageFlow_1j3ru8z |-> 0, MessageFlow_01l3u25 |-> 1]
/\ net = (<<"Customer_Id", "TravelAgency_Id", "message1">> :> 2 @@ <<"Customer_Id", "TravelAgency_Id", "message2">> :> 1)
/\ nodemarks = [Airline_id |-> 0, Ticket_Order_Received |-> 1]
|]
state1assign :: Map Variable Value
state1assign =
fromList
[ ("edgemarks", MapValue (fromList [("MessageFlow_01l3u25", IntegerValue 1), ("MessageFlow_1j3ru8z", IntegerValue 0)])),
("net", BagValue (fromList [(TupleValue [StringValue "Customer_Id", StringValue "TravelAgency_Id", StringValue "message1"], IntegerValue 2), (TupleValue [StringValue "Customer_Id", StringValue "TravelAgency_Id", StringValue "message2"], IntegerValue 1)])),
("nodemarks", MapValue (fromList [("Airline_id", IntegerValue 0), ("Ticket_Order_Received", IntegerValue 1)]))
]
stateN :: Text
stateN =
[text|
State 29: Stuttering
Finished checking temporal properties in 00s at 2019-04-11 15:37:25
81 states generated, 60 distinct states found, 0 states left on queue.
Finished in 01s at (2019-04-11 15:37:25)
|]
uLog :: TestTree
uLog =
testGroup
"Unit tests for log parsing"
[ testCase "parse status ok (success)" $ parseOnly parseStatus okLine @?= Right Success,
testCase "parse status ok (failure)" $ parseOnly parseStatus errorLine1 @?= Right Failure,
testCase "parse status ko" $ parseOnly parseStatus ("foo" <> errorLine1) @?= parseNEI,
testCase "parse status ok after skipping lines" $ parseOnly parseStatus ("foo\nbar\n" <> errorLine1) @?= Right Failure,
testCase "parse variable ok (alpha)" $ parseOnly parseIdentifier " f " @?= Right "f",
testCase "parse variable ok (alpha)" $ parseOnly parseIdentifier " foo " @?= Right "foo",
testCase "parse variable ok (non alpha)" $ parseOnly parseIdentifier " _ " @?= Right "_",
testCase "parse variable ok (non alpha)" $ parseOnly parseIdentifier " f_123 " @?= Right "f_123",
testCase "parse variable ok (non alpha)" $ parseOnly parseIdentifier " _123 " @?= Right "_123",
testCase "parse variable ko" $ parseOnly parseIdentifier " " @?= parseNEI,
testCase "parse string ok" $ parseOnly parseString " \" 1 2 3 \" " @?= Right " 1 2 3 ",
testCase "parse string ko" $ parseOnly parseString " 1 2 3 " @?= parseWS,
testCase "parse string ko" $ parseOnly parseString " " @?= parseNEI,
testCase "parse integer ok" $ parseOnly parseInteger " 123 " @?= Right 123,
testCase "parse integer ko" $ parseOnly parseInteger " " @?= parseNEI,
testCase "parse integer ko" $ parseOnly parseInteger " abc " @?= parseTW1,
testCase "parse tuple (empty)" $ parseOnly parseTuple "<<>>" @?= Right [],
testCase "parse tuple (empty)" $ parseOnly parseTuple " <<>> " @?= Right [],
testCase "parse tuple (empty)" $ parseOnly parseTuple " << >> " @?= Right [],
testCase "parse tuple (non empty)" $ parseOnly parseTuple "<<123,\"foo\",bar>>" @?= Right [IntegerValue 123, StringValue "foo", VariableValue "bar"],
testCase "parse tuple (non empty)" $ parseOnly parseTuple " << 123 , \"foo\" , bar >> " @?= Right [IntegerValue 123, StringValue "foo", VariableValue "bar"],
testCase "parse map item" $ parseOnly parseMapItem "a|->1" @?= Right ("a", IntegerValue 1),
testCase "parse map item" $ parseOnly parseMapItem " a |-> <<123,\"foo\",bar>> " @?= Right ("a", TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"]),
testCase "parse bag item (integer value)" $ parseOnly parseBagItem "<<123,\"foo\",bar>>:>1" @?= Right (TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"], IntegerValue 1),
testCase "parse bag item (integer value)" $ parseOnly parseBagItem " <<123,\"foo\",bar>> :> 1 " @?= Right (TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"], IntegerValue 1),
testCase "parse bag item (general value)" $ parseOnly parseBagItem " <<\"id1\", \"id2\">> :> <<\"message\">> " @?= Right (TupleValue [StringValue "id1", StringValue "id2"], TupleValue [StringValue "message"]),
testCase "parse assignment" $ parseOnly parseAssignment "/\\ a=1" @?= Right ("a", IntegerValue 1),
testCase "parse assignment" $ parseOnly parseAssignment " /\\ a = <<123,\"foo\",bar>> " @?= Right ("a", TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"]),
testCase "parse map (empty)" $ parseOnly parseMap "[]" @?= Right [],
testCase "parse map (empty)" $ parseOnly parseMap " [ ] " @?= Right [],
testCase "parse map (non empty)" $ parseOnly parseMap "[foo|->123,bar|->456]" @?= Right [("foo", IntegerValue 123), ("bar", IntegerValue 456)],
testCase "parse map (non empty)" $ parseOnly parseMap " [ foo |-> 123 , bar |-> 456 ] " @?= Right [("foo", IntegerValue 123), ("bar", IntegerValue 456)],
testCase "parse bag (empty)" $ parseOnly parseBag "()" @?= Right [],
testCase "parse bag (empty)" $ parseOnly parseBag " ( ) " @?= Right [],
testCase "parse bag (non empty)" $ parseOnly parseBag "(foo:>123@@bar:>456)" @?= Right [(VariableValue "foo", IntegerValue 123), (VariableValue "bar", IntegerValue 456)],
testCase "parse bag (non empty)" $ parseOnly parseBag " ( foo :> 123 @@ bar :> 456 ) " @?= Right [(VariableValue "foo", IntegerValue 123), (VariableValue "bar", IntegerValue 456)],
testCase "parse bag (general)" $ parseOnly parseBag " ( <<\"id1\", \"id2\">> :> <<\"message1\">> @@\n<<\"id2\", \"id1\">> :> <<>> ) " @?= Right [(TupleValue [StringValue "id1", StringValue "id2"], TupleValue [StringValue "message1"]), (TupleValue [StringValue "id2", StringValue "id1"], TupleValue [])],
testCase "parse value (string)" $ parseOnly parseValue " \" 1 2 3 \" " @?= Right (StringValue " 1 2 3 "),
testCase "parse value (integer)" $ parseOnly parseValue " 123 " @?= Right (IntegerValue 123),
testCase "parse value (variable)" $ parseOnly parseValue " foo " @?= Right (VariableValue "foo"),
testCase "parse value (tuple)" $ parseOnly parseValue " << 123 , \"foo\" , bar >> " @?= Right (TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"]),
testCase "parse value (map)" $ parseOnly parseValue " [ foo |-> 123 , bar |-> 456 ] " @?= Right (MapValue . fromList $ [("foo", IntegerValue 123), ("bar", IntegerValue 456)]),
testCase "parse value (bag)" $ parseOnly parseValue " ( foo :> 123 @@ bar :> 456 ) " @?= Right (BagValue . fromList $ [(VariableValue "foo", IntegerValue 123), (VariableValue "bar", IntegerValue 456)]),
testCase "parse state (regular)" $ parseOnly parseState state1 @?= Right (CounterExampleState 12 "<Action line 177, col 1 to line 177, col 21 of module e037Comm>" state1assign),
testCase "parse state (stuttering)" $ parseOnly parseState stateN @?= Right (CounterExampleState 29 "Stuttering" (fromList []))
]
uIsValidGraph :: TestTree
uIsValidGraph =
testGroup
"Unit tests for isValidGraph"
[ testCase "all ok g1" $ isValidGraph g0 @?= True,
testCase "all ok g2" $ isValidGraph g2 @?= True,
testCase "all ok g3" $ isValidGraph g3 @?= True,
testCase "wrong message flow" $ isValidGraph g0e1 @?= False,
testCase "wrong message flow" $ isValidGraph g0e2 @?= False,
testCase "missing catN" $ isValidGraph g0a @?= False,
testCase "missing catE" $ isValidGraph g0b @?= False,
testCase "missing sourceE" $ isValidGraph g0c @?= False,
testCase "missing targetE" $ isValidGraph g0d @?= False,
testCase "all ok" $ isValidGraph g1 @?= True
]
uNodesT :: TestTree
uNodesT =
testGroup
"Unit tests for nodesT"
[ testCase "empty" $ nodesT g1 SendTask @?= [],
testCase "non empty, direct" $
nodesT g1 AbstractTask
@?= ["T1a", "T1b", "T2a", "T2b"]
]
uEdgesT :: TestTree
uEdgesT =
testGroup
"Unit tests for edgesT"
[ testCase "empty" $ edgesT g1 MessageFlow @?= [],
testCase "non empty, direct" $
edgesT g1 NormalSequenceFlow
@?= ["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
]
uInN :: TestTree
uInN =
testGroup
"Unit tests for inN"
[ testCase "empty" $ inN g1 "Start" @?= [],
testCase "non empty" $ inN g1 "JoinAnd" @?= ["ej+a", "ej+b"]
]
uOutN :: TestTree
uOutN =
testGroup
"Unit tests for outN"
[ testCase "empty" $ outN g1 "End" @?= [],
testCase "non empty" $ outN g1 "SplitAnd" @?= ["es+a", "es+b"]
]
uPredecessorEdges :: TestTree
uPredecessorEdges =
testGroup
"Unit tests of predecessorEdges"
[ testCase "general e0" $ predecessorEdges g2 "e0" @?= [],
testCase "general e1" $ predecessorEdges g2 "e1" @?= ["e0", "e15"],
testCase "general e2" $ predecessorEdges g2 "e2" @?= ["e1"],
testCase "general e3" $ predecessorEdges g2 "e3" @?= ["e2"],
testCase "general e4" $ predecessorEdges g2 "e4" @?= ["e2"],
testCase "general e5" $ predecessorEdges g2 "e5" @?= ["e4"],
testCase "general e6" $ predecessorEdges g2 "e6" @?= ["e3", "e8"],
testCase "general e7" $ predecessorEdges g2 "e7" @?= ["e6"],
testCase "general e8" $ predecessorEdges g2 "e8" @?= ["e7"],
testCase "general e9" $ predecessorEdges g2 "e9" @?= ["e7"],
testCase "general e10" $ predecessorEdges g2 "e10" @?= ["e12", "e5", "e9"],
testCase "general e11" $ predecessorEdges g2 "e11" @?= ["e10"],
testCase "general e12" $ predecessorEdges g2 "e12" @?= ["e11"],
testCase "general e13" $ predecessorEdges g2 "e13" @?= ["e11"],
testCase "general e14" $ predecessorEdges g2 "e14" @?= ["e13"],
testCase "general e15" $ predecessorEdges g2 "e15" @?= ["e2"]
]
uPre :: TestTree
uPre =
testGroup
"Unit tests for preE"
[ testCase "general e5" $ preE g2 "Or1" "e2" @?= ["e0", "e1", "e15"],
testCase "general e5" $
preE g2 "Or2" "e5"
@?= ["e0", "e1", "e15", "e2", "e4"],
testCase "general e9" $
preE g2 "Or2" "e9"
@?= ["e0", "e1", "e15", "e2", "e3", "e6", "e7", "e8"],
testCase "general e10" $ preE g2 "Or2" "e10" @?= [],
testCase "general e11" $ preE g2 "Or2" "e11" @?= ["e10"],
testCase "general e12" $ preE g2 "Or2" "e12" @?= ["e10", "e11"],
--
testCase "with communication e5" $
preE g3 "Or1" "e2"
@?= ["e0", "e1", "e15"],
testCase "with communication e5" $
preE g3 "Or2" "e5"
@?= ["e0", "e1", "e15", "e2", "e4"],
testCase "with communication e9" $
preE g3 "Or2" "e9"
@?= ["e0", "e1", "e15", "e2", "e3", "e6", "e7", "e8"],
testCase "with communication e10" $ preE g3 "Or2" "e10" @?= [],
testCase "with communication e11" $ preE g3 "Or2" "e11" @?= ["e10"],
testCase "with communication e12" $ preE g3 "Or2" "e12" @?= ["e10", "e11"]
]
--
-- graphs
--
g0a :: BpmnGraph
g0a =
mkGraph
"g0a"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
, ( " " , AndGateway )
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
("e2b", NormalSequenceFlow),
("ej+a", NormalSequenceFlow),
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
("e2b", "T1b"),
("ej+a", "T2a"),
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
("e2b", "T2b"),
("ej+a", "JoinAnd"),
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0b :: BpmnGraph
g0b =
mkGraph
"g0b"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
("JoinAnd", AndGateway),
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
( "e2b",
NormalSequenceFlow
),
, ( " ej+a " , NormalSequenceFlow )
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
("e2b", "T1b"),
("ej+a", "T2a"),
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
("e2b", "T2b"),
("ej+a", "JoinAnd"),
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0c :: BpmnGraph
g0c =
mkGraph
"g0c"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
("JoinAnd", AndGateway),
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
("e2b", NormalSequenceFlow),
("ej+a", NormalSequenceFlow),
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
( "e2b",
"T1b"
),
, ( " ej+a " , " T2a " )
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
("e2b", "T2b"),
("ej+a", "JoinAnd"),
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0d :: BpmnGraph
g0d =
mkGraph
"g0d"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
("JoinAnd", AndGateway),
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
("e2b", NormalSequenceFlow),
("ej+a", NormalSequenceFlow),
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
("e2b", "T1b"),
("ej+a", "T2a"),
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
( "e2b",
"T2b"
),
, ( " ej+a " , " " )
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0e1 :: BpmnGraph
g0e1 =
mkGraph
"g0e1"
["Sender", "Receiver", "NSE1", "NSE2", "ST1", "RT2", "NEE1", "NEE2"]
["a", "b", "c", "d", "m"]
catN
catE
source
target
name
containN
containE
attached
["message"]
(fromList [("m", "message")])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Sender", Process),
("Receiver", Process),
("NSE1", NoneStartEvent),
("NSE2", NoneStartEvent),
("ST1", SendTask),
("RT2", ReceiveTask),
("NEE1", NoneEndEvent),
("NEE2", NoneEndEvent)
]
catE =
fromList
[ ("a", NormalSequenceFlow),
("b", NormalSequenceFlow),
("c", NormalSequenceFlow),
("d", NormalSequenceFlow),
("m", MessageFlow)
]
source =
fromList
[("a", "NSE1"), ("b", "ST1"), ("c", "NSE2"), ("d", "RT2"), ("m", "NSE1")]
target =
fromList
[("a", "ST1"), ("b", "NEE1"), ("c", "RT2"), ("d", "NEE2"), ("m", "RT2")]
name = fromList []
containN =
fromList
[("Sender", ["NSE1", "ST1", "NEE1"]), ("Receiver", ["NSE2", "RT2", "NEE2"])]
containE = fromList [("Sender", ["a", "b"]), ("Receiver", ["c", "d"])]
attached = fromList []
g0e2 :: BpmnGraph
g0e2 =
mkGraph
"g0e2"
["Sender", "Receiver", "NSE1", "NSE2", "ST1", "RT2", "NEE1", "NEE2"]
["a", "b", "c", "d", "m"]
catN
catE
source
target
name
containN
containE
attached
["message"]
(fromList [("m", "message")])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Sender", Process),
("Receiver", Process),
("NSE1", NoneStartEvent),
("NSE2", NoneStartEvent),
("ST1", SendTask),
("RT2", ReceiveTask),
("NEE1", NoneEndEvent),
("NEE2", NoneEndEvent)
]
catE =
fromList
[ ("a", NormalSequenceFlow),
("b", NormalSequenceFlow),
("c", NormalSequenceFlow),
("d", NormalSequenceFlow),
("m", MessageFlow)
]
source =
fromList
[("a", "NSE1"), ("b", "ST1"), ("c", "NSE2"), ("d", "RT2"), ("m", "ST1")]
target =
fromList
[("a", "ST1"), ("b", "NEE1"), ("c", "RT2"), ("d", "NEE2"), ("m", "NEE2")]
name = fromList []
containN =
fromList
[("Sender", ["NSE1", "ST1", "NEE1"]), ("Receiver", ["NSE2", "RT2", "NEE2"])]
containE = fromList [("Sender", ["a", "b"]), ("Receiver", ["c", "d"])]
attached = fromList []
g2 :: BpmnGraph
g2 =
mkGraph
"g2"
[ "Process",
"NSE",
"Xor0",
"AT1",
"Or1",
"Xor1",
"AT2",
"Xor2",
"AT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE"
]
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15"
]
catN
catE
source
target
(fromList [])
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("NSE", NoneStartEvent),
("AT1", AbstractTask),
("Xor0", XorGateway),
("Or1", OrGateway),
("Xor1", XorGateway),
("AT2", AbstractTask),
("Xor2", XorGateway),
("AT3", AbstractTask),
("Or2", OrGateway),
("AT4", AbstractTask),
("Xor3", XorGateway),
("AT5", AbstractTask),
("NEE", NoneEndEvent)
]
catE =
fromList
[ ("e0", NormalSequenceFlow),
("e1", NormalSequenceFlow),
("e2", NormalSequenceFlow),
("e3", ConditionalSequenceFlow),
("e4", ConditionalSequenceFlow),
("e5", NormalSequenceFlow),
("e6", NormalSequenceFlow),
("e7", NormalSequenceFlow),
("e8", DefaultSequenceFlow),
("e9", ConditionalSequenceFlow),
("e10", NormalSequenceFlow),
("e11", NormalSequenceFlow),
("e12", DefaultSequenceFlow),
("e13", ConditionalSequenceFlow),
("e14", NormalSequenceFlow),
("e15", DefaultSequenceFlow)
]
source =
fromList
[ ("e0", "NSE"),
("e1", "Xor0"),
("e2", "AT1"),
("e3", "Or1"),
("e4", "Or1"),
("e5", "AT3"),
("e6", "Xor1"),
("e7", "AT2"),
("e8", "Xor2"),
("e9", "Xor2"),
("e10", "Or2"),
("e11", "AT4"),
("e12", "Xor3"),
("e13", "Xor3"),
("e14", "AT5"),
("e15", "Or1")
]
target =
fromList
[ ("e0", "Xor0"),
("e1", "AT1"),
("e2", "Or1"),
("e3", "Xor1"),
("e4", "AT3"),
("e5", "Or2"),
("e6", "AT2"),
("e7", "Xor2"),
("e8", "Xor1"),
("e9", "Or2"),
("e10", "AT4"),
("e11", "Xor3"),
("e12", "Or2"),
("e13", "AT5"),
("e14", "NEE"),
("e15", "Xor0")
]
containN =
fromList
[ ( "Process",
[ "NSE",
"AT1",
"Xor0",
"Or1",
"Xor1",
"AT2",
"Xor2",
"AT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE"
]
)
]
containE =
fromList
[ ( "Process",
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15"
]
)
]
attached = fromList []
g3 :: BpmnGraph
g3 =
mkGraph
"g3"
[ "Process",
"NSE",
"Xor0",
"AT1",
"Or1",
"Xor1",
"AT2",
"Xor2",
"RT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE",
"Sender",
"NSE2",
"ST1",
"NEE2"
]
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15",
"e16",
"e17",
"mf1"
]
catN
catE
source
target
(fromList [])
containN
containE
attached
["message"]
(fromList [("mf1", "message")])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("NSE", NoneStartEvent),
("AT1", AbstractTask),
("Xor0", XorGateway),
("Or1", OrGateway),
("Xor1", XorGateway),
("AT2", AbstractTask),
("Xor2", XorGateway),
("RT3", ReceiveTask),
("Or2", OrGateway),
("AT4", AbstractTask),
("Xor3", XorGateway),
("AT5", AbstractTask),
("NEE", NoneEndEvent),
("Sender", Process),
("NSE2", NoneStartEvent),
("ST1", SendTask),
("NEE2", NoneEndEvent)
]
catE =
fromList
[ ("e0", NormalSequenceFlow),
("e1", NormalSequenceFlow),
("e2", NormalSequenceFlow),
("e3", ConditionalSequenceFlow),
("e4", ConditionalSequenceFlow),
("e5", NormalSequenceFlow),
("e6", NormalSequenceFlow),
("e7", NormalSequenceFlow),
("e8", DefaultSequenceFlow),
("e9", ConditionalSequenceFlow),
("e10", NormalSequenceFlow),
("e11", NormalSequenceFlow),
("e12", DefaultSequenceFlow),
("e13", ConditionalSequenceFlow),
("e14", NormalSequenceFlow),
("e15", DefaultSequenceFlow),
("e16", NormalSequenceFlow),
("e17", NormalSequenceFlow),
("mf1", MessageFlow)
]
source =
fromList
[ ("e0", "NSE"),
("e1", "Xor0"),
("e2", "AT1"),
("e3", "Or1"),
("e4", "Or1"),
("e5", "RT3"),
("e6", "Xor1"),
("e7", "AT2"),
("e8", "Xor2"),
("e9", "Xor2"),
("e10", "Or2"),
("e11", "AT4"),
("e12", "Xor3"),
("e13", "Xor3"),
("e14", "AT5"),
("e15", "Or1"),
("e16", "NSE2"),
("e17", "ST1"),
("mf1", "ST1")
]
target =
fromList
[ ("e0", "Xor0"),
("e1", "AT1"),
("e2", "Or1"),
("e3", "Xor1"),
("e4", "RT3"),
("e5", "Or2"),
("e6", "AT2"),
("e7", "Xor2"),
("e8", "Xor1"),
("e9", "Or2"),
("e10", "AT4"),
("e11", "Xor3"),
("e12", "Or2"),
("e13", "AT5"),
("e14", "NEE"),
("e15", "Xor0"),
("e16", "ST1"),
("e17", "NEE2"),
("mf1", "RT3")
]
containN =
fromList
[ ( "Process",
[ "NSE",
"AT1",
"Xor0",
"Or1",
"Xor1",
"AT2",
"Xor2",
"AT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE"
]
),
("Sender", ["NSE2", "ST1", "NEE2"])
]
containE =
fromList
[ ( "Process",
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15"
]
),
("Sender", ["e16", "e17"])
]
attached = fromList []
| null | https://raw.githubusercontent.com/pascalpoizat/fbpmn/0e99d26e3ff0a24edc8e3f603fcc47e78fbf209e/test/Spec.hs | haskell | parse error (not enough input)
parse error (not enough input, letter case)
parseLNEI :: Either String a
parseLNEI = Left "letter: not enough input"
parse error (not enough input, _ case)
parse error (correct string not found)
parse error (while using takeWhile1)
graphs
| # LANGUAGE QuasiQuotes #
import Test . Tasty . QuickCheck as QC
import Test . Tasty . SmallCheck as SC
import Data.Attoparsec.Text
import Examples
( g0,
g1,
)
import Fbpmn.Analysis.Tla.IO.Log
import Fbpmn.Analysis.Tla.Model
import Fbpmn.BpmnGraph.Model
import Fbpmn.Helper (parseIdentifier, parseInteger, parseString)
import NeatInterpolation (text)
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.Runners.Html
main :: IO ()
main = defaultMainWithIngredients (htmlRunner : defaultIngredients) test
test :: TestTree
test = testGroup "Tests" [mainTests]
mainTests :: TestTree
mainTests = testGroup "Main tests" [unittests]
unittests :: TestTree
unittests =
testGroup
"Unit tests"
[uIsValidGraph, uNodesT, uEdgesT, uInN, uOutN, uPredecessorEdges, uPre, uLog]
parseNEI :: Either String a
parseNEI = Left "not enough input"
parseUNEI :: Either String a
parseUNEI = Left "'_': not enough input"
parseWS :: Either String a
parseWS = Left "string"
parseTW1 :: Either String a
parseTW1 = Left "Failed reading: takeWhile1"
state1 :: Text
state1 =
[text|
State 12: <Action line 177, col 1 to line 177, col 21 of module e037Comm>
/\ edgemarks = [MessageFlow_1j3ru8z |-> 0, MessageFlow_01l3u25 |-> 1]
/\ net = (<<"Customer_Id", "TravelAgency_Id", "message1">> :> 2 @@ <<"Customer_Id", "TravelAgency_Id", "message2">> :> 1)
/\ nodemarks = [Airline_id |-> 0, Ticket_Order_Received |-> 1]
|]
state1assign :: Map Variable Value
state1assign =
fromList
[ ("edgemarks", MapValue (fromList [("MessageFlow_01l3u25", IntegerValue 1), ("MessageFlow_1j3ru8z", IntegerValue 0)])),
("net", BagValue (fromList [(TupleValue [StringValue "Customer_Id", StringValue "TravelAgency_Id", StringValue "message1"], IntegerValue 2), (TupleValue [StringValue "Customer_Id", StringValue "TravelAgency_Id", StringValue "message2"], IntegerValue 1)])),
("nodemarks", MapValue (fromList [("Airline_id", IntegerValue 0), ("Ticket_Order_Received", IntegerValue 1)]))
]
stateN :: Text
stateN =
[text|
State 29: Stuttering
Finished checking temporal properties in 00s at 2019-04-11 15:37:25
81 states generated, 60 distinct states found, 0 states left on queue.
Finished in 01s at (2019-04-11 15:37:25)
|]
uLog :: TestTree
uLog =
testGroup
"Unit tests for log parsing"
[ testCase "parse status ok (success)" $ parseOnly parseStatus okLine @?= Right Success,
testCase "parse status ok (failure)" $ parseOnly parseStatus errorLine1 @?= Right Failure,
testCase "parse status ko" $ parseOnly parseStatus ("foo" <> errorLine1) @?= parseNEI,
testCase "parse status ok after skipping lines" $ parseOnly parseStatus ("foo\nbar\n" <> errorLine1) @?= Right Failure,
testCase "parse variable ok (alpha)" $ parseOnly parseIdentifier " f " @?= Right "f",
testCase "parse variable ok (alpha)" $ parseOnly parseIdentifier " foo " @?= Right "foo",
testCase "parse variable ok (non alpha)" $ parseOnly parseIdentifier " _ " @?= Right "_",
testCase "parse variable ok (non alpha)" $ parseOnly parseIdentifier " f_123 " @?= Right "f_123",
testCase "parse variable ok (non alpha)" $ parseOnly parseIdentifier " _123 " @?= Right "_123",
testCase "parse variable ko" $ parseOnly parseIdentifier " " @?= parseNEI,
testCase "parse string ok" $ parseOnly parseString " \" 1 2 3 \" " @?= Right " 1 2 3 ",
testCase "parse string ko" $ parseOnly parseString " 1 2 3 " @?= parseWS,
testCase "parse string ko" $ parseOnly parseString " " @?= parseNEI,
testCase "parse integer ok" $ parseOnly parseInteger " 123 " @?= Right 123,
testCase "parse integer ko" $ parseOnly parseInteger " " @?= parseNEI,
testCase "parse integer ko" $ parseOnly parseInteger " abc " @?= parseTW1,
testCase "parse tuple (empty)" $ parseOnly parseTuple "<<>>" @?= Right [],
testCase "parse tuple (empty)" $ parseOnly parseTuple " <<>> " @?= Right [],
testCase "parse tuple (empty)" $ parseOnly parseTuple " << >> " @?= Right [],
testCase "parse tuple (non empty)" $ parseOnly parseTuple "<<123,\"foo\",bar>>" @?= Right [IntegerValue 123, StringValue "foo", VariableValue "bar"],
testCase "parse tuple (non empty)" $ parseOnly parseTuple " << 123 , \"foo\" , bar >> " @?= Right [IntegerValue 123, StringValue "foo", VariableValue "bar"],
testCase "parse map item" $ parseOnly parseMapItem "a|->1" @?= Right ("a", IntegerValue 1),
testCase "parse map item" $ parseOnly parseMapItem " a |-> <<123,\"foo\",bar>> " @?= Right ("a", TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"]),
testCase "parse bag item (integer value)" $ parseOnly parseBagItem "<<123,\"foo\",bar>>:>1" @?= Right (TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"], IntegerValue 1),
testCase "parse bag item (integer value)" $ parseOnly parseBagItem " <<123,\"foo\",bar>> :> 1 " @?= Right (TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"], IntegerValue 1),
testCase "parse bag item (general value)" $ parseOnly parseBagItem " <<\"id1\", \"id2\">> :> <<\"message\">> " @?= Right (TupleValue [StringValue "id1", StringValue "id2"], TupleValue [StringValue "message"]),
testCase "parse assignment" $ parseOnly parseAssignment "/\\ a=1" @?= Right ("a", IntegerValue 1),
testCase "parse assignment" $ parseOnly parseAssignment " /\\ a = <<123,\"foo\",bar>> " @?= Right ("a", TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"]),
testCase "parse map (empty)" $ parseOnly parseMap "[]" @?= Right [],
testCase "parse map (empty)" $ parseOnly parseMap " [ ] " @?= Right [],
testCase "parse map (non empty)" $ parseOnly parseMap "[foo|->123,bar|->456]" @?= Right [("foo", IntegerValue 123), ("bar", IntegerValue 456)],
testCase "parse map (non empty)" $ parseOnly parseMap " [ foo |-> 123 , bar |-> 456 ] " @?= Right [("foo", IntegerValue 123), ("bar", IntegerValue 456)],
testCase "parse bag (empty)" $ parseOnly parseBag "()" @?= Right [],
testCase "parse bag (empty)" $ parseOnly parseBag " ( ) " @?= Right [],
testCase "parse bag (non empty)" $ parseOnly parseBag "(foo:>123@@bar:>456)" @?= Right [(VariableValue "foo", IntegerValue 123), (VariableValue "bar", IntegerValue 456)],
testCase "parse bag (non empty)" $ parseOnly parseBag " ( foo :> 123 @@ bar :> 456 ) " @?= Right [(VariableValue "foo", IntegerValue 123), (VariableValue "bar", IntegerValue 456)],
testCase "parse bag (general)" $ parseOnly parseBag " ( <<\"id1\", \"id2\">> :> <<\"message1\">> @@\n<<\"id2\", \"id1\">> :> <<>> ) " @?= Right [(TupleValue [StringValue "id1", StringValue "id2"], TupleValue [StringValue "message1"]), (TupleValue [StringValue "id2", StringValue "id1"], TupleValue [])],
testCase "parse value (string)" $ parseOnly parseValue " \" 1 2 3 \" " @?= Right (StringValue " 1 2 3 "),
testCase "parse value (integer)" $ parseOnly parseValue " 123 " @?= Right (IntegerValue 123),
testCase "parse value (variable)" $ parseOnly parseValue " foo " @?= Right (VariableValue "foo"),
testCase "parse value (tuple)" $ parseOnly parseValue " << 123 , \"foo\" , bar >> " @?= Right (TupleValue [IntegerValue 123, StringValue "foo", VariableValue "bar"]),
testCase "parse value (map)" $ parseOnly parseValue " [ foo |-> 123 , bar |-> 456 ] " @?= Right (MapValue . fromList $ [("foo", IntegerValue 123), ("bar", IntegerValue 456)]),
testCase "parse value (bag)" $ parseOnly parseValue " ( foo :> 123 @@ bar :> 456 ) " @?= Right (BagValue . fromList $ [(VariableValue "foo", IntegerValue 123), (VariableValue "bar", IntegerValue 456)]),
testCase "parse state (regular)" $ parseOnly parseState state1 @?= Right (CounterExampleState 12 "<Action line 177, col 1 to line 177, col 21 of module e037Comm>" state1assign),
testCase "parse state (stuttering)" $ parseOnly parseState stateN @?= Right (CounterExampleState 29 "Stuttering" (fromList []))
]
uIsValidGraph :: TestTree
uIsValidGraph =
testGroup
"Unit tests for isValidGraph"
[ testCase "all ok g1" $ isValidGraph g0 @?= True,
testCase "all ok g2" $ isValidGraph g2 @?= True,
testCase "all ok g3" $ isValidGraph g3 @?= True,
testCase "wrong message flow" $ isValidGraph g0e1 @?= False,
testCase "wrong message flow" $ isValidGraph g0e2 @?= False,
testCase "missing catN" $ isValidGraph g0a @?= False,
testCase "missing catE" $ isValidGraph g0b @?= False,
testCase "missing sourceE" $ isValidGraph g0c @?= False,
testCase "missing targetE" $ isValidGraph g0d @?= False,
testCase "all ok" $ isValidGraph g1 @?= True
]
uNodesT :: TestTree
uNodesT =
testGroup
"Unit tests for nodesT"
[ testCase "empty" $ nodesT g1 SendTask @?= [],
testCase "non empty, direct" $
nodesT g1 AbstractTask
@?= ["T1a", "T1b", "T2a", "T2b"]
]
uEdgesT :: TestTree
uEdgesT =
testGroup
"Unit tests for edgesT"
[ testCase "empty" $ edgesT g1 MessageFlow @?= [],
testCase "non empty, direct" $
edgesT g1 NormalSequenceFlow
@?= ["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
]
uInN :: TestTree
uInN =
testGroup
"Unit tests for inN"
[ testCase "empty" $ inN g1 "Start" @?= [],
testCase "non empty" $ inN g1 "JoinAnd" @?= ["ej+a", "ej+b"]
]
uOutN :: TestTree
uOutN =
testGroup
"Unit tests for outN"
[ testCase "empty" $ outN g1 "End" @?= [],
testCase "non empty" $ outN g1 "SplitAnd" @?= ["es+a", "es+b"]
]
uPredecessorEdges :: TestTree
uPredecessorEdges =
testGroup
"Unit tests of predecessorEdges"
[ testCase "general e0" $ predecessorEdges g2 "e0" @?= [],
testCase "general e1" $ predecessorEdges g2 "e1" @?= ["e0", "e15"],
testCase "general e2" $ predecessorEdges g2 "e2" @?= ["e1"],
testCase "general e3" $ predecessorEdges g2 "e3" @?= ["e2"],
testCase "general e4" $ predecessorEdges g2 "e4" @?= ["e2"],
testCase "general e5" $ predecessorEdges g2 "e5" @?= ["e4"],
testCase "general e6" $ predecessorEdges g2 "e6" @?= ["e3", "e8"],
testCase "general e7" $ predecessorEdges g2 "e7" @?= ["e6"],
testCase "general e8" $ predecessorEdges g2 "e8" @?= ["e7"],
testCase "general e9" $ predecessorEdges g2 "e9" @?= ["e7"],
testCase "general e10" $ predecessorEdges g2 "e10" @?= ["e12", "e5", "e9"],
testCase "general e11" $ predecessorEdges g2 "e11" @?= ["e10"],
testCase "general e12" $ predecessorEdges g2 "e12" @?= ["e11"],
testCase "general e13" $ predecessorEdges g2 "e13" @?= ["e11"],
testCase "general e14" $ predecessorEdges g2 "e14" @?= ["e13"],
testCase "general e15" $ predecessorEdges g2 "e15" @?= ["e2"]
]
uPre :: TestTree
uPre =
testGroup
"Unit tests for preE"
[ testCase "general e5" $ preE g2 "Or1" "e2" @?= ["e0", "e1", "e15"],
testCase "general e5" $
preE g2 "Or2" "e5"
@?= ["e0", "e1", "e15", "e2", "e4"],
testCase "general e9" $
preE g2 "Or2" "e9"
@?= ["e0", "e1", "e15", "e2", "e3", "e6", "e7", "e8"],
testCase "general e10" $ preE g2 "Or2" "e10" @?= [],
testCase "general e11" $ preE g2 "Or2" "e11" @?= ["e10"],
testCase "general e12" $ preE g2 "Or2" "e12" @?= ["e10", "e11"],
testCase "with communication e5" $
preE g3 "Or1" "e2"
@?= ["e0", "e1", "e15"],
testCase "with communication e5" $
preE g3 "Or2" "e5"
@?= ["e0", "e1", "e15", "e2", "e4"],
testCase "with communication e9" $
preE g3 "Or2" "e9"
@?= ["e0", "e1", "e15", "e2", "e3", "e6", "e7", "e8"],
testCase "with communication e10" $ preE g3 "Or2" "e10" @?= [],
testCase "with communication e11" $ preE g3 "Or2" "e11" @?= ["e10"],
testCase "with communication e12" $ preE g3 "Or2" "e12" @?= ["e10", "e11"]
]
g0a :: BpmnGraph
g0a =
mkGraph
"g0a"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
, ( " " , AndGateway )
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
("e2b", NormalSequenceFlow),
("ej+a", NormalSequenceFlow),
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
("e2b", "T1b"),
("ej+a", "T2a"),
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
("e2b", "T2b"),
("ej+a", "JoinAnd"),
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0b :: BpmnGraph
g0b =
mkGraph
"g0b"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
("JoinAnd", AndGateway),
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
( "e2b",
NormalSequenceFlow
),
, ( " ej+a " , NormalSequenceFlow )
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
("e2b", "T1b"),
("ej+a", "T2a"),
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
("e2b", "T2b"),
("ej+a", "JoinAnd"),
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0c :: BpmnGraph
g0c =
mkGraph
"g0c"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
("JoinAnd", AndGateway),
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
("e2b", NormalSequenceFlow),
("ej+a", NormalSequenceFlow),
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
( "e2b",
"T1b"
),
, ( " ej+a " , " T2a " )
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
("e2b", "T2b"),
("ej+a", "JoinAnd"),
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0d :: BpmnGraph
g0d =
mkGraph
"g0d"
["Process", "Start", "SplitAnd", "T1a", "T1b", "T2a", "T2b", "JoinAnd", "End"]
["e1", "es+a", "es+b", "e2a", "e2b", "ej+a", "ej+b", "e3"]
catN
catE
source
target
name
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("Start", NoneStartEvent),
("SplitAnd", AndGateway),
("T1a", AbstractTask),
("T2a", AbstractTask),
("T1b", AbstractTask),
("T2b", AbstractTask),
("JoinAnd", AndGateway),
("End", NoneEndEvent)
]
catE =
fromList
[ ("e1", NormalSequenceFlow),
("es+a", NormalSequenceFlow),
("es+b", NormalSequenceFlow),
("e2a", NormalSequenceFlow),
("e2b", NormalSequenceFlow),
("ej+a", NormalSequenceFlow),
("ej+b", NormalSequenceFlow),
("e3", NormalSequenceFlow)
]
source =
fromList
[ ("e1", "Start"),
("es+a", "SplitAnd"),
("es+b", "SplitAnd"),
("e2a", "T1a"),
("e2b", "T1b"),
("ej+a", "T2a"),
("ej+b", "T2b"),
("e3", "JoinAnd")
]
target =
fromList
[ ("e1", "SplitAnd"),
("es+a", "T1a"),
("es+b", "T1b"),
("e2a", "T2a"),
( "e2b",
"T2b"
),
, ( " ej+a " , " " )
("ej+b", "JoinAnd"),
("e3", "End")
]
name = fromList []
containN = fromList [("Process", [])]
containE = fromList [("Process", [])]
attached = fromList []
g0e1 :: BpmnGraph
g0e1 =
mkGraph
"g0e1"
["Sender", "Receiver", "NSE1", "NSE2", "ST1", "RT2", "NEE1", "NEE2"]
["a", "b", "c", "d", "m"]
catN
catE
source
target
name
containN
containE
attached
["message"]
(fromList [("m", "message")])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Sender", Process),
("Receiver", Process),
("NSE1", NoneStartEvent),
("NSE2", NoneStartEvent),
("ST1", SendTask),
("RT2", ReceiveTask),
("NEE1", NoneEndEvent),
("NEE2", NoneEndEvent)
]
catE =
fromList
[ ("a", NormalSequenceFlow),
("b", NormalSequenceFlow),
("c", NormalSequenceFlow),
("d", NormalSequenceFlow),
("m", MessageFlow)
]
source =
fromList
[("a", "NSE1"), ("b", "ST1"), ("c", "NSE2"), ("d", "RT2"), ("m", "NSE1")]
target =
fromList
[("a", "ST1"), ("b", "NEE1"), ("c", "RT2"), ("d", "NEE2"), ("m", "RT2")]
name = fromList []
containN =
fromList
[("Sender", ["NSE1", "ST1", "NEE1"]), ("Receiver", ["NSE2", "RT2", "NEE2"])]
containE = fromList [("Sender", ["a", "b"]), ("Receiver", ["c", "d"])]
attached = fromList []
g0e2 :: BpmnGraph
g0e2 =
mkGraph
"g0e2"
["Sender", "Receiver", "NSE1", "NSE2", "ST1", "RT2", "NEE1", "NEE2"]
["a", "b", "c", "d", "m"]
catN
catE
source
target
name
containN
containE
attached
["message"]
(fromList [("m", "message")])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Sender", Process),
("Receiver", Process),
("NSE1", NoneStartEvent),
("NSE2", NoneStartEvent),
("ST1", SendTask),
("RT2", ReceiveTask),
("NEE1", NoneEndEvent),
("NEE2", NoneEndEvent)
]
catE =
fromList
[ ("a", NormalSequenceFlow),
("b", NormalSequenceFlow),
("c", NormalSequenceFlow),
("d", NormalSequenceFlow),
("m", MessageFlow)
]
source =
fromList
[("a", "NSE1"), ("b", "ST1"), ("c", "NSE2"), ("d", "RT2"), ("m", "ST1")]
target =
fromList
[("a", "ST1"), ("b", "NEE1"), ("c", "RT2"), ("d", "NEE2"), ("m", "NEE2")]
name = fromList []
containN =
fromList
[("Sender", ["NSE1", "ST1", "NEE1"]), ("Receiver", ["NSE2", "RT2", "NEE2"])]
containE = fromList [("Sender", ["a", "b"]), ("Receiver", ["c", "d"])]
attached = fromList []
g2 :: BpmnGraph
g2 =
mkGraph
"g2"
[ "Process",
"NSE",
"Xor0",
"AT1",
"Or1",
"Xor1",
"AT2",
"Xor2",
"AT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE"
]
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15"
]
catN
catE
source
target
(fromList [])
containN
containE
attached
[]
(fromList [])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("NSE", NoneStartEvent),
("AT1", AbstractTask),
("Xor0", XorGateway),
("Or1", OrGateway),
("Xor1", XorGateway),
("AT2", AbstractTask),
("Xor2", XorGateway),
("AT3", AbstractTask),
("Or2", OrGateway),
("AT4", AbstractTask),
("Xor3", XorGateway),
("AT5", AbstractTask),
("NEE", NoneEndEvent)
]
catE =
fromList
[ ("e0", NormalSequenceFlow),
("e1", NormalSequenceFlow),
("e2", NormalSequenceFlow),
("e3", ConditionalSequenceFlow),
("e4", ConditionalSequenceFlow),
("e5", NormalSequenceFlow),
("e6", NormalSequenceFlow),
("e7", NormalSequenceFlow),
("e8", DefaultSequenceFlow),
("e9", ConditionalSequenceFlow),
("e10", NormalSequenceFlow),
("e11", NormalSequenceFlow),
("e12", DefaultSequenceFlow),
("e13", ConditionalSequenceFlow),
("e14", NormalSequenceFlow),
("e15", DefaultSequenceFlow)
]
source =
fromList
[ ("e0", "NSE"),
("e1", "Xor0"),
("e2", "AT1"),
("e3", "Or1"),
("e4", "Or1"),
("e5", "AT3"),
("e6", "Xor1"),
("e7", "AT2"),
("e8", "Xor2"),
("e9", "Xor2"),
("e10", "Or2"),
("e11", "AT4"),
("e12", "Xor3"),
("e13", "Xor3"),
("e14", "AT5"),
("e15", "Or1")
]
target =
fromList
[ ("e0", "Xor0"),
("e1", "AT1"),
("e2", "Or1"),
("e3", "Xor1"),
("e4", "AT3"),
("e5", "Or2"),
("e6", "AT2"),
("e7", "Xor2"),
("e8", "Xor1"),
("e9", "Or2"),
("e10", "AT4"),
("e11", "Xor3"),
("e12", "Or2"),
("e13", "AT5"),
("e14", "NEE"),
("e15", "Xor0")
]
containN =
fromList
[ ( "Process",
[ "NSE",
"AT1",
"Xor0",
"Or1",
"Xor1",
"AT2",
"Xor2",
"AT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE"
]
)
]
containE =
fromList
[ ( "Process",
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15"
]
)
]
attached = fromList []
g3 :: BpmnGraph
g3 =
mkGraph
"g3"
[ "Process",
"NSE",
"Xor0",
"AT1",
"Or1",
"Xor1",
"AT2",
"Xor2",
"RT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE",
"Sender",
"NSE2",
"ST1",
"NEE2"
]
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15",
"e16",
"e17",
"mf1"
]
catN
catE
source
target
(fromList [])
containN
containE
attached
["message"]
(fromList [("mf1", "message")])
(fromList [])
(fromList [])
where
catN =
fromList
[ ("Process", Process),
("NSE", NoneStartEvent),
("AT1", AbstractTask),
("Xor0", XorGateway),
("Or1", OrGateway),
("Xor1", XorGateway),
("AT2", AbstractTask),
("Xor2", XorGateway),
("RT3", ReceiveTask),
("Or2", OrGateway),
("AT4", AbstractTask),
("Xor3", XorGateway),
("AT5", AbstractTask),
("NEE", NoneEndEvent),
("Sender", Process),
("NSE2", NoneStartEvent),
("ST1", SendTask),
("NEE2", NoneEndEvent)
]
catE =
fromList
[ ("e0", NormalSequenceFlow),
("e1", NormalSequenceFlow),
("e2", NormalSequenceFlow),
("e3", ConditionalSequenceFlow),
("e4", ConditionalSequenceFlow),
("e5", NormalSequenceFlow),
("e6", NormalSequenceFlow),
("e7", NormalSequenceFlow),
("e8", DefaultSequenceFlow),
("e9", ConditionalSequenceFlow),
("e10", NormalSequenceFlow),
("e11", NormalSequenceFlow),
("e12", DefaultSequenceFlow),
("e13", ConditionalSequenceFlow),
("e14", NormalSequenceFlow),
("e15", DefaultSequenceFlow),
("e16", NormalSequenceFlow),
("e17", NormalSequenceFlow),
("mf1", MessageFlow)
]
source =
fromList
[ ("e0", "NSE"),
("e1", "Xor0"),
("e2", "AT1"),
("e3", "Or1"),
("e4", "Or1"),
("e5", "RT3"),
("e6", "Xor1"),
("e7", "AT2"),
("e8", "Xor2"),
("e9", "Xor2"),
("e10", "Or2"),
("e11", "AT4"),
("e12", "Xor3"),
("e13", "Xor3"),
("e14", "AT5"),
("e15", "Or1"),
("e16", "NSE2"),
("e17", "ST1"),
("mf1", "ST1")
]
target =
fromList
[ ("e0", "Xor0"),
("e1", "AT1"),
("e2", "Or1"),
("e3", "Xor1"),
("e4", "RT3"),
("e5", "Or2"),
("e6", "AT2"),
("e7", "Xor2"),
("e8", "Xor1"),
("e9", "Or2"),
("e10", "AT4"),
("e11", "Xor3"),
("e12", "Or2"),
("e13", "AT5"),
("e14", "NEE"),
("e15", "Xor0"),
("e16", "ST1"),
("e17", "NEE2"),
("mf1", "RT3")
]
containN =
fromList
[ ( "Process",
[ "NSE",
"AT1",
"Xor0",
"Or1",
"Xor1",
"AT2",
"Xor2",
"AT3",
"Or2",
"AT4",
"Xor3",
"AT5",
"NEE"
]
),
("Sender", ["NSE2", "ST1", "NEE2"])
]
containE =
fromList
[ ( "Process",
[ "e0",
"e1",
"e2",
"e3",
"e4",
"e5",
"e6",
"e7",
"e8",
"e9",
"e10",
"e11",
"e12",
"e13",
"e14",
"e15"
]
),
("Sender", ["e16", "e17"])
]
attached = fromList []
|
59bc23bf4ffe9cdc11483f32a643cdde19f67222ba3bd4cac30c0f213127a79e | andreaslyn/mini-yu | Main.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE CPP #
#include "split-stack-config.h"
module Main (main) where
import PackageMap (PackageMap)
import System.Console.ArgParser.Params as ArPa
import System.Console.ArgParser as Ar
import TypeCheck.TypeCheck
import qualified Ir.BaseIr as Ba
import qualified Ir.HighLevelIr as Hl
import qualified Ir.RefCountIr as Rc
import System.Directory (canonicalizePath)
import Control.Monad
import qualified System.Exit as Exit
import qualified Ir.CodeGen as Cg
import System.Command (command_)
import System.IO (hPutStrLn, stderr)
import System.FilePath (takeDirectory, takeFileName)
import Str (quote, stdRuntimePath)
import System.Environment (getArgs, getExecutablePath)
import qualified Data.Map as Map
import Data.IORef
collectIr :: IORef [FilePath] -> TypeCheckContCollect
collectIr objectFilesRef outputBaseName = do
let ofile = outputBaseName ++ ".o"
modifyIORef objectFilesRef (ofile :)
runIr :: IORef [FilePath] -> ProgramOptions -> TypeCheckContCompile
runIr objectFilesRef opts outputBaseName importBaseNames allBaseNames
moduleName vs dm im rm =
when (optionPrintHighLevelIR opts
|| optionPrintBaseIR opts
|| optionPrintRefCountIR opts
|| optionAssembly opts
|| optionCompile opts)
runFromHighLevelIr
where
runFromHighLevelIr :: IO ()
runFromHighLevelIr = do
let (hap, har) = Hl.highLevelIr (not $ optionFast opts) moduleName vs dm im rm
when (optionPrintHighLevelIR opts) $ do
putStrLn "\n## High level intermediate representation\n"
putStrLn (Hl.irToString hap har)
when (optionPrintBaseIR opts
|| optionPrintRefCountIR opts
|| optionAssembly opts
|| optionCompile opts) $
runFromBaseIr hap har
runFromBaseIr :: Hl.Program -> Hl.ProgramRoots -> IO ()
runFromBaseIr hap har = do
bap <- Ba.baseIr (not $ optionFast opts) (optionVerboseOutput opts)
outputBaseName allBaseNames moduleName hap har
when (optionPrintBaseIR opts) $ do
putStrLn "\n## Base intermediate representation\n"
putStrLn (Ba.irToString bap)
when (optionPrintRefCountIR opts
|| optionAssembly opts
|| optionCompile opts) $
runFromRefCountIr bap
runFromRefCountIr :: Ba.Program -> IO ()
runFromRefCountIr bap = do
let rcp = Rc.refCountIr bap
when (optionPrintRefCountIR opts) $ do
putStrLn "\n## Reference counted intermediate representation\n"
putStrLn (Rc.irToString rcp)
when (optionAssembly opts
|| optionCompile opts) $ do
runFromAssemblyCompile rcp
runFromAssemblyCompile :: Rc.Program -> IO ()
runFromAssemblyCompile rcp = do
let cfile = outputBaseName ++ ".c"
let hfile = outputBaseName ++ ".h"
let himports = map (++ ".h") importBaseNames
Cg.genCode rcp cfile hfile himports
let root = projectRootPath opts
let runtimePath = root ++ "/" ++ stdRuntimePath
let mimallocLib = root ++ "/mimalloc/out/libmimalloc.a"
let gcc = if optionNoSplitStack opts
then "gcc"
else root ++ "/gcc/yu-stack-install/bin/gcc"
when (optionAssembly opts) $ do
let outfile = outputBaseName ++ ".s"
putStrLn $ "assemble " ++ outfile
let cargs = if optionOptimize opts
then ["-std=gnu11",
"-Wall",
"-pthread",
"-S",
"-O3",
"-DNDEBUG",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
else ["-std=gnu11",
"-Wall",
"-pthread",
"-S",
"-O1",
"-foptimize-sibling-calls",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
let debugOpt = if optionDebug opts then ["-g"] else []
let splitArgs = if optionNoSplitStack opts
then ["-Dyur_DISABLE_SPLIT_STACK"]
else ["-fyu-stack", "-fno-omit-frame-pointer"]
let allArgs = splitArgs ++ cargs ++ debugOpt ++ argumentGccOptions opts
when (optionVerboseOutput opts) $
putStrLn (gcc ++ concat (map (" "++) allArgs))
command_ [] gcc allArgs
when (optionCompile opts) $ do
let runtime = if optionNoSplitStack opts
then runtimePath ++ "/out/system-stack/libyur.a"
else runtimePath ++ "/out/split-stack/libyur.a"
let link = moduleName == ""
let outfile = if link
then outputBaseName ++ ".exe"
else outputBaseName ++ ".o"
objectFiles <- readIORef objectFilesRef
if link
then do
putStrLn $ "build and link " ++ outfile
else do
writeIORef objectFilesRef (outfile : objectFiles)
putStrLn $ "build " ++ outfile
let compileArg = if link then [] else ["-c"]
let cargs = if optionOptimize opts
then ["-std=gnu11",
"-Wall",
"-pthread",
"-DNDEBUG",
"-O3",
"-mtune=native",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
else ["-std=gnu11",
"-Wall",
"-pthread",
"-O1",
"-foptimize-sibling-calls",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
let linkArgs = if not link
then []
else
objectFiles ++
(if not $ optionFast opts then ["-Wl,-s"] else []) ++
["-static",
runtime,
mimallocLib,
"-Wl,--whole-archive",
"-lpthread",
"-Wl,--no-whole-archive",
"-latomic"]
let debugOpt = if optionDebug opts then ["-g"] else []
let splitArgs = if optionNoSplitStack opts
then ["-Dyur_DISABLE_SPLIT_STACK"]
else ["-fyu-stack", "-fno-omit-frame-pointer"]
let allArgs = compileArg
++ splitArgs
++ cargs
++ debugOpt
++ linkArgs
++ argumentGccOptions opts
when (optionVerboseOutput opts) $
putStrLn (gcc ++ concat (map (" "++) allArgs))
command_ [] gcc allArgs
getProjectPath :: IO FilePath
getProjectPath = do
e <- getExecutablePath
canonicalizePath (takeDirectory e ++ "/..")
packagePaths :: ProgramOptions -> IO PackageMap
packagePaths opts = do
let yuPath = projectRootPath opts ++ "/stdlib/yu"
aps <- mapM canonicalizePath (optionPackages opts)
let ps = map (\ p -> (takeFileName p, p)) aps
return (Map.fromList (("yu", yuPath) : ps))
run :: ProgramOptions -> IO ()
run opts = do
packs <- packagePaths opts
let params = TypeCheckParams
{ tcParamVerbose = optionVerboseOutput opts
, tcParamCompile = optionCompile opts || optionAssembly opts
, tcParamClean = optionClean opts
}
objectFilesRef <- newIORef []
tc <- runTT params packs (argumentFileName opts)
(runIr objectFilesRef opts, collectIr objectFilesRef)
case tc of
Just msg -> hPutStrLn stderr msg >> Exit.exitWith (Exit.ExitFailure 1)
Nothing -> return ()
data ProgramOptions = ProgramOptions
{ optionPackages :: [String]
, optionCompile :: Bool
, optionClean :: Bool
, optionAssembly :: Bool
, optionOptimize :: Bool
, optionFast :: Bool
, optionDebug :: Bool
, optionNoSplitStack :: Bool
, optionPrintHighLevelIR :: Bool
, optionPrintBaseIR :: Bool
, optionPrintRefCountIR :: Bool
, optionVerboseOutput :: Bool
, projectRootPath :: FilePath
, argumentFileName :: FilePath
, argumentGccOptions :: [FilePath]
}
makeProgramOptions ::
FilePath -> [FilePath] -> [String] ->
Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool ->
ProgramOptions
makeProgramOptions
argFileName
argGccOptions
optPackages
optCompile
optClean
optAssembly
optOptimize
optFast
optDebug
optNoSplitStack
optPrintHighLevelIR
optPrintBaseIR
optPrintRefCountIR
optVerboseOutput
= ProgramOptions
{ optionPackages = optPackages
, optionCompile = optCompile
, optionClean = optClean
, optionAssembly = optAssembly
, optionOptimize = optOptimize
, optionFast = optFast
, optionDebug = optDebug
, optionNoSplitStack = NO_SPLIT_STACK || optNoSplitStack
, optionPrintHighLevelIR = optPrintHighLevelIR
, optionPrintBaseIR = optPrintBaseIR
, optionPrintRefCountIR = optPrintRefCountIR
, optionVerboseOutput = optVerboseOutput
, argumentFileName = argFileName
, argumentGccOptions = argGccOptions
, projectRootPath = ""
}
cmdParser :: Ar.ParserSpec ProgramOptions
cmdParser = makeProgramOptions
`Ar.parsedBy` reqPos "file"
`Ar.Descr` "The mini-yu source code file."
`Ar.andBy` posArgs "gcc files" [] (\xs x -> xs ++ [x])
`Ar.Descr` "Additional files passed to gcc."
`Ar.andBy` Ar.optFlagArgs [] "package" [] (\ ps p -> p : ps)
`Ar.Descr` "Paths of Mini Yu packages to include."
`Ar.andBy` ArPa.FlagParam ArPa.Short "compile" id
`Ar.Descr` "Compile the source code."
`Ar.andBy` ArPa.FlagParam ArPa.Long "clean" id
`Ar.Descr` "Force compiler to re-type-check and re-compile everything."
`Ar.andBy` ArPa.FlagParam ArPa.Short "assembly" id
`Ar.Descr` "Output compiler generated assembly code."
`Ar.andBy` ArPa.FlagParam ArPa.Short "optimize" id
`Ar.Descr` "Enable more than the default optimizations to improve performance."
`Ar.andBy` ArPa.FlagParam ArPa.Long "fast" id
`Ar.Descr` "Disable optimizations to build faster."
`Ar.andBy` ArPa.FlagParam ArPa.Long "debug" id
`Ar.Descr` "Enable gcc debug information."
`Ar.andBy` ArPa.FlagParam ArPa.Long "no-split-stack" id
`Ar.Descr` "Use a large (3GB) system stack instead of split (segmented) stack."
`Ar.andBy` ArPa.FlagParam ArPa.Long "print-high-level-ir" id
`Ar.Descr` "Print initial intermediate representation."
`Ar.andBy` ArPa.FlagParam ArPa.Long "print-base-ir" id
`Ar.Descr` "Print second intermediate representation."
`Ar.andBy` ArPa.FlagParam ArPa.Long "print-ref-count-ir" id
`Ar.Descr` "Print reference counted intermediate representation."
`Ar.andBy` ArPa.FlagParam ArPa.Long "verbose" id
`Ar.Descr` "Enable verbose output."
verifyOptions :: ProgramOptions -> IO ()
verifyOptions opts
| optionFast opts && optionOptimize opts = do
hPutStrLn stderr ("Options " ++ quote "--fast" ++ " and "
++ quote "--optimize" ++ " are incompatible together")
Exit.exitWith (Exit.ExitFailure 1)
| True = return ()
cmdInterface :: IO (Ar.CmdLnInterface ProgramOptions)
cmdInterface = mkApp cmdParser
main :: IO ()
main = do
interface <- cmdInterface
args <- getArgs
case parseArgs args interface of
Right opts -> preRun opts >>= run
Left msg -> do
if msg == "too many arguments"
then hPutStrLn stderr ("Invalid command line arguments, try " ++ quote "--help")
else hPutStrLn stderr msg
Exit.exitWith (Exit.ExitFailure 1)
where
preRun :: ProgramOptions -> IO ProgramOptions
preRun opts = do
verifyOptions opts
a <- canonicalizePath (argumentFileName opts)
p <- getProjectPath
return (opts { argumentFileName = a
, projectRootPath = p })
| null | https://raw.githubusercontent.com/andreaslyn/mini-yu/b4c5ef2ac24c6e9519d79ee378e39e9c22ee873d/app/Main.hs | haskell | # LANGUAGE BangPatterns # | # LANGUAGE CPP #
#include "split-stack-config.h"
module Main (main) where
import PackageMap (PackageMap)
import System.Console.ArgParser.Params as ArPa
import System.Console.ArgParser as Ar
import TypeCheck.TypeCheck
import qualified Ir.BaseIr as Ba
import qualified Ir.HighLevelIr as Hl
import qualified Ir.RefCountIr as Rc
import System.Directory (canonicalizePath)
import Control.Monad
import qualified System.Exit as Exit
import qualified Ir.CodeGen as Cg
import System.Command (command_)
import System.IO (hPutStrLn, stderr)
import System.FilePath (takeDirectory, takeFileName)
import Str (quote, stdRuntimePath)
import System.Environment (getArgs, getExecutablePath)
import qualified Data.Map as Map
import Data.IORef
collectIr :: IORef [FilePath] -> TypeCheckContCollect
collectIr objectFilesRef outputBaseName = do
let ofile = outputBaseName ++ ".o"
modifyIORef objectFilesRef (ofile :)
runIr :: IORef [FilePath] -> ProgramOptions -> TypeCheckContCompile
runIr objectFilesRef opts outputBaseName importBaseNames allBaseNames
moduleName vs dm im rm =
when (optionPrintHighLevelIR opts
|| optionPrintBaseIR opts
|| optionPrintRefCountIR opts
|| optionAssembly opts
|| optionCompile opts)
runFromHighLevelIr
where
runFromHighLevelIr :: IO ()
runFromHighLevelIr = do
let (hap, har) = Hl.highLevelIr (not $ optionFast opts) moduleName vs dm im rm
when (optionPrintHighLevelIR opts) $ do
putStrLn "\n## High level intermediate representation\n"
putStrLn (Hl.irToString hap har)
when (optionPrintBaseIR opts
|| optionPrintRefCountIR opts
|| optionAssembly opts
|| optionCompile opts) $
runFromBaseIr hap har
runFromBaseIr :: Hl.Program -> Hl.ProgramRoots -> IO ()
runFromBaseIr hap har = do
bap <- Ba.baseIr (not $ optionFast opts) (optionVerboseOutput opts)
outputBaseName allBaseNames moduleName hap har
when (optionPrintBaseIR opts) $ do
putStrLn "\n## Base intermediate representation\n"
putStrLn (Ba.irToString bap)
when (optionPrintRefCountIR opts
|| optionAssembly opts
|| optionCompile opts) $
runFromRefCountIr bap
runFromRefCountIr :: Ba.Program -> IO ()
runFromRefCountIr bap = do
let rcp = Rc.refCountIr bap
when (optionPrintRefCountIR opts) $ do
putStrLn "\n## Reference counted intermediate representation\n"
putStrLn (Rc.irToString rcp)
when (optionAssembly opts
|| optionCompile opts) $ do
runFromAssemblyCompile rcp
runFromAssemblyCompile :: Rc.Program -> IO ()
runFromAssemblyCompile rcp = do
let cfile = outputBaseName ++ ".c"
let hfile = outputBaseName ++ ".h"
let himports = map (++ ".h") importBaseNames
Cg.genCode rcp cfile hfile himports
let root = projectRootPath opts
let runtimePath = root ++ "/" ++ stdRuntimePath
let mimallocLib = root ++ "/mimalloc/out/libmimalloc.a"
let gcc = if optionNoSplitStack opts
then "gcc"
else root ++ "/gcc/yu-stack-install/bin/gcc"
when (optionAssembly opts) $ do
let outfile = outputBaseName ++ ".s"
putStrLn $ "assemble " ++ outfile
let cargs = if optionOptimize opts
then ["-std=gnu11",
"-Wall",
"-pthread",
"-S",
"-O3",
"-DNDEBUG",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
else ["-std=gnu11",
"-Wall",
"-pthread",
"-S",
"-O1",
"-foptimize-sibling-calls",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
let debugOpt = if optionDebug opts then ["-g"] else []
let splitArgs = if optionNoSplitStack opts
then ["-Dyur_DISABLE_SPLIT_STACK"]
else ["-fyu-stack", "-fno-omit-frame-pointer"]
let allArgs = splitArgs ++ cargs ++ debugOpt ++ argumentGccOptions opts
when (optionVerboseOutput opts) $
putStrLn (gcc ++ concat (map (" "++) allArgs))
command_ [] gcc allArgs
when (optionCompile opts) $ do
let runtime = if optionNoSplitStack opts
then runtimePath ++ "/out/system-stack/libyur.a"
else runtimePath ++ "/out/split-stack/libyur.a"
let link = moduleName == ""
let outfile = if link
then outputBaseName ++ ".exe"
else outputBaseName ++ ".o"
objectFiles <- readIORef objectFilesRef
if link
then do
putStrLn $ "build and link " ++ outfile
else do
writeIORef objectFilesRef (outfile : objectFiles)
putStrLn $ "build " ++ outfile
let compileArg = if link then [] else ["-c"]
let cargs = if optionOptimize opts
then ["-std=gnu11",
"-Wall",
"-pthread",
"-DNDEBUG",
"-O3",
"-mtune=native",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
else ["-std=gnu11",
"-Wall",
"-pthread",
"-O1",
"-foptimize-sibling-calls",
"-momit-leaf-frame-pointer",
"-I", runtimePath,
"-o", outfile,
cfile]
let linkArgs = if not link
then []
else
objectFiles ++
(if not $ optionFast opts then ["-Wl,-s"] else []) ++
["-static",
runtime,
mimallocLib,
"-Wl,--whole-archive",
"-lpthread",
"-Wl,--no-whole-archive",
"-latomic"]
let debugOpt = if optionDebug opts then ["-g"] else []
let splitArgs = if optionNoSplitStack opts
then ["-Dyur_DISABLE_SPLIT_STACK"]
else ["-fyu-stack", "-fno-omit-frame-pointer"]
let allArgs = compileArg
++ splitArgs
++ cargs
++ debugOpt
++ linkArgs
++ argumentGccOptions opts
when (optionVerboseOutput opts) $
putStrLn (gcc ++ concat (map (" "++) allArgs))
command_ [] gcc allArgs
getProjectPath :: IO FilePath
getProjectPath = do
e <- getExecutablePath
canonicalizePath (takeDirectory e ++ "/..")
packagePaths :: ProgramOptions -> IO PackageMap
packagePaths opts = do
let yuPath = projectRootPath opts ++ "/stdlib/yu"
aps <- mapM canonicalizePath (optionPackages opts)
let ps = map (\ p -> (takeFileName p, p)) aps
return (Map.fromList (("yu", yuPath) : ps))
run :: ProgramOptions -> IO ()
run opts = do
packs <- packagePaths opts
let params = TypeCheckParams
{ tcParamVerbose = optionVerboseOutput opts
, tcParamCompile = optionCompile opts || optionAssembly opts
, tcParamClean = optionClean opts
}
objectFilesRef <- newIORef []
tc <- runTT params packs (argumentFileName opts)
(runIr objectFilesRef opts, collectIr objectFilesRef)
case tc of
Just msg -> hPutStrLn stderr msg >> Exit.exitWith (Exit.ExitFailure 1)
Nothing -> return ()
data ProgramOptions = ProgramOptions
{ optionPackages :: [String]
, optionCompile :: Bool
, optionClean :: Bool
, optionAssembly :: Bool
, optionOptimize :: Bool
, optionFast :: Bool
, optionDebug :: Bool
, optionNoSplitStack :: Bool
, optionPrintHighLevelIR :: Bool
, optionPrintBaseIR :: Bool
, optionPrintRefCountIR :: Bool
, optionVerboseOutput :: Bool
, projectRootPath :: FilePath
, argumentFileName :: FilePath
, argumentGccOptions :: [FilePath]
}
makeProgramOptions ::
FilePath -> [FilePath] -> [String] ->
Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool ->
ProgramOptions
makeProgramOptions
argFileName
argGccOptions
optPackages
optCompile
optClean
optAssembly
optOptimize
optFast
optDebug
optNoSplitStack
optPrintHighLevelIR
optPrintBaseIR
optPrintRefCountIR
optVerboseOutput
= ProgramOptions
{ optionPackages = optPackages
, optionCompile = optCompile
, optionClean = optClean
, optionAssembly = optAssembly
, optionOptimize = optOptimize
, optionFast = optFast
, optionDebug = optDebug
, optionNoSplitStack = NO_SPLIT_STACK || optNoSplitStack
, optionPrintHighLevelIR = optPrintHighLevelIR
, optionPrintBaseIR = optPrintBaseIR
, optionPrintRefCountIR = optPrintRefCountIR
, optionVerboseOutput = optVerboseOutput
, argumentFileName = argFileName
, argumentGccOptions = argGccOptions
, projectRootPath = ""
}
cmdParser :: Ar.ParserSpec ProgramOptions
cmdParser = makeProgramOptions
`Ar.parsedBy` reqPos "file"
`Ar.Descr` "The mini-yu source code file."
`Ar.andBy` posArgs "gcc files" [] (\xs x -> xs ++ [x])
`Ar.Descr` "Additional files passed to gcc."
`Ar.andBy` Ar.optFlagArgs [] "package" [] (\ ps p -> p : ps)
`Ar.Descr` "Paths of Mini Yu packages to include."
`Ar.andBy` ArPa.FlagParam ArPa.Short "compile" id
`Ar.Descr` "Compile the source code."
`Ar.andBy` ArPa.FlagParam ArPa.Long "clean" id
`Ar.Descr` "Force compiler to re-type-check and re-compile everything."
`Ar.andBy` ArPa.FlagParam ArPa.Short "assembly" id
`Ar.Descr` "Output compiler generated assembly code."
`Ar.andBy` ArPa.FlagParam ArPa.Short "optimize" id
`Ar.Descr` "Enable more than the default optimizations to improve performance."
`Ar.andBy` ArPa.FlagParam ArPa.Long "fast" id
`Ar.Descr` "Disable optimizations to build faster."
`Ar.andBy` ArPa.FlagParam ArPa.Long "debug" id
`Ar.Descr` "Enable gcc debug information."
`Ar.andBy` ArPa.FlagParam ArPa.Long "no-split-stack" id
`Ar.Descr` "Use a large (3GB) system stack instead of split (segmented) stack."
`Ar.andBy` ArPa.FlagParam ArPa.Long "print-high-level-ir" id
`Ar.Descr` "Print initial intermediate representation."
`Ar.andBy` ArPa.FlagParam ArPa.Long "print-base-ir" id
`Ar.Descr` "Print second intermediate representation."
`Ar.andBy` ArPa.FlagParam ArPa.Long "print-ref-count-ir" id
`Ar.Descr` "Print reference counted intermediate representation."
`Ar.andBy` ArPa.FlagParam ArPa.Long "verbose" id
`Ar.Descr` "Enable verbose output."
verifyOptions :: ProgramOptions -> IO ()
verifyOptions opts
| optionFast opts && optionOptimize opts = do
hPutStrLn stderr ("Options " ++ quote "--fast" ++ " and "
++ quote "--optimize" ++ " are incompatible together")
Exit.exitWith (Exit.ExitFailure 1)
| True = return ()
cmdInterface :: IO (Ar.CmdLnInterface ProgramOptions)
cmdInterface = mkApp cmdParser
main :: IO ()
main = do
interface <- cmdInterface
args <- getArgs
case parseArgs args interface of
Right opts -> preRun opts >>= run
Left msg -> do
if msg == "too many arguments"
then hPutStrLn stderr ("Invalid command line arguments, try " ++ quote "--help")
else hPutStrLn stderr msg
Exit.exitWith (Exit.ExitFailure 1)
where
preRun :: ProgramOptions -> IO ProgramOptions
preRun opts = do
verifyOptions opts
a <- canonicalizePath (argumentFileName opts)
p <- getProjectPath
return (opts { argumentFileName = a
, projectRootPath = p })
|
083bfd08b8795a6e67df746b936dbc1fe14255e6b314ad7058b6db8b91a163e7 | datacrypt-project/hitchhiker-tree | messaging.cljc | (ns hitchhiker.tree.messaging
(:refer-clojure :exclude [subvec])
(:require [clojure.core.rrb-vector :refer [catvec]]
[hasch.core :refer [uuid]]
#?(:clj [clojure.core.async :as async]
:cljs [cljs.core.async :as async])
#?(:clj [clojure.pprint :as pp])
#?(:clj [hitchhiker.tree.core :refer [go-try <? <??] :as core]
:cljs [hitchhiker.tree.core :as core]))
#?(:clj (:import java.io.Writer))
#?(:cljs (:require-macros [hitchhiker.tree.core :refer [go-try <? <?resolve]])))
;; An operation is an object with a few functions
1 . It has a function that it applies to the tree to apply its effect
;; In the future, it could also have
2 . It has a promise which can be filled with the end result
;; (more memory but faster results for repeat queries)
(defprotocol IOperation
(affects-key [op] "Which key this affects--currently must be a single key")
(apply-op-to-coll [op coll] "Applies the operation to the collection")
(apply-op-to-tree [op tree] "Applies the operation to the tree. Returns go-block."))
(defrecord InsertOp [key value]
IOperation
(affects-key [_] key)
(apply-op-to-coll [_ map] (assoc map key value))
(apply-op-to-tree [_ tree] (core/insert tree key value)))
(defrecord DeleteOp [key]
IOperation
(affects-key [_] key)
(apply-op-to-coll [_ map] (dissoc map key))
(apply-op-to-tree [_ tree] (core/delete tree key)))
#?(:clj
(defmethod print-method InsertOp
[op ^Writer writer]
(.write writer "InsertOp")
(.write writer (str {:key (:key op) :value (:value op) " - " (:tag op)}))))
#?(:clj
(defmethod print-dup InsertOp
[op ^Writer writer]
(.write writer "(tree.messaging/->InsertOp ")
(.write writer (pr-str (:key op)))
(.write writer ", ")
(.write writer (pr-str (:value op)))
(.write writer ")")))
#?(:clj
(defmethod pp/simple-dispatch InsertOp
[op]
(print op)))
#?(:clj
(defmethod print-method DeleteOp
[op ^Writer writer]
(.write writer "DeleteOp")
(.write writer (str {:key (:key op)} " - " (:tag op)))))
#?(:clj
(defmethod print-dup DeleteOp
[op ^Writer writer]
(.write writer "(tree.messaging/->DeleteOp ")
(.write writer (pr-str (:key op)))
(.write writer ")")))
#?(:clj
(defmethod pp/simple-dispatch DeleteOp
[op]
(print op)))
(defn enqueue
([tree msgs]
(go-try
(let [deferred-ops (atom [])
msg-buffers-propagated (<? (enqueue tree msgs deferred-ops))]
;(when (seq @deferred-ops) (println "appyling deferred ops" @deferred-ops))
(loop [tree msg-buffers-propagated
[op & r] @deferred-ops]
(if op
(recur (<? (apply-op-to-tree op tree)) r)
tree)))))
([tree msgs deferred-ops]
(go-try
(let [tree (core/<?resolve tree)]
(cond
(core/data-node? tree) ; need to return ops to apply to the tree proper...
(do (swap! deferred-ops into msgs)
tree)
(<= (+ (count msgs) (count (:op-buf tree)))
(get-in tree [:cfg :op-buf-size])) ; will there be enough space?
(-> tree
(core/dirty!)
(update-in [:op-buf] into msgs))
overflow , should be IndexNode
(do (assert (core/index-node? tree))
( println " overflowing node " (: keys tree ) " with buf " (: op - buf tree )
" with new msgs " msgs
; )
(loop [[child & children] (:children tree)
rebuilt-children []
msgs (vec (sort-by affects-key ;must be a stable sort
(concat (:op-buf tree) msgs)))]
(let [took-msgs (into []
(take-while #(>= 0 (core/compare
(affects-key %)
(core/last-key child))))
msgs)
extra-msgs (into []
(drop-while #(>= 0 (core/compare
(affects-key %)
(core/last-key child))))
msgs)
;_ (println "last-key:" (core/last-key child))
;_ (println "goes left:" took-msgs)
;_ (println "goes right:" extra-msgs)
on-the-last-child? (empty? children)
;; Any changes to the current child?
new-child
(cond
(and on-the-last-child? (seq extra-msgs))
(<? (enqueue (core/<?resolve child)
(catvec took-msgs extra-msgs)
deferred-ops))
(seq took-msgs) ; save a write
(<? (enqueue (core/<?resolve child)
(catvec took-msgs)
deferred-ops))
:else
child)]
(if on-the-last-child?
(-> tree
(assoc :children (conj rebuilt-children new-child))
(assoc :op-buf [])
(core/dirty!))
(recur children (conj rebuilt-children new-child) extra-msgs))))))))))
;;TODO delete in core needs to stop using the index-node constructor to be more
;;careful about how we handle op-bufs during splits and merges.
;;
;;After we've got delete working, lookup, pred, and succ should be fixed
;;
;;broadcast nodes will need IDs so that they can combine during merges...
;;
(defn general-max [e & r]
;; fast track for number keys
(if (number? e)
(apply max e r)
(reduce (fn [old elem]
(if (pos? (core/compare old elem))
old
elem))
e r)))
(defn apply-ops-in-path
[path]
(if (>= 1 (count path))
(:children (peek path))
(let [ops (->> path
(into [] (comp (filter core/index-node?)
(map :op-buf)))
(rseq) ; highest node should be last in seq
(apply catvec)
(sort-by affects-key)) ;must be a stable sort
this-node-index (-> path pop peek)
parent (-> path pop pop peek)
is-first? (zero? this-node-index)
;;We'll need to find the smallest last-key of the left siblings along the path
[left-sibs-on-path is-last?]
(loop [path path
is-last? true
left-sibs []]
(if (= 1 (count path)) ; are we at the root?
[left-sibs is-last?]
(let [this-node-index (-> path pop peek)
parent (-> path pop pop peek)
is-first? (zero? this-node-index)
local-last? (= (-> parent :children count dec)
this-node-index)]
(if is-first?
(recur (pop (pop path)) (and is-last? local-last?) left-sibs)
(recur (pop (pop path))
(and is-last? local-last?)
(conj left-sibs
(nth (:children parent)
(dec this-node-index))))))))
left-sibs-min-last (when (seq left-sibs-on-path)
(->> left-sibs-on-path
(map core/last-key)
(apply general-max)))
left-sib-filter (if left-sibs-min-last
(drop-while #(>= 0 (core/compare (affects-key %)
left-sibs-min-last)))
identity)
data-node (peek path)
my-last (core/last-key data-node)
right-side-filter (if is-last?
identity
(take-while #(>= 0 (core/compare (affects-key %) my-last))))
correct-ops (into [] (comp left-sib-filter right-side-filter) ops)
We include op if leq my left , and not if leq left 's left
;;TODO we can't apply all ops, we should ensure to only apply ops whose keys are in the defined range, unless we're the last sibling
]
;(println "left-sibs-min-last" left-sibs-min-last)
;(println "is-last?" is-last?)
;(println "expanding data node" data-node "with ops" correct-ops)
(reduce (fn [coll op]
(apply-op-to-coll op coll))
(:children data-node)
correct-ops))))
(defn lookup
([tree key]
(lookup tree key nil))
([tree key not-found]
(go-try
(let [path (<? (core/lookup-path tree key))
expanded (apply-ops-in-path path)]
(get expanded key not-found)))))
(defn insert
[tree key value]
(enqueue tree [(assoc (->InsertOp key value)
:tag (uuid)
)]))
(defn delete
[tree key]
(enqueue tree [(assoc (->DeleteOp key)
:tag (uuid)
)]))
(defn forward-iterator
"Takes the result of a search and puts the iterated elements onto iter-ch
going forward over the tree as needed. Does lg(n) backtracking sometimes."
[iter-ch path start-key]
(go-try
(loop [path path]
(if path
(let [_ (assert (core/data-node? (peek path)))
elements (drop-while (fn [[k v]]
(neg? (core/compare k start-key)))
(apply-ops-in-path path))]
(<? (async/onto-chan iter-ch elements false))
(recur (<? (core/right-successor (pop path)))))
(async/close! iter-ch)))))
#?(:clj
(defn lookup-fwd-iter
"Compatibility helper to clojure sequences. Please prefer the channel
interface of forward-iterator, as this function blocks your thread, which
disturbs async contexts and might lead to poor performance. It is mainly here
to facilitate testing or for exploration on the REPL."
[tree key]
(let [path (<?? (core/lookup-path tree key))
iter-ch (async/chan)]
(forward-iterator iter-ch path key)
(core/chan-seq iter-ch))))
| null | https://raw.githubusercontent.com/datacrypt-project/hitchhiker-tree/f7d0f926541d7cb31fac11c2d2245c5bac451b86/src/hitchhiker/tree/messaging.cljc | clojure | An operation is an object with a few functions
In the future, it could also have
(more memory but faster results for repeat queries)
(when (seq @deferred-ops) (println "appyling deferred ops" @deferred-ops))
need to return ops to apply to the tree proper...
will there be enough space?
)
must be a stable sort
_ (println "last-key:" (core/last-key child))
_ (println "goes left:" took-msgs)
_ (println "goes right:" extra-msgs)
Any changes to the current child?
save a write
TODO delete in core needs to stop using the index-node constructor to be more
careful about how we handle op-bufs during splits and merges.
After we've got delete working, lookup, pred, and succ should be fixed
broadcast nodes will need IDs so that they can combine during merges...
fast track for number keys
highest node should be last in seq
must be a stable sort
We'll need to find the smallest last-key of the left siblings along the path
are we at the root?
TODO we can't apply all ops, we should ensure to only apply ops whose keys are in the defined range, unless we're the last sibling
(println "left-sibs-min-last" left-sibs-min-last)
(println "is-last?" is-last?)
(println "expanding data node" data-node "with ops" correct-ops) | (ns hitchhiker.tree.messaging
(:refer-clojure :exclude [subvec])
(:require [clojure.core.rrb-vector :refer [catvec]]
[hasch.core :refer [uuid]]
#?(:clj [clojure.core.async :as async]
:cljs [cljs.core.async :as async])
#?(:clj [clojure.pprint :as pp])
#?(:clj [hitchhiker.tree.core :refer [go-try <? <??] :as core]
:cljs [hitchhiker.tree.core :as core]))
#?(:clj (:import java.io.Writer))
#?(:cljs (:require-macros [hitchhiker.tree.core :refer [go-try <? <?resolve]])))
1 . It has a function that it applies to the tree to apply its effect
2 . It has a promise which can be filled with the end result
(defprotocol IOperation
(affects-key [op] "Which key this affects--currently must be a single key")
(apply-op-to-coll [op coll] "Applies the operation to the collection")
(apply-op-to-tree [op tree] "Applies the operation to the tree. Returns go-block."))
(defrecord InsertOp [key value]
IOperation
(affects-key [_] key)
(apply-op-to-coll [_ map] (assoc map key value))
(apply-op-to-tree [_ tree] (core/insert tree key value)))
(defrecord DeleteOp [key]
IOperation
(affects-key [_] key)
(apply-op-to-coll [_ map] (dissoc map key))
(apply-op-to-tree [_ tree] (core/delete tree key)))
#?(:clj
(defmethod print-method InsertOp
[op ^Writer writer]
(.write writer "InsertOp")
(.write writer (str {:key (:key op) :value (:value op) " - " (:tag op)}))))
#?(:clj
(defmethod print-dup InsertOp
[op ^Writer writer]
(.write writer "(tree.messaging/->InsertOp ")
(.write writer (pr-str (:key op)))
(.write writer ", ")
(.write writer (pr-str (:value op)))
(.write writer ")")))
#?(:clj
(defmethod pp/simple-dispatch InsertOp
[op]
(print op)))
#?(:clj
(defmethod print-method DeleteOp
[op ^Writer writer]
(.write writer "DeleteOp")
(.write writer (str {:key (:key op)} " - " (:tag op)))))
#?(:clj
(defmethod print-dup DeleteOp
[op ^Writer writer]
(.write writer "(tree.messaging/->DeleteOp ")
(.write writer (pr-str (:key op)))
(.write writer ")")))
#?(:clj
(defmethod pp/simple-dispatch DeleteOp
[op]
(print op)))
(defn enqueue
([tree msgs]
(go-try
(let [deferred-ops (atom [])
msg-buffers-propagated (<? (enqueue tree msgs deferred-ops))]
(loop [tree msg-buffers-propagated
[op & r] @deferred-ops]
(if op
(recur (<? (apply-op-to-tree op tree)) r)
tree)))))
([tree msgs deferred-ops]
(go-try
(let [tree (core/<?resolve tree)]
(cond
(do (swap! deferred-ops into msgs)
tree)
(<= (+ (count msgs) (count (:op-buf tree)))
(-> tree
(core/dirty!)
(update-in [:op-buf] into msgs))
overflow , should be IndexNode
(do (assert (core/index-node? tree))
( println " overflowing node " (: keys tree ) " with buf " (: op - buf tree )
" with new msgs " msgs
(loop [[child & children] (:children tree)
rebuilt-children []
(concat (:op-buf tree) msgs)))]
(let [took-msgs (into []
(take-while #(>= 0 (core/compare
(affects-key %)
(core/last-key child))))
msgs)
extra-msgs (into []
(drop-while #(>= 0 (core/compare
(affects-key %)
(core/last-key child))))
msgs)
on-the-last-child? (empty? children)
new-child
(cond
(and on-the-last-child? (seq extra-msgs))
(<? (enqueue (core/<?resolve child)
(catvec took-msgs extra-msgs)
deferred-ops))
(<? (enqueue (core/<?resolve child)
(catvec took-msgs)
deferred-ops))
:else
child)]
(if on-the-last-child?
(-> tree
(assoc :children (conj rebuilt-children new-child))
(assoc :op-buf [])
(core/dirty!))
(recur children (conj rebuilt-children new-child) extra-msgs))))))))))
(defn general-max [e & r]
(if (number? e)
(apply max e r)
(reduce (fn [old elem]
(if (pos? (core/compare old elem))
old
elem))
e r)))
(defn apply-ops-in-path
[path]
(if (>= 1 (count path))
(:children (peek path))
(let [ops (->> path
(into [] (comp (filter core/index-node?)
(map :op-buf)))
(apply catvec)
this-node-index (-> path pop peek)
parent (-> path pop pop peek)
is-first? (zero? this-node-index)
[left-sibs-on-path is-last?]
(loop [path path
is-last? true
left-sibs []]
[left-sibs is-last?]
(let [this-node-index (-> path pop peek)
parent (-> path pop pop peek)
is-first? (zero? this-node-index)
local-last? (= (-> parent :children count dec)
this-node-index)]
(if is-first?
(recur (pop (pop path)) (and is-last? local-last?) left-sibs)
(recur (pop (pop path))
(and is-last? local-last?)
(conj left-sibs
(nth (:children parent)
(dec this-node-index))))))))
left-sibs-min-last (when (seq left-sibs-on-path)
(->> left-sibs-on-path
(map core/last-key)
(apply general-max)))
left-sib-filter (if left-sibs-min-last
(drop-while #(>= 0 (core/compare (affects-key %)
left-sibs-min-last)))
identity)
data-node (peek path)
my-last (core/last-key data-node)
right-side-filter (if is-last?
identity
(take-while #(>= 0 (core/compare (affects-key %) my-last))))
correct-ops (into [] (comp left-sib-filter right-side-filter) ops)
We include op if leq my left , and not if leq left 's left
]
(reduce (fn [coll op]
(apply-op-to-coll op coll))
(:children data-node)
correct-ops))))
(defn lookup
([tree key]
(lookup tree key nil))
([tree key not-found]
(go-try
(let [path (<? (core/lookup-path tree key))
expanded (apply-ops-in-path path)]
(get expanded key not-found)))))
(defn insert
[tree key value]
(enqueue tree [(assoc (->InsertOp key value)
:tag (uuid)
)]))
(defn delete
[tree key]
(enqueue tree [(assoc (->DeleteOp key)
:tag (uuid)
)]))
(defn forward-iterator
"Takes the result of a search and puts the iterated elements onto iter-ch
going forward over the tree as needed. Does lg(n) backtracking sometimes."
[iter-ch path start-key]
(go-try
(loop [path path]
(if path
(let [_ (assert (core/data-node? (peek path)))
elements (drop-while (fn [[k v]]
(neg? (core/compare k start-key)))
(apply-ops-in-path path))]
(<? (async/onto-chan iter-ch elements false))
(recur (<? (core/right-successor (pop path)))))
(async/close! iter-ch)))))
#?(:clj
(defn lookup-fwd-iter
"Compatibility helper to clojure sequences. Please prefer the channel
interface of forward-iterator, as this function blocks your thread, which
disturbs async contexts and might lead to poor performance. It is mainly here
to facilitate testing or for exploration on the REPL."
[tree key]
(let [path (<?? (core/lookup-path tree key))
iter-ch (async/chan)]
(forward-iterator iter-ch path key)
(core/chan-seq iter-ch))))
|
6219f9968559e77ee005e57e529828c4e9a177fb13bc68a9321753502f28de27 | S8A/htdp-exercises | ex344.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex344) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp")) #f)))
(define file-part1 (make-file "part1" 99 ""))
(define file-part2 (make-file "part2" 52 ""))
(define file-part3 (make-file "part3" 17 ""))
(define file-hang (make-file "hang" 8 ""))
(define file-draw (make-file "draw" 2 ""))
(define file-docs-read (make-file "read!" 19 ""))
(define file-ts-read (make-file "read!" 10 ""))
(define dir-text (make-dir "Text" '() (list file-part1 file-part2 file-part3)))
(define dir-code (make-dir "Code" '() (list file-hang file-draw)))
(define dir-docs (make-dir "Docs" '() (list file-docs-read)))
(define dir-libs (make-dir "Libs" (list dir-code dir-docs) '()))
(define dir-ts (make-dir "TS" (list dir-text dir-libs) (list file-ts-read)))
(define path-part1 '("Text" "part1"))
(define path-part2 '("Text" "part2"))
(define path-part3 '("Text" "part3"))
(define path-hang '("Libs" "Code" "hang"))
(define path-draw '("Libs" "Code" "draw"))
(define path-docs-read '("Libs" "Docs" "read!"))
(define path-ts-read '("read!"))
; String Dir -> [List-of Path]
; produces the lists of paths belonging to files named f in the given
; directory tree
(define (find-all f d)
(filter (lambda (path) (string=? f (first (reverse path))))
(ls-R d)))
(check-expect (find-all "read!" dir-text) '())
(check-expect (find-all "read!" dir-code) '())
(check-expect (find-all "read!" dir-docs) '(("read!")))
(check-expect (find-all "read!" dir-libs) '(("Docs" "read!")))
(check-expect (find-all "read!" dir-ts) '(("Libs" "Docs" "read!")
("read!")))
; Dir -> [List-of Path]
; lists the paths of all files and directories in a given directory tree
(define (ls-R d)
(local ((define files-paths ; [List-of Path]
(map (lambda (f) (list (file-name f))) (dir-files d)))
(define dirs-file-paths ; [List-of Path]
(foldr append '()
(map (lambda (dir)
(map (lambda (result) (cons (dir-name dir) result))
(ls-R dir)))
(dir-dirs d)))))
(append dirs-file-paths files-paths)))
(check-satisfied (ls-R dir-text) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,(rest path-part1)
,(rest path-part2)
,(rest path-part3)))))
(check-satisfied (ls-R dir-code) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,(rest (rest path-hang))
,(rest (rest path-draw))))))
(check-expect (ls-R dir-docs) `(,(rest (rest path-docs-read))))
(check-satisfied (ls-R dir-libs) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,(rest path-hang) ,(rest path-draw)
,(rest path-docs-read)))))
(check-satisfied (ls-R dir-ts) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,path-part1 ,path-part2 ,path-part3
,path-hang ,path-draw
,path-docs-read
,path-ts-read))))
; Path Path -> Boolean
does path 1 come before path 2 ( lexicographically )
(define (path-name<? path1 path2)
(local (; Path -> String
(define (path-name p)
(foldr (lambda (parent child) (string-append parent "/" child))
"" p)))
(string<? (path-name path1) (path-name path2))))
(check-expect (path-name<? path-hang path-part1) #true)
(check-expect (path-name<? path-hang path-draw) #false)
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex344.rkt | racket | about the language level of this file in a form that our tools can easily process.
String Dir -> [List-of Path]
produces the lists of paths belonging to files named f in the given
directory tree
Dir -> [List-of Path]
lists the paths of all files and directories in a given directory tree
[List-of Path]
[List-of Path]
Path Path -> Boolean
Path -> String | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex344) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp")) #f)))
(define file-part1 (make-file "part1" 99 ""))
(define file-part2 (make-file "part2" 52 ""))
(define file-part3 (make-file "part3" 17 ""))
(define file-hang (make-file "hang" 8 ""))
(define file-draw (make-file "draw" 2 ""))
(define file-docs-read (make-file "read!" 19 ""))
(define file-ts-read (make-file "read!" 10 ""))
(define dir-text (make-dir "Text" '() (list file-part1 file-part2 file-part3)))
(define dir-code (make-dir "Code" '() (list file-hang file-draw)))
(define dir-docs (make-dir "Docs" '() (list file-docs-read)))
(define dir-libs (make-dir "Libs" (list dir-code dir-docs) '()))
(define dir-ts (make-dir "TS" (list dir-text dir-libs) (list file-ts-read)))
(define path-part1 '("Text" "part1"))
(define path-part2 '("Text" "part2"))
(define path-part3 '("Text" "part3"))
(define path-hang '("Libs" "Code" "hang"))
(define path-draw '("Libs" "Code" "draw"))
(define path-docs-read '("Libs" "Docs" "read!"))
(define path-ts-read '("read!"))
(define (find-all f d)
(filter (lambda (path) (string=? f (first (reverse path))))
(ls-R d)))
(check-expect (find-all "read!" dir-text) '())
(check-expect (find-all "read!" dir-code) '())
(check-expect (find-all "read!" dir-docs) '(("read!")))
(check-expect (find-all "read!" dir-libs) '(("Docs" "read!")))
(check-expect (find-all "read!" dir-ts) '(("Libs" "Docs" "read!")
("read!")))
(define (ls-R d)
(map (lambda (f) (list (file-name f))) (dir-files d)))
(foldr append '()
(map (lambda (dir)
(map (lambda (result) (cons (dir-name dir) result))
(ls-R dir)))
(dir-dirs d)))))
(append dirs-file-paths files-paths)))
(check-satisfied (ls-R dir-text) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,(rest path-part1)
,(rest path-part2)
,(rest path-part3)))))
(check-satisfied (ls-R dir-code) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,(rest (rest path-hang))
,(rest (rest path-draw))))))
(check-expect (ls-R dir-docs) `(,(rest (rest path-docs-read))))
(check-satisfied (ls-R dir-libs) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,(rest path-hang) ,(rest path-draw)
,(rest path-docs-read)))))
(check-satisfied (ls-R dir-ts) (lambda (l)
(andmap (lambda (p) (member? p l))
`(,path-part1 ,path-part2 ,path-part3
,path-hang ,path-draw
,path-docs-read
,path-ts-read))))
does path 1 come before path 2 ( lexicographically )
(define (path-name<? path1 path2)
(define (path-name p)
(foldr (lambda (parent child) (string-append parent "/" child))
"" p)))
(string<? (path-name path1) (path-name path2))))
(check-expect (path-name<? path-hang path-part1) #true)
(check-expect (path-name<? path-hang path-draw) #false)
|
fc2b953b9013f3ad1d72bb37739024ededb7dc3f02bc88360ae01452efc03a42 | haskell/hackage-security | Lens.hs | -- | Some very simple lens definitions (to avoid further dependencies)
--
-- Intended to be double-imported
-- > import Hackage.Security.Util.Lens (Lens)
-- > import qualified Hackage.Security.Util.Lens as Lens
module Hackage.Security.Util.Lens (
-- * Generic definitions
Lens
, Lens'
, Traversal
, Traversal'
, get
, over
, set
) where
import MyPrelude
import Control.Applicative
import Data.Functor.Identity
{-------------------------------------------------------------------------------
General definitions
-------------------------------------------------------------------------------}
-- | Polymorphic lens
type Lens s t a b = forall f. Functor f => LensLike f s t a b
| lens
type Lens' s a = Lens s s a a
-- | Polymorphic traversal
type Traversal s t a b = forall f. Applicative f => LensLike f s t a b
| traversal
type Traversal' s a = Traversal s s a a
type LensLike f s t a b = (a -> f b) -> s -> f t
type LensLike' f s a = LensLike f s s a a
get :: LensLike' (Const a) s a -> s -> a
get l = getConst . l Const
over :: LensLike Identity s t a b -> (a -> b) -> s -> t
over l f = runIdentity . l (Identity . f)
set :: LensLike Identity s t a b -> b -> s -> t
set l = over l . const
| null | https://raw.githubusercontent.com/haskell/hackage-security/745b294e8cda2b46a21a6d1766a87f699a0277a8/hackage-security/src/Hackage/Security/Util/Lens.hs | haskell | | Some very simple lens definitions (to avoid further dependencies)
Intended to be double-imported
> import Hackage.Security.Util.Lens (Lens)
> import qualified Hackage.Security.Util.Lens as Lens
* Generic definitions
------------------------------------------------------------------------------
General definitions
------------------------------------------------------------------------------
| Polymorphic lens
| Polymorphic traversal | module Hackage.Security.Util.Lens (
Lens
, Lens'
, Traversal
, Traversal'
, get
, over
, set
) where
import MyPrelude
import Control.Applicative
import Data.Functor.Identity
type Lens s t a b = forall f. Functor f => LensLike f s t a b
| lens
type Lens' s a = Lens s s a a
type Traversal s t a b = forall f. Applicative f => LensLike f s t a b
| traversal
type Traversal' s a = Traversal s s a a
type LensLike f s t a b = (a -> f b) -> s -> f t
type LensLike' f s a = LensLike f s s a a
get :: LensLike' (Const a) s a -> s -> a
get l = getConst . l Const
over :: LensLike Identity s t a b -> (a -> b) -> s -> t
over l f = runIdentity . l (Identity . f)
set :: LensLike Identity s t a b -> b -> s -> t
set l = over l . const
|
9ff9c279fe2509ab3dae46f3ccbda45d01fe962df569a8a957f928f8928b54cb | athoune/carcel | carcel_tests.erl | -module(carcel_tests).
-include_lib("eunit/include/eunit.hrl").
carcel_test() ->
Writer = [<<"erlang.net">>, article, 42, write],
Editor = [<<"erlang.net">>, article],
?assert(not(carcel:can(Writer, [<<"erlang.net">>, article]))),
?assert(carcel:can(Editor, [<<"erlang.net">>, article])),
?assert(not(carcel:can(Editor, [<<"erlang.net">>, blog]))),
?assert(carcel:can(Editor, ['_', article])),
?assert(carcel:can(Writer, ['_', article, '_', write])).
carcel_check_test() ->
Acls = [
[<<"erlang.net">>, article, 42, write],
[<<"erlang.net">>, article, 43, write]
],
?assert(not(carcel:check(Acls, [<<"erlang.net">>, article, 44, write]))),
?assert(carcel:check(Acls, [<<"erlang.net">>, article, 42, write])).
list_test() ->
Acls = [<<"erlang.net">>, article, [42, 43], write],
?assert(not(carcel:can(Acls, [<<"erlang.net">>, article, 44, write]))),
?assert(carcel:can(Acls, [<<"erlang.net">>, article, 42, write])).
sort_test() ->
Acls = [
[<<"erlang.net">>, article, 42, write],
[<<"erlang.net">>, comment, '_', moderate],
[<<"erlang.net">>, stats]
],
?assertEqual( [<<"erlang.net">>, stats], lists:nth(1, carcel:sort(Acls))).
compact_test() ->
Acls = [
[<<"erlang.net">>, article, 42, write],
[<<"erlang.net">>, article],
[<<"erlang.net">>, stats]
],
?assert(not(lists:member([<<"erlang.net">>, article, 42, write], carcel:compact(Acls)))).
dynamic_test() ->
Acl = [<<"erlang.net">>, article, fun(Context) -> Context + 22 end, write],
?assert(carcel:can(Acl, [<<"erlang.net">>, article, 42, write], 20)),
?assert(not(carcel:can(Acl, [<<"erlang.net">>, article, 42, write], 19))).
relation_test() ->
Relation = fun([_User, _Object]) -> [owner] end,% Just a mock
User = robert,
Object = article,
Acl1 = [<<"erlang.net">>, article, '_', write, Relation], % Can write any article wich I own
Action = [<<"erlang.net">>, article, 42, write, owner],
?assert(carcel:can(Acl1, Action, [User, Object])),
Can write article 42
?assert(carcel:can(Acl2, Action, [User, Object])).
| null | https://raw.githubusercontent.com/athoune/carcel/7f48b51f6d71f8a63f560cb719e7a99c8d548a4c/test/carcel_tests.erl | erlang | Just a mock
Can write any article wich I own | -module(carcel_tests).
-include_lib("eunit/include/eunit.hrl").
carcel_test() ->
Writer = [<<"erlang.net">>, article, 42, write],
Editor = [<<"erlang.net">>, article],
?assert(not(carcel:can(Writer, [<<"erlang.net">>, article]))),
?assert(carcel:can(Editor, [<<"erlang.net">>, article])),
?assert(not(carcel:can(Editor, [<<"erlang.net">>, blog]))),
?assert(carcel:can(Editor, ['_', article])),
?assert(carcel:can(Writer, ['_', article, '_', write])).
carcel_check_test() ->
Acls = [
[<<"erlang.net">>, article, 42, write],
[<<"erlang.net">>, article, 43, write]
],
?assert(not(carcel:check(Acls, [<<"erlang.net">>, article, 44, write]))),
?assert(carcel:check(Acls, [<<"erlang.net">>, article, 42, write])).
list_test() ->
Acls = [<<"erlang.net">>, article, [42, 43], write],
?assert(not(carcel:can(Acls, [<<"erlang.net">>, article, 44, write]))),
?assert(carcel:can(Acls, [<<"erlang.net">>, article, 42, write])).
sort_test() ->
Acls = [
[<<"erlang.net">>, article, 42, write],
[<<"erlang.net">>, comment, '_', moderate],
[<<"erlang.net">>, stats]
],
?assertEqual( [<<"erlang.net">>, stats], lists:nth(1, carcel:sort(Acls))).
compact_test() ->
Acls = [
[<<"erlang.net">>, article, 42, write],
[<<"erlang.net">>, article],
[<<"erlang.net">>, stats]
],
?assert(not(lists:member([<<"erlang.net">>, article, 42, write], carcel:compact(Acls)))).
dynamic_test() ->
Acl = [<<"erlang.net">>, article, fun(Context) -> Context + 22 end, write],
?assert(carcel:can(Acl, [<<"erlang.net">>, article, 42, write], 20)),
?assert(not(carcel:can(Acl, [<<"erlang.net">>, article, 42, write], 19))).
relation_test() ->
User = robert,
Object = article,
Action = [<<"erlang.net">>, article, 42, write, owner],
?assert(carcel:can(Acl1, Action, [User, Object])),
Can write article 42
?assert(carcel:can(Acl2, Action, [User, Object])).
|
f621d7aeaa2b5b4f64d6c67a840e451e54f9bba92de628c591d66c9f3b0003c1 | RJMetrics/sweet-liberty | utils.clj | (ns com.rjmetrics.sweet-liberty.integration.utils
(:require [com.rjmetrics.sweet-liberty.core :refer :all]
[compojure.core :refer [defroutes GET]]
[clojure.java.jdbc :as j]
[ring.middleware.params :refer [wrap-params]]))
(defn get-db-spec
[db-name]
{:subprotocol "hsqldb"
:subname (str "mem:" db-name)})
(def default-liberator-hooks {:available-media-types ["application/json"]
:authorized? true
:allowed? true})
(def default-table :test_table)
(def default-table-structure {:attributes [:name :id :state :note :datetime :date :timestamp]
:table-name default-table
:primary-key :id})
(defn keyword-to-str
[keyword]
(subs (str keyword) 1))
(defn create-table
([db-spec] (create-table db-spec default-table))
([db-spec table-name] (create-table db-spec
table-name
[[:id "INTEGER" "NOT NULL" "IDENTITY"]
[:name "VARCHAR(255)" "NOT NULL"]
[:state "INTEGER" "NOT NULL"]
[:note "VARCHAR(255)"]
[:datetime "DATETIME"]
[:date "DATE"]
[:timestamp "TIMESTAMP"]]))
([db-spec table-name fields]
(j/execute! db-spec [(apply j/create-table-ddl table-name fields)])))
(defn drop-table
([db-spec] (drop-table db-spec default-table))
([db-spec table-name]
;; I specifically opted not to use the ddl lib here since it doesn't support IF EXISTS
(j/execute! db-spec [(str "DROP TABLE IF EXISTS " (keyword-to-str table-name))])))
(defn populate-table
([db-spec] (populate-table db-spec default-table))
([db-spec table-name]
(apply j/insert! db-spec table-name [["id" "name" "state" "note" "datetime" "date" "timestamp"]
[0 "test0" 0 nil nil nil nil]
[1 "test1" 1 nil "2014-10-15 10:25:49" "1986-04-26" "2014-10-15 10:25:49"]])))
(defn get-all-rows
([db-spec] (get-all-rows db-spec default-table))
([db-spec table-name]
(j/query db-spec (str "SELECT * FROM " (keyword-to-str table-name)))))
(defn initialize-db
([db-spec] (initialize-db db-spec populate-table))
([db-spec populate-fn] (initialize-db db-spec populate-fn default-table))
([db-spec populate-fn table-name]
(drop-table db-spec table-name)
(create-table db-spec table-name)
(populate-fn db-spec table-name)))
(defn drop-db
([db-spec] (drop-db db-spec default-table))
([db-spec table-name]
(drop-table db-spec table-name)))
| null | https://raw.githubusercontent.com/RJMetrics/sweet-liberty/812a1caee1a6ef2053d0545a9e05d83e03011212/test/com/rjmetrics/sweet_liberty/integration/utils.clj | clojure | I specifically opted not to use the ddl lib here since it doesn't support IF EXISTS | (ns com.rjmetrics.sweet-liberty.integration.utils
(:require [com.rjmetrics.sweet-liberty.core :refer :all]
[compojure.core :refer [defroutes GET]]
[clojure.java.jdbc :as j]
[ring.middleware.params :refer [wrap-params]]))
(defn get-db-spec
[db-name]
{:subprotocol "hsqldb"
:subname (str "mem:" db-name)})
(def default-liberator-hooks {:available-media-types ["application/json"]
:authorized? true
:allowed? true})
(def default-table :test_table)
(def default-table-structure {:attributes [:name :id :state :note :datetime :date :timestamp]
:table-name default-table
:primary-key :id})
(defn keyword-to-str
[keyword]
(subs (str keyword) 1))
(defn create-table
([db-spec] (create-table db-spec default-table))
([db-spec table-name] (create-table db-spec
table-name
[[:id "INTEGER" "NOT NULL" "IDENTITY"]
[:name "VARCHAR(255)" "NOT NULL"]
[:state "INTEGER" "NOT NULL"]
[:note "VARCHAR(255)"]
[:datetime "DATETIME"]
[:date "DATE"]
[:timestamp "TIMESTAMP"]]))
([db-spec table-name fields]
(j/execute! db-spec [(apply j/create-table-ddl table-name fields)])))
(defn drop-table
([db-spec] (drop-table db-spec default-table))
([db-spec table-name]
(j/execute! db-spec [(str "DROP TABLE IF EXISTS " (keyword-to-str table-name))])))
(defn populate-table
([db-spec] (populate-table db-spec default-table))
([db-spec table-name]
(apply j/insert! db-spec table-name [["id" "name" "state" "note" "datetime" "date" "timestamp"]
[0 "test0" 0 nil nil nil nil]
[1 "test1" 1 nil "2014-10-15 10:25:49" "1986-04-26" "2014-10-15 10:25:49"]])))
(defn get-all-rows
([db-spec] (get-all-rows db-spec default-table))
([db-spec table-name]
(j/query db-spec (str "SELECT * FROM " (keyword-to-str table-name)))))
(defn initialize-db
([db-spec] (initialize-db db-spec populate-table))
([db-spec populate-fn] (initialize-db db-spec populate-fn default-table))
([db-spec populate-fn table-name]
(drop-table db-spec table-name)
(create-table db-spec table-name)
(populate-fn db-spec table-name)))
(defn drop-db
([db-spec] (drop-db db-spec default-table))
([db-spec table-name]
(drop-table db-spec table-name)))
|
a6319867188d570b2c1d5085adc4ad6fcdb83f6d15ee74c0a192d1fd438e3ae1 | Mzk-Levi/texts | SmartAConstructors.hs | # LANGUAGE TemplateHaskell #
--------------------------------------------------------------------------------
-- |
Module : Data . Comp . . Derive . SmartAConstructors
Copyright : ( c ) 2011 ,
-- License : BSD3
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC Extensions )
--
-- Automatically derive smart constructors with annotations for difunctors.
--
--------------------------------------------------------------------------------
module Data.Comp.Param.Derive.SmartAConstructors
(
smartAConstructors
) where
import Language.Haskell.TH hiding (Cxt)
import Data.Comp.Derive.Utils
import Data.Comp.Param.Ops
import Data.Comp.Param.Term
import Data.Comp.Param.Difunctor
import Control.Monad
| Derive smart constructors with annotations for a difunctor . The smart
constructors are similar to the ordinary constructors , but a
' injectA . dimap Var i d ' is automatically inserted .
constructors are similar to the ordinary constructors, but a
'injectA . dimap Var id' is automatically inserted. -}
smartAConstructors :: Name -> Q [Dec]
smartAConstructors fname = do
TyConI (DataD _cxt _tname _targs constrs _deriving) <- abstractNewtypeQ $ reify fname
let cons = map abstractConType constrs
liftM concat $ mapM genSmartConstr cons
where genSmartConstr (name, args) = do
let bname = nameBase name
genSmartConstr' (mkName $ "iA" ++ bname) name args
genSmartConstr' sname name args = do
varNs <- newNames args "x"
varPr <- newName "_p"
let pats = map varP (varPr : varNs)
vars = map varE varNs
val = appE [|injectA $(varE varPr)|] $
appE [|inj . dimap Var id|] $ foldl appE (conE name) vars
function = [funD sname [clause pats (normalB [|In $val|]) []]]
sequence function
| null | https://raw.githubusercontent.com/Mzk-Levi/texts/34916d6531af9bc39e50b596247ac2017d8cfdc3/compdata-param-master/src/Data/Comp/Param/Derive/SmartAConstructors.hs | haskell | ------------------------------------------------------------------------------
|
License : BSD3
Stability : experimental
Automatically derive smart constructors with annotations for difunctors.
------------------------------------------------------------------------------ | # LANGUAGE TemplateHaskell #
Module : Data . Comp . . Derive . SmartAConstructors
Copyright : ( c ) 2011 ,
Maintainer : < >
Portability : non - portable ( GHC Extensions )
module Data.Comp.Param.Derive.SmartAConstructors
(
smartAConstructors
) where
import Language.Haskell.TH hiding (Cxt)
import Data.Comp.Derive.Utils
import Data.Comp.Param.Ops
import Data.Comp.Param.Term
import Data.Comp.Param.Difunctor
import Control.Monad
| Derive smart constructors with annotations for a difunctor . The smart
constructors are similar to the ordinary constructors , but a
' injectA . dimap Var i d ' is automatically inserted .
constructors are similar to the ordinary constructors, but a
'injectA . dimap Var id' is automatically inserted. -}
smartAConstructors :: Name -> Q [Dec]
smartAConstructors fname = do
TyConI (DataD _cxt _tname _targs constrs _deriving) <- abstractNewtypeQ $ reify fname
let cons = map abstractConType constrs
liftM concat $ mapM genSmartConstr cons
where genSmartConstr (name, args) = do
let bname = nameBase name
genSmartConstr' (mkName $ "iA" ++ bname) name args
genSmartConstr' sname name args = do
varNs <- newNames args "x"
varPr <- newName "_p"
let pats = map varP (varPr : varNs)
vars = map varE varNs
val = appE [|injectA $(varE varPr)|] $
appE [|inj . dimap Var id|] $ foldl appE (conE name) vars
function = [funD sname [clause pats (normalB [|In $val|]) []]]
sequence function
|
3d709a78a43649b47055501008918aae8dfe9ca2e878a209c3fea7c0168e3b9b | vikram/lisplibraries | admin.lisp | ;;;; -*- lisp -*-
(in-package :it.bese.ucw)
(defvar *admin-application*
(make-instance 'standard-application
:url-prefix "/admin/"
:tal-generator (make-instance 'yaclml:file-system-generator
:cachep t
:root-directories (list *ucw-tal-root*))
:dispatchers (append (make-standard-ucw-dispatchers)
(list (make-url-dispatcher "index.ucw"
(call 'admin-app)))
(list (make-url-dispatcher ""
(call 'admin-app))))))
(defcomponent admin-app (simple-window-component)
((body :initarg :body
:accessor admin-app.body
:initform nil
:component admin-login))
(:default-initargs :title "UCW Administration" :stylesheet "/admin/ucw/ucw.css"))
(defmethod render ((app admin-app))
(<:h1 "UCW Administration.")
(render (admin-app.body app))
(<:br)
(<:A :href "index.ucw" "Back to admin entry."))
(defclass admin-login (login)
()
(:metaclass standard-component-class))
(defmethod check-credentials ((login admin-login))
(and (string= (login.username login) "admin")
(string= (login.password login) "admin")))
(defaction login-successful ((l admin-login))
(let* ((control-panel (make-instance 'admin-control-panel))
(server-repl (make-instance 'admin-repl))
(applications-contents (mapcar (lambda (app)
(cons (application.url-prefix app)
(make-instance 'application-inspector
:datum app)))
(server.applications *default-server*)))
(applications (make-instance 'tabbed-pane
:contents applications-contents
:current-component-key (caar applications-contents))))
(call 'tabbed-pane
:contents (list
(cons "Control Panel" control-panel)
(cons "Server REPL" server-repl)
(cons "Applications" applications))
:key-test #'string=
:current-component-key "Control Panel")))
Control Panel
(defclass admin-control-panel ()
()
(:metaclass standard-component-class))
(defmethod render ((c admin-control-panel))
(<:ul
(<:li (<ucw:a :action-body (admin-room c) "ROOM"))
(<:li (<ucw:a :action-body (start-slime-server c) "Start a SLIME server."))
(<:li (<ucw:a :action-body (toggle-inspectors c)
(<:as-html (if *inspect-components*
"Deactivate "
"Activate "))
"inspectors on all components."))
(<:li (<ucw:a :action-body (shutdown-ucw c) "Shutdown this instance of UCW."))))
(defaction toggle-inspectors ((c admin-control-panel))
(setf *inspect-components* (not *inspect-components*))
(call 'info-message :message (strcat "Inspectors " (if *inspect-components*
""
"de")
"activated.")))
(defaction shutdown-ucw ((c admin-control-panel))
(call 'info-message
:message "I. Don't. Think. So."
:ok-text "Sorry, I didn't really mean it."))
;;; ROOM
(defclass admin-room ()
()
(:metaclass standard-component-class))
(defaction admin-room ((c admin-control-panel))
(call 'admin-room))
(defmethod render ((room admin-room))
(<ucw:a :action-body (answer-component room t) "OK.")
(<:pre
(<:as-is (with-output-to-string (*standard-output*)
(room t))))
(<ucw:a :action-body (answer-component room t) "OK."))
;;;; Slime integration
(defaction start-slime-server ((c admin-control-panel))
(ucw.admin.info "Starting slime server.")
(call 'info-message
:message (format nil "Swank server started on port ~D." (swank:create-server))))
The REPL
(defclass package-select-field (select-field)
()
(:default-initargs
:data-set (sort (list-all-packages)
#'string< :key #'package-name)))
(defmethod render-value ((field package-select-field) (package package))
(<:as-html (package-name package)))
(defcomponent admin-repl (template-component)
((package-select :accessor package-select :initform (make-instance 'package-select-field))
(input :accessor input :initform (make-instance 'textarea-field
:rows 10
:cols 60))
(form-value :accessor admin-repl.form-value :initarg :form-value :initform nil))
(:default-initargs :template-name "ucw/admin/admin-repl.tal"))
(defun admin-do-eval (repl)
"Evaluate FORM in PACKAGE. We can't do this directly from the
EXECUTE-FORM action due to variable renaming issues."
(with-slots (package-select input form-value)
repl
(let* ((*package* (value package-select))
(form (read-from-string (value input))))
(setf form-value (eval form)))))
(defaction submit ((repl admin-repl))
(ucw.admin.info "Executing ~S." (client-value (input repl)))
;; parse the form values
(admin-do-eval repl))
(defaction new-repl ((repl admin-repl))
(setf (place (component.place repl)) (make-instance 'admin-repl)))
(defmethod safe-print-repl-value ((repl admin-repl))
(let ((*print-circle* t))
(labels ((abort-print (new-value)
(format t "Calling ABORT-PRINT with value ~S.~%" new-value)
(setf (admin-repl.form-value repl) new-value)
(return-from safe-print-repl-value
"#<ERROR PRINTING VALUE>")))
(restart-case
(handler-bind ((error #'abort-print))
(princ-to-string (admin-repl.form-value repl)))
(:return-condition ()
:report "Continue using NIL as the value."
(abort-print nil))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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_ajax/src/admin/admin.lisp | lisp | -*- lisp -*-
ROOM
Slime integration
parse the form values
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)
(defvar *admin-application*
(make-instance 'standard-application
:url-prefix "/admin/"
:tal-generator (make-instance 'yaclml:file-system-generator
:cachep t
:root-directories (list *ucw-tal-root*))
:dispatchers (append (make-standard-ucw-dispatchers)
(list (make-url-dispatcher "index.ucw"
(call 'admin-app)))
(list (make-url-dispatcher ""
(call 'admin-app))))))
(defcomponent admin-app (simple-window-component)
((body :initarg :body
:accessor admin-app.body
:initform nil
:component admin-login))
(:default-initargs :title "UCW Administration" :stylesheet "/admin/ucw/ucw.css"))
(defmethod render ((app admin-app))
(<:h1 "UCW Administration.")
(render (admin-app.body app))
(<:br)
(<:A :href "index.ucw" "Back to admin entry."))
(defclass admin-login (login)
()
(:metaclass standard-component-class))
(defmethod check-credentials ((login admin-login))
(and (string= (login.username login) "admin")
(string= (login.password login) "admin")))
(defaction login-successful ((l admin-login))
(let* ((control-panel (make-instance 'admin-control-panel))
(server-repl (make-instance 'admin-repl))
(applications-contents (mapcar (lambda (app)
(cons (application.url-prefix app)
(make-instance 'application-inspector
:datum app)))
(server.applications *default-server*)))
(applications (make-instance 'tabbed-pane
:contents applications-contents
:current-component-key (caar applications-contents))))
(call 'tabbed-pane
:contents (list
(cons "Control Panel" control-panel)
(cons "Server REPL" server-repl)
(cons "Applications" applications))
:key-test #'string=
:current-component-key "Control Panel")))
Control Panel
(defclass admin-control-panel ()
()
(:metaclass standard-component-class))
(defmethod render ((c admin-control-panel))
(<:ul
(<:li (<ucw:a :action-body (admin-room c) "ROOM"))
(<:li (<ucw:a :action-body (start-slime-server c) "Start a SLIME server."))
(<:li (<ucw:a :action-body (toggle-inspectors c)
(<:as-html (if *inspect-components*
"Deactivate "
"Activate "))
"inspectors on all components."))
(<:li (<ucw:a :action-body (shutdown-ucw c) "Shutdown this instance of UCW."))))
(defaction toggle-inspectors ((c admin-control-panel))
(setf *inspect-components* (not *inspect-components*))
(call 'info-message :message (strcat "Inspectors " (if *inspect-components*
""
"de")
"activated.")))
(defaction shutdown-ucw ((c admin-control-panel))
(call 'info-message
:message "I. Don't. Think. So."
:ok-text "Sorry, I didn't really mean it."))
(defclass admin-room ()
()
(:metaclass standard-component-class))
(defaction admin-room ((c admin-control-panel))
(call 'admin-room))
(defmethod render ((room admin-room))
(<ucw:a :action-body (answer-component room t) "OK.")
(<:pre
(<:as-is (with-output-to-string (*standard-output*)
(room t))))
(<ucw:a :action-body (answer-component room t) "OK."))
(defaction start-slime-server ((c admin-control-panel))
(ucw.admin.info "Starting slime server.")
(call 'info-message
:message (format nil "Swank server started on port ~D." (swank:create-server))))
The REPL
(defclass package-select-field (select-field)
()
(:default-initargs
:data-set (sort (list-all-packages)
#'string< :key #'package-name)))
(defmethod render-value ((field package-select-field) (package package))
(<:as-html (package-name package)))
(defcomponent admin-repl (template-component)
((package-select :accessor package-select :initform (make-instance 'package-select-field))
(input :accessor input :initform (make-instance 'textarea-field
:rows 10
:cols 60))
(form-value :accessor admin-repl.form-value :initarg :form-value :initform nil))
(:default-initargs :template-name "ucw/admin/admin-repl.tal"))
(defun admin-do-eval (repl)
"Evaluate FORM in PACKAGE. We can't do this directly from the
EXECUTE-FORM action due to variable renaming issues."
(with-slots (package-select input form-value)
repl
(let* ((*package* (value package-select))
(form (read-from-string (value input))))
(setf form-value (eval form)))))
(defaction submit ((repl admin-repl))
(ucw.admin.info "Executing ~S." (client-value (input repl)))
(admin-do-eval repl))
(defaction new-repl ((repl admin-repl))
(setf (place (component.place repl)) (make-instance 'admin-repl)))
(defmethod safe-print-repl-value ((repl admin-repl))
(let ((*print-circle* t))
(labels ((abort-print (new-value)
(format t "Calling ABORT-PRINT with value ~S.~%" new-value)
(setf (admin-repl.form-value repl) new-value)
(return-from safe-print-repl-value
"#<ERROR PRINTING VALUE>")))
(restart-case
(handler-bind ((error #'abort-print))
(princ-to-string (admin-repl.form-value repl)))
(:return-condition ()
:report "Continue using NIL as the value."
(abort-print nil))))))
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
|
2031e748e1afcc118901ad6d37eb51d86d32f4fc41684afbf3b5d4fe2f25626a | andrewthad/country | Unsafe.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE UnboxedTuples #
# OPTIONS_HADDOCK not - home #
| This module provides the data constructor for a ' Country ' .
While pattern matching on a country is perfectly safe ,
constructing one is not . There is an invariant the type
system does not capture that the country number , as defined
by ISO 3166 - 1 , is between the inclusive bounds 0 and 999 .
Failure to maintain this invariant can cause other functions
in this library to segfault .
While pattern matching on a country is perfectly safe,
constructing one is not. There is an invariant the type
system does not capture that the country number, as defined
by ISO 3166-1, is between the inclusive bounds 0 and 999.
Failure to maintain this invariant can cause other functions
in this library to segfault.
-}
module Country.Unsafe
( Country(..)
) where
import Country.Unexposed.Names (Country(..))
| null | https://raw.githubusercontent.com/andrewthad/country/e03df9d4528b030f30c233dd1b60942fd7d6ad05/country/src/Country/Unsafe.hs | haskell | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE UnboxedTuples #
# OPTIONS_HADDOCK not - home #
| This module provides the data constructor for a ' Country ' .
While pattern matching on a country is perfectly safe ,
constructing one is not . There is an invariant the type
system does not capture that the country number , as defined
by ISO 3166 - 1 , is between the inclusive bounds 0 and 999 .
Failure to maintain this invariant can cause other functions
in this library to segfault .
While pattern matching on a country is perfectly safe,
constructing one is not. There is an invariant the type
system does not capture that the country number, as defined
by ISO 3166-1, is between the inclusive bounds 0 and 999.
Failure to maintain this invariant can cause other functions
in this library to segfault.
-}
module Country.Unsafe
( Country(..)
) where
import Country.Unexposed.Names (Country(..))
|
|
1d6f17e48ec0fd36a71c22c63a6995c38ac955240419b2a5b34bfdae287ba978 | ml4tp/tcoq | hipattern.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
open Term
open Coqlib
(** High-order patterns *)
* Given a term with second - order variables in it ,
represented by Meta 's , and possibly applied using SoApp
terms , this function will perform second - order , binding - preserving ,
matching , in the case where the pattern is a pattern in the sense
of .
ALGORITHM :
Given a pattern , we decompose it , flattening casts and apply 's ,
recursing on all operators , and pushing the name of the binder each
time we descend a binder .
When we reach a first - order variable , we ask that the corresponding
term 's free - rels all be higher than the depth of the current stack .
When we reach a second - order application , we ask that the
intersection of the free - rels of the term and the current stack be
contained in the arguments of the application
represented by Meta's, and possibly applied using SoApp
terms, this function will perform second-order, binding-preserving,
matching, in the case where the pattern is a pattern in the sense
of Dale Miller.
ALGORITHM:
Given a pattern, we decompose it, flattening casts and apply's,
recursing on all operators, and pushing the name of the binder each
time we descend a binder.
When we reach a first-order variable, we ask that the corresponding
term's free-rels all be higher than the depth of the current stack.
When we reach a second-order application, we ask that the
intersection of the free-rels of the term and the current stack be
contained in the arguments of the application *)
* I implemented the following functions which test whether a term [ t ]
is an inductive but non - recursive type , a general conjuction , a
general disjunction , or a type with no constructors .
They are more general than matching with [ or_term ] , [ and_term ] , etc ,
since they do not depend on the name of the type . Hence , they
also work on ad - hoc disjunctions introduced by the user .
( , 6/8/97 ) .
is an inductive but non-recursive type, a general conjuction, a
general disjunction, or a type with no constructors.
They are more general than matching with [or_term], [and_term], etc,
since they do not depend on the name of the type. Hence, they
also work on ad-hoc disjunctions introduced by the user.
(Eduardo, 6/8/97). *)
type 'a matching_function = constr -> 'a option
type testing_function = constr -> bool
val match_with_non_recursive_type : (constr * constr list) matching_function
val is_non_recursive_type : testing_function
* Non recursive type with no indices and exactly one argument for each
constructor ; canonical definition of n - ary disjunction if strict
constructor; canonical definition of n-ary disjunction if strict *)
val match_with_disjunction : ?strict:bool -> ?onlybinary:bool -> (constr * constr list) matching_function
val is_disjunction : ?strict:bool -> ?onlybinary:bool -> testing_function
* Non recursive tuple ( one constructor and no indices ) with no inner
dependencies ; canonical definition of n - ary conjunction if strict
dependencies; canonical definition of n-ary conjunction if strict *)
val match_with_conjunction : ?strict:bool -> ?onlybinary:bool -> (constr * constr list) matching_function
val is_conjunction : ?strict:bool -> ?onlybinary:bool -> testing_function
(** Non recursive tuple, possibly with inner dependencies *)
val match_with_record : (constr * constr list) matching_function
val is_record : testing_function
* Like record but supports and tells if recursive ( e.g. Acc )
val match_with_tuple : (constr * constr list * bool) matching_function
val is_tuple : testing_function
(** No constructor, possibly with indices *)
val match_with_empty_type : constr matching_function
val is_empty_type : testing_function
* type with only one constructor and no arguments , possibly with indices
val match_with_unit_or_eq_type : constr matching_function
val is_unit_or_eq_type : testing_function
* type with only one constructor and no arguments , no indices
val is_unit_type : testing_function
* type with only one constructor , no arguments and at least one dependency
val is_inductive_equality : inductive -> bool
val match_with_equality_type : (constr * constr list) matching_function
val is_equality_type : testing_function
val match_with_nottype : (constr * constr) matching_function
val is_nottype : testing_function
val match_with_forall_term : (Name.t * constr * constr) matching_function
val is_forall_term : testing_function
val match_with_imp_term : (constr * constr) matching_function
val is_imp_term : testing_function
* I added these functions to test whether a type contains dependent
products or not , and if an inductive has constructors with dependent types
( excluding parameters ) . this is useful to check whether a conjunction is a
real conjunction and not a dependent tuple . ( , 13/5/2002 )
products or not, and if an inductive has constructors with dependent types
(excluding parameters). this is useful to check whether a conjunction is a
real conjunction and not a dependent tuple. (Pierre Corbineau, 13/5/2002) *)
val has_nodep_prod_after : int -> testing_function
val has_nodep_prod : testing_function
val match_with_nodep_ind : (constr * constr list * int) matching_function
val is_nodep_ind : testing_function
val match_with_sigma_type : (constr * constr list) matching_function
val is_sigma_type : testing_function
(** Recongnize inductive relation defined by reflexivity *)
type equation_kind =
| MonomorphicLeibnizEq of constr * constr
| PolymorphicLeibnizEq of constr * constr * constr
| HeterogenousEq of constr * constr * constr * constr
exception NoEquationFound
val match_with_equation:
constr -> coq_eq_data option * constr * equation_kind
* * * * patterns bound to some theory
* Match terms [ eq A t u ] , [ identity A t u ] or [ JMeq A t A u ]
Returns associated lemmas and [ A , t , u ] or fails PatternMatchingFailure
Returns associated lemmas and [A,t,u] or fails PatternMatchingFailure *)
val find_eq_data_decompose : ([ `NF ], 'r) Proofview.Goal.t -> constr ->
coq_eq_data * Univ.universe_instance * (types * constr * constr)
(** Idem but fails with an error message instead of PatternMatchingFailure *)
val find_this_eq_data_decompose : ([ `NF ], 'r) Proofview.Goal.t -> constr ->
coq_eq_data * Univ.universe_instance * (types * constr * constr)
(** A variant that returns more informative structure on the equality found *)
val find_eq_data : constr -> coq_eq_data * Univ.universe_instance * equation_kind
(** Match a term of the form [(existT A P t p)]
Returns associated lemmas and [A,P,t,p] *)
val find_sigma_data_decompose : constr ->
coq_sigma_data * (Univ.universe_instance * constr * constr * constr * constr)
(** Match a term of the form [{x:A|P}], returns [A] and [P] *)
val match_sigma : constr -> constr * constr
val is_matching_sigma : constr -> bool
(** Match a decidable equality judgement (e.g [{t=u:>T}+{~t=u}]), returns
[t,u,T] and a boolean telling if equality is on the left side *)
val match_eqdec : constr -> bool * constr * constr * constr * constr
* Match an equality up to conversion ; returns [ ( eq , ) ] in normal form
val dest_nf_eq : ([ `NF ], 'r) Proofview.Goal.t -> constr -> (constr * constr * constr)
(** Match a negation *)
val is_matching_not : constr -> bool
val is_matching_imp_False : constr -> bool
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/tactics/hipattern.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* High-order patterns
* Non recursive tuple, possibly with inner dependencies
* No constructor, possibly with indices
* Recongnize inductive relation defined by reflexivity
* Idem but fails with an error message instead of PatternMatchingFailure
* A variant that returns more informative structure on the equality found
* Match a term of the form [(existT A P t p)]
Returns associated lemmas and [A,P,t,p]
* Match a term of the form [{x:A|P}], returns [A] and [P]
* Match a decidable equality judgement (e.g [{t=u:>T}+{~t=u}]), returns
[t,u,T] and a boolean telling if equality is on the left side
* Match a negation | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Coqlib
* Given a term with second - order variables in it ,
represented by Meta 's , and possibly applied using SoApp
terms , this function will perform second - order , binding - preserving ,
matching , in the case where the pattern is a pattern in the sense
of .
ALGORITHM :
Given a pattern , we decompose it , flattening casts and apply 's ,
recursing on all operators , and pushing the name of the binder each
time we descend a binder .
When we reach a first - order variable , we ask that the corresponding
term 's free - rels all be higher than the depth of the current stack .
When we reach a second - order application , we ask that the
intersection of the free - rels of the term and the current stack be
contained in the arguments of the application
represented by Meta's, and possibly applied using SoApp
terms, this function will perform second-order, binding-preserving,
matching, in the case where the pattern is a pattern in the sense
of Dale Miller.
ALGORITHM:
Given a pattern, we decompose it, flattening casts and apply's,
recursing on all operators, and pushing the name of the binder each
time we descend a binder.
When we reach a first-order variable, we ask that the corresponding
term's free-rels all be higher than the depth of the current stack.
When we reach a second-order application, we ask that the
intersection of the free-rels of the term and the current stack be
contained in the arguments of the application *)
* I implemented the following functions which test whether a term [ t ]
is an inductive but non - recursive type , a general conjuction , a
general disjunction , or a type with no constructors .
They are more general than matching with [ or_term ] , [ and_term ] , etc ,
since they do not depend on the name of the type . Hence , they
also work on ad - hoc disjunctions introduced by the user .
( , 6/8/97 ) .
is an inductive but non-recursive type, a general conjuction, a
general disjunction, or a type with no constructors.
They are more general than matching with [or_term], [and_term], etc,
since they do not depend on the name of the type. Hence, they
also work on ad-hoc disjunctions introduced by the user.
(Eduardo, 6/8/97). *)
type 'a matching_function = constr -> 'a option
type testing_function = constr -> bool
val match_with_non_recursive_type : (constr * constr list) matching_function
val is_non_recursive_type : testing_function
* Non recursive type with no indices and exactly one argument for each
constructor ; canonical definition of n - ary disjunction if strict
constructor; canonical definition of n-ary disjunction if strict *)
val match_with_disjunction : ?strict:bool -> ?onlybinary:bool -> (constr * constr list) matching_function
val is_disjunction : ?strict:bool -> ?onlybinary:bool -> testing_function
* Non recursive tuple ( one constructor and no indices ) with no inner
dependencies ; canonical definition of n - ary conjunction if strict
dependencies; canonical definition of n-ary conjunction if strict *)
val match_with_conjunction : ?strict:bool -> ?onlybinary:bool -> (constr * constr list) matching_function
val is_conjunction : ?strict:bool -> ?onlybinary:bool -> testing_function
val match_with_record : (constr * constr list) matching_function
val is_record : testing_function
* Like record but supports and tells if recursive ( e.g. Acc )
val match_with_tuple : (constr * constr list * bool) matching_function
val is_tuple : testing_function
val match_with_empty_type : constr matching_function
val is_empty_type : testing_function
* type with only one constructor and no arguments , possibly with indices
val match_with_unit_or_eq_type : constr matching_function
val is_unit_or_eq_type : testing_function
* type with only one constructor and no arguments , no indices
val is_unit_type : testing_function
* type with only one constructor , no arguments and at least one dependency
val is_inductive_equality : inductive -> bool
val match_with_equality_type : (constr * constr list) matching_function
val is_equality_type : testing_function
val match_with_nottype : (constr * constr) matching_function
val is_nottype : testing_function
val match_with_forall_term : (Name.t * constr * constr) matching_function
val is_forall_term : testing_function
val match_with_imp_term : (constr * constr) matching_function
val is_imp_term : testing_function
* I added these functions to test whether a type contains dependent
products or not , and if an inductive has constructors with dependent types
( excluding parameters ) . this is useful to check whether a conjunction is a
real conjunction and not a dependent tuple . ( , 13/5/2002 )
products or not, and if an inductive has constructors with dependent types
(excluding parameters). this is useful to check whether a conjunction is a
real conjunction and not a dependent tuple. (Pierre Corbineau, 13/5/2002) *)
val has_nodep_prod_after : int -> testing_function
val has_nodep_prod : testing_function
val match_with_nodep_ind : (constr * constr list * int) matching_function
val is_nodep_ind : testing_function
val match_with_sigma_type : (constr * constr list) matching_function
val is_sigma_type : testing_function
type equation_kind =
| MonomorphicLeibnizEq of constr * constr
| PolymorphicLeibnizEq of constr * constr * constr
| HeterogenousEq of constr * constr * constr * constr
exception NoEquationFound
val match_with_equation:
constr -> coq_eq_data option * constr * equation_kind
* * * * patterns bound to some theory
* Match terms [ eq A t u ] , [ identity A t u ] or [ JMeq A t A u ]
Returns associated lemmas and [ A , t , u ] or fails PatternMatchingFailure
Returns associated lemmas and [A,t,u] or fails PatternMatchingFailure *)
val find_eq_data_decompose : ([ `NF ], 'r) Proofview.Goal.t -> constr ->
coq_eq_data * Univ.universe_instance * (types * constr * constr)
val find_this_eq_data_decompose : ([ `NF ], 'r) Proofview.Goal.t -> constr ->
coq_eq_data * Univ.universe_instance * (types * constr * constr)
val find_eq_data : constr -> coq_eq_data * Univ.universe_instance * equation_kind
val find_sigma_data_decompose : constr ->
coq_sigma_data * (Univ.universe_instance * constr * constr * constr * constr)
val match_sigma : constr -> constr * constr
val is_matching_sigma : constr -> bool
val match_eqdec : constr -> bool * constr * constr * constr * constr
* Match an equality up to conversion ; returns [ ( eq , ) ] in normal form
val dest_nf_eq : ([ `NF ], 'r) Proofview.Goal.t -> constr -> (constr * constr * constr)
val is_matching_not : constr -> bool
val is_matching_imp_False : constr -> bool
|
0b1f48cc6bcc6b3ac508735b2b071d926cb8d624a59c1698084bf711b0078fd5 | patricoferris/jsoo-p5 | indent.ml | open Js_of_ocaml
let textarea (textbox : Dom_html.textAreaElement Js.t) : unit =
let rec loop s acc (i, pos') =
try
let pos = String.index_from s pos' '\n' in
loop s ((i, (pos', pos)) :: acc) (succ i, succ pos)
with _ -> List.rev ((i, (pos', String.length s)) :: acc)
in
let rec find (l : (int * (int * int)) list) c =
match l with
| [] -> assert false
| (i, (lo, up)) :: _ when up >= c -> (c, i, lo, up)
| (_, (_lo, _up)) :: rem -> find rem c
in
let v = textbox##.value in
let pos =
let c1 = textbox##.selectionStart and c2 = textbox##.selectionEnd in
if Js.Opt.test (Js.Opt.return c1) && Js.Opt.test (Js.Opt.return c2) then
let l = loop (Js.to_string v) [] (0, 0) in
Some (find l c1, find l c2)
else None
in
let f =
match pos with
| None -> fun _ -> true
| Some ((_c1, line1, _lo1, _up1), (_c2, line2, _lo2, _up2)) ->
fun l -> l >= line1 + 1 && l <= line2 + 1
in
let v = Ocp_indent.indent (Js.to_string v) f in
textbox##.value := Js.string v;
match pos with
| Some ((c1, line1, _lo1, up1), (c2, line2, _lo2, up2)) ->
let l = loop v [] (0, 0) in
let lo1'', up1'' = List.assoc line1 l in
let lo2'', up2'' = List.assoc line2 l in
let n1 = max (c1 + up1'' - up1) lo1'' in
let n2 = max (c2 + up2'' - up2) lo2'' in
let () = (Obj.magic textbox)##setSelectionRange n1 n2 in
textbox##focus;
()
| None -> ()
| null | https://raw.githubusercontent.com/patricoferris/jsoo-p5/743dccce67cd8d942e3028a526046f20c08306be/editor/lib/indent.ml | ocaml | open Js_of_ocaml
let textarea (textbox : Dom_html.textAreaElement Js.t) : unit =
let rec loop s acc (i, pos') =
try
let pos = String.index_from s pos' '\n' in
loop s ((i, (pos', pos)) :: acc) (succ i, succ pos)
with _ -> List.rev ((i, (pos', String.length s)) :: acc)
in
let rec find (l : (int * (int * int)) list) c =
match l with
| [] -> assert false
| (i, (lo, up)) :: _ when up >= c -> (c, i, lo, up)
| (_, (_lo, _up)) :: rem -> find rem c
in
let v = textbox##.value in
let pos =
let c1 = textbox##.selectionStart and c2 = textbox##.selectionEnd in
if Js.Opt.test (Js.Opt.return c1) && Js.Opt.test (Js.Opt.return c2) then
let l = loop (Js.to_string v) [] (0, 0) in
Some (find l c1, find l c2)
else None
in
let f =
match pos with
| None -> fun _ -> true
| Some ((_c1, line1, _lo1, _up1), (_c2, line2, _lo2, _up2)) ->
fun l -> l >= line1 + 1 && l <= line2 + 1
in
let v = Ocp_indent.indent (Js.to_string v) f in
textbox##.value := Js.string v;
match pos with
| Some ((c1, line1, _lo1, up1), (c2, line2, _lo2, up2)) ->
let l = loop v [] (0, 0) in
let lo1'', up1'' = List.assoc line1 l in
let lo2'', up2'' = List.assoc line2 l in
let n1 = max (c1 + up1'' - up1) lo1'' in
let n2 = max (c2 + up2'' - up2) lo2'' in
let () = (Obj.magic textbox)##setSelectionRange n1 n2 in
textbox##focus;
()
| None -> ()
|
|
55129ff828cd7fb4de07fc2a938b9bd84b7e77620abc7d43571311ee2f4fe135 | alexandroid000/improv | JointState.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Sensor_msgs.JointState where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Data.Vector.Storable as V
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data JointState = JointState { _header :: Header.Header
, _name :: [P.String]
, _position :: V.Vector P.Double
, _velocity :: V.Vector P.Double
, _effort :: V.Vector P.Double
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''JointState)
instance RosBinary JointState where
put obj' = put (_header obj') *> putList (_name obj') *> put (_position obj') *> put (_velocity obj') *> put (_effort obj')
get = JointState <$> get <*> getList <*> get <*> get <*> get
putMsg = putStampedMsg
instance HasHeader JointState where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo JointState where
sourceMD5 _ = "3066dcd76a6cfaef579bd0f34173e9fd"
msgTypeName _ = "sensor_msgs/JointState"
instance D.Default JointState
| null | https://raw.githubusercontent.com/alexandroid000/improv/ef0f4a6a5f99a9c7ff3d25f50529417aba9f757c/roshask/msgs/Sensor_msgs/Ros/Sensor_msgs/JointState.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable # | # LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Ros.Sensor_msgs.JointState where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Data.Vector.Storable as V
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data JointState = JointState { _header :: Header.Header
, _name :: [P.String]
, _position :: V.Vector P.Double
, _velocity :: V.Vector P.Double
, _effort :: V.Vector P.Double
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''JointState)
instance RosBinary JointState where
put obj' = put (_header obj') *> putList (_name obj') *> put (_position obj') *> put (_velocity obj') *> put (_effort obj')
get = JointState <$> get <*> getList <*> get <*> get <*> get
putMsg = putStampedMsg
instance HasHeader JointState where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo JointState where
sourceMD5 _ = "3066dcd76a6cfaef579bd0f34173e9fd"
msgTypeName _ = "sensor_msgs/JointState"
instance D.Default JointState
|
324faaf70c6f15756e9d04b83ae93e9b6375796eaae126fb1796b035e20abe24 | hexlet-basics/exercises-racket | index.rkt | #lang racket
(provide add)
#| BEGIN |#
(define (add x y)
(let* ([result (~a (+ x y))]
[width (string-length result)])
(format
"+~a~n ~a~n ~a~n ~a"
(~a x #:min-width width #:align 'right)
(~a y #:min-width width #:align 'right)
(make-string width #\-)
result)))
#| END |#
| null | https://raw.githubusercontent.com/hexlet-basics/exercises-racket/ae3a45453584de1e5082c841178d4e43dd47e08a/modules/50-strings/50-formatting/index.rkt | racket | BEGIN
END | #lang racket
(provide add)
(define (add x y)
(let* ([result (~a (+ x y))]
[width (string-length result)])
(format
"+~a~n ~a~n ~a~n ~a"
(~a x #:min-width width #:align 'right)
(~a y #:min-width width #:align 'right)
(make-string width #\-)
result)))
|
9ec3a30f934593f0495929d4698648299acf94d74f1c43ecde835b07c78eca47 | gogins/csound-extended-nudruz | cring-cm.lisp | ;;; **********************************************************************
;;; $Name$
;;; $Revision$
$ Date$
(require :asdf)
(require :fomus)
(require :nudruz)
(load "example-csd.lisp")
(in-package :cm)
;;;
;;; Examples of "change ringing". I was made aware of this compositional
technique by . Change ringing is an algorithmic procedure
for church bell ringing invented by those clever British , who also gave
these algorithms great names like Plain , Grandsire Doubles etc .
;;; The algorithms all involve rotating diferent pairs of bells in the peal,
;;; but "...the composer's job is to be sure that he has selected as far as
possible the most musical sequences from the many thousands available . "
;;; We implement change ringing by passsing the appropriate changes to the
rotation pattern . These rotation changes affect just the first two
;;; change value numbers, ie. the start index and the stepping increment of
;;; the rotation. Change ringing rotates (almost always) by pairs, so the
step increment between rotations is generally 2 . The start index is
( almost always ) the mod 2 cycle . The basic changes for even bell hunting
is therefore a cycle of two changes : ( items ( 0 2 ) ( 1 2 ) ) . This pattern
;;; is called the Plain Hunt. Plain Hunting causes a set of n elements to
repeat after 2n changes , or n times through our cycle . Here is Plain Hunt
Minumus ( 4 elements A B C D ) ; X marks the rotations .
;;;
Plain
;;; A B C D
;;; X X
;;; B A D C
;;; X
;;; B D A C
;;; X X
;;; D B C A
;;; X
;;; D C B A
;;; X X
;;; C D A B
;;; X
;;; C A D B
;;; X X
;;; A C B D
;;; X
;;; A B C D
;;;
;;; utility function to return pattern results.
(defun peals (p)
return periods of one full cyle and changes .
(let* ((a (next p t))
(r (list a))
(i 1))
(loop for l = (next p t)
until (equal l a)
do
(nconc r (list l))
(incf i))
(values r i)))
;;;
Plain Hunt changes : start = cycle(0,1 ) and step=2 .
;;; For n elements, this process brings a pattern back to its original
;;; form after 2*n changes, which we look at as n repetitions of
;;; cycle(0,1)
;;;
(defun plain-hunt () (new cycle of '((0 2) (1 2))))
;(peals (new rotation of '(a b c d) rotations (plain-hunt)))
;;;
Plain Bob builds on the Plain Hunt and is n-1 repetions of cycle(0,1 )
followed by a " dodge " on the nth : ) , causes the rotation
to start at the 2nd index instead of the first , this stops the return
of the pattern , which finally repeats after 2n*(n-1 ) changes .
;;;
(defun dodge (start &optional (step 2))
returns a " dodged " cycle , ie instead of 0,1 its 0,x
(new cycle of `((0 2) (,start ,step))))
(defun plain-bob (n)
(new cycle
of (list (new cycle of (plain-hunt) for (1- n))
(dodge 2))))
;(peals (new rotation of '(a b c d) rotations (plain-bob 4)))
;;;
Call builds on Plain Bob . It 's n-2 repitions of Plain Bob
followed by a plain bob whose dodge is different : ) . The
total number of changes become 3*(2n*(n-1 ) ) . So for 6 bells
( Call ) , the pattern repeats after 3 * 60 or 180 changes .
;;;
(defun call-bob (n)
(new cycle
of
(list (new cycle of (plain-bob n) for (- n 2))
(new cycle of (list (new cycle of (plain-hunt) for (1- n))
(dodge 1 3))))))
;(peals (new rotation of '(a b c d e f) rotations (call-bob 6)))
;;;
Call Single builds on Call , but the very last dodge of 1,3 is
replaced by a rotation of just the last two elements , which causes
the process to double ( 360 changes for 6 bells ) .
;;;
(defun call-single (n)
(new cycle of
(list
(new cycle of (call-bob n) for 2)
(new cycle
of
(list
(new cycle of (plain-bob n) for (- n 2))
the third call - bob is the single
(new cycle of (list (new cycle of (plain-hunt) for (1- n))
(dodge (- n 2)))))))))
( peals ( new rotation of ' ( a b c d e f ) rotations ( call - single 6 ) ) )
;;;
;;; Grandsire rotates an odd number of Bells
;;;
(defun grandsire (n)
(new cycle of
(list
'(0 3)
(new cycle of (new cycle of '((1 2) (0 2))) for (1- n))
'(1 2))))
(peals (new rotation of '(a b c d) rotations (plain-hunt)))
(peals (new rotation of '(a b c d e) rotations (grandsire 5)))
(defprocess chrds (n p r d k a z)
(process with j
repeat n
do
(setf j k)
(loop for i in (next p t)
unless (eql i 0)
do
(output
(new midi time (now)
duration d amplitude a
keynum j))
(incf j i))
(setf k (+ k z))
(wait r)))
; (events
; (list
( chrds 60 ( new rotation of ' ( 0 3 4 7 8 11 ) rotations ( plain - bob 6 ) )
; .5 .5 48 .3 0)
(chrds 60 (new rotation of '(0 3 4 7 8 11) rotations (plain-bob 6))
.7 2 20 .3 1)
; )
"midi.port"
; "brad2.midi"
; )
; (events
; (list
( chrds 60 ( new rotation of ' ( 0 3 4 7 8 11 ) rotations ( plain - bob 6 ) )
.7 2 80 .3 -1 )
( chrds 60 ( new rotation of ' ( 0 3 4 7 8 11 ) rotations ( plain - bob 6 ) )
.7 2 20 .3 1 )
; )
; "brad3.midi")
(defprocess dograndshire (r n tr am)
(let ((pat (new rotation of '(cs4 ds fs gs as g a d)
rotations (grandsire 5) parser #'note)))
(process repeat n
for k = (next pat)
do
(output
(new midi keynum (transpose k tr)
time (now)
amplitude am
duration (* r 1.5)))
(wait r))))
(defparameter csound-seq (new seq :name "csound-test"))
(events (list (dograndshire (rhythm 's 100) 100 12 .4)
(dograndshire (rhythm 'e 100) 50 -12 .5)
(dograndshire (rhythm 'qq 100) 32 -36 .7)
)
csound-seq)
(list-objects csound-seq)
(defparameter *piano-part*
(new fomus:part
:name "Bells"
:partid 0
:instr '(:piano :staves 2)
)
)
(defparameter partids (make-hash-table))
(setf (gethash 0 partids) 0)
(defparameter voices (make-hash-table))
(defparameter voicelist '(1 2 3))
(setf (gethash 0 voices) voicelist)
( seq - to - lilypond csound - seq " cring-cm.ly " * piano - part * partids voices : title " Change Ringing " : composer " ? " )
(render-with-csd csound-seq csd-text :channel-offset 14 :velocity-scale 100 :csd-filename "cring-cm.csd" :output "test.wav")
(quit)
| null | https://raw.githubusercontent.com/gogins/csound-extended-nudruz/4551d54890f4adbadc5db8f46cc24af8e92fb9e9/examples/cring-cm.lisp | lisp | **********************************************************************
$Name$
$Revision$
Examples of "change ringing". I was made aware of this compositional
The algorithms all involve rotating diferent pairs of bells in the peal,
but "...the composer's job is to be sure that he has selected as far as
We implement change ringing by passsing the appropriate changes to the
change value numbers, ie. the start index and the stepping increment of
the rotation. Change ringing rotates (almost always) by pairs, so the
is called the Plain Hunt. Plain Hunting causes a set of n elements to
X marks the rotations .
A B C D
X X
B A D C
X
B D A C
X X
D B C A
X
D C B A
X X
C D A B
X
C A D B
X X
A C B D
X
A B C D
utility function to return pattern results.
For n elements, this process brings a pattern back to its original
form after 2*n changes, which we look at as n repetitions of
cycle(0,1)
(peals (new rotation of '(a b c d) rotations (plain-hunt)))
(peals (new rotation of '(a b c d) rotations (plain-bob 4)))
(peals (new rotation of '(a b c d e f) rotations (call-bob 6)))
Grandsire rotates an odd number of Bells
(events
(list
.5 .5 48 .3 0)
)
"brad2.midi"
)
(events
(list
)
"brad3.midi") | $ Date$
(require :asdf)
(require :fomus)
(require :nudruz)
(load "example-csd.lisp")
(in-package :cm)
technique by . Change ringing is an algorithmic procedure
for church bell ringing invented by those clever British , who also gave
these algorithms great names like Plain , Grandsire Doubles etc .
possible the most musical sequences from the many thousands available . "
rotation pattern . These rotation changes affect just the first two
step increment between rotations is generally 2 . The start index is
( almost always ) the mod 2 cycle . The basic changes for even bell hunting
is therefore a cycle of two changes : ( items ( 0 2 ) ( 1 2 ) ) . This pattern
repeat after 2n changes , or n times through our cycle . Here is Plain Hunt
Plain
(defun peals (p)
return periods of one full cyle and changes .
(let* ((a (next p t))
(r (list a))
(i 1))
(loop for l = (next p t)
until (equal l a)
do
(nconc r (list l))
(incf i))
(values r i)))
Plain Hunt changes : start = cycle(0,1 ) and step=2 .
(defun plain-hunt () (new cycle of '((0 2) (1 2))))
Plain Bob builds on the Plain Hunt and is n-1 repetions of cycle(0,1 )
followed by a " dodge " on the nth : ) , causes the rotation
to start at the 2nd index instead of the first , this stops the return
of the pattern , which finally repeats after 2n*(n-1 ) changes .
(defun dodge (start &optional (step 2))
returns a " dodged " cycle , ie instead of 0,1 its 0,x
(new cycle of `((0 2) (,start ,step))))
(defun plain-bob (n)
(new cycle
of (list (new cycle of (plain-hunt) for (1- n))
(dodge 2))))
Call builds on Plain Bob . It 's n-2 repitions of Plain Bob
followed by a plain bob whose dodge is different : ) . The
total number of changes become 3*(2n*(n-1 ) ) . So for 6 bells
( Call ) , the pattern repeats after 3 * 60 or 180 changes .
(defun call-bob (n)
(new cycle
of
(list (new cycle of (plain-bob n) for (- n 2))
(new cycle of (list (new cycle of (plain-hunt) for (1- n))
(dodge 1 3))))))
Call Single builds on Call , but the very last dodge of 1,3 is
replaced by a rotation of just the last two elements , which causes
the process to double ( 360 changes for 6 bells ) .
(defun call-single (n)
(new cycle of
(list
(new cycle of (call-bob n) for 2)
(new cycle
of
(list
(new cycle of (plain-bob n) for (- n 2))
the third call - bob is the single
(new cycle of (list (new cycle of (plain-hunt) for (1- n))
(dodge (- n 2)))))))))
( peals ( new rotation of ' ( a b c d e f ) rotations ( call - single 6 ) ) )
(defun grandsire (n)
(new cycle of
(list
'(0 3)
(new cycle of (new cycle of '((1 2) (0 2))) for (1- n))
'(1 2))))
(peals (new rotation of '(a b c d) rotations (plain-hunt)))
(peals (new rotation of '(a b c d e) rotations (grandsire 5)))
(defprocess chrds (n p r d k a z)
(process with j
repeat n
do
(setf j k)
(loop for i in (next p t)
unless (eql i 0)
do
(output
(new midi time (now)
duration d amplitude a
keynum j))
(incf j i))
(setf k (+ k z))
(wait r)))
( chrds 60 ( new rotation of ' ( 0 3 4 7 8 11 ) rotations ( plain - bob 6 ) )
(chrds 60 (new rotation of '(0 3 4 7 8 11) rotations (plain-bob 6))
.7 2 20 .3 1)
"midi.port"
( chrds 60 ( new rotation of ' ( 0 3 4 7 8 11 ) rotations ( plain - bob 6 ) )
.7 2 80 .3 -1 )
( chrds 60 ( new rotation of ' ( 0 3 4 7 8 11 ) rotations ( plain - bob 6 ) )
.7 2 20 .3 1 )
(defprocess dograndshire (r n tr am)
(let ((pat (new rotation of '(cs4 ds fs gs as g a d)
rotations (grandsire 5) parser #'note)))
(process repeat n
for k = (next pat)
do
(output
(new midi keynum (transpose k tr)
time (now)
amplitude am
duration (* r 1.5)))
(wait r))))
(defparameter csound-seq (new seq :name "csound-test"))
(events (list (dograndshire (rhythm 's 100) 100 12 .4)
(dograndshire (rhythm 'e 100) 50 -12 .5)
(dograndshire (rhythm 'qq 100) 32 -36 .7)
)
csound-seq)
(list-objects csound-seq)
(defparameter *piano-part*
(new fomus:part
:name "Bells"
:partid 0
:instr '(:piano :staves 2)
)
)
(defparameter partids (make-hash-table))
(setf (gethash 0 partids) 0)
(defparameter voices (make-hash-table))
(defparameter voicelist '(1 2 3))
(setf (gethash 0 voices) voicelist)
( seq - to - lilypond csound - seq " cring-cm.ly " * piano - part * partids voices : title " Change Ringing " : composer " ? " )
(render-with-csd csound-seq csd-text :channel-offset 14 :velocity-scale 100 :csd-filename "cring-cm.csd" :output "test.wav")
(quit)
|
0b1517a6df10692c7f295ac9a673d5da7e383552b82a4e577a91e2ed45395919 | McCLIM/McCLIM | sheet.lisp | ;;; ---------------------------------------------------------------------------
;;; License: LGPL-2.1+ (See file 'Copyright' for details).
;;; ---------------------------------------------------------------------------
;;;
( c ) Copyright 2001 by >
( c ) Copyright 2001 by < >
( c ) Copyright 2002 by < >
( c ) Copyright 2002 by < >
( c ) Copyright 2022 by < >
;;;
;;; ---------------------------------------------------------------------------
;;;
;;; TODO:
;;;
;;; - do smth with POSTSCRIPT-GRAFT.
;;; Also missing IMO:
;;;
;;; - WITH-OUTPUT-TO-POSTSCRIPT-STREAM should offer a :PAPER-SIZE option.
;;; - NEW-PAGE should also offer to specify the page name.
;;; - device fonts are missing
;;; - font metrics are missing
;;;
;;;--GB
(in-package #:clim-postscript)
(defun write-font-to-postscript-stream (stream text-style)
(with-open-file (font-stream
(clim-postscript-font:postscript-device-font-name-font-file
(clim-internals::device-font-name text-style))
:direction :input
:external-format :latin-1)
(let ((font (make-string (file-length font-stream))))
(read-sequence font font-stream)
(write-string font (medium-drawable stream)))))
(defmacro with-output-to-postscript-stream
((stream-var file-stream &rest options) &body body)
`(with-output-to-drawing-stream (,stream-var :ps ,file-stream ,@options)
,@body))
(defmethod invoke-with-output-to-drawing-stream
(continuation (port (eql :ps)) file-stream &rest args
&key (device-type :a4) (orientation :portrait) &allow-other-keys)
(flet ((make-it (file-stream)
(with-port (port :ps :stream file-stream
:device-type device-type
:page-orientation orientation)
(apply #'invoke-with-output-to-drawing-stream
continuation port file-stream args))))
(typecase file-stream
((or pathname string)
(with-open-file (stream file-stream :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(make-it stream)))
(t (make-it file-stream)))))
(defmethod invoke-with-output-to-drawing-stream
(continuation (port postscript-port) (file-stream stream)
&key (device-type :a4) multi-page scale-to-fit (orientation :portrait) header-comments)
(let ((stream (make-postscript-stream port device-type
multi-page scale-to-fit
orientation header-comments))
(trim-page-to-output-size (eql device-type :eps))
translate-x translate-y)
(sheet-adopt-child (find-graft :port port) stream)
(unwind-protect
(with-slots (title for) stream
(with-output-recording-options (stream :record t :draw nil)
(with-graphics-state (stream)
we need at least one level of saving -- APD , 2002 - 02 - 11
(funcall continuation stream)
(unless trim-page-to-output-size
(new-page stream)))) ; Close final page.
(format file-stream "%!PS-Adobe-3.0~@[ EPSF-3.0~*~]~@
%%Creator: McCLIM~@
%%Title: ~A~@
%%For: ~A~@
%%LanguageLevel: 2~%"
trim-page-to-output-size title for)
(if trim-page-to-output-size
(let ((record (stream-output-history stream)))
(with-bounding-rectangle* (lx ly ux uy) record
(setf translate-x (- (floor lx))
translate-y (ceiling uy))
(format file-stream "%%BoundingBox: ~A ~A ~A ~A~%"
0 0
(+ translate-x (ceiling ux))
(- translate-y (floor ly)))))
(let ((width (graft-width (graft stream)))
(height (graft-height (graft stream)))
(paper (device-type port)))
(format file-stream "%%BoundingBox: 0 0 ~A ~A~@
%%DocumentMedia: ~A ~A ~A 0 () ()~@
%%Pages: (atend)~%"
width height paper width height)))
(format file-stream "%%DocumentNeededResources: (atend)~@
%%EndComments~%~%")
(write-postscript-dictionary file-stream)
(dolist (text-style (clim-postscript-font:device-fonts (sheet-medium stream)))
(write-font-to-postscript-stream (sheet-medium stream) text-style))
(start-page stream)
(format file-stream "~@[~A ~]~@[~A translate~%~]" translate-x translate-y)
(with-output-recording-options (stream :draw t :record nil)
(with-graphics-state (stream)
(if trim-page-to-output-size
(replay (stream-output-history stream) stream)
(let ((last-page (first (postscript-pages stream))))
(dolist (page (reverse (postscript-pages stream)))
(climi::letf (((sheet-transformation stream)
(make-postscript-transformation
(sheet-native-region (graft stream))
page
scale-to-fit)))
(replay page stream))
(unless (eql page last-page)
(emit-new-page stream))))))))
(with-slots (current-page document-fonts) stream
(format file-stream "end~%showpage~%~@
%%Trailer~@
%%Pages: ~D~@
%%DocumentNeededResources: ~{font ~A~%~^%%+ ~}~@
%%EOF~%"
current-page (reverse document-fonts))
(finish-output file-stream)))))
(defun start-page (stream)
(with-slots (current-page transformation) stream
(let ((file-stream (sheet-mirror stream)))
(format file-stream "%%Page: ~D ~:*~D~%" (incf current-page))
(format file-stream "~A begin~%" *dictionary-name*))))
(defmethod new-page ((stream postscript-stream))
(push (stream-output-history stream) (postscript-pages stream))
(let ((history (make-instance 'standard-tree-output-history :stream stream)))
(setf (slot-value stream 'climi::output-history) history
(stream-current-output-record stream) history))
(setf (stream-cursor-position stream)
(stream-cursor-initial-position stream)))
(defun emit-new-page (stream)
FIXME : it is necessary to do smth with GS -- APD , 2002 - 02 - 11
FIXME^2 : what do you mean by that ? -- TPD , 2005 - 12 - 23
(postscript-restore-graphics-state stream)
(format (sheet-mirror stream) "end~%showpage~%")
(start-page stream)
(postscript-save-graphics-state stream))
;;; Output Protocol
(defmethod make-medium ((port postscript-port) (sheet postscript-stream))
(make-instance 'postscript-medium :port port :sheet sheet))
(defmethod medium-miter-limit ((medium postscript-medium))
#.(* pi (/ 11 180))) ; ?
;;; Some strange functions
(defmethod pane-viewport ((pane postscript-stream))
nil)
(defmethod scroll-extent ((pane postscript-stream) x y)
(declare (ignore x y))
(values))
;;; POSTSCRIPT-GRAFT
(defclass postscript-graft (graft)
())
(defmethod initialize-instance :after ((graft postscript-graft) &key)
(setf (slot-value graft 'native-transformation) nil)
(setf (slot-value graft 'native-region) nil))
(defun graft-length (length units)
(* length (ecase units
(:device 1)
(:inches (/ 72))
(:millimeters (/ 254 720))
(:screen-sized (/ length)))))
(defmethod graft-width ((graft postscript-graft) &key (units :device))
(unless (eql (sheet-native-region graft) +everywhere+)
(graft-length (bounding-rectangle-width (sheet-native-region graft)) units)))
(defmethod graft-height ((graft postscript-graft) &key (units :device))
(unless (eql (sheet-native-region graft) +everywhere+)
(graft-length (bounding-rectangle-height (sheet-native-region graft)) units)))
(defmethod sheet-region ((sheet postscript-graft))
(let ((units (graft-units sheet)))
(make-rectangle* 0 0
(graft-width sheet :units units)
(graft-height sheet :units units))))
(defmethod sheet-native-region ((sheet postscript-graft))
(with-slots (native-region) sheet
(unless native-region
(setf native-region
(paper-region (device-type (port sheet))
(page-orientation (port sheet)))))
native-region))
This is necessary because did n't reset the
native - transformation for basic - sheet . -- admich 2020 - 01 - 30
(defmethod invalidate-cached-transformations ((sheet postscript-graft))
(with-slots (native-transformation device-transformation) sheet
(setf native-transformation nil
device-transformation nil))
(loop for child in (sheet-children sheet)
do (invalidate-cached-transformations child)))
(defun graft-units-transformation (graft)
(ecase (graft-units graft)
(:device +identity-transformation+)
(:inches (make-scaling-transformation* 72 72))
(:millimeters (make-scaling-transformation* (/ 720 254) (/ 720 254)))
(:screen-sized (make-scaling-transformation* (graft-width graft) (graft-height graft)))))
(defun graft-orientation-transformation (graft)
(ecase (graft-orientation graft)
(:graphics +identity-transformation+)
(:default (if (eql (sheet-native-region graft) +everywhere+)
(make-reflection-transformation* 0 0 1 0)
(compose-transformations
(make-translation-transformation
0
(bounding-rectangle-height (sheet-native-region graft)))
(make-reflection-transformation* 0 0 1 0))))))
(defmethod sheet-native-transformation ((sheet postscript-graft))
(with-slots (native-transformation) sheet
(unless native-transformation
(setf native-transformation
(compose-transformations
(graft-orientation-transformation sheet)
(graft-units-transformation sheet))))
native-transformation))
;;; Port
(defmethod find-port-type ((type (eql :ps)))
(values 'postscript-port 'identity))
| null | https://raw.githubusercontent.com/McCLIM/McCLIM/670a37df04d9b9c9f092d024130149ac48c8fd81/Backends/PostScript/sheet.lisp | lisp | ---------------------------------------------------------------------------
License: LGPL-2.1+ (See file 'Copyright' for details).
---------------------------------------------------------------------------
---------------------------------------------------------------------------
TODO:
- do smth with POSTSCRIPT-GRAFT.
Also missing IMO:
- WITH-OUTPUT-TO-POSTSCRIPT-STREAM should offer a :PAPER-SIZE option.
- NEW-PAGE should also offer to specify the page name.
- device fonts are missing
- font metrics are missing
--GB
Close final page.
Output Protocol
?
Some strange functions
POSTSCRIPT-GRAFT
Port | ( c ) Copyright 2001 by >
( c ) Copyright 2001 by < >
( c ) Copyright 2002 by < >
( c ) Copyright 2002 by < >
( c ) Copyright 2022 by < >
(in-package #:clim-postscript)
(defun write-font-to-postscript-stream (stream text-style)
(with-open-file (font-stream
(clim-postscript-font:postscript-device-font-name-font-file
(clim-internals::device-font-name text-style))
:direction :input
:external-format :latin-1)
(let ((font (make-string (file-length font-stream))))
(read-sequence font font-stream)
(write-string font (medium-drawable stream)))))
(defmacro with-output-to-postscript-stream
((stream-var file-stream &rest options) &body body)
`(with-output-to-drawing-stream (,stream-var :ps ,file-stream ,@options)
,@body))
(defmethod invoke-with-output-to-drawing-stream
(continuation (port (eql :ps)) file-stream &rest args
&key (device-type :a4) (orientation :portrait) &allow-other-keys)
(flet ((make-it (file-stream)
(with-port (port :ps :stream file-stream
:device-type device-type
:page-orientation orientation)
(apply #'invoke-with-output-to-drawing-stream
continuation port file-stream args))))
(typecase file-stream
((or pathname string)
(with-open-file (stream file-stream :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(make-it stream)))
(t (make-it file-stream)))))
(defmethod invoke-with-output-to-drawing-stream
(continuation (port postscript-port) (file-stream stream)
&key (device-type :a4) multi-page scale-to-fit (orientation :portrait) header-comments)
(let ((stream (make-postscript-stream port device-type
multi-page scale-to-fit
orientation header-comments))
(trim-page-to-output-size (eql device-type :eps))
translate-x translate-y)
(sheet-adopt-child (find-graft :port port) stream)
(unwind-protect
(with-slots (title for) stream
(with-output-recording-options (stream :record t :draw nil)
(with-graphics-state (stream)
we need at least one level of saving -- APD , 2002 - 02 - 11
(funcall continuation stream)
(unless trim-page-to-output-size
(format file-stream "%!PS-Adobe-3.0~@[ EPSF-3.0~*~]~@
%%Creator: McCLIM~@
%%Title: ~A~@
%%For: ~A~@
%%LanguageLevel: 2~%"
trim-page-to-output-size title for)
(if trim-page-to-output-size
(let ((record (stream-output-history stream)))
(with-bounding-rectangle* (lx ly ux uy) record
(setf translate-x (- (floor lx))
translate-y (ceiling uy))
(format file-stream "%%BoundingBox: ~A ~A ~A ~A~%"
0 0
(+ translate-x (ceiling ux))
(- translate-y (floor ly)))))
(let ((width (graft-width (graft stream)))
(height (graft-height (graft stream)))
(paper (device-type port)))
(format file-stream "%%BoundingBox: 0 0 ~A ~A~@
%%DocumentMedia: ~A ~A ~A 0 () ()~@
%%Pages: (atend)~%"
width height paper width height)))
(format file-stream "%%DocumentNeededResources: (atend)~@
%%EndComments~%~%")
(write-postscript-dictionary file-stream)
(dolist (text-style (clim-postscript-font:device-fonts (sheet-medium stream)))
(write-font-to-postscript-stream (sheet-medium stream) text-style))
(start-page stream)
(format file-stream "~@[~A ~]~@[~A translate~%~]" translate-x translate-y)
(with-output-recording-options (stream :draw t :record nil)
(with-graphics-state (stream)
(if trim-page-to-output-size
(replay (stream-output-history stream) stream)
(let ((last-page (first (postscript-pages stream))))
(dolist (page (reverse (postscript-pages stream)))
(climi::letf (((sheet-transformation stream)
(make-postscript-transformation
(sheet-native-region (graft stream))
page
scale-to-fit)))
(replay page stream))
(unless (eql page last-page)
(emit-new-page stream))))))))
(with-slots (current-page document-fonts) stream
(format file-stream "end~%showpage~%~@
%%Trailer~@
%%Pages: ~D~@
%%DocumentNeededResources: ~{font ~A~%~^%%+ ~}~@
%%EOF~%"
current-page (reverse document-fonts))
(finish-output file-stream)))))
(defun start-page (stream)
(with-slots (current-page transformation) stream
(let ((file-stream (sheet-mirror stream)))
(format file-stream "%%Page: ~D ~:*~D~%" (incf current-page))
(format file-stream "~A begin~%" *dictionary-name*))))
(defmethod new-page ((stream postscript-stream))
(push (stream-output-history stream) (postscript-pages stream))
(let ((history (make-instance 'standard-tree-output-history :stream stream)))
(setf (slot-value stream 'climi::output-history) history
(stream-current-output-record stream) history))
(setf (stream-cursor-position stream)
(stream-cursor-initial-position stream)))
(defun emit-new-page (stream)
FIXME : it is necessary to do smth with GS -- APD , 2002 - 02 - 11
FIXME^2 : what do you mean by that ? -- TPD , 2005 - 12 - 23
(postscript-restore-graphics-state stream)
(format (sheet-mirror stream) "end~%showpage~%")
(start-page stream)
(postscript-save-graphics-state stream))
(defmethod make-medium ((port postscript-port) (sheet postscript-stream))
(make-instance 'postscript-medium :port port :sheet sheet))
(defmethod medium-miter-limit ((medium postscript-medium))
(defmethod pane-viewport ((pane postscript-stream))
nil)
(defmethod scroll-extent ((pane postscript-stream) x y)
(declare (ignore x y))
(values))
(defclass postscript-graft (graft)
())
(defmethod initialize-instance :after ((graft postscript-graft) &key)
(setf (slot-value graft 'native-transformation) nil)
(setf (slot-value graft 'native-region) nil))
(defun graft-length (length units)
(* length (ecase units
(:device 1)
(:inches (/ 72))
(:millimeters (/ 254 720))
(:screen-sized (/ length)))))
(defmethod graft-width ((graft postscript-graft) &key (units :device))
(unless (eql (sheet-native-region graft) +everywhere+)
(graft-length (bounding-rectangle-width (sheet-native-region graft)) units)))
(defmethod graft-height ((graft postscript-graft) &key (units :device))
(unless (eql (sheet-native-region graft) +everywhere+)
(graft-length (bounding-rectangle-height (sheet-native-region graft)) units)))
(defmethod sheet-region ((sheet postscript-graft))
(let ((units (graft-units sheet)))
(make-rectangle* 0 0
(graft-width sheet :units units)
(graft-height sheet :units units))))
(defmethod sheet-native-region ((sheet postscript-graft))
(with-slots (native-region) sheet
(unless native-region
(setf native-region
(paper-region (device-type (port sheet))
(page-orientation (port sheet)))))
native-region))
This is necessary because did n't reset the
native - transformation for basic - sheet . -- admich 2020 - 01 - 30
(defmethod invalidate-cached-transformations ((sheet postscript-graft))
(with-slots (native-transformation device-transformation) sheet
(setf native-transformation nil
device-transformation nil))
(loop for child in (sheet-children sheet)
do (invalidate-cached-transformations child)))
(defun graft-units-transformation (graft)
(ecase (graft-units graft)
(:device +identity-transformation+)
(:inches (make-scaling-transformation* 72 72))
(:millimeters (make-scaling-transformation* (/ 720 254) (/ 720 254)))
(:screen-sized (make-scaling-transformation* (graft-width graft) (graft-height graft)))))
(defun graft-orientation-transformation (graft)
(ecase (graft-orientation graft)
(:graphics +identity-transformation+)
(:default (if (eql (sheet-native-region graft) +everywhere+)
(make-reflection-transformation* 0 0 1 0)
(compose-transformations
(make-translation-transformation
0
(bounding-rectangle-height (sheet-native-region graft)))
(make-reflection-transformation* 0 0 1 0))))))
(defmethod sheet-native-transformation ((sheet postscript-graft))
(with-slots (native-transformation) sheet
(unless native-transformation
(setf native-transformation
(compose-transformations
(graft-orientation-transformation sheet)
(graft-units-transformation sheet))))
native-transformation))
(defmethod find-port-type ((type (eql :ps)))
(values 'postscript-port 'identity))
|
de2813b1842af7ac4d3abbde67d3ef5d58dcd0f604fd848e2fdeecbd5e4af091 | robert-strandh/SICL | establish-call-sites.lisp | (cl:in-package #:sicl-boot-compile-and-tie)
(defgeneric instruction (call-site))
(defclass call-site (sicl-compiler:call-site)
((%instruction :initarg :instruction :reader instruction)))
(defun call-site-name (instruction)
(typecase instruction
(cleavir-ir:named-call-instruction
(cleavir-ir:callee-name instruction))
(cleavir-ir:enclose-instruction
'sicl-run-time:enclose)
(cleavir-ir:catch-instruction
'sicl-run-time:augment-with-block/tagbody-entry)
(cleavir-ir:dynamic-catch-instruction
'sicl-run-time:augment-with-catch-entry)
(cleavir-ir:bind-instruction
'sicl-run-time:augment-with-special-variable-entry)
(cleavir-ir:unwind-protect-instruction
'sicl-run-time:augment-with-unwind-protect-entry)
(cleavir-ir:unwind-instruction
'sicl-run-time:unwind)
(cleavir-ir:initialize-values-instruction
;; FIXME: Use a better function.
'error)
(cleavir-ir:multiple-value-call-instruction
'sicl-run-time:call-with-values)
(cleavir-ir:save-values-instruction
'sicl-run-time:save-values)
(cleavir-ir:restore-values-instruction
'sicl-run-time:restore-values)
(sicl-ir:patch-literal-instruction
'sicl-run-time:resolve-load-time-value)))
(defun establish-call-site (instruction)
(change-class instruction
'sicl-ir:named-call-instruction
:function-cell-cell (list nil))
(make-instance 'call-site
:name (call-site-name instruction)
:instruction instruction))
(defun establish-call-sites (client environment ir)
(declare (ignore client environment))
(let ((call-sites '()))
(cleavir-ir:map-instructions-arbitrary-order
(lambda (instruction)
(when (typep instruction 'cleavir-ir:named-call-instruction)
(push (establish-call-site instruction)
call-sites)))
ir)
call-sites))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/7b0d08345d358ee574f4a5cd88ecf188e6ec5112/Code/Boot/Compiler/establish-call-sites.lisp | lisp | FIXME: Use a better function. | (cl:in-package #:sicl-boot-compile-and-tie)
(defgeneric instruction (call-site))
(defclass call-site (sicl-compiler:call-site)
((%instruction :initarg :instruction :reader instruction)))
(defun call-site-name (instruction)
(typecase instruction
(cleavir-ir:named-call-instruction
(cleavir-ir:callee-name instruction))
(cleavir-ir:enclose-instruction
'sicl-run-time:enclose)
(cleavir-ir:catch-instruction
'sicl-run-time:augment-with-block/tagbody-entry)
(cleavir-ir:dynamic-catch-instruction
'sicl-run-time:augment-with-catch-entry)
(cleavir-ir:bind-instruction
'sicl-run-time:augment-with-special-variable-entry)
(cleavir-ir:unwind-protect-instruction
'sicl-run-time:augment-with-unwind-protect-entry)
(cleavir-ir:unwind-instruction
'sicl-run-time:unwind)
(cleavir-ir:initialize-values-instruction
'error)
(cleavir-ir:multiple-value-call-instruction
'sicl-run-time:call-with-values)
(cleavir-ir:save-values-instruction
'sicl-run-time:save-values)
(cleavir-ir:restore-values-instruction
'sicl-run-time:restore-values)
(sicl-ir:patch-literal-instruction
'sicl-run-time:resolve-load-time-value)))
(defun establish-call-site (instruction)
(change-class instruction
'sicl-ir:named-call-instruction
:function-cell-cell (list nil))
(make-instance 'call-site
:name (call-site-name instruction)
:instruction instruction))
(defun establish-call-sites (client environment ir)
(declare (ignore client environment))
(let ((call-sites '()))
(cleavir-ir:map-instructions-arbitrary-order
(lambda (instruction)
(when (typep instruction 'cleavir-ir:named-call-instruction)
(push (establish-call-site instruction)
call-sites)))
ir)
call-sites))
|
fa3dccad58d65e769f792784dfeb462e53a2f136512dc2b5ac08a2a40660a79e | DerekCuevas/interview-cake-clj | core.clj | (ns inflight-entertainment.core
(:gen-class))
(defn can-two-movies-fill-flight?
"O(n) time solution - using a set."
[movie-lengths flight-length]
(true? (reduce
(fn [seen-lengths movie-length]
(if (contains? seen-lengths (- flight-length movie-length))
(reduced true)
(conj seen-lengths movie-length)))
#{}
movie-lengths)))
| null | https://raw.githubusercontent.com/DerekCuevas/interview-cake-clj/f17d3239bb30bcc17ced473f055a9859f9d1fb8d/inflight-entertainment/src/inflight_entertainment/core.clj | clojure | (ns inflight-entertainment.core
(:gen-class))
(defn can-two-movies-fill-flight?
"O(n) time solution - using a set."
[movie-lengths flight-length]
(true? (reduce
(fn [seen-lengths movie-length]
(if (contains? seen-lengths (- flight-length movie-length))
(reduced true)
(conj seen-lengths movie-length)))
#{}
movie-lengths)))
|
|
1656e1baa788fc09a950665836ba98c5f439da82320ab9d144c4d4d178bd02b6 | bjorng/wings | auv_matrix.erl | %%
auv_matrix.erl --
%%
%% Provides matrix ops for sparsely populated matrixes.
%%
Copyright ( c ) 2001 - 2002 ,
2004 - 2011
%%
%% See the file "license.terms" for information on usage and redistribution
%% of this file, and for a DISCLAIMER OF ALL WARRANTIES.
%%
%% $Id$
%%
-module(auv_matrix).
-export([dim/1]).
-export([vector/1, vector/2]).
-export([rows/2, cols/1, cols/2]).
-export([cat_cols/2, cat_rows/2]).
-export([diag/1, row_norm/1]).
-export([trans/1, mult/2, mult_trans/2]).
-export([add/2, sub/2]).
-export([reduce/1, backsubst/1]).
-ifdef(DEBUG).
-export([float_perf/2]).
-endif.
-define(TAG, ?MODULE).
-compile(inline).
-compile({inline_size, 100}).
-import(lists, [reverse/1]).
%% Exported
%%
dim({?TAG,N,M,_}) ->
{N,M};
dim({?TAG,N,_}) ->
{N,1};
dim(V) when is_number(V) ->
{1,1};
dim(A) ->
error(badarg, [A]).
%% Exported
%%
vector({?TAG,_N,A}) ->
lists:reverse(vector_to_list_r(A, []));
vector(V) when is_number(V) ->
[V];
vector(L) when is_list(L) ->
case vector_from_list(0, L, []) of
{[], 0} ->
error(badarg, [L]);
{A, N} when is_list(A) ->
fix({?TAG,N,A});
Fault ->
error(Fault, [L])
end;
vector(L) ->
error(badarg, [L]).
vector_to_list_r([], C) -> C;
vector_to_list_r([V | A], C) when is_float(V) ->
vector_to_list_r(A, [V | C]);
vector_to_list_r([1 | A], C) ->
vector_to_list_r(A, [0.0 | C]);
vector_to_list_r([Z | A], C) ->
vector_to_list_r([Z-1 | A], [0.0 | C]).
vector_from_list(N, [], C) ->
{lists:reverse(C), N};
vector_from_list(N, [V | L], C) when is_number(V) ->
F = float(V),
vector_from_list(N+1, L, push_v(F, C));
vector_from_list(_, _, _) ->
badarg.
%% Exported
%%
vector(N, D) when is_integer(N), is_list(D), 1 =< N ->
case vector_from_tuplist(1, N, lists:sort(D), []) of
L when is_list(L) ->
fix({?TAG,N,L});
Fault ->
error(Fault, [N, D])
end;
vector(N, D) ->
error(badarg, [N, D]).
vector_from_tuplist(I, N, [], C) when I =< N ->
vector_from_tuplist(N+1, N, [], push_v(N+1-I, C));
vector_from_tuplist(_, _, [], C) ->
lists:reverse(C);
vector_from_tuplist(I1, N, [{I2,V} | D], C)
when is_integer(I2), is_number(V),
I1 =< I2, I2 =< N ->
F = float(V),
vector_from_tuplist(I2+1, N, D, push_v(F, push_v(I2-I1, C)));
vector_from_tuplist(_, _, _, _) ->
badarg.
%% Exported
%%
rows({?TAG,1,M,[A]}) ->
fix({?TAG,M,A});
rows({?TAG,_,M,A}) ->
rows_to_list(M, A, []);
rows({?TAG,_,_} = A) ->
vector(A);
rows(V) when is_number(V) ->
[V];
rows(A) ->
error(badarg, [A]).
rows_to_list(_, [], C) ->
lists:reverse(C);
rows_to_list(M, [Row | A], C) ->
rows_to_list(M, A, [fix({?TAG,M,Row}) | C]).
%% Exported
%%
rows(M, L) when is_integer(M), is_list(L), M >= 1 ->
case vecs(M, L) of
{A, N} when is_list(A) ->
fix({?TAG,N,M,A});
Fault ->
error(Fault, [M, L])
end;
rows(M, L) ->
error(badarg, [M, L]).
%% Exported
%%
cols({?TAG,_,_,_} = A) ->
rows(trans(A));
cols({?TAG,_,_} = A) ->
[fix(A)];
cols(V) when is_number(V) ->
[V];
cols(A) ->
error(badarg, A).
%% Exported
%%
cols(N, L)
when is_integer(N), is_list(L), N >= 1 ->
case vecs(N, L) of
{A, M} when is_list(A) ->
trans({?TAG,M,N,A});
Fault ->
error(Fault, [N, L])
end;
cols(N, L) ->
error(badarg, [N, L]).
%% Exported
%%
cat_cols({?TAG,N,_,_} = A, {?TAG,N,_,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols({?TAG,N,_,_} = A, {?TAG,N,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols({?TAG,N,_} = A, {?TAG,N,_,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols({?TAG,N,_} = A, {?TAG,N,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols(A, B) ->
error(badarg, [A, B]).
%% Exported
%%
cat_rows({?TAG,Na,M,A}, {?TAG,Nb,M,B}) ->
{?TAG,Na+Nb,M,A++B};
cat_rows({?TAG,_,_} = A, {?TAG,_,1,_} = B) ->
rows(1, rows(A)++rows(B));
cat_rows({?TAG,_,1,_} = A, {?TAG,_,_} = B) ->
rows(1, rows(A)++rows(B));
cat_rows({?TAG,_,_} = A, {?TAG,_,_} = B) ->
rows(1, rows(A)++rows(B));
cat_rows(A, B) ->
error(badarg, [A, B]).
%% Exported
%%
diag({?TAG,_,_,A}) ->
diag_rows(1, A, []);
diag({?TAG,_,[Z | _]}) when is_integer(Z) ->
[0.0];
diag({?TAG,_,[V | _]}) ->
[V];
diag(V) when is_number(V) ->
[float(V)];
diag([V]) when is_number(V) ->
float(V);
diag(L) when is_list(L) ->
N = length(L),
case diag_list(1, N, L, []) of
A when is_list(A) ->
fix({?TAG,N,N,A});
Fault ->
error(Fault, [L])
end;
diag(A) ->
error(badarg, [A]).
diag_rows(_, [], C) ->
lists:reverse(C);
diag_rows(I, [Row | A], C) ->
diag_cols(I, 1, A, Row, C).
diag_cols(I, I, A, [V | Row], C) when is_float(V) ->
diag_rows(I+1,
if Row == [] -> []; true -> A end,
[V | C]);
diag_cols(I, J, A, [V | Row], C) when is_float(V) ->
diag_cols(I, J+1, A, Row, C);
diag_cols(I, J, A, [Z | Row], C) when J+Z > I ->
diag_rows(I+1,
if Row == [] -> []; true -> A end,
[0.0 | C]);
diag_cols(I, J, A, [Z | Row], C) ->
diag_cols(I, J+Z, A, Row, C).
diag_list(N, N, [V], C) when is_number(V) ->
lists:reverse(C, [[N-1, float(V)]]);
diag_list(I, N, [V | L], C) when is_number(V), V == 0 ->
diag_list(I+1, N, L, [[N] | C]);
diag_list(1, N, [V | L], C) when is_number(V) ->
diag_list(2, N, L, [[float(V), N-1] | C]);
diag_list(I, N, [V | L], C) when is_number(V) ->
diag_list(I+1, N, L, [[I-1, float(V), N-I] | C]);
diag_list(_, _, _, _) ->
badarg.
%% Exported
%%
row_norm({?TAG,_,_,A}) ->
row_norm_int(A, []);
row_norm({?TAG,_,A}) ->
row_norm_col(A, []);
row_norm(A) ->
error(badarg, [A]).
row_norm_int([], C) ->
lists:reverse(C);
row_norm_int([Row | A], C) ->
row_norm_int(A, [vec_sq(Row, 0.0) | C]).
row_norm_col([], C) ->
lists:reverse(C);
row_norm_col([V | A], C) when is_float(V) ->
row_norm_col(A, [V*V | C]);
row_norm_col([Z | A], C) ->
row_norm_col(Z, A, C).
row_norm_col(0, A, C) ->
row_norm_col(A, C);
row_norm_col(Z, A, C) ->
row_norm_col(Z-1, A, [0.0 | C]).
%% Exported
%%
trans({?TAG,1,M,[A]}) ->
fix({?TAG,M,A});
trans({?TAG,N,M,A}) ->
fix({?TAG,M,N,trans_cols_forw(1, M, A, [])});
trans({?TAG,N,A}) ->
fix({?TAG,1,N,[A]});
trans(A) when is_number(A) ->
float(A);
trans(A) ->
error(badarg, [A]).
trans_cols_forw(J, M, _, C_r) when J == M+1 ->
lists:reverse(C_r);
trans_cols_forw(J, M, A, C_r) ->
{Col_r, A_r} = trans_mk_col_r(A),
trans_cols_rev(J+1, M, A_r, [lists:reverse(Col_r) | C_r]).
trans_cols_rev(J, M, _, C_r) when J == M+1 ->
lists:reverse(C_r);
trans_cols_rev(J, M, A_r, C_r) ->
{Col, A} = trans_mk_col_r(A_r),
trans_cols_forw(J+1, M, A, [Col | C_r]).
trans_mk_col_r(A) ->
trans_mk_col_r(A, [], []).
trans_mk_col_r([], B, C) ->
{C, B};
trans_mk_col_r([[V | Row] | A], B, C) when is_float(V) ->
trans_mk_col_r(A, [Row | B], [V | C]);
trans_mk_col_r([Row | A], B, C) ->
trans_mk_col_r(A, [pop_z(Row) | B], push_v(1, C)).
%% Exported
%%
mult({?TAG,K,_M} = A, {?TAG,1,K,[B]}) ->
mult_trans(A, {?TAG,K,B});
mult({?TAG,_,K,_} = A, {?TAG,K,_,_} = B) ->
mult_trans(A, trans(B));
mult({?TAG,1,M,[A]}, {?TAG,M,B}) ->
vec_mult(A, B);
mult({?TAG,N,M,A}, {?TAG,M,B}) ->
Waste of time to call here .
{?TAG,N,mult_vec(B, A)};
mult(A, B) when is_number(A), A == 1 ->
fix(B);
mult(A, {?TAG,N,1,[B]}) when is_number(A) ->
{?TAG,N,1,[vec_mult_const(float(A), B, [])]};
mult(A, {?TAG,N,M,B}) when is_number(A) ->
{?TAG,N,M,mult_const(float(A), B, [])};
mult(A, {?TAG,N,B}) when is_number(A) ->
Waste of time to call here .
{?TAG,N,vec_mult_const(float(A), B, [])};
mult(A, B) when is_number(B), B == 1 ->
fix(A);
mult({?TAG,N,1,[A]}, B) when is_number(B) ->
{?TAG,N,1,[vec_mult_const(float(B), A, [])]};
mult({?TAG,N,M,A}, B) when is_number(B) ->
{?TAG,N,M,mult_const(float(B), A, [])};
mult({?TAG,N,A}, B) when is_number(B) ->
{?TAG,N,vec_mult_const(float(B), A, [])};
mult(A, B) when is_number(A), is_number(B) ->
float(A*B);
mult(A, B) ->
error(badarg, [A, B]).
mult_vec(VecA, B) ->
mult_vec_1(list_to_tuple(reverse(vector_to_list_r(VecA, []))), B, 0.0, []).
mult_vec_1(_, [], _, C) -> reverse(C);
mult_vec_1(VecA, [VecB | B], Z, C) ->
mult_vec_1(VecA, B, Z, [vec_mult_tuple(VecA, 1, VecB, Z) | C]).
%% Exported
%%
mult_trans({?TAG,1,M,[A]}, {?TAG,1,M,[B]}) ->
vec_mult(A, B);
mult_trans({?TAG,_N,M,_} = A, {?TAG,1,M,_} = B) ->
mult(A, trans(B));
mult_trans({?TAG,Na,M,A}, {?TAG,Nb,M,B}) ->
fix({?TAG,Na,Nb,mult_row(A, B, [])});
%%
mult_trans(A, {?TAG,N,B}) ->
mult(A, {?TAG,1,N,[B]});
mult_trans({?TAG,N,A}, B) ->
mult_trans(trans({?TAG,1,N,[A]}), B);
%%
mult_trans(A, B) when is_number(A), is_number(B) ->
float(A * B);
mult_trans(A, B) when is_number(B) ->
mult(A, B);
mult_trans(A, B) when is_number(A) ->
trans(mult(A, B));
mult_trans(A, B) ->
error(badarg, [A, B]).
mult_row([], _, C) ->
lists:reverse(C);
mult_row([RowA | A], B, C) ->
mult_row(A, B, [mult_vec(RowA, B) | C]).
mult_const(_, [], C) ->
lists:reverse(C);
mult_const(F, [Row | A], C) ->
mult_const(F, A, [vec_mult_const(F, Row, []) | C]).
%% Exported
%%
add({?TAG,N,M,A}, {?TAG,N,M,B}) ->
fix({?TAG,N,M,add_row(A, B, [])});
add({?TAG,N,A}, {?TAG,N,B}) ->
fix({?TAG,N,vec_add(A, B)});
add({?TAG,N,1,_} = A, {?TAG,N,B}) ->
{?TAG,1,N,[C]} = trans(A),
fix({?TAG,N,vec_add(C, B)});
add({?TAG,N,A}, {?TAG,N,1,_} = B) ->
{?TAG,1,N,[C]} = trans(B),
fix({?TAG,N,vec_add(A, C)});
add(Va, Vb) when is_number(Va), is_number(Vb) ->
float(Va + Vb);
%%
add({?TAG,1,1,_} = A, Vb) when is_number(Vb) ->
add(A, {?TAG,1,1,[push_v(Vb, [])]});
add({?TAG,1,_} = A, Vb) when is_number(Vb) ->
add(A, {?TAG,1,push_v(Vb, [])});
add(Va, B) when is_number(Va) ->
add(B, Va);
%%
add(A, B) ->
error(badarg, [A, B]).
add_row([], [], C) ->
lists:reverse(C);
add_row([RowA | A], [RowB | B], C) ->
add_row(A, B, [vec_add(RowA, RowB) | C]).
%% Exported
%%
sub(A, B) ->
add(A, mult(-1, B)).
%% Exported
%%
reduce({?TAG,N,M,A}) ->
case catch reduce_sort(A, []) of
{'EXIT',{badarith,_}} ->
illconditioned;
B ->
{?TAG,N,M,B}
end;
reduce(A) ->
error(badarg, [A]).
reduce_sort([], C) ->
reduce_row(lists:sort(C), []);
reduce_sort([Row | A], C) ->
reduce_sort(A, [reduce_presort(0, Row) | C]).
reduce_presort(Z, []) ->
{Z, infinity, []};
reduce_presort(Z, [0.0 | Row]) ->
reduce_presort(Z+1, Row);
reduce_presort(Z, [V | _] = Row) when is_float(V) ->
{Z, 1.0/abs(V), Row};
reduce_presort(Z, [Zr | Row]) ->
reduce_presort(Z+Zr, Row).
reduce_row([], C) ->
lists:reverse(C);
reduce_row([Row | A], C) ->
reduce_row(reduce_zap(Row, A, []), [reduce_postsort(Row) | C]).
reduce_postsort({0, _, Row}) ->
Row;
reduce_postsort({Z, _, Row}) ->
[Z | Row].
reduce_zap({Z, _, [V | Row]} = R, [{Z, _, [Va | RowA]} | A], C)
when is_float(V), is_float(Va) ->
reduce_zap(R, A, [reduce_presort(Z+1, vec_add(RowA, -Va/V, Row)) | C]);
reduce_zap(_, [], C) ->
lists:sort(C);
reduce_zap(_, A, C) ->
lists:merge(A, lists:sort(C)).
%% Exported
%%
backsubst({?TAG,N,M,A} = AA) when M == N+1 ->
case catch backsubst_rev(0, A, []) of
A_tri when is_list(A_tri) ->
case catch backsubst_const(A_tri, [], []) of
X when is_list(X) ->
{?TAG,N,X};
{error, Reason} ->
Reason;
{'EXIT', {badarith, []}} ->
illconditioned;
{'EXIT', Reason} ->
exit(Reason);
Fault ->
error(Fault, [AA])
end;
{error, Reason} ->
Reason;
{'EXIT', {badarith, []}} ->
illconditioned;
{'EXIT', Reason} ->
exit(Reason);
Fault ->
error(Fault, [AA])
end;
backsubst(A) ->
error(badarg, [A]).
backsubst_rev(_, [], C) ->
lists:reverse(C);
backsubst_rev(Z, [RowA | A], C) ->
backsubst_rev_z(Z, 0, RowA, A, C).
backsubst_rev_z(Z, Za, _, _, _) when Za > Z ->
{error, not_reduced};
backsubst_rev_z(_, _, [_], _, _) ->
{error, not_reduced};
backsubst_rev_z(Z, Za, [0.0 | RowA], A, C) ->
backsubst_rev_z(Z, Za+1, RowA, A, C);
backsubst_rev_z(Z, Za, [Va | _] = RowA, A, C) when is_float(Va) ->
if Z == Za ->
backsubst_rev(Z+1, A, [vector_to_list_r(RowA, []) | C]);
true ->
{error, undetermined}
end;
backsubst_rev_z(Z, Za, [Zaa | RowA], A, C) ->
backsubst_rev_z(Z, Za+Zaa, RowA, A, C).
backsubst_const([], C, B) ->
backsubst_vec_r(C, B, []);
backsubst_const([[_]], _, _) ->
{error, undetermined};
backsubst_const([[V | RowA] | A], C, B) when is_float(V) ->
backsubst_const(A, [RowA | C], [-V | B]).
backsubst_vec_r([], [], X) ->
lists:reverse(X);
backsubst_vec_r([RowA | A], [Vb | B], X) ->
backsubst_vec_x(RowA, A, B, X, X, Vb).
backsubst_vec_x([Va], A, B, [], X0, S)
when is_float(Va), is_float(S) ->
backsubst_vec_r(A, B, X0++[S/Va]);
backsubst_vec_x([Va | RowA], A, B, [Vx | X], X0, S)
when is_float(Va), is_float(Vx), is_float(S) ->
backsubst_vec_x(RowA, A, B, X, X0, S - Va*Vx).
vecs(N, L) ->
vecs(0, N, L, []).
vecs(I, _, [], C) ->
{lists:reverse(C), I};
vecs(I, N, [{?TAG,N,D} | L], C) ->
vecs(I+1, N, L, [D | C]);
vecs(I, 1, [V | L], C) when is_number(V) ->
vecs(I+1, 1, L, [push_v(float(V), []) | C]);
vecs(_, _, _, _) ->
badarg.
vec_add(A, B) ->
vec_add(0, A, 0, B, 0, []).
vec_add(A, F, B) when is_float(F) ->
vec_add(0, A, F, 0, B, 0, []).
vec_add(Za, [Va | A], Zb, B, Zc, C) when is_integer(Va) ->
vec_add(Za+Va, A, Zb, B, Zc, C);
vec_add(Za, A, Zb, [Vb | B], Zc, C) when is_integer(Vb) ->
vec_add(Za, A, Zb+Vb, B, Zc, C);
vec_add(0, [], 0, [], Zc, C) ->
if Zc == 0 ->
lists:reverse(C);
true ->
lists:reverse(C, [Zc])
end;
vec_add(0, [Va | A], 0, [Vb | B], Zc, C)
when is_float(Va), is_float(Vb) ->
Vc = Va + Vb,
vec_add(0, A, 0, B, 0, if Zc == 0 -> [Vc | C];
true -> [Vc, Zc | C]
end);
vec_add(0, [Va | A], Zb, B, Zc, C) ->
vec_add(0, A, Zb-1, B, 0, if Zc == 0 -> [Va | C];
true -> [Va, Zc | C]
end);
vec_add(Za, A, 0, [Vb | B], Zc, C)
when is_float(Vb) ->
vec_add(Za-1, A, 0, B, 0, if Zc == 0 -> [Vb | C];
true -> [Vb, Zc | C]
end);
vec_add(Za, A, Zb, B, Zc, C) ->
if Za < Zb ->
vec_add(0, A, Zb-Za, B, Zc+Za, C);
Zb < Za ->
vec_add(Za-Zb, A, 0, B, Zc+Zb, C);
true ->
vec_add(0, A, 0, B, Zc+Za, C)
end.
vec_add(Za, [Va | A], F, Zb, B, Zc, C) when is_integer(Va) ->
vec_add(Za+Va, A, F, Zb, B, Zc, C);
vec_add(Za, A, F, Zb, [Vb | B], Zc, C) when is_integer(Vb) ->
vec_add(Za, A, F, Zb+Vb, B, Zc, C);
vec_add(0, [], _, 0, [], Zc, C) ->
if Zc == 0 ->
lists:reverse(C);
true ->
lists:reverse(C, [Zc])
end;
vec_add(0, [Va | A], F, 0, [Vb | B], Zc, C)
when is_float(Va), is_float(F), is_float(Vb) ->
Vc = Va + F*Vb,
vec_add(0, A, F, 0, B, 0, if Zc == 0 -> [Vc | C];
true -> [Vc, Zc | C]
end);
vec_add(0, [Va | A], F, Zb, B, Zc, C) ->
vec_add(0, A, F, Zb-1, B, 0, if Zc == 0 -> [Va | C];
true -> [Va, Zc | C]
end);
vec_add(Za, A, F, 0, [Vb | B], Zc, C)
when is_float(F), is_float(Vb) ->
Vc = F*Vb,
vec_add(Za-1, A, F, 0, B, 0, if Zc == 0 -> [Vc | C];
true -> [Vc, Zc | C]
end);
vec_add(Za, A, F, Zb, B, Zc, C) ->
if Za < Zb ->
vec_add(0, A, F, Zb-Za, B, Zc+Za, C);
Zb < Za ->
vec_add(Za-Zb, A, F, 0, B, Zc+Zb, C);
true ->
vec_add(0, A, F, 0, B, Zc+Za, C)
end.
vec_mult_const(F, [V | B], C) when is_float(F), is_float(V) ->
vec_mult_const(F, B, [V*F | C]);
vec_mult_const(F, [Z | B], C) ->
vec_mult_const(F, B, [Z | C]);
vec_mult_const(_, [], C) ->
lists:reverse(C).
vec_mult_tuple(T, I, [Zb | B], S) when is_integer(Zb) ->
vec_mult_tuple(T, I+Zb, B, S);
vec_mult_tuple(T, I, [Vb | B], S) when is_float(Vb), is_float(S) ->
case element(I, T) of
Va when is_float(Va) ->
vec_mult_tuple(T, I+1, B, Va*Vb + S)
end;
vec_mult_tuple(_, _, [], S) -> S.
vec_mult(A, B) ->
vec_mult(A, B, 0.0).
vec_mult([Va | A], [Vb | B], S) when is_float(Va), is_float(Vb) ->
vec_mult(A, B, Va*Vb + S);
vec_mult([Za|A], [_|_]=B, S) when is_integer(Za) ->
vec_mult_pop(Za, A, B, S);
vec_mult([_|_]=A, [Zb | B], S) -> %% when is_integer(Zb)
vec_mult_pop(Zb, B, A, S);
vec_mult(_, _, S) -> S.
vec_mult_pop(_, [], _, S) -> S;
vec_mult_pop(0, A, B, S) ->
vec_mult(A, B, S);
vec_mult_pop(Za, A, [Vb | B], S) when is_float(Vb) ->
vec_mult_pop(Za-1, A, B, S);
vec_mult_pop(_, _, [_], S) -> % when is_integer(Zb)
S;
vec_mult_pop(Za, A, [Zb | B], S) when Za < Zb ->
vec_mult_pop(Zb-Za, B, A, S);
vec_mult_pop(Za, A, [Zb | B], S) when Zb < Za ->
vec_mult_pop(Za-Zb, A, B, S);
vec_mult_pop(_, A, [_ | B], S) -> % when Za == Zb
vec_mult(A, B, S);
vec_mult_pop(_, _, [], S) ->
S.
vec_sq([], S) ->
S;
vec_sq([V | A], S) when is_float(V), is_float(S) ->
vec_sq(A, S + V*V);
vec_sq([_ | A], S) ->
vec_sq(A, S).
Push value ; zeros or float
push_v(0.0, C) ->
case C of
[Z | R] when is_integer(Z) ->
[Z+1 | R];
R ->
[1 | R]
end;
push_v(V, C) when is_float(V) ->
[V | C];
push_v(0, C) ->
C;
push_v(Z1, C) when is_integer(Z1) ->
case C of
[Z2 | R] when is_integer(Z2) ->
[Z1+Z2 | R];
R ->
[Z1 | R]
end.
%% Pop zero
pop_z([]) ->
[];
pop_z([1]) ->
[];
pop_z([1 | C]) ->
C;
pop_z([Z | C]) when is_integer(Z) ->
[Z-1 | C].
%% Fix 1x1 matrixes to become scalars
%%
fix({?TAG,1,1,[[1]]}) ->
0.0;
fix({?TAG,1,1,[[V]]}) ->
V;
fix({?TAG,1,[1]}) ->
0.0;
fix({?TAG,1,[V]}) ->
V;
fix(V) when is_integer(V) ->
float(V);
fix(M) ->
M.
-ifdef(DEBUG).
float_perf(A, L) ->
float_perf(A, L, []).
float_perf(_, [], C) ->
lists:reverse(C);
float_perf(A, [B | T], C) ->
float_perf(A, T, [float_perf_int(A, B, 0.0), C]).
float_perf_int([], [], S) ->
S;
float_perf_int([Va | A], [Vb | B], S) when is_float(Va), float(Vb), float(S) ->
float_perf_int(A, B, Va*Vb + S).
-endif.
| null | https://raw.githubusercontent.com/bjorng/wings/dec64a500220359dbc552600af486be47c45d301/plugins_src/autouv/auv_matrix.erl | erlang |
Provides matrix ops for sparsely populated matrixes.
See the file "license.terms" for information on usage and redistribution
of this file, and for a DISCLAIMER OF ALL WARRANTIES.
$Id$
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
Exported
when is_integer(Zb)
when is_integer(Zb)
when Za == Zb
Pop zero
Fix 1x1 matrixes to become scalars
| auv_matrix.erl --
Copyright ( c ) 2001 - 2002 ,
2004 - 2011
-module(auv_matrix).
-export([dim/1]).
-export([vector/1, vector/2]).
-export([rows/2, cols/1, cols/2]).
-export([cat_cols/2, cat_rows/2]).
-export([diag/1, row_norm/1]).
-export([trans/1, mult/2, mult_trans/2]).
-export([add/2, sub/2]).
-export([reduce/1, backsubst/1]).
-ifdef(DEBUG).
-export([float_perf/2]).
-endif.
-define(TAG, ?MODULE).
-compile(inline).
-compile({inline_size, 100}).
-import(lists, [reverse/1]).
dim({?TAG,N,M,_}) ->
{N,M};
dim({?TAG,N,_}) ->
{N,1};
dim(V) when is_number(V) ->
{1,1};
dim(A) ->
error(badarg, [A]).
vector({?TAG,_N,A}) ->
lists:reverse(vector_to_list_r(A, []));
vector(V) when is_number(V) ->
[V];
vector(L) when is_list(L) ->
case vector_from_list(0, L, []) of
{[], 0} ->
error(badarg, [L]);
{A, N} when is_list(A) ->
fix({?TAG,N,A});
Fault ->
error(Fault, [L])
end;
vector(L) ->
error(badarg, [L]).
vector_to_list_r([], C) -> C;
vector_to_list_r([V | A], C) when is_float(V) ->
vector_to_list_r(A, [V | C]);
vector_to_list_r([1 | A], C) ->
vector_to_list_r(A, [0.0 | C]);
vector_to_list_r([Z | A], C) ->
vector_to_list_r([Z-1 | A], [0.0 | C]).
vector_from_list(N, [], C) ->
{lists:reverse(C), N};
vector_from_list(N, [V | L], C) when is_number(V) ->
F = float(V),
vector_from_list(N+1, L, push_v(F, C));
vector_from_list(_, _, _) ->
badarg.
vector(N, D) when is_integer(N), is_list(D), 1 =< N ->
case vector_from_tuplist(1, N, lists:sort(D), []) of
L when is_list(L) ->
fix({?TAG,N,L});
Fault ->
error(Fault, [N, D])
end;
vector(N, D) ->
error(badarg, [N, D]).
vector_from_tuplist(I, N, [], C) when I =< N ->
vector_from_tuplist(N+1, N, [], push_v(N+1-I, C));
vector_from_tuplist(_, _, [], C) ->
lists:reverse(C);
vector_from_tuplist(I1, N, [{I2,V} | D], C)
when is_integer(I2), is_number(V),
I1 =< I2, I2 =< N ->
F = float(V),
vector_from_tuplist(I2+1, N, D, push_v(F, push_v(I2-I1, C)));
vector_from_tuplist(_, _, _, _) ->
badarg.
rows({?TAG,1,M,[A]}) ->
fix({?TAG,M,A});
rows({?TAG,_,M,A}) ->
rows_to_list(M, A, []);
rows({?TAG,_,_} = A) ->
vector(A);
rows(V) when is_number(V) ->
[V];
rows(A) ->
error(badarg, [A]).
rows_to_list(_, [], C) ->
lists:reverse(C);
rows_to_list(M, [Row | A], C) ->
rows_to_list(M, A, [fix({?TAG,M,Row}) | C]).
rows(M, L) when is_integer(M), is_list(L), M >= 1 ->
case vecs(M, L) of
{A, N} when is_list(A) ->
fix({?TAG,N,M,A});
Fault ->
error(Fault, [M, L])
end;
rows(M, L) ->
error(badarg, [M, L]).
cols({?TAG,_,_,_} = A) ->
rows(trans(A));
cols({?TAG,_,_} = A) ->
[fix(A)];
cols(V) when is_number(V) ->
[V];
cols(A) ->
error(badarg, A).
cols(N, L)
when is_integer(N), is_list(L), N >= 1 ->
case vecs(N, L) of
{A, M} when is_list(A) ->
trans({?TAG,M,N,A});
Fault ->
error(Fault, [N, L])
end;
cols(N, L) ->
error(badarg, [N, L]).
cat_cols({?TAG,N,_,_} = A, {?TAG,N,_,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols({?TAG,N,_,_} = A, {?TAG,N,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols({?TAG,N,_} = A, {?TAG,N,_,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols({?TAG,N,_} = A, {?TAG,N,_} = B) ->
cols(N, cols(A)++cols(B));
cat_cols(A, B) ->
error(badarg, [A, B]).
cat_rows({?TAG,Na,M,A}, {?TAG,Nb,M,B}) ->
{?TAG,Na+Nb,M,A++B};
cat_rows({?TAG,_,_} = A, {?TAG,_,1,_} = B) ->
rows(1, rows(A)++rows(B));
cat_rows({?TAG,_,1,_} = A, {?TAG,_,_} = B) ->
rows(1, rows(A)++rows(B));
cat_rows({?TAG,_,_} = A, {?TAG,_,_} = B) ->
rows(1, rows(A)++rows(B));
cat_rows(A, B) ->
error(badarg, [A, B]).
diag({?TAG,_,_,A}) ->
diag_rows(1, A, []);
diag({?TAG,_,[Z | _]}) when is_integer(Z) ->
[0.0];
diag({?TAG,_,[V | _]}) ->
[V];
diag(V) when is_number(V) ->
[float(V)];
diag([V]) when is_number(V) ->
float(V);
diag(L) when is_list(L) ->
N = length(L),
case diag_list(1, N, L, []) of
A when is_list(A) ->
fix({?TAG,N,N,A});
Fault ->
error(Fault, [L])
end;
diag(A) ->
error(badarg, [A]).
diag_rows(_, [], C) ->
lists:reverse(C);
diag_rows(I, [Row | A], C) ->
diag_cols(I, 1, A, Row, C).
diag_cols(I, I, A, [V | Row], C) when is_float(V) ->
diag_rows(I+1,
if Row == [] -> []; true -> A end,
[V | C]);
diag_cols(I, J, A, [V | Row], C) when is_float(V) ->
diag_cols(I, J+1, A, Row, C);
diag_cols(I, J, A, [Z | Row], C) when J+Z > I ->
diag_rows(I+1,
if Row == [] -> []; true -> A end,
[0.0 | C]);
diag_cols(I, J, A, [Z | Row], C) ->
diag_cols(I, J+Z, A, Row, C).
diag_list(N, N, [V], C) when is_number(V) ->
lists:reverse(C, [[N-1, float(V)]]);
diag_list(I, N, [V | L], C) when is_number(V), V == 0 ->
diag_list(I+1, N, L, [[N] | C]);
diag_list(1, N, [V | L], C) when is_number(V) ->
diag_list(2, N, L, [[float(V), N-1] | C]);
diag_list(I, N, [V | L], C) when is_number(V) ->
diag_list(I+1, N, L, [[I-1, float(V), N-I] | C]);
diag_list(_, _, _, _) ->
badarg.
row_norm({?TAG,_,_,A}) ->
row_norm_int(A, []);
row_norm({?TAG,_,A}) ->
row_norm_col(A, []);
row_norm(A) ->
error(badarg, [A]).
row_norm_int([], C) ->
lists:reverse(C);
row_norm_int([Row | A], C) ->
row_norm_int(A, [vec_sq(Row, 0.0) | C]).
row_norm_col([], C) ->
lists:reverse(C);
row_norm_col([V | A], C) when is_float(V) ->
row_norm_col(A, [V*V | C]);
row_norm_col([Z | A], C) ->
row_norm_col(Z, A, C).
row_norm_col(0, A, C) ->
row_norm_col(A, C);
row_norm_col(Z, A, C) ->
row_norm_col(Z-1, A, [0.0 | C]).
trans({?TAG,1,M,[A]}) ->
fix({?TAG,M,A});
trans({?TAG,N,M,A}) ->
fix({?TAG,M,N,trans_cols_forw(1, M, A, [])});
trans({?TAG,N,A}) ->
fix({?TAG,1,N,[A]});
trans(A) when is_number(A) ->
float(A);
trans(A) ->
error(badarg, [A]).
trans_cols_forw(J, M, _, C_r) when J == M+1 ->
lists:reverse(C_r);
trans_cols_forw(J, M, A, C_r) ->
{Col_r, A_r} = trans_mk_col_r(A),
trans_cols_rev(J+1, M, A_r, [lists:reverse(Col_r) | C_r]).
trans_cols_rev(J, M, _, C_r) when J == M+1 ->
lists:reverse(C_r);
trans_cols_rev(J, M, A_r, C_r) ->
{Col, A} = trans_mk_col_r(A_r),
trans_cols_forw(J+1, M, A, [Col | C_r]).
trans_mk_col_r(A) ->
trans_mk_col_r(A, [], []).
trans_mk_col_r([], B, C) ->
{C, B};
trans_mk_col_r([[V | Row] | A], B, C) when is_float(V) ->
trans_mk_col_r(A, [Row | B], [V | C]);
trans_mk_col_r([Row | A], B, C) ->
trans_mk_col_r(A, [pop_z(Row) | B], push_v(1, C)).
mult({?TAG,K,_M} = A, {?TAG,1,K,[B]}) ->
mult_trans(A, {?TAG,K,B});
mult({?TAG,_,K,_} = A, {?TAG,K,_,_} = B) ->
mult_trans(A, trans(B));
mult({?TAG,1,M,[A]}, {?TAG,M,B}) ->
vec_mult(A, B);
mult({?TAG,N,M,A}, {?TAG,M,B}) ->
Waste of time to call here .
{?TAG,N,mult_vec(B, A)};
mult(A, B) when is_number(A), A == 1 ->
fix(B);
mult(A, {?TAG,N,1,[B]}) when is_number(A) ->
{?TAG,N,1,[vec_mult_const(float(A), B, [])]};
mult(A, {?TAG,N,M,B}) when is_number(A) ->
{?TAG,N,M,mult_const(float(A), B, [])};
mult(A, {?TAG,N,B}) when is_number(A) ->
Waste of time to call here .
{?TAG,N,vec_mult_const(float(A), B, [])};
mult(A, B) when is_number(B), B == 1 ->
fix(A);
mult({?TAG,N,1,[A]}, B) when is_number(B) ->
{?TAG,N,1,[vec_mult_const(float(B), A, [])]};
mult({?TAG,N,M,A}, B) when is_number(B) ->
{?TAG,N,M,mult_const(float(B), A, [])};
mult({?TAG,N,A}, B) when is_number(B) ->
{?TAG,N,vec_mult_const(float(B), A, [])};
mult(A, B) when is_number(A), is_number(B) ->
float(A*B);
mult(A, B) ->
error(badarg, [A, B]).
mult_vec(VecA, B) ->
mult_vec_1(list_to_tuple(reverse(vector_to_list_r(VecA, []))), B, 0.0, []).
mult_vec_1(_, [], _, C) -> reverse(C);
mult_vec_1(VecA, [VecB | B], Z, C) ->
mult_vec_1(VecA, B, Z, [vec_mult_tuple(VecA, 1, VecB, Z) | C]).
mult_trans({?TAG,1,M,[A]}, {?TAG,1,M,[B]}) ->
vec_mult(A, B);
mult_trans({?TAG,_N,M,_} = A, {?TAG,1,M,_} = B) ->
mult(A, trans(B));
mult_trans({?TAG,Na,M,A}, {?TAG,Nb,M,B}) ->
fix({?TAG,Na,Nb,mult_row(A, B, [])});
mult_trans(A, {?TAG,N,B}) ->
mult(A, {?TAG,1,N,[B]});
mult_trans({?TAG,N,A}, B) ->
mult_trans(trans({?TAG,1,N,[A]}), B);
mult_trans(A, B) when is_number(A), is_number(B) ->
float(A * B);
mult_trans(A, B) when is_number(B) ->
mult(A, B);
mult_trans(A, B) when is_number(A) ->
trans(mult(A, B));
mult_trans(A, B) ->
error(badarg, [A, B]).
mult_row([], _, C) ->
lists:reverse(C);
mult_row([RowA | A], B, C) ->
mult_row(A, B, [mult_vec(RowA, B) | C]).
mult_const(_, [], C) ->
lists:reverse(C);
mult_const(F, [Row | A], C) ->
mult_const(F, A, [vec_mult_const(F, Row, []) | C]).
add({?TAG,N,M,A}, {?TAG,N,M,B}) ->
fix({?TAG,N,M,add_row(A, B, [])});
add({?TAG,N,A}, {?TAG,N,B}) ->
fix({?TAG,N,vec_add(A, B)});
add({?TAG,N,1,_} = A, {?TAG,N,B}) ->
{?TAG,1,N,[C]} = trans(A),
fix({?TAG,N,vec_add(C, B)});
add({?TAG,N,A}, {?TAG,N,1,_} = B) ->
{?TAG,1,N,[C]} = trans(B),
fix({?TAG,N,vec_add(A, C)});
add(Va, Vb) when is_number(Va), is_number(Vb) ->
float(Va + Vb);
add({?TAG,1,1,_} = A, Vb) when is_number(Vb) ->
add(A, {?TAG,1,1,[push_v(Vb, [])]});
add({?TAG,1,_} = A, Vb) when is_number(Vb) ->
add(A, {?TAG,1,push_v(Vb, [])});
add(Va, B) when is_number(Va) ->
add(B, Va);
add(A, B) ->
error(badarg, [A, B]).
add_row([], [], C) ->
lists:reverse(C);
add_row([RowA | A], [RowB | B], C) ->
add_row(A, B, [vec_add(RowA, RowB) | C]).
sub(A, B) ->
add(A, mult(-1, B)).
reduce({?TAG,N,M,A}) ->
case catch reduce_sort(A, []) of
{'EXIT',{badarith,_}} ->
illconditioned;
B ->
{?TAG,N,M,B}
end;
reduce(A) ->
error(badarg, [A]).
reduce_sort([], C) ->
reduce_row(lists:sort(C), []);
reduce_sort([Row | A], C) ->
reduce_sort(A, [reduce_presort(0, Row) | C]).
reduce_presort(Z, []) ->
{Z, infinity, []};
reduce_presort(Z, [0.0 | Row]) ->
reduce_presort(Z+1, Row);
reduce_presort(Z, [V | _] = Row) when is_float(V) ->
{Z, 1.0/abs(V), Row};
reduce_presort(Z, [Zr | Row]) ->
reduce_presort(Z+Zr, Row).
reduce_row([], C) ->
lists:reverse(C);
reduce_row([Row | A], C) ->
reduce_row(reduce_zap(Row, A, []), [reduce_postsort(Row) | C]).
reduce_postsort({0, _, Row}) ->
Row;
reduce_postsort({Z, _, Row}) ->
[Z | Row].
reduce_zap({Z, _, [V | Row]} = R, [{Z, _, [Va | RowA]} | A], C)
when is_float(V), is_float(Va) ->
reduce_zap(R, A, [reduce_presort(Z+1, vec_add(RowA, -Va/V, Row)) | C]);
reduce_zap(_, [], C) ->
lists:sort(C);
reduce_zap(_, A, C) ->
lists:merge(A, lists:sort(C)).
backsubst({?TAG,N,M,A} = AA) when M == N+1 ->
case catch backsubst_rev(0, A, []) of
A_tri when is_list(A_tri) ->
case catch backsubst_const(A_tri, [], []) of
X when is_list(X) ->
{?TAG,N,X};
{error, Reason} ->
Reason;
{'EXIT', {badarith, []}} ->
illconditioned;
{'EXIT', Reason} ->
exit(Reason);
Fault ->
error(Fault, [AA])
end;
{error, Reason} ->
Reason;
{'EXIT', {badarith, []}} ->
illconditioned;
{'EXIT', Reason} ->
exit(Reason);
Fault ->
error(Fault, [AA])
end;
backsubst(A) ->
error(badarg, [A]).
backsubst_rev(_, [], C) ->
lists:reverse(C);
backsubst_rev(Z, [RowA | A], C) ->
backsubst_rev_z(Z, 0, RowA, A, C).
backsubst_rev_z(Z, Za, _, _, _) when Za > Z ->
{error, not_reduced};
backsubst_rev_z(_, _, [_], _, _) ->
{error, not_reduced};
backsubst_rev_z(Z, Za, [0.0 | RowA], A, C) ->
backsubst_rev_z(Z, Za+1, RowA, A, C);
backsubst_rev_z(Z, Za, [Va | _] = RowA, A, C) when is_float(Va) ->
if Z == Za ->
backsubst_rev(Z+1, A, [vector_to_list_r(RowA, []) | C]);
true ->
{error, undetermined}
end;
backsubst_rev_z(Z, Za, [Zaa | RowA], A, C) ->
backsubst_rev_z(Z, Za+Zaa, RowA, A, C).
backsubst_const([], C, B) ->
backsubst_vec_r(C, B, []);
backsubst_const([[_]], _, _) ->
{error, undetermined};
backsubst_const([[V | RowA] | A], C, B) when is_float(V) ->
backsubst_const(A, [RowA | C], [-V | B]).
backsubst_vec_r([], [], X) ->
lists:reverse(X);
backsubst_vec_r([RowA | A], [Vb | B], X) ->
backsubst_vec_x(RowA, A, B, X, X, Vb).
backsubst_vec_x([Va], A, B, [], X0, S)
when is_float(Va), is_float(S) ->
backsubst_vec_r(A, B, X0++[S/Va]);
backsubst_vec_x([Va | RowA], A, B, [Vx | X], X0, S)
when is_float(Va), is_float(Vx), is_float(S) ->
backsubst_vec_x(RowA, A, B, X, X0, S - Va*Vx).
vecs(N, L) ->
vecs(0, N, L, []).
vecs(I, _, [], C) ->
{lists:reverse(C), I};
vecs(I, N, [{?TAG,N,D} | L], C) ->
vecs(I+1, N, L, [D | C]);
vecs(I, 1, [V | L], C) when is_number(V) ->
vecs(I+1, 1, L, [push_v(float(V), []) | C]);
vecs(_, _, _, _) ->
badarg.
vec_add(A, B) ->
vec_add(0, A, 0, B, 0, []).
vec_add(A, F, B) when is_float(F) ->
vec_add(0, A, F, 0, B, 0, []).
vec_add(Za, [Va | A], Zb, B, Zc, C) when is_integer(Va) ->
vec_add(Za+Va, A, Zb, B, Zc, C);
vec_add(Za, A, Zb, [Vb | B], Zc, C) when is_integer(Vb) ->
vec_add(Za, A, Zb+Vb, B, Zc, C);
vec_add(0, [], 0, [], Zc, C) ->
if Zc == 0 ->
lists:reverse(C);
true ->
lists:reverse(C, [Zc])
end;
vec_add(0, [Va | A], 0, [Vb | B], Zc, C)
when is_float(Va), is_float(Vb) ->
Vc = Va + Vb,
vec_add(0, A, 0, B, 0, if Zc == 0 -> [Vc | C];
true -> [Vc, Zc | C]
end);
vec_add(0, [Va | A], Zb, B, Zc, C) ->
vec_add(0, A, Zb-1, B, 0, if Zc == 0 -> [Va | C];
true -> [Va, Zc | C]
end);
vec_add(Za, A, 0, [Vb | B], Zc, C)
when is_float(Vb) ->
vec_add(Za-1, A, 0, B, 0, if Zc == 0 -> [Vb | C];
true -> [Vb, Zc | C]
end);
vec_add(Za, A, Zb, B, Zc, C) ->
if Za < Zb ->
vec_add(0, A, Zb-Za, B, Zc+Za, C);
Zb < Za ->
vec_add(Za-Zb, A, 0, B, Zc+Zb, C);
true ->
vec_add(0, A, 0, B, Zc+Za, C)
end.
vec_add(Za, [Va | A], F, Zb, B, Zc, C) when is_integer(Va) ->
vec_add(Za+Va, A, F, Zb, B, Zc, C);
vec_add(Za, A, F, Zb, [Vb | B], Zc, C) when is_integer(Vb) ->
vec_add(Za, A, F, Zb+Vb, B, Zc, C);
vec_add(0, [], _, 0, [], Zc, C) ->
if Zc == 0 ->
lists:reverse(C);
true ->
lists:reverse(C, [Zc])
end;
vec_add(0, [Va | A], F, 0, [Vb | B], Zc, C)
when is_float(Va), is_float(F), is_float(Vb) ->
Vc = Va + F*Vb,
vec_add(0, A, F, 0, B, 0, if Zc == 0 -> [Vc | C];
true -> [Vc, Zc | C]
end);
vec_add(0, [Va | A], F, Zb, B, Zc, C) ->
vec_add(0, A, F, Zb-1, B, 0, if Zc == 0 -> [Va | C];
true -> [Va, Zc | C]
end);
vec_add(Za, A, F, 0, [Vb | B], Zc, C)
when is_float(F), is_float(Vb) ->
Vc = F*Vb,
vec_add(Za-1, A, F, 0, B, 0, if Zc == 0 -> [Vc | C];
true -> [Vc, Zc | C]
end);
vec_add(Za, A, F, Zb, B, Zc, C) ->
if Za < Zb ->
vec_add(0, A, F, Zb-Za, B, Zc+Za, C);
Zb < Za ->
vec_add(Za-Zb, A, F, 0, B, Zc+Zb, C);
true ->
vec_add(0, A, F, 0, B, Zc+Za, C)
end.
vec_mult_const(F, [V | B], C) when is_float(F), is_float(V) ->
vec_mult_const(F, B, [V*F | C]);
vec_mult_const(F, [Z | B], C) ->
vec_mult_const(F, B, [Z | C]);
vec_mult_const(_, [], C) ->
lists:reverse(C).
vec_mult_tuple(T, I, [Zb | B], S) when is_integer(Zb) ->
vec_mult_tuple(T, I+Zb, B, S);
vec_mult_tuple(T, I, [Vb | B], S) when is_float(Vb), is_float(S) ->
case element(I, T) of
Va when is_float(Va) ->
vec_mult_tuple(T, I+1, B, Va*Vb + S)
end;
vec_mult_tuple(_, _, [], S) -> S.
vec_mult(A, B) ->
vec_mult(A, B, 0.0).
vec_mult([Va | A], [Vb | B], S) when is_float(Va), is_float(Vb) ->
vec_mult(A, B, Va*Vb + S);
vec_mult([Za|A], [_|_]=B, S) when is_integer(Za) ->
vec_mult_pop(Za, A, B, S);
vec_mult_pop(Zb, B, A, S);
vec_mult(_, _, S) -> S.
vec_mult_pop(_, [], _, S) -> S;
vec_mult_pop(0, A, B, S) ->
vec_mult(A, B, S);
vec_mult_pop(Za, A, [Vb | B], S) when is_float(Vb) ->
vec_mult_pop(Za-1, A, B, S);
S;
vec_mult_pop(Za, A, [Zb | B], S) when Za < Zb ->
vec_mult_pop(Zb-Za, B, A, S);
vec_mult_pop(Za, A, [Zb | B], S) when Zb < Za ->
vec_mult_pop(Za-Zb, A, B, S);
vec_mult(A, B, S);
vec_mult_pop(_, _, [], S) ->
S.
vec_sq([], S) ->
S;
vec_sq([V | A], S) when is_float(V), is_float(S) ->
vec_sq(A, S + V*V);
vec_sq([_ | A], S) ->
vec_sq(A, S).
Push value ; zeros or float
push_v(0.0, C) ->
case C of
[Z | R] when is_integer(Z) ->
[Z+1 | R];
R ->
[1 | R]
end;
push_v(V, C) when is_float(V) ->
[V | C];
push_v(0, C) ->
C;
push_v(Z1, C) when is_integer(Z1) ->
case C of
[Z2 | R] when is_integer(Z2) ->
[Z1+Z2 | R];
R ->
[Z1 | R]
end.
pop_z([]) ->
[];
pop_z([1]) ->
[];
pop_z([1 | C]) ->
C;
pop_z([Z | C]) when is_integer(Z) ->
[Z-1 | C].
fix({?TAG,1,1,[[1]]}) ->
0.0;
fix({?TAG,1,1,[[V]]}) ->
V;
fix({?TAG,1,[1]}) ->
0.0;
fix({?TAG,1,[V]}) ->
V;
fix(V) when is_integer(V) ->
float(V);
fix(M) ->
M.
-ifdef(DEBUG).
float_perf(A, L) ->
float_perf(A, L, []).
float_perf(_, [], C) ->
lists:reverse(C);
float_perf(A, [B | T], C) ->
float_perf(A, T, [float_perf_int(A, B, 0.0), C]).
float_perf_int([], [], S) ->
S;
float_perf_int([Va | A], [Vb | B], S) when is_float(Va), float(Vb), float(S) ->
float_perf_int(A, B, Va*Vb + S).
-endif.
|
7aaa28def88aa7cd7e0efb621abc0fefb691a7bbf750001a94829d391a5149f1 | ocaml/oasis | OASISAst_types.ml | (******************************************************************************)
OASIS : architecture for building OCaml libraries and applications
(* *)
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
(* *)
(* This library is free software; you can redistribute it and/or modify it *)
(* under the terms of the GNU Lesser General Public License as published by *)
the Free Software Foundation ; either version 2.1 of the License , or ( at
(* your option) any later version, with the OCaml static compilation *)
(* exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *)
(* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *)
(* details. *)
(* *)
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
(******************************************************************************)
* AST types
@author
@author Sylvain Le Gall
*)
open OASISTypes
(* TODO: get rid of that if possible. *)
(** Context for parsing and checking AST *)
type ctxt =
{
(** Current condition for conditional fields. *)
cond: OASISExpr.t option;
(** Valid flags *)
valid_flags: name list;
(** Combine values rather than setting it, when
setting field values
*)
append: bool;
(** Global context *)
ctxt: OASISContext.t;
}
(** Abstract Syntax Tree *)
type field_op =
| FSet of string
| FAdd of string
| FEval of OASISExpr.t
type stmt =
| SField of name * field_op
| SIfThenElse of OASISExpr.t * stmt * stmt
| SBlock of stmt list
type top_stmt =
| TSSection of section_kind * name * stmt
| TSStmt of stmt
| TSBlock of top_stmt list
let norm =
let rec norm_top_stmt =
function
| TSSection(sct_knd, nm, stmt) -> TSSection(sct_knd, nm, norm_stmt stmt)
| TSStmt stmt -> TSStmt(norm_stmt stmt)
| TSBlock [tstmt] -> norm_top_stmt tstmt
| TSBlock lst -> TSBlock(norm_flatten_tsblock lst)
and norm_flatten_tsblock =
function
| (TSBlock l1) :: l2 -> norm_flatten_tsblock (l1 @ l2)
| hd :: tl -> norm_top_stmt hd :: norm_flatten_tsblock tl
| [] -> []
and norm_stmt =
function
| SField(nm, fop) -> SField(nm, norm_field_op fop)
| SIfThenElse(expr, stmt1, stmt2) ->
SIfThenElse(OASISExpr.reduce expr, norm_stmt stmt1, norm_stmt stmt2)
| SBlock [stmt] -> norm_stmt stmt
| SBlock lst -> SBlock(norm_flatten_sblock lst)
and norm_flatten_sblock =
function
| (SBlock l1) :: l2 -> norm_flatten_sblock (l1 @ l2)
| hd :: tl -> norm_stmt hd :: norm_flatten_sblock tl
| [] -> []
and norm_field_op =
function
| FSet _ as e -> e
| FAdd _ as e -> e
| FEval expr -> FEval (OASISExpr.reduce expr)
in
norm_top_stmt
| null | https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/src/oasis/OASISAst_types.ml | ocaml | ****************************************************************************
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
your option) any later version, with the OCaml static compilation
exception.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more
details.
****************************************************************************
TODO: get rid of that if possible.
* Context for parsing and checking AST
* Current condition for conditional fields.
* Valid flags
* Combine values rather than setting it, when
setting field values
* Global context
* Abstract Syntax Tree | OASIS : architecture for building OCaml libraries and applications
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
the Free Software Foundation ; either version 2.1 of the License , or ( at
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
* AST types
@author
@author Sylvain Le Gall
*)
open OASISTypes
type ctxt =
{
cond: OASISExpr.t option;
valid_flags: name list;
append: bool;
ctxt: OASISContext.t;
}
type field_op =
| FSet of string
| FAdd of string
| FEval of OASISExpr.t
type stmt =
| SField of name * field_op
| SIfThenElse of OASISExpr.t * stmt * stmt
| SBlock of stmt list
type top_stmt =
| TSSection of section_kind * name * stmt
| TSStmt of stmt
| TSBlock of top_stmt list
let norm =
let rec norm_top_stmt =
function
| TSSection(sct_knd, nm, stmt) -> TSSection(sct_knd, nm, norm_stmt stmt)
| TSStmt stmt -> TSStmt(norm_stmt stmt)
| TSBlock [tstmt] -> norm_top_stmt tstmt
| TSBlock lst -> TSBlock(norm_flatten_tsblock lst)
and norm_flatten_tsblock =
function
| (TSBlock l1) :: l2 -> norm_flatten_tsblock (l1 @ l2)
| hd :: tl -> norm_top_stmt hd :: norm_flatten_tsblock tl
| [] -> []
and norm_stmt =
function
| SField(nm, fop) -> SField(nm, norm_field_op fop)
| SIfThenElse(expr, stmt1, stmt2) ->
SIfThenElse(OASISExpr.reduce expr, norm_stmt stmt1, norm_stmt stmt2)
| SBlock [stmt] -> norm_stmt stmt
| SBlock lst -> SBlock(norm_flatten_sblock lst)
and norm_flatten_sblock =
function
| (SBlock l1) :: l2 -> norm_flatten_sblock (l1 @ l2)
| hd :: tl -> norm_stmt hd :: norm_flatten_sblock tl
| [] -> []
and norm_field_op =
function
| FSet _ as e -> e
| FAdd _ as e -> e
| FEval expr -> FEval (OASISExpr.reduce expr)
in
norm_top_stmt
|
54d785a1d3ac902f9c12e8312cb6684fc929ec8032b476fabfdb3b32bf8f0d0c | nubank/vessel | cli_test.clj | (ns vessel.cli-test
(:require [clojure.java.io :as io]
[clojure.string :as string]
[clojure.test :refer :all]
[vessel.cli :as cli]))
(defmacro with-err-str
[& body]
`(let [writer# (java.io.StringWriter.)]
(binding [*err* writer#]
~@body
(str writer#))))
(defn greet
[{:keys [names]}]
(println "Hello"
(string/join ", " names)))
(defn goodbye
[{:keys [names]}]
(println "Goodbye"
(string/join ", " names)))
(def vessel
{:desc "FIXME"
:commands
{"greet"
{:desc "Say a hello message for someone"
:fn greet
:opts [["-n" "--name NAME"
:id :names
:desc "Name of the person to greet"
:assoc-fn cli/repeat-option]]}
"goodbye"
{:desc "Print a goodbye message"
:fn greet
:opts [["-n" "--name NAME"
:id :names
:desc "Name of the person to say goodbye to"
:assoc-fn cli/repeat-option]]}
"boom"
{:desc "Simply blows up"
:fn (fn [_] (throw (Exception. "Boom!")))}}})
(deftest run-test
(testing "calls the function assigned to the command in question"
(is (= "Hello John Doe\n"
(with-out-str (cli/run vessel ["greet"
"-n" "John Doe"])))))
(testing "the function `repeat-option`, when assigned to the `:assoc-fn`
option, allows the flag to be repeated multiple times"
(is (= "Hello John Doe, Jane Doe\n"
(with-out-str (cli/run vessel ["greet"
"-n" "John Doe"
"-n" "Jane Doe"])))))
(testing "returns 0 indicating success"
(is (= 0
(cli/run vessel ["greet"
"-n" "John Doe"]))))
(testing "shows the help message when one calls Vessel with no arguments or with
the help flag"
(are [args] (= "Usage: vessel [OPTIONS] COMMAND\n\nFIXME\n\nOptions:\n -?, --help Show this help message and exit\n\nCommands:\n boom Simply blows up\n goodbye Print a goodbye message\n greet Say a hello message for someone\n\nSee \"vessel COMMAND --help\" for more information on a command\n"
(with-out-str
(cli/run vessel args)))
[]
["-?"]
["--help"]))
(testing "shows the help message for the command in question"
(is (= "Usage: vessel greet [OPTIONS]
Say a hello message for someone
Options:
-n, --name NAME Name of the person to greet
-?, --help Show this help message and exit\n"
(with-out-str
(cli/run vessel ["greet" "--help"])))))
(testing "returns 0 after showing the help message"
(is (= 0
(cli/run vessel ["--help"])))
(is (= 0
(cli/run vessel ["goodbye" "--help"]))))
(testing "shows a meaningful message when Vessel is called with wrong options"
(is (= "Vessel: Unknown option: \"--foo\"\nSee \"vessel --help\"\n"
(with-err-str
(cli/run vessel ["--foo"])))))
(testing "returns 1 indicating the error"
(is (= 1
(cli/run vessel ["--foo"]))))
(testing "shows a meaningful message when the command in question doesn't
exist"
(is (= "Vessel: \"build\" isn't a Vessel command\nSee \"vessel --help\"\n"
(with-err-str
(cli/run vessel ["build" "--help"])))))
(testing "returns 127 indicating that the command could not be found"
(is (= 127
(cli/run vessel ["build" "--help"]))))
(testing "shows a meaningful message when a command is mistakenly called"
(is (= "Vessel: Missing required argument for \"-n NAME\"\nSee \"vessel greet --help\"\n"
(with-err-str
(cli/run vessel ["greet" "-n"])))))
(testing "returns 1 indicating an error"
(is (= 1
(cli/run vessel ["greet" "-n"]))))
(testing "shows an error message when the command throws an exception"
(is (= "Vessel: Boom!\n"
(with-err-str
(cli/run vessel ["boom"])))))
(testing "returns 1 indicating an error"
(is (= 1
(cli/run vessel ["boom"])))))
(deftest parse-attribute-test
(testing "parses the input in the form `key:value`"
(is (= [:name "my-app"]
(cli/parse-attribute "name:my-app"))))
(testing "the value can contain colons"
(is (= [:build-date "Fri Jan 31 12:04:26"]
(cli/parse-attribute "build-date:Fri Jan 31 12:04:26"))))
(testing "throws an exception when the input is malformed"
(is (thrown-with-msg? IllegalArgumentException #"^Invalid attribute format.*"
(cli/parse-attribute "name")))))
(deftest parse-extra-path-test
(testing "parses the input in the form `source:target`"
(is (= {:source (io/file "web.xml")
:target (io/file "/app/web.xml")
:churn 0}
(cli/parse-extra-path "web.xml:/app/web.xml"))))
(testing "parses the input in the form `source:target@churn`"
(is (= {:source (io/file "web.xml")
:target (io/file "/app/web.xml")
:churn 2}
(cli/parse-extra-path "web.xml:/app/web.xml@2"))))
(testing "throws an exception when the input is malformed"
(is (thrown-with-msg? IllegalArgumentException #"^Invalid extra-path format.*"
(cli/parse-extra-path "web.xml"))))
(testing "throws an exception when the churn isn't an integer"
(is (thrown-with-msg? IllegalArgumentException #"Expected an integer but got 'foo' in the churn field of the extra-path specification\."
(cli/parse-extra-path "web.xml:/app/web.xml@foo")))))
(defn validate
[[validate-fn message] input]
(when-not (validate-fn input)
message))
(deftest file-or-dir-must-exist-test
(is (= "no such file or directory"
(validate cli/file-or-dir-must-exist (io/file "foo.txt"))))
(is (nil?
(validate cli/file-or-dir-must-exist (io/file "deps.edn")))))
(deftest source-must-exist-test
(is (= "no such file or directory"
(validate cli/source-must-exist {:source (io/file "foo.txt")})))
(is (nil?
(validate cli/source-must-exist {:source (io/file "deps.edn")}))))
| null | https://raw.githubusercontent.com/nubank/vessel/40036928d20cfd07b31b99bb2389d5421c49d26d/test/unit/vessel/cli_test.clj | clojure | (ns vessel.cli-test
(:require [clojure.java.io :as io]
[clojure.string :as string]
[clojure.test :refer :all]
[vessel.cli :as cli]))
(defmacro with-err-str
[& body]
`(let [writer# (java.io.StringWriter.)]
(binding [*err* writer#]
~@body
(str writer#))))
(defn greet
[{:keys [names]}]
(println "Hello"
(string/join ", " names)))
(defn goodbye
[{:keys [names]}]
(println "Goodbye"
(string/join ", " names)))
(def vessel
{:desc "FIXME"
:commands
{"greet"
{:desc "Say a hello message for someone"
:fn greet
:opts [["-n" "--name NAME"
:id :names
:desc "Name of the person to greet"
:assoc-fn cli/repeat-option]]}
"goodbye"
{:desc "Print a goodbye message"
:fn greet
:opts [["-n" "--name NAME"
:id :names
:desc "Name of the person to say goodbye to"
:assoc-fn cli/repeat-option]]}
"boom"
{:desc "Simply blows up"
:fn (fn [_] (throw (Exception. "Boom!")))}}})
(deftest run-test
(testing "calls the function assigned to the command in question"
(is (= "Hello John Doe\n"
(with-out-str (cli/run vessel ["greet"
"-n" "John Doe"])))))
(testing "the function `repeat-option`, when assigned to the `:assoc-fn`
option, allows the flag to be repeated multiple times"
(is (= "Hello John Doe, Jane Doe\n"
(with-out-str (cli/run vessel ["greet"
"-n" "John Doe"
"-n" "Jane Doe"])))))
(testing "returns 0 indicating success"
(is (= 0
(cli/run vessel ["greet"
"-n" "John Doe"]))))
(testing "shows the help message when one calls Vessel with no arguments or with
the help flag"
(are [args] (= "Usage: vessel [OPTIONS] COMMAND\n\nFIXME\n\nOptions:\n -?, --help Show this help message and exit\n\nCommands:\n boom Simply blows up\n goodbye Print a goodbye message\n greet Say a hello message for someone\n\nSee \"vessel COMMAND --help\" for more information on a command\n"
(with-out-str
(cli/run vessel args)))
[]
["-?"]
["--help"]))
(testing "shows the help message for the command in question"
(is (= "Usage: vessel greet [OPTIONS]
Say a hello message for someone
Options:
-n, --name NAME Name of the person to greet
-?, --help Show this help message and exit\n"
(with-out-str
(cli/run vessel ["greet" "--help"])))))
(testing "returns 0 after showing the help message"
(is (= 0
(cli/run vessel ["--help"])))
(is (= 0
(cli/run vessel ["goodbye" "--help"]))))
(testing "shows a meaningful message when Vessel is called with wrong options"
(is (= "Vessel: Unknown option: \"--foo\"\nSee \"vessel --help\"\n"
(with-err-str
(cli/run vessel ["--foo"])))))
(testing "returns 1 indicating the error"
(is (= 1
(cli/run vessel ["--foo"]))))
(testing "shows a meaningful message when the command in question doesn't
exist"
(is (= "Vessel: \"build\" isn't a Vessel command\nSee \"vessel --help\"\n"
(with-err-str
(cli/run vessel ["build" "--help"])))))
(testing "returns 127 indicating that the command could not be found"
(is (= 127
(cli/run vessel ["build" "--help"]))))
(testing "shows a meaningful message when a command is mistakenly called"
(is (= "Vessel: Missing required argument for \"-n NAME\"\nSee \"vessel greet --help\"\n"
(with-err-str
(cli/run vessel ["greet" "-n"])))))
(testing "returns 1 indicating an error"
(is (= 1
(cli/run vessel ["greet" "-n"]))))
(testing "shows an error message when the command throws an exception"
(is (= "Vessel: Boom!\n"
(with-err-str
(cli/run vessel ["boom"])))))
(testing "returns 1 indicating an error"
(is (= 1
(cli/run vessel ["boom"])))))
(deftest parse-attribute-test
(testing "parses the input in the form `key:value`"
(is (= [:name "my-app"]
(cli/parse-attribute "name:my-app"))))
(testing "the value can contain colons"
(is (= [:build-date "Fri Jan 31 12:04:26"]
(cli/parse-attribute "build-date:Fri Jan 31 12:04:26"))))
(testing "throws an exception when the input is malformed"
(is (thrown-with-msg? IllegalArgumentException #"^Invalid attribute format.*"
(cli/parse-attribute "name")))))
(deftest parse-extra-path-test
(testing "parses the input in the form `source:target`"
(is (= {:source (io/file "web.xml")
:target (io/file "/app/web.xml")
:churn 0}
(cli/parse-extra-path "web.xml:/app/web.xml"))))
(testing "parses the input in the form `source:target@churn`"
(is (= {:source (io/file "web.xml")
:target (io/file "/app/web.xml")
:churn 2}
(cli/parse-extra-path "web.xml:/app/web.xml@2"))))
(testing "throws an exception when the input is malformed"
(is (thrown-with-msg? IllegalArgumentException #"^Invalid extra-path format.*"
(cli/parse-extra-path "web.xml"))))
(testing "throws an exception when the churn isn't an integer"
(is (thrown-with-msg? IllegalArgumentException #"Expected an integer but got 'foo' in the churn field of the extra-path specification\."
(cli/parse-extra-path "web.xml:/app/web.xml@foo")))))
(defn validate
[[validate-fn message] input]
(when-not (validate-fn input)
message))
(deftest file-or-dir-must-exist-test
(is (= "no such file or directory"
(validate cli/file-or-dir-must-exist (io/file "foo.txt"))))
(is (nil?
(validate cli/file-or-dir-must-exist (io/file "deps.edn")))))
(deftest source-must-exist-test
(is (= "no such file or directory"
(validate cli/source-must-exist {:source (io/file "foo.txt")})))
(is (nil?
(validate cli/source-must-exist {:source (io/file "deps.edn")}))))
|
|
bedf9f9140d83fc0a8c132de72b8a3a00e2f461b575ed104d5766a74a67e023d | shop-planner/shop3 | p09.lisp | (in-package :shop-openstacks)
#.(make-problem 'OS-SEQUENCEDSTRIPS-P15_3 'OPENSTACKS-SEQUENCEDSTRIPS-ADL-INCLUDED '((NEXT-COUNT
N0
N1)
(NEXT-COUNT
N1
N2)
(NEXT-COUNT
N2
N3)
(NEXT-COUNT
N3
N4)
(NEXT-COUNT
N4
N5)
(NEXT-COUNT
N5
N6)
(NEXT-COUNT
N6
N7)
(NEXT-COUNT
N7
N8)
(NEXT-COUNT
N8
N9)
(NEXT-COUNT
N9
N10)
(NEXT-COUNT
N10
N11)
(NEXT-COUNT
N11
N12)
(NEXT-COUNT
N12
N13)
(NEXT-COUNT
N13
N14)
(NEXT-COUNT
N14
N15)
(STACKS-AVAIL
N0)
(WAITING
O1)
(INCLUDES
O1
P2)
(WAITING
O2)
(INCLUDES
O2
P7)
(WAITING
O3)
(INCLUDES
O3
P13)
(WAITING
O4)
(INCLUDES
O4
P3)
(INCLUDES
O4
P4)
(INCLUDES
O4
P11)
(INCLUDES
O4
P14)
(WAITING
O5)
(INCLUDES
O5
P2)
(WAITING
O6)
(INCLUDES
O6
P9)
(WAITING
O7)
(INCLUDES
O7
P5)
(WAITING
O8)
(INCLUDES
O8
P2)
(INCLUDES
O8
P10)
(WAITING
O9)
(INCLUDES
O9
P10)
(WAITING
O10)
(INCLUDES
O10
P10)
(INCLUDES
O10
P12)
(WAITING
O11)
(INCLUDES
O11
P1)
(INCLUDES
O11
P2)
(WAITING
O12)
(INCLUDES
O12
P6)
(WAITING
O13)
(INCLUDES
O13
P7)
(WAITING
O14)
(INCLUDES
O14
P9)
(INCLUDES
O14
P15)
(WAITING
O15)
(INCLUDES
O15
P8)
(=
(TOTAL-COST)
0)
(COUNT
N0)
(COUNT
N1)
(COUNT
N2)
(COUNT
N3)
(COUNT
N4)
(COUNT
N5)
(COUNT
N6)
(COUNT
N7)
(COUNT
N8)
(COUNT
N9)
(COUNT
N10)
(COUNT
N11)
(COUNT
N12)
(COUNT
N13)
(COUNT
N14)
(COUNT
N15)
(ORDER
O1)
(ORDER
O2)
(ORDER
O3)
(ORDER
O4)
(ORDER
O5)
(ORDER
O6)
(ORDER
O7)
(ORDER
O8)
(ORDER
O9)
(ORDER
O10)
(ORDER
O11)
(ORDER
O12)
(ORDER
O13)
(ORDER
O14)
(ORDER
O15)
(PRODUCT
P1)
(PRODUCT
P2)
(PRODUCT
P3)
(PRODUCT
P4)
(PRODUCT
P5)
(PRODUCT
P6)
(PRODUCT
P7)
(PRODUCT
P8)
(PRODUCT
P9)
(PRODUCT
P10)
(PRODUCT
P11)
(PRODUCT
P12)
(PRODUCT
P13)
(PRODUCT
P14)
(PRODUCT
P15)
(:GOAL
(AND
(SHIPPED
O1)
(SHIPPED
O2)
(SHIPPED
O3)
(SHIPPED
O4)
(SHIPPED
O5)
(SHIPPED
O6)
(SHIPPED
O7)
(SHIPPED
O8)
(SHIPPED
O9)
(SHIPPED
O10)
(SHIPPED
O11)
(SHIPPED
O12)
(SHIPPED
O13)
(SHIPPED
O14)
(SHIPPED
O15)))) '(:TASK
PLAN)) | null | https://raw.githubusercontent.com/shop-planner/shop3/ba429cf91a575e88f28b7f0e89065de7b4d666a6/shop3/examples/openstacks-adl/p09.lisp | lisp | (in-package :shop-openstacks)
#.(make-problem 'OS-SEQUENCEDSTRIPS-P15_3 'OPENSTACKS-SEQUENCEDSTRIPS-ADL-INCLUDED '((NEXT-COUNT
N0
N1)
(NEXT-COUNT
N1
N2)
(NEXT-COUNT
N2
N3)
(NEXT-COUNT
N3
N4)
(NEXT-COUNT
N4
N5)
(NEXT-COUNT
N5
N6)
(NEXT-COUNT
N6
N7)
(NEXT-COUNT
N7
N8)
(NEXT-COUNT
N8
N9)
(NEXT-COUNT
N9
N10)
(NEXT-COUNT
N10
N11)
(NEXT-COUNT
N11
N12)
(NEXT-COUNT
N12
N13)
(NEXT-COUNT
N13
N14)
(NEXT-COUNT
N14
N15)
(STACKS-AVAIL
N0)
(WAITING
O1)
(INCLUDES
O1
P2)
(WAITING
O2)
(INCLUDES
O2
P7)
(WAITING
O3)
(INCLUDES
O3
P13)
(WAITING
O4)
(INCLUDES
O4
P3)
(INCLUDES
O4
P4)
(INCLUDES
O4
P11)
(INCLUDES
O4
P14)
(WAITING
O5)
(INCLUDES
O5
P2)
(WAITING
O6)
(INCLUDES
O6
P9)
(WAITING
O7)
(INCLUDES
O7
P5)
(WAITING
O8)
(INCLUDES
O8
P2)
(INCLUDES
O8
P10)
(WAITING
O9)
(INCLUDES
O9
P10)
(WAITING
O10)
(INCLUDES
O10
P10)
(INCLUDES
O10
P12)
(WAITING
O11)
(INCLUDES
O11
P1)
(INCLUDES
O11
P2)
(WAITING
O12)
(INCLUDES
O12
P6)
(WAITING
O13)
(INCLUDES
O13
P7)
(WAITING
O14)
(INCLUDES
O14
P9)
(INCLUDES
O14
P15)
(WAITING
O15)
(INCLUDES
O15
P8)
(=
(TOTAL-COST)
0)
(COUNT
N0)
(COUNT
N1)
(COUNT
N2)
(COUNT
N3)
(COUNT
N4)
(COUNT
N5)
(COUNT
N6)
(COUNT
N7)
(COUNT
N8)
(COUNT
N9)
(COUNT
N10)
(COUNT
N11)
(COUNT
N12)
(COUNT
N13)
(COUNT
N14)
(COUNT
N15)
(ORDER
O1)
(ORDER
O2)
(ORDER
O3)
(ORDER
O4)
(ORDER
O5)
(ORDER
O6)
(ORDER
O7)
(ORDER
O8)
(ORDER
O9)
(ORDER
O10)
(ORDER
O11)
(ORDER
O12)
(ORDER
O13)
(ORDER
O14)
(ORDER
O15)
(PRODUCT
P1)
(PRODUCT
P2)
(PRODUCT
P3)
(PRODUCT
P4)
(PRODUCT
P5)
(PRODUCT
P6)
(PRODUCT
P7)
(PRODUCT
P8)
(PRODUCT
P9)
(PRODUCT
P10)
(PRODUCT
P11)
(PRODUCT
P12)
(PRODUCT
P13)
(PRODUCT
P14)
(PRODUCT
P15)
(:GOAL
(AND
(SHIPPED
O1)
(SHIPPED
O2)
(SHIPPED
O3)
(SHIPPED
O4)
(SHIPPED
O5)
(SHIPPED
O6)
(SHIPPED
O7)
(SHIPPED
O8)
(SHIPPED
O9)
(SHIPPED
O10)
(SHIPPED
O11)
(SHIPPED
O12)
(SHIPPED
O13)
(SHIPPED
O14)
(SHIPPED
O15)))) '(:TASK
PLAN)) |
|
967423ca72feb60223eab2da5d26e3c955fd0a300c650750f28bdfc8a5e80969 | nuprl/gradual-typing-performance | tetras-tetra-change-color.rkt | #lang typed/racket/base
(provide tetra-change-color)
(require benchmark-util
"data-block-adapted.rkt"
"data-tetra-adapted.rkt")
(require/typed/check "bset-blocks-change-color.rkt"
[blocks-change-color (-> BSet Color BSet)])
;; =============================================================================
;; Change the color of the given tetra.
(: tetra-change-color (-> Tetra Color Tetra))
(define (tetra-change-color t c)
(tetra (tetra-center t)
(blocks-change-color (tetra-blocks t) c)))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/experimental/micro/tetris/typed/tetras-tetra-change-color.rkt | racket | =============================================================================
Change the color of the given tetra. | #lang typed/racket/base
(provide tetra-change-color)
(require benchmark-util
"data-block-adapted.rkt"
"data-tetra-adapted.rkt")
(require/typed/check "bset-blocks-change-color.rkt"
[blocks-change-color (-> BSet Color BSet)])
(: tetra-change-color (-> Tetra Color Tetra))
(define (tetra-change-color t c)
(tetra (tetra-center t)
(blocks-change-color (tetra-blocks t) c)))
|
bbc08645cd56abf2812839b03b65decf3204ed2d0db5fa6ff6def796d4872514 | IagoAbal/eba | uniq.ml |
open Batteries
type t = int
let fresh = unique
let compare = Int.compare
let to_int u = u
let pp = PP.int
let to_string = string_of_int
| null | https://raw.githubusercontent.com/IagoAbal/eba/81ab71efff1ea407a7b5a98f7e8fd8a9d8d60815/src/uniq.ml | ocaml |
open Batteries
type t = int
let fresh = unique
let compare = Int.compare
let to_int u = u
let pp = PP.int
let to_string = string_of_int
|
|
d85aea52b2a13cb07de1d4d57e573fefd069fa45e31b7e5fdfd45a00413041cc | exoscale/clojure-kubernetes-client | v1_api_versions.clj | (ns clojure-kubernetes-client.specs.v1-api-versions
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-server-address-by-client-cidr :refer :all]
)
(:import (java.io File)))
(declare v1-api-versions-data v1-api-versions)
(def v1-api-versions-data
{
(ds/opt :apiVersion) string?
(ds/opt :kind) string?
(ds/req :serverAddressByClientCIDRs) (s/coll-of v1-server-address-by-client-cidr)
(ds/req :versions) (s/coll-of string?)
})
(def v1-api-versions
(ds/spec
{:name ::v1-api-versions
:spec v1-api-versions-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_api_versions.clj | clojure | (ns clojure-kubernetes-client.specs.v1-api-versions
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-server-address-by-client-cidr :refer :all]
)
(:import (java.io File)))
(declare v1-api-versions-data v1-api-versions)
(def v1-api-versions-data
{
(ds/opt :apiVersion) string?
(ds/opt :kind) string?
(ds/req :serverAddressByClientCIDRs) (s/coll-of v1-server-address-by-client-cidr)
(ds/req :versions) (s/coll-of string?)
})
(def v1-api-versions
(ds/spec
{:name ::v1-api-versions
:spec v1-api-versions-data}))
|
|
433926bf12bd357319d20c93e54123b1e8b22f811d63d1697e256bb0ef607695 | meta-ex/ignite | resources.clj | (ns ^{:doc "A simple auto-generating file store for storing EDN"
:author "Sam Aaron"}
meta-ex.resources
(:require [overtone.config.file-store :as fstore]
[clojure.java.io :as io]))
(defonce __MAKE-RESOURCES-DIR___
(.mkdirs (io/file "resources/overtone-store")))
(defonce edn-stores (agent {}))
(defn- safe-store-k
[store-k]
(let [store-k (if (keyword? store-k)
(.replace (str store-k) ":" "")
(name store-k) )]
(.replaceAll store-k "[^a-zA-Z0-9]" "-_-")))
(defn- store-path
[store-k]
(let [store-k (safe-store-k store-k)]
(.getAbsolutePath (io/file (str "resources/overtone-store/" store-k ".clj")))))
(defn- find-store
[store-k]
(let [store-p (promise)]
(send edn-stores
(fn [s]
(let [store (or (get s store-k)
(fstore/live-file-store (store-path store-k)))]
(deliver store-p store)
(assoc s store-k store))))
@store-p))
(defn edn-save
"Set store-k's key k to value v."
[store-k k v]
(let [store (find-store store-k)]
(swap! store assoc k v)))
(defn edn-load
"Get store-k's val at key k."
([store-k k] (edn-load store-k k nil))
([store-k k not-found]
(when-let [store (find-store store-k)]
(get @store k not-found))))
(defn edn-delete
"Remove store-k's val at key k."
[store-k k]
(when-let [store (find-store store-k)]
(swap! store dissoc k)))
| null | https://raw.githubusercontent.com/meta-ex/ignite/b9b1ed7ae2fa01d017c23febabb714a6389a98dd/src/meta_ex/resources.clj | clojure | (ns ^{:doc "A simple auto-generating file store for storing EDN"
:author "Sam Aaron"}
meta-ex.resources
(:require [overtone.config.file-store :as fstore]
[clojure.java.io :as io]))
(defonce __MAKE-RESOURCES-DIR___
(.mkdirs (io/file "resources/overtone-store")))
(defonce edn-stores (agent {}))
(defn- safe-store-k
[store-k]
(let [store-k (if (keyword? store-k)
(.replace (str store-k) ":" "")
(name store-k) )]
(.replaceAll store-k "[^a-zA-Z0-9]" "-_-")))
(defn- store-path
[store-k]
(let [store-k (safe-store-k store-k)]
(.getAbsolutePath (io/file (str "resources/overtone-store/" store-k ".clj")))))
(defn- find-store
[store-k]
(let [store-p (promise)]
(send edn-stores
(fn [s]
(let [store (or (get s store-k)
(fstore/live-file-store (store-path store-k)))]
(deliver store-p store)
(assoc s store-k store))))
@store-p))
(defn edn-save
"Set store-k's key k to value v."
[store-k k v]
(let [store (find-store store-k)]
(swap! store assoc k v)))
(defn edn-load
"Get store-k's val at key k."
([store-k k] (edn-load store-k k nil))
([store-k k not-found]
(when-let [store (find-store store-k)]
(get @store k not-found))))
(defn edn-delete
"Remove store-k's val at key k."
[store-k k]
(when-let [store (find-store store-k)]
(swap! store dissoc k)))
|
|
6d4df9674876261283a093cdbda17402fee42c43f2e3e47152428160b9dd3fba | istathar/vaultaire | ContentsTest.hs | --
-- Data vault for metrics
--
Copyright © 2013 - 2014 Anchor Systems , Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
the 3 - clause BSD licence .
--
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -fno-warn-type-defaults #-}
module Main where
import System.ZMQ4.Monadic
import Test.Hspec hiding (pending)
import Control.Concurrent
import Data.HashMap.Strict (fromList)
import Data.Maybe
import Data.String
import Data.Text
import Network.URI
import Pipes.Prelude (toListM)
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Test.QuickCheck.Monadic (assert, monadicIO, run)
import Marquise.Client
import TestHelpers
import Vaultaire.Broker
import Vaultaire.Contents
import Vaultaire.Daemon
import Vaultaire.Util
startDaemons :: IO ()
startDaemons = do
quit <- newEmptyMVar
linkThread $ do
runZMQ $ startProxy (Router,"tcp://*:5580")
(Dealer,"tcp://*:5581") "tcp://*:5008"
readMVar quit
args <- daemonArgsDefault (fromJust $ parseURI "tcp:5581")
Nothing "test" quit
linkThread $ startContents args
main :: IO ()
main = do
startDaemons
hspec suite
suite :: Spec
suite = do
-- TODO: This does not belong here, move to another test at the least.
-- The reason for encodeAddressToString and decodeStringAsAddress beyond
Show and IsString is questionable . Is this made use of anywhere ? Perhaps
-- we can remove it before we have to maintain it.
describe "Addresses" $ do
it "encodes an address in base62" $ do
show (0 :: Address) `shouldBe` "00000000000"
show (2^64-1 :: Address) `shouldBe` "LygHa16AHYF"
show (minBound :: Address) `shouldBe` "00000000000"
show (maxBound :: Address) `shouldBe` "LygHa16AHYF"
it "decodes an address from base62" $ do
fromString "00000000000" `shouldBe` (0 :: Address)
fromString "00000000001" `shouldBe` (1 :: Address)
fromString "LygHa16AHYF" `shouldBe` ((2^64-1) :: Address)
fromString "LygHa16AHYG" `shouldBe` (0 :: Address)
describe "Full stack" $ do
it "unions two dicts" $ do
let dict_a = listToDict [("a", "1")]
let dict_b = listToDict [("a", "2")]
let addr = 1
cleanupTestEnvironment
let o = Origin "PONY"
xs <- withContentsConnection "localhost" $ \c -> do
updateSourceDict addr dict_a o c
updateSourceDict addr dict_b o c
toListM (enumerateOrigin o c)
case xs of
[(addr', dict)] -> do
dict `shouldBe` dict_b
addr' `shouldBe` addr
_ -> error "expected one"
prop "updates source dict for any address" propSourceDictUpdated
listToDict :: [(Text, Text)] -> SourceDict
listToDict elts = either error id . makeSourceDict $ fromList elts
propSourceDictUpdated :: Address -> SourceDict -> Property
propSourceDictUpdated addr dict = monadicIO $ do
xs <- run $ do
-- Clear out ceph
cleanupTestEnvironment
let o = Origin "PONY"
withContentsConnection "localhost" $ \c -> do
updateSourceDict addr dict o c
toListM (enumerateOrigin o c)
case xs of
[(addr', dict')] -> assert (addr' == addr && dict' == dict)
_ -> error "expected one"
| null | https://raw.githubusercontent.com/istathar/vaultaire/75603ea614b125568ca871e88280bd29b3aef4ba/tests/ContentsTest.hs | haskell |
Data vault for metrics
The code in this file, and the program it is a part of, is
made available to you by its authors as open source software:
you can redistribute it and/or modify it under the terms of
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# OPTIONS -fno-warn-type-defaults #
TODO: This does not belong here, move to another test at the least.
The reason for encodeAddressToString and decodeStringAsAddress beyond
we can remove it before we have to maintain it.
Clear out ceph | Copyright © 2013 - 2014 Anchor Systems , Pty Ltd and Others
the 3 - clause BSD licence .
module Main where
import System.ZMQ4.Monadic
import Test.Hspec hiding (pending)
import Control.Concurrent
import Data.HashMap.Strict (fromList)
import Data.Maybe
import Data.String
import Data.Text
import Network.URI
import Pipes.Prelude (toListM)
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Test.QuickCheck.Monadic (assert, monadicIO, run)
import Marquise.Client
import TestHelpers
import Vaultaire.Broker
import Vaultaire.Contents
import Vaultaire.Daemon
import Vaultaire.Util
startDaemons :: IO ()
startDaemons = do
quit <- newEmptyMVar
linkThread $ do
runZMQ $ startProxy (Router,"tcp://*:5580")
(Dealer,"tcp://*:5581") "tcp://*:5008"
readMVar quit
args <- daemonArgsDefault (fromJust $ parseURI "tcp:5581")
Nothing "test" quit
linkThread $ startContents args
main :: IO ()
main = do
startDaemons
hspec suite
suite :: Spec
suite = do
Show and IsString is questionable . Is this made use of anywhere ? Perhaps
describe "Addresses" $ do
it "encodes an address in base62" $ do
show (0 :: Address) `shouldBe` "00000000000"
show (2^64-1 :: Address) `shouldBe` "LygHa16AHYF"
show (minBound :: Address) `shouldBe` "00000000000"
show (maxBound :: Address) `shouldBe` "LygHa16AHYF"
it "decodes an address from base62" $ do
fromString "00000000000" `shouldBe` (0 :: Address)
fromString "00000000001" `shouldBe` (1 :: Address)
fromString "LygHa16AHYF" `shouldBe` ((2^64-1) :: Address)
fromString "LygHa16AHYG" `shouldBe` (0 :: Address)
describe "Full stack" $ do
it "unions two dicts" $ do
let dict_a = listToDict [("a", "1")]
let dict_b = listToDict [("a", "2")]
let addr = 1
cleanupTestEnvironment
let o = Origin "PONY"
xs <- withContentsConnection "localhost" $ \c -> do
updateSourceDict addr dict_a o c
updateSourceDict addr dict_b o c
toListM (enumerateOrigin o c)
case xs of
[(addr', dict)] -> do
dict `shouldBe` dict_b
addr' `shouldBe` addr
_ -> error "expected one"
prop "updates source dict for any address" propSourceDictUpdated
listToDict :: [(Text, Text)] -> SourceDict
listToDict elts = either error id . makeSourceDict $ fromList elts
propSourceDictUpdated :: Address -> SourceDict -> Property
propSourceDictUpdated addr dict = monadicIO $ do
xs <- run $ do
cleanupTestEnvironment
let o = Origin "PONY"
withContentsConnection "localhost" $ \c -> do
updateSourceDict addr dict o c
toListM (enumerateOrigin o c)
case xs of
[(addr', dict')] -> assert (addr' == addr && dict' == dict)
_ -> error "expected one"
|
8bbef76c58e4738427e01fd39238898e01bdda370e590cda9530906d7f367096 | yoriyuki/Camomile | xArray.mli | (** XArray : extensible arrays *)
Copyright ( C ) 2002 , 2003 .
(* This library is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public License *)
as published by the Free Software Foundation ; either version 2 of
the License , or ( at your option ) any later version .
As a special exception to the GNU Library General Public License , you
(* may link, statically or dynamically, a "work that uses this library" *)
(* with a publicly distributed version of this library to produce an *)
(* executable file containing portions of this library, and distribute *)
(* that executable file under terms of your choice, without any of the *)
additional requirements listed in clause 6 of the GNU Library General
(* Public License. By "a publicly distributed version of this library", *)
we mean either the unmodified Library as distributed by the authors ,
(* or a modified version of this library that is distributed under the *)
conditions defined in clause 3 of the GNU Library General Public
(* License. This exception does not however invalidate any other reasons *)
why the executable file might be covered by the GNU Library General
(* Public License . *)
(* This library is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *)
(* Lesser General Public License for more details. *)
You should have received a copy of the GNU Lesser General Public
(* License along with this library; if not, write to the Free Software *)
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
(* You can contact the authour by sending email to *)
(* *)
* XArray will be replaced by in future .
type 'a xarray
type 'a t = 'a xarray
init ~bufsize len default f :
* returned has length [ len ] , its nth - element is [ f n ] ,
* its default value is [ default ] . The size of the internal buffer
* is initially ~bufsize . However , accessible elements are only up to [ len ] .
* [ f ] is called with integers [ 0 ... len - 1 ] , only once for each integer .
* The call is in the increasing order f 0 , f1 , f2 , ...
* returned xarray has length [len], its nth-element is [f n],
* its default value is [default]. The size of the internal buffer
* is initially ~bufsize. However, accessible elements are only up to [len].
* [f] is called with integers [0 ... len - 1], only once for each integer.
* The call is in the increasing order f 0, f1, f2, ... *)
val init : ?bufsize:int -> int -> 'a -> (int -> 'a) -> 'a xarray
make ~bufsize len default :
* returns filled with [ default ] , whose default value is [ default ] ,
* size of the internal buffer is [ bufsize ] .
* returns xarray filled with [default], whose default value is [default],
* size of the internal buffer is [bufsize]. *)
val make : ?bufsize:int -> int -> 'a -> 'a xarray
val length : 'a xarray -> int
val get : 'a xarray -> int -> 'a
(* set x i e :
* set the [i]-th element of [x] to [e].
* The length of [x] is automatically extended to [i], and
* intermediate elements are set to the default value of [x] *)
val set : 'a xarray -> int -> 'a -> unit
type index
val nth : 'a xarray -> int -> index
val first : 'a xarray -> index
val last : 'a xarray -> index
val look : 'a xarray -> index -> 'a
(* next x i, prev x i :
* operation is valid if [i] points the valid element, i.e.
* returned value may point the location beyond valid elements by one.
* If [i] does not point a valid element, the results are unspecified. *)
val next : 'a t -> index -> index
val prev : 'a t -> index -> index
val move : 'a t -> index -> int -> index
(* test whether the given index points the valid element. *)
val out_of_range : 'a xarray -> index -> bool
val compare_index : 'a xarray -> index -> index -> int
(* semantics of these functions are similar to equivalents of
* Array or Buffer. *)
val clear : 'a xarray -> unit
val reset : 'a xarray -> unit
val copy : 'a xarray -> 'a xarray
val sub : 'a xarray -> int -> int -> 'a xarray
val add_element : 'a xarray -> 'a -> unit
val add_array : 'a xarray -> 'a array -> unit
val add_xarray : 'a xarray -> 'a xarray -> unit
val append : 'a xarray -> 'a xarray -> 'a xarray
val iter : ('a -> unit) -> 'a xarray -> unit
val array_of : 'a xarray -> 'a array
(* shrink x len : reduce the length of [x] to [len].
* If there is an element beyond [len], such elements are discarded. *)
val shrink : 'a xarray -> int -> unit
| null | https://raw.githubusercontent.com/yoriyuki/Camomile/d7d8843c88fae774f513610f8e09a613778e64b3/Camomile/internal/xArray.mli | ocaml | * XArray : extensible arrays
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
may link, statically or dynamically, a "work that uses this library"
with a publicly distributed version of this library to produce an
executable file containing portions of this library, and distribute
that executable file under terms of your choice, without any of the
Public License. By "a publicly distributed version of this library",
or a modified version of this library that is distributed under the
License. This exception does not however invalidate any other reasons
Public License .
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software
You can contact the authour by sending email to
set x i e :
* set the [i]-th element of [x] to [e].
* The length of [x] is automatically extended to [i], and
* intermediate elements are set to the default value of [x]
next x i, prev x i :
* operation is valid if [i] points the valid element, i.e.
* returned value may point the location beyond valid elements by one.
* If [i] does not point a valid element, the results are unspecified.
test whether the given index points the valid element.
semantics of these functions are similar to equivalents of
* Array or Buffer.
shrink x len : reduce the length of [x] to [len].
* If there is an element beyond [len], such elements are discarded. | Copyright ( C ) 2002 , 2003 .
as published by the Free Software Foundation ; either version 2 of
the License , or ( at your option ) any later version .
As a special exception to the GNU Library General Public License , you
additional requirements listed in clause 6 of the GNU Library General
we mean either the unmodified Library as distributed by the authors ,
conditions defined in clause 3 of the GNU Library General Public
why the executable file might be covered by the GNU Library General
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
* XArray will be replaced by in future .
type 'a xarray
type 'a t = 'a xarray
init ~bufsize len default f :
* returned has length [ len ] , its nth - element is [ f n ] ,
* its default value is [ default ] . The size of the internal buffer
* is initially ~bufsize . However , accessible elements are only up to [ len ] .
* [ f ] is called with integers [ 0 ... len - 1 ] , only once for each integer .
* The call is in the increasing order f 0 , f1 , f2 , ...
* returned xarray has length [len], its nth-element is [f n],
* its default value is [default]. The size of the internal buffer
* is initially ~bufsize. However, accessible elements are only up to [len].
* [f] is called with integers [0 ... len - 1], only once for each integer.
* The call is in the increasing order f 0, f1, f2, ... *)
val init : ?bufsize:int -> int -> 'a -> (int -> 'a) -> 'a xarray
make ~bufsize len default :
* returns filled with [ default ] , whose default value is [ default ] ,
* size of the internal buffer is [ bufsize ] .
* returns xarray filled with [default], whose default value is [default],
* size of the internal buffer is [bufsize]. *)
val make : ?bufsize:int -> int -> 'a -> 'a xarray
val length : 'a xarray -> int
val get : 'a xarray -> int -> 'a
val set : 'a xarray -> int -> 'a -> unit
type index
val nth : 'a xarray -> int -> index
val first : 'a xarray -> index
val last : 'a xarray -> index
val look : 'a xarray -> index -> 'a
val next : 'a t -> index -> index
val prev : 'a t -> index -> index
val move : 'a t -> index -> int -> index
val out_of_range : 'a xarray -> index -> bool
val compare_index : 'a xarray -> index -> index -> int
val clear : 'a xarray -> unit
val reset : 'a xarray -> unit
val copy : 'a xarray -> 'a xarray
val sub : 'a xarray -> int -> int -> 'a xarray
val add_element : 'a xarray -> 'a -> unit
val add_array : 'a xarray -> 'a array -> unit
val add_xarray : 'a xarray -> 'a xarray -> unit
val append : 'a xarray -> 'a xarray -> 'a xarray
val iter : ('a -> unit) -> 'a xarray -> unit
val array_of : 'a xarray -> 'a array
val shrink : 'a xarray -> int -> unit
|
b395d83695f3c3953cce2875d7e6cde9b765f77aa4cc6a054de32c2e9e96ff3c | wh5a/thih | DataConsAssump.hs | ------------------------------------------------------------------------------
Copyright : The Hatchet Team ( see file Contributors )
Module : DataConsAssump
Description : Computes the type assumptions of data
constructors in a module
For example :
MyCons : : a - > MyList a
Just : : a - > Maybe a
True : : Well :
from section 4.2 of the Haskell Report :
" These declarations may only appear at the
top level of a module . "
Primary Authors :
Notes : See the file License for license information
------------------------------------------------------------------------------
Copyright: The Hatchet Team (see file Contributors)
Module: DataConsAssump
Description: Computes the type assumptions of data
constructors in a module
For example:
MyCons :: a -> MyList a
Just :: a -> Maybe a
True :: Bool
Note Well:
from section 4.2 of the Haskell Report:
"These declarations may only appear at the
top level of a module."
Primary Authors: Bernie Pope
Notes: See the file License for license information
-------------------------------------------------------------------------------}
module DataConsAssump (dataConsEnv) where
import AnnotatedHsSyn (AHsDecl (..),
AHsName (..),
AModule (AModule),
AHsBangType (..),
AHsConDecl (..),
AHsContext)
import Representation (Type (..),
Tycon (..),
Tyvar (..),
unfoldKind,
Kind (..),
Pred (..),
Qual (..),
Assump (..),
Scheme)
import Type (assumpToPair,
makeAssump,
Types (..),
quantify)
import HaskellPrelude (fn)
import Utils (fromAHsName)
import TypeUtils (aHsTypeToType)
import FiniteMaps (FiniteMap,
toListFM,
listToFM)
import KindInference (KindEnv,
kindOf)
import Env (Env,
showEnv,
joinListEnvs,
unitEnv,
emptyEnv,
listToEnv)
--------------------------------------------------------------------------------
dataConsEnv :: AModule -> KindEnv -> [AHsDecl] -> Env Scheme
dataConsEnv modName kt decls
= joinListEnvs $ map (dataDeclEnv modName kt) decls
-- we should only apply this function to data decls and newtype decls
-- howver the fall through case is just there for completeness
dataDeclEnv :: AModule -> KindEnv -> (AHsDecl) -> Env Scheme
dataDeclEnv modName kt (AHsDataDecl _sloc context typeName args condecls derives)
= joinListEnvs $ map (conDeclType modName kt preds resultType) $ condecls
where
typeKind = kindOf typeName kt
resultType = foldl TAp tycon argVars
tycon = TCon (Tycon typeName typeKind)
argVars = map fromAHsNameToTyVar $ zip argKinds args
argKinds = init $ unfoldKind typeKind
fromAHsNameToTyVar :: (Kind, AHsName) -> Type
fromAHsNameToTyVar (k, n)
= TVar (Tyvar n k)
preds = hsContextToPreds kt context
dataDeclEnv modName kt (AHsNewTypeDecl _sloc context typeName args condecl derives)
= conDeclType modName kt preds resultType condecl
where
typeKind = kindOf typeName kt
resultType = foldl TAp tycon argVars
tycon = TCon (Tycon typeName typeKind)
argVars = map fromAHsNameToTyVar $ zip argKinds args
argKinds = init $ unfoldKind typeKind
fromAHsNameToTyVar :: (Kind, AHsName) -> Type
fromAHsNameToTyVar (k, n)
= TVar (Tyvar n k)
preds = hsContextToPreds kt context
dataDeclEnv _modName _kt _anyOtherDecl
= emptyEnv
-- broken until classes are added properly
hsContextToPreds :: KindEnv -> AHsContext -> [Pred]
hsContextToPreds _ assts
= []
conDeclType :: AModule -> KindEnv -> [Pred] -> Type -> AHsConDecl -> Env Scheme
conDeclType modName kt preds tResult (AHsConDecl _sloc conName bangTypes)
= unitEnv $ assumpToPair $ makeAssump conName $ quantify (tv qualConType) qualConType
where
conType = foldr fn tResult (map (bangTypeToType kt) bangTypes)
qualConType = preds :=> conType
bangTypeToType :: KindEnv -> AHsBangType -> Type
bangTypeToType kt (AHsBangedTy t) = aHsTypeToType kt t
bangTypeToType kt (AHsUnBangedTy t) = aHsTypeToType kt t
| null | https://raw.githubusercontent.com/wh5a/thih/dc5cb16ba4e998097135beb0c7b0b416cac7bfae/hatchet/DataConsAssump.hs | haskell | ----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
------------------------------------------------------------------------------
we should only apply this function to data decls and newtype decls
howver the fall through case is just there for completeness
broken until classes are added properly |
Copyright : The Hatchet Team ( see file Contributors )
Module : DataConsAssump
Description : Computes the type assumptions of data
constructors in a module
For example :
MyCons : : a - > MyList a
Just : : a - > Maybe a
True : : Well :
from section 4.2 of the Haskell Report :
" These declarations may only appear at the
top level of a module . "
Primary Authors :
Notes : See the file License for license information
Copyright: The Hatchet Team (see file Contributors)
Module: DataConsAssump
Description: Computes the type assumptions of data
constructors in a module
For example:
MyCons :: a -> MyList a
Just :: a -> Maybe a
True :: Bool
Note Well:
from section 4.2 of the Haskell Report:
"These declarations may only appear at the
top level of a module."
Primary Authors: Bernie Pope
Notes: See the file License for license information
module DataConsAssump (dataConsEnv) where
import AnnotatedHsSyn (AHsDecl (..),
AHsName (..),
AModule (AModule),
AHsBangType (..),
AHsConDecl (..),
AHsContext)
import Representation (Type (..),
Tycon (..),
Tyvar (..),
unfoldKind,
Kind (..),
Pred (..),
Qual (..),
Assump (..),
Scheme)
import Type (assumpToPair,
makeAssump,
Types (..),
quantify)
import HaskellPrelude (fn)
import Utils (fromAHsName)
import TypeUtils (aHsTypeToType)
import FiniteMaps (FiniteMap,
toListFM,
listToFM)
import KindInference (KindEnv,
kindOf)
import Env (Env,
showEnv,
joinListEnvs,
unitEnv,
emptyEnv,
listToEnv)
dataConsEnv :: AModule -> KindEnv -> [AHsDecl] -> Env Scheme
dataConsEnv modName kt decls
= joinListEnvs $ map (dataDeclEnv modName kt) decls
dataDeclEnv :: AModule -> KindEnv -> (AHsDecl) -> Env Scheme
dataDeclEnv modName kt (AHsDataDecl _sloc context typeName args condecls derives)
= joinListEnvs $ map (conDeclType modName kt preds resultType) $ condecls
where
typeKind = kindOf typeName kt
resultType = foldl TAp tycon argVars
tycon = TCon (Tycon typeName typeKind)
argVars = map fromAHsNameToTyVar $ zip argKinds args
argKinds = init $ unfoldKind typeKind
fromAHsNameToTyVar :: (Kind, AHsName) -> Type
fromAHsNameToTyVar (k, n)
= TVar (Tyvar n k)
preds = hsContextToPreds kt context
dataDeclEnv modName kt (AHsNewTypeDecl _sloc context typeName args condecl derives)
= conDeclType modName kt preds resultType condecl
where
typeKind = kindOf typeName kt
resultType = foldl TAp tycon argVars
tycon = TCon (Tycon typeName typeKind)
argVars = map fromAHsNameToTyVar $ zip argKinds args
argKinds = init $ unfoldKind typeKind
fromAHsNameToTyVar :: (Kind, AHsName) -> Type
fromAHsNameToTyVar (k, n)
= TVar (Tyvar n k)
preds = hsContextToPreds kt context
dataDeclEnv _modName _kt _anyOtherDecl
= emptyEnv
hsContextToPreds :: KindEnv -> AHsContext -> [Pred]
hsContextToPreds _ assts
= []
conDeclType :: AModule -> KindEnv -> [Pred] -> Type -> AHsConDecl -> Env Scheme
conDeclType modName kt preds tResult (AHsConDecl _sloc conName bangTypes)
= unitEnv $ assumpToPair $ makeAssump conName $ quantify (tv qualConType) qualConType
where
conType = foldr fn tResult (map (bangTypeToType kt) bangTypes)
qualConType = preds :=> conType
bangTypeToType :: KindEnv -> AHsBangType -> Type
bangTypeToType kt (AHsBangedTy t) = aHsTypeToType kt t
bangTypeToType kt (AHsUnBangedTy t) = aHsTypeToType kt t
|
bc1d631e7a3ac3d6f60ff945889a3600faf0a90935427d25ddddb4271a9c429c | jacekschae/learn-reitit-course-files | auth0.clj | (ns cheffy.auth0
(:require [clj-http.client :as http]
[muuntaja.core :as m]))
(defn get-test-token
[email]
(->> {:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:client_id "ts5NfJYbsIZ6rvhmbKykF9TkWz0tKcGS"
:audience "-reitit-playground.eu.auth0.com/api/v2/"
:grant_type "password"
:username email
:password "s#m3R4nd0m-pass"
:scope "openid profile email"})}
(http/post "-reitit-playground.eu.auth0.com/oauth/token")
(m/decode-response-body)
:access_token))
(defn get-management-token
[]
(->> {:throw-exceptions false
:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:client_id "0NLsiVfeEF2ZY0fstfzOk6K9AKZ1a5hP"
:client_secret "Pir0LuiCDE5Us-2pWo3ajk0C6LIndbcXJ1cEp96kMwVhkwurVbMlTa4I7z-jKLKB"
:audience "-reitit-playground.eu.auth0.com/api/v2/"
:grant_type "client_credentials"})}
(http/post "-reitit-playground.eu.auth0.com/oauth/token")
(m/decode-response-body)
:access_token))
(defn get-role-id
[token]
(->> {:headers {"Authorization" (str "Bearer " token)}
:throw-exceptions false
:content-type :json
:cookie-policy :standard}
(http/get "-reitit-playground.eu.auth0.com/api/v2/roles")
(m/decode-response-body)
(filter (fn [role] (= (:name role) "manage-recipes")))
(first)
:id))
(defn create-auth0-user
[{:keys [connection email password]}]
(->> {:headers {"Authorization" (str "Bearer " (get-management-token))}
:throw-exceptions false
:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:connection connection
:email email
:password password})}
(http/post "-reitit-playground.eu.auth0.com/api/v2/users")
(m/decode-response-body)))
(comment
(create-auth0-user
{:connection "Username-Password-Authentication"
:email ""
:password "s#m3R4nd0m-pass"})
(http/delete "-reitit-playground.eu.auth0.com/api/v2/users/5fe110f779ac79006fa4efba")
(->> {:headers {"Authorization" (str "Bearer " (get-management-token))}
:throw-exceptions false
:content-type :json
:cookie-policy :standard}
(http/delete "-reitit-playground.eu.auth0.com/api/v2/users/auth0|5fe110f779ac79006fa4efba"))
(let [uid "auth0|5fbf7db6271d5e0076903601"
token (get-management-token)]
(->> {:headers {"Authorization" (str "Bearer " token)}
:cookie-policy :standard
:content-type :json
:throw-exceptions false
#_#_:body (m/encode "application/json"
{:roles [(get-role-id token)]})}
(http/get (str "-reitit-playground.eu.auth0.com/api/v2/users/" uid "/roles"))))) | null | https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/47-tests-refactor/src/cheffy/auth0.clj | clojure | (ns cheffy.auth0
(:require [clj-http.client :as http]
[muuntaja.core :as m]))
(defn get-test-token
[email]
(->> {:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:client_id "ts5NfJYbsIZ6rvhmbKykF9TkWz0tKcGS"
:audience "-reitit-playground.eu.auth0.com/api/v2/"
:grant_type "password"
:username email
:password "s#m3R4nd0m-pass"
:scope "openid profile email"})}
(http/post "-reitit-playground.eu.auth0.com/oauth/token")
(m/decode-response-body)
:access_token))
(defn get-management-token
[]
(->> {:throw-exceptions false
:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:client_id "0NLsiVfeEF2ZY0fstfzOk6K9AKZ1a5hP"
:client_secret "Pir0LuiCDE5Us-2pWo3ajk0C6LIndbcXJ1cEp96kMwVhkwurVbMlTa4I7z-jKLKB"
:audience "-reitit-playground.eu.auth0.com/api/v2/"
:grant_type "client_credentials"})}
(http/post "-reitit-playground.eu.auth0.com/oauth/token")
(m/decode-response-body)
:access_token))
(defn get-role-id
[token]
(->> {:headers {"Authorization" (str "Bearer " token)}
:throw-exceptions false
:content-type :json
:cookie-policy :standard}
(http/get "-reitit-playground.eu.auth0.com/api/v2/roles")
(m/decode-response-body)
(filter (fn [role] (= (:name role) "manage-recipes")))
(first)
:id))
(defn create-auth0-user
[{:keys [connection email password]}]
(->> {:headers {"Authorization" (str "Bearer " (get-management-token))}
:throw-exceptions false
:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:connection connection
:email email
:password password})}
(http/post "-reitit-playground.eu.auth0.com/api/v2/users")
(m/decode-response-body)))
(comment
(create-auth0-user
{:connection "Username-Password-Authentication"
:email ""
:password "s#m3R4nd0m-pass"})
(http/delete "-reitit-playground.eu.auth0.com/api/v2/users/5fe110f779ac79006fa4efba")
(->> {:headers {"Authorization" (str "Bearer " (get-management-token))}
:throw-exceptions false
:content-type :json
:cookie-policy :standard}
(http/delete "-reitit-playground.eu.auth0.com/api/v2/users/auth0|5fe110f779ac79006fa4efba"))
(let [uid "auth0|5fbf7db6271d5e0076903601"
token (get-management-token)]
(->> {:headers {"Authorization" (str "Bearer " token)}
:cookie-policy :standard
:content-type :json
:throw-exceptions false
#_#_:body (m/encode "application/json"
{:roles [(get-role-id token)]})}
(http/get (str "-reitit-playground.eu.auth0.com/api/v2/users/" uid "/roles"))))) |
|
f6bb6fbdffe6f2be8a6e28c3393c61fd2da75501a34a38627b233e274fa3596e | rizo/snowflake-os | listLabels.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : listLabels.ml , v 1.3 2001 - 12 - 07 13:40:54 xleroy Exp $
(* Module [ListLabels]: labelled List module *)
include List
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/libraries/stdlib/listLabels.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
Module [ListLabels]: labelled List module | , Kyoto University RIMS
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : listLabels.ml , v 1.3 2001 - 12 - 07 13:40:54 xleroy Exp $
include List
|
197c07b73efa55385c5c8a3f79ff1134d8974281ac564f08a50e20762965799e | exercism/haskell | Tests.hs | # OPTIONS_GHC -fno - warn - type - defaults #
# LANGUAGE RecordWildCards #
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import WordProblem (answer)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "answer" $ for_ cases test
where
test Case{..} = it description assertion
where
assertion = answer input `shouldBe` fromIntegral <$> expected
data Case = Case { description :: String
, input :: String
, expected :: Maybe Integer
}
cases :: [Case]
cases = [ Case { description = "just a number"
, input = "What is 5?"
, expected = Just 5
}
, Case { description = "addition"
, input = "What is 1 plus 1?"
, expected = Just 2
}
, Case { description = "more addition"
, input = "What is 53 plus 2?"
, expected = Just 55
}
, Case { description = "addition with negative numbers"
, input = "What is -1 plus -10?"
, expected = Just (-11)
}
, Case { description = "large addition"
, input = "What is 123 plus 45678?"
, expected = Just 45801
}
, Case { description = "subtraction"
, input = "What is 4 minus -12?"
, expected = Just 16
}
, Case { description = "multiplication"
, input = "What is -3 multiplied by 25?"
, expected = Just (-75)
}
, Case { description = "division"
, input = "What is 33 divided by -3?"
, expected = Just (-11)
}
, Case { description = "multiple additions"
, input = "What is 1 plus 1 plus 1?"
, expected = Just 3
}
, Case { description = "addition and subtraction"
, input = "What is 1 plus 5 minus -2?"
, expected = Just 8
}
, Case { description = "multiple subtraction"
, input = "What is 20 minus 4 minus 13?"
, expected = Just 3
}
, Case { description = "subtraction then addition"
, input = "What is 17 minus 6 plus 3?"
, expected = Just 14
}
, Case { description = "multiple multiplication"
, input = "What is 2 multiplied by -2 multiplied by 3?"
, expected = Just (-12)
}
, Case { description = "addition and multiplication"
, input = "What is -3 plus 7 multiplied by -2?"
, expected = Just (-8)
}
, Case { description = "multiple division"
, input = "What is -12 divided by 2 divided by -3?"
, expected = Just 2
}
, Case { description = "unknown operation"
, input = "What is 52 cubed?"
, expected = Nothing
}
, Case { description = "Non math question"
, input = "Who is the President of the United States?"
, expected = Nothing
}
, Case { description = "reject problem missing an operand"
, input = "What is 1 plus?"
, expected = Nothing
}
, Case { description = "reject problem with no operands or operators"
, input = "What is?"
, expected = Nothing
}
, Case { description = "reject two operations in a row"
, input = "What is 1 plus plus 2?"
, expected = Nothing
}
, Case { description = "reject two numbers in a row"
, input = "What is 1 plus 2 1?"
, expected = Nothing
}
, Case { description = "reject postfix notation"
, input = "What is 1 2 plus?"
, expected = Nothing
}
, Case { description = "reject prefix notation"
, input = "What is plus 1 2?"
, expected = Nothing
}
]
| null | https://raw.githubusercontent.com/exercism/haskell/f81ee7dc338294b3dbefb7bd39fc193546fcec26/exercises/practice/wordy/test/Tests.hs | haskell | # OPTIONS_GHC -fno - warn - type - defaults #
# LANGUAGE RecordWildCards #
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import WordProblem (answer)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "answer" $ for_ cases test
where
test Case{..} = it description assertion
where
assertion = answer input `shouldBe` fromIntegral <$> expected
data Case = Case { description :: String
, input :: String
, expected :: Maybe Integer
}
cases :: [Case]
cases = [ Case { description = "just a number"
, input = "What is 5?"
, expected = Just 5
}
, Case { description = "addition"
, input = "What is 1 plus 1?"
, expected = Just 2
}
, Case { description = "more addition"
, input = "What is 53 plus 2?"
, expected = Just 55
}
, Case { description = "addition with negative numbers"
, input = "What is -1 plus -10?"
, expected = Just (-11)
}
, Case { description = "large addition"
, input = "What is 123 plus 45678?"
, expected = Just 45801
}
, Case { description = "subtraction"
, input = "What is 4 minus -12?"
, expected = Just 16
}
, Case { description = "multiplication"
, input = "What is -3 multiplied by 25?"
, expected = Just (-75)
}
, Case { description = "division"
, input = "What is 33 divided by -3?"
, expected = Just (-11)
}
, Case { description = "multiple additions"
, input = "What is 1 plus 1 plus 1?"
, expected = Just 3
}
, Case { description = "addition and subtraction"
, input = "What is 1 plus 5 minus -2?"
, expected = Just 8
}
, Case { description = "multiple subtraction"
, input = "What is 20 minus 4 minus 13?"
, expected = Just 3
}
, Case { description = "subtraction then addition"
, input = "What is 17 minus 6 plus 3?"
, expected = Just 14
}
, Case { description = "multiple multiplication"
, input = "What is 2 multiplied by -2 multiplied by 3?"
, expected = Just (-12)
}
, Case { description = "addition and multiplication"
, input = "What is -3 plus 7 multiplied by -2?"
, expected = Just (-8)
}
, Case { description = "multiple division"
, input = "What is -12 divided by 2 divided by -3?"
, expected = Just 2
}
, Case { description = "unknown operation"
, input = "What is 52 cubed?"
, expected = Nothing
}
, Case { description = "Non math question"
, input = "Who is the President of the United States?"
, expected = Nothing
}
, Case { description = "reject problem missing an operand"
, input = "What is 1 plus?"
, expected = Nothing
}
, Case { description = "reject problem with no operands or operators"
, input = "What is?"
, expected = Nothing
}
, Case { description = "reject two operations in a row"
, input = "What is 1 plus plus 2?"
, expected = Nothing
}
, Case { description = "reject two numbers in a row"
, input = "What is 1 plus 2 1?"
, expected = Nothing
}
, Case { description = "reject postfix notation"
, input = "What is 1 2 plus?"
, expected = Nothing
}
, Case { description = "reject prefix notation"
, input = "What is plus 1 2?"
, expected = Nothing
}
]
|
|
ccd8d68c66d5811e5f286d25c0a6f2c26f196e9b9e6f1be31822ee53c676b03a | typeclasses/loc | Pos.hs | module Data.Loc.Pos
(
Pos, Line, Column, ToNat (..),
-- * Show and Read
posShowsPrec, posReadPrec,
)
where
import Data.Loc.Internal.Prelude
import Prelude (Num (..))
import Data.Data (Data)
|
' Pos ' stands for /positive integer/. You can also think of it as ,
because we use it to represent line and column numbers ( ' Line ' and ' Column ' ) .
' Pos ' has instances of several of the standard numeric typeclasses , although
many of the operations throw ' Underflow ' when non - positive values result .
' Pos ' does /not/ have an ' Integral ' instance , because there is no sensible
way to implement ' quotRem ' .
'Pos' stands for /positive integer/. You can also think of it as /position/,
because we use it to represent line and column numbers ('Line' and 'Column').
'Pos' has instances of several of the standard numeric typeclasses, although
many of the operations throw 'Underflow' when non-positive values result.
'Pos' does /not/ have an 'Integral' instance, because there is no sensible
way to implement 'quotRem'.
-}
newtype Pos = Pos Natural
deriving (Data, Eq, Ord)
instance ToNat Pos
where
toNat (Pos n) = n
instance Show Pos
where
showsPrec = posShowsPrec
instance Read Pos
where
readPrec = posReadPrec
|
> > > fromInteger 3 : : Pos
3
> > > fromInteger 0 : : Pos
* * * Exception : arithmetic underflow
> > > 2 + 3 : : Pos
5
> > > 3 - 2 : : Pos
1
> > > 3 - 3 : : Pos
* * * Exception : arithmetic underflow
> > > 2 * 3 : : Pos
6
> > > negate 3 : : Pos
* * * Exception : arithmetic underflow
>>> fromInteger 3 :: Pos
3
>>> fromInteger 0 :: Pos
*** Exception: arithmetic underflow
>>> 2 + 3 :: Pos
5
>>> 3 - 2 :: Pos
1
>>> 3 - 3 :: Pos
*** Exception: arithmetic underflow
>>> 2 * 3 :: Pos
6
>>> negate 3 :: Pos
*** Exception: arithmetic underflow
-}
instance Num Pos
where
fromInteger = Pos . checkForUnderflow . fromInteger
Pos x + Pos y = Pos (x + y)
Pos x - Pos y = Pos (checkForUnderflow (x - y))
Pos x * Pos y = Pos (x * y)
abs = id
signum _ = Pos 1
negate _ = throw Underflow
instance Real Pos
where
toRational (Pos n) = toRational n
|
> > > toEnum 3 : : Pos
3
> > > toEnum 0 : : Pos
* * * Exception : arithmetic underflow
> > > fromEnum ( 3 : : Pos )
3
>>> toEnum 3 :: Pos
3
>>> toEnum 0 :: Pos
*** Exception: arithmetic underflow
>>> fromEnum (3 :: Pos)
3
-}
instance Enum Pos
where
toEnum = Pos . checkForUnderflow . toEnum
fromEnum (Pos n) = fromEnum n
checkForUnderflow :: Natural -> Natural
checkForUnderflow n =
if n == 0 then throw Underflow else n
|
> > > posShowsPrec minPrec 1 " "
" 1 "
> > > posShowsPrec minPrec 42 " "
" 42 "
>>> posShowsPrec minPrec 1 ""
"1"
>>> posShowsPrec minPrec 42 ""
"42"
-}
posShowsPrec :: Int -> Pos -> ShowS
posShowsPrec i (Pos n) =
showsPrec i n
|
> > > readPrec_to_S posReadPrec minPrec " 1 "
[ ( 1 , " " ) ]
> > > readPrec_to_S posReadPrec minPrec " 42 "
[ ( 42 , " " ) ]
> > > readPrec_to_S posReadPrec minPrec " 0 "
[ ]
> > > readPrec_to_S posReadPrec minPrec " -1 "
[ ]
>>> readPrec_to_S posReadPrec minPrec "1"
[(1,"")]
>>> readPrec_to_S posReadPrec minPrec "42"
[(42,"")]
>>> readPrec_to_S posReadPrec minPrec "0"
[]
>>> readPrec_to_S posReadPrec minPrec "-1"
[]
-}
posReadPrec :: ReadPrec Pos
posReadPrec =
Pos <$> mfilter (/= 0) readPrec
--------------------------------------------------------------------------------
-- ToNat
--------------------------------------------------------------------------------
{- |
Types that can be converted to 'Natural'.
This class mostly exists so that 'toNat' can be used in situations that would
normally call for 'toInteger' (which we cannot use because 'Pos' does not have
an instance of 'Integral').
-}
class ToNat a
where
toNat :: a -> Natural
--------------------------------------------------------------------------------
-- Line
--------------------------------------------------------------------------------
newtype Line = Line Pos
deriving (Data, Eq, Ord, Num, Real, Enum, ToNat)
instance Show Line
where
showsPrec i (Line pos) = showsPrec i pos
instance Read Line
where
readPrec = Line <$> readPrec
--------------------------------------------------------------------------------
-- Column
--------------------------------------------------------------------------------
newtype Column = Column Pos
deriving (Data, Eq, Ord, Num, Real, Enum, ToNat)
instance Show Column
where
showsPrec i (Column pos) = showsPrec i pos
instance Read Column
where
readPrec = Column <$> readPrec
| null | https://raw.githubusercontent.com/typeclasses/loc/9fe47b1f6097bbe0d850443bcdea5267c955a3c5/loc/src/Data/Loc/Pos.hs | haskell | * Show and Read
------------------------------------------------------------------------------
ToNat
------------------------------------------------------------------------------
|
Types that can be converted to 'Natural'.
This class mostly exists so that 'toNat' can be used in situations that would
normally call for 'toInteger' (which we cannot use because 'Pos' does not have
an instance of 'Integral').
------------------------------------------------------------------------------
Line
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Column
------------------------------------------------------------------------------ | module Data.Loc.Pos
(
Pos, Line, Column, ToNat (..),
posShowsPrec, posReadPrec,
)
where
import Data.Loc.Internal.Prelude
import Prelude (Num (..))
import Data.Data (Data)
|
' Pos ' stands for /positive integer/. You can also think of it as ,
because we use it to represent line and column numbers ( ' Line ' and ' Column ' ) .
' Pos ' has instances of several of the standard numeric typeclasses , although
many of the operations throw ' Underflow ' when non - positive values result .
' Pos ' does /not/ have an ' Integral ' instance , because there is no sensible
way to implement ' quotRem ' .
'Pos' stands for /positive integer/. You can also think of it as /position/,
because we use it to represent line and column numbers ('Line' and 'Column').
'Pos' has instances of several of the standard numeric typeclasses, although
many of the operations throw 'Underflow' when non-positive values result.
'Pos' does /not/ have an 'Integral' instance, because there is no sensible
way to implement 'quotRem'.
-}
newtype Pos = Pos Natural
deriving (Data, Eq, Ord)
instance ToNat Pos
where
toNat (Pos n) = n
instance Show Pos
where
showsPrec = posShowsPrec
instance Read Pos
where
readPrec = posReadPrec
|
> > > fromInteger 3 : : Pos
3
> > > fromInteger 0 : : Pos
* * * Exception : arithmetic underflow
> > > 2 + 3 : : Pos
5
> > > 3 - 2 : : Pos
1
> > > 3 - 3 : : Pos
* * * Exception : arithmetic underflow
> > > 2 * 3 : : Pos
6
> > > negate 3 : : Pos
* * * Exception : arithmetic underflow
>>> fromInteger 3 :: Pos
3
>>> fromInteger 0 :: Pos
*** Exception: arithmetic underflow
>>> 2 + 3 :: Pos
5
>>> 3 - 2 :: Pos
1
>>> 3 - 3 :: Pos
*** Exception: arithmetic underflow
>>> 2 * 3 :: Pos
6
>>> negate 3 :: Pos
*** Exception: arithmetic underflow
-}
instance Num Pos
where
fromInteger = Pos . checkForUnderflow . fromInteger
Pos x + Pos y = Pos (x + y)
Pos x - Pos y = Pos (checkForUnderflow (x - y))
Pos x * Pos y = Pos (x * y)
abs = id
signum _ = Pos 1
negate _ = throw Underflow
instance Real Pos
where
toRational (Pos n) = toRational n
|
> > > toEnum 3 : : Pos
3
> > > toEnum 0 : : Pos
* * * Exception : arithmetic underflow
> > > fromEnum ( 3 : : Pos )
3
>>> toEnum 3 :: Pos
3
>>> toEnum 0 :: Pos
*** Exception: arithmetic underflow
>>> fromEnum (3 :: Pos)
3
-}
instance Enum Pos
where
toEnum = Pos . checkForUnderflow . toEnum
fromEnum (Pos n) = fromEnum n
checkForUnderflow :: Natural -> Natural
checkForUnderflow n =
if n == 0 then throw Underflow else n
|
> > > posShowsPrec minPrec 1 " "
" 1 "
> > > posShowsPrec minPrec 42 " "
" 42 "
>>> posShowsPrec minPrec 1 ""
"1"
>>> posShowsPrec minPrec 42 ""
"42"
-}
posShowsPrec :: Int -> Pos -> ShowS
posShowsPrec i (Pos n) =
showsPrec i n
|
> > > readPrec_to_S posReadPrec minPrec " 1 "
[ ( 1 , " " ) ]
> > > readPrec_to_S posReadPrec minPrec " 42 "
[ ( 42 , " " ) ]
> > > readPrec_to_S posReadPrec minPrec " 0 "
[ ]
> > > readPrec_to_S posReadPrec minPrec " -1 "
[ ]
>>> readPrec_to_S posReadPrec minPrec "1"
[(1,"")]
>>> readPrec_to_S posReadPrec minPrec "42"
[(42,"")]
>>> readPrec_to_S posReadPrec minPrec "0"
[]
>>> readPrec_to_S posReadPrec minPrec "-1"
[]
-}
posReadPrec :: ReadPrec Pos
posReadPrec =
Pos <$> mfilter (/= 0) readPrec
class ToNat a
where
toNat :: a -> Natural
newtype Line = Line Pos
deriving (Data, Eq, Ord, Num, Real, Enum, ToNat)
instance Show Line
where
showsPrec i (Line pos) = showsPrec i pos
instance Read Line
where
readPrec = Line <$> readPrec
newtype Column = Column Pos
deriving (Data, Eq, Ord, Num, Real, Enum, ToNat)
instance Show Column
where
showsPrec i (Column pos) = showsPrec i pos
instance Read Column
where
readPrec = Column <$> readPrec
|
1200d4b8d67f963fc07c9ee4e38bb8b410629e60b4273484e34612333a319c0e | esoeylemez/rapid | Rapid.hs | -- |
Copyright : ( c ) 2016
-- License: BSD3
Maintainer : < >
-- Stability: experimental
--
-- This module provides a rapid prototyping suite for GHCi that can be
-- used standalone or integrated into editors. You can hot-reload
-- individual running components as you make changes to their code. It
-- is designed to shorten the development cycle during the development
-- of long-running programs like servers, web applications and
-- interactive user interfaces.
--
-- It can also be used in the context of batch-style programs: Keep
-- resources that are expensive to create in memory and reuse them
-- across module reloads instead of reloading/recomputing them after
-- every code change.
--
-- Technically this package is a safe and convenient wrapper around
-- <-store foreign-store>.
--
-- __Read the "Safety and securty" section before using this module!__
{-# LANGUAGE RankNTypes #-}
module Rapid
( -- * Introduction
-- $intro
-- ** Communication
-- $communication
-- ** Reusing expensive resources
-- $reusing
* * notes
-- $cabal
-- ** Emacs integration
-- $emacs
-- ** Safety and security
-- $safety
-- * Hot code reloading
Rapid,
rapid,
-- * Threads
restart,
restartWith,
start,
startWith,
stop,
-- * Communication
createRef,
deleteRef,
writeRef
)
where
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Exception
import Data.Dynamic
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Word
import Foreign.Store
-- | Handle to the current Rapid state.
data Rapid k =
Rapid {
rLock :: TVar Bool, -- ^ Lock on the current state.
rRefs :: TVar (Map k Dynamic), -- ^ Mutable variables.
rThreads :: TVar (Map k (Async ())) -- ^ Active threads.
}
-- | Cancel the given thread and wait for it to finish.
cancelAndWait :: Async a -> IO ()
cancelAndWait tv = do
cancel tv
() <$ waitCatch tv
-- | Get the value of the mutable variable with the given name. If it
-- does not exist, it is created and initialised with the value returned
-- by the given action.
--
-- Mutable variables should only be used with values that can be
-- garbage-collected, for example communication primitives like
' Control . Concurrent . MVar . MVar ' and ' TVar ' , but also pure run - time
-- information that is expensive to generate, for example the parsed
-- contents of a file.
createRef
:: (Ord k, Typeable a)
=> Rapid k -- ^ Rapid state handle.
-> k -- ^ Name of the mutable variable.
-> IO a -- ^ Action to create.
-> IO a
createRef r k gen =
withRef r k $ \mxd ->
case mxd of
Nothing -> fmap (\x -> (Just (toDyn x), x)) gen
Just xd
| Just x <- fromDynamic xd -> pure (Just xd, x)
| otherwise -> throwIO (userError "createRef: Wrong reference type")
-- | Delete the mutable variable with the given name, if it exists.
deleteRef
:: (Ord k)
=> Rapid k -- ^ Rapid state handle.
-> k -- ^ Name of the mutable variable.
-> IO ()
deleteRef r k =
withRef r k (\_ -> pure (Nothing, ()))
-- | Retrieve the current Rapid state handle, and pass it to the given
-- continuation. If the state handle doesn't exist, it is created. The
key type @k@ is used for naming reloadable services like threads .
--
-- __Warning__: The key type must not change during a session. If you
-- need to change the key type, currently the safest option is to
-- restart GHCi.
--
-- This function uses the
-- <-store foreign-store library>
-- to establish a state handle that survives GHCi reloads and is
-- suitable for hot reloading.
--
The first argument is the ' Store ' index . If you do not use the
-- /foreign-store/ library in your development workflow, just use 0,
-- otherwise use any unused index.
rapid
:: forall k r.
Word32 -- ^ Store index (if in doubt, use 0).
-> (Rapid k -> IO r) -- ^ Action on the Rapid state.
-> IO r
rapid stNum k =
mask $ \unmask ->
lookupStore stNum >>=
maybe (storeAction store create)
(\_ -> readStore store) >>=
pass unmask
where
create =
pure Rapid
<*> newTVarIO False
<*> newTVarIO M.empty
<*> newTVarIO M.empty
pass unmask r = do
atomically $ do
readTVar (rLock r) >>= check . not
writeTVar (rLock r) True
unmask (k r) `finally` atomically (writeTVar (rLock r) False)
store :: Store (Rapid k)
store = Store stNum
-- | Create a thread with the given name that runs the given action.
--
-- The thread is restarted each time an update occurs.
restart
:: (Ord k)
=> Rapid k -- ^ Rapid state handle.
-> k -- ^ Name of the thread.
-> IO () -- ^ Action the thread runs.
-> IO ()
restart = restartWith async
-- | Create a thread with the given name that runs the given action.
--
-- The thread is restarted each time an update occurs.
--
The first argument is the function used to create the thread . It can
-- be used to select between 'async', 'asyncBound' and 'asyncOn'.
restartWith
:: (Ord k)
=> (forall a. IO a -> IO (Async a)) -- ^ Thread creation function.
-> Rapid k -- ^ Rapid state handle.
-> k -- ^ Name of the thread.
-> IO () -- ^ Action the thread runs.
-> IO ()
restartWith myAsync r k action =
withThread r k $ \mtv -> do
mapM_ cancelAndWait mtv
Just <$> myAsync action
-- | Create a thread with the given name that runs the given action.
--
-- When an update occurs and the thread is currently not running, it is
-- started.
start
:: (Ord k)
=> Rapid k -- ^ Rapid state handle.
-> k -- ^ Name of the thread.
-> IO () -- ^ Action the thread runs.
-> IO ()
start = startWith async
-- | Create a thread with the given name that runs the given action.
--
-- When an update occurs and the thread is currently not running, it is
-- started.
--
The first argument is the function used to create the thread . It can
-- be used to select between 'async', 'asyncBound' and 'asyncOn'.
startWith
:: (Ord k)
=> (forall a. IO a -> IO (Async a)) -- ^ Thread creation function.
-> Rapid k -- ^ Rapid state handle.
-> k -- ^ Name of the thread.
-> IO () -- ^ Action the thread runs.
-> IO ()
startWith myAsync r k action =
withThread r k $
maybe (Just <$> myAsync action)
(\tv -> poll tv >>=
maybe (pure (Just tv))
(\_ -> Just <$> myAsync action))
-- | Delete the thread with the given name.
--
-- When an update occurs and the thread is currently running, it is
-- cancelled.
stop :: (Ord k) => Rapid k -> k -> x -> IO ()
stop r k _ =
withThread r k $ \mtv ->
Nothing <$ mapM_ cancelAndWait mtv
-- | Apply the given transform to the reference with the given name.
withRef
:: (Ord k)
=> Rapid k
-> k
-> (Maybe Dynamic -> IO (Maybe Dynamic, a))
-> IO a
withRef r k f = do
(mx, y) <- atomically (M.lookup k <$> readTVar (rRefs r)) >>=
f
atomically $ modifyTVar' (rRefs r) (maybe (M.delete k) (M.insert k) mx)
pure y
-- | Apply the given transform to the thread with the given name.
withThread
:: (Ord k)
=> Rapid k
-> k
-> (Maybe (Async ()) -> IO (Maybe (Async ())))
-> IO ()
withThread r k f =
atomically (M.lookup k <$> readTVar (rThreads r)) >>=
f >>=
atomically . modifyTVar' (rThreads r) . maybe (M.delete k) (M.insert k)
-- | Overwrite the mutable variable with the given name with the value
-- returned by the given action. If the mutable variable does not
-- exist, it is created.
--
-- This function may be used to change the value type of a mutable
-- variable.
writeRef
:: (Ord k, Typeable a)
=> Rapid k -- ^ Rapid state handle.
-> k -- ^ Name of the mutable variable.
-> IO a -- ^ Value action.
-> IO a
writeRef r k gen =
withRef r k $ \_ ->
fmap (\x -> (Just (toDyn x), x)) gen
$ cabal
In general a Cabal project should not have this library as a build - time
dependency . However , in certain environments ( like - based
development ) it may be beneficial to include it in the @.cabal@ file
regardless . A simple solution is to add a flag :
> flag Devel
> default : False
> description : Enable development dependencies
> manual : True
>
> library
> build - depends :
> base > = 4.8 & & < 5 ,
> { - ...
In general a Cabal project should not have this library as a build-time
dependency. However, in certain environments (like Nix-based
development) it may be beneficial to include it in the @.cabal@ file
regardless. A simple solution is to add a flag:
> flag Devel
> default: False
> description: Enable development dependencies
> manual: True
>
> library
> build-depends:
> base >= 4.8 && < 5,
> {- ... -}
> if flag(devel)
> build-depends: rapid
> {- ... -}
Now you can configure your project with @-fdevel@ during development and
have this module available.
-}
$ communication
If you need your background threads to communicate with each other , for
example by using concurrency primitives , some additional support is
required . You can not just create a ' TVar ' within your @update@ action .
It would be a different one for every invocation , so threads that are
restarted would not communicate with already running threads , because
they would use a fresh @TVar@ , while the old threads would still use the
old one .
To solve this , you need to wrap your ' newTVar ' action with ' createRef ' .
The @TVar@ created this way will survive reloads in the same way as
background threads do . In particular , if there is already one from an
older invocation of @update@ , it will be reused :
> import Control . Concurrent . STM
> import Control . Monad
> import Rapid
>
> update =
> rapid 0 $ \r - > do
> mv1 < - createRef r " var1 " newEmptyTMVarIO
> mv2 < - createRef r " var2 " newEmptyTMVarIO
>
> start r " producer " $
> mapM _ ( atomically . putTMVar mv1 ) [ 0 : : Integer .. ]
>
> restart r " consumer " $
> forever . atomically $ do
> x < - takeTMVar mv1
> putTMVar ( x , " blah " )
>
> -- For debugging the update action :
> replicateM _ 3 $
> atomically ( takeTMVar mv2 ) > > = print
You can now change the string in the consumer thread and then
run @update@. You will notice that the numbers in the left component of
the tuples keep increasing even after a reload , while the string in the
right component changes . That means the producer thread was not
restarted , but the consumer thread was . Yet the restarted consumer
thread still refers to the same @TVar@ as before , so it still receives
from the producer .
If you need your background threads to communicate with each other, for
example by using concurrency primitives, some additional support is
required. You cannot just create a 'TVar' within your @update@ action.
It would be a different one for every invocation, so threads that are
restarted would not communicate with already running threads, because
they would use a fresh @TVar@, while the old threads would still use the
old one.
To solve this, you need to wrap your 'newTVar' action with 'createRef'.
The @TVar@ created this way will survive reloads in the same way as
background threads do. In particular, if there is already one from an
older invocation of @update@, it will be reused:
> import Control.Concurrent.STM
> import Control.Monad
> import Rapid
>
> update =
> rapid 0 $ \r -> do
> mv1 <- createRef r "var1" newEmptyTMVarIO
> mv2 <- createRef r "var2" newEmptyTMVarIO
>
> start r "producer" $
> mapM_ (atomically . putTMVar mv1) [0 :: Integer ..]
>
> restart r "consumer" $
> forever . atomically $ do
> x <- takeTMVar mv1
> putTMVar mv2 (x, "blah")
>
> -- For debugging the update action:
> replicateM_ 3 $
> atomically (takeTMVar mv2) >>= print
You can now change the string @"blah"@ in the consumer thread and then
run @update@. You will notice that the numbers in the left component of
the tuples keep increasing even after a reload, while the string in the
right component changes. That means the producer thread was not
restarted, but the consumer thread was. Yet the restarted consumer
thread still refers to the same @TVar@ as before, so it still receives
from the producer.
-}
$ emacs
This library integrates well with
< - mode > ,
particularly with its somewhat hidden
@haskell - process - reload - devel - main@ function .
This function finds your @DevelMain@ module by looking for a buffer
named @DevelMain.hs@ , loads or reloads it in your current project 's
interactive session and then runs @update@. Assuming that you are
already using /haskell - interactive - mode/ all you need to do to use it is
to keep your @DevelMain@ module open in a buffer and type @M - x
haskell - process - reload - devel - main RET@ when you want to hot - reload . You
may want to bind it to a key :
> ( define - key haskell - mode - map ( " C - c m " ) ' haskell - process - reload - devel - main )
Since you will likely always reload the current module before running
@update@ , you can save a few keystrokes by defining a small function
that does both and bind that one to a key instead :
> ( defun my - haskell - run - devel ( )
> " Reloads the current module and then hot - reloads code via DevelMain.update . "
> ( interactive )
> ( haskell - process - load - file )
> ( haskell - process - reload - devel - main ) )
>
> ( define - key haskell - mode - map ( " C - c m " ) ' my - haskell - run - devel )
This library integrates well with
<-mode/manual/latest/Interactive-Haskell.html haskell-interactive-mode>,
particularly with its somewhat hidden
@haskell-process-reload-devel-main@ function.
This function finds your @DevelMain@ module by looking for a buffer
named @DevelMain.hs@, loads or reloads it in your current project's
interactive session and then runs @update@. Assuming that you are
already using /haskell-interactive-mode/ all you need to do to use it is
to keep your @DevelMain@ module open in a buffer and type @M-x
haskell-process-reload-devel-main RET@ when you want to hot-reload. You
may want to bind it to a key:
> (define-key haskell-mode-map (kbd "C-c m") 'haskell-process-reload-devel-main)
Since you will likely always reload the current module before running
@update@, you can save a few keystrokes by defining a small function
that does both and bind that one to a key instead:
> (defun my-haskell-run-devel ()
> "Reloads the current module and then hot-reloads code via DevelMain.update."
> (interactive)
> (haskell-process-load-file)
> (haskell-process-reload-devel-main))
>
> (define-key haskell-mode-map (kbd "C-c m") 'my-haskell-run-devel)
-}
$ intro
While working on a project you may want to have your code running in the
background and restart parts of it as you make changes . The premise of
this introduction is that you already have such a project , for example a
web application , and that you use a persistent GHCi session ( either
standalone or built into your editor ) .
To use this library in your project create a module conventionally named
@DevelMain@ that exports an action conventionally named @update@ :
> module DevelMain ( update ) where
>
> import Rapid
>
> update : : IO ( )
> update =
> rapid 0 $ \r - >
> -- We 'll list our components here shortly .
> pure ( )
The idea is that within a GHCi session you run this @update@ action
whenever you want to reload your project during development . In the
simplest case , like in a web application , your project consists of a
single HTTP server thread that is just restarted each time you reload .
Here is an example using the Snap Framework :
> import qualified Data . Text as T
> import Rapid
> import Snap . Core
> import Snap . Http . Server
>
> update =
> rapid 0 $ \r - >
> restart r " webserver " $
> quickHttpServe ( writeText ( T.pack " Hello world ! " ) )
Once you run @update@ in a GHCi session , a server is started ( port 8000 )
that keeps running in the background , even when you reload modules . The
REPL is fully responsive , so you can continue working . When you want to
apply the changes you have made , you reload the @DevelMain@ module and
run @update@ again . To see this in action , change the text string in
the example , reload the module and then run @update@. Also observe that
nothing is changed until you actually run @update@.
When you want to stop a running background thread , replace ' restart '
within the @update@ action by ' stop ' and run @update@. The action given
to ' stop ' is actually ignored . It only takes the action argument for
your convenience .
You can run multiple threads at the same time and also have threads that
are not restarted during a reload , but are only started and then kept
running :
> import MyProject . MyDatabase
> import MyProject . MyBackgroundWorker
> import MyProject . MyWebServer
> import Rapid
>
> update =
> rapid 0 $ \r - > do
> start r " database " myDatabase
> start r " worker " myBackgroundWorker
> restart r " webserver " myWebServer
Usually you would put ' restart ' in front of the component that you are
currently working on , while using ' start ' with all others .
Note that even though you are working on the code in
@MyProject . MyWebServer@ you are always reloading the @DevelMain@ module .
There is nothing wrong with loading and reloading other modules , but
only this module gives you access to your @update@ action .
While working on a project you may want to have your code running in the
background and restart parts of it as you make changes. The premise of
this introduction is that you already have such a project, for example a
web application, and that you use a persistent GHCi session (either
standalone or built into your editor).
To use this library in your project create a module conventionally named
@DevelMain@ that exports an action conventionally named @update@:
> module DevelMain (update) where
>
> import Rapid
>
> update :: IO ()
> update =
> rapid 0 $ \r ->
> -- We'll list our components here shortly.
> pure ()
The idea is that within a GHCi session you run this @update@ action
whenever you want to reload your project during development. In the
simplest case, like in a web application, your project consists of a
single HTTP server thread that is just restarted each time you reload.
Here is an example using the Snap Framework:
> import qualified Data.Text as T
> import Rapid
> import Snap.Core
> import Snap.Http.Server
>
> update =
> rapid 0 $ \r ->
> restart r "webserver" $
> quickHttpServe (writeText (T.pack "Hello world!"))
Once you run @update@ in a GHCi session, a server is started (port 8000)
that keeps running in the background, even when you reload modules. The
REPL is fully responsive, so you can continue working. When you want to
apply the changes you have made, you reload the @DevelMain@ module and
run @update@ again. To see this in action, change the text string in
the example, reload the module and then run @update@. Also observe that
nothing is changed until you actually run @update@.
When you want to stop a running background thread, replace 'restart'
within the @update@ action by 'stop' and run @update@. The action given
to 'stop' is actually ignored. It only takes the action argument for
your convenience.
You can run multiple threads at the same time and also have threads that
are not restarted during a reload, but are only started and then kept
running:
> import MyProject.MyDatabase
> import MyProject.MyBackgroundWorker
> import MyProject.MyWebServer
> import Rapid
>
> update =
> rapid 0 $ \r -> do
> start r "database" myDatabase
> start r "worker" myBackgroundWorker
> restart r "webserver" myWebServer
Usually you would put 'restart' in front of the component that you are
currently working on, while using 'start' with all others.
Note that even though you are working on the code in
@MyProject.MyWebServer@ you are always reloading the @DevelMain@ module.
There is nothing wrong with loading and reloading other modules, but
only this module gives you access to your @update@ action.
-}
$ reusing
Mutable references as introduced in the previous section can also be
used to shorten the development cycle in the case when an expensive
resource has to be created . As an example imagine that you need to
parse a huge file into a data structure . You can keep the result of
that in memory across reloads . Example with parsing JSON :
> import Control . Exception
> import Data . Aeson
> import qualified Data . ByteString as B
>
> update =
> rapid 0 $ \r - >
> value < - createRef r " file " $
> B.readFile " blah.json " > > =
> either ( throwIO . userError ) pure . >
> -- You can now reuse ' value ' across reloads .
If you want to recreate the value at some point , you can just change
' createRef ' to ' writeRef ' and then run @update@. Keep in mind to change
it back @createRef@ afterward . Use ' deleteRef ' to remove values you no
longer need , so they can be garbage - collected .
Mutable references as introduced in the previous section can also be
used to shorten the development cycle in the case when an expensive
resource has to be created. As an example imagine that you need to
parse a huge file into a data structure. You can keep the result of
that in memory across reloads. Example with parsing JSON:
> import Control.Exception
> import Data.Aeson
> import qualified Data.ByteString as B
>
> update =
> rapid 0 $ \r ->
> value <- createRef r "file" $
> B.readFile "blah.json" >>=
> either (throwIO . userError) pure . eitherDecode
>
> -- You can now reuse 'value' across reloads.
If you want to recreate the value at some point, you can just change
'createRef' to 'writeRef' and then run @update@. Keep in mind to change
it back @createRef@ afterward. Use 'deleteRef' to remove values you no
longer need, so they can be garbage-collected.
-}
$ safety
It 's easy to crash your GHCi session with this library . In order to
prevent that , you must follow these rules :
* Do not change your service name type ( the type argument of ' Rapid ' ,
i.e. the second argument to ' restart ' , ' start ' and ' stop ' ) within a
session . The simplest way to do that is to resist the temptation to
define a custom name type , and just use strings instead . If you do
change the name type , you should restart GHCi .
* Be careful with mutable variable created with ' createRef ' : If the
value type changes ( e.g. constructors or fields were changed ) , the
variable must be recreated , for example by using ' writeRef ' once . This
most likely entails restarting all threads that were using the variable .
Again the safest option is to just restart GHCi .
* If any package in the current environment changes ( especially this
library itself ) , for example by updating a package via @cabal@ or
@stack@ , the @update@ action is likely to crash or go wrong in subtle
ways due to binary incompatibility . If packages change , restart GHCi .
* _ _ This library is a development tool ! Do not even think of using it to hot - reload in a productive environment ! _ _
There are much safer and more appropriate ways to hot - reload code in
production , for example by using a plugin system .
The reason for this unsafety is that the underlying /foreign - store/
library is itself very unsafe in nature and requires that we maintain
binary compatibility . This library hides most of that unsafety , but
still requires that you follow the rules above .
Please take the last rule seriously and never ever use this library in
production ! If something goes wrong during a reload , we do not get a
convenient run - time exception ; we get a memory violation , which can
cause anything from a segfault to a remotely exploitable security hole .
It's easy to crash your GHCi session with this library. In order to
prevent that, you must follow these rules:
* Do not change your service name type (the type argument of 'Rapid',
i.e. the second argument to 'restart', 'start' and 'stop') within a
session. The simplest way to do that is to resist the temptation to
define a custom name type, and just use strings instead. If you do
change the name type, you should restart GHCi.
* Be careful with mutable variable created with 'createRef': If the
value type changes (e.g. constructors or fields were changed), the
variable must be recreated, for example by using 'writeRef' once. This
most likely entails restarting all threads that were using the variable.
Again the safest option is to just restart GHCi.
* If any package in the current environment changes (especially this
library itself), for example by updating a package via @cabal@ or
@stack@, the @update@ action is likely to crash or go wrong in subtle
ways due to binary incompatibility. If packages change, restart GHCi.
* __This library is a development tool! Do not even think of using it to hot-reload in a productive environment!__
There are much safer and more appropriate ways to hot-reload code in
production, for example by using a plugin system.
The reason for this unsafety is that the underlying /foreign-store/
library is itself very unsafe in nature and requires that we maintain
binary compatibility. This library hides most of that unsafety, but
still requires that you follow the rules above.
Please take the last rule seriously and never ever use this library in
production! If something goes wrong during a reload, we do not get a
convenient run-time exception; we get a memory violation, which can
cause anything from a segfault to a remotely exploitable security hole.
-}
| null | https://raw.githubusercontent.com/esoeylemez/rapid/aae24ba82ef9972b10fb3cfd57049d844d521750/Rapid.hs | haskell | |
License: BSD3
Stability: experimental
This module provides a rapid prototyping suite for GHCi that can be
used standalone or integrated into editors. You can hot-reload
individual running components as you make changes to their code. It
is designed to shorten the development cycle during the development
of long-running programs like servers, web applications and
interactive user interfaces.
It can also be used in the context of batch-style programs: Keep
resources that are expensive to create in memory and reuse them
across module reloads instead of reloading/recomputing them after
every code change.
Technically this package is a safe and convenient wrapper around
<-store foreign-store>.
__Read the "Safety and securty" section before using this module!__
# LANGUAGE RankNTypes #
* Introduction
$intro
** Communication
$communication
** Reusing expensive resources
$reusing
$cabal
** Emacs integration
$emacs
** Safety and security
$safety
* Hot code reloading
* Threads
* Communication
| Handle to the current Rapid state.
^ Lock on the current state.
^ Mutable variables.
^ Active threads.
| Cancel the given thread and wait for it to finish.
| Get the value of the mutable variable with the given name. If it
does not exist, it is created and initialised with the value returned
by the given action.
Mutable variables should only be used with values that can be
garbage-collected, for example communication primitives like
information that is expensive to generate, for example the parsed
contents of a file.
^ Rapid state handle.
^ Name of the mutable variable.
^ Action to create.
| Delete the mutable variable with the given name, if it exists.
^ Rapid state handle.
^ Name of the mutable variable.
| Retrieve the current Rapid state handle, and pass it to the given
continuation. If the state handle doesn't exist, it is created. The
__Warning__: The key type must not change during a session. If you
need to change the key type, currently the safest option is to
restart GHCi.
This function uses the
<-store foreign-store library>
to establish a state handle that survives GHCi reloads and is
suitable for hot reloading.
/foreign-store/ library in your development workflow, just use 0,
otherwise use any unused index.
^ Store index (if in doubt, use 0).
^ Action on the Rapid state.
| Create a thread with the given name that runs the given action.
The thread is restarted each time an update occurs.
^ Rapid state handle.
^ Name of the thread.
^ Action the thread runs.
| Create a thread with the given name that runs the given action.
The thread is restarted each time an update occurs.
be used to select between 'async', 'asyncBound' and 'asyncOn'.
^ Thread creation function.
^ Rapid state handle.
^ Name of the thread.
^ Action the thread runs.
| Create a thread with the given name that runs the given action.
When an update occurs and the thread is currently not running, it is
started.
^ Rapid state handle.
^ Name of the thread.
^ Action the thread runs.
| Create a thread with the given name that runs the given action.
When an update occurs and the thread is currently not running, it is
started.
be used to select between 'async', 'asyncBound' and 'asyncOn'.
^ Thread creation function.
^ Rapid state handle.
^ Name of the thread.
^ Action the thread runs.
| Delete the thread with the given name.
When an update occurs and the thread is currently running, it is
cancelled.
| Apply the given transform to the reference with the given name.
| Apply the given transform to the thread with the given name.
| Overwrite the mutable variable with the given name with the value
returned by the given action. If the mutable variable does not
exist, it is created.
This function may be used to change the value type of a mutable
variable.
^ Rapid state handle.
^ Name of the mutable variable.
^ Value action.
...
...
For debugging the update action :
For debugging the update action:
We 'll list our components here shortly .
We'll list our components here shortly.
You can now reuse ' value ' across reloads .
You can now reuse 'value' across reloads. | Copyright : ( c ) 2016
Maintainer : < >
module Rapid
* * notes
Rapid,
rapid,
restart,
restartWith,
start,
startWith,
stop,
createRef,
deleteRef,
writeRef
)
where
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Exception
import Data.Dynamic
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Word
import Foreign.Store
data Rapid k =
Rapid {
}
cancelAndWait :: Async a -> IO ()
cancelAndWait tv = do
cancel tv
() <$ waitCatch tv
' Control . Concurrent . MVar . MVar ' and ' TVar ' , but also pure run - time
createRef
:: (Ord k, Typeable a)
-> IO a
createRef r k gen =
withRef r k $ \mxd ->
case mxd of
Nothing -> fmap (\x -> (Just (toDyn x), x)) gen
Just xd
| Just x <- fromDynamic xd -> pure (Just xd, x)
| otherwise -> throwIO (userError "createRef: Wrong reference type")
deleteRef
:: (Ord k)
-> IO ()
deleteRef r k =
withRef r k (\_ -> pure (Nothing, ()))
key type @k@ is used for naming reloadable services like threads .
The first argument is the ' Store ' index . If you do not use the
rapid
:: forall k r.
-> IO r
rapid stNum k =
mask $ \unmask ->
lookupStore stNum >>=
maybe (storeAction store create)
(\_ -> readStore store) >>=
pass unmask
where
create =
pure Rapid
<*> newTVarIO False
<*> newTVarIO M.empty
<*> newTVarIO M.empty
pass unmask r = do
atomically $ do
readTVar (rLock r) >>= check . not
writeTVar (rLock r) True
unmask (k r) `finally` atomically (writeTVar (rLock r) False)
store :: Store (Rapid k)
store = Store stNum
restart
:: (Ord k)
-> IO ()
restart = restartWith async
The first argument is the function used to create the thread . It can
restartWith
:: (Ord k)
-> IO ()
restartWith myAsync r k action =
withThread r k $ \mtv -> do
mapM_ cancelAndWait mtv
Just <$> myAsync action
start
:: (Ord k)
-> IO ()
start = startWith async
The first argument is the function used to create the thread . It can
startWith
:: (Ord k)
-> IO ()
startWith myAsync r k action =
withThread r k $
maybe (Just <$> myAsync action)
(\tv -> poll tv >>=
maybe (pure (Just tv))
(\_ -> Just <$> myAsync action))
stop :: (Ord k) => Rapid k -> k -> x -> IO ()
stop r k _ =
withThread r k $ \mtv ->
Nothing <$ mapM_ cancelAndWait mtv
withRef
:: (Ord k)
=> Rapid k
-> k
-> (Maybe Dynamic -> IO (Maybe Dynamic, a))
-> IO a
withRef r k f = do
(mx, y) <- atomically (M.lookup k <$> readTVar (rRefs r)) >>=
f
atomically $ modifyTVar' (rRefs r) (maybe (M.delete k) (M.insert k) mx)
pure y
withThread
:: (Ord k)
=> Rapid k
-> k
-> (Maybe (Async ()) -> IO (Maybe (Async ())))
-> IO ()
withThread r k f =
atomically (M.lookup k <$> readTVar (rThreads r)) >>=
f >>=
atomically . modifyTVar' (rThreads r) . maybe (M.delete k) (M.insert k)
writeRef
:: (Ord k, Typeable a)
-> IO a
writeRef r k gen =
withRef r k $ \_ ->
fmap (\x -> (Just (toDyn x), x)) gen
$ cabal
In general a Cabal project should not have this library as a build - time
dependency . However , in certain environments ( like - based
development ) it may be beneficial to include it in the @.cabal@ file
regardless . A simple solution is to add a flag :
> flag Devel
> default : False
> description : Enable development dependencies
> manual : True
>
> library
> build - depends :
> base > = 4.8 & & < 5 ,
> { - ...
In general a Cabal project should not have this library as a build-time
dependency. However, in certain environments (like Nix-based
development) it may be beneficial to include it in the @.cabal@ file
regardless. A simple solution is to add a flag:
> flag Devel
> default: False
> description: Enable development dependencies
> manual: True
>
> library
> build-depends:
> base >= 4.8 && < 5,
> if flag(devel)
> build-depends: rapid
Now you can configure your project with @-fdevel@ during development and
have this module available.
-}
$ communication
If you need your background threads to communicate with each other , for
example by using concurrency primitives , some additional support is
required . You can not just create a ' TVar ' within your @update@ action .
It would be a different one for every invocation , so threads that are
restarted would not communicate with already running threads , because
they would use a fresh @TVar@ , while the old threads would still use the
old one .
To solve this , you need to wrap your ' newTVar ' action with ' createRef ' .
The @TVar@ created this way will survive reloads in the same way as
background threads do . In particular , if there is already one from an
older invocation of @update@ , it will be reused :
> import Control . Concurrent . STM
> import Control . Monad
> import Rapid
>
> update =
> rapid 0 $ \r - > do
> mv1 < - createRef r " var1 " newEmptyTMVarIO
> mv2 < - createRef r " var2 " newEmptyTMVarIO
>
> start r " producer " $
> mapM _ ( atomically . putTMVar mv1 ) [ 0 : : Integer .. ]
>
> restart r " consumer " $
> forever . atomically $ do
> x < - takeTMVar mv1
> putTMVar ( x , " blah " )
>
> replicateM _ 3 $
> atomically ( takeTMVar mv2 ) > > = print
You can now change the string in the consumer thread and then
run @update@. You will notice that the numbers in the left component of
the tuples keep increasing even after a reload , while the string in the
right component changes . That means the producer thread was not
restarted , but the consumer thread was . Yet the restarted consumer
thread still refers to the same @TVar@ as before , so it still receives
from the producer .
If you need your background threads to communicate with each other, for
example by using concurrency primitives, some additional support is
required. You cannot just create a 'TVar' within your @update@ action.
It would be a different one for every invocation, so threads that are
restarted would not communicate with already running threads, because
they would use a fresh @TVar@, while the old threads would still use the
old one.
To solve this, you need to wrap your 'newTVar' action with 'createRef'.
The @TVar@ created this way will survive reloads in the same way as
background threads do. In particular, if there is already one from an
older invocation of @update@, it will be reused:
> import Control.Concurrent.STM
> import Control.Monad
> import Rapid
>
> update =
> rapid 0 $ \r -> do
> mv1 <- createRef r "var1" newEmptyTMVarIO
> mv2 <- createRef r "var2" newEmptyTMVarIO
>
> start r "producer" $
> mapM_ (atomically . putTMVar mv1) [0 :: Integer ..]
>
> restart r "consumer" $
> forever . atomically $ do
> x <- takeTMVar mv1
> putTMVar mv2 (x, "blah")
>
> replicateM_ 3 $
> atomically (takeTMVar mv2) >>= print
You can now change the string @"blah"@ in the consumer thread and then
run @update@. You will notice that the numbers in the left component of
the tuples keep increasing even after a reload, while the string in the
right component changes. That means the producer thread was not
restarted, but the consumer thread was. Yet the restarted consumer
thread still refers to the same @TVar@ as before, so it still receives
from the producer.
-}
$ emacs
This library integrates well with
< - mode > ,
particularly with its somewhat hidden
@haskell - process - reload - devel - main@ function .
This function finds your @DevelMain@ module by looking for a buffer
named @DevelMain.hs@ , loads or reloads it in your current project 's
interactive session and then runs @update@. Assuming that you are
already using /haskell - interactive - mode/ all you need to do to use it is
to keep your @DevelMain@ module open in a buffer and type @M - x
haskell - process - reload - devel - main RET@ when you want to hot - reload . You
may want to bind it to a key :
> ( define - key haskell - mode - map ( " C - c m " ) ' haskell - process - reload - devel - main )
Since you will likely always reload the current module before running
@update@ , you can save a few keystrokes by defining a small function
that does both and bind that one to a key instead :
> ( defun my - haskell - run - devel ( )
> " Reloads the current module and then hot - reloads code via DevelMain.update . "
> ( interactive )
> ( haskell - process - load - file )
> ( haskell - process - reload - devel - main ) )
>
> ( define - key haskell - mode - map ( " C - c m " ) ' my - haskell - run - devel )
This library integrates well with
<-mode/manual/latest/Interactive-Haskell.html haskell-interactive-mode>,
particularly with its somewhat hidden
@haskell-process-reload-devel-main@ function.
This function finds your @DevelMain@ module by looking for a buffer
named @DevelMain.hs@, loads or reloads it in your current project's
interactive session and then runs @update@. Assuming that you are
already using /haskell-interactive-mode/ all you need to do to use it is
to keep your @DevelMain@ module open in a buffer and type @M-x
haskell-process-reload-devel-main RET@ when you want to hot-reload. You
may want to bind it to a key:
> (define-key haskell-mode-map (kbd "C-c m") 'haskell-process-reload-devel-main)
Since you will likely always reload the current module before running
@update@, you can save a few keystrokes by defining a small function
that does both and bind that one to a key instead:
> (defun my-haskell-run-devel ()
> "Reloads the current module and then hot-reloads code via DevelMain.update."
> (interactive)
> (haskell-process-load-file)
> (haskell-process-reload-devel-main))
>
> (define-key haskell-mode-map (kbd "C-c m") 'my-haskell-run-devel)
-}
$ intro
While working on a project you may want to have your code running in the
background and restart parts of it as you make changes . The premise of
this introduction is that you already have such a project , for example a
web application , and that you use a persistent GHCi session ( either
standalone or built into your editor ) .
To use this library in your project create a module conventionally named
@DevelMain@ that exports an action conventionally named @update@ :
> module DevelMain ( update ) where
>
> import Rapid
>
> update : : IO ( )
> update =
> rapid 0 $ \r - >
> pure ( )
The idea is that within a GHCi session you run this @update@ action
whenever you want to reload your project during development . In the
simplest case , like in a web application , your project consists of a
single HTTP server thread that is just restarted each time you reload .
Here is an example using the Snap Framework :
> import qualified Data . Text as T
> import Rapid
> import Snap . Core
> import Snap . Http . Server
>
> update =
> rapid 0 $ \r - >
> restart r " webserver " $
> quickHttpServe ( writeText ( T.pack " Hello world ! " ) )
Once you run @update@ in a GHCi session , a server is started ( port 8000 )
that keeps running in the background , even when you reload modules . The
REPL is fully responsive , so you can continue working . When you want to
apply the changes you have made , you reload the @DevelMain@ module and
run @update@ again . To see this in action , change the text string in
the example , reload the module and then run @update@. Also observe that
nothing is changed until you actually run @update@.
When you want to stop a running background thread , replace ' restart '
within the @update@ action by ' stop ' and run @update@. The action given
to ' stop ' is actually ignored . It only takes the action argument for
your convenience .
You can run multiple threads at the same time and also have threads that
are not restarted during a reload , but are only started and then kept
running :
> import MyProject . MyDatabase
> import MyProject . MyBackgroundWorker
> import MyProject . MyWebServer
> import Rapid
>
> update =
> rapid 0 $ \r - > do
> start r " database " myDatabase
> start r " worker " myBackgroundWorker
> restart r " webserver " myWebServer
Usually you would put ' restart ' in front of the component that you are
currently working on , while using ' start ' with all others .
Note that even though you are working on the code in
@MyProject . MyWebServer@ you are always reloading the @DevelMain@ module .
There is nothing wrong with loading and reloading other modules , but
only this module gives you access to your @update@ action .
While working on a project you may want to have your code running in the
background and restart parts of it as you make changes. The premise of
this introduction is that you already have such a project, for example a
web application, and that you use a persistent GHCi session (either
standalone or built into your editor).
To use this library in your project create a module conventionally named
@DevelMain@ that exports an action conventionally named @update@:
> module DevelMain (update) where
>
> import Rapid
>
> update :: IO ()
> update =
> rapid 0 $ \r ->
> pure ()
The idea is that within a GHCi session you run this @update@ action
whenever you want to reload your project during development. In the
simplest case, like in a web application, your project consists of a
single HTTP server thread that is just restarted each time you reload.
Here is an example using the Snap Framework:
> import qualified Data.Text as T
> import Rapid
> import Snap.Core
> import Snap.Http.Server
>
> update =
> rapid 0 $ \r ->
> restart r "webserver" $
> quickHttpServe (writeText (T.pack "Hello world!"))
Once you run @update@ in a GHCi session, a server is started (port 8000)
that keeps running in the background, even when you reload modules. The
REPL is fully responsive, so you can continue working. When you want to
apply the changes you have made, you reload the @DevelMain@ module and
run @update@ again. To see this in action, change the text string in
the example, reload the module and then run @update@. Also observe that
nothing is changed until you actually run @update@.
When you want to stop a running background thread, replace 'restart'
within the @update@ action by 'stop' and run @update@. The action given
to 'stop' is actually ignored. It only takes the action argument for
your convenience.
You can run multiple threads at the same time and also have threads that
are not restarted during a reload, but are only started and then kept
running:
> import MyProject.MyDatabase
> import MyProject.MyBackgroundWorker
> import MyProject.MyWebServer
> import Rapid
>
> update =
> rapid 0 $ \r -> do
> start r "database" myDatabase
> start r "worker" myBackgroundWorker
> restart r "webserver" myWebServer
Usually you would put 'restart' in front of the component that you are
currently working on, while using 'start' with all others.
Note that even though you are working on the code in
@MyProject.MyWebServer@ you are always reloading the @DevelMain@ module.
There is nothing wrong with loading and reloading other modules, but
only this module gives you access to your @update@ action.
-}
$ reusing
Mutable references as introduced in the previous section can also be
used to shorten the development cycle in the case when an expensive
resource has to be created . As an example imagine that you need to
parse a huge file into a data structure . You can keep the result of
that in memory across reloads . Example with parsing JSON :
> import Control . Exception
> import Data . Aeson
> import qualified Data . ByteString as B
>
> update =
> rapid 0 $ \r - >
> value < - createRef r " file " $
> B.readFile " blah.json " > > =
> either ( throwIO . userError ) pure . >
If you want to recreate the value at some point , you can just change
' createRef ' to ' writeRef ' and then run @update@. Keep in mind to change
it back @createRef@ afterward . Use ' deleteRef ' to remove values you no
longer need , so they can be garbage - collected .
Mutable references as introduced in the previous section can also be
used to shorten the development cycle in the case when an expensive
resource has to be created. As an example imagine that you need to
parse a huge file into a data structure. You can keep the result of
that in memory across reloads. Example with parsing JSON:
> import Control.Exception
> import Data.Aeson
> import qualified Data.ByteString as B
>
> update =
> rapid 0 $ \r ->
> value <- createRef r "file" $
> B.readFile "blah.json" >>=
> either (throwIO . userError) pure . eitherDecode
>
If you want to recreate the value at some point, you can just change
'createRef' to 'writeRef' and then run @update@. Keep in mind to change
it back @createRef@ afterward. Use 'deleteRef' to remove values you no
longer need, so they can be garbage-collected.
-}
$ safety
It 's easy to crash your GHCi session with this library . In order to
prevent that , you must follow these rules :
* Do not change your service name type ( the type argument of ' Rapid ' ,
i.e. the second argument to ' restart ' , ' start ' and ' stop ' ) within a
session . The simplest way to do that is to resist the temptation to
define a custom name type , and just use strings instead . If you do
change the name type , you should restart GHCi .
* Be careful with mutable variable created with ' createRef ' : If the
value type changes ( e.g. constructors or fields were changed ) , the
variable must be recreated , for example by using ' writeRef ' once . This
most likely entails restarting all threads that were using the variable .
Again the safest option is to just restart GHCi .
* If any package in the current environment changes ( especially this
library itself ) , for example by updating a package via @cabal@ or
@stack@ , the @update@ action is likely to crash or go wrong in subtle
ways due to binary incompatibility . If packages change , restart GHCi .
* _ _ This library is a development tool ! Do not even think of using it to hot - reload in a productive environment ! _ _
There are much safer and more appropriate ways to hot - reload code in
production , for example by using a plugin system .
The reason for this unsafety is that the underlying /foreign - store/
library is itself very unsafe in nature and requires that we maintain
binary compatibility . This library hides most of that unsafety , but
still requires that you follow the rules above .
Please take the last rule seriously and never ever use this library in
production ! If something goes wrong during a reload , we do not get a
convenient run - time exception ; we get a memory violation , which can
cause anything from a segfault to a remotely exploitable security hole .
It's easy to crash your GHCi session with this library. In order to
prevent that, you must follow these rules:
* Do not change your service name type (the type argument of 'Rapid',
i.e. the second argument to 'restart', 'start' and 'stop') within a
session. The simplest way to do that is to resist the temptation to
define a custom name type, and just use strings instead. If you do
change the name type, you should restart GHCi.
* Be careful with mutable variable created with 'createRef': If the
value type changes (e.g. constructors or fields were changed), the
variable must be recreated, for example by using 'writeRef' once. This
most likely entails restarting all threads that were using the variable.
Again the safest option is to just restart GHCi.
* If any package in the current environment changes (especially this
library itself), for example by updating a package via @cabal@ or
@stack@, the @update@ action is likely to crash or go wrong in subtle
ways due to binary incompatibility. If packages change, restart GHCi.
* __This library is a development tool! Do not even think of using it to hot-reload in a productive environment!__
There are much safer and more appropriate ways to hot-reload code in
production, for example by using a plugin system.
The reason for this unsafety is that the underlying /foreign-store/
library is itself very unsafe in nature and requires that we maintain
binary compatibility. This library hides most of that unsafety, but
still requires that you follow the rules above.
Please take the last rule seriously and never ever use this library in
production! If something goes wrong during a reload, we do not get a
convenient run-time exception; we get a memory violation, which can
cause anything from a segfault to a remotely exploitable security hole.
-}
|
d8c0588556d27b88043af14b6d0878bb66fe908509c6f255bb6b7a5cca7b221b | aryx/yacfe | oassoc_cache.ml | open Common
open Oassoc
open Oassocb
open Osetb
todo : gather stat of use per key , so when flush , try keep
* entries that are used above a certain threshold , and if after
* this step , there is still too much , then erase also those keys .
*
* todo : limit number of entries , and erase all ( then better do a ltu )
*
* todo : another cache that behave as in lfs1 ,
* every 100 operation do a flush
*
* todo : choose between oassocb and oassoch ?
*
* Also take care that must often redefine all function in the original
* oassoc.ml because if some methods are not redefined , for instance
* # clear , then if do wrapper over a oassocdbm , then even if oassocdbm
* redefine # clear , it will not be called , but instead the default
* method will be called that internally will call another method .
* So better delegate all the methods and override even the method
* with a default definition .
*
* In the same way sometimes an exn can occur at weird time . When
* we add an element , sometimes this may raise an exn such as Out_of_memory ,
* but as we do nt add directly but only at flush time , the exn
* may happen far later the user added something in this oassoc .
* Also in the case of Out_of_memory , even if the entry is not
* added in the wrapped , it will still be present in the cache
* and so the next flush will still generate an exn that again
* may not be cached . So for the moment if Out_of_memory then
* do something special and erase the entry in the cache .
* entries that are used above a certain threshold, and if after
* this step, there is still too much, then erase also those keys.
*
* todo: limit number of entries, and erase all (then better do a ltu)
*
* todo: another cache that behave as in lfs1,
* every 100 operation do a flush
*
* todo: choose between oassocb and oassoch ?
*
* Also take care that must often redefine all function in the original
* oassoc.ml because if some methods are not redefined, for instance
* #clear, then if do wrapper over a oassocdbm, then even if oassocdbm
* redefine #clear, it will not be called, but instead the default
* method will be called that internally will call another method.
* So better delegate all the methods and override even the method
* with a default definition.
*
* In the same way sometimes an exn can occur at weird time. When
* we add an element, sometimes this may raise an exn such as Out_of_memory,
* but as we dont add directly but only at flush time, the exn
* may happen far later the user added something in this oassoc.
* Also in the case of Out_of_memory, even if the entry is not
* added in the wrapped, it will still be present in the cache
* and so the next flush will still generate an exn that again
* may not be cached. So for the moment if Out_of_memory then
* do something special and erase the entry in the cache.
*)
(* !!take care!!: this class has side effect, not a pure oassoc *)
(* can not make it pure, cos the assoc have side effect on the cache *)
class ['a,'b] oassoc_buffer max cached =
object(o)
inherit ['a,'b] oassoc
val counter = ref 0
val cache = ref (new oassocb [])
val dirty = ref (new osetb Set_poly.empty)
val wrapped = ref cached
method private myflush =
let has_a_raised = ref false in
!dirty#iter (fun k ->
try
wrapped := !wrapped#add (k, !cache#assoc k)
with Out_of_memory ->
pr2 "PBBBBBB: Out_of_memory in oassoc_buffer, but still empty cache";
has_a_raised := true;
);
dirty := (new osetb Set_poly.empty);
cache := (new oassocb []);
counter := 0;
if !has_a_raised then raise Out_of_memory
method misc_op_hook2 = o#myflush
method empty =
raise Todo
what happens in k is already present ? or if add multiple times
* the same k ? cache is a oassocb and so the previous binding is
* still there , but dirty is a set , and in we iter based
* on dirty so we will flush only the last ' k ' in the cache .
* the same k ? cache is a oassocb and so the previous binding is
* still there, but dirty is a set, and in myflush we iter based
* on dirty so we will flush only the last 'k' in the cache.
*)
method add (k,v) =
cache := !cache#add (k,v);
dirty := !dirty#add k;
incr counter;
if !counter > max then o#myflush;
o
method iter f =
o#myflush; (* bugfix: have to flush !!! *)
!wrapped#iter f
method keys =
o#myflush; (* bugfix: have to flush !!! *)
!wrapped#keys
method clear =
o#myflush; (* bugfix: have to flush !!! *)
!wrapped#clear
method length =
o#myflush;
!wrapped#length
method view =
raise Todo
method del (k,v) =
cache := !cache#del (k,v);
TODO as for , do a try over wrapped
wrapped := !wrapped#del (k,v);
dirty := !dirty#del k;
o
method mem e = raise Todo
method null = raise Todo
method assoc k =
try !cache#assoc k
with Not_found ->
(* may launch Not_found, but this time, dont catch it *)
let v = !wrapped#assoc k in
begin
cache := !cache#add (k,v);
(* otherwise can use too much mem *)
incr counter;
if !counter > max then o#myflush;
v
end
method delkey k =
cache := !cache#delkey k;
(* sometimes have not yet flushed, so may not be yet in, (could
* also flush in place of doing try).
*
* TODO would be better to see if was in cache (in case mean that
* perhaps not flushed and do try and in other case just cos del
* (without try) cos forcement flushed ou was an error *)
begin
try wrapped := !wrapped#delkey k
with Not_found -> ()
end;
dirty := !dirty#del k;
o
end
class [ ' a,'b ] oassoc_cache cache cached max =
object(o )
inherit [ ' a,'b ] oassoc
val full = ref 0
val max = = cache
val cached = cached
val lru = TODO
val data = Hashtbl.create 100
method empty = raise Todo
method add ( k , v ) = ( Hashtbl.add data k v ; o )
method iter f = cached#iter f
method view = raise Todo
method del ( k , v ) = ( cache#del ( k , v ) ; cached#del ( k , v ) ; o )
method mem e = raise Todo
method null = raise Todo
method assoc k = Hashtbl.find data k
method ( ( k , v ) ; cached#del ( k , v ) ; o )
end
class ['a,'b] oassoc_cache cache cached max =
object(o)
inherit ['a,'b] oassoc
val full = ref 0
val max = max
val cache = cache
val cached = cached
val lru = TODO
val data = Hashtbl.create 100
method empty = raise Todo
method add (k,v) = (Hashtbl.add data k v; o)
method iter f = cached#iter f
method view = raise Todo
method del (k,v) = (cache#del (k,v); cached#del (k,v); o)
method mem e = raise Todo
method null = raise Todo
method assoc k = Hashtbl.find data k
method delkey k = (cache#delkey (k,v); cached#del (k,v); o)
end
*)
| null | https://raw.githubusercontent.com/aryx/yacfe/86a4994822abca03ec9e03f1a7e60eca66db0a08/commons_ocollection/oassoc_cache.ml | ocaml | !!take care!!: this class has side effect, not a pure oassoc
can not make it pure, cos the assoc have side effect on the cache
bugfix: have to flush !!!
bugfix: have to flush !!!
bugfix: have to flush !!!
may launch Not_found, but this time, dont catch it
otherwise can use too much mem
sometimes have not yet flushed, so may not be yet in, (could
* also flush in place of doing try).
*
* TODO would be better to see if was in cache (in case mean that
* perhaps not flushed and do try and in other case just cos del
* (without try) cos forcement flushed ou was an error | open Common
open Oassoc
open Oassocb
open Osetb
todo : gather stat of use per key , so when flush , try keep
* entries that are used above a certain threshold , and if after
* this step , there is still too much , then erase also those keys .
*
* todo : limit number of entries , and erase all ( then better do a ltu )
*
* todo : another cache that behave as in lfs1 ,
* every 100 operation do a flush
*
* todo : choose between oassocb and oassoch ?
*
* Also take care that must often redefine all function in the original
* oassoc.ml because if some methods are not redefined , for instance
* # clear , then if do wrapper over a oassocdbm , then even if oassocdbm
* redefine # clear , it will not be called , but instead the default
* method will be called that internally will call another method .
* So better delegate all the methods and override even the method
* with a default definition .
*
* In the same way sometimes an exn can occur at weird time . When
* we add an element , sometimes this may raise an exn such as Out_of_memory ,
* but as we do nt add directly but only at flush time , the exn
* may happen far later the user added something in this oassoc .
* Also in the case of Out_of_memory , even if the entry is not
* added in the wrapped , it will still be present in the cache
* and so the next flush will still generate an exn that again
* may not be cached . So for the moment if Out_of_memory then
* do something special and erase the entry in the cache .
* entries that are used above a certain threshold, and if after
* this step, there is still too much, then erase also those keys.
*
* todo: limit number of entries, and erase all (then better do a ltu)
*
* todo: another cache that behave as in lfs1,
* every 100 operation do a flush
*
* todo: choose between oassocb and oassoch ?
*
* Also take care that must often redefine all function in the original
* oassoc.ml because if some methods are not redefined, for instance
* #clear, then if do wrapper over a oassocdbm, then even if oassocdbm
* redefine #clear, it will not be called, but instead the default
* method will be called that internally will call another method.
* So better delegate all the methods and override even the method
* with a default definition.
*
* In the same way sometimes an exn can occur at weird time. When
* we add an element, sometimes this may raise an exn such as Out_of_memory,
* but as we dont add directly but only at flush time, the exn
* may happen far later the user added something in this oassoc.
* Also in the case of Out_of_memory, even if the entry is not
* added in the wrapped, it will still be present in the cache
* and so the next flush will still generate an exn that again
* may not be cached. So for the moment if Out_of_memory then
* do something special and erase the entry in the cache.
*)
class ['a,'b] oassoc_buffer max cached =
object(o)
inherit ['a,'b] oassoc
val counter = ref 0
val cache = ref (new oassocb [])
val dirty = ref (new osetb Set_poly.empty)
val wrapped = ref cached
method private myflush =
let has_a_raised = ref false in
!dirty#iter (fun k ->
try
wrapped := !wrapped#add (k, !cache#assoc k)
with Out_of_memory ->
pr2 "PBBBBBB: Out_of_memory in oassoc_buffer, but still empty cache";
has_a_raised := true;
);
dirty := (new osetb Set_poly.empty);
cache := (new oassocb []);
counter := 0;
if !has_a_raised then raise Out_of_memory
method misc_op_hook2 = o#myflush
method empty =
raise Todo
what happens in k is already present ? or if add multiple times
* the same k ? cache is a oassocb and so the previous binding is
* still there , but dirty is a set , and in we iter based
* on dirty so we will flush only the last ' k ' in the cache .
* the same k ? cache is a oassocb and so the previous binding is
* still there, but dirty is a set, and in myflush we iter based
* on dirty so we will flush only the last 'k' in the cache.
*)
method add (k,v) =
cache := !cache#add (k,v);
dirty := !dirty#add k;
incr counter;
if !counter > max then o#myflush;
o
method iter f =
!wrapped#iter f
method keys =
!wrapped#keys
method clear =
!wrapped#clear
method length =
o#myflush;
!wrapped#length
method view =
raise Todo
method del (k,v) =
cache := !cache#del (k,v);
TODO as for , do a try over wrapped
wrapped := !wrapped#del (k,v);
dirty := !dirty#del k;
o
method mem e = raise Todo
method null = raise Todo
method assoc k =
try !cache#assoc k
with Not_found ->
let v = !wrapped#assoc k in
begin
cache := !cache#add (k,v);
incr counter;
if !counter > max then o#myflush;
v
end
method delkey k =
cache := !cache#delkey k;
begin
try wrapped := !wrapped#delkey k
with Not_found -> ()
end;
dirty := !dirty#del k;
o
end
class [ ' a,'b ] oassoc_cache cache cached max =
object(o )
inherit [ ' a,'b ] oassoc
val full = ref 0
val max = = cache
val cached = cached
val lru = TODO
val data = Hashtbl.create 100
method empty = raise Todo
method add ( k , v ) = ( Hashtbl.add data k v ; o )
method iter f = cached#iter f
method view = raise Todo
method del ( k , v ) = ( cache#del ( k , v ) ; cached#del ( k , v ) ; o )
method mem e = raise Todo
method null = raise Todo
method assoc k = Hashtbl.find data k
method ( ( k , v ) ; cached#del ( k , v ) ; o )
end
class ['a,'b] oassoc_cache cache cached max =
object(o)
inherit ['a,'b] oassoc
val full = ref 0
val max = max
val cache = cache
val cached = cached
val lru = TODO
val data = Hashtbl.create 100
method empty = raise Todo
method add (k,v) = (Hashtbl.add data k v; o)
method iter f = cached#iter f
method view = raise Todo
method del (k,v) = (cache#del (k,v); cached#del (k,v); o)
method mem e = raise Todo
method null = raise Todo
method assoc k = Hashtbl.find data k
method delkey k = (cache#delkey (k,v); cached#del (k,v); o)
end
*)
|
9b04fcb418ba37bbfdb0e080eb2fe267b4f5d7a7b495facf2954d4696917b853 | jtdaugherty/tracy | Local.hs | {-# LANGUAGE BangPatterns #-}
module Tracy.RenderManagers.Local
( localRenderManager
)
where
import Control.Applicative
import Control.Concurrent.Chan
import Control.Lens
import Control.Monad
import qualified Data.Map as M
import qualified Data.Vector as V
import System.Random.MWC
import Tracy.Types
import Tracy.SceneBuilder
import Tracy.Samplers
import Tracy.ChunkRender
localNodeName :: String
localNodeName = "<local>"
localSetSceneAndRender :: Chan JobRequest -> Chan (String, JobResponse) -> RenderConfig
-> SceneDesc -> ImageGroup -> MeshGroup -> SampleData -> M.Map Int [V.Vector Int]
-> IO ()
localSetSceneAndRender jobReq jobResp cfg sDesc ig mg sampleData sampleIndexMap = do
let processRequests builtScene = do
let baseWorld = builtScene^.sceneWorld
shadowWorld = case cfg^.forceShadows of
Nothing -> baseWorld
Just v -> baseWorld & worldShadows .~ v
scene = builtScene & sceneWorld .~ shadowWorld
tracer = builtScene^.sceneTracer
ev <- readChan jobReq
case ev of
RenderRequest rowRange sampleRange@(sa, sb) -> do
let Row startRow = fst rowRange
!sampleIndices = sampleIndexMap M.! startRow
sc = length [sa..sb]
ch <- renderChunk cfg scene tracer sampleData sampleIndices sampleRange rowRange
writeChan jobResp (localNodeName, ChunkFinished rowRange (Count sc) ch)
processRequests builtScene
FrameFinished -> writeChan jobResp (localNodeName, JobAck) >> return True
RenderFinished -> writeChan jobResp (localNodeName, JobAck) >> return False
_ -> do
writeChan jobResp ( localNodeName
, JobError "Expected RenderRequest or RenderFinished, got unexpected event"
)
return False
processFrames = do
ev <- readChan jobReq
case ev of
SetFrame fn -> do
case sceneFromDesc sDesc ig mg fn of
Right s -> do
writeChan jobResp (localNodeName, SetFrameAck)
continue <- processRequests s
when continue processFrames
Left e -> writeChan jobResp ( localNodeName
, JobError $ "Could not create scene from description for frame " ++ (show fn) ++ ": " ++ e
)
RenderFinished -> writeChan jobResp (localNodeName, JobAck)
_ -> writeChan jobResp ( localNodeName
, JobError "Unexpected request; expected SetFrame!"
)
processFrames
localRenderManager :: Chan JobRequest -> Chan (String, JobResponse) -> IO ()
localRenderManager jobReq jobResp = do
let waitForJob = do
reqEv <- readChan jobReq
case reqEv of
SetScene cfg sDesc ig mg seedV rowRanges -> do
NOTE : this creates a " bogus " scene for frame 1 even
-- though we won't use this frame (necessarily). This
-- is just so we can get access to the samplers and
-- other details that will not (or should not) change
-- per frame.
case sceneFromDesc sDesc ig mg (Frame 1) of
Right s -> do
let pxSampler = s^.sceneWorld.viewPlane.pixelSampler
sqSampler = correlatedMultiJittered
diskSampler = s^.sceneCamera.cameraData.lensSampler
theNumSets = fromEnum $ s^.sceneWorld.viewPlane.hres
seed = toSeed seedV
rng <- restore seed
-- Generate sample data for square and disk samplers
pSamplesVec <- V.generateM theNumSets $ const $ runSampler pxSampler rng (cfg^.sampleRoot)
sSamplesVec <- V.generateM theNumSets $ const $ runSampler sqSampler rng (cfg^.sampleRoot)
dSamplesVec <- V.generateM theNumSets $ const $ runSampler diskSampler rng (cfg^.sampleRoot)
oSamplesVec <- V.generateM theNumSets $ const $ runSampler sqSampler rng (cfg^.sampleRoot)
let sampleData = SampleData theNumSets pSamplesVec sSamplesVec dSamplesVec oSamplesVec
sampleIndexMap <- M.fromList <$>
(forM rowRanges $ \(Row startRow, Row endRow) ->
(,) <$> (pure startRow) <*>
(replicateM (endRow-startRow+1) $
V.replicateM (fromEnum $ s^.sceneWorld.viewPlane.hres) $
uniformR (0, sampleData^.numSets - 1) rng
)
)
writeChan jobResp (localNodeName, SetSceneAck)
localSetSceneAndRender jobReq jobResp cfg sDesc ig mg sampleData sampleIndexMap
Left e -> writeChan jobResp (localNodeName, JobError e)
waitForJob
Shutdown -> do
writeChan jobResp (localNodeName, JobAck)
RenderFinished -> writeChan jobResp (localNodeName, JobAck)
FrameFinished -> writeChan jobResp (localNodeName, JobError "Expected SetScene or Shutdown, got FrameFinished")
SetFrame _ -> writeChan jobResp (localNodeName, JobError "Expected SetScene or Shutdown, got SetFrame")
_ -> writeChan jobResp (localNodeName, JobError "Expected SetScene or Shutdown, got unexpected event")
waitForJob
| null | https://raw.githubusercontent.com/jtdaugherty/tracy/ad36ea16a3b9cda5071ca72374d6e1c1b415d520/src/Tracy/RenderManagers/Local.hs | haskell | # LANGUAGE BangPatterns #
though we won't use this frame (necessarily). This
is just so we can get access to the samplers and
other details that will not (or should not) change
per frame.
Generate sample data for square and disk samplers | module Tracy.RenderManagers.Local
( localRenderManager
)
where
import Control.Applicative
import Control.Concurrent.Chan
import Control.Lens
import Control.Monad
import qualified Data.Map as M
import qualified Data.Vector as V
import System.Random.MWC
import Tracy.Types
import Tracy.SceneBuilder
import Tracy.Samplers
import Tracy.ChunkRender
localNodeName :: String
localNodeName = "<local>"
localSetSceneAndRender :: Chan JobRequest -> Chan (String, JobResponse) -> RenderConfig
-> SceneDesc -> ImageGroup -> MeshGroup -> SampleData -> M.Map Int [V.Vector Int]
-> IO ()
localSetSceneAndRender jobReq jobResp cfg sDesc ig mg sampleData sampleIndexMap = do
let processRequests builtScene = do
let baseWorld = builtScene^.sceneWorld
shadowWorld = case cfg^.forceShadows of
Nothing -> baseWorld
Just v -> baseWorld & worldShadows .~ v
scene = builtScene & sceneWorld .~ shadowWorld
tracer = builtScene^.sceneTracer
ev <- readChan jobReq
case ev of
RenderRequest rowRange sampleRange@(sa, sb) -> do
let Row startRow = fst rowRange
!sampleIndices = sampleIndexMap M.! startRow
sc = length [sa..sb]
ch <- renderChunk cfg scene tracer sampleData sampleIndices sampleRange rowRange
writeChan jobResp (localNodeName, ChunkFinished rowRange (Count sc) ch)
processRequests builtScene
FrameFinished -> writeChan jobResp (localNodeName, JobAck) >> return True
RenderFinished -> writeChan jobResp (localNodeName, JobAck) >> return False
_ -> do
writeChan jobResp ( localNodeName
, JobError "Expected RenderRequest or RenderFinished, got unexpected event"
)
return False
processFrames = do
ev <- readChan jobReq
case ev of
SetFrame fn -> do
case sceneFromDesc sDesc ig mg fn of
Right s -> do
writeChan jobResp (localNodeName, SetFrameAck)
continue <- processRequests s
when continue processFrames
Left e -> writeChan jobResp ( localNodeName
, JobError $ "Could not create scene from description for frame " ++ (show fn) ++ ": " ++ e
)
RenderFinished -> writeChan jobResp (localNodeName, JobAck)
_ -> writeChan jobResp ( localNodeName
, JobError "Unexpected request; expected SetFrame!"
)
processFrames
localRenderManager :: Chan JobRequest -> Chan (String, JobResponse) -> IO ()
localRenderManager jobReq jobResp = do
let waitForJob = do
reqEv <- readChan jobReq
case reqEv of
SetScene cfg sDesc ig mg seedV rowRanges -> do
NOTE : this creates a " bogus " scene for frame 1 even
case sceneFromDesc sDesc ig mg (Frame 1) of
Right s -> do
let pxSampler = s^.sceneWorld.viewPlane.pixelSampler
sqSampler = correlatedMultiJittered
diskSampler = s^.sceneCamera.cameraData.lensSampler
theNumSets = fromEnum $ s^.sceneWorld.viewPlane.hres
seed = toSeed seedV
rng <- restore seed
pSamplesVec <- V.generateM theNumSets $ const $ runSampler pxSampler rng (cfg^.sampleRoot)
sSamplesVec <- V.generateM theNumSets $ const $ runSampler sqSampler rng (cfg^.sampleRoot)
dSamplesVec <- V.generateM theNumSets $ const $ runSampler diskSampler rng (cfg^.sampleRoot)
oSamplesVec <- V.generateM theNumSets $ const $ runSampler sqSampler rng (cfg^.sampleRoot)
let sampleData = SampleData theNumSets pSamplesVec sSamplesVec dSamplesVec oSamplesVec
sampleIndexMap <- M.fromList <$>
(forM rowRanges $ \(Row startRow, Row endRow) ->
(,) <$> (pure startRow) <*>
(replicateM (endRow-startRow+1) $
V.replicateM (fromEnum $ s^.sceneWorld.viewPlane.hres) $
uniformR (0, sampleData^.numSets - 1) rng
)
)
writeChan jobResp (localNodeName, SetSceneAck)
localSetSceneAndRender jobReq jobResp cfg sDesc ig mg sampleData sampleIndexMap
Left e -> writeChan jobResp (localNodeName, JobError e)
waitForJob
Shutdown -> do
writeChan jobResp (localNodeName, JobAck)
RenderFinished -> writeChan jobResp (localNodeName, JobAck)
FrameFinished -> writeChan jobResp (localNodeName, JobError "Expected SetScene or Shutdown, got FrameFinished")
SetFrame _ -> writeChan jobResp (localNodeName, JobError "Expected SetScene or Shutdown, got SetFrame")
_ -> writeChan jobResp (localNodeName, JobError "Expected SetScene or Shutdown, got unexpected event")
waitForJob
|
7466f6748c756cbba4cec5a79d5df3c86adfb330629d5309534fe4b73e1180e1 | xclerc/ocamljava | args.mli |
* This file is part of OCaml - Java optimizer .
* Copyright ( C ) 2007 - 2015 .
*
* optimizer is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation ; either version 3 of the License , or
* ( at your option ) any later version .
*
* optimizer is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java optimizer.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java optimizer is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java optimizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
(** Handling of command-line parameters. *)
val classpath : string list ref
(** Classpath elements. *)
val no_backtrace : bool ref
(** Whether to assume absence of backtrace. *)
val no_debug : bool ref
(** Whether to remove debug statements. *)
val no_dynlink : bool ref
(** Whether to assume absence of dynamic linking. *)
val no_runtime_lock : bool ref
(** Whether to remove support for runtime lock. *)
val no_signals : bool ref
(** Whether to remove support for signals. *)
val no_unused_global : bool ref
(** Whether to remove initialization of unused globals. *)
val one_context : bool ref
(** Whether to assume unique context. *)
val unsafe : bool ref
(** Whether to use unsafe containers. *)
val verbose : bool ref
(** Whether to enable verbose mode. *)
val war : bool ref
(** Whether optimized file is a war file. *)
val files : string list ref
(** Files provided on the command line. *)
val parse : unit -> unit
(** Parses the command line, and initializes the values exported by this
module. *)
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/optimizer/src/args.mli | ocaml | * Handling of command-line parameters.
* Classpath elements.
* Whether to assume absence of backtrace.
* Whether to remove debug statements.
* Whether to assume absence of dynamic linking.
* Whether to remove support for runtime lock.
* Whether to remove support for signals.
* Whether to remove initialization of unused globals.
* Whether to assume unique context.
* Whether to use unsafe containers.
* Whether to enable verbose mode.
* Whether optimized file is a war file.
* Files provided on the command line.
* Parses the command line, and initializes the values exported by this
module. |
* This file is part of OCaml - Java optimizer .
* Copyright ( C ) 2007 - 2015 .
*
* optimizer is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation ; either version 3 of the License , or
* ( at your option ) any later version .
*
* optimizer is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java optimizer.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java optimizer is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java optimizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
val classpath : string list ref
val no_backtrace : bool ref
val no_debug : bool ref
val no_dynlink : bool ref
val no_runtime_lock : bool ref
val no_signals : bool ref
val no_unused_global : bool ref
val one_context : bool ref
val unsafe : bool ref
val verbose : bool ref
val war : bool ref
val files : string list ref
val parse : unit -> unit
|
53ceb288957be40275c43aee350ddde6c909ed14da51358102c2da3fba63bd5e | cyppan/grape | http_test.clj | (ns grape.http-test
(:require [clojure.test :refer :all]
[grape.http :refer :all]
[grape.schema :refer :all]
[bidi.ring :refer [make-handler]]
[schema.core :as s]
[grape.fixtures.comments :refer :all]
[grape.rest.route :refer [handler-builder]]
[grape.store :refer [map->MongoDataSource]]
[ring.middleware.params :refer [wrap-params]]
[ring.middleware.json :refer [wrap-json-body wrap-json-response]]
[ring.middleware.cors :refer [wrap-cors]]
[clj-http.client :as client]
[com.stuartsierra.component :as component]
[grape.rest.route :refer [build-resources-routes]]
[grape.store :as store])
(:import (clojure.lang ExceptionInfo)
(org.bson.types ObjectId)))
;; token generated with jwt.io
{ " aud " : " api " , " user - id " : " 57503897eeb06b64ada8fa08 " }
(def token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJzdWIiOiIxMjM0NTY3ODkwIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.KCVn0lDXiHnYJJp7DxEn5fEwPhF4O-HEGHDCqvl6Z4Y")
(deftest auth-middleware
(testing "request is correctly enriched"
(let [;; token generated with jwt.io
{ " aud " : " api " , " user - id " : " 57503897eeb06b64ada8fa08 " }
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJzdWIiOiIxMjM0NTY3ODkwIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.KCVn0lDXiHnYJJp7DxEn5fEwPhF4O-HEGHDCqvl6Z4Y"
request {:query-params {"access_token" token}}
;; we setup a simple handler that responds with the incoming request
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (= (ObjectId. "57503897eeb06b64ada8fa08") (get-in response [:auth :user-id]))))
)
(testing "request jwt signature invalid"
(let [;; invalid token
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJzdWIiOiIxMjM0NTY3ODkwIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.KCVn0lDXiHnYJJp7DxEn5fEwPhF4O-HEGHDCqvl6Z4Ya"
request {:query-params {"access_token" token}}
;; we setup a simple handler that responds with the incoming request
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (nil? (:auth response)))))
(testing "request jwt expired"
(let [;; invalid token
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJ1c2VyLWlkIjoiNTc1MDM4OTdlZWIwNmI2NGFkYThmYTA4IiwiZXhwIjoxNDY5MTgyMDIzfQ.fabF9L5JEHo8SG6B_5cebmez7WdmLPmd3CJGRSjOPyg"
request {:query-params {"access_token" token}}
;; we setup a simple handler that responds with the incoming request
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (nil? (:auth response)))))
(testing "request audience invalid"
(let [;; invalid token
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJpbnZhbGlkIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.-DJBqvuoMP-rgc4L7-3CpB4CQzKjWJcVZUahHeQOpnw"
request {:query-params {"access_token" token}}
;; we setup a simple handler that responds with the incoming request
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (nil? (:auth response))))))
;(deftest http-server-test
; (testing "fetch me through fully started component system"
; (load-fixtures)
; (let [app-routes
( fn [ ]
; (make-handler ["/" (concat
( build - resources - routes )
[ [ true ( fn [ _ ] { : status 404 : body { : _ status 404 : _ message " not found " } } ) ] ] ) ] ) )
; app-wrapper
( fn [ ]
; (fn [handler]
; (-> handler
; (wrap-cors identity)
; wrap-json-response
; (wrap-json-body {:keywords? true})
( wrap - jwt - auth ( get - in [: config : jwt ] ) )
; wrap-params)))
; system (component/start (component/system-map
: resources - registry (: resources - registry )
: hooks (: hooks )
: config (: config )
: store ( store / new - mongo - datasource ( get - in [: config : mongo - db ] ) )
: http - server ( new - http - server ( get - in [: config : http - server ] ) app - routes app - wrapper
; [:store :resources-registry :config :hooks])))]
; ;; no token provided
( is ( thrown - with - msg ? ExceptionInfo # " status 401 " ( client / get " :8080 / me " ) ) )
; ;; token schema invalid
( is ( thrown - with - msg ? ExceptionInfo # " status 401 " ( client / get " :8080 / me?access_token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJ1c2VyLWlkIjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWExIn0.835 - 6ptNKv0pLcWLu6GtIOIjj9KfaquAhvdygUAaPZ0 " ) ) )
( is ( thrown - with - msg ? ExceptionInfo # " status 404 " ( client / get " :8080 / unknown " ) ) )
; (is (= (get-in
( client / get " :8080 / me?access_token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWExIiwiYXVkIjoiYXBpIn0.RWIwbbgk7QUcmOzhf7Z19ifr0AzcLVZ_z2CMYuIVPnM " { : as : )
; [:body :username])
" user 1 " ) )
; (component/stop system)))
;
; (testing "options request always ok through fully started component system"
; (load-fixtures)
; (let [app-routes
( fn [ ]
; (make-handler ["/" (concat
( build - resources - routes )
[ [ true ( fn [ _ ] { : status 404 : body { : _ status 404 : _ message " not found " } } ) ] ] ) ] ) )
; app-wrapper
( fn [ ]
; (fn [handler]
; (-> handler
; (wrap-cors identity)
; wrap-json-response
; (wrap-json-body {:keywords? true})
( wrap - jwt - auth ( get - in [: config : jwt ] ) )
; wrap-params)))
; system (component/start (component/system-map
: resources - registry (: resources - registry )
: hooks (: hooks )
: config (: config )
: store ( store / new - mongo - datasource ( get - in [: config : mongo - db ] ) )
: http - server ( new - http - server ( get - in [: config : http - server ] ) app - routes app - wrapper
; [:store :resources-registry :config :hooks])))]
( is (= 200 (: status ( client / options " :8080 / me " ) ) ) )
; (component/stop system)))) | null | https://raw.githubusercontent.com/cyppan/grape/62488a335542fc58fc9126b8d5ff7fccdd16f1d7/test/grape/http_test.clj | clojure | token generated with jwt.io
token generated with jwt.io
we setup a simple handler that responds with the incoming request
invalid token
we setup a simple handler that responds with the incoming request
invalid token
we setup a simple handler that responds with the incoming request
invalid token
we setup a simple handler that responds with the incoming request
(deftest http-server-test
(testing "fetch me through fully started component system"
(load-fixtures)
(let [app-routes
(make-handler ["/" (concat
app-wrapper
(fn [handler]
(-> handler
(wrap-cors identity)
wrap-json-response
(wrap-json-body {:keywords? true})
wrap-params)))
system (component/start (component/system-map
[:store :resources-registry :config :hooks])))]
;; no token provided
;; token schema invalid
(is (= (get-in
[:body :username])
(component/stop system)))
(testing "options request always ok through fully started component system"
(load-fixtures)
(let [app-routes
(make-handler ["/" (concat
app-wrapper
(fn [handler]
(-> handler
(wrap-cors identity)
wrap-json-response
(wrap-json-body {:keywords? true})
wrap-params)))
system (component/start (component/system-map
[:store :resources-registry :config :hooks])))]
(component/stop system)))) | (ns grape.http-test
(:require [clojure.test :refer :all]
[grape.http :refer :all]
[grape.schema :refer :all]
[bidi.ring :refer [make-handler]]
[schema.core :as s]
[grape.fixtures.comments :refer :all]
[grape.rest.route :refer [handler-builder]]
[grape.store :refer [map->MongoDataSource]]
[ring.middleware.params :refer [wrap-params]]
[ring.middleware.json :refer [wrap-json-body wrap-json-response]]
[ring.middleware.cors :refer [wrap-cors]]
[clj-http.client :as client]
[com.stuartsierra.component :as component]
[grape.rest.route :refer [build-resources-routes]]
[grape.store :as store])
(:import (clojure.lang ExceptionInfo)
(org.bson.types ObjectId)))
{ " aud " : " api " , " user - id " : " 57503897eeb06b64ada8fa08 " }
(def token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJzdWIiOiIxMjM0NTY3ODkwIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.KCVn0lDXiHnYJJp7DxEn5fEwPhF4O-HEGHDCqvl6Z4Y")
(deftest auth-middleware
(testing "request is correctly enriched"
{ " aud " : " api " , " user - id " : " 57503897eeb06b64ada8fa08 " }
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJzdWIiOiIxMjM0NTY3ODkwIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.KCVn0lDXiHnYJJp7DxEn5fEwPhF4O-HEGHDCqvl6Z4Y"
request {:query-params {"access_token" token}}
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (= (ObjectId. "57503897eeb06b64ada8fa08") (get-in response [:auth :user-id]))))
)
(testing "request jwt signature invalid"
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJzdWIiOiIxMjM0NTY3ODkwIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.KCVn0lDXiHnYJJp7DxEn5fEwPhF4O-HEGHDCqvl6Z4Ya"
request {:query-params {"access_token" token}}
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (nil? (:auth response)))))
(testing "request jwt expired"
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJ1c2VyLWlkIjoiNTc1MDM4OTdlZWIwNmI2NGFkYThmYTA4IiwiZXhwIjoxNDY5MTgyMDIzfQ.fabF9L5JEHo8SG6B_5cebmez7WdmLPmd3CJGRSjOPyg"
request {:query-params {"access_token" token}}
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (nil? (:auth response)))))
(testing "request audience invalid"
token "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJpbnZhbGlkIiwidXNlci1pZCI6IjU3NTAzODk3ZWViMDZiNjRhZGE4ZmEwOCJ9.-DJBqvuoMP-rgc4L7-3CpB4CQzKjWJcVZUahHeQOpnw"
request {:query-params {"access_token" token}}
handler (wrap-jwt-auth identity {:audience "api" :secret "secret" :auth-schema {:user-id ObjectId s/Any s/Any}})
response (handler request)]
(is (nil? (:auth response))))))
( fn [ ]
( build - resources - routes )
[ [ true ( fn [ _ ] { : status 404 : body { : _ status 404 : _ message " not found " } } ) ] ] ) ] ) )
( fn [ ]
( wrap - jwt - auth ( get - in [: config : jwt ] ) )
: resources - registry (: resources - registry )
: hooks (: hooks )
: config (: config )
: store ( store / new - mongo - datasource ( get - in [: config : mongo - db ] ) )
: http - server ( new - http - server ( get - in [: config : http - server ] ) app - routes app - wrapper
( is ( thrown - with - msg ? ExceptionInfo # " status 401 " ( client / get " :8080 / me " ) ) )
( is ( thrown - with - msg ? ExceptionInfo # " status 401 " ( client / get " :8080 / me?access_token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhcGkiLCJ1c2VyLWlkIjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWExIn0.835 - 6ptNKv0pLcWLu6GtIOIjj9KfaquAhvdygUAaPZ0 " ) ) )
( is ( thrown - with - msg ? ExceptionInfo # " status 404 " ( client / get " :8080 / unknown " ) ) )
( client / get " :8080 / me?access_token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWExIiwiYXVkIjoiYXBpIn0.RWIwbbgk7QUcmOzhf7Z19ifr0AzcLVZ_z2CMYuIVPnM " { : as : )
" user 1 " ) )
( fn [ ]
( build - resources - routes )
[ [ true ( fn [ _ ] { : status 404 : body { : _ status 404 : _ message " not found " } } ) ] ] ) ] ) )
( fn [ ]
( wrap - jwt - auth ( get - in [: config : jwt ] ) )
: resources - registry (: resources - registry )
: hooks (: hooks )
: config (: config )
: store ( store / new - mongo - datasource ( get - in [: config : mongo - db ] ) )
: http - server ( new - http - server ( get - in [: config : http - server ] ) app - routes app - wrapper
( is (= 200 (: status ( client / options " :8080 / me " ) ) ) ) |
376630ec8fb4f24ad5e21d02e01afcbd3508e3aa4c29ba9f5de515c4c0ee4993 | re-ops/re-cipes | k8s.clj | (ns re-cipes.infra.k8s
"k8s setup"
(:require
[re-cipes.access :refer (permissions)]
[re-cog.common.recipe :refer (require-recipe)]
[re-cog.resources.download :refer (download)]
[re-cog.resources.file :refer (rename symlink chmod)]))
(require-recipe)
(def-inline {:depends #'re-cipes.access/permissions} minikube
"Setting minikube"
[]
(let [version "0.9.1"
release (<< "restic_~{version}_linux_amd64")
expected "81d77d1babe63be393e0a3204aac7825eb35e0fdf58ffefd9f66508a43864866"
url "-linux-amd64"]
(download url "/usr/bin/minikube" expected)
(chmod "/usr/bin/minikube" "0755" {})))
(def-inline kubectl
"Setting minikube"
[]
(let [version "v1.17.0"
url (<< "-release/release/~{version}/bin/linux/amd64/kubectl")
expected "6e0aaaffe5507a44ec6b1b8a0fb585285813b78cc045f8804e70a6aac9d1cb4c"]
(download url "/usr/local/bin/kubectl" expected)
(chmod "/usr/local/bin/kubectl" "0755" {})))
| null | https://raw.githubusercontent.com/re-ops/re-cipes/183bdb637e54df1c6f20e8d529132e0c004e8ead/src/re_cipes/infra/k8s.clj | clojure | (ns re-cipes.infra.k8s
"k8s setup"
(:require
[re-cipes.access :refer (permissions)]
[re-cog.common.recipe :refer (require-recipe)]
[re-cog.resources.download :refer (download)]
[re-cog.resources.file :refer (rename symlink chmod)]))
(require-recipe)
(def-inline {:depends #'re-cipes.access/permissions} minikube
"Setting minikube"
[]
(let [version "0.9.1"
release (<< "restic_~{version}_linux_amd64")
expected "81d77d1babe63be393e0a3204aac7825eb35e0fdf58ffefd9f66508a43864866"
url "-linux-amd64"]
(download url "/usr/bin/minikube" expected)
(chmod "/usr/bin/minikube" "0755" {})))
(def-inline kubectl
"Setting minikube"
[]
(let [version "v1.17.0"
url (<< "-release/release/~{version}/bin/linux/amd64/kubectl")
expected "6e0aaaffe5507a44ec6b1b8a0fb585285813b78cc045f8804e70a6aac9d1cb4c"]
(download url "/usr/local/bin/kubectl" expected)
(chmod "/usr/local/bin/kubectl" "0755" {})))
|
|
f72ef0d5606e58aaebae4ab03df276aa9ebf4598979ee4662e008ee2b38f9987 | UU-ComputerScience/uhc | pr-nmintro1.hs | class A a
f :: A a => a -> a
g = \{! d <: A a !} a -> a
main = g {! () <: A Int !} 3
| null | https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/regress/12/pr-nmintro1.hs | haskell | class A a
f :: A a => a -> a
g = \{! d <: A a !} a -> a
main = g {! () <: A Int !} 3
|
|
2de0dc698d145ca96afa7ad021a87f2aa7ad776098278651806c4357df6fbb90 | johnlawrenceaspden/hobby-code | hello.clj | #!/usr/bin/env clojure
(println "Hello World")
(require 'cemerick.pomegranate)
| null | https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/3961bc2c3909a4daa632afbd2783526f744fd4cf/clojure2022/hello.clj | clojure | #!/usr/bin/env clojure
(println "Hello World")
(require 'cemerick.pomegranate)
|
|
dfa1a123258b34c3599b2c1668c9f5bf4fda7e9a07a8ce655bf93819451c9301 | mwand/eopl3 | environments.scm | (module environments (lib "eopl.ss" "eopl")
;; builds environment interface, using data structures defined in
;; data-structures.scm.
(require "data-structures.scm")
(provide init-env empty-env extend-env apply-env)
;;;;;;;;;;;;;;;; initial environment ;;;;;;;;;;;;;;;;
;; init-env : () -> Env
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
;; (init-env) builds an environment in which i is bound to the
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
;;;;;;;;;;;;;;;; environment constructors and observers ;;;;;;;;;;;;;;;;
(define empty-env
(lambda ()
(empty-env-record)))
(define empty-env?
(lambda (x)
(empty-env-record? x)))
(define extend-env
(lambda (sym val old-env)
(extended-env-record sym val old-env)))
(define apply-env
(lambda (env search-sym)
(if (empty-env? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let ((sym (extended-env-record->sym env))
(val (extended-env-record->val env))
(old-env (extended-env-record->old-env env)))
(if (eqv? search-sym sym)
val
(apply-env old-env search-sym))))))
) | null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter3/let-lang/environments.scm | scheme | builds environment interface, using data structures defined in
data-structures.scm.
initial environment ;;;;;;;;;;;;;;;;
init-env : () -> Env
(init-env) builds an environment in which i is bound to the
environment constructors and observers ;;;;;;;;;;;;;;;; | (module environments (lib "eopl.ss" "eopl")
(require "data-structures.scm")
(provide init-env empty-env extend-env apply-env)
usage : ( init - env ) = [ i=1 , v=5 , x=10 ]
expressed value 1 , v is bound to the expressed value 5 , and x is
bound to the expressed value 10 .
Page : 69
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
(define empty-env
(lambda ()
(empty-env-record)))
(define empty-env?
(lambda (x)
(empty-env-record? x)))
(define extend-env
(lambda (sym val old-env)
(extended-env-record sym val old-env)))
(define apply-env
(lambda (env search-sym)
(if (empty-env? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let ((sym (extended-env-record->sym env))
(val (extended-env-record->val env))
(old-env (extended-env-record->old-env env)))
(if (eqv? search-sym sym)
val
(apply-env old-env search-sym))))))
) |
33283d7d207d1ccd47c0292eba86247c7e579c32ee855ed9c7513b39be8a8501 | mindreframer/clojure-stuff | tcp.clj | Copyright ( c ) . All rights reserved .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns aleph.tcp
(:use
[lamina core trace]
[aleph netty formats])
(:import
[java.nio.channels
ClosedChannelException]))
(defn- wrap-tcp-channel [options ch]
(with-meta
(wrap-socket-channel
options
(let [ch* (channel)]
(join (map* bytes->channel-buffer ch*) ch)
(splice ch ch*)))
(meta ch)))
(defn start-tcp-server [handler options]
(let [server-name (or
(:name options)
(-> options :server :name)
"tcp-server")]
(start-server
server-name
(fn [channel-group]
(create-netty-pipeline server-name true channel-group
:handler (server-message-handler
(fn [ch x]
(handler (wrap-tcp-channel options ch) x)))))
options)))
(defn tcp-client [options]
(let [client-name (or
(:name options)
(-> options :client :name)
"tcp-client")]
(run-pipeline nil
{:error-handler (fn [_])}
(fn [_]
(create-client
client-name
(fn [channel-group]
(create-netty-pipeline client-name false channel-group))
options))
(partial wrap-tcp-channel options))))
| null | https://raw.githubusercontent.com/mindreframer/clojure-stuff/1e761b2dacbbfbeec6f20530f136767e788e0fe3/github.com/ztellman/aleph/src/aleph/tcp.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) . All rights reserved .
(ns aleph.tcp
(:use
[lamina core trace]
[aleph netty formats])
(:import
[java.nio.channels
ClosedChannelException]))
(defn- wrap-tcp-channel [options ch]
(with-meta
(wrap-socket-channel
options
(let [ch* (channel)]
(join (map* bytes->channel-buffer ch*) ch)
(splice ch ch*)))
(meta ch)))
(defn start-tcp-server [handler options]
(let [server-name (or
(:name options)
(-> options :server :name)
"tcp-server")]
(start-server
server-name
(fn [channel-group]
(create-netty-pipeline server-name true channel-group
:handler (server-message-handler
(fn [ch x]
(handler (wrap-tcp-channel options ch) x)))))
options)))
(defn tcp-client [options]
(let [client-name (or
(:name options)
(-> options :client :name)
"tcp-client")]
(run-pipeline nil
{:error-handler (fn [_])}
(fn [_]
(create-client
client-name
(fn [channel-group]
(create-netty-pipeline client-name false channel-group))
options))
(partial wrap-tcp-channel options))))
|
6d562c88e8dbbf87780b8f9d68d8406a525077c4d6b00f3028495b2793329742 | TheLortex/mirage-monorepo | positions.ml | This module builds a buffer of " instructions " , in order to represent a compact sequence
of delimiting positions and newlines . The parser stores the positions of each :
- newline
- beginning of atom
- end of atom
- left parenthesis
- right parenthesis
Instructions are encoded as a sequence bits . The next instruction is determined by
looking at the next few bits :
- bit 0 represents a saved position followed by an offset increment
- bits 10 represent an offset increment
- bits 110 are followed by 5 bits of payload . The 5 - bit payloads of any subsequent 110-
instructions are squashed to form a number ( least significant 5 - bit chunk first ) .
This number + 5 represents an offset increment
- bits 1110 marks the beginning of a new line ( with offset incremented )
- bits 1111 represent a position saved twice followed by an offset increment
For instance let 's consider the following sexp :
{ [
{ |
( abc
" foo
bar "
)
| }
] }
the sequence of instructions to record in order to reconstruct the position of any
sub - sexp is :
- 0 save position and advance 1 : first ' ( '
- 0 save position and advance 1 : start of " abc "
- 10 advance 1
- 0 save position and advance 1 : end of " abc "
- 1110 newline
- 1100_0001 advance 6
- 0 save position and advance 1 : start of " foo\n bar "
- 10 advance 1
- 10 advance 1
- 10 advance 1
- 1110 newline
- 1100_0000 advance 5
- 0 save position and advance 1 : end of " foo\n bar "
- 1110 newline
- 0 save position and advance 1 : last ' ) '
( we save the position after the closing parenthesis )
The total sequence is 42 bits , so we need 6 bytes to store it
The sequence of bits is encoded as a sequence of 16 - bit values , where the earlier bits
are most significant .
Note that the parser stores the end positions as inclusive . This way only single
character atoms require a double positions . If we were storing end positions as
exclusive , we would need double positions for [ ) ( ] and [ a ( ] , which are likely to be
frequent in s - expressions printed with the non [ _ hum ] printer . We expect single
character atoms to be less frequent so it makes sense to penalize them instead .
of delimiting positions and newlines. The parser stores the positions of each:
- newline
- beginning of atom
- end of atom
- left parenthesis
- right parenthesis
Instructions are encoded as a sequence bits. The next instruction is determined by
looking at the next few bits:
- bit 0 represents a saved position followed by an offset increment
- bits 10 represent an offset increment
- bits 110 are followed by 5 bits of payload. The 5-bit payloads of any subsequent 110-
instructions are squashed to form a number (least significant 5-bit chunk first).
This number + 5 represents an offset increment
- bits 1110 marks the beginning of a new line (with offset incremented)
- bits 1111 represent a position saved twice followed by an offset increment
For instance let's consider the following sexp:
{[
{|
(abc
"foo
bar"
)
|}
]}
the sequence of instructions to record in order to reconstruct the position of any
sub-sexp is:
- 0 save position and advance 1: first '('
- 0 save position and advance 1: start of "abc"
- 10 advance 1
- 0 save position and advance 1: end of "abc"
- 1110 newline
- 1100_0001 advance 6
- 0 save position and advance 1: start of "foo\n bar"
- 10 advance 1
- 10 advance 1
- 10 advance 1
- 1110 newline
- 1100_0000 advance 5
- 0 save position and advance 1: end of "foo\n bar"
- 1110 newline
- 0 save position and advance 1: last ')'
(we save the position after the closing parenthesis)
The total sequence is 42 bits, so we need 6 bytes to store it
The sequence of bits is encoded as a sequence of 16-bit values, where the earlier bits
are most significant.
Note that the parser stores the end positions as inclusive. This way only single
character atoms require a double positions. If we were storing end positions as
exclusive, we would need double positions for [)(] and [a(], which are likely to be
frequent in s-expressions printed with the non [_hum] printer. We expect single
character atoms to be less frequent so it makes sense to penalize them instead.
*)
open! Import
type pos =
{ line : int
; col : int
; offset : int
}
[@@deriving_inline sexp_of]
let sexp_of_pos =
(fun { line = line__002_; col = col__004_; offset = offset__006_ } ->
let bnds__001_ = [] in
let bnds__001_ =
let arg__007_ = sexp_of_int offset__006_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "offset"; arg__007_ ] :: bnds__001_
in
let bnds__001_ =
let arg__005_ = sexp_of_int col__004_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "col"; arg__005_ ] :: bnds__001_
in
let bnds__001_ =
let arg__003_ = sexp_of_int line__002_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "line"; arg__003_ ] :: bnds__001_
in
Sexplib0.Sexp.List bnds__001_
: pos -> Sexplib0.Sexp.t)
;;
[@@@end]
let compare_pos = Caml.compare
let beginning_of_file = { line = 1; col = 0; offset = 0 }
let shift_pos pos ~cols = { pos with col = pos.col + cols; offset = pos.offset + cols }
type range =
{ start_pos : pos
; end_pos : pos
}
[@@deriving_inline sexp_of]
let sexp_of_range =
(fun { start_pos = start_pos__009_; end_pos = end_pos__011_ } ->
let bnds__008_ = [] in
let bnds__008_ =
let arg__012_ = sexp_of_pos end_pos__011_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "end_pos"; arg__012_ ] :: bnds__008_
in
let bnds__008_ =
let arg__010_ = sexp_of_pos start_pos__009_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "start_pos"; arg__010_ ] :: bnds__008_
in
Sexplib0.Sexp.List bnds__008_
: range -> Sexplib0.Sexp.t)
;;
[@@@end]
let compare_range = Caml.compare
let make_range_incl ~start_pos ~last_pos =
{ start_pos; end_pos = shift_pos last_pos ~cols:1 }
;;
module Chunk : sig
* Represents an array of [ length/2 ] signed 16 - bit values
type t
(** Length in bytes. *)
val length : int
val alloc : unit -> t
* [ get16 ~pos ] and [ set16 ~pos ] manipulate the [ pos/2]th stored value .
[ pos ] must be even .
[ set16 x ] only uses the 16 least significant bits of [ x ] .
[pos] must be even.
[set16 x] only uses the 16 least significant bits of [x]. *)
val get16 : t -> pos:int -> int
val set16 : t -> pos:int -> int -> unit
end = struct
type t = bytes
OCaml strings always waste two bytes at the end , so we take a power of two minus two
to be sure we do n't waste space .
to be sure we don't waste space. *)
let length = 62
let alloc () = Bytes.create length
external get16 : bytes -> pos:int -> int = "%caml_bytes_get16"
external set16 : bytes -> pos:int -> int -> unit = "%caml_bytes_set16"
If we want to make a [ Positions.t ] serializable :
{ [
external bswap16 : int - > int = " % bswap16 " ; ;
let get16 =
if . then
fun buf ~pos - > get16 buf ~pos | > bswap16
else
get16
let set16 =
if . then
fun buf ~pos x - > set16 buf ~pos ( bswap16 x )
else
set16
] }
{[
external bswap16 : int -> int = "%bswap16";;
let get16 =
if Caml.Sys.arch_big_endian then
fun buf ~pos -> get16 buf ~pos |> bswap16
else
get16
let set16 =
if Caml.Sys.arch_big_endian then
fun buf ~pos x -> set16 buf ~pos (bswap16 x)
else
set16
]}
*)
end
type t_ =
{ chunks : Chunk.t list
[ num_bytes * 8 + extra_bits ] is the number of bits stored in [ chunks ] .
The last [ extra_bits ] bits will be stored as the * least * significant bits
of the appropriate pair of bytes of the last chunk .
The last [extra_bits] bits will be stored as the *least* significant bits
of the appropriate pair of bytes of the last chunk. *)
num_bytes : int
; extra_bits : int
; initial_pos : pos
}
type t = t_ Lazy.t
let memory_footprint_in_bytes (lazy t) =
let num_fields = 4 in
let header_words = 1 in
let word_bytes =
match Sys.word_size with
| 32 -> 4
| 64 -> 8
| _ -> assert false
in
let chunk_words =
let div_ceil a b = (a + b - 1) / b in
let n =
div_ceil
(Chunk.length
NUL terminating bytes
+ 1 (* number of wasted bytes to fill a word *))
word_bytes
in
n + header_words
in
let pos_fields = 3 in
let pos_words = header_words + pos_fields in
let list_cons_words = header_words + 2 in
(header_words
+ num_fields
+ pos_words
+ (List.length t.chunks * (chunk_words + list_cons_words)))
* word_bytes
;;
module Builder = struct
type t =
{ mutable chunk : Chunk.t
; mutable chunk_pos : int
; mutable filled_chunks : Chunk.t list (* Filled chunks in reverse order *)
; mutable offset : int
(* Offset of the last saved position or newline plus
one, or [initial_pos] *)
; mutable int_buf : int
(* the [num_bits] least significant bits of [int_buf]
are the bits not yet pushed to [chunk]. *)
; mutable num_bits : int (* number of bits stored in [int_buf] *)
; mutable initial_pos : pos
}
let invariant t =
assert (t.chunk_pos >= 0 && t.chunk_pos <= Chunk.length);
assert (t.offset >= t.initial_pos.offset);
assert (t.num_bits <= 15)
;;
let check_invariant = false
let invariant t = if check_invariant then invariant t
let create ?(initial_pos = beginning_of_file) () =
{ chunk = Chunk.alloc ()
; chunk_pos = 0
; filled_chunks = []
; offset = initial_pos.offset
; int_buf = 0
; num_bits = 0
; initial_pos
}
;;
let reset t (pos : pos) =
(* We need a new chunk as [contents] keeps the current chunk in the closure of the
lazy value. *)
t.chunk <- Chunk.alloc ();
t.chunk_pos <- 0;
t.filled_chunks <- [];
t.offset <- pos.offset;
t.int_buf <- 0;
t.num_bits <- 0;
t.initial_pos <- pos
;;
let[@inlined never] alloc_new_chunk t =
t.filled_chunks <- t.chunk :: t.filled_chunks;
t.chunk <- Chunk.alloc ();
t.chunk_pos <- 0
;;
let add_uint16 t n =
if t.chunk_pos = Chunk.length then alloc_new_chunk t;
Chunk.set16 t.chunk ~pos:t.chunk_pos n
;;
let add_bits t n ~num_bits =
let int_buf = (t.int_buf lsl num_bits) lor n in
let num_bits = t.num_bits + num_bits in
t.int_buf <- int_buf;
if num_bits < 16
then t.num_bits <- num_bits
else (
let num_bits = num_bits - 16 in
t.num_bits <- num_bits;
add_uint16 t (int_buf lsr num_bits);
t.chunk_pos <- t.chunk_pos + 2
(* no need to clear the bits of int_buf we just wrote, as further set16 will ignore
these extra bits. *))
;;
let contents t =
(* Flush the current [t.int_buf] *)
add_uint16 t t.int_buf;
let rev_chunks = t.chunk :: t.filled_chunks in
let chunk_pos = t.chunk_pos in
let extra_bits = t.num_bits in
let initial_pos = t.initial_pos in
lazy
{ chunks = List.rev rev_chunks
; num_bytes = ((List.length rev_chunks - 1) * Chunk.length) + chunk_pos
; extra_bits
; initial_pos
}
;;
let long_shift t n =
let n = ref (n - 5) in
while !n > 0 do
add_bits t (0b1100_0000 lor (!n land 0b0001_1111)) ~num_bits:8;
n := !n lsr 5
done
;;
precondition : n > = 5
let[@inlined never] add_gen_slow t n ~instr ~instr_bits =
long_shift t n;
add_bits t instr ~num_bits:instr_bits
;;
let shift4 = 0b10_10_10_10
let[@inline always] add_gen t ~offset ~instr ~instr_bits =
invariant t;
let n = offset - t.offset in
t.offset <- offset + 1;
match n with
| 0 | 1 | 2 | 3 | 4 ->
let num_bits = (n lsl 1) + instr_bits in
add_bits t ((shift4 lsl instr_bits) lor instr land ((1 lsl num_bits) - 1)) ~num_bits
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| 13
| 14
| 15
| 16
| 17
| 18
| 19
| 20
| 21
| 22
| 23
| 24
| 25
| 26
| 27
| 28
| 29
| 30
| 31
| 32
| 33
| 34
| 35
| 36 ->
add_bits
t
(((0b1100_0000 lor (n - 5)) lsl instr_bits) lor instr)
~num_bits:(8 + instr_bits)
| _ ->
if n < 0 then invalid_arg "Parsexp.Positions.add_gen";
add_gen_slow t n ~instr ~instr_bits
;;
let add t ~offset = add_gen t ~offset ~instr:0b0 ~instr_bits:1
let add_twice t ~offset = add_gen t ~offset ~instr:0b1111 ~instr_bits:4
let add_newline t ~offset = add_gen t ~offset ~instr:0b1110 ~instr_bits:4
end
type positions = t
module Iterator : sig
type t
val create : positions -> t
exception No_more
(* [advance t ~skip] ignores [skip] saved positions and returns the next saved position.
Raises [No_more] when reaching the end of the position set. *)
val advance_exn : t -> skip:int -> pos
end = struct
type t =
{ mutable chunk : Chunk.t
; mutable chunks : Chunk.t list
[ num_bytes * 8 + extra_bits ] is the number of bits available from [ instr_pos ] in
[ chunk : : chunks ] .
[chunk :: chunks]. *)
mutable num_bytes : int
; extra_bits : int
; mutable instr_pos : int (* position in [chunk] *)
; mutable offset : int
; mutable line : int
; mutable bol : int
; mutable int_buf : int
; mutable num_bits : int (* Number of bits not yet consumed in [int_buf] *)
; mutable pending : pos option
}
let create ((lazy p) : positions) =
match p.chunks with
| [] -> assert false
| chunk :: chunks ->
{ chunk
; chunks
; num_bytes = p.num_bytes
; extra_bits = p.extra_bits
; instr_pos = 0
; offset = p.initial_pos.offset
; line = p.initial_pos.line
; bol = p.initial_pos.offset - p.initial_pos.col
; int_buf = 0
; num_bits = 0
; pending = None
}
;;
exception No_more
let no_more () = raise_notrace No_more
let[@inlined never] fetch_chunk t =
match t.chunks with
| [] -> assert false
| chunk :: chunks ->
t.instr_pos <- 0;
t.num_bytes <- t.num_bytes - Chunk.length;
t.chunk <- chunk;
t.chunks <- chunks
;;
let fetch t =
if t.instr_pos > t.num_bytes then no_more ();
if t.instr_pos = Chunk.length then fetch_chunk t;
let v = Chunk.get16 t.chunk ~pos:t.instr_pos in
let added_bits = if t.instr_pos = t.num_bytes then t.extra_bits else 16 in
t.int_buf <- (t.int_buf lsl added_bits) lor (v land ((1 lsl added_bits) - 1));
t.num_bits <- t.num_bits + added_bits;
t.instr_pos <- t.instr_pos + 2
;;
let next_instruction_bits t ~num_bits =
if t.num_bits < num_bits
then (
fetch t;
if t.num_bits < num_bits then no_more ());
let n = (t.int_buf lsr (t.num_bits - num_bits)) land ((1 lsl num_bits) - 1) in
t.num_bits <- t.num_bits - num_bits;
n
;;
[ offset_shift ] and [ offset_shift_num_bits ] encode the offset number
specified by the immediately preceding [ 110 ] instructions .
specified by the immediately preceding [110] instructions. *)
let rec advance t ~skip ~offset_shift ~offset_shift_num_bits =
match next_instruction_bits t ~num_bits:1 with
| 0 ->
(* bit seq 0 -> new item *)
let offset = t.offset + offset_shift in
t.offset <- offset + 1;
if skip = 0
then { line = t.line; col = offset - t.bol; offset }
else advance t ~skip:(skip - 1) ~offset_shift:0 ~offset_shift_num_bits:0
| _ ->
(match next_instruction_bits t ~num_bits:1 with
| 0 ->
bit seq 10 - > shift
t.offset <- t.offset + offset_shift + 1;
advance t ~skip ~offset_shift:0 ~offset_shift_num_bits:0
| _ ->
(match next_instruction_bits t ~num_bits:1 with
| 0 ->
bit seq 110 - > long shift
let n = next_instruction_bits t ~num_bits:5 in
let offset_shift = if offset_shift_num_bits = 0 then 5 else offset_shift in
advance
t
~skip
~offset_shift:(offset_shift + (n lsl offset_shift_num_bits))
~offset_shift_num_bits:(offset_shift_num_bits + 5)
| _ ->
(match next_instruction_bits t ~num_bits:1 with
| 0 ->
bit seq 1110 - > newline
t.offset <- t.offset + offset_shift + 1;
t.bol <- t.offset;
t.line <- t.line + 1;
advance t ~skip ~offset_shift:0 ~offset_shift_num_bits:0
| _ ->
bit seq 1111 - > 2 new items
let offset = t.offset + offset_shift in
t.offset <- offset + 1;
if skip <= 1
then (
let pos = { line = t.line; col = offset - t.bol; offset } in
if skip = 0 then t.pending <- Some pos;
pos)
else advance t ~skip:(skip - 2) ~offset_shift:0 ~offset_shift_num_bits:0)))
;;
let advance_exn t ~skip =
match t.pending with
| Some pos ->
t.pending <- None;
if skip = 0
then pos
else advance t ~skip:(skip - 1) ~offset_shift:0 ~offset_shift_num_bits:0
| None -> advance t ~skip ~offset_shift:0 ~offset_shift_num_bits:0
;;
end
let find t a b =
if a < 0 || b <= a then invalid_arg "Parsexp.Positions.find";
let iter = Iterator.create t in
try
let start_pos = Iterator.advance_exn iter ~skip:a in
let last_pos = Iterator.advance_exn iter ~skip:(b - a - 1) in
make_range_incl ~start_pos ~last_pos
with
| Iterator.No_more -> failwith "Parsexp.Position.find"
;;
let rec sub_sexp_count (sexp : Sexp.t) =
match sexp with
| Atom _ -> 1
| List l -> List.fold_left l ~init:1 ~f:(fun acc x -> acc + sub_sexp_count x)
;;
module Sexp_search = struct
exception Found of int
let rec loop ~sub index (sexp : Sexp.t) =
if sexp == sub
then raise_notrace (Found index)
else (
match sexp with
| Atom _ -> index + 2
| List l ->
let index = loop_list ~sub (index + 1) l in
index + 1)
and loop_list ~sub index (sexps : Sexp.t list) =
List.fold_left sexps ~init:index ~f:(loop ~sub)
;;
let finalize t ~sub a =
let b = a + (sub_sexp_count sub * 2) - 1 in
Some (find t a b)
;;
let find_sub_sexp_phys t sexp ~sub =
match loop ~sub 0 sexp with
| (_ : int) -> None
| exception Found n -> finalize t ~sub n
;;
let find_sub_sexp_in_list_phys t sexps ~sub =
match loop_list ~sub 0 sexps with
| (_ : int) -> None
| exception Found n -> finalize t ~sub n
;;
end
let find_sub_sexp_phys = Sexp_search.find_sub_sexp_phys
let find_sub_sexp_in_list_phys = Sexp_search.find_sub_sexp_in_list_phys
let to_list t =
let iter = Iterator.create t in
let rec loop acc =
match Iterator.advance_exn iter ~skip:0 with
| exception Iterator.No_more -> List.rev acc
| pos -> loop (pos :: acc)
in
loop []
;;
let to_array t = to_list t |> Array.of_list
let compare t1 t2 = Caml.compare (to_array t1) (to_array t2)
let sexp_of_t t = sexp_of_array sexp_of_pos (to_array t)
| null | https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/parsexp/src/positions.ml | ocaml | * Length in bytes.
number of wasted bytes to fill a word
Filled chunks in reverse order
Offset of the last saved position or newline plus
one, or [initial_pos]
the [num_bits] least significant bits of [int_buf]
are the bits not yet pushed to [chunk].
number of bits stored in [int_buf]
We need a new chunk as [contents] keeps the current chunk in the closure of the
lazy value.
no need to clear the bits of int_buf we just wrote, as further set16 will ignore
these extra bits.
Flush the current [t.int_buf]
[advance t ~skip] ignores [skip] saved positions and returns the next saved position.
Raises [No_more] when reaching the end of the position set.
position in [chunk]
Number of bits not yet consumed in [int_buf]
bit seq 0 -> new item | This module builds a buffer of " instructions " , in order to represent a compact sequence
of delimiting positions and newlines . The parser stores the positions of each :
- newline
- beginning of atom
- end of atom
- left parenthesis
- right parenthesis
Instructions are encoded as a sequence bits . The next instruction is determined by
looking at the next few bits :
- bit 0 represents a saved position followed by an offset increment
- bits 10 represent an offset increment
- bits 110 are followed by 5 bits of payload . The 5 - bit payloads of any subsequent 110-
instructions are squashed to form a number ( least significant 5 - bit chunk first ) .
This number + 5 represents an offset increment
- bits 1110 marks the beginning of a new line ( with offset incremented )
- bits 1111 represent a position saved twice followed by an offset increment
For instance let 's consider the following sexp :
{ [
{ |
( abc
" foo
bar "
)
| }
] }
the sequence of instructions to record in order to reconstruct the position of any
sub - sexp is :
- 0 save position and advance 1 : first ' ( '
- 0 save position and advance 1 : start of " abc "
- 10 advance 1
- 0 save position and advance 1 : end of " abc "
- 1110 newline
- 1100_0001 advance 6
- 0 save position and advance 1 : start of " foo\n bar "
- 10 advance 1
- 10 advance 1
- 10 advance 1
- 1110 newline
- 1100_0000 advance 5
- 0 save position and advance 1 : end of " foo\n bar "
- 1110 newline
- 0 save position and advance 1 : last ' ) '
( we save the position after the closing parenthesis )
The total sequence is 42 bits , so we need 6 bytes to store it
The sequence of bits is encoded as a sequence of 16 - bit values , where the earlier bits
are most significant .
Note that the parser stores the end positions as inclusive . This way only single
character atoms require a double positions . If we were storing end positions as
exclusive , we would need double positions for [ ) ( ] and [ a ( ] , which are likely to be
frequent in s - expressions printed with the non [ _ hum ] printer . We expect single
character atoms to be less frequent so it makes sense to penalize them instead .
of delimiting positions and newlines. The parser stores the positions of each:
- newline
- beginning of atom
- end of atom
- left parenthesis
- right parenthesis
Instructions are encoded as a sequence bits. The next instruction is determined by
looking at the next few bits:
- bit 0 represents a saved position followed by an offset increment
- bits 10 represent an offset increment
- bits 110 are followed by 5 bits of payload. The 5-bit payloads of any subsequent 110-
instructions are squashed to form a number (least significant 5-bit chunk first).
This number + 5 represents an offset increment
- bits 1110 marks the beginning of a new line (with offset incremented)
- bits 1111 represent a position saved twice followed by an offset increment
For instance let's consider the following sexp:
{[
{|
(abc
"foo
bar"
)
|}
]}
the sequence of instructions to record in order to reconstruct the position of any
sub-sexp is:
- 0 save position and advance 1: first '('
- 0 save position and advance 1: start of "abc"
- 10 advance 1
- 0 save position and advance 1: end of "abc"
- 1110 newline
- 1100_0001 advance 6
- 0 save position and advance 1: start of "foo\n bar"
- 10 advance 1
- 10 advance 1
- 10 advance 1
- 1110 newline
- 1100_0000 advance 5
- 0 save position and advance 1: end of "foo\n bar"
- 1110 newline
- 0 save position and advance 1: last ')'
(we save the position after the closing parenthesis)
The total sequence is 42 bits, so we need 6 bytes to store it
The sequence of bits is encoded as a sequence of 16-bit values, where the earlier bits
are most significant.
Note that the parser stores the end positions as inclusive. This way only single
character atoms require a double positions. If we were storing end positions as
exclusive, we would need double positions for [)(] and [a(], which are likely to be
frequent in s-expressions printed with the non [_hum] printer. We expect single
character atoms to be less frequent so it makes sense to penalize them instead.
*)
open! Import
type pos =
{ line : int
; col : int
; offset : int
}
[@@deriving_inline sexp_of]
let sexp_of_pos =
(fun { line = line__002_; col = col__004_; offset = offset__006_ } ->
let bnds__001_ = [] in
let bnds__001_ =
let arg__007_ = sexp_of_int offset__006_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "offset"; arg__007_ ] :: bnds__001_
in
let bnds__001_ =
let arg__005_ = sexp_of_int col__004_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "col"; arg__005_ ] :: bnds__001_
in
let bnds__001_ =
let arg__003_ = sexp_of_int line__002_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "line"; arg__003_ ] :: bnds__001_
in
Sexplib0.Sexp.List bnds__001_
: pos -> Sexplib0.Sexp.t)
;;
[@@@end]
let compare_pos = Caml.compare
let beginning_of_file = { line = 1; col = 0; offset = 0 }
let shift_pos pos ~cols = { pos with col = pos.col + cols; offset = pos.offset + cols }
type range =
{ start_pos : pos
; end_pos : pos
}
[@@deriving_inline sexp_of]
let sexp_of_range =
(fun { start_pos = start_pos__009_; end_pos = end_pos__011_ } ->
let bnds__008_ = [] in
let bnds__008_ =
let arg__012_ = sexp_of_pos end_pos__011_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "end_pos"; arg__012_ ] :: bnds__008_
in
let bnds__008_ =
let arg__010_ = sexp_of_pos start_pos__009_ in
Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "start_pos"; arg__010_ ] :: bnds__008_
in
Sexplib0.Sexp.List bnds__008_
: range -> Sexplib0.Sexp.t)
;;
[@@@end]
let compare_range = Caml.compare
let make_range_incl ~start_pos ~last_pos =
{ start_pos; end_pos = shift_pos last_pos ~cols:1 }
;;
module Chunk : sig
* Represents an array of [ length/2 ] signed 16 - bit values
type t
val length : int
val alloc : unit -> t
* [ get16 ~pos ] and [ set16 ~pos ] manipulate the [ pos/2]th stored value .
[ pos ] must be even .
[ set16 x ] only uses the 16 least significant bits of [ x ] .
[pos] must be even.
[set16 x] only uses the 16 least significant bits of [x]. *)
val get16 : t -> pos:int -> int
val set16 : t -> pos:int -> int -> unit
end = struct
type t = bytes
OCaml strings always waste two bytes at the end , so we take a power of two minus two
to be sure we do n't waste space .
to be sure we don't waste space. *)
let length = 62
let alloc () = Bytes.create length
external get16 : bytes -> pos:int -> int = "%caml_bytes_get16"
external set16 : bytes -> pos:int -> int -> unit = "%caml_bytes_set16"
If we want to make a [ Positions.t ] serializable :
{ [
external bswap16 : int - > int = " % bswap16 " ; ;
let get16 =
if . then
fun buf ~pos - > get16 buf ~pos | > bswap16
else
get16
let set16 =
if . then
fun buf ~pos x - > set16 buf ~pos ( bswap16 x )
else
set16
] }
{[
external bswap16 : int -> int = "%bswap16";;
let get16 =
if Caml.Sys.arch_big_endian then
fun buf ~pos -> get16 buf ~pos |> bswap16
else
get16
let set16 =
if Caml.Sys.arch_big_endian then
fun buf ~pos x -> set16 buf ~pos (bswap16 x)
else
set16
]}
*)
end
type t_ =
{ chunks : Chunk.t list
[ num_bytes * 8 + extra_bits ] is the number of bits stored in [ chunks ] .
The last [ extra_bits ] bits will be stored as the * least * significant bits
of the appropriate pair of bytes of the last chunk .
The last [extra_bits] bits will be stored as the *least* significant bits
of the appropriate pair of bytes of the last chunk. *)
num_bytes : int
; extra_bits : int
; initial_pos : pos
}
type t = t_ Lazy.t
let memory_footprint_in_bytes (lazy t) =
let num_fields = 4 in
let header_words = 1 in
let word_bytes =
match Sys.word_size with
| 32 -> 4
| 64 -> 8
| _ -> assert false
in
let chunk_words =
let div_ceil a b = (a + b - 1) / b in
let n =
div_ceil
(Chunk.length
NUL terminating bytes
word_bytes
in
n + header_words
in
let pos_fields = 3 in
let pos_words = header_words + pos_fields in
let list_cons_words = header_words + 2 in
(header_words
+ num_fields
+ pos_words
+ (List.length t.chunks * (chunk_words + list_cons_words)))
* word_bytes
;;
module Builder = struct
type t =
{ mutable chunk : Chunk.t
; mutable chunk_pos : int
; mutable offset : int
; mutable int_buf : int
; mutable initial_pos : pos
}
let invariant t =
assert (t.chunk_pos >= 0 && t.chunk_pos <= Chunk.length);
assert (t.offset >= t.initial_pos.offset);
assert (t.num_bits <= 15)
;;
let check_invariant = false
let invariant t = if check_invariant then invariant t
let create ?(initial_pos = beginning_of_file) () =
{ chunk = Chunk.alloc ()
; chunk_pos = 0
; filled_chunks = []
; offset = initial_pos.offset
; int_buf = 0
; num_bits = 0
; initial_pos
}
;;
let reset t (pos : pos) =
t.chunk <- Chunk.alloc ();
t.chunk_pos <- 0;
t.filled_chunks <- [];
t.offset <- pos.offset;
t.int_buf <- 0;
t.num_bits <- 0;
t.initial_pos <- pos
;;
let[@inlined never] alloc_new_chunk t =
t.filled_chunks <- t.chunk :: t.filled_chunks;
t.chunk <- Chunk.alloc ();
t.chunk_pos <- 0
;;
let add_uint16 t n =
if t.chunk_pos = Chunk.length then alloc_new_chunk t;
Chunk.set16 t.chunk ~pos:t.chunk_pos n
;;
let add_bits t n ~num_bits =
let int_buf = (t.int_buf lsl num_bits) lor n in
let num_bits = t.num_bits + num_bits in
t.int_buf <- int_buf;
if num_bits < 16
then t.num_bits <- num_bits
else (
let num_bits = num_bits - 16 in
t.num_bits <- num_bits;
add_uint16 t (int_buf lsr num_bits);
t.chunk_pos <- t.chunk_pos + 2
;;
let contents t =
add_uint16 t t.int_buf;
let rev_chunks = t.chunk :: t.filled_chunks in
let chunk_pos = t.chunk_pos in
let extra_bits = t.num_bits in
let initial_pos = t.initial_pos in
lazy
{ chunks = List.rev rev_chunks
; num_bytes = ((List.length rev_chunks - 1) * Chunk.length) + chunk_pos
; extra_bits
; initial_pos
}
;;
let long_shift t n =
let n = ref (n - 5) in
while !n > 0 do
add_bits t (0b1100_0000 lor (!n land 0b0001_1111)) ~num_bits:8;
n := !n lsr 5
done
;;
precondition : n > = 5
let[@inlined never] add_gen_slow t n ~instr ~instr_bits =
long_shift t n;
add_bits t instr ~num_bits:instr_bits
;;
let shift4 = 0b10_10_10_10
let[@inline always] add_gen t ~offset ~instr ~instr_bits =
invariant t;
let n = offset - t.offset in
t.offset <- offset + 1;
match n with
| 0 | 1 | 2 | 3 | 4 ->
let num_bits = (n lsl 1) + instr_bits in
add_bits t ((shift4 lsl instr_bits) lor instr land ((1 lsl num_bits) - 1)) ~num_bits
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| 13
| 14
| 15
| 16
| 17
| 18
| 19
| 20
| 21
| 22
| 23
| 24
| 25
| 26
| 27
| 28
| 29
| 30
| 31
| 32
| 33
| 34
| 35
| 36 ->
add_bits
t
(((0b1100_0000 lor (n - 5)) lsl instr_bits) lor instr)
~num_bits:(8 + instr_bits)
| _ ->
if n < 0 then invalid_arg "Parsexp.Positions.add_gen";
add_gen_slow t n ~instr ~instr_bits
;;
let add t ~offset = add_gen t ~offset ~instr:0b0 ~instr_bits:1
let add_twice t ~offset = add_gen t ~offset ~instr:0b1111 ~instr_bits:4
let add_newline t ~offset = add_gen t ~offset ~instr:0b1110 ~instr_bits:4
end
type positions = t
module Iterator : sig
type t
val create : positions -> t
exception No_more
val advance_exn : t -> skip:int -> pos
end = struct
type t =
{ mutable chunk : Chunk.t
; mutable chunks : Chunk.t list
[ num_bytes * 8 + extra_bits ] is the number of bits available from [ instr_pos ] in
[ chunk : : chunks ] .
[chunk :: chunks]. *)
mutable num_bytes : int
; extra_bits : int
; mutable offset : int
; mutable line : int
; mutable bol : int
; mutable int_buf : int
; mutable pending : pos option
}
let create ((lazy p) : positions) =
match p.chunks with
| [] -> assert false
| chunk :: chunks ->
{ chunk
; chunks
; num_bytes = p.num_bytes
; extra_bits = p.extra_bits
; instr_pos = 0
; offset = p.initial_pos.offset
; line = p.initial_pos.line
; bol = p.initial_pos.offset - p.initial_pos.col
; int_buf = 0
; num_bits = 0
; pending = None
}
;;
exception No_more
let no_more () = raise_notrace No_more
let[@inlined never] fetch_chunk t =
match t.chunks with
| [] -> assert false
| chunk :: chunks ->
t.instr_pos <- 0;
t.num_bytes <- t.num_bytes - Chunk.length;
t.chunk <- chunk;
t.chunks <- chunks
;;
let fetch t =
if t.instr_pos > t.num_bytes then no_more ();
if t.instr_pos = Chunk.length then fetch_chunk t;
let v = Chunk.get16 t.chunk ~pos:t.instr_pos in
let added_bits = if t.instr_pos = t.num_bytes then t.extra_bits else 16 in
t.int_buf <- (t.int_buf lsl added_bits) lor (v land ((1 lsl added_bits) - 1));
t.num_bits <- t.num_bits + added_bits;
t.instr_pos <- t.instr_pos + 2
;;
let next_instruction_bits t ~num_bits =
if t.num_bits < num_bits
then (
fetch t;
if t.num_bits < num_bits then no_more ());
let n = (t.int_buf lsr (t.num_bits - num_bits)) land ((1 lsl num_bits) - 1) in
t.num_bits <- t.num_bits - num_bits;
n
;;
[ offset_shift ] and [ offset_shift_num_bits ] encode the offset number
specified by the immediately preceding [ 110 ] instructions .
specified by the immediately preceding [110] instructions. *)
let rec advance t ~skip ~offset_shift ~offset_shift_num_bits =
match next_instruction_bits t ~num_bits:1 with
| 0 ->
let offset = t.offset + offset_shift in
t.offset <- offset + 1;
if skip = 0
then { line = t.line; col = offset - t.bol; offset }
else advance t ~skip:(skip - 1) ~offset_shift:0 ~offset_shift_num_bits:0
| _ ->
(match next_instruction_bits t ~num_bits:1 with
| 0 ->
bit seq 10 - > shift
t.offset <- t.offset + offset_shift + 1;
advance t ~skip ~offset_shift:0 ~offset_shift_num_bits:0
| _ ->
(match next_instruction_bits t ~num_bits:1 with
| 0 ->
bit seq 110 - > long shift
let n = next_instruction_bits t ~num_bits:5 in
let offset_shift = if offset_shift_num_bits = 0 then 5 else offset_shift in
advance
t
~skip
~offset_shift:(offset_shift + (n lsl offset_shift_num_bits))
~offset_shift_num_bits:(offset_shift_num_bits + 5)
| _ ->
(match next_instruction_bits t ~num_bits:1 with
| 0 ->
bit seq 1110 - > newline
t.offset <- t.offset + offset_shift + 1;
t.bol <- t.offset;
t.line <- t.line + 1;
advance t ~skip ~offset_shift:0 ~offset_shift_num_bits:0
| _ ->
bit seq 1111 - > 2 new items
let offset = t.offset + offset_shift in
t.offset <- offset + 1;
if skip <= 1
then (
let pos = { line = t.line; col = offset - t.bol; offset } in
if skip = 0 then t.pending <- Some pos;
pos)
else advance t ~skip:(skip - 2) ~offset_shift:0 ~offset_shift_num_bits:0)))
;;
let advance_exn t ~skip =
match t.pending with
| Some pos ->
t.pending <- None;
if skip = 0
then pos
else advance t ~skip:(skip - 1) ~offset_shift:0 ~offset_shift_num_bits:0
| None -> advance t ~skip ~offset_shift:0 ~offset_shift_num_bits:0
;;
end
let find t a b =
if a < 0 || b <= a then invalid_arg "Parsexp.Positions.find";
let iter = Iterator.create t in
try
let start_pos = Iterator.advance_exn iter ~skip:a in
let last_pos = Iterator.advance_exn iter ~skip:(b - a - 1) in
make_range_incl ~start_pos ~last_pos
with
| Iterator.No_more -> failwith "Parsexp.Position.find"
;;
let rec sub_sexp_count (sexp : Sexp.t) =
match sexp with
| Atom _ -> 1
| List l -> List.fold_left l ~init:1 ~f:(fun acc x -> acc + sub_sexp_count x)
;;
module Sexp_search = struct
exception Found of int
let rec loop ~sub index (sexp : Sexp.t) =
if sexp == sub
then raise_notrace (Found index)
else (
match sexp with
| Atom _ -> index + 2
| List l ->
let index = loop_list ~sub (index + 1) l in
index + 1)
and loop_list ~sub index (sexps : Sexp.t list) =
List.fold_left sexps ~init:index ~f:(loop ~sub)
;;
let finalize t ~sub a =
let b = a + (sub_sexp_count sub * 2) - 1 in
Some (find t a b)
;;
let find_sub_sexp_phys t sexp ~sub =
match loop ~sub 0 sexp with
| (_ : int) -> None
| exception Found n -> finalize t ~sub n
;;
let find_sub_sexp_in_list_phys t sexps ~sub =
match loop_list ~sub 0 sexps with
| (_ : int) -> None
| exception Found n -> finalize t ~sub n
;;
end
let find_sub_sexp_phys = Sexp_search.find_sub_sexp_phys
let find_sub_sexp_in_list_phys = Sexp_search.find_sub_sexp_in_list_phys
let to_list t =
let iter = Iterator.create t in
let rec loop acc =
match Iterator.advance_exn iter ~skip:0 with
| exception Iterator.No_more -> List.rev acc
| pos -> loop (pos :: acc)
in
loop []
;;
let to_array t = to_list t |> Array.of_list
let compare t1 t2 = Caml.compare (to_array t1) (to_array t2)
let sexp_of_t t = sexp_of_array sexp_of_pos (to_array t)
|
fd359872b6221a11fe83bd6bca7d145d58b504e100e35acc5e1baa8da51908d3 | hatsugai/Guedra | vscroll.ml | open Csp
open Guedra
open Scroll
let init wch pch cch nch range0 page0 index0 =
let pque = Queue.create () in
let nque = Queue.create () in
let cc = make_cc range0 page0 index0 in
let rec process () =
let event_list =
[ recvEvt wch always win_msg;
recvEvt cch always win_cmd ]
in
select_que3 event_list cc.inv pque nque
and win_msg msg =
match msg with
Paint (x, y, w, h) ->
(* background *)
set_color o_o.color_back;
fill_rect 0.0 0.0 cc.fWidth cc.fHeight;
(* thumb *)
(if cc.range > 0 && cc.height > o_o.scroll_thumb_size then (
set_color o_o.color_handle;
fill_rect 0.0 (flo cc.pos) cc.fWidth (flo o_o.scroll_thumb_size)));
send pch (wch, PaintAck) process
| WinSize (w, h) ->
cc.width <- w;
cc.height <- h;
cc.fWidth <- float_of_int w;
cc.fHeight <- float_of_int h;
let p = calc_pos h cc.range cc.index in
cc.pos <- p;
invalidate ()
| MouseDown (x, y, state, button) ->
request Activate;
if y < cc.pos then (
(* page up *)
let i = max 0 (cc.index - cc.page) in
let p = calc_pos cc.height cc.range i in
cc.index <- i;
cc.pos <- p;
notify (Pos i);
invalidate ())
else if y >= cc.pos + o_o.scroll_thumb_size then (
(* page down *)
let i = min (cc.index + cc.page) cc.range in
let p = calc_pos cc.height cc.range i in
cc.index <- i;
cc.pos <- p;
notify (Pos i);
invalidate ())
else if cc.height > o_o.scroll_thumb_size && cc.range > 0 then (
(* thumb *)
cc.capture <- true;
cc.displacement <- cc.pos - y;
process ())
else
process ()
| MouseUp (x, y, state, button) ->
if cc.capture then
let p = max 0
(min (y + cc.displacement)
(cc.height - o_o.scroll_thumb_size))
in
let i = calc_index cc.height cc.range p in
let p = calc_pos cc.height cc.range i in
cc.pos <- p;
cc.index <- i;
cc.capture <- false;
notify (Pos i);
invalidate ()
else
process ()
| MouseMove (x, y, state) ->
if cc.capture then
let p = max 0
(min (y + cc.displacement)
(cc.height - o_o.scroll_thumb_size))
in
let i = calc_index cc.height cc.range p in
let p = calc_pos cc.height cc.range i in
cc.pos <- p;
cc.index <- i;
notify (Pos i);
invalidate ()
else
process ()
| _ -> process ()
and win_cmd msg =
match msg with
SetIndex i ->
assert (i >= 0 && i <= cc.range);
cc.index <- i;
cc.pos <- calc_pos cc.height cc.range i;
invalidate ()
| SetRange (r, i) ->
assert (r >= 0 && i >= 0 && i <= r);
cc.range <- r;
cc.index <- i;
cc.pos <- calc_pos cc.height r i;
invalidate ()
and request msg =
Queue.add (sendEvt pch (wch, msg) pque_drop) pque;
and notify msg =
Queue.add (sendEvt nch (cch, msg) nque_drop) nque
and inv () =
let msg = (wch, Invalidate (0, 0, cc.width, cc.height)) in
let e = sendEvt pch msg clear_inv in
cc.inv <- Some e
and invalidate () =
inv ();
process ()
and clear_inv () =
cc.inv <- None;
process ()
and pque_drop () = let _ = Queue.take pque in process ()
and nque_drop () = let _ = Queue.take nque in process ()
in process ()
| null | https://raw.githubusercontent.com/hatsugai/Guedra/592e9b4cff151228735d2c61c337154cde8b5329/src/vscroll.ml | ocaml | background
thumb
page up
page down
thumb | open Csp
open Guedra
open Scroll
let init wch pch cch nch range0 page0 index0 =
let pque = Queue.create () in
let nque = Queue.create () in
let cc = make_cc range0 page0 index0 in
let rec process () =
let event_list =
[ recvEvt wch always win_msg;
recvEvt cch always win_cmd ]
in
select_que3 event_list cc.inv pque nque
and win_msg msg =
match msg with
Paint (x, y, w, h) ->
set_color o_o.color_back;
fill_rect 0.0 0.0 cc.fWidth cc.fHeight;
(if cc.range > 0 && cc.height > o_o.scroll_thumb_size then (
set_color o_o.color_handle;
fill_rect 0.0 (flo cc.pos) cc.fWidth (flo o_o.scroll_thumb_size)));
send pch (wch, PaintAck) process
| WinSize (w, h) ->
cc.width <- w;
cc.height <- h;
cc.fWidth <- float_of_int w;
cc.fHeight <- float_of_int h;
let p = calc_pos h cc.range cc.index in
cc.pos <- p;
invalidate ()
| MouseDown (x, y, state, button) ->
request Activate;
if y < cc.pos then (
let i = max 0 (cc.index - cc.page) in
let p = calc_pos cc.height cc.range i in
cc.index <- i;
cc.pos <- p;
notify (Pos i);
invalidate ())
else if y >= cc.pos + o_o.scroll_thumb_size then (
let i = min (cc.index + cc.page) cc.range in
let p = calc_pos cc.height cc.range i in
cc.index <- i;
cc.pos <- p;
notify (Pos i);
invalidate ())
else if cc.height > o_o.scroll_thumb_size && cc.range > 0 then (
cc.capture <- true;
cc.displacement <- cc.pos - y;
process ())
else
process ()
| MouseUp (x, y, state, button) ->
if cc.capture then
let p = max 0
(min (y + cc.displacement)
(cc.height - o_o.scroll_thumb_size))
in
let i = calc_index cc.height cc.range p in
let p = calc_pos cc.height cc.range i in
cc.pos <- p;
cc.index <- i;
cc.capture <- false;
notify (Pos i);
invalidate ()
else
process ()
| MouseMove (x, y, state) ->
if cc.capture then
let p = max 0
(min (y + cc.displacement)
(cc.height - o_o.scroll_thumb_size))
in
let i = calc_index cc.height cc.range p in
let p = calc_pos cc.height cc.range i in
cc.pos <- p;
cc.index <- i;
notify (Pos i);
invalidate ()
else
process ()
| _ -> process ()
and win_cmd msg =
match msg with
SetIndex i ->
assert (i >= 0 && i <= cc.range);
cc.index <- i;
cc.pos <- calc_pos cc.height cc.range i;
invalidate ()
| SetRange (r, i) ->
assert (r >= 0 && i >= 0 && i <= r);
cc.range <- r;
cc.index <- i;
cc.pos <- calc_pos cc.height r i;
invalidate ()
and request msg =
Queue.add (sendEvt pch (wch, msg) pque_drop) pque;
and notify msg =
Queue.add (sendEvt nch (cch, msg) nque_drop) nque
and inv () =
let msg = (wch, Invalidate (0, 0, cc.width, cc.height)) in
let e = sendEvt pch msg clear_inv in
cc.inv <- Some e
and invalidate () =
inv ();
process ()
and clear_inv () =
cc.inv <- None;
process ()
and pque_drop () = let _ = Queue.take pque in process ()
and nque_drop () = let _ = Queue.take nque in process ()
in process ()
|
fe1303ae5582a8d3b272e8160984e10a208efb60101d16e65752e537caf7d403 | yomimono/stitchcraft | pat2stitchy.ml | let input =
let doc = "file from which to read"
and docv = "FILE" in
Cmdliner.Arg.(value & pos_all string [] & info [] ~doc ~docv)
let verbose =
let doc = "print file metadata on stderr"
and docv = "VERBOSE" in
Cmdliner.Arg.(value & flag & info ["v";"verbose"] ~doc ~docv)
let info =
let doc = "read .pat files" in
Cmdliner.Cmd.info "patreader" ~doc
let spoo (fabric, metadata, palette, stitches, extras, knots, backstitches) =
Format.eprintf "metadata: %a\n%!" Patreader.pp_metadata metadata;
Format.eprintf "fabric: %a\n%!" Patreader.pp_fabric fabric;
Format.eprintf "palette: %a\n%!" Patreader.pp_palette palette;
Format.eprintf "got %d stitches\n%!" @@ List.length stitches;
Format.eprintf "got %d extras\n%!" @@ List.length extras;
Format.eprintf "got %d knots\n%!" @@ List.length knots;
Format.eprintf "got %d backstitches\n%!" @@ List.length backstitches;
()
let read_one verbose filename =
let open Lwt.Infix in
Lwt_io.open_file ~mode:Input filename >>= fun input ->
if verbose then Format.eprintf "beginning parse for file %s\n%!" filename;
Angstrom_lwt_unix.parse Patreader.file input >>= fun (_, result) ->
match result with
| Error _ as e -> Lwt.return e
| Ok (fabric, metadata, palette, stitches, extras, knots, backstitches) ->
if verbose then spoo (fabric, metadata, palette, stitches, extras, knots, backstitches);
let substrate = Translator.to_substrate fabric in
TODO : this is probably not strictly correct ; I think some entries in the
* stitch list can be half , 3/4 , etc stitches
* stitch list can be half, 3/4, etc stitches *)
let stitches = List.map (fun (coords, color, _stitch) ->
coords, color, (Stitchy.Types.Cross Full)) stitches in
match Translator.to_stitches (fabric, metadata, palette, stitches, backstitches) with
| Error (`Msg e) -> Lwt.return @@ Error e
| Ok (layers, backstitch_layers) -> begin
let pattern = {Stitchy.Types.substrate = substrate;
backstitch_layers;
layers } in
Format.printf "%s" (Stitchy.Types.pattern_to_yojson pattern |> Yojson.Safe.to_string);
Lwt.return (Ok ())
end
let main verbose inputs =
let res =
List.fold_left (fun acc input ->
let res = Lwt_main.run @@ read_one verbose input in
match acc, res with
| e, Ok () -> e
| Ok (), e -> e
| Error e1, Error e2 -> Error (e1 ^ "\n" ^ input ^ ": " ^ e2)
) (Ok ()) inputs
in
let () = match res with
| Error e -> Format.eprintf "%s\n%!" e
| Ok _ when verbose -> Format.printf "successfully completed\n%!"
| Ok _ -> ()
in
res
let read_t = Cmdliner.Term.(const main $ verbose $ input)
let () =
exit @@ (Cmdliner.Cmd.eval_result @@ Cmdliner.Cmd.v info read_t)
| null | https://raw.githubusercontent.com/yomimono/stitchcraft/f2920cb13be030fecab1d23d9320ace051767158/patreader/src/pat2stitchy.ml | ocaml | let input =
let doc = "file from which to read"
and docv = "FILE" in
Cmdliner.Arg.(value & pos_all string [] & info [] ~doc ~docv)
let verbose =
let doc = "print file metadata on stderr"
and docv = "VERBOSE" in
Cmdliner.Arg.(value & flag & info ["v";"verbose"] ~doc ~docv)
let info =
let doc = "read .pat files" in
Cmdliner.Cmd.info "patreader" ~doc
let spoo (fabric, metadata, palette, stitches, extras, knots, backstitches) =
Format.eprintf "metadata: %a\n%!" Patreader.pp_metadata metadata;
Format.eprintf "fabric: %a\n%!" Patreader.pp_fabric fabric;
Format.eprintf "palette: %a\n%!" Patreader.pp_palette palette;
Format.eprintf "got %d stitches\n%!" @@ List.length stitches;
Format.eprintf "got %d extras\n%!" @@ List.length extras;
Format.eprintf "got %d knots\n%!" @@ List.length knots;
Format.eprintf "got %d backstitches\n%!" @@ List.length backstitches;
()
let read_one verbose filename =
let open Lwt.Infix in
Lwt_io.open_file ~mode:Input filename >>= fun input ->
if verbose then Format.eprintf "beginning parse for file %s\n%!" filename;
Angstrom_lwt_unix.parse Patreader.file input >>= fun (_, result) ->
match result with
| Error _ as e -> Lwt.return e
| Ok (fabric, metadata, palette, stitches, extras, knots, backstitches) ->
if verbose then spoo (fabric, metadata, palette, stitches, extras, knots, backstitches);
let substrate = Translator.to_substrate fabric in
TODO : this is probably not strictly correct ; I think some entries in the
* stitch list can be half , 3/4 , etc stitches
* stitch list can be half, 3/4, etc stitches *)
let stitches = List.map (fun (coords, color, _stitch) ->
coords, color, (Stitchy.Types.Cross Full)) stitches in
match Translator.to_stitches (fabric, metadata, palette, stitches, backstitches) with
| Error (`Msg e) -> Lwt.return @@ Error e
| Ok (layers, backstitch_layers) -> begin
let pattern = {Stitchy.Types.substrate = substrate;
backstitch_layers;
layers } in
Format.printf "%s" (Stitchy.Types.pattern_to_yojson pattern |> Yojson.Safe.to_string);
Lwt.return (Ok ())
end
let main verbose inputs =
let res =
List.fold_left (fun acc input ->
let res = Lwt_main.run @@ read_one verbose input in
match acc, res with
| e, Ok () -> e
| Ok (), e -> e
| Error e1, Error e2 -> Error (e1 ^ "\n" ^ input ^ ": " ^ e2)
) (Ok ()) inputs
in
let () = match res with
| Error e -> Format.eprintf "%s\n%!" e
| Ok _ when verbose -> Format.printf "successfully completed\n%!"
| Ok _ -> ()
in
res
let read_t = Cmdliner.Term.(const main $ verbose $ input)
let () =
exit @@ (Cmdliner.Cmd.eval_result @@ Cmdliner.Cmd.v info read_t)
|
|
58389e16580cca3d1253bd1838a11f71d0bcc0e6bcc1e53f5143cef0eb005aac | tonyg/kali-scheme | jar-defrecord.scm | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
; This knows about the implementation of records and creates the various
accessors , mutators , etc . directly instead of calling the procedures
; from the record structure. This is done to allow the optional auto-inlining
optimizer to inline the accessors , mutators , etc .
; LOOPHOLE is used to get a little compile-time type checking (in addition to
; the usual complete run-time checking).
(define-syntax define-record-type
(syntax-rules ()
((define-record-type ?id ?type
(?constructor ?arg ...)
(?field . ?field-stuff)
...)
(begin (define ?type (make-record-type '?id '(?field ...)))
(define-constructor ?constructor ?type
((?arg :value) ...)
(?field ...))
(define-accessors ?type (?field . ?field-stuff) ...)))
((define-record-type ?id ?type
(?constructor ?arg ...)
?pred
?more ...)
(begin (define-record-type ?id ?type
(?constructor ?arg ...)
?more ...)
(define ?pred
(lambda (x)
(and (record? x)
(eq? ?type (record-ref x 0)))))))))
; (define-constructor <id> <type> ((<arg> <arg-type>)*) (<field-name>*))
;
; Checks to see that there is an <arg> corresponding to every <field-name>.
(define-syntax define-constructor
(lambda (e r c)
(let ((%record (r 'record))
(%begin (r 'begin))
(%lambda (r 'lambda))
(%loophole (r 'loophole))
(%proc (r 'proc))
(%unspecific (r 'unspecific))
(name (cadr e))
(type (caddr e))
(args (map car (cadddr e)))
(arg-types (map cadr (cadddr e)))
(fields (caddr (cddr e))))
(define (mem? name list)
(cond ((null? list) #f)
((c name (car list)) #t)
(else
(mem? name (cdr list)))))
(define (every? pred list)
(cond ((null? list) #t)
((pred (car list))
(every? pred (cdr list)))
(else #f)))
(if (every? (lambda (arg)
(mem? arg fields))
args)
`(define ,name
(,%loophole (,%proc ,arg-types ,type)
(,%lambda ,args
(,%record ,type . ,(map (lambda (field)
(if (mem? field args)
field
(list %unspecific)))
fields)))))
e)))
(record begin lambda loophole proc unspecific))
(define-syntax define-accessors
(lambda (e r c)
(let ((%define-accessor (r 'define-accessor))
(%begin (r 'begin))
(type (cadr e))
(field-specs (cddr e)))
(do ((i 1 (+ i 1))
(field-specs field-specs (cdr field-specs))
(ds '()
(cons `(,%define-accessor ,type ,i ,@(cdar field-specs))
ds)))
((null? field-specs)
`(,%begin ,@ds)))))
(define-accessor begin))
(define-syntax define-accessor
(syntax-rules ()
((define-accessor ?type ?index ?accessor)
(define ?accessor
(loophole (proc (?type) :value)
(lambda (r)
(checked-record-ref (loophole :record r) ?type ?index)))))
((define-accessor ?type ?index ?accessor ?modifier)
(begin (define-accessor ?type ?index ?accessor)
(define ?modifier
(loophole (proc (?type :value) :unspecific)
(lambda (r new)
(checked-record-set! (loophole :record r) ?type ?index new))))))
((define-accessor ?type ?index)
(begin))))
| null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/rts/jar-defrecord.scm | scheme | This knows about the implementation of records and creates the various
from the record structure. This is done to allow the optional auto-inlining
LOOPHOLE is used to get a little compile-time type checking (in addition to
the usual complete run-time checking).
(define-constructor <id> <type> ((<arg> <arg-type>)*) (<field-name>*))
Checks to see that there is an <arg> corresponding to every <field-name>. | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
accessors , mutators , etc . directly instead of calling the procedures
optimizer to inline the accessors , mutators , etc .
(define-syntax define-record-type
(syntax-rules ()
((define-record-type ?id ?type
(?constructor ?arg ...)
(?field . ?field-stuff)
...)
(begin (define ?type (make-record-type '?id '(?field ...)))
(define-constructor ?constructor ?type
((?arg :value) ...)
(?field ...))
(define-accessors ?type (?field . ?field-stuff) ...)))
((define-record-type ?id ?type
(?constructor ?arg ...)
?pred
?more ...)
(begin (define-record-type ?id ?type
(?constructor ?arg ...)
?more ...)
(define ?pred
(lambda (x)
(and (record? x)
(eq? ?type (record-ref x 0)))))))))
(define-syntax define-constructor
(lambda (e r c)
(let ((%record (r 'record))
(%begin (r 'begin))
(%lambda (r 'lambda))
(%loophole (r 'loophole))
(%proc (r 'proc))
(%unspecific (r 'unspecific))
(name (cadr e))
(type (caddr e))
(args (map car (cadddr e)))
(arg-types (map cadr (cadddr e)))
(fields (caddr (cddr e))))
(define (mem? name list)
(cond ((null? list) #f)
((c name (car list)) #t)
(else
(mem? name (cdr list)))))
(define (every? pred list)
(cond ((null? list) #t)
((pred (car list))
(every? pred (cdr list)))
(else #f)))
(if (every? (lambda (arg)
(mem? arg fields))
args)
`(define ,name
(,%loophole (,%proc ,arg-types ,type)
(,%lambda ,args
(,%record ,type . ,(map (lambda (field)
(if (mem? field args)
field
(list %unspecific)))
fields)))))
e)))
(record begin lambda loophole proc unspecific))
(define-syntax define-accessors
(lambda (e r c)
(let ((%define-accessor (r 'define-accessor))
(%begin (r 'begin))
(type (cadr e))
(field-specs (cddr e)))
(do ((i 1 (+ i 1))
(field-specs field-specs (cdr field-specs))
(ds '()
(cons `(,%define-accessor ,type ,i ,@(cdar field-specs))
ds)))
((null? field-specs)
`(,%begin ,@ds)))))
(define-accessor begin))
(define-syntax define-accessor
(syntax-rules ()
((define-accessor ?type ?index ?accessor)
(define ?accessor
(loophole (proc (?type) :value)
(lambda (r)
(checked-record-ref (loophole :record r) ?type ?index)))))
((define-accessor ?type ?index ?accessor ?modifier)
(begin (define-accessor ?type ?index ?accessor)
(define ?modifier
(loophole (proc (?type :value) :unspecific)
(lambda (r new)
(checked-record-set! (loophole :record r) ?type ?index new))))))
((define-accessor ?type ?index)
(begin))))
|
068ece6ece3baef017a97453623bd9ea13bc5b41e6d42658e1dec4df3d346bbe | freedesktop/bustle | Setup.hs | # LANGUAGE CPP #
# OPTIONS_GHC -Wall #
#if defined(VERSION_hgettext)
import System.FilePath ( (</>), (<.>) )
import Distribution.PackageDescription
import Distribution.Simple
import Distribution.Simple.BuildPaths ( autogenPackageModulesDir )
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Setup as S
import Distribution.Simple.Utils
import Distribution.Text ( display )
import Distribution.ModuleName (ModuleName)
import qualified Distribution.ModuleName as ModuleName
import qualified GetText
main :: IO ()
main = defaultMainWithHooks $ installBustleHooks simpleUserHooks
-- Okay, so we want to use hgettext's install hook, but not the hook that
miraculously runs all our code through CPP just to add a couple of
constants . ( does n't like multi - line strings , so this is not
-- purely an academic preference.)
--
-- Instead, we generate GetText_bustle.hs which contains the constants, in the
same way as Paths_bustle.hs gets generated by Cabal . Much neater .
--
-- TODO: upstream this to hgettext
installBustleHooks :: UserHooks
-> UserHooks
installBustleHooks uh = uh
{ postInst = \a b c d -> do
postInst uh a b c d
GetText.installPOFiles a b c d
, buildHook = \pkg lbi hooks flags -> do
writeGetTextConstantsFile pkg lbi flags
buildHook uh pkg lbi hooks flags
}
writeGetTextConstantsFile :: PackageDescription -> LocalBuildInfo -> BuildFlags -> IO ()
writeGetTextConstantsFile pkg lbi flags = do
let verbosity = fromFlag (buildVerbosity flags)
createDirectoryIfMissingVerbose verbosity True (autogenPackageModulesDir lbi)
let pathsModulePath = autogenPackageModulesDir lbi
</> ModuleName.toFilePath (getTextConstantsModuleName pkg) <.> "hs"
rewriteFileEx verbosity pathsModulePath (generateModule pkg lbi)
getTextConstantsModuleName :: PackageDescription -> ModuleName
getTextConstantsModuleName pkg_descr =
ModuleName.fromString $
"GetText_" ++ fixedPackageName pkg_descr
Cargo - culted from two separate places in Cabal !
fixedPackageName :: PackageDescription -> String
fixedPackageName = map fixchar . display . packageName
where fixchar '-' = '_'
fixchar c = c
generateModule :: PackageDescription -> LocalBuildInfo -> String
generateModule pkg lbi =
header ++ body
where
moduleName = getTextConstantsModuleName pkg
header =
"module " ++ display moduleName ++ " (\n"++
" getMessageCatalogDomain,\n" ++
" getMessageCatalogDir\n" ++
") where\n"++
"\n" ++
"import qualified Control.Exception as Exception\n" ++
"import System.Environment (getEnv)\n"
body =
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n" ++
"catchIO = Exception.catch\n" ++
"\n" ++
"getMessageCatalogDomain :: IO String\n" ++
"getMessageCatalogDomain = return " ++ show dom ++ "\n" ++
"\n" ++
"messageCatalogDir :: String\n" ++
"messageCatalogDir = " ++ show tar ++ "\n" ++
"\n" ++
"getMessageCatalogDir :: IO FilePath\n" ++
"getMessageCatalogDir = catchIO (getEnv \"" ++ fixedPackageName pkg ++ "_localedir\") (\\_ -> return messageCatalogDir)\n"
sMap = customFieldsPD (localPkgDescr lbi)
dom = GetText.getDomainNameDefault sMap (GetText.getPackageName lbi)
tar = GetText.targetDataDir lbi
-- Cargo-culted from hgettext
#else
import Distribution.Simple
main :: IO ()
main = defaultMain
#endif
| null | https://raw.githubusercontent.com/freedesktop/bustle/e506b5ca71e14af3d2ebd0a63c1b8d3ea0fb1795/Setup.hs | haskell | Okay, so we want to use hgettext's install hook, but not the hook that
purely an academic preference.)
Instead, we generate GetText_bustle.hs which contains the constants, in the
TODO: upstream this to hgettext
Cargo-culted from hgettext | # LANGUAGE CPP #
# OPTIONS_GHC -Wall #
#if defined(VERSION_hgettext)
import System.FilePath ( (</>), (<.>) )
import Distribution.PackageDescription
import Distribution.Simple
import Distribution.Simple.BuildPaths ( autogenPackageModulesDir )
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Setup as S
import Distribution.Simple.Utils
import Distribution.Text ( display )
import Distribution.ModuleName (ModuleName)
import qualified Distribution.ModuleName as ModuleName
import qualified GetText
main :: IO ()
main = defaultMainWithHooks $ installBustleHooks simpleUserHooks
miraculously runs all our code through CPP just to add a couple of
constants . ( does n't like multi - line strings , so this is not
same way as Paths_bustle.hs gets generated by Cabal . Much neater .
installBustleHooks :: UserHooks
-> UserHooks
installBustleHooks uh = uh
{ postInst = \a b c d -> do
postInst uh a b c d
GetText.installPOFiles a b c d
, buildHook = \pkg lbi hooks flags -> do
writeGetTextConstantsFile pkg lbi flags
buildHook uh pkg lbi hooks flags
}
writeGetTextConstantsFile :: PackageDescription -> LocalBuildInfo -> BuildFlags -> IO ()
writeGetTextConstantsFile pkg lbi flags = do
let verbosity = fromFlag (buildVerbosity flags)
createDirectoryIfMissingVerbose verbosity True (autogenPackageModulesDir lbi)
let pathsModulePath = autogenPackageModulesDir lbi
</> ModuleName.toFilePath (getTextConstantsModuleName pkg) <.> "hs"
rewriteFileEx verbosity pathsModulePath (generateModule pkg lbi)
getTextConstantsModuleName :: PackageDescription -> ModuleName
getTextConstantsModuleName pkg_descr =
ModuleName.fromString $
"GetText_" ++ fixedPackageName pkg_descr
Cargo - culted from two separate places in Cabal !
fixedPackageName :: PackageDescription -> String
fixedPackageName = map fixchar . display . packageName
where fixchar '-' = '_'
fixchar c = c
generateModule :: PackageDescription -> LocalBuildInfo -> String
generateModule pkg lbi =
header ++ body
where
moduleName = getTextConstantsModuleName pkg
header =
"module " ++ display moduleName ++ " (\n"++
" getMessageCatalogDomain,\n" ++
" getMessageCatalogDir\n" ++
") where\n"++
"\n" ++
"import qualified Control.Exception as Exception\n" ++
"import System.Environment (getEnv)\n"
body =
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n" ++
"catchIO = Exception.catch\n" ++
"\n" ++
"getMessageCatalogDomain :: IO String\n" ++
"getMessageCatalogDomain = return " ++ show dom ++ "\n" ++
"\n" ++
"messageCatalogDir :: String\n" ++
"messageCatalogDir = " ++ show tar ++ "\n" ++
"\n" ++
"getMessageCatalogDir :: IO FilePath\n" ++
"getMessageCatalogDir = catchIO (getEnv \"" ++ fixedPackageName pkg ++ "_localedir\") (\\_ -> return messageCatalogDir)\n"
sMap = customFieldsPD (localPkgDescr lbi)
dom = GetText.getDomainNameDefault sMap (GetText.getPackageName lbi)
tar = GetText.targetDataDir lbi
#else
import Distribution.Simple
main :: IO ()
main = defaultMain
#endif
|
335e22d2346b7f226542b411b571a70b0e17e5ac96cf1a413db830128b7b7a2a | tcsprojects/pgsolver | localmodelchecker.mli | open Paritygame ;;
val partially_solve : partial_solver
val solve : global_solver
val register: unit -> unit | null | https://raw.githubusercontent.com/tcsprojects/pgsolver/b0c31a8b367c405baed961385ad645d52f648325/src/solvers/localmodelchecker.mli | ocaml | open Paritygame ;;
val partially_solve : partial_solver
val solve : global_solver
val register: unit -> unit |
|
c3ae3fb9ef7e69d4f3855323e0e3dfdf124be4b2eafeeda87300f5882df9ae1e | dgtized/shimmers | point_to_point.cljs | (ns shimmers.sketches.point-to-point
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[shimmers.common.framerate :as framerate]
[shimmers.common.quil :as cq]
[shimmers.math.points :as points]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
;; Some experiments with drawing lines derived from a set of random points
(defn setup []
(q/color-mode :hsl 1.0)
{:circles
(map #(assoc {}
:p %
:theta (- (* 2 Math/PI (rand)) Math/PI)
:radius (tm/clamp (+ 0.05 (* 0.02 (q/random-gaussian))) 0 0.5))
(points/generate 24 #(+ 0.5 (* 0.13 (q/random-gaussian)))))})
(defn sign+
"Increase magnitude of `n` by `v` without changing sign of `n`"
[n v]
((if (> n 0) + -) n v))
(defn update-state [{:keys [circles] :as state}]
(assoc state
:circles
(map #(update % :theta sign+ 0.01) circles)
:points
(for [{:keys [p theta radius]} circles]
(->> (gv/vec2 radius theta)
g/as-cartesian
(g/translate p)))))
(defn all-lines [points]
(doseq [[x y] (map cq/rel-pos points)]
(q/line 0 y (q/width) y)
(q/line x 0 x (q/height))))
(defn closest-edge-point
[[x y]]
(cond (and (>= x 0.5) (>= y 0.5))
(if (> x y)
[1.0 y]
[x 1.0])
(and (< x 0.5) (< y 0.5))
(if (> x y)
[x 0.0]
[0.0 y])
(and (>= x 0.5) (< y 0.5))
(if (> (- 1.0 x) y)
[x 0.0]
[1.0 y])
(and (< x 0.5) (>= y 0.5))
(if (> x (- 1.0 y))
[x 1.0]
[0.0 y])))
(defn draw [{:keys [points]}]
(q/background 1.0 1.0)
(q/stroke-weight 2)
(q/ellipse-mode :radius)
(q/stroke 0 0 0)
(doseq [point (map cq/rel-pos points)]
(cq/circle point 0.2))
(q/stroke-weight 0.5)
(q/stroke 0.99 0.5 0.5)
(doseq [[p q] (take (* 1.2 (count points)) (points/ranked-pairs points))]
(q/line (cq/rel-pos p) (cq/rel-pos q)))
(q/stroke 0 0 0)
(q/stroke-weight 0.2)
(all-lines points)
(q/stroke 0.45 0.3 0.5)
(q/stroke-weight 1.0)
(doseq [p points
:let [q (closest-edge-point p)]]
(q/line (cq/rel-pos p) (cq/rel-pos q))))
(sketch/defquil point-to-point
:created-at "2021-04-02"
:size [600 600]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
| null | https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/sketches/point_to_point.cljs | clojure | Some experiments with drawing lines derived from a set of random points | (ns shimmers.sketches.point-to-point
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[shimmers.common.framerate :as framerate]
[shimmers.common.quil :as cq]
[shimmers.math.points :as points]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.core :as g]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
(defn setup []
(q/color-mode :hsl 1.0)
{:circles
(map #(assoc {}
:p %
:theta (- (* 2 Math/PI (rand)) Math/PI)
:radius (tm/clamp (+ 0.05 (* 0.02 (q/random-gaussian))) 0 0.5))
(points/generate 24 #(+ 0.5 (* 0.13 (q/random-gaussian)))))})
(defn sign+
"Increase magnitude of `n` by `v` without changing sign of `n`"
[n v]
((if (> n 0) + -) n v))
(defn update-state [{:keys [circles] :as state}]
(assoc state
:circles
(map #(update % :theta sign+ 0.01) circles)
:points
(for [{:keys [p theta radius]} circles]
(->> (gv/vec2 radius theta)
g/as-cartesian
(g/translate p)))))
(defn all-lines [points]
(doseq [[x y] (map cq/rel-pos points)]
(q/line 0 y (q/width) y)
(q/line x 0 x (q/height))))
(defn closest-edge-point
[[x y]]
(cond (and (>= x 0.5) (>= y 0.5))
(if (> x y)
[1.0 y]
[x 1.0])
(and (< x 0.5) (< y 0.5))
(if (> x y)
[x 0.0]
[0.0 y])
(and (>= x 0.5) (< y 0.5))
(if (> (- 1.0 x) y)
[x 0.0]
[1.0 y])
(and (< x 0.5) (>= y 0.5))
(if (> x (- 1.0 y))
[x 1.0]
[0.0 y])))
(defn draw [{:keys [points]}]
(q/background 1.0 1.0)
(q/stroke-weight 2)
(q/ellipse-mode :radius)
(q/stroke 0 0 0)
(doseq [point (map cq/rel-pos points)]
(cq/circle point 0.2))
(q/stroke-weight 0.5)
(q/stroke 0.99 0.5 0.5)
(doseq [[p q] (take (* 1.2 (count points)) (points/ranked-pairs points))]
(q/line (cq/rel-pos p) (cq/rel-pos q)))
(q/stroke 0 0 0)
(q/stroke-weight 0.2)
(all-lines points)
(q/stroke 0.45 0.3 0.5)
(q/stroke-weight 1.0)
(doseq [p points
:let [q (closest-edge-point p)]]
(q/line (cq/rel-pos p) (cq/rel-pos q))))
(sketch/defquil point-to-point
:created-at "2021-04-02"
:size [600 600]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
|
115d91b2fd82419213ea85f5251bee774c4be2433d2fbd7e4d2b314062ec4a46 | christoph-frick/factorio-blueprint-tools | tile.cljc | (ns factorio-blueprint-tools.tile
(:require [com.rpl.specter :as s]
[factorio-blueprint-tools.blueprint :as blueprint]))
(defn width-and-height
[blueprint]
(case (blueprint/snap blueprint)
:default
(let [area (blueprint/blueprint-area blueprint)
[[min-x min-y] [max-x max-y]] area
width (Math/ceil (- max-x min-x))
height (Math/ceil (- max-y min-y))]
[width height])
(blueprint/snap-grid blueprint)))
(defn tile-items
[items x-times y-times width height]
(into [] cat (for [y (range y-times)
x (range x-times)]
(map #(blueprint/move-position % (* x width) (* y height)) items))))
(defn tile-entities
[blueprint x-times y-times width height]
(update-in
blueprint
blueprint/entities-get-in
#(blueprint/fix-entity-numbers (tile-items % x-times y-times width height))))
(defn tile-tiles
[blueprint x-times y-times width height]
(update-in
blueprint
blueprint/tiles-get-in
#(tile-items % x-times y-times width height)))
(defn tile
[blueprint x-times y-times]
(if (blueprint/blueprint? blueprint)
(let [[width height] (width-and-height blueprint)]
(cond-> blueprint
(blueprint/has-entities? blueprint)
(tile-entities x-times y-times width height)
(blueprint/has-tiles? blueprint)
(tile-tiles x-times y-times width height)
(not= :default (blueprint/snap blueprint))
(blueprint/set-snap-grid (* width x-times) (* width y-times))))
blueprint))
| null | https://raw.githubusercontent.com/christoph-frick/factorio-blueprint-tools/58da0ed00eae2d53f5fea6691af22daf90f608b7/src/factorio_blueprint_tools/tile.cljc | clojure | (ns factorio-blueprint-tools.tile
(:require [com.rpl.specter :as s]
[factorio-blueprint-tools.blueprint :as blueprint]))
(defn width-and-height
[blueprint]
(case (blueprint/snap blueprint)
:default
(let [area (blueprint/blueprint-area blueprint)
[[min-x min-y] [max-x max-y]] area
width (Math/ceil (- max-x min-x))
height (Math/ceil (- max-y min-y))]
[width height])
(blueprint/snap-grid blueprint)))
(defn tile-items
[items x-times y-times width height]
(into [] cat (for [y (range y-times)
x (range x-times)]
(map #(blueprint/move-position % (* x width) (* y height)) items))))
(defn tile-entities
[blueprint x-times y-times width height]
(update-in
blueprint
blueprint/entities-get-in
#(blueprint/fix-entity-numbers (tile-items % x-times y-times width height))))
(defn tile-tiles
[blueprint x-times y-times width height]
(update-in
blueprint
blueprint/tiles-get-in
#(tile-items % x-times y-times width height)))
(defn tile
[blueprint x-times y-times]
(if (blueprint/blueprint? blueprint)
(let [[width height] (width-and-height blueprint)]
(cond-> blueprint
(blueprint/has-entities? blueprint)
(tile-entities x-times y-times width height)
(blueprint/has-tiles? blueprint)
(tile-tiles x-times y-times width height)
(not= :default (blueprint/snap blueprint))
(blueprint/set-snap-grid (* width x-times) (* width y-times))))
blueprint))
|
|
dd5c65a97ed6f16640abb613e26906ec9785bd5a62ff363008e3065faa663d2e | regex-generate/regenerate | langgen.ml | module type SIGMA = sig
type t
val sigma : t
end
module[@inline always] Make
(Word : Word.S)
(Segment : Segments.S with type elt = Word.t)
(Sigma : SIGMA with type t = Segment.t)
= struct
module Word = Word
module Segment = Segment
(** Spline of a language, a cascade-like thunk list with multiple nils. *)
type node =
| Nothing
| Everything
| Cons of Segment.t * lang
and lang = unit -> node
(** Utilities *)
let segmentEpsilon = Segment.return Word.empty
let nothing () = Nothing
let everything () = Everything
let (@:) h t () = Cons (h, t)
let langEpsilon = segmentEpsilon @: nothing
module IMap = struct
include CCMap.Make(CCInt)
let save k s m =
if Segment.is_empty s then m
else add k (Segment.memoize s) m
end
* Precomputed full language . Used to replace " Everything " when need
module Sigma_star = struct
type t = (Segment.t, CCVector.rw) CCVector.t
let v : t = CCVector.make 1 segmentEpsilon
let rec complete_from_to i j =
if i > j then ()
else
let s = Segment.append Sigma.sigma (CCVector.get v (i-1)) in
CCVector.push v @@ Segment.memoize s;
complete_from_to (i+1) j
let get i =
assert (i >= 0);
let l = CCVector.size v in
if i < l then CCVector.get v i
else begin
CCVector.ensure_with ~init:Segment.empty v (i+1);
complete_from_to l i ;
CCVector.get v i
end
let rec iter n k =
k (get n) ;
iter (n+1) k
end
let pp_item =
Fmt.parens @@
Fmt.hbox @@
Fmt.iter ~sep:(Fmt.unit ", ") (CCFun.flip Segment.to_iter) Word.pp
let pp fmt (l : lang) =
let pp_sep = Fmt.unit "@." in
let rec pp fmt l =
pp_sep fmt ();
match l() with
| Nothing -> Fmt.pf fmt "(Nothing)"
| Everything -> Fmt.pf fmt "(Everything)"
| Cons (x,l') ->
pp_item fmt x ; pp fmt l'
in
pp fmt l
let of_list l =
let rec aux n l () = match l with
| [] -> nothing ()
| _ ->
let x, rest = CCList.partition (fun s -> Word.length s = n) l in
Cons (Segment.of_list x, aux (n+1) rest)
in aux 0 l
* Classic operations
let rec union s1 s2 () = match s1(), s2() with
| Everything, _ | _, Everything -> Everything
| Nothing, x | x, Nothing -> x
| Cons (x1, next1), Cons (x2, next2) ->
Cons (Segment.union x1 x2, union next1 next2)
let rec inter s1 s2 () = match s1(), s2() with
| Everything, x | x, Everything -> x
| Nothing, _ | _, Nothing -> Nothing
| Cons (x1, next1), Cons (x2, next2) ->
Cons (Segment.inter x1 x2, inter next1 next2)
let rec difference_aux i s1 s2 () = match s1(), s2() with
| Nothing, _ -> Nothing
| _, Everything -> Nothing
| x, Nothing -> x
| Everything, Cons (x2, next2) ->
let x1 = Sigma_star.get i and next1 = everything in
Cons (Segment.diff x1 x2, difference_aux (i+1) next1 next2)
| Cons (x1, next1), Cons (x2, next2) ->
Cons (Segment.diff x1 x2, difference_aux (i+1) next1 next2)
let difference = difference_aux 0
let compl = difference everything
(** Concatenation *)
* Invariants for each language :
- [ nbSeg = indices ]
- After [ ] , [ CCVector.size vec > = n ]
- if [ bound = Some n ] then [ n > = nbSeg ] and [ seqₙ = Nothing ] .
- [nbSeg = List.length indices]
- After [explode_head], [CCVector.size vec >= n]
- if [bound = Some n] then [n >= nbSeg] and [seqₙ = Nothing].
*)
let[@inline] explode_head vec (seq, bound, nbSeg, indices) n =
match bound with
| Some _ -> nothing, bound, nbSeg, indices
| None -> match seq() with
| Nothing -> nothing, Some n, nbSeg, indices
| Everything ->
begin if n = CCVector.size vec then
CCVector.push vec @@ Sigma_star.get n
end ;
everything, None, nbSeg+1, n :: indices
| Cons (segm, s) ->
begin if n = CCVector.size vec then
CCVector.push vec @@ Segment.memoize segm
end;
let b = Segment.is_empty segm in
let indices' = if b then indices else n :: indices in
let nbSeg' = if b then nbSeg else nbSeg+1 in
s, None, nbSeg', indices'
let[@inline] concat_subterms_of_length ~n ~f validIndicesA vecA vecB =
let rec combine_segments acc = function
| [] -> acc
| i :: l ->
(* indices are in decreasing order, we can bail early. *)
if n - i >= CCVector.size vecB then acc
else
combine_segments
(f ~a:(CCVector.get vecA i) (CCVector.get vecB (n - i)) :: acc)
l
in
validIndicesA
|> combine_segments []
|> Segment.merge
let[@inline] combine_segments_left ~n indL vecL vecR =
concat_subterms_of_length
~n ~f:(fun ~a b -> Segment.append a b) indL vecL vecR
let[@inline] combine_segments_right ~n vecL indR vecR =
concat_subterms_of_length
~n ~f:(fun ~a b -> Segment.append b a) indR vecR vecL
let concatenate seqL0 seqR0 =
let vecL = CCVector.make 0 Segment.empty in
let vecR = CCVector.make 0 Segment.empty in
let[@specialize] rec collect n descL descR () =
let (_, boundL, nbSegL, indL) as descL = explode_head vecL descL n in
let (_, boundR, nbSegR, indR) as descR = explode_head vecR descR n in
match boundL, boundR with
| Some bL, Some bR when n >= bL + bR - 1 -> Nothing
| Some _, _ when nbSegL = 0 -> Nothing
| _, Some _ when nbSegR = 0 -> Nothing
| _ ->
let head =
if nbSegL <= nbSegR then
combine_segments_left ~n indL vecL vecR
else
combine_segments_right ~n vecL indR vecR
in
let tail = collect (n+1) descL descR in
Cons (head, tail)
in
collect 0 (seqL0, None, 0, []) (seqR0, None, 0, [])
(** Star *)
let star_subterms_of_length ~max validIndices mapS =
let combine_segments (i, segm) =
match IMap.get (max - i) mapS with
| None -> Segment.empty
| Some s -> Segment.append segm s
in
validIndices
|> List.rev_map combine_segments
|> Segment.merge
let star =
let rec collect n mapS seq validIndices () = match seq () with
| Everything -> Everything
| Nothing ->
let segmS = star_subterms_of_length ~max:n validIndices mapS in
let mapS = IMap.save n segmS mapS in
Cons (segmS, collect (n+1) mapS seq validIndices)
| Cons (segm, seq) ->
let validIndices =
if Segment.is_empty segm
then validIndices
else (n, segm) :: validIndices
in
let segmS = star_subterms_of_length ~max:n validIndices mapS in
let mapS = IMap.save n segmS mapS in
Cons (segmS, collect (n+1) mapS seq validIndices)
in
fun s () -> match s() with
| Nothing -> Cons (segmentEpsilon, nothing)
| Everything as v -> v
| Cons (_, seq) ->
match seq() with
| Nothing -> Cons (segmentEpsilon, nothing)
| seq ->
let mS = IMap.singleton 0 segmentEpsilon in
Cons (segmentEpsilon, collect 1 mS (fun () -> seq) [])
let add_epsilonX i x = if i = 0 then union x langEpsilon else x
let dec k = max (k-1) 0
let rec rep_with_acc acc i j lang =
match i, j with
| 0, None -> concatenate acc (star lang)
| 0, Some 0 -> acc
| i, j ->
let acc =
concatenate (add_epsilonX i lang) acc
in
rep_with_acc acc (dec i) (CCOpt.map dec j) lang
let rep i j lang = match i,j with
| 0, None -> star lang
| 0, Some 0 -> langEpsilon
| i, j ->
let acc = add_epsilonX i lang in
rep_with_acc acc (dec i) (CCOpt.map dec j) lang
(** Others *)
let charset b l = match l with
| [] when b -> nothing
| l ->
let set = Segment.of_list @@ List.map Word.singleton l in
let segm1 =
if b then set else Segment.diff Sigma.sigma set
in
Segment.empty @: segm1 @: nothing
(****)
let rec gen : Word.char Regex.t -> lang = function
| Set (b, l) -> charset b l
| One -> langEpsilon
| Seq (r1, r2) -> concatenate (gen r1) (gen r2)
| Or (r1, r2) -> union (gen r1) (gen r2)
| And (r1, r2) -> inter (gen r1) (gen r2)
| Not r -> compl (gen r)
| Rep (i, j, r) -> rep i j (gen r)
(** Exporting *)
let rec flatten_from n s k = match s () with
| Nothing -> ()
| Everything ->
Sigma_star.iter n (fun s -> Segment.to_iter s k)
| Cons (x, s) ->
Segment.to_iter x k;
flatten_from (n+1) s k
let flatten s = flatten_from 0 s
type res = Done | Finite | GaveUp
* [ sample ~skip ~n lang ] returns a sequence of on average [ n ] elements .
[ lang ] is only consumed when needed .
We sample one element every [ k ] , where [ k ] follows a power law of
average [ skip ] . Furthermore , if we consume more than [ sqrt k ] empty segments ,
we assume that the rest of the segments will be infinitely empty and
stop .
If [ firsts ] is provided , we always output the [ firsts ] first elements .
[lang] is only consumed when needed.
We sample one element every [k], where [k] follows a power law of
average [skip]. Furthermore, if we consume more than [sqrt k] empty segments,
we assume that the rest of the segments will be infinitely empty and
stop.
If [firsts] is provided, we always output the [firsts] first elements.
*)
exception ExitSample
let sample ?(st=Random.State.make_self_init ()) ?n ?(firsts=0) ~skip lang (k : _ -> unit) =
let i = ref (-1) in
(* The number of element to always take at the beginning. *)
let rem_firsts = ref firsts in
(* Draw the amount of element we skip and store the next element to take. *)
let draw_skip st =
let f = !rem_firsts in
if f > 0
then (decr rem_firsts ; 0)
else
let u = Random.State.float st 1. in
1 + int_of_float (-. (float skip) *. log1p (-. u))
in
let next = ref (draw_skip st) in
(* Our chance to continue after each sample. *)
let continue st =
match n with
| Some n -> Random.State.float st 1. > (1. /. float n)
| None -> true
in
(* Our "empty segment" budget. If we exceed this, we stop. *)
let budget_of_skip n = 2 + (int_of_float @@ sqrt @@ float n) in
let budget = ref (budget_of_skip !next) in
let onSegm x =
incr i ;
if i < next then ()
else begin
k x ;
if not (continue st) then raise ExitSample
else begin
let newskip = draw_skip st in
next := !next + newskip ;
budget := budget_of_skip newskip ;
end
end
in
let rec walk_lang n seq =
let i0 = !i in
let next segm seq =
match Segment.to_iter segm onSegm with
| exception ExitSample -> Done
| () ->
let i1 = !i in
if i0 <> i1 then walk_lang (n+1) seq
else if !budget < 0 then GaveUp
else begin
decr budget ;
walk_lang (n+1) seq
end
in
match seq () with
| Nothing -> Finite
| Everything ->
let segm = Sigma_star.get n in
next segm everything
| Cons (segm, seq) ->
next segm seq
in
walk_lang 0 lang
end
let arbitrary
(type t) (type char)
(module W : Word.S with type char = char and type t = t)
(module S : Segments.S with type elt = W.t)
?(skip=8)
~compl
~pp
~samples
(alphabet : W.char list) =
let sigma = S.of_list @@ List.map W.singleton alphabet in
let module Sigma = struct type t = S.t let sigma = sigma end in
let module L = Make (W) (S) (Sigma) in
let gen st =
let open QCheck.Gen in
let re = Regex.gen ~compl (oneofl alphabet) st in
Fmt.epr "Regex: %a@." (Regex.pp pp) re;
let print_samples s l =
Fmt.epr "@[<2>%s:@ %a@]@." s Fmt.(list ~sep:(unit ",@ ") W.pp) l
in
let lang = L.gen re in
let f s l =
l
|> L.sample ~st ~skip ~n:samples
|> CCFun.(%) ignore
|> Iter.to_list
|> CCFun.tap (print_samples s)
in
let pos_examples = f "Pos" lang in
let neg_examples = f "Neg" @@ L.compl lang in
(re, pos_examples, neg_examples)
in
let pp fmt (x, l , l') =
Fmt.pf fmt "@[<2>Regex:@ %a@]@.@[<v2>Pos:@ %a@]@.@[<v2>Neg:@ %a@]"
(Regex.pp pp) x Fmt.(list W.pp) l Fmt.(list W.pp) l'
in
let print = Fmt.to_to_string pp in
let small (x, _, _) = Regex.size x in
let shrink = QCheck.Shrink.(triple nil list list) in
QCheck.make ~print ~small ~shrink gen
| null | https://raw.githubusercontent.com/regex-generate/regenerate/a616d6c2faf4a55f794ac9b6fbf03acca91fbeb9/lib/langgen.ml | ocaml | * Spline of a language, a cascade-like thunk list with multiple nils.
* Utilities
* Concatenation
indices are in decreasing order, we can bail early.
* Star
* Others
**
* Exporting
The number of element to always take at the beginning.
Draw the amount of element we skip and store the next element to take.
Our chance to continue after each sample.
Our "empty segment" budget. If we exceed this, we stop. | module type SIGMA = sig
type t
val sigma : t
end
module[@inline always] Make
(Word : Word.S)
(Segment : Segments.S with type elt = Word.t)
(Sigma : SIGMA with type t = Segment.t)
= struct
module Word = Word
module Segment = Segment
type node =
| Nothing
| Everything
| Cons of Segment.t * lang
and lang = unit -> node
let segmentEpsilon = Segment.return Word.empty
let nothing () = Nothing
let everything () = Everything
let (@:) h t () = Cons (h, t)
let langEpsilon = segmentEpsilon @: nothing
module IMap = struct
include CCMap.Make(CCInt)
let save k s m =
if Segment.is_empty s then m
else add k (Segment.memoize s) m
end
* Precomputed full language . Used to replace " Everything " when need
module Sigma_star = struct
type t = (Segment.t, CCVector.rw) CCVector.t
let v : t = CCVector.make 1 segmentEpsilon
let rec complete_from_to i j =
if i > j then ()
else
let s = Segment.append Sigma.sigma (CCVector.get v (i-1)) in
CCVector.push v @@ Segment.memoize s;
complete_from_to (i+1) j
let get i =
assert (i >= 0);
let l = CCVector.size v in
if i < l then CCVector.get v i
else begin
CCVector.ensure_with ~init:Segment.empty v (i+1);
complete_from_to l i ;
CCVector.get v i
end
let rec iter n k =
k (get n) ;
iter (n+1) k
end
let pp_item =
Fmt.parens @@
Fmt.hbox @@
Fmt.iter ~sep:(Fmt.unit ", ") (CCFun.flip Segment.to_iter) Word.pp
let pp fmt (l : lang) =
let pp_sep = Fmt.unit "@." in
let rec pp fmt l =
pp_sep fmt ();
match l() with
| Nothing -> Fmt.pf fmt "(Nothing)"
| Everything -> Fmt.pf fmt "(Everything)"
| Cons (x,l') ->
pp_item fmt x ; pp fmt l'
in
pp fmt l
let of_list l =
let rec aux n l () = match l with
| [] -> nothing ()
| _ ->
let x, rest = CCList.partition (fun s -> Word.length s = n) l in
Cons (Segment.of_list x, aux (n+1) rest)
in aux 0 l
* Classic operations
let rec union s1 s2 () = match s1(), s2() with
| Everything, _ | _, Everything -> Everything
| Nothing, x | x, Nothing -> x
| Cons (x1, next1), Cons (x2, next2) ->
Cons (Segment.union x1 x2, union next1 next2)
let rec inter s1 s2 () = match s1(), s2() with
| Everything, x | x, Everything -> x
| Nothing, _ | _, Nothing -> Nothing
| Cons (x1, next1), Cons (x2, next2) ->
Cons (Segment.inter x1 x2, inter next1 next2)
let rec difference_aux i s1 s2 () = match s1(), s2() with
| Nothing, _ -> Nothing
| _, Everything -> Nothing
| x, Nothing -> x
| Everything, Cons (x2, next2) ->
let x1 = Sigma_star.get i and next1 = everything in
Cons (Segment.diff x1 x2, difference_aux (i+1) next1 next2)
| Cons (x1, next1), Cons (x2, next2) ->
Cons (Segment.diff x1 x2, difference_aux (i+1) next1 next2)
let difference = difference_aux 0
let compl = difference everything
* Invariants for each language :
- [ nbSeg = indices ]
- After [ ] , [ CCVector.size vec > = n ]
- if [ bound = Some n ] then [ n > = nbSeg ] and [ seqₙ = Nothing ] .
- [nbSeg = List.length indices]
- After [explode_head], [CCVector.size vec >= n]
- if [bound = Some n] then [n >= nbSeg] and [seqₙ = Nothing].
*)
let[@inline] explode_head vec (seq, bound, nbSeg, indices) n =
match bound with
| Some _ -> nothing, bound, nbSeg, indices
| None -> match seq() with
| Nothing -> nothing, Some n, nbSeg, indices
| Everything ->
begin if n = CCVector.size vec then
CCVector.push vec @@ Sigma_star.get n
end ;
everything, None, nbSeg+1, n :: indices
| Cons (segm, s) ->
begin if n = CCVector.size vec then
CCVector.push vec @@ Segment.memoize segm
end;
let b = Segment.is_empty segm in
let indices' = if b then indices else n :: indices in
let nbSeg' = if b then nbSeg else nbSeg+1 in
s, None, nbSeg', indices'
let[@inline] concat_subterms_of_length ~n ~f validIndicesA vecA vecB =
let rec combine_segments acc = function
| [] -> acc
| i :: l ->
if n - i >= CCVector.size vecB then acc
else
combine_segments
(f ~a:(CCVector.get vecA i) (CCVector.get vecB (n - i)) :: acc)
l
in
validIndicesA
|> combine_segments []
|> Segment.merge
let[@inline] combine_segments_left ~n indL vecL vecR =
concat_subterms_of_length
~n ~f:(fun ~a b -> Segment.append a b) indL vecL vecR
let[@inline] combine_segments_right ~n vecL indR vecR =
concat_subterms_of_length
~n ~f:(fun ~a b -> Segment.append b a) indR vecR vecL
let concatenate seqL0 seqR0 =
let vecL = CCVector.make 0 Segment.empty in
let vecR = CCVector.make 0 Segment.empty in
let[@specialize] rec collect n descL descR () =
let (_, boundL, nbSegL, indL) as descL = explode_head vecL descL n in
let (_, boundR, nbSegR, indR) as descR = explode_head vecR descR n in
match boundL, boundR with
| Some bL, Some bR when n >= bL + bR - 1 -> Nothing
| Some _, _ when nbSegL = 0 -> Nothing
| _, Some _ when nbSegR = 0 -> Nothing
| _ ->
let head =
if nbSegL <= nbSegR then
combine_segments_left ~n indL vecL vecR
else
combine_segments_right ~n vecL indR vecR
in
let tail = collect (n+1) descL descR in
Cons (head, tail)
in
collect 0 (seqL0, None, 0, []) (seqR0, None, 0, [])
let star_subterms_of_length ~max validIndices mapS =
let combine_segments (i, segm) =
match IMap.get (max - i) mapS with
| None -> Segment.empty
| Some s -> Segment.append segm s
in
validIndices
|> List.rev_map combine_segments
|> Segment.merge
let star =
let rec collect n mapS seq validIndices () = match seq () with
| Everything -> Everything
| Nothing ->
let segmS = star_subterms_of_length ~max:n validIndices mapS in
let mapS = IMap.save n segmS mapS in
Cons (segmS, collect (n+1) mapS seq validIndices)
| Cons (segm, seq) ->
let validIndices =
if Segment.is_empty segm
then validIndices
else (n, segm) :: validIndices
in
let segmS = star_subterms_of_length ~max:n validIndices mapS in
let mapS = IMap.save n segmS mapS in
Cons (segmS, collect (n+1) mapS seq validIndices)
in
fun s () -> match s() with
| Nothing -> Cons (segmentEpsilon, nothing)
| Everything as v -> v
| Cons (_, seq) ->
match seq() with
| Nothing -> Cons (segmentEpsilon, nothing)
| seq ->
let mS = IMap.singleton 0 segmentEpsilon in
Cons (segmentEpsilon, collect 1 mS (fun () -> seq) [])
let add_epsilonX i x = if i = 0 then union x langEpsilon else x
let dec k = max (k-1) 0
let rec rep_with_acc acc i j lang =
match i, j with
| 0, None -> concatenate acc (star lang)
| 0, Some 0 -> acc
| i, j ->
let acc =
concatenate (add_epsilonX i lang) acc
in
rep_with_acc acc (dec i) (CCOpt.map dec j) lang
let rep i j lang = match i,j with
| 0, None -> star lang
| 0, Some 0 -> langEpsilon
| i, j ->
let acc = add_epsilonX i lang in
rep_with_acc acc (dec i) (CCOpt.map dec j) lang
let charset b l = match l with
| [] when b -> nothing
| l ->
let set = Segment.of_list @@ List.map Word.singleton l in
let segm1 =
if b then set else Segment.diff Sigma.sigma set
in
Segment.empty @: segm1 @: nothing
let rec gen : Word.char Regex.t -> lang = function
| Set (b, l) -> charset b l
| One -> langEpsilon
| Seq (r1, r2) -> concatenate (gen r1) (gen r2)
| Or (r1, r2) -> union (gen r1) (gen r2)
| And (r1, r2) -> inter (gen r1) (gen r2)
| Not r -> compl (gen r)
| Rep (i, j, r) -> rep i j (gen r)
let rec flatten_from n s k = match s () with
| Nothing -> ()
| Everything ->
Sigma_star.iter n (fun s -> Segment.to_iter s k)
| Cons (x, s) ->
Segment.to_iter x k;
flatten_from (n+1) s k
let flatten s = flatten_from 0 s
type res = Done | Finite | GaveUp
* [ sample ~skip ~n lang ] returns a sequence of on average [ n ] elements .
[ lang ] is only consumed when needed .
We sample one element every [ k ] , where [ k ] follows a power law of
average [ skip ] . Furthermore , if we consume more than [ sqrt k ] empty segments ,
we assume that the rest of the segments will be infinitely empty and
stop .
If [ firsts ] is provided , we always output the [ firsts ] first elements .
[lang] is only consumed when needed.
We sample one element every [k], where [k] follows a power law of
average [skip]. Furthermore, if we consume more than [sqrt k] empty segments,
we assume that the rest of the segments will be infinitely empty and
stop.
If [firsts] is provided, we always output the [firsts] first elements.
*)
exception ExitSample
let sample ?(st=Random.State.make_self_init ()) ?n ?(firsts=0) ~skip lang (k : _ -> unit) =
let i = ref (-1) in
let rem_firsts = ref firsts in
let draw_skip st =
let f = !rem_firsts in
if f > 0
then (decr rem_firsts ; 0)
else
let u = Random.State.float st 1. in
1 + int_of_float (-. (float skip) *. log1p (-. u))
in
let next = ref (draw_skip st) in
let continue st =
match n with
| Some n -> Random.State.float st 1. > (1. /. float n)
| None -> true
in
let budget_of_skip n = 2 + (int_of_float @@ sqrt @@ float n) in
let budget = ref (budget_of_skip !next) in
let onSegm x =
incr i ;
if i < next then ()
else begin
k x ;
if not (continue st) then raise ExitSample
else begin
let newskip = draw_skip st in
next := !next + newskip ;
budget := budget_of_skip newskip ;
end
end
in
let rec walk_lang n seq =
let i0 = !i in
let next segm seq =
match Segment.to_iter segm onSegm with
| exception ExitSample -> Done
| () ->
let i1 = !i in
if i0 <> i1 then walk_lang (n+1) seq
else if !budget < 0 then GaveUp
else begin
decr budget ;
walk_lang (n+1) seq
end
in
match seq () with
| Nothing -> Finite
| Everything ->
let segm = Sigma_star.get n in
next segm everything
| Cons (segm, seq) ->
next segm seq
in
walk_lang 0 lang
end
let arbitrary
(type t) (type char)
(module W : Word.S with type char = char and type t = t)
(module S : Segments.S with type elt = W.t)
?(skip=8)
~compl
~pp
~samples
(alphabet : W.char list) =
let sigma = S.of_list @@ List.map W.singleton alphabet in
let module Sigma = struct type t = S.t let sigma = sigma end in
let module L = Make (W) (S) (Sigma) in
let gen st =
let open QCheck.Gen in
let re = Regex.gen ~compl (oneofl alphabet) st in
Fmt.epr "Regex: %a@." (Regex.pp pp) re;
let print_samples s l =
Fmt.epr "@[<2>%s:@ %a@]@." s Fmt.(list ~sep:(unit ",@ ") W.pp) l
in
let lang = L.gen re in
let f s l =
l
|> L.sample ~st ~skip ~n:samples
|> CCFun.(%) ignore
|> Iter.to_list
|> CCFun.tap (print_samples s)
in
let pos_examples = f "Pos" lang in
let neg_examples = f "Neg" @@ L.compl lang in
(re, pos_examples, neg_examples)
in
let pp fmt (x, l , l') =
Fmt.pf fmt "@[<2>Regex:@ %a@]@.@[<v2>Pos:@ %a@]@.@[<v2>Neg:@ %a@]"
(Regex.pp pp) x Fmt.(list W.pp) l Fmt.(list W.pp) l'
in
let print = Fmt.to_to_string pp in
let small (x, _, _) = Regex.size x in
let shrink = QCheck.Shrink.(triple nil list list) in
QCheck.make ~print ~small ~shrink gen
|
ebd192d9e518aa3b081c68922e392168025c30734520d2d942d50d95074b01d2 | janestreet/patdiff | import.mli | open! Core
open! Async
include module type of struct
include Expect_test_helpers_core
include Expect_test_helpers_async
end
val links : (string * [ `In_path_as | `In_temp_as ] * string) list
val patdiff : extra_flags:string list -> prev:string -> next:string -> unit Deferred.t
val patdiff_dir
: extra_flags:string list
-> prev:(Filename.t * string) list
-> next:(Filename.t * string) list
-> unit Deferred.t
| null | https://raw.githubusercontent.com/janestreet/patdiff/95b83a1b69f6dac9ab97c612feccbda1ac2c18c9/test/src/import.mli | ocaml | open! Core
open! Async
include module type of struct
include Expect_test_helpers_core
include Expect_test_helpers_async
end
val links : (string * [ `In_path_as | `In_temp_as ] * string) list
val patdiff : extra_flags:string list -> prev:string -> next:string -> unit Deferred.t
val patdiff_dir
: extra_flags:string list
-> prev:(Filename.t * string) list
-> next:(Filename.t * string) list
-> unit Deferred.t
|
|
7b23c8a18644b991fc483b01fc6b68b7e4c7aeccf3f213275107b7f732d221f6 | jvf/scalaris | dht_node.erl | 2007 - 2015 Zuse Institute Berlin
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.
@author < >
%% @doc dht_node main file
%% @end
%% @version $Id$
-module(dht_node).
-author('').
-vsn('$Id$').
-include("scalaris.hrl").
-include("client_types.hrl").
-include("lookup.hrl").
-behaviour(gen_component).
-export([start_link/2, on/2, init/1]).
-export([is_first/1, is_alive/1, is_alive_no_slide/1, is_alive_fully_joined/1]).
-export_type([message/0]).
-include("gen_component.hrl").
-type(database_message() ::
{?get_key, Source_PID::comm:mypid(), SourceId::any(), HashedKey::?RT:key()} |
{get_entries, Source_PID::comm:mypid(), Interval::intervals:interval()} |
{get_entries, Source_PID::comm:mypid(), FilterFun::fun((db_entry:entry()) -> boolean()),
ValFun::fun((db_entry:entry()) -> any())} |
{get_chunk, Source_PID::comm:mypid(), Interval::intervals:interval(), MaxChunkSize::pos_integer() | all} |
{get_chunk, Source_PID::comm:mypid(), Interval::intervals:interval(), FilterFun::fun((db_entry:entry()) -> boolean()),
ValFun::fun((db_entry:entry()) -> any()), MaxChunkSize::pos_integer() | all} |
{update_key_entries, Source_PID::comm:mypid(), [{HashedKey::?RT:key(), NewValue::db_dht:value(), NewVersion::client_version()}]} |
%% % DB subscriptions:
%% {db_set_subscription, SubscrTuple::db_dht:subscr_t()} |
{ db_get_subscription , ( ) , SourcePid::comm : erl_local_pid ( ) } |
{ db_remove_subscription , ( ) } |
% direct DB manipulation:
{get_key_entry, Source_PID::comm:mypid(), HashedKey::?RT:key()} |
{set_key_entry, Source_PID::comm:mypid(), Entry::db_entry:entry()} |
{delete_key, Source_PID::comm:mypid(), ClientsId::{delete_client_id, uid:global_uid()}, HashedKey::?RT:key()} |
{add_data, Source_PID::comm:mypid(), db_dht:db_as_list()} |
{drop_data, Data::db_dht:db_as_list(), Sender::comm:mypid()}).
-type(lookup_message() ::
{?lookup_aux, Key::?RT:key(), Hops::pos_integer(), Msg::comm:message()} |
{?lookup_fin, Key::?RT:key(), Data::dht_node_lookup:data(), Msg::comm:message()}).
-type(snapshot_message() ::
{do_snapshot, SnapNumber::non_neg_integer(), Leader::comm:mypid()} |
{local_snapshot_is_done}).
-type(rt_message() ::
{rt_update, RoutingTable::?RT:external_rt()}).
-type(misc_message() ::
{get_yaws_info, Pid::comm:mypid()} |
{get_state, Pid::comm:mypid(), Which::dht_node_state:name()} |
{get_node_details, Pid::comm:mypid()} |
{get_node_details, Pid::comm:mypid(), Which::[node_details:node_details_name()]} |
{get_pid_group, Pid::comm:mypid()} |
{dump} |
{web_debug_info, Requestor::comm:erl_local_pid()} |
{get_dht_nodes_response, KnownHosts::[comm:mypid()]} |
{unittest_get_bounds_and_data, SourcePid::comm:mypid(), full | kv}).
% accepted messages of dht_node processes
-type message() ::
bulkowner:bulkowner_msg() |
database_message() |
lookup_message() |
dht_node_join:join_message() |
rt_message() |
dht_node_move:move_message() |
misc_message() |
snapshot_message() |
{zombie, Node::node:node_type()} |
{fd_notify, fd:event(), DeadPid::comm:mypid(), Reason::fd:reason()} |
{leave, SourcePid::comm:erl_local_pid() | null} |
{rejoin, IdVersion::non_neg_integer(), JoinOptions::[tuple()],
{get_move_state_response, MoveState::[tuple()]}}.
%% @doc message handler
-spec on(message(), dht_node_state:state()) -> dht_node_state:state() | kill.
Join messages ( see dht_node_join.erl )
%% userdevguide-begin dht_node:join_message
on(Msg, State) when join =:= element(1, Msg) ->
lb_stats:set_ignore_db_requests(true),
NewState = dht_node_join:process_join_msg(Msg, State),
lb_stats:set_ignore_db_requests(false),
NewState;
%% userdevguide-end dht_node:join_message
% Move messages (see dht_node_move.erl)
on(Msg, State) when move =:= element(1, Msg) ->
lb_stats:set_ignore_db_requests(true),
NewState = dht_node_move:process_move_msg(Msg, State),
lb_stats:set_ignore_db_requests(false),
NewState;
% Lease management messages (see l_on_cseq.erl)
on(Msg, State) when l_on_cseq =:= element(1, Msg) ->
l_on_cseq:on(Msg, State);
% RM messages (see rm_loop.erl)
on(Msg, State) when element(1, Msg) =:= rm ->
RMState = dht_node_state:get(State, rm_state),
RMState1 = rm_loop:on(Msg, RMState),
dht_node_state:set_rm(State, RMState1);
on({leave, SourcePid}, State) ->
dht_node_move:make_slide_leave(State, SourcePid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Finger Maintenance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on({rt_update, RoutingTable}, State) ->
dht_node_state:set_rt(State, RoutingTable);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Transactions (see transactions/*.erl)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on({get_rtm, Source_PID, Key, Process}, State) ->
case pid_groups:get_my(Process) of
failed ->
R = config:read(replication_factor),
case Process of
{tx_rtm,X} when X =< R ->
these rtms are concurrently started by the supervisor
%% we just have to wait a bit...
comm:send_local(self(),
{get_rtm, Source_PID, Key, Process});
_ ->
log:log(warn, "[ ~.0p ] requested non-existing rtm ~.0p~n",
[comm:this(), Process])
end;
Pid ->
GPid = comm:make_global(Pid),
GPidAcc = comm:make_global(tx_tm_rtm:get_my(Process, acceptor)),
comm:send(Source_PID, {get_rtm_reply, Key, GPid, GPidAcc})
end,
State;
%% messages handled as a transaction participant (TP)
on({?init_TP, {_Tid, _RTMs, _Accs, _TM, _RTLogEntry, _ItemId, _PaxId, SnapNo} = Params}, State) ->
% check if new snapshot
SnapState = dht_node_state:get(State,snapshot_state),
LocalSnapNumber = snapshot_state:get_number(SnapState),
case SnapNo > LocalSnapNumber of
true ->
comm:send(comm:this(), {do_snapshot, SnapNo, none});
false ->
ok
end,
tx_tp:on_init_TP(Params, State);
on({?tp_do_commit_abort, Id, Result, SnapNumber}, State) ->
tx_tp:on_do_commit_abort(Id, Result, SnapNumber, State);
on({?tp_do_commit_abort_fwd, TM, TMItemId, RTLogEntry, Result, OwnProposal, SnapNumber}, State) ->
tx_tp:on_do_commit_abort_fwd(TM, TMItemId, RTLogEntry, Result, OwnProposal, SnapNumber, State);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Lookup ( see api_dht_raw.erl and dht_node_lookup.erl )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on({?lookup_aux, Key, Hops, Msg}=FullMsg, State) ->
%% Forward msg to the routing_table (rt_loop).
%% If possible, messages should be sent directly to routing_table (rt_loop).
%% Only forward messages for which we aren't responsible (leases).
%% log:pal("lookup_aux_leases in dht_node"),
case config:read(leases) of
true ->
%% Check lease and translate to lookup_fin or forward to rt_loop
%% accordingly.
dht_node_lookup:lookup_aux_leases(State, Key, Hops, Msg);
_ ->
%% simply forward the message to routing_table (rt_loop)
comm:send_local(pid_groups:get_my(routing_table), FullMsg)
end,
State;
on({lookup_decision, Key, Hops, Msg}, State) ->
%% message from rt_loop requesting a decision about a aux-fin transformation
%% (chord only)
dht_node_lookup:lookup_decision_chord(State, Key, Hops, Msg),
State;
on({?lookup_fin, Key, Data, Msg}, State) ->
dht_node_lookup:lookup_fin(State, Key, Data, Msg);
on({send_error, Target, {?lookup_aux, _, _, _} = Message, _Reason}, State) ->
dht_node_lookup:lookup_aux_failed(State, Target, Message);
on({send_error, Target, {?send_to_group_member, routing_table,
{?lookup_aux, _Key, _Hops, _Msg} = Message}, _Reason}, State) ->
dht_node_lookup:lookup_aux_failed(State, Target, Message);
on({send_failed , { send_error , Target , { ? lookup_aux , _ , _ , _ } } = Message , _ Reason } , _ Pids } } , State ) - >
dht_node_lookup : lookup_aux_failed(State , Target , Message ) ;
on({send_error, Target, {?lookup_fin, _, _, _} = Message, _Reason}, State) ->
dht_node_lookup:lookup_fin_failed(State, Target, Message);
%% messages handled as a prbr
on(X, State) when is_tuple(X) andalso element(1, X) =:= prbr ->
as prbr has several use cases ( may operate on different DBs ) in
the dht_node , the addressed use case is given in the third
%% element by convention.
DBKind = element(3, X),
PRBRState = dht_node_state:get(State, DBKind),
NewRBRState = prbr:on(X, PRBRState),
dht_node_state:set_prbr_state(State, DBKind, NewRBRState);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Database
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on({?get_key, Source_PID, SourceId, HashedKey}, State) ->
Msg = {?get_key_with_id_reply, SourceId, HashedKey,
db_dht:read(dht_node_state:get(State, db), HashedKey)},
comm:send(Source_PID, Msg),
State;
on({?read_op, Source_PID, SourceId, HashedKey, Op}, State) ->
DB = dht_node_state:get(State, db),
{ok, Value, Version} = db_dht:read(DB, HashedKey),
{Ok_Fail, Val_Reason, Vers} = rdht_tx_read:extract_from_value(Value, Version, Op),
SnapInfo = dht_node_state:get(State, snapshot_state),
SnapNumber = snapshot_state:get_number(SnapInfo),
Msg = {?read_op_with_id_reply, SourceId, SnapNumber, Ok_Fail, Val_Reason, Vers},
comm:send(Source_PID, Msg),
State;
on({get_entries, Source_PID, Interval}, State) ->
Entries = db_dht:get_entries(dht_node_state:get(State, db), Interval),
comm:send_local(Source_PID, {get_entries_response, Entries}),
State;
on({get_entries, Source_PID, FilterFun, ValFun}, State) ->
Entries = db_dht:get_entries(dht_node_state:get(State, db), FilterFun, ValFun),
comm:send_local(Source_PID, {get_entries_response, Entries}),
State;
on({get_data, Source_PID}, State) ->
Data = db_dht:get_data(dht_node_state:get(State, db)),
comm:send_local(Source_PID, {get_data_response, Data}),
State;
on({get_data, Source_PID, FilterFun, ValueFun}, State) ->
Data = db_dht:get_data(dht_node_state:get(State, db), FilterFun, ValueFun),
comm:send_local(Source_PID, {get_data_response, Data}),
State;
on({get_chunk, Source_PID, Interval, MaxChunkSize}, State) ->
Chunk = db_dht:get_chunk(dht_node_state:get(State, db),
dht_node_state:get(State, pred_id),
Interval, MaxChunkSize),
comm:send_local(Source_PID, {get_chunk_response, Chunk}),
State;
on({get_chunk, Source_PID, Interval, FilterFun, ValueFun, MaxChunkSize}, State) ->
Chunk = db_dht:get_chunk(dht_node_state:get(State, db),
dht_node_state:get(State, pred_id),
Interval, FilterFun, ValueFun, MaxChunkSize),
comm:send_local(Source_PID, {get_chunk_response, Chunk}),
State;
on({update_key_entries, Source_PID, KvvList}, State) ->
DB = dht_node_state:get(State, db),
{NewDB, NewEntryList} = update_key_entries(KvvList, DB, State, []),
% send caller update_key_entries_ack with list of {Entry, Exists (Yes/No), Updated (Yes/No)}
comm:send(Source_PID, {update_key_entries_ack, NewEntryList}),
dht_node_state:set_db(State, NewDB);
on({db_set_subscription , SubscrTuple } , State ) - >
DB2 = db_dht : set_subscription(dht_node_state : get(State , db ) , ) ,
%% dht_node_state:set_db(State, DB2);
%%
on({db_get_subscription , Tag , SourcePid } , State ) - >
Subscr = db_dht : get_subscription(dht_node_state : get(State , db ) , Tag ) ,
comm : send_local(SourcePid , { db_get_subscription_response , Tag , Subscr } ) ,
State ;
%%
on({db_remove_subscription , Tag } , State ) - >
DB2 = db_dht : remove_subscription(dht_node_state : get(State , db ) , Tag ) ,
%% dht_node_state:set_db(State, DB2);
on({delete_key, Source_PID, ClientsId, HashedKey}, State) ->
{DB2, Result} = db_dht:delete(dht_node_state:get(State, db), HashedKey),
comm:send(Source_PID, {delete_key_response, ClientsId, HashedKey, Result}),
dht_node_state:set_db(State, DB2);
%% for unit testing only: allow direct DB manipulation
on({get_key_entry, Source_PID, HashedKey}, State) ->
Entry = db_dht:get_entry(dht_node_state:get(State, db), HashedKey),
comm:send(Source_PID, {get_key_entry_reply, Entry}),
State;
on({set_key_entry, Source_PID, Entry}, State) ->
NewDB = db_dht:set_entry(dht_node_state:get(State, db), Entry),
comm:send(Source_PID, {set_key_entry_reply, Entry}),
dht_node_state:set_db(State, NewDB);
on({add_data, Source_PID, Data}, State) ->
NewDB = db_dht:add_data(dht_node_state:get(State, db), Data),
comm:send(Source_PID, {add_data_reply}),
dht_node_state:set_db(State, NewDB);
on({delete_keys, Source_PID, HashedKeys}, State) ->
DB2 = db_dht:delete_entries(dht_node_state:get(State, db), intervals:from_elements(HashedKeys)),
comm:send(Source_PID, {delete_keys_reply}),
dht_node_state:set_db(State, DB2);
on({drop_data, Data, Sender}, State) ->
comm:send(Sender, {drop_data_ack}),
DB = db_dht:add_data(dht_node_state:get(State, db), Data),
dht_node_state:set_db(State, DB);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Bulk owner messages ( see bulkowner.erl )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on(Msg, State) when bulkowner =:= element(1, Msg) ->
bulkowner:on(Msg, State);
on({send_error, _FailedTarget, FailedMsg, _Reason} = Msg, State)
when bulkowner =:= element(1, FailedMsg) ->
bulkowner:on(Msg, State);
on({bulk_distribute, _Id, _Range, InnerMsg, _Parents} = Msg, State)
when mr =:= element(1, InnerMsg) ->
mr:on(Msg, State);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% map reduce related messages (see mr.erl)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on(Msg, State) when mr =:= element(1, Msg) ->
mr:on(Msg, State);
on(Msg, State) when mr_master =:= element(1, Msg) ->
try
mr_master:on(Msg, State)
catch
error:function_clause ->
log:log(warn, "Received Message to non-existing master...ignoring!"),
State
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
active load balancing messages ( see )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on(Msg, State) when lb_active =:= element(1, Msg) ->
lb_active:handle_dht_msg(Msg, State);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% handling of failed sends
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Misc.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
on({get_yaws_info, Pid}, State) ->
comm:send(Pid, {get_yaws_info_response, comm:get_ip(comm:this()), config:read(yaws_port), pid_groups:my_groupname()}),
State;
on({get_state, Pid, Which}, State) when is_list(Which) ->
comm:send(Pid, {get_state_response,
[{X, dht_node_state:get(State, X)} || X <- Which]}),
State;
on({get_state, Pid, Which}, State) when is_atom(Which) ->
comm:send(Pid, {get_state_response, dht_node_state:get(State, Which)}),
State;
on({set_state, Pid, F}, State) when is_function(F) ->
?ASSERT(util:is_unittest()), % may only be used in unit-tests
NewState = F(State),
comm:send(Pid, {set_state_response, NewState}),
NewState;
on({get_node_details, Pid}, State) ->
comm:send(Pid, {get_node_details_response, dht_node_state:details(State)}),
State;
on({get_node_details, Pid, Which}, State) ->
comm:send(Pid, {get_node_details_response, dht_node_state:details(State, Which)}),
State;
on({get_pid_group, Pid}, State) ->
comm:send(Pid, {get_pid_group_response, pid_groups:my_groupname()}),
State;
on({dump}, State) ->
dht_node_state:dump(State),
State;
on({web_debug_info, Requestor}, State) ->
RMState = dht_node_state:get(State, rm_state),
Load = dht_node_state:get(State, load),
get a list of up to 50 KV pairs to display :
DataListTmp = [{"",
webhelpers:safe_html_string("~p", [DBEntry])}
|| DBEntry <- element(2, db_dht:get_chunk(dht_node_state:get(State, db),
dht_node_state:get(State, node_id),
intervals:all(), 50))],
DataList = case Load > 50 of
true -> lists:append(DataListTmp, [{"...", ""}]);
false -> DataListTmp
end,
KVList1 =
[{"rt_algorithm", webhelpers:safe_html_string("~p", [?RT])},
{"rt_size", dht_node_state:get(State, rt_size)},
{"my_range", webhelpers:safe_html_string("~p", [intervals:get_bounds(dht_node_state:get(State, my_range))])},
{"db_range", webhelpers:safe_html_string("~p", [dht_node_state:get(State, db_range)])},
{"load", webhelpers:safe_html_string("~p", [Load])},
{"join_time", webhelpers:safe_html_string("~p UTC", [calendar:now_to_universal_time(dht_node_state:get(State, join_time))])},
%% {"db", webhelpers:safe_html_string("~p", [dht_node_state:get(State, db)])},
{ " proposer " , webhelpers : safe_html_string("~p " , [ pid_groups : ) ] ) } ,
{"tx_tp_db", webhelpers:safe_html_string("~p", [dht_node_state:get(State, tx_tp_db)])},
{"slide_pred", webhelpers:safe_html_string("~p", [dht_node_state:get(State, slide_pred)])},
{"slide_succ", webhelpers:safe_html_string("~p", [dht_node_state:get(State, slide_succ)])},
{"msg_fwd", webhelpers:safe_html_string("~p", [dht_node_state:get(State, msg_fwd)])}
],
KVList2 = lists:append(KVList1, [{"", ""} | rm_loop:get_web_debug_info(RMState)]),
KVList3 = lists:append(KVList2, [{"", ""} , {"data (db_entry):", ""} | DataList]),
comm:send_local(Requestor, {web_debug_info_reply, KVList3}),
State;
on({unittest_get_bounds_and_data, SourcePid, Type}, State) ->
MyRange = dht_node_state:get(State, my_range),
MyBounds = intervals:get_bounds(MyRange),
DB = dht_node_state:get(State, db),
Data =
case Type of
kv ->
element(
2,
db_dht:get_chunk(
DB, ?MINUS_INFINITY, intervals:all(),
fun(_) -> true end,
fun(E) -> {db_entry:get_key(E), db_entry:get_version(E)} end,
all));
full ->
db_dht:get_data(DB)
end,
Pred = dht_node_state:get(State, pred),
Succ = dht_node_state:get(State, succ),
comm:send(SourcePid, {unittest_get_bounds_and_data_response, MyBounds, Data, Pred, Succ}),
State;
on({unittest_consistent_send, Pid, _X} = Msg, State) ->
?ASSERT(util:is_unittest()),
comm:send_local(Pid, Msg),
State;
on({get_dht_nodes_response, _KnownHosts}, State) ->
% will ignore these messages after join
State;
on({fd_notify, Event, DeadPid, Data}, State) ->
% TODO: forward to further integrated modules, e.g. join?
RMState = dht_node_state:get(State, rm_state),
RMState1 = rm_loop:fd_notify(RMState, Event, DeadPid, Data),
dht_node_state:set_rm(State, RMState1);
% dead-node-cache reported dead node to be alive again
on({zombie, Node}, State) ->
RMState = dht_node_state:get(State, rm_state),
RMState1 = rm_loop:zombie_node(RMState, Node),
% TODO: call other modules, e.g. join, move
dht_node_state:set_rm(State, RMState1);
on({do_snapshot, SnapNumber, Leader}, State) ->
snapshot:on_do_snapshot(SnapNumber, Leader, State);
on({local_snapshot_is_done}, State) ->
snapshot:on_local_snapshot_is_done(State);
on({rejoin, Id, Options, {get_move_state_response, MoveState}}, State) ->
% clean up RM, e.g. fd subscriptions:
rm_loop:cleanup(dht_node_state:get(State, rm_state)),
%% start new join
comm:send_local(self(), {join, start}),
JoinOptions = [{move_state, MoveState} | Options],
IdVersion = node:id_version(dht_node_state:get(State, node)),
dht_node_state:delete_for_rejoin(State), % clean up state!
dht_node_join:join_as_other(Id, IdVersion+1, JoinOptions).
%% userdevguide-begin dht_node:start
%% @doc joins this node in the ring and calls the main loop
-spec init(Options::[tuple()])
-> dht_node_state:state() |
{'$gen_component', [{on_handler, Handler::gen_component:handler()}], State::dht_node_join:join_state()}.
init(Options) ->
{my_sup_dht_node_id, MySupDhtNode} = lists:keyfind(my_sup_dht_node_id, 1, Options),
erlang:put(my_sup_dht_node_id, MySupDhtNode),
% start trigger here to prevent infection when tracing e.g. node joins
% (otherwise the trigger would be started at the end of the join and thus
% be infected forever)
% NOTE: any trigger started here, needs an exception for queuing messages
in dht_node_join to prevent infection with msg_queue : send/1 !
rm_loop:init_first(),
dht_node_move:send_trigger(),
Recover = config:read(start_type) =:= recover,
case {is_first(Options), config:read(leases), Recover, is_add_nodes(Options)} of
{_ , true, true, false} ->
% we are recovering
dht_node_join_recover:join(Options);
{true, true, false, _} ->
msg_delay:send_trigger(1, {l_on_cseq, renew_leases}),
Id = l_on_cseq:id(intervals:all()),
TmpState = dht_node_join:join_as_first(Id, 0, Options),
we have to inject the first lease by hand , as otherwise
%% no routing will work.
l_on_cseq:add_first_lease_to_db(Id, TmpState);
{false, true, _, true} ->
msg_delay:send_trigger(1, {l_on_cseq, renew_leases}),
% get my ID (if set, otherwise chose a random ID):
Id = case lists:keyfind({dht_node, id}, 1, Options) of
{{dht_node, id}, IdX} -> IdX;
_ -> ?RT:get_random_node_id()
end,
dht_node_join:join_as_other(Id, 0, Options);
{IsFirst, _, _, _} ->
% get my ID (if set, otherwise chose a random ID):
Id = case lists:keyfind({dht_node, id}, 1, Options) of
{{dht_node, id}, IdX} -> IdX;
_ -> ?RT:get_random_node_id()
end,
if IsFirst -> dht_node_join:join_as_first(Id, 0, Options);
true -> dht_node_join:join_as_other(Id, 0, Options)
end
end.
%% userdevguide-end dht_node:start
userdevguide - begin dht_node : start_link
@doc spawns a scalaris node , called by the scalaris supervisor process
-spec start_link(pid_groups:groupname(), [tuple()]) -> {ok, pid()}.
start_link(DHTNodeGroup, Options) ->
gen_component:start_link(?MODULE, fun ?MODULE:on/2, Options,
[{pid_groups_join_as, DHTNodeGroup, dht_node},
{wait_for_init},
{spawn_opts, [{fullsweep_after, 0},
{min_heap_size, 131071}]}]).
userdevguide - end dht_node : start_link
@doc Checks whether this VM is marked as first , e.g. in a unit test , and
this is the first node in this VM .
-spec is_first([tuple()]) -> boolean().
is_first(Options) ->
lists:member({first}, Options) andalso admin_first:is_first_vm().
-spec is_add_nodes([tuple()]) -> boolean().
is_add_nodes(Options) ->
lists:member({add_node}, Options).
-spec is_alive(State::dht_node_join:join_state() | dht_node_state:state() | term()) -> boolean().
is_alive(State) ->
erlang:is_tuple(State) andalso element(1, State) =:= state.
-spec is_alive_no_slide(State::dht_node_join:join_state() | dht_node_state:state() | term()) -> boolean().
is_alive_no_slide(State) ->
try
SlidePred = dht_node_state:get(State, slide_pred), % note: this also tests dht_node_state:state()
SlideSucc = dht_node_state:get(State, slide_succ),
SlidePred =:= null andalso SlideSucc =:= null
catch _:_ -> false
end.
-spec is_alive_fully_joined(State::dht_node_join:join_state() | dht_node_state:state() | term()) -> boolean().
is_alive_fully_joined(State) ->
try
SlidePred = dht_node_state:get(State, slide_pred), % note: this also tests dht_node_state:state()
(SlidePred =:= null orelse not slide_op:is_join(SlidePred, 'rcv'))
catch _:_ -> false
end.
-spec update_key_entries(Entries::[{?RT:key(), db_dht:value(), client_version()}],
DB, dht_node_state:state(), NewEntries) -> {DB, NewEntries}
when is_subtype(DB, db_dht:db()),
is_subtype(NewEntries, [{db_entry:entry(), Exists::boolean(), Done::boolean()}]).
update_key_entries([], DB, _State, NewEntries) ->
{DB, lists:reverse(NewEntries)};
update_key_entries([{Key, NewValue, NewVersion} | Entries], DB, State, NewEntries) ->
IsResponsible = dht_node_state:is_db_responsible(Key, State),
Entry = db_dht:get_entry(DB, Key),
Exists = not db_entry:is_null(Entry),
EntryVersion = db_entry:get_version(Entry),
WL = db_entry:get_writelock(Entry),
DoUpdate = Exists
andalso EntryVersion =/= -1
andalso EntryVersion < NewVersion
andalso (WL =:= false orelse WL < NewVersion)
andalso IsResponsible,
DoRegen = (not Exists) andalso IsResponsible,
log : pal("update_key_entries:~nold : ~p ~ : ~p ~ nDoUpdate : ~w , : ~w " ,
[ { db_entry : ) , db_entry : get_version(Entry ) } ,
{ Key , NewVersion } , DoUpdate , ] ) ,
if
DoUpdate ->
UpdEntry = db_entry:set_value(Entry, NewValue, NewVersion),
NewEntry = if WL < NewVersion -> db_entry:reset_locks(UpdEntry);
true -> UpdEntry
end,
NewDB = db_dht:update_entry(DB, NewEntry),
ok;
DoRegen ->
NewEntry = db_entry:new(Key, NewValue, NewVersion),
NewDB = db_dht:set_entry(DB, NewEntry),
ok;
true ->
NewDB = DB,
NewEntry = Entry,
ok
end,
update_key_entries(Entries, NewDB, State,
[{NewEntry, Exists, DoUpdate orelse DoRegen} | NewEntries]).
| null | https://raw.githubusercontent.com/jvf/scalaris/c069f44cf149ea6c69e24bdb08714bda242e7ee0/src/dht_node.erl | erlang | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc dht_node main file
@end
@version $Id$
% DB subscriptions:
{db_set_subscription, SubscrTuple::db_dht:subscr_t()} |
direct DB manipulation:
accepted messages of dht_node processes
@doc message handler
userdevguide-begin dht_node:join_message
userdevguide-end dht_node:join_message
Move messages (see dht_node_move.erl)
Lease management messages (see l_on_cseq.erl)
RM messages (see rm_loop.erl)
Finger Maintenance
Transactions (see transactions/*.erl)
we just have to wait a bit...
messages handled as a transaction participant (TP)
check if new snapshot
Forward msg to the routing_table (rt_loop).
If possible, messages should be sent directly to routing_table (rt_loop).
Only forward messages for which we aren't responsible (leases).
log:pal("lookup_aux_leases in dht_node"),
Check lease and translate to lookup_fin or forward to rt_loop
accordingly.
simply forward the message to routing_table (rt_loop)
message from rt_loop requesting a decision about a aux-fin transformation
(chord only)
messages handled as a prbr
element by convention.
send caller update_key_entries_ack with list of {Entry, Exists (Yes/No), Updated (Yes/No)}
dht_node_state:set_db(State, DB2);
dht_node_state:set_db(State, DB2);
for unit testing only: allow direct DB manipulation
map reduce related messages (see mr.erl)
handling of failed sends
Misc.
may only be used in unit-tests
{"db", webhelpers:safe_html_string("~p", [dht_node_state:get(State, db)])},
will ignore these messages after join
TODO: forward to further integrated modules, e.g. join?
dead-node-cache reported dead node to be alive again
TODO: call other modules, e.g. join, move
clean up RM, e.g. fd subscriptions:
start new join
clean up state!
userdevguide-begin dht_node:start
@doc joins this node in the ring and calls the main loop
start trigger here to prevent infection when tracing e.g. node joins
(otherwise the trigger would be started at the end of the join and thus
be infected forever)
NOTE: any trigger started here, needs an exception for queuing messages
we are recovering
no routing will work.
get my ID (if set, otherwise chose a random ID):
get my ID (if set, otherwise chose a random ID):
userdevguide-end dht_node:start
note: this also tests dht_node_state:state()
note: this also tests dht_node_state:state() | 2007 - 2015 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
-module(dht_node).
-author('').
-vsn('$Id$').
-include("scalaris.hrl").
-include("client_types.hrl").
-include("lookup.hrl").
-behaviour(gen_component).
-export([start_link/2, on/2, init/1]).
-export([is_first/1, is_alive/1, is_alive_no_slide/1, is_alive_fully_joined/1]).
-export_type([message/0]).
-include("gen_component.hrl").
-type(database_message() ::
{?get_key, Source_PID::comm:mypid(), SourceId::any(), HashedKey::?RT:key()} |
{get_entries, Source_PID::comm:mypid(), Interval::intervals:interval()} |
{get_entries, Source_PID::comm:mypid(), FilterFun::fun((db_entry:entry()) -> boolean()),
ValFun::fun((db_entry:entry()) -> any())} |
{get_chunk, Source_PID::comm:mypid(), Interval::intervals:interval(), MaxChunkSize::pos_integer() | all} |
{get_chunk, Source_PID::comm:mypid(), Interval::intervals:interval(), FilterFun::fun((db_entry:entry()) -> boolean()),
ValFun::fun((db_entry:entry()) -> any()), MaxChunkSize::pos_integer() | all} |
{update_key_entries, Source_PID::comm:mypid(), [{HashedKey::?RT:key(), NewValue::db_dht:value(), NewVersion::client_version()}]} |
{ db_get_subscription , ( ) , SourcePid::comm : erl_local_pid ( ) } |
{ db_remove_subscription , ( ) } |
{get_key_entry, Source_PID::comm:mypid(), HashedKey::?RT:key()} |
{set_key_entry, Source_PID::comm:mypid(), Entry::db_entry:entry()} |
{delete_key, Source_PID::comm:mypid(), ClientsId::{delete_client_id, uid:global_uid()}, HashedKey::?RT:key()} |
{add_data, Source_PID::comm:mypid(), db_dht:db_as_list()} |
{drop_data, Data::db_dht:db_as_list(), Sender::comm:mypid()}).
-type(lookup_message() ::
{?lookup_aux, Key::?RT:key(), Hops::pos_integer(), Msg::comm:message()} |
{?lookup_fin, Key::?RT:key(), Data::dht_node_lookup:data(), Msg::comm:message()}).
-type(snapshot_message() ::
{do_snapshot, SnapNumber::non_neg_integer(), Leader::comm:mypid()} |
{local_snapshot_is_done}).
-type(rt_message() ::
{rt_update, RoutingTable::?RT:external_rt()}).
-type(misc_message() ::
{get_yaws_info, Pid::comm:mypid()} |
{get_state, Pid::comm:mypid(), Which::dht_node_state:name()} |
{get_node_details, Pid::comm:mypid()} |
{get_node_details, Pid::comm:mypid(), Which::[node_details:node_details_name()]} |
{get_pid_group, Pid::comm:mypid()} |
{dump} |
{web_debug_info, Requestor::comm:erl_local_pid()} |
{get_dht_nodes_response, KnownHosts::[comm:mypid()]} |
{unittest_get_bounds_and_data, SourcePid::comm:mypid(), full | kv}).
-type message() ::
bulkowner:bulkowner_msg() |
database_message() |
lookup_message() |
dht_node_join:join_message() |
rt_message() |
dht_node_move:move_message() |
misc_message() |
snapshot_message() |
{zombie, Node::node:node_type()} |
{fd_notify, fd:event(), DeadPid::comm:mypid(), Reason::fd:reason()} |
{leave, SourcePid::comm:erl_local_pid() | null} |
{rejoin, IdVersion::non_neg_integer(), JoinOptions::[tuple()],
{get_move_state_response, MoveState::[tuple()]}}.
-spec on(message(), dht_node_state:state()) -> dht_node_state:state() | kill.
Join messages ( see dht_node_join.erl )
on(Msg, State) when join =:= element(1, Msg) ->
lb_stats:set_ignore_db_requests(true),
NewState = dht_node_join:process_join_msg(Msg, State),
lb_stats:set_ignore_db_requests(false),
NewState;
on(Msg, State) when move =:= element(1, Msg) ->
lb_stats:set_ignore_db_requests(true),
NewState = dht_node_move:process_move_msg(Msg, State),
lb_stats:set_ignore_db_requests(false),
NewState;
on(Msg, State) when l_on_cseq =:= element(1, Msg) ->
l_on_cseq:on(Msg, State);
on(Msg, State) when element(1, Msg) =:= rm ->
RMState = dht_node_state:get(State, rm_state),
RMState1 = rm_loop:on(Msg, RMState),
dht_node_state:set_rm(State, RMState1);
on({leave, SourcePid}, State) ->
dht_node_move:make_slide_leave(State, SourcePid);
on({rt_update, RoutingTable}, State) ->
dht_node_state:set_rt(State, RoutingTable);
on({get_rtm, Source_PID, Key, Process}, State) ->
case pid_groups:get_my(Process) of
failed ->
R = config:read(replication_factor),
case Process of
{tx_rtm,X} when X =< R ->
these rtms are concurrently started by the supervisor
comm:send_local(self(),
{get_rtm, Source_PID, Key, Process});
_ ->
log:log(warn, "[ ~.0p ] requested non-existing rtm ~.0p~n",
[comm:this(), Process])
end;
Pid ->
GPid = comm:make_global(Pid),
GPidAcc = comm:make_global(tx_tm_rtm:get_my(Process, acceptor)),
comm:send(Source_PID, {get_rtm_reply, Key, GPid, GPidAcc})
end,
State;
on({?init_TP, {_Tid, _RTMs, _Accs, _TM, _RTLogEntry, _ItemId, _PaxId, SnapNo} = Params}, State) ->
SnapState = dht_node_state:get(State,snapshot_state),
LocalSnapNumber = snapshot_state:get_number(SnapState),
case SnapNo > LocalSnapNumber of
true ->
comm:send(comm:this(), {do_snapshot, SnapNo, none});
false ->
ok
end,
tx_tp:on_init_TP(Params, State);
on({?tp_do_commit_abort, Id, Result, SnapNumber}, State) ->
tx_tp:on_do_commit_abort(Id, Result, SnapNumber, State);
on({?tp_do_commit_abort_fwd, TM, TMItemId, RTLogEntry, Result, OwnProposal, SnapNumber}, State) ->
tx_tp:on_do_commit_abort_fwd(TM, TMItemId, RTLogEntry, Result, OwnProposal, SnapNumber, State);
Lookup ( see api_dht_raw.erl and dht_node_lookup.erl )
on({?lookup_aux, Key, Hops, Msg}=FullMsg, State) ->
case config:read(leases) of
true ->
dht_node_lookup:lookup_aux_leases(State, Key, Hops, Msg);
_ ->
comm:send_local(pid_groups:get_my(routing_table), FullMsg)
end,
State;
on({lookup_decision, Key, Hops, Msg}, State) ->
dht_node_lookup:lookup_decision_chord(State, Key, Hops, Msg),
State;
on({?lookup_fin, Key, Data, Msg}, State) ->
dht_node_lookup:lookup_fin(State, Key, Data, Msg);
on({send_error, Target, {?lookup_aux, _, _, _} = Message, _Reason}, State) ->
dht_node_lookup:lookup_aux_failed(State, Target, Message);
on({send_error, Target, {?send_to_group_member, routing_table,
{?lookup_aux, _Key, _Hops, _Msg} = Message}, _Reason}, State) ->
dht_node_lookup:lookup_aux_failed(State, Target, Message);
on({send_failed , { send_error , Target , { ? lookup_aux , _ , _ , _ } } = Message , _ Reason } , _ Pids } } , State ) - >
dht_node_lookup : lookup_aux_failed(State , Target , Message ) ;
on({send_error, Target, {?lookup_fin, _, _, _} = Message, _Reason}, State) ->
dht_node_lookup:lookup_fin_failed(State, Target, Message);
on(X, State) when is_tuple(X) andalso element(1, X) =:= prbr ->
as prbr has several use cases ( may operate on different DBs ) in
the dht_node , the addressed use case is given in the third
DBKind = element(3, X),
PRBRState = dht_node_state:get(State, DBKind),
NewRBRState = prbr:on(X, PRBRState),
dht_node_state:set_prbr_state(State, DBKind, NewRBRState);
Database
on({?get_key, Source_PID, SourceId, HashedKey}, State) ->
Msg = {?get_key_with_id_reply, SourceId, HashedKey,
db_dht:read(dht_node_state:get(State, db), HashedKey)},
comm:send(Source_PID, Msg),
State;
on({?read_op, Source_PID, SourceId, HashedKey, Op}, State) ->
DB = dht_node_state:get(State, db),
{ok, Value, Version} = db_dht:read(DB, HashedKey),
{Ok_Fail, Val_Reason, Vers} = rdht_tx_read:extract_from_value(Value, Version, Op),
SnapInfo = dht_node_state:get(State, snapshot_state),
SnapNumber = snapshot_state:get_number(SnapInfo),
Msg = {?read_op_with_id_reply, SourceId, SnapNumber, Ok_Fail, Val_Reason, Vers},
comm:send(Source_PID, Msg),
State;
on({get_entries, Source_PID, Interval}, State) ->
Entries = db_dht:get_entries(dht_node_state:get(State, db), Interval),
comm:send_local(Source_PID, {get_entries_response, Entries}),
State;
on({get_entries, Source_PID, FilterFun, ValFun}, State) ->
Entries = db_dht:get_entries(dht_node_state:get(State, db), FilterFun, ValFun),
comm:send_local(Source_PID, {get_entries_response, Entries}),
State;
on({get_data, Source_PID}, State) ->
Data = db_dht:get_data(dht_node_state:get(State, db)),
comm:send_local(Source_PID, {get_data_response, Data}),
State;
on({get_data, Source_PID, FilterFun, ValueFun}, State) ->
Data = db_dht:get_data(dht_node_state:get(State, db), FilterFun, ValueFun),
comm:send_local(Source_PID, {get_data_response, Data}),
State;
on({get_chunk, Source_PID, Interval, MaxChunkSize}, State) ->
Chunk = db_dht:get_chunk(dht_node_state:get(State, db),
dht_node_state:get(State, pred_id),
Interval, MaxChunkSize),
comm:send_local(Source_PID, {get_chunk_response, Chunk}),
State;
on({get_chunk, Source_PID, Interval, FilterFun, ValueFun, MaxChunkSize}, State) ->
Chunk = db_dht:get_chunk(dht_node_state:get(State, db),
dht_node_state:get(State, pred_id),
Interval, FilterFun, ValueFun, MaxChunkSize),
comm:send_local(Source_PID, {get_chunk_response, Chunk}),
State;
on({update_key_entries, Source_PID, KvvList}, State) ->
DB = dht_node_state:get(State, db),
{NewDB, NewEntryList} = update_key_entries(KvvList, DB, State, []),
comm:send(Source_PID, {update_key_entries_ack, NewEntryList}),
dht_node_state:set_db(State, NewDB);
on({db_set_subscription , SubscrTuple } , State ) - >
DB2 = db_dht : set_subscription(dht_node_state : get(State , db ) , ) ,
on({db_get_subscription , Tag , SourcePid } , State ) - >
Subscr = db_dht : get_subscription(dht_node_state : get(State , db ) , Tag ) ,
comm : send_local(SourcePid , { db_get_subscription_response , Tag , Subscr } ) ,
State ;
on({db_remove_subscription , Tag } , State ) - >
DB2 = db_dht : remove_subscription(dht_node_state : get(State , db ) , Tag ) ,
on({delete_key, Source_PID, ClientsId, HashedKey}, State) ->
{DB2, Result} = db_dht:delete(dht_node_state:get(State, db), HashedKey),
comm:send(Source_PID, {delete_key_response, ClientsId, HashedKey, Result}),
dht_node_state:set_db(State, DB2);
on({get_key_entry, Source_PID, HashedKey}, State) ->
Entry = db_dht:get_entry(dht_node_state:get(State, db), HashedKey),
comm:send(Source_PID, {get_key_entry_reply, Entry}),
State;
on({set_key_entry, Source_PID, Entry}, State) ->
NewDB = db_dht:set_entry(dht_node_state:get(State, db), Entry),
comm:send(Source_PID, {set_key_entry_reply, Entry}),
dht_node_state:set_db(State, NewDB);
on({add_data, Source_PID, Data}, State) ->
NewDB = db_dht:add_data(dht_node_state:get(State, db), Data),
comm:send(Source_PID, {add_data_reply}),
dht_node_state:set_db(State, NewDB);
on({delete_keys, Source_PID, HashedKeys}, State) ->
DB2 = db_dht:delete_entries(dht_node_state:get(State, db), intervals:from_elements(HashedKeys)),
comm:send(Source_PID, {delete_keys_reply}),
dht_node_state:set_db(State, DB2);
on({drop_data, Data, Sender}, State) ->
comm:send(Sender, {drop_data_ack}),
DB = db_dht:add_data(dht_node_state:get(State, db), Data),
dht_node_state:set_db(State, DB);
Bulk owner messages ( see bulkowner.erl )
on(Msg, State) when bulkowner =:= element(1, Msg) ->
bulkowner:on(Msg, State);
on({send_error, _FailedTarget, FailedMsg, _Reason} = Msg, State)
when bulkowner =:= element(1, FailedMsg) ->
bulkowner:on(Msg, State);
on({bulk_distribute, _Id, _Range, InnerMsg, _Parents} = Msg, State)
when mr =:= element(1, InnerMsg) ->
mr:on(Msg, State);
on(Msg, State) when mr =:= element(1, Msg) ->
mr:on(Msg, State);
on(Msg, State) when mr_master =:= element(1, Msg) ->
try
mr_master:on(Msg, State)
catch
error:function_clause ->
log:log(warn, "Received Message to non-existing master...ignoring!"),
State
end;
active load balancing messages ( see )
on(Msg, State) when lb_active =:= element(1, Msg) ->
lb_active:handle_dht_msg(Msg, State);
on({get_yaws_info, Pid}, State) ->
comm:send(Pid, {get_yaws_info_response, comm:get_ip(comm:this()), config:read(yaws_port), pid_groups:my_groupname()}),
State;
on({get_state, Pid, Which}, State) when is_list(Which) ->
comm:send(Pid, {get_state_response,
[{X, dht_node_state:get(State, X)} || X <- Which]}),
State;
on({get_state, Pid, Which}, State) when is_atom(Which) ->
comm:send(Pid, {get_state_response, dht_node_state:get(State, Which)}),
State;
on({set_state, Pid, F}, State) when is_function(F) ->
NewState = F(State),
comm:send(Pid, {set_state_response, NewState}),
NewState;
on({get_node_details, Pid}, State) ->
comm:send(Pid, {get_node_details_response, dht_node_state:details(State)}),
State;
on({get_node_details, Pid, Which}, State) ->
comm:send(Pid, {get_node_details_response, dht_node_state:details(State, Which)}),
State;
on({get_pid_group, Pid}, State) ->
comm:send(Pid, {get_pid_group_response, pid_groups:my_groupname()}),
State;
on({dump}, State) ->
dht_node_state:dump(State),
State;
on({web_debug_info, Requestor}, State) ->
RMState = dht_node_state:get(State, rm_state),
Load = dht_node_state:get(State, load),
get a list of up to 50 KV pairs to display :
DataListTmp = [{"",
webhelpers:safe_html_string("~p", [DBEntry])}
|| DBEntry <- element(2, db_dht:get_chunk(dht_node_state:get(State, db),
dht_node_state:get(State, node_id),
intervals:all(), 50))],
DataList = case Load > 50 of
true -> lists:append(DataListTmp, [{"...", ""}]);
false -> DataListTmp
end,
KVList1 =
[{"rt_algorithm", webhelpers:safe_html_string("~p", [?RT])},
{"rt_size", dht_node_state:get(State, rt_size)},
{"my_range", webhelpers:safe_html_string("~p", [intervals:get_bounds(dht_node_state:get(State, my_range))])},
{"db_range", webhelpers:safe_html_string("~p", [dht_node_state:get(State, db_range)])},
{"load", webhelpers:safe_html_string("~p", [Load])},
{"join_time", webhelpers:safe_html_string("~p UTC", [calendar:now_to_universal_time(dht_node_state:get(State, join_time))])},
{ " proposer " , webhelpers : safe_html_string("~p " , [ pid_groups : ) ] ) } ,
{"tx_tp_db", webhelpers:safe_html_string("~p", [dht_node_state:get(State, tx_tp_db)])},
{"slide_pred", webhelpers:safe_html_string("~p", [dht_node_state:get(State, slide_pred)])},
{"slide_succ", webhelpers:safe_html_string("~p", [dht_node_state:get(State, slide_succ)])},
{"msg_fwd", webhelpers:safe_html_string("~p", [dht_node_state:get(State, msg_fwd)])}
],
KVList2 = lists:append(KVList1, [{"", ""} | rm_loop:get_web_debug_info(RMState)]),
KVList3 = lists:append(KVList2, [{"", ""} , {"data (db_entry):", ""} | DataList]),
comm:send_local(Requestor, {web_debug_info_reply, KVList3}),
State;
on({unittest_get_bounds_and_data, SourcePid, Type}, State) ->
MyRange = dht_node_state:get(State, my_range),
MyBounds = intervals:get_bounds(MyRange),
DB = dht_node_state:get(State, db),
Data =
case Type of
kv ->
element(
2,
db_dht:get_chunk(
DB, ?MINUS_INFINITY, intervals:all(),
fun(_) -> true end,
fun(E) -> {db_entry:get_key(E), db_entry:get_version(E)} end,
all));
full ->
db_dht:get_data(DB)
end,
Pred = dht_node_state:get(State, pred),
Succ = dht_node_state:get(State, succ),
comm:send(SourcePid, {unittest_get_bounds_and_data_response, MyBounds, Data, Pred, Succ}),
State;
on({unittest_consistent_send, Pid, _X} = Msg, State) ->
?ASSERT(util:is_unittest()),
comm:send_local(Pid, Msg),
State;
on({get_dht_nodes_response, _KnownHosts}, State) ->
State;
on({fd_notify, Event, DeadPid, Data}, State) ->
RMState = dht_node_state:get(State, rm_state),
RMState1 = rm_loop:fd_notify(RMState, Event, DeadPid, Data),
dht_node_state:set_rm(State, RMState1);
on({zombie, Node}, State) ->
RMState = dht_node_state:get(State, rm_state),
RMState1 = rm_loop:zombie_node(RMState, Node),
dht_node_state:set_rm(State, RMState1);
on({do_snapshot, SnapNumber, Leader}, State) ->
snapshot:on_do_snapshot(SnapNumber, Leader, State);
on({local_snapshot_is_done}, State) ->
snapshot:on_local_snapshot_is_done(State);
on({rejoin, Id, Options, {get_move_state_response, MoveState}}, State) ->
rm_loop:cleanup(dht_node_state:get(State, rm_state)),
comm:send_local(self(), {join, start}),
JoinOptions = [{move_state, MoveState} | Options],
IdVersion = node:id_version(dht_node_state:get(State, node)),
dht_node_join:join_as_other(Id, IdVersion+1, JoinOptions).
-spec init(Options::[tuple()])
-> dht_node_state:state() |
{'$gen_component', [{on_handler, Handler::gen_component:handler()}], State::dht_node_join:join_state()}.
init(Options) ->
{my_sup_dht_node_id, MySupDhtNode} = lists:keyfind(my_sup_dht_node_id, 1, Options),
erlang:put(my_sup_dht_node_id, MySupDhtNode),
in dht_node_join to prevent infection with msg_queue : send/1 !
rm_loop:init_first(),
dht_node_move:send_trigger(),
Recover = config:read(start_type) =:= recover,
case {is_first(Options), config:read(leases), Recover, is_add_nodes(Options)} of
{_ , true, true, false} ->
dht_node_join_recover:join(Options);
{true, true, false, _} ->
msg_delay:send_trigger(1, {l_on_cseq, renew_leases}),
Id = l_on_cseq:id(intervals:all()),
TmpState = dht_node_join:join_as_first(Id, 0, Options),
we have to inject the first lease by hand , as otherwise
l_on_cseq:add_first_lease_to_db(Id, TmpState);
{false, true, _, true} ->
msg_delay:send_trigger(1, {l_on_cseq, renew_leases}),
Id = case lists:keyfind({dht_node, id}, 1, Options) of
{{dht_node, id}, IdX} -> IdX;
_ -> ?RT:get_random_node_id()
end,
dht_node_join:join_as_other(Id, 0, Options);
{IsFirst, _, _, _} ->
Id = case lists:keyfind({dht_node, id}, 1, Options) of
{{dht_node, id}, IdX} -> IdX;
_ -> ?RT:get_random_node_id()
end,
if IsFirst -> dht_node_join:join_as_first(Id, 0, Options);
true -> dht_node_join:join_as_other(Id, 0, Options)
end
end.
userdevguide - begin dht_node : start_link
@doc spawns a scalaris node , called by the scalaris supervisor process
-spec start_link(pid_groups:groupname(), [tuple()]) -> {ok, pid()}.
start_link(DHTNodeGroup, Options) ->
gen_component:start_link(?MODULE, fun ?MODULE:on/2, Options,
[{pid_groups_join_as, DHTNodeGroup, dht_node},
{wait_for_init},
{spawn_opts, [{fullsweep_after, 0},
{min_heap_size, 131071}]}]).
userdevguide - end dht_node : start_link
@doc Checks whether this VM is marked as first , e.g. in a unit test , and
this is the first node in this VM .
-spec is_first([tuple()]) -> boolean().
is_first(Options) ->
lists:member({first}, Options) andalso admin_first:is_first_vm().
-spec is_add_nodes([tuple()]) -> boolean().
is_add_nodes(Options) ->
lists:member({add_node}, Options).
-spec is_alive(State::dht_node_join:join_state() | dht_node_state:state() | term()) -> boolean().
is_alive(State) ->
erlang:is_tuple(State) andalso element(1, State) =:= state.
-spec is_alive_no_slide(State::dht_node_join:join_state() | dht_node_state:state() | term()) -> boolean().
is_alive_no_slide(State) ->
try
SlideSucc = dht_node_state:get(State, slide_succ),
SlidePred =:= null andalso SlideSucc =:= null
catch _:_ -> false
end.
-spec is_alive_fully_joined(State::dht_node_join:join_state() | dht_node_state:state() | term()) -> boolean().
is_alive_fully_joined(State) ->
try
(SlidePred =:= null orelse not slide_op:is_join(SlidePred, 'rcv'))
catch _:_ -> false
end.
-spec update_key_entries(Entries::[{?RT:key(), db_dht:value(), client_version()}],
DB, dht_node_state:state(), NewEntries) -> {DB, NewEntries}
when is_subtype(DB, db_dht:db()),
is_subtype(NewEntries, [{db_entry:entry(), Exists::boolean(), Done::boolean()}]).
update_key_entries([], DB, _State, NewEntries) ->
{DB, lists:reverse(NewEntries)};
update_key_entries([{Key, NewValue, NewVersion} | Entries], DB, State, NewEntries) ->
IsResponsible = dht_node_state:is_db_responsible(Key, State),
Entry = db_dht:get_entry(DB, Key),
Exists = not db_entry:is_null(Entry),
EntryVersion = db_entry:get_version(Entry),
WL = db_entry:get_writelock(Entry),
DoUpdate = Exists
andalso EntryVersion =/= -1
andalso EntryVersion < NewVersion
andalso (WL =:= false orelse WL < NewVersion)
andalso IsResponsible,
DoRegen = (not Exists) andalso IsResponsible,
log : pal("update_key_entries:~nold : ~p ~ : ~p ~ nDoUpdate : ~w , : ~w " ,
[ { db_entry : ) , db_entry : get_version(Entry ) } ,
{ Key , NewVersion } , DoUpdate , ] ) ,
if
DoUpdate ->
UpdEntry = db_entry:set_value(Entry, NewValue, NewVersion),
NewEntry = if WL < NewVersion -> db_entry:reset_locks(UpdEntry);
true -> UpdEntry
end,
NewDB = db_dht:update_entry(DB, NewEntry),
ok;
DoRegen ->
NewEntry = db_entry:new(Key, NewValue, NewVersion),
NewDB = db_dht:set_entry(DB, NewEntry),
ok;
true ->
NewDB = DB,
NewEntry = Entry,
ok
end,
update_key_entries(Entries, NewDB, State,
[{NewEntry, Exists, DoUpdate orelse DoRegen} | NewEntries]).
|
d467cfc4ec1322aa41dd11d515f63d0cfb61d5e5a2f33a580d42c89de3f4706b | francescoc/scalabilitywitherlangotp | tcp_wrapper.erl | -module(tcp_wrapper).
-export([start_link/2, cast/3]).
-export([init/3, system_continue/3, system_terminate/4, init_request/2]).
%-export([behaviour_info/1]).
-callback init_request() -> {'ok', Reply :: term()}.
-callback get_request(Data :: term(), LoopData :: term()) -> {'ok', Reply :: term()} |
{'stop', Reason :: atom(), LoopData :: term()}.
-callback stop_request(Reason :: term(), LoopData :: term()) -> term().
%behaviour_info(callbacks) ->
[ { init_request , 0},{get_request , 2},{stop_request , 2 } ] .
start_link(Mod, Port) ->
proc_lib:start_link(?MODULE, init, [Mod, Port, self()]).
cast(Host, Port, Data) ->
{ok, Socket} = gen_tcp:connect(Host, Port, [binary, {active, false}, {reuseaddr, true}]),
send(Socket, Data),
ok = gen_tcp:close(Socket).
send(Socket, <<Chunk:1/binary,Rest/binary>>) ->
gen_tcp:send(Socket, [Chunk]),
send(Socket, Rest);
send(Socket, <<Rest/binary>>) ->
gen_tcp:send(Socket, Rest).
init(Mod, Port, Parent) ->
{ok, Listener} = gen_tcp:listen(Port, [{active, false}]),
proc_lib:init_ack({ok, self()}),
loop(Mod, Listener, Parent, sys:debug_options([])).
loop(Mod, Listener, Parent, Debug) ->
receive
{system,From,Msg} ->
sys:handle_system_msg(Msg, From, Parent, ?MODULE, Debug, {Listener, Mod});
{'EXIT', Parent, Reason} ->
terminate(Reason, Listener, Debug);
{'EXIT', Child, _Reason} ->
NewDebug = sys:handle_debug(Debug, fun debug/3, stop_request, Child),
loop(Mod, Listener, Parent, NewDebug)
after 0 ->
accept(Mod, Listener, Parent, Debug)
end.
accept(Mod, Listener, Parent, Debug) ->
case gen_tcp:accept(Listener, 1000) of
{ok, Socket} ->
Pid = proc_lib:spawn_link(?MODULE, init_request, [Mod, Socket]),
gen_tcp:controlling_process(Socket, Pid),
NewDebug = sys:handle_debug(Debug, fun debug/3, init_request, Pid),
loop(Mod, Listener, Parent, NewDebug);
{error, timeout} ->
loop(Mod, Listener, Parent, Debug);
{error, Reason} ->
NewDebug = sys:handle_debug(Debug, fun debug/3, error, Reason),
terminate(Reason, Listener, NewDebug)
end.
system_continue(Parent, Debug, {Listener, Mod}) ->
loop(Mod, Listener, Parent, Debug).
system_terminate(Reason, _Parent, Debug, {Listener, _Mod}) ->
terminate(Reason, Listener, Debug).
terminate(Reason, Listener, Debug) ->
sys:handle_debug(Debug, fun debug/3, terminating, Reason),
gen_tcp:close(Listener),
exit(Reason).
debug(Dev, Event, Data) ->
io:format(Dev, "Listener ~w:~w~n", [Event,Data]).
init_request(Mod, Socket) ->
{ok, LoopData} = Mod:init_request(),
get_request(Mod, Socket, LoopData).
get_request(Mod, Socket, LoopData) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
case Mod:get_request(Data, LoopData) of
{ok, NewLoopData} ->
get_request(Mod, Socket, NewLoopData);
{stop, Reason, NewLoopData} ->
gen_tcp:close(Socket),
stop_request(Mod, Reason, NewLoopData)
end;
{error, Reason} ->
stop_request(Mod, Reason, LoopData)
end.
stop_request(Mod, Reason, LoopData) ->
Mod:stop_request(Reason, LoopData).
| null | https://raw.githubusercontent.com/francescoc/scalabilitywitherlangotp/961de968f034e55eba22eea9a368fe9f47c608cc/ch10/tcp_wrapper.erl | erlang | -export([behaviour_info/1]).
behaviour_info(callbacks) -> | -module(tcp_wrapper).
-export([start_link/2, cast/3]).
-export([init/3, system_continue/3, system_terminate/4, init_request/2]).
-callback init_request() -> {'ok', Reply :: term()}.
-callback get_request(Data :: term(), LoopData :: term()) -> {'ok', Reply :: term()} |
{'stop', Reason :: atom(), LoopData :: term()}.
-callback stop_request(Reason :: term(), LoopData :: term()) -> term().
[ { init_request , 0},{get_request , 2},{stop_request , 2 } ] .
start_link(Mod, Port) ->
proc_lib:start_link(?MODULE, init, [Mod, Port, self()]).
cast(Host, Port, Data) ->
{ok, Socket} = gen_tcp:connect(Host, Port, [binary, {active, false}, {reuseaddr, true}]),
send(Socket, Data),
ok = gen_tcp:close(Socket).
send(Socket, <<Chunk:1/binary,Rest/binary>>) ->
gen_tcp:send(Socket, [Chunk]),
send(Socket, Rest);
send(Socket, <<Rest/binary>>) ->
gen_tcp:send(Socket, Rest).
init(Mod, Port, Parent) ->
{ok, Listener} = gen_tcp:listen(Port, [{active, false}]),
proc_lib:init_ack({ok, self()}),
loop(Mod, Listener, Parent, sys:debug_options([])).
loop(Mod, Listener, Parent, Debug) ->
receive
{system,From,Msg} ->
sys:handle_system_msg(Msg, From, Parent, ?MODULE, Debug, {Listener, Mod});
{'EXIT', Parent, Reason} ->
terminate(Reason, Listener, Debug);
{'EXIT', Child, _Reason} ->
NewDebug = sys:handle_debug(Debug, fun debug/3, stop_request, Child),
loop(Mod, Listener, Parent, NewDebug)
after 0 ->
accept(Mod, Listener, Parent, Debug)
end.
accept(Mod, Listener, Parent, Debug) ->
case gen_tcp:accept(Listener, 1000) of
{ok, Socket} ->
Pid = proc_lib:spawn_link(?MODULE, init_request, [Mod, Socket]),
gen_tcp:controlling_process(Socket, Pid),
NewDebug = sys:handle_debug(Debug, fun debug/3, init_request, Pid),
loop(Mod, Listener, Parent, NewDebug);
{error, timeout} ->
loop(Mod, Listener, Parent, Debug);
{error, Reason} ->
NewDebug = sys:handle_debug(Debug, fun debug/3, error, Reason),
terminate(Reason, Listener, NewDebug)
end.
system_continue(Parent, Debug, {Listener, Mod}) ->
loop(Mod, Listener, Parent, Debug).
system_terminate(Reason, _Parent, Debug, {Listener, _Mod}) ->
terminate(Reason, Listener, Debug).
terminate(Reason, Listener, Debug) ->
sys:handle_debug(Debug, fun debug/3, terminating, Reason),
gen_tcp:close(Listener),
exit(Reason).
debug(Dev, Event, Data) ->
io:format(Dev, "Listener ~w:~w~n", [Event,Data]).
init_request(Mod, Socket) ->
{ok, LoopData} = Mod:init_request(),
get_request(Mod, Socket, LoopData).
get_request(Mod, Socket, LoopData) ->
case gen_tcp:recv(Socket, 0) of
{ok, Data} ->
case Mod:get_request(Data, LoopData) of
{ok, NewLoopData} ->
get_request(Mod, Socket, NewLoopData);
{stop, Reason, NewLoopData} ->
gen_tcp:close(Socket),
stop_request(Mod, Reason, NewLoopData)
end;
{error, Reason} ->
stop_request(Mod, Reason, LoopData)
end.
stop_request(Mod, Reason, LoopData) ->
Mod:stop_request(Reason, LoopData).
|
6f405e755119cff8277f940be3de0a3a39b394902d29cd7a863efcc441db8bdb | ocaml/dune | clflags.ml | let store_orig_src_dir = ref false
let ignore_promoted_rules = ref false
let promote_install_files = ref false
let display = Dune_engine.Clflags.display
let capture_outputs = Dune_engine.Clflags.capture_outputs
let debug_artifact_substitution = ref false
| null | https://raw.githubusercontent.com/ocaml/dune/4edb5ff19aa3efcabdc8194ef7f837e49866517b/src/dune_rules/clflags.ml | ocaml | let store_orig_src_dir = ref false
let ignore_promoted_rules = ref false
let promote_install_files = ref false
let display = Dune_engine.Clflags.display
let capture_outputs = Dune_engine.Clflags.capture_outputs
let debug_artifact_substitution = ref false
|
|
f52e123d16b8a3564ec9efd9a532c210fd64465f37c988f296e440ed56b39526 | Lysxia/generic-data | Data.hs | # LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- | Generic representations as data types.
--
-- === Warning
--
-- This is an internal module: it is not subject to any versioning policy,
-- breaking changes can happen at any time.
--
-- If something here seems useful, please report it or create a pull request to
-- export it from an external module.
module Generic.Data.Internal.Data where
import Control.Applicative
import Control.Monad
import Data.Functor.Classes
import Data.Functor.Contravariant (Contravariant, phantom)
import Data.Semigroup
import GHC.Generics
import Generic.Data.Internal.Enum
import Generic.Data.Internal.Show
-- | Synthetic data type.
--
-- A wrapper to view a generic 'Rep' as the datatype it's supposed to
-- represent, without needing a declaration.
newtype Data r p = Data { unData :: r p }
deriving ( Functor, Foldable, Traversable, Applicative, Alternative
, Monad, MonadPlus, Contravariant
, Eq, Ord, Eq1, Ord1, Semigroup, Monoid )
-- | Conversion between a generic type and the synthetic type made using its
-- representation. Inverse of 'fromData'.
toData :: Generic a => a -> Data (Rep a) p
toData = Data . from
-- | Inverse of 'toData'.
fromData :: Generic a => Data (Rep a) p -> a
fromData = to . unData
instance (Functor r, Contravariant r) => Generic (Data r p) where
type Rep (Data r p) = r
to = Data . phantom
from = phantom . unData
instance Generic1 (Data r) where
type Rep1 (Data r) = r
to1 = Data
from1 = unData
instance (GShow1 r, Show p) => Show (Data r p) where
showsPrec = flip (gLiftPrecShows showsPrec showList . unData)
instance GShow1 r => Show1 (Data r) where
liftShowsPrec = (fmap . fmap) (flip . (. unData)) gLiftPrecShows
instance GEnum StandardEnum r => Enum (Data r p) where
toEnum = Data . gToEnum @StandardEnum
fromEnum = gFromEnum @StandardEnum . unData
instance GBounded r => Bounded (Data r p) where
minBound = Data gMinBound
maxBound = Data gMaxBound
| null | https://raw.githubusercontent.com/Lysxia/generic-data/846fafb9ec1e4e60424e4f266451665fe25fdfa9/src/Generic/Data/Internal/Data.hs | haskell | # LANGUAGE DeriveTraversable #
| Generic representations as data types.
=== Warning
This is an internal module: it is not subject to any versioning policy,
breaking changes can happen at any time.
If something here seems useful, please report it or create a pull request to
export it from an external module.
| Synthetic data type.
A wrapper to view a generic 'Rep' as the datatype it's supposed to
represent, without needing a declaration.
| Conversion between a generic type and the synthetic type made using its
representation. Inverse of 'fromData'.
| Inverse of 'toData'. | # LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Generic.Data.Internal.Data where
import Control.Applicative
import Control.Monad
import Data.Functor.Classes
import Data.Functor.Contravariant (Contravariant, phantom)
import Data.Semigroup
import GHC.Generics
import Generic.Data.Internal.Enum
import Generic.Data.Internal.Show
newtype Data r p = Data { unData :: r p }
deriving ( Functor, Foldable, Traversable, Applicative, Alternative
, Monad, MonadPlus, Contravariant
, Eq, Ord, Eq1, Ord1, Semigroup, Monoid )
toData :: Generic a => a -> Data (Rep a) p
toData = Data . from
fromData :: Generic a => Data (Rep a) p -> a
fromData = to . unData
instance (Functor r, Contravariant r) => Generic (Data r p) where
type Rep (Data r p) = r
to = Data . phantom
from = phantom . unData
instance Generic1 (Data r) where
type Rep1 (Data r) = r
to1 = Data
from1 = unData
instance (GShow1 r, Show p) => Show (Data r p) where
showsPrec = flip (gLiftPrecShows showsPrec showList . unData)
instance GShow1 r => Show1 (Data r) where
liftShowsPrec = (fmap . fmap) (flip . (. unData)) gLiftPrecShows
instance GEnum StandardEnum r => Enum (Data r p) where
toEnum = Data . gToEnum @StandardEnum
fromEnum = gFromEnum @StandardEnum . unData
instance GBounded r => Bounded (Data r p) where
minBound = Data gMinBound
maxBound = Data gMaxBound
|
1f19aab4fd5f8ec54c3a5827666a1c46c2fe6b1d2b2d907c4420fc7e2620874c | s-cerevisiae/leetcode-racket | 525-contiguous-array.rkt | #lang racket
(define (find-max-length nums)
(define table (make-hash '((0 . -1))))
(for/fold ([cnt 0] [len 0]
#:result len)
([n (in-list nums)]
[i (in-naturals)])
(define next-cnt
((if (= n 1) add1 sub1) cnt))
(define prev-i (hash-ref! table next-cnt i))
(values next-cnt
(max len (- i prev-i)))))
| null | https://raw.githubusercontent.com/s-cerevisiae/leetcode-racket/13289f66ef8d0375909cedd8aacaaed57b1b3ca4/525-contiguous-array.rkt | racket | #lang racket
(define (find-max-length nums)
(define table (make-hash '((0 . -1))))
(for/fold ([cnt 0] [len 0]
#:result len)
([n (in-list nums)]
[i (in-naturals)])
(define next-cnt
((if (= n 1) add1 sub1) cnt))
(define prev-i (hash-ref! table next-cnt i))
(values next-cnt
(max len (- i prev-i)))))
|
|
33ed6c9956bbb187aeeeaab3a4e2db9bdb1f9d474214930986c0183af3c53a15 | flodihn/NextGen | obj_loop.erl | %%----------------------------------------------------------------------
@author < >
%% @doc
%% This module contains the object loop that every object executes.
%% @end
%%----------------------------------------------------------------------
-module(obj_loop).
-author("").
@headerfile " obj.hrl "
-include("obj.hrl").
%% Exports for fitting into a supervisor tree
-export([
start_link/2
]).
Interal exports
-export([
loop_init/1,
loop_init/2,
loop/1
]).
% Exports used by other modules.
-export([
has_fun/3
]).
%%----------------------------------------------------------------------
, Type ) - > { ok , Pid }
%% where
%% Arg = any()
%% Type = any()
%% @doc
%% Starts a new object with a new state. Arg should either be new_state or
{ existing_state , State } , Type should be a tuple { type , Mod } where Mod
%% is the implementation module of the object, for example obj, player or
%% animal.
%% @end
%%----------------------------------------------------------------------
start_link(new_state, {type, Type}) ->
Pid = spawn_link(?MODULE, loop_init, [Type]),
{ok, Pid};
start_link({existing_state, State}, {type, Type}) ->
error_logger:info_report([{starting, type, Type, state, State}]),
Pid = spawn_link(?MODULE, loop_init, [Type, State]),
{ok, Pid}.
%%----------------------------------------------------------------------
) - > ok
%% where
%% Type = atom()
%% @doc
%% Starts the object loop with a new state.
%% @end
%%----------------------------------------------------------------------
loop_init(Type) ->
{ok, State} = Type:create_state(Type),
{ok, InitState} = Type:init(State),
loop(InitState).
%%----------------------------------------------------------------------
, State ) - > ok
%% where
%% Type = atom(),
%% State = obj()
%% @doc
%% Starts the object loop with an existing state.
%% @end
%%----------------------------------------------------------------------
loop_init(Type, State) ->
{ok, InitState} = Type:init(State),
loop(InitState).
%%----------------------------------------------------------------------
) - > ok
%% where
%% State = obj()
%% @doc
%% Object loop for all types of objects.
%% @end
%%----------------------------------------------------------------------
loop(#obj{properties=Dict} = State) ->
HeartBeat = fetch_heart_beat(Dict),
NewState = check_heart_beat(State),
receive
% An execute call without an event id calls apply_fun/4
% which does not send anything back to the calling process "From".
{execute, {from, From}, {call, Fun}, {args, Args}} ->
error_logger : info_report({execute , Fun , Args } ) ,
{ok, NewState2} = apply_async_inheritance(
From, Fun, Args, NewState),
loop(NewState2);
% An execute call with an event id will try to send back
% the result to the calling process "From".
{execute, {from, From}, {call, Fun}, {args, Args},
{event_id, EventId}} ->
error_logger : info_report({execute , Fun , Args } ) ,
{ok, NewState2} = apply_sync_inheritance(
From, Fun, Args, NewState, EventId),
loop(NewState2);
% Implement some sort of upgrade
% {upgrade, From} ->
% ?MODULE:loop(State);
Other ->
error_logger:info_report([{unexpected_message, Other}]),
loop(State)
after HeartBeat ->
NewState2 = call_heart_beat(NewState),
loop(NewState2)
end.
apply_sync_inheritance(From, Fun, Args, #obj{type=Type} = State, EventId) ->
ArgLen = length(Args) + 2,
case shared_cache:retr({Fun, ArgLen}) of
undefined ->
case has_fun(Type:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Type),
apply_fun(Type, From, Fun, Args, State, EventId);
false ->
apply_sync_inheritance(
State#obj.parents, From, Fun, Args, State, EventId)
end;
CachedType ->
apply_fun(CachedType, From, Fun, Args, State, EventId)
end.
apply_sync_inheritance([], _From, Fun, Args, #obj{type=Type} = State,
_EventId) ->
error_logger:error_report([{Type, sync_undef, Fun, Args}]),
{ok, State};
apply_sync_inheritance([Parent | Parents], From, Fun, Args, State,
EventId) ->
ArgLen = length(Args) + 2,
case shared_cache:retr({Fun, ArgLen}) of
undefined ->
case has_fun(Parent:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Parent),
apply_fun(Parent, From, Fun, Args, State, EventId);
false ->
apply_sync_inheritance(
Parents, From, Fun, Args, State, EventId)
end;
CachedType ->
apply_fun(CachedType, From, Fun, Args, State)
end.
apply_async_inheritance(From, Fun, Args, #obj{type=Type} = State) ->
ArgLen = length(Args) + 2,
error_logger:info_report(apply_async_inheritance, State#obj.parents),
case shared_cache:retr({Fun, ArgLen}) of
undefined ->
case has_fun(Type:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Type),
apply_fun(Type, From, Fun, Args, State);
false ->
apply_async_inheritance(
State#obj.parents, From, Fun, Args, State)
end;
CachedType ->
apply_fun(CachedType, From, Fun, Args, State)
end.
apply_async_inheritance([], _From, Fun, Args, #obj{type=Type} = State) ->
error_logger:error_report([{Type, async_undef, Fun, Args,
Type, State#obj.parents}]),
{ok, State};
apply_async_inheritance([Parent | Parents], From, Fun, Args, State) ->
ArgLen = length(Args) + 2,
case has_fun(Parent:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Parent),
apply_fun(Parent, From, Fun, Args, State);
false ->
apply_async_inheritance(Parents, From, Fun, Args, State)
end.
%%----------------------------------------------------------------------
@private
@spec apply_fun(Type , From , Event , , State ) - > { ok , NewState }
%% where
%% Type = atom(),
%% From = pid,
%% Event = atom(),
= list ( ) ,
%% State = obj()
%% @doc
Applies the function Event , with the arguments in itself . Ignores
%% the result.
%% @end
%%----------------------------------------------------------------------
apply_fun(Type, From, Event, Args, State)->
case apply(Type, Event, [From] ++ Args ++ [State]) of
{noreply, NewState} ->
{ok, NewState};
{reply, _Reply, NewState} ->
{ok, NewState}
end.
%%----------------------------------------------------------------------
@spec apply_fun(Type , From , Event , , State , EventId ) - > { ok , NewState }
%% where
%% Type = atom(),
%% From = pid,
%% Event = atom(),
= list ( ) ,
%% State = obj(),
%% EventId = ref()
%% @doc
%% Applies a function in the object type and sends back the result to the
%% calling process From.
%% @end
%%----------------------------------------------------------------------
apply_fun(Type, From, Fun, Args, State, EventId)->
case apply(Type, Fun, [From] ++ Args ++ [State]) of
{noreply, NewState} ->
From ! {EventId, noreply},
{ok, NewState};
{reply, Reply, NewState} ->
From ! {EventId, Reply},
{ok, NewState}
end.
has_fun([], _Fun, _NrArgs) ->
false;
has_fun([{Fun, NrArgs} | _Rest], Fun, NrArgs) ->
true;
has_fun([{_Fun, _NrArgs} | Rest], Fun, NrArgs) ->
has_fun(Rest, Fun, NrArgs).
fetch_heart_beat(Dict) ->
case cache:fetch(heart_beat) of
undefined ->
infinity;
HeartBeat ->
HeartBeat
end.
case dict : find(heart_beat , ) of
{ ok ,
% HeartBeat;
% error ->
% infinity
%end.
fetch_last_heart_beat(Dict) ->
case get(last_heart_beat) of
undefined->
{0, 0, 0};
LastHeartBeat ->
LastHeartBeat
end.
call_heart_beat(State) ->
{ok, NewState} = apply_async_inheritance(
self(), heart_beat, [], State),
{ok, _Reply, NewState2} = obj:call_self(set_property,
[last_heart_beat, now()], NewState),
NewState2.
check_heart_beat(#obj{properties=Dict} = State) ->
HeartBeat = fetch_heart_beat(Dict),
LastHeartBeat = fetch_last_heart_beat(Dict),
Diff = timer:now_diff(now(), LastHeartBeat) / 1000,
case Diff > HeartBeat of
true ->
call_heart_beat(State);
false ->
State
end.
| null | https://raw.githubusercontent.com/flodihn/NextGen/3da1c3ee0d8f658383bdf5fccbdd49ace3cdb323/AreaServer/src/obj_loop.erl | erlang | ----------------------------------------------------------------------
@doc
This module contains the object loop that every object executes.
@end
----------------------------------------------------------------------
Exports for fitting into a supervisor tree
Exports used by other modules.
----------------------------------------------------------------------
where
Arg = any()
Type = any()
@doc
Starts a new object with a new state. Arg should either be new_state or
is the implementation module of the object, for example obj, player or
animal.
@end
----------------------------------------------------------------------
----------------------------------------------------------------------
where
Type = atom()
@doc
Starts the object loop with a new state.
@end
----------------------------------------------------------------------
----------------------------------------------------------------------
where
Type = atom(),
State = obj()
@doc
Starts the object loop with an existing state.
@end
----------------------------------------------------------------------
----------------------------------------------------------------------
where
State = obj()
@doc
Object loop for all types of objects.
@end
----------------------------------------------------------------------
An execute call without an event id calls apply_fun/4
which does not send anything back to the calling process "From".
An execute call with an event id will try to send back
the result to the calling process "From".
Implement some sort of upgrade
{upgrade, From} ->
?MODULE:loop(State);
----------------------------------------------------------------------
where
Type = atom(),
From = pid,
Event = atom(),
State = obj()
@doc
the result.
@end
----------------------------------------------------------------------
----------------------------------------------------------------------
where
Type = atom(),
From = pid,
Event = atom(),
State = obj(),
EventId = ref()
@doc
Applies a function in the object type and sends back the result to the
calling process From.
@end
----------------------------------------------------------------------
HeartBeat;
error ->
infinity
end. | @author < >
-module(obj_loop).
-author("").
@headerfile " obj.hrl "
-include("obj.hrl").
-export([
start_link/2
]).
Interal exports
-export([
loop_init/1,
loop_init/2,
loop/1
]).
-export([
has_fun/3
]).
, Type ) - > { ok , Pid }
{ existing_state , State } , Type should be a tuple { type , Mod } where Mod
start_link(new_state, {type, Type}) ->
Pid = spawn_link(?MODULE, loop_init, [Type]),
{ok, Pid};
start_link({existing_state, State}, {type, Type}) ->
error_logger:info_report([{starting, type, Type, state, State}]),
Pid = spawn_link(?MODULE, loop_init, [Type, State]),
{ok, Pid}.
) - > ok
loop_init(Type) ->
{ok, State} = Type:create_state(Type),
{ok, InitState} = Type:init(State),
loop(InitState).
, State ) - > ok
loop_init(Type, State) ->
{ok, InitState} = Type:init(State),
loop(InitState).
) - > ok
loop(#obj{properties=Dict} = State) ->
HeartBeat = fetch_heart_beat(Dict),
NewState = check_heart_beat(State),
receive
{execute, {from, From}, {call, Fun}, {args, Args}} ->
error_logger : info_report({execute , Fun , Args } ) ,
{ok, NewState2} = apply_async_inheritance(
From, Fun, Args, NewState),
loop(NewState2);
{execute, {from, From}, {call, Fun}, {args, Args},
{event_id, EventId}} ->
error_logger : info_report({execute , Fun , Args } ) ,
{ok, NewState2} = apply_sync_inheritance(
From, Fun, Args, NewState, EventId),
loop(NewState2);
Other ->
error_logger:info_report([{unexpected_message, Other}]),
loop(State)
after HeartBeat ->
NewState2 = call_heart_beat(NewState),
loop(NewState2)
end.
apply_sync_inheritance(From, Fun, Args, #obj{type=Type} = State, EventId) ->
ArgLen = length(Args) + 2,
case shared_cache:retr({Fun, ArgLen}) of
undefined ->
case has_fun(Type:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Type),
apply_fun(Type, From, Fun, Args, State, EventId);
false ->
apply_sync_inheritance(
State#obj.parents, From, Fun, Args, State, EventId)
end;
CachedType ->
apply_fun(CachedType, From, Fun, Args, State, EventId)
end.
apply_sync_inheritance([], _From, Fun, Args, #obj{type=Type} = State,
_EventId) ->
error_logger:error_report([{Type, sync_undef, Fun, Args}]),
{ok, State};
apply_sync_inheritance([Parent | Parents], From, Fun, Args, State,
EventId) ->
ArgLen = length(Args) + 2,
case shared_cache:retr({Fun, ArgLen}) of
undefined ->
case has_fun(Parent:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Parent),
apply_fun(Parent, From, Fun, Args, State, EventId);
false ->
apply_sync_inheritance(
Parents, From, Fun, Args, State, EventId)
end;
CachedType ->
apply_fun(CachedType, From, Fun, Args, State)
end.
apply_async_inheritance(From, Fun, Args, #obj{type=Type} = State) ->
ArgLen = length(Args) + 2,
error_logger:info_report(apply_async_inheritance, State#obj.parents),
case shared_cache:retr({Fun, ArgLen}) of
undefined ->
case has_fun(Type:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Type),
apply_fun(Type, From, Fun, Args, State);
false ->
apply_async_inheritance(
State#obj.parents, From, Fun, Args, State)
end;
CachedType ->
apply_fun(CachedType, From, Fun, Args, State)
end.
apply_async_inheritance([], _From, Fun, Args, #obj{type=Type} = State) ->
error_logger:error_report([{Type, async_undef, Fun, Args,
Type, State#obj.parents}]),
{ok, State};
apply_async_inheritance([Parent | Parents], From, Fun, Args, State) ->
ArgLen = length(Args) + 2,
case has_fun(Parent:module_info(exports), Fun, ArgLen) of
true ->
shared_cache:store({Fun, ArgLen}, Parent),
apply_fun(Parent, From, Fun, Args, State);
false ->
apply_async_inheritance(Parents, From, Fun, Args, State)
end.
@private
@spec apply_fun(Type , From , Event , , State ) - > { ok , NewState }
= list ( ) ,
Applies the function Event , with the arguments in itself . Ignores
apply_fun(Type, From, Event, Args, State)->
case apply(Type, Event, [From] ++ Args ++ [State]) of
{noreply, NewState} ->
{ok, NewState};
{reply, _Reply, NewState} ->
{ok, NewState}
end.
@spec apply_fun(Type , From , Event , , State , EventId ) - > { ok , NewState }
= list ( ) ,
apply_fun(Type, From, Fun, Args, State, EventId)->
case apply(Type, Fun, [From] ++ Args ++ [State]) of
{noreply, NewState} ->
From ! {EventId, noreply},
{ok, NewState};
{reply, Reply, NewState} ->
From ! {EventId, Reply},
{ok, NewState}
end.
has_fun([], _Fun, _NrArgs) ->
false;
has_fun([{Fun, NrArgs} | _Rest], Fun, NrArgs) ->
true;
has_fun([{_Fun, _NrArgs} | Rest], Fun, NrArgs) ->
has_fun(Rest, Fun, NrArgs).
fetch_heart_beat(Dict) ->
case cache:fetch(heart_beat) of
undefined ->
infinity;
HeartBeat ->
HeartBeat
end.
case dict : find(heart_beat , ) of
{ ok ,
fetch_last_heart_beat(Dict) ->
case get(last_heart_beat) of
undefined->
{0, 0, 0};
LastHeartBeat ->
LastHeartBeat
end.
call_heart_beat(State) ->
{ok, NewState} = apply_async_inheritance(
self(), heart_beat, [], State),
{ok, _Reply, NewState2} = obj:call_self(set_property,
[last_heart_beat, now()], NewState),
NewState2.
check_heart_beat(#obj{properties=Dict} = State) ->
HeartBeat = fetch_heart_beat(Dict),
LastHeartBeat = fetch_last_heart_beat(Dict),
Diff = timer:now_diff(now(), LastHeartBeat) / 1000,
case Diff > HeartBeat of
true ->
call_heart_beat(State);
false ->
State
end.
|
852de904175a7356dff237651b511c41656ddda73ebfaf4d1499f21c444bc18a | bufferswap/ViralityEngine | material.lisp | (in-package #:virality)
;; material-profile impl
;; NOTE: will be replaced by defstruct constructor
(defun %make-material-profile (&rest init-args)
(apply #'make-instance 'material-profile init-args))
(defun %add-material-profile (profile core)
(setf (u:href (profiles (materials core)) (name profile)) profile))
;; material impl
(defun %make-material (id shader instances attributes profiles core)
(make-instance 'material :id id
:shader shader
:instances instances
:attributes attributes
:profile-overlay-names profiles
:core core))
(defmethod (setf instances) (value (mat material))
(with-slots (%instances) mat
(setf %instances value)))
(defmethod (setf attributes) (value (mat material))
(with-slots (%attributes) mat
(setf %attributes value)))
(defun %deep-copy-material (current-mat new-mat-name)
(let* ((new-id new-mat-name)
(new-shader (shader current-mat))
(new-shader-program (shader-program current-mat))
(new-instances (instances current-mat))
(new-attributes
(copy-seq (attributes current-mat)))
(new-uniforms (u:dict #'eq))
(new-blocks (u:dict #'eq))
(new-profile-overlay-names
(copy-seq (profile-overlay-names current-mat)))
(new-active-texture-unit (active-texture-unit current-mat))
(new-mat
;; TODO: Fix %make-material so I don't have to do this.
(make-instance 'material
:id new-id
:shader new-shader
:shader-program new-shader-program
:instances new-instances
:attributes new-attributes
:core (core current-mat)
:uniforms new-uniforms
:blocks new-blocks
:profile-overlay-names new-profile-overlay-names
:active-texture-unit new-active-texture-unit)))
;; Now we copy over the uniforms
(u:do-hash (k v (uniforms current-mat))
(setf (u:href new-uniforms k)
(%deep-copy-material-uniform-value v new-mat)))
;; Now we copy over the blocks.
(u:do-hash (k v (blocks current-mat))
(setf (u:href new-blocks k)
(%deep-copy-material-block-value v new-mat)))
new-mat))
(defun bind-material-uniforms (mat)
(when mat
(u:do-hash (k v (uniforms mat))
(when (functionp (semantic-value v))
(execute-composition/semantic->computed v))
(funcall (binder v) (shader-program mat) k (computed-value v)))))
(defun bind-material-buffers (mat)
(when mat
(u:do-hash (k v (blocks mat))
(declare (ignore k v))
;; TODO: we probably need to call into core buffer binding management
;; services to perform the binding right here.
nil)))
;; export PUBLIC API
(defun bind-material (mat)
(bind-material-uniforms mat)
(bind-material-buffers mat))
(defun uniform-ref-p (mat uniform-var)
"Return a generalized boolean if the specified uniform ref exists or not."
(u:href (uniforms mat) uniform-var))
;; TODO: these modify the semantic-buffer which then gets processed into a new
;; computed buffer.
(defun uniform-ref (mat uniform-var)
(u:if-let ((material-uniform-value (u:href (uniforms mat) uniform-var)))
(semantic-value material-uniform-value)
(error "Material ~s does not have the referenced uniform ~s.~%~
Please add a uniform to the material, and/or check your material ~
profile settings."
(id mat) uniform-var)))
;; We can only set the semantic-value, which gets automatically upgraded to the
;; computed-value upon setting.
(defun (setf uniform-ref) (new-val mat uniform-var)
(u:if-let ((material-uniform-value (u:href (uniforms mat) uniform-var)))
(progn
;; TODO: Need to do something with the old computed value since it might
be consuming resources like when it is a sampler on the GPU .
(setf (semantic-value material-uniform-value) new-val)
(execute-composition/semantic->computed material-uniform-value)
(semantic-value material-uniform-value))
(error "Material ~s does not have the referenced uniform ~s.~%~
Please add a uniform to the material, and/or check your material ~
profile settings."
(id mat) uniform-var)))
;; export PUBLIC API
;; This is read only, it is the computed value in the material.
(defun mat-computed-uniform-ref (mat uniform-var)
(computed-value (u:href (uniforms mat) uniform-var)))
;;; Default conversion functions for each uniform type.
(defun determine-binder-function (material glsl-type)
(typecase glsl-type
(symbol
(if (sampler-p glsl-type)
(let ((unit (active-texture-unit material)))
(incf (active-texture-unit material))
(lambda (shader uniform-name texture)
(gl:active-texture unit)
(gl:bind-texture (sampler-type->texture-type glsl-type)
(tex::texid texture))
(shadow:uniform-int shader uniform-name unit)))
(ecase glsl-type
(:bool (lambda (shader uniform value)
(shadow:uniform-int shader uniform (if value 1 0))))
(:int #'shadow:uniform-int)
(:float #'shadow:uniform-float)
(:vec2 #'shadow:uniform-vec2)
(:vec3 #'shadow:uniform-vec3)
(:vec4 #'shadow:uniform-vec4)
(:mat2 #'shadow:uniform-mat2)
(:mat3 #'shadow:uniform-mat3)
(:mat4 #'shadow:uniform-mat4))))
(cons
(if (sampler-p (car glsl-type))
(let* ((units
(loop :for i :below (cdr glsl-type)
:collect (prog1 (active-texture-unit material)
(incf (active-texture-unit material)))))
(units (coerce units 'vector)))
(lambda (shader uniform-name texture-array)
Bind all of the textures to their active units first
(loop :for texture :across texture-array
:for unit :across units
:do (gl:active-texture unit)
(gl:bind-texture
(sampler-type->texture-type (car glsl-type))
(tex::texid texture)))
(shadow:uniform-int-array shader uniform-name units)))
(ecase (car glsl-type)
(:bool #'shadow:uniform-int-array)
(:int #'shadow:uniform-int-array)
(:float #'shadow:uniform-float-array)
(:vec2 #'shadow:uniform-vec2-array)
(:vec3 #'shadow:uniform-vec3-array)
(:vec4 #'shadow:uniform-vec4-array)
(:mat2 #'shadow:uniform-mat2-array)
(:mat3 #'shadow:uniform-mat3-array)
(:mat4 #'shadow:uniform-mat4-array))))
(t
(error "Cannot determine binder function for glsl-type: ~s~%"
glsl-type))))
(defun annotate-material-uniform (uniform-name uniform-value material
shader-program)
(u:if-found (type-info (u:href (shadow:uniforms shader-program)
uniform-name))
(let ((uniform-type (u:href type-info :type)))
1 . Find the uniform in the shader - program and get its
;; type-info. Use that to set the binder function.
(setf (binder uniform-value) (determine-binder-function
material uniform-type))
2 . Figure out the semantic->computed composition function
;; for this specific uniform type. This will be the last
;; function executed and will convert the in-flight semantic
;; value into a real computed value for use by the binder
;; function.
;; NOTE: We set it to NIL here because if we're changing the
;; shader on a material, we'll push multiple copies of the this
;; sequence into the list when we resolve-material on that copy
;; with the changed shader--which is wrong. This will now do
;; the right thing in any (I believe) situation.
(setf (semantic->computed uniform-value) nil)
(push (if (sampler-p uniform-type)
(gen-sampler/sem->com)
(if (force-copy uniform-value)
(gen-default-copy/sem->com)
#'identity/for-material-custom-functions))
(semantic->computed uniform-value))
3 . Put the user specified semantic transformer function into
;; the composition sequence before the above.
(push (transformer uniform-value)
(semantic->computed uniform-value))
4 . Execute the composition function sequence to produce the
;; computed value.
(execute-composition/semantic->computed uniform-value))
(error "Material ~s uses unknown uniform ~s in shader ~s."
(id material) uniform-name (shader material))))
(defun annotate-material-uniforms (material shader-program)
(u:do-hash (k v (uniforms material))
(annotate-material-uniform k v material shader-program)))
(defun annotate-material-block (alias-name block-value material shader-program
core)
(declare (ignore shader-program core))
1 . Validate that this material - block - value is present in the shaders in
;; core
TODO : 2 . Create the block - name - alias , but only once .
(unless (shadow:find-block alias-name)
(shadow:create-block-alias (storage-type block-value)
(block-name block-value)
(shader material)
alias-name)))
(defun annotate-material-blocks (material shader-program core)
;; TODO: Ensure that all :block-alias names are unique in the material
(u:do-hash (k v (blocks material))
(annotate-material-block k v material shader-program core)))
(defun resolve-material (material-instance)
"Convert semantic-values to computed-values. Type check the uniforms against
the shader program in the material."
(let ((core (core material-instance)))
(u:if-found (shader-program (u:href (shaders core)
(shader material-instance)))
(progn
(with-slots (%shader-program) material-instance
(setf %shader-program shader-program))
(annotate-material-uniforms material-instance shader-program)
(annotate-material-blocks
material-instance shader-program core))
(error "Material ~s uses an undefined shader: ~s."
(id material-instance) (shader material-instance)))))
;; An accessor for the material type pops up all the way over here since we
;; need to understand that it requires a large amount of high level work to
;; perform its function of changing the shader program associated with the
;; amterial..
(defmethod (setf shader) (value (mat material))
(with-slots (%shader) mat
(setf %shader value)
(resolve-material mat))
value)
| null | https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/src/core-late/material.lisp | lisp | material-profile impl
NOTE: will be replaced by defstruct constructor
material impl
TODO: Fix %make-material so I don't have to do this.
Now we copy over the uniforms
Now we copy over the blocks.
TODO: we probably need to call into core buffer binding management
services to perform the binding right here.
export PUBLIC API
TODO: these modify the semantic-buffer which then gets processed into a new
computed buffer.
We can only set the semantic-value, which gets automatically upgraded to the
computed-value upon setting.
TODO: Need to do something with the old computed value since it might
export PUBLIC API
This is read only, it is the computed value in the material.
Default conversion functions for each uniform type.
type-info. Use that to set the binder function.
for this specific uniform type. This will be the last
function executed and will convert the in-flight semantic
value into a real computed value for use by the binder
function.
NOTE: We set it to NIL here because if we're changing the
shader on a material, we'll push multiple copies of the this
sequence into the list when we resolve-material on that copy
with the changed shader--which is wrong. This will now do
the right thing in any (I believe) situation.
the composition sequence before the above.
computed value.
core
TODO: Ensure that all :block-alias names are unique in the material
An accessor for the material type pops up all the way over here since we
need to understand that it requires a large amount of high level work to
perform its function of changing the shader program associated with the
amterial.. | (in-package #:virality)
(defun %make-material-profile (&rest init-args)
(apply #'make-instance 'material-profile init-args))
(defun %add-material-profile (profile core)
(setf (u:href (profiles (materials core)) (name profile)) profile))
(defun %make-material (id shader instances attributes profiles core)
(make-instance 'material :id id
:shader shader
:instances instances
:attributes attributes
:profile-overlay-names profiles
:core core))
(defmethod (setf instances) (value (mat material))
(with-slots (%instances) mat
(setf %instances value)))
(defmethod (setf attributes) (value (mat material))
(with-slots (%attributes) mat
(setf %attributes value)))
(defun %deep-copy-material (current-mat new-mat-name)
(let* ((new-id new-mat-name)
(new-shader (shader current-mat))
(new-shader-program (shader-program current-mat))
(new-instances (instances current-mat))
(new-attributes
(copy-seq (attributes current-mat)))
(new-uniforms (u:dict #'eq))
(new-blocks (u:dict #'eq))
(new-profile-overlay-names
(copy-seq (profile-overlay-names current-mat)))
(new-active-texture-unit (active-texture-unit current-mat))
(new-mat
(make-instance 'material
:id new-id
:shader new-shader
:shader-program new-shader-program
:instances new-instances
:attributes new-attributes
:core (core current-mat)
:uniforms new-uniforms
:blocks new-blocks
:profile-overlay-names new-profile-overlay-names
:active-texture-unit new-active-texture-unit)))
(u:do-hash (k v (uniforms current-mat))
(setf (u:href new-uniforms k)
(%deep-copy-material-uniform-value v new-mat)))
(u:do-hash (k v (blocks current-mat))
(setf (u:href new-blocks k)
(%deep-copy-material-block-value v new-mat)))
new-mat))
(defun bind-material-uniforms (mat)
(when mat
(u:do-hash (k v (uniforms mat))
(when (functionp (semantic-value v))
(execute-composition/semantic->computed v))
(funcall (binder v) (shader-program mat) k (computed-value v)))))
(defun bind-material-buffers (mat)
(when mat
(u:do-hash (k v (blocks mat))
(declare (ignore k v))
nil)))
(defun bind-material (mat)
(bind-material-uniforms mat)
(bind-material-buffers mat))
(defun uniform-ref-p (mat uniform-var)
"Return a generalized boolean if the specified uniform ref exists or not."
(u:href (uniforms mat) uniform-var))
(defun uniform-ref (mat uniform-var)
(u:if-let ((material-uniform-value (u:href (uniforms mat) uniform-var)))
(semantic-value material-uniform-value)
(error "Material ~s does not have the referenced uniform ~s.~%~
Please add a uniform to the material, and/or check your material ~
profile settings."
(id mat) uniform-var)))
(defun (setf uniform-ref) (new-val mat uniform-var)
(u:if-let ((material-uniform-value (u:href (uniforms mat) uniform-var)))
(progn
be consuming resources like when it is a sampler on the GPU .
(setf (semantic-value material-uniform-value) new-val)
(execute-composition/semantic->computed material-uniform-value)
(semantic-value material-uniform-value))
(error "Material ~s does not have the referenced uniform ~s.~%~
Please add a uniform to the material, and/or check your material ~
profile settings."
(id mat) uniform-var)))
(defun mat-computed-uniform-ref (mat uniform-var)
(computed-value (u:href (uniforms mat) uniform-var)))
(defun determine-binder-function (material glsl-type)
(typecase glsl-type
(symbol
(if (sampler-p glsl-type)
(let ((unit (active-texture-unit material)))
(incf (active-texture-unit material))
(lambda (shader uniform-name texture)
(gl:active-texture unit)
(gl:bind-texture (sampler-type->texture-type glsl-type)
(tex::texid texture))
(shadow:uniform-int shader uniform-name unit)))
(ecase glsl-type
(:bool (lambda (shader uniform value)
(shadow:uniform-int shader uniform (if value 1 0))))
(:int #'shadow:uniform-int)
(:float #'shadow:uniform-float)
(:vec2 #'shadow:uniform-vec2)
(:vec3 #'shadow:uniform-vec3)
(:vec4 #'shadow:uniform-vec4)
(:mat2 #'shadow:uniform-mat2)
(:mat3 #'shadow:uniform-mat3)
(:mat4 #'shadow:uniform-mat4))))
(cons
(if (sampler-p (car glsl-type))
(let* ((units
(loop :for i :below (cdr glsl-type)
:collect (prog1 (active-texture-unit material)
(incf (active-texture-unit material)))))
(units (coerce units 'vector)))
(lambda (shader uniform-name texture-array)
Bind all of the textures to their active units first
(loop :for texture :across texture-array
:for unit :across units
:do (gl:active-texture unit)
(gl:bind-texture
(sampler-type->texture-type (car glsl-type))
(tex::texid texture)))
(shadow:uniform-int-array shader uniform-name units)))
(ecase (car glsl-type)
(:bool #'shadow:uniform-int-array)
(:int #'shadow:uniform-int-array)
(:float #'shadow:uniform-float-array)
(:vec2 #'shadow:uniform-vec2-array)
(:vec3 #'shadow:uniform-vec3-array)
(:vec4 #'shadow:uniform-vec4-array)
(:mat2 #'shadow:uniform-mat2-array)
(:mat3 #'shadow:uniform-mat3-array)
(:mat4 #'shadow:uniform-mat4-array))))
(t
(error "Cannot determine binder function for glsl-type: ~s~%"
glsl-type))))
(defun annotate-material-uniform (uniform-name uniform-value material
shader-program)
(u:if-found (type-info (u:href (shadow:uniforms shader-program)
uniform-name))
(let ((uniform-type (u:href type-info :type)))
1 . Find the uniform in the shader - program and get its
(setf (binder uniform-value) (determine-binder-function
material uniform-type))
2 . Figure out the semantic->computed composition function
(setf (semantic->computed uniform-value) nil)
(push (if (sampler-p uniform-type)
(gen-sampler/sem->com)
(if (force-copy uniform-value)
(gen-default-copy/sem->com)
#'identity/for-material-custom-functions))
(semantic->computed uniform-value))
3 . Put the user specified semantic transformer function into
(push (transformer uniform-value)
(semantic->computed uniform-value))
4 . Execute the composition function sequence to produce the
(execute-composition/semantic->computed uniform-value))
(error "Material ~s uses unknown uniform ~s in shader ~s."
(id material) uniform-name (shader material))))
(defun annotate-material-uniforms (material shader-program)
(u:do-hash (k v (uniforms material))
(annotate-material-uniform k v material shader-program)))
(defun annotate-material-block (alias-name block-value material shader-program
core)
(declare (ignore shader-program core))
1 . Validate that this material - block - value is present in the shaders in
TODO : 2 . Create the block - name - alias , but only once .
(unless (shadow:find-block alias-name)
(shadow:create-block-alias (storage-type block-value)
(block-name block-value)
(shader material)
alias-name)))
(defun annotate-material-blocks (material shader-program core)
(u:do-hash (k v (blocks material))
(annotate-material-block k v material shader-program core)))
(defun resolve-material (material-instance)
"Convert semantic-values to computed-values. Type check the uniforms against
the shader program in the material."
(let ((core (core material-instance)))
(u:if-found (shader-program (u:href (shaders core)
(shader material-instance)))
(progn
(with-slots (%shader-program) material-instance
(setf %shader-program shader-program))
(annotate-material-uniforms material-instance shader-program)
(annotate-material-blocks
material-instance shader-program core))
(error "Material ~s uses an undefined shader: ~s."
(id material-instance) (shader material-instance)))))
(defmethod (setf shader) (value (mat material))
(with-slots (%shader) mat
(setf %shader value)
(resolve-material mat))
value)
|
e1d2ce45dd0d82993cf05da60ebc10070cd9ecb6af927466ca73871feb115772 | kelvin-mai/clj-auth | utils.clj | (ns auth.utils
(:require [buddy.auth :refer [authenticated?]]
[buddy.auth.backends :as backends]
[buddy.auth.middleware :refer [wrap-authentication]]
[buddy.sign.jwt :as jwt]))
(def jwt-secret "JWT_SECRET")
(def backend (backends/jws {:secret jwt-secret}))
(defn wrap-jwt-authentication
[handler]
(wrap-authentication handler backend))
(defn auth-middleware
[handler]
(fn [request]
(if (authenticated? request)
(handler request)
{:status 401 :body {:error "Unauthorized"}})))
(defn create-token [payload]
(jwt/sign payload jwt-secret))
| null | https://raw.githubusercontent.com/kelvin-mai/clj-auth/254a82d01c731bf18a5974408d3c5cf5ab159aaf/src/auth/utils.clj | clojure | (ns auth.utils
(:require [buddy.auth :refer [authenticated?]]
[buddy.auth.backends :as backends]
[buddy.auth.middleware :refer [wrap-authentication]]
[buddy.sign.jwt :as jwt]))
(def jwt-secret "JWT_SECRET")
(def backend (backends/jws {:secret jwt-secret}))
(defn wrap-jwt-authentication
[handler]
(wrap-authentication handler backend))
(defn auth-middleware
[handler]
(fn [request]
(if (authenticated? request)
(handler request)
{:status 401 :body {:error "Unauthorized"}})))
(defn create-token [payload]
(jwt/sign payload jwt-secret))
|
|
6c9565549e2dbf784109663949bac1823ffdc2eae600fd509595694c914fa6be | achirkin/vulkan | VK_NV_coverage_reduction_mode.hs | # OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_HADDOCK not - home #
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE ForeignFunctionInterface #
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.Vulkan.Ext.VK_NV_coverage_reduction_mode
* Vulkan extension : @VK_NV_coverage_reduction_mode@
-- |
--
-- supported: @vulkan@
--
-- contact: @Kedarnath Thangudu @kthangudu@
--
author :
--
-- type: @device@
--
-- Extension number: @251@
--
-- Required extensions: 'VK_NV_framebuffer_mixed_samples'.
--
-- ** Required extensions: 'VK_NV_framebuffer_mixed_samples'.
module Graphics.Vulkan.Marshal, AHardwareBuffer(),
ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkCoverageModulationModeNV(..), VkCoverageReductionModeNV(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkFramebufferMixedSamplesCombinationNV,
VkPhysicalDeviceCoverageReductionModeFeaturesNV,
VkPhysicalDeviceFeatures, VkPhysicalDeviceFeatures2,
VkPipelineCoverageReductionStateCreateInfoNV,
VkPipelineMultisampleStateCreateInfo, VkSampleCountBitmask(..),
VkSampleCountFlagBits(), VkSampleCountFlags(), VkStructureType(..),
-- > #include "vk_platform.h"
VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
pattern VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
VkResult(..), VkAccelerationStructureKHR,
VkAccelerationStructureKHR_T(), VkAccelerationStructureNV,
VkAccelerationStructureNV_T(), VkBuffer, VkBufferView,
VkBufferView_T(), VkBuffer_T(), VkCommandBuffer,
VkCommandBuffer_T(), VkCommandPool, VkCommandPool_T(),
VkDebugReportCallbackEXT, VkDebugReportCallbackEXT_T(),
VkDebugUtilsMessengerEXT, VkDebugUtilsMessengerEXT_T(),
VkDeferredOperationKHR, VkDeferredOperationKHR_T(),
VkDescriptorPool, VkDescriptorPool_T(), VkDescriptorSet,
VkDescriptorSetLayout, VkDescriptorSetLayout_T(),
VkDescriptorSet_T(), VkDescriptorUpdateTemplate,
VkDescriptorUpdateTemplateKHR, VkDescriptorUpdateTemplateKHR_T(),
VkDescriptorUpdateTemplate_T(), VkDevice, VkDeviceMemory,
VkDeviceMemory_T(), VkDevice_T(), VkDisplayKHR, VkDisplayKHR_T(),
VkDisplayModeKHR, VkDisplayModeKHR_T(), VkEvent, VkEvent_T(),
VkFence, VkFence_T(), VkFramebuffer, VkFramebuffer_T(), VkImage,
VkImageView, VkImageView_T(), VkImage_T(),
VkIndirectCommandsLayoutNV, VkIndirectCommandsLayoutNV_T(),
VkInstance, VkInstance_T(), VkPerformanceConfigurationINTEL,
VkPerformanceConfigurationINTEL_T(), VkPhysicalDevice,
VkPhysicalDevice_T(), VkPipeline, VkPipelineCache,
VkPipelineCache_T(), VkPipelineLayout, VkPipelineLayout_T(),
VkPipeline_T(), VkPrivateDataSlotEXT, VkPrivateDataSlotEXT_T(),
VkQueryPool, VkQueryPool_T(), VkQueue, VkQueue_T(), VkRenderPass,
VkRenderPass_T(), VkSampler, VkSamplerYcbcrConversion,
VkSamplerYcbcrConversionKHR, VkSamplerYcbcrConversionKHR_T(),
VkSamplerYcbcrConversion_T(), VkSampler_T(), VkSemaphore,
VkSemaphore_T(), VkShaderModule, VkShaderModule_T(), VkSurfaceKHR,
VkSurfaceKHR_T(), VkSwapchainKHR, VkSwapchainKHR_T(),
VkValidationCacheEXT, VkValidationCacheEXT_T(),
VkFramebufferAttachmentImageInfo,
VkFramebufferAttachmentImageInfoKHR,
VkFramebufferAttachmentsCreateInfo,
VkFramebufferAttachmentsCreateInfoKHR, VkFramebufferCreateInfo,
VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION,
pattern VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION,
VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME,
pattern VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV,
pattern VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV,
pattern VK_STRUCTURE_TYPE_FRAMEBUFFER_MIXED_SAMPLES_COMBINATION_NV)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Marshal.Proc (VulkanProc (..))
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Coverage
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.Result
import Graphics.Vulkan.Types.Enum.SampleCountFlags
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Handles
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.Framebuffer
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceCoverageReductionModeFeaturesNV,
VkPhysicalDeviceFeatures2)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
import Graphics.Vulkan.Types.Struct.Pipeline (VkPipelineCoverageReductionStateCreateInfoNV,
VkPipelineMultisampleStateCreateInfo)
pattern VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
:: CString
pattern VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
<-
(is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
-> True)
where
VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
= _VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
{-# INLINE _VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
#-}
_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV ::
CString
_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
= Ptr
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV\NUL"#
{-# INLINE is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
#-}
is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV ::
CString -> Bool
is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
= (EQ ==) .
cmpCStrings
_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
type VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
=
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV"
| Success codes : ' VK_SUCCESS ' , ' VK_INCOMPLETE ' .
--
-- Error codes: 'VK_ERROR_OUT_OF_HOST_MEMORY', 'VK_ERROR_OUT_OF_DEVICE_MEMORY'.
--
> VkResult vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
-- > ( VkPhysicalDevice physicalDevice
> , uint32_t * pCombinationCount
> , VkFramebufferMixedSamplesCombinationNV * pCombinations
-- > )
--
-- <-extensions/html/vkspec.html#vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV registry at www.khronos.org>
type HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
=
^ physicalDevice
->
Ptr Word32 -- ^ pCombinationCount
->
Ptr VkFramebufferMixedSamplesCombinationNV -- ^ pCombinations
-> IO VkResult
type PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
=
FunPtr
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
foreign import ccall unsafe "dynamic"
unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVUnsafe
::
PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
->
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
foreign import ccall safe "dynamic"
unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVSafe
::
PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
->
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
instance VulkanProc
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV"
where
type VkProcType
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV"
=
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
vkProcSymbol
= _VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
# INLINE vkProcSymbol #
unwrapVkProcPtrUnsafe
= unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVUnsafe
# INLINE unwrapVkProcPtrUnsafe #
unwrapVkProcPtrSafe
= unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVSafe
# INLINE unwrapVkProcPtrSafe #
pattern VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION = 1
type VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION = 1
pattern VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME :: CString
pattern VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME <-
(is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME -> True)
where
VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
= _VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
{-# INLINE _VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME #-}
_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME :: CString
_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
= Ptr "VK_NV_coverage_reduction_mode\NUL"#
# INLINE is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME #
is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME :: CString -> Bool
is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
= (EQ ==) .
cmpCStrings _VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
type VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME =
"VK_NV_coverage_reduction_mode"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV
= VkStructureType 1000250000
pattern VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV
= VkStructureType 1000250001
pattern VK_STRUCTURE_TYPE_FRAMEBUFFER_MIXED_SAMPLES_COMBINATION_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_FRAMEBUFFER_MIXED_SAMPLES_COMBINATION_NV
= VkStructureType 1000250002
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_NV_coverage_reduction_mode.hs | haskell | # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE PatternSynonyms #
# LANGUAGE Strict #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
|
supported: @vulkan@
contact: @Kedarnath Thangudu @kthangudu@
type: @device@
Extension number: @251@
Required extensions: 'VK_NV_framebuffer_mixed_samples'.
** Required extensions: 'VK_NV_framebuffer_mixed_samples'.
> #include "vk_platform.h"
# INLINE _VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
#
# INLINE is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
#
Error codes: 'VK_ERROR_OUT_OF_HOST_MEMORY', 'VK_ERROR_OUT_OF_DEVICE_MEMORY'.
> ( VkPhysicalDevice physicalDevice
> )
<-extensions/html/vkspec.html#vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV registry at www.khronos.org>
^ pCombinationCount
^ pCombinations
# INLINE _VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME # | # OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_HADDOCK not - home #
# LANGUAGE FlexibleInstances #
# LANGUAGE ForeignFunctionInterface #
module Graphics.Vulkan.Ext.VK_NV_coverage_reduction_mode
* Vulkan extension : @VK_NV_coverage_reduction_mode@
author :
module Graphics.Vulkan.Marshal, AHardwareBuffer(),
ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkCoverageModulationModeNV(..), VkCoverageReductionModeNV(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkFramebufferMixedSamplesCombinationNV,
VkPhysicalDeviceCoverageReductionModeFeaturesNV,
VkPhysicalDeviceFeatures, VkPhysicalDeviceFeatures2,
VkPipelineCoverageReductionStateCreateInfoNV,
VkPipelineMultisampleStateCreateInfo, VkSampleCountBitmask(..),
VkSampleCountFlagBits(), VkSampleCountFlags(), VkStructureType(..),
VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
pattern VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV,
VkResult(..), VkAccelerationStructureKHR,
VkAccelerationStructureKHR_T(), VkAccelerationStructureNV,
VkAccelerationStructureNV_T(), VkBuffer, VkBufferView,
VkBufferView_T(), VkBuffer_T(), VkCommandBuffer,
VkCommandBuffer_T(), VkCommandPool, VkCommandPool_T(),
VkDebugReportCallbackEXT, VkDebugReportCallbackEXT_T(),
VkDebugUtilsMessengerEXT, VkDebugUtilsMessengerEXT_T(),
VkDeferredOperationKHR, VkDeferredOperationKHR_T(),
VkDescriptorPool, VkDescriptorPool_T(), VkDescriptorSet,
VkDescriptorSetLayout, VkDescriptorSetLayout_T(),
VkDescriptorSet_T(), VkDescriptorUpdateTemplate,
VkDescriptorUpdateTemplateKHR, VkDescriptorUpdateTemplateKHR_T(),
VkDescriptorUpdateTemplate_T(), VkDevice, VkDeviceMemory,
VkDeviceMemory_T(), VkDevice_T(), VkDisplayKHR, VkDisplayKHR_T(),
VkDisplayModeKHR, VkDisplayModeKHR_T(), VkEvent, VkEvent_T(),
VkFence, VkFence_T(), VkFramebuffer, VkFramebuffer_T(), VkImage,
VkImageView, VkImageView_T(), VkImage_T(),
VkIndirectCommandsLayoutNV, VkIndirectCommandsLayoutNV_T(),
VkInstance, VkInstance_T(), VkPerformanceConfigurationINTEL,
VkPerformanceConfigurationINTEL_T(), VkPhysicalDevice,
VkPhysicalDevice_T(), VkPipeline, VkPipelineCache,
VkPipelineCache_T(), VkPipelineLayout, VkPipelineLayout_T(),
VkPipeline_T(), VkPrivateDataSlotEXT, VkPrivateDataSlotEXT_T(),
VkQueryPool, VkQueryPool_T(), VkQueue, VkQueue_T(), VkRenderPass,
VkRenderPass_T(), VkSampler, VkSamplerYcbcrConversion,
VkSamplerYcbcrConversionKHR, VkSamplerYcbcrConversionKHR_T(),
VkSamplerYcbcrConversion_T(), VkSampler_T(), VkSemaphore,
VkSemaphore_T(), VkShaderModule, VkShaderModule_T(), VkSurfaceKHR,
VkSurfaceKHR_T(), VkSwapchainKHR, VkSwapchainKHR_T(),
VkValidationCacheEXT, VkValidationCacheEXT_T(),
VkFramebufferAttachmentImageInfo,
VkFramebufferAttachmentImageInfoKHR,
VkFramebufferAttachmentsCreateInfo,
VkFramebufferAttachmentsCreateInfoKHR, VkFramebufferCreateInfo,
VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION,
pattern VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION,
VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME,
pattern VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV,
pattern VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV,
pattern VK_STRUCTURE_TYPE_FRAMEBUFFER_MIXED_SAMPLES_COMBINATION_NV)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Marshal.Proc (VulkanProc (..))
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Coverage
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.Result
import Graphics.Vulkan.Types.Enum.SampleCountFlags
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Handles
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.Framebuffer
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceCoverageReductionModeFeaturesNV,
VkPhysicalDeviceFeatures2)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
import Graphics.Vulkan.Types.Struct.Pipeline (VkPipelineCoverageReductionStateCreateInfoNV,
VkPipelineMultisampleStateCreateInfo)
pattern VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
:: CString
pattern VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
<-
(is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
-> True)
where
VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
= _VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV ::
CString
_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
= Ptr
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV\NUL"#
is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV ::
CString -> Bool
is_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
= (EQ ==) .
cmpCStrings
_VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
type VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
=
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV"
| Success codes : ' VK_SUCCESS ' , ' VK_INCOMPLETE ' .
> VkResult vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
> , uint32_t * pCombinationCount
> , VkFramebufferMixedSamplesCombinationNV * pCombinations
type HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
=
^ physicalDevice
->
->
-> IO VkResult
type PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
=
FunPtr
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
foreign import ccall unsafe "dynamic"
unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVUnsafe
::
PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
->
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
foreign import ccall safe "dynamic"
unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVSafe
::
PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
->
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
instance VulkanProc
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV"
where
type VkProcType
"vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV"
=
HS_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
vkProcSymbol
= _VkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV
# INLINE vkProcSymbol #
unwrapVkProcPtrUnsafe
= unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVUnsafe
# INLINE unwrapVkProcPtrUnsafe #
unwrapVkProcPtrSafe
= unwrapVkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNVSafe
# INLINE unwrapVkProcPtrSafe #
pattern VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION = 1
type VK_NV_COVERAGE_REDUCTION_MODE_SPEC_VERSION = 1
pattern VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME :: CString
pattern VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME <-
(is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME -> True)
where
VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
= _VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME :: CString
_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
= Ptr "VK_NV_coverage_reduction_mode\NUL"#
# INLINE is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME #
is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME :: CString -> Bool
is_VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
= (EQ ==) .
cmpCStrings _VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME
type VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME =
"VK_NV_coverage_reduction_mode"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV
= VkStructureType 1000250000
pattern VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV
= VkStructureType 1000250001
pattern VK_STRUCTURE_TYPE_FRAMEBUFFER_MIXED_SAMPLES_COMBINATION_NV
:: VkStructureType
pattern VK_STRUCTURE_TYPE_FRAMEBUFFER_MIXED_SAMPLES_COMBINATION_NV
= VkStructureType 1000250002
|
394fa4acbb702501b984068f1c5961b010a98cd438c45b17ff4088dd253b345f | svdm/ClojureGP | helpers.clj | Copyright ( c ) . All rights reserved .
The use and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php) which
;; can be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other, from
;; this software.
; Various functions and data structures used in the tests
(ns test.helpers
(:use clojure.test
cljgp.breeding
cljgp.generate
cljgp.selection
cljgp.config
cljgp.random
cljgp.util)
(:import [java.io OutputStreamWriter OutputStream]))
(defmacro quiet
[form]
`(binding [*out* (OutputStreamWriter.
(proxy [OutputStream] []
(write [a# b# c#] nil)))]
~form))
; Validity checks
(defn valid-tree?
"Does this tree fit the most fundamental requirements? That is, is it a seq or
a valid result?"
[tree]
(or (coll? tree)
(number? tree)
(symbol? tree)))
(defn valid-ind?
"Returns whether given map contains keys required for individuals."
[ind]
(and (map? ind)
(every? (set (keys ind)) [:func
:gen
:fitness])))
; A config for a simple gimped experiment
(derive ::num ::any)
(derive Number ::num)
(derive ::seq ::any)
(derive ::string ::seq)
(derive ::vector ::seq)
(def _1 1)
(def _2 2)
(def _3 3)
(def _4 4)
(def _5 5)
(def TEXT "foobar")
(def VECT [94 17 2])
(defn safe-nth
[coll idx]
(if-let [result (try (nth coll idx)
(catch RuntimeException e nil))]
result
0))
(def config-maths
{:function-set [(prim `-
{:gp-type Number
:gp-arg-types [Number Number]})
(prim `+
{:gp-type Number
:gp-arg-types [Number Number]})
(prim `*
{:gp-type Number
:gp-arg-types [Number Number]})
(prim `count
{:gp-type Number
:gp-arg-types [::seq]})
(prim `safe-nth
{:gp-type Number
:gp-arg-types [::vector Number]})]
:terminal-set [(prim `_1 {:gp-type Number})
(prim `_2 {:gp-type Number})
(prim `_3 {:gp-type Number})
4
5
(prim `TEXT {:gp-type ::string})
(prim `VECT {:gp-type ::vector})]
:arg-list []
:func-template-fn (make-func-template 'gp-mather [])
:root-type Number
:evaluation-fn (fn [func ind] (rand))
:selection-fn (partial tournament-select {:size 3})
:end-condition-fn (make-end 50)
:population-size 8
:breeders [{:prob 0.8 :breeder-fn crossover-breeder}
{:prob 0.1 :breeder-fn mutation-breeder}
{:prob 0.1 :breeder-fn reproduction-breeder}]
:breeding-retries 50
:validate-tree-fn identity
:pop-generation-fn (partial generate-ramped {:max-depth 7
:grow-change 0.5})
:threads 2
:rand-seeds [0 1] ; not used
:rand-fn-maker make-default-rand
; supply premade rand-fns instead of
; depending on preproc to do this
:rand-fns (map make-default-rand
(take 2 (repeatedly #(System/currentTimeMillis))))
})
; Helpers for breeding and generate tests
(def func-set-maths (:function-set config-maths))
(def term-set-maths (:terminal-set config-maths))
(defn my-tpl [tree] (list `fn 'gp-mather [] tree))
(defn my-gen
[max-depth method root-type]
(if-let [tree (try
(generate-tree max-depth
method
func-set-maths
term-set-maths
root-type)
(catch RuntimeException e
false))]
tree
(recur max-depth method root-type)))
(def rtype (:root-type config-maths))
; for this primitive set, trees should always return a number
(def valid-result? number?)
(defn valid-eval?
"When evaluated, does this tree produce a valid result?"
[tree]
(valid-result? (eval tree)))
(defn full-tree-test
[tree]
(is (valid-tree? tree)
(str "Root must be seq or result constant, tree: " tree))
(is (valid-types? tree rtype)
(str "Tree must be validly typed, tree: " tree))
(is (valid-eval? tree)
(str "Result of evaluation must be valid, tree: " tree)))
| null | https://raw.githubusercontent.com/svdm/ClojureGP/266e501411b37297bdeb082913df63ececa8515c/test/helpers.clj | clojure | Public License 1.0 (-1.0.php) which
can be found in the file epl-v10.html at the root of this distribution. By
using this software in any fashion, you are agreeing to be bound by the
terms of this license. You must not remove this notice, or any other, from
this software.
Various functions and data structures used in the tests
Validity checks
A config for a simple gimped experiment
not used
supply premade rand-fns instead of
depending on preproc to do this
Helpers for breeding and generate tests
for this primitive set, trees should always return a number
| Copyright ( c ) . All rights reserved .
The use and distribution terms for this software are covered by the Eclipse
(ns test.helpers
(:use clojure.test
cljgp.breeding
cljgp.generate
cljgp.selection
cljgp.config
cljgp.random
cljgp.util)
(:import [java.io OutputStreamWriter OutputStream]))
(defmacro quiet
[form]
`(binding [*out* (OutputStreamWriter.
(proxy [OutputStream] []
(write [a# b# c#] nil)))]
~form))
(defn valid-tree?
"Does this tree fit the most fundamental requirements? That is, is it a seq or
a valid result?"
[tree]
(or (coll? tree)
(number? tree)
(symbol? tree)))
(defn valid-ind?
"Returns whether given map contains keys required for individuals."
[ind]
(and (map? ind)
(every? (set (keys ind)) [:func
:gen
:fitness])))
(derive ::num ::any)
(derive Number ::num)
(derive ::seq ::any)
(derive ::string ::seq)
(derive ::vector ::seq)
(def _1 1)
(def _2 2)
(def _3 3)
(def _4 4)
(def _5 5)
(def TEXT "foobar")
(def VECT [94 17 2])
(defn safe-nth
[coll idx]
(if-let [result (try (nth coll idx)
(catch RuntimeException e nil))]
result
0))
(def config-maths
{:function-set [(prim `-
{:gp-type Number
:gp-arg-types [Number Number]})
(prim `+
{:gp-type Number
:gp-arg-types [Number Number]})
(prim `*
{:gp-type Number
:gp-arg-types [Number Number]})
(prim `count
{:gp-type Number
:gp-arg-types [::seq]})
(prim `safe-nth
{:gp-type Number
:gp-arg-types [::vector Number]})]
:terminal-set [(prim `_1 {:gp-type Number})
(prim `_2 {:gp-type Number})
(prim `_3 {:gp-type Number})
4
5
(prim `TEXT {:gp-type ::string})
(prim `VECT {:gp-type ::vector})]
:arg-list []
:func-template-fn (make-func-template 'gp-mather [])
:root-type Number
:evaluation-fn (fn [func ind] (rand))
:selection-fn (partial tournament-select {:size 3})
:end-condition-fn (make-end 50)
:population-size 8
:breeders [{:prob 0.8 :breeder-fn crossover-breeder}
{:prob 0.1 :breeder-fn mutation-breeder}
{:prob 0.1 :breeder-fn reproduction-breeder}]
:breeding-retries 50
:validate-tree-fn identity
:pop-generation-fn (partial generate-ramped {:max-depth 7
:grow-change 0.5})
:threads 2
:rand-fn-maker make-default-rand
:rand-fns (map make-default-rand
(take 2 (repeatedly #(System/currentTimeMillis))))
})
(def func-set-maths (:function-set config-maths))
(def term-set-maths (:terminal-set config-maths))
(defn my-tpl [tree] (list `fn 'gp-mather [] tree))
(defn my-gen
[max-depth method root-type]
(if-let [tree (try
(generate-tree max-depth
method
func-set-maths
term-set-maths
root-type)
(catch RuntimeException e
false))]
tree
(recur max-depth method root-type)))
(def rtype (:root-type config-maths))
(def valid-result? number?)
(defn valid-eval?
"When evaluated, does this tree produce a valid result?"
[tree]
(valid-result? (eval tree)))
(defn full-tree-test
[tree]
(is (valid-tree? tree)
(str "Root must be seq or result constant, tree: " tree))
(is (valid-types? tree rtype)
(str "Tree must be validly typed, tree: " tree))
(is (valid-eval? tree)
(str "Result of evaluation must be valid, tree: " tree)))
|
4a2f1ca7b4f9adc91d5906bac932213b12928ac38a28e2553e2447d70b9f25a2 | LPCIC/matita | content.ml | Copyright ( C ) 2000 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /.
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /.
*)
(**************************************************************************)
(* *)
(* *)
< >
(* 16/6/2003 *)
(* *)
(**************************************************************************)
$ I d : content.ml 11008 2010 - 10 - 26 14:32:14Z asperti $
type id = string;;
type joint_recursion_kind =
[ `Recursive of int list
| `CoRecursive
| `Inductive of int (* paramsno *)
| `CoInductive of int (* paramsno *)
]
;;
type var_or_const = Var | Const;;
type 'term declaration =
{ dec_name : string option;
dec_id : id ;
dec_inductive : bool;
dec_aref : string;
dec_type : 'term
}
;;
type 'term definition =
{ def_name : string option;
def_id : id ;
def_aref : string ;
def_term : 'term ;
def_type : 'term
}
;;
type 'term inductive =
{ inductive_id : id ;
inductive_name : string;
inductive_kind : bool;
inductive_type : 'term;
inductive_constructors : 'term declaration list
}
;;
type 'term decl_context_element =
[ `Declaration of 'term declaration
| `Hypothesis of 'term declaration
]
;;
type ('term,'proof) def_context_element =
[ `Proof of 'proof
| `Definition of 'term definition
]
;;
type ('term,'proof) in_joint_context_element =
[ `Inductive of 'term inductive
| 'term decl_context_element
| ('term,'proof) def_context_element
]
;;
type ('term,'proof) joint =
{ joint_id : id ;
joint_kind : joint_recursion_kind ;
joint_defs : ('term,'proof) in_joint_context_element list
}
;;
type ('term,'proof) joint_context_element =
[ `Joint of ('term,'proof) joint ]
;;
type 'term proof =
{ proof_name : string option;
proof_id : id ;
proof_context : 'term in_proof_context_element list ;
proof_apply_context: 'term proof list;
proof_conclude : 'term conclude_item
}
and 'term in_proof_context_element =
[ 'term decl_context_element
| ('term,'term proof) def_context_element
| ('term,'term proof) joint_context_element
]
and 'term conclude_item =
{ conclude_id : id;
conclude_aref : string;
conclude_method : string;
conclude_args : ('term arg) list ;
conclude_conclusion : 'term option
}
and 'term arg =
Aux of string
| Premise of premise
| Lemma of lemma
| Term of bool * 'term
| ArgProof of 'term proof
| ArgMethod of string (* ???? *)
and premise =
{ premise_id: id;
premise_xref : string ;
premise_binder : string option;
premise_n : int option;
}
and lemma =
{ lemma_id: id;
lemma_name: string;
lemma_uri: string
}
;;
type 'term conjecture = id * int * 'term context * 'term
and 'term context = 'term hypothesis list
and 'term hypothesis =
['term decl_context_element | ('term,'term proof) def_context_element ] option
;;
type 'term in_object_context_element =
[ `Decl of var_or_const * 'term decl_context_element
| `Def of var_or_const * 'term * ('term,'term proof) def_context_element
| ('term,'term proof) joint_context_element
]
;;
type 'term cobj =
id * (* id *)
'term conjecture list option * (* optional metasenv *)
'term in_object_context_element (* actual object *)
;;
| null | https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/content/content.ml | ocaml | ************************************************************************
16/6/2003
************************************************************************
paramsno
paramsno
????
id
optional metasenv
actual object | Copyright ( C ) 2000 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /.
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /.
*)
< >
$ I d : content.ml 11008 2010 - 10 - 26 14:32:14Z asperti $
type id = string;;
type joint_recursion_kind =
[ `Recursive of int list
| `CoRecursive
]
;;
type var_or_const = Var | Const;;
type 'term declaration =
{ dec_name : string option;
dec_id : id ;
dec_inductive : bool;
dec_aref : string;
dec_type : 'term
}
;;
type 'term definition =
{ def_name : string option;
def_id : id ;
def_aref : string ;
def_term : 'term ;
def_type : 'term
}
;;
type 'term inductive =
{ inductive_id : id ;
inductive_name : string;
inductive_kind : bool;
inductive_type : 'term;
inductive_constructors : 'term declaration list
}
;;
type 'term decl_context_element =
[ `Declaration of 'term declaration
| `Hypothesis of 'term declaration
]
;;
type ('term,'proof) def_context_element =
[ `Proof of 'proof
| `Definition of 'term definition
]
;;
type ('term,'proof) in_joint_context_element =
[ `Inductive of 'term inductive
| 'term decl_context_element
| ('term,'proof) def_context_element
]
;;
type ('term,'proof) joint =
{ joint_id : id ;
joint_kind : joint_recursion_kind ;
joint_defs : ('term,'proof) in_joint_context_element list
}
;;
type ('term,'proof) joint_context_element =
[ `Joint of ('term,'proof) joint ]
;;
type 'term proof =
{ proof_name : string option;
proof_id : id ;
proof_context : 'term in_proof_context_element list ;
proof_apply_context: 'term proof list;
proof_conclude : 'term conclude_item
}
and 'term in_proof_context_element =
[ 'term decl_context_element
| ('term,'term proof) def_context_element
| ('term,'term proof) joint_context_element
]
and 'term conclude_item =
{ conclude_id : id;
conclude_aref : string;
conclude_method : string;
conclude_args : ('term arg) list ;
conclude_conclusion : 'term option
}
and 'term arg =
Aux of string
| Premise of premise
| Lemma of lemma
| Term of bool * 'term
| ArgProof of 'term proof
and premise =
{ premise_id: id;
premise_xref : string ;
premise_binder : string option;
premise_n : int option;
}
and lemma =
{ lemma_id: id;
lemma_name: string;
lemma_uri: string
}
;;
type 'term conjecture = id * int * 'term context * 'term
and 'term context = 'term hypothesis list
and 'term hypothesis =
['term decl_context_element | ('term,'term proof) def_context_element ] option
;;
type 'term in_object_context_element =
[ `Decl of var_or_const * 'term decl_context_element
| `Def of var_or_const * 'term * ('term,'term proof) def_context_element
| ('term,'term proof) joint_context_element
]
;;
type 'term cobj =
;;
|
1b7e194ab04deef660af5babb4cebe809212d8d049468f36e09077ed28fd8552 | shayne-fletcher/zen | heap.ml | (* Heaps *)
module type S = sig
val heap_sort : 'a array -> 'a array
val heap_max : 'a array -> 'a
val heap_extract_max : 'a array -> int -> 'a * int
val heap_increase_key : 'a array -> int -> unit
val max_heap_insert : 'a array -> int -> int -> int
end
module Heap = struct
let parent i = i/2 - 1
let left i = 2 * i + 1
let right i = 2 * (i + 1)
(* In a max-heap,[i (i <> 0). arr.(parent (i)) >= arr.(i)].
That is, the value of a node is at most the value of its parent.
*)
let swap (arr : 'a array) (i : int) (j : int) =
let t = arr. (j) in
Array.set arr j (Array.get arr i);
Array.set arr i t
(* [max_heapfiy ~heapsize i] arranges for the subtree rooted at [i]
to be a max-heap under the assumption the children of [i] are
sub-heaps. *)
let rec max_heapify (arr : 'a array) ~(heap_size : int) (i : int) =
let l = left i in
let r = right i in
let largest =
if l < 0 then i
else if l >= heap_size then i
else if arr. (l) > arr. (i) then l
else i
in
let largest =
if r < 0 then largest
else if r >= heap_size then largest
else if arr. (r) > arr. (largest) then r
else largest
in
if largest <> i then (
swap arr i largest;
max_heapify arr ~heap_size largest
)
[ ] organizes [ arr ] into a max - heap .
let build_max_heap (arr : 'a array) =
let heap_size = Array.length arr in
for i = (heap_size - 1) / 2 - 1 downto 0 do
max_heapify arr ~heap_size i
done
(* [heap_sort arr] sorts in-place using heap-sort. *)
let heap_sort (arr : 'a array) =
let heap_size = ref (Array.length arr) in
build_max_heap arr;
for i = Array.length arr - 1 downto 1 do
swap arr 0 i;
heap_size := !heap_size - 1;
max_heapify arr ~heap_size:!heap_size 0;
done
(* [heap_max arr] returns the element of [arr] with the largest
key. *)
let heap_max (arr : 'a array) = arr. (0)
[ heap_extract_max arr heap_size ] removes and returns the element
of [ arr ] with the largest key . It is to be understood that the
returned heap is one element smaller .
of [arr] with the largest key. It is to be understood that the
returned heap is one element smaller. *)
let heap_extract_max (arr : 'a array) (heap_size : int) =
let () = if heap_size < 1 then failwith "heap underflow" else () in
let max = arr. (0) in
Array.set arr 0 (Array.get arr (heap_size - 1));
max_heapify arr ~heap_size:(heap_size - 1) 0;
max, (heap_size - 1)
(* [heap_increase_key arr i key] increases the value of element
[i]'s key to the new value [key] which is assumed to be at least
as large as [i]'s current key value.
- update arr.(i) to its new value - because the max-heap property
may now not be satisfied
- traverse a path from the node to the root
- repeatedly compare key to to parent
- exchange keys and continue of the elements's key is larger and
terminate if the element's keys is smaller
*)
let heap_increase_key (arr : 'a array) (i : int) (key : int) =
let () =
if key < arr. (i) then
failwith "new key is smaller than current key"
else () in
let i = ref i in
Array.set arr !i key;
while !i > 0 && arr. (parent !i) < arr. (!i ) do
swap arr !i (parent !i);
i := parent !i
done
[ max_heap_insert arr heap_size key ] inserts [ key ] into [ arr ] . It
is understood the size of the resulting heap is one greater than
the argument [ heap_size ] .
is understood the size of the resulting heap is one greater than
the argument [heap_size]. *)
let max_heap_insert (arr : 'a array) (heap_size : int) (key : int) =
let heap_size = heap_size + 1 in
Array.set arr (heap_size - 1) min_int;
heap_increase_key arr heap_size key;
heap_size
end
let () =
let arr = [| 5; 13; 2; 25; 7; 17; 20; 8; 4 |] in
Heap.heap_sort arr;
Array.iter (fun x -> Printf.printf "%d, " x) arr;
Printf.printf "\n";
flush stdout
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/prep/sort/heap.ml | ocaml | Heaps
In a max-heap,[i (i <> 0). arr.(parent (i)) >= arr.(i)].
That is, the value of a node is at most the value of its parent.
[max_heapfiy ~heapsize i] arranges for the subtree rooted at [i]
to be a max-heap under the assumption the children of [i] are
sub-heaps.
[heap_sort arr] sorts in-place using heap-sort.
[heap_max arr] returns the element of [arr] with the largest
key.
[heap_increase_key arr i key] increases the value of element
[i]'s key to the new value [key] which is assumed to be at least
as large as [i]'s current key value.
- update arr.(i) to its new value - because the max-heap property
may now not be satisfied
- traverse a path from the node to the root
- repeatedly compare key to to parent
- exchange keys and continue of the elements's key is larger and
terminate if the element's keys is smaller
|
module type S = sig
val heap_sort : 'a array -> 'a array
val heap_max : 'a array -> 'a
val heap_extract_max : 'a array -> int -> 'a * int
val heap_increase_key : 'a array -> int -> unit
val max_heap_insert : 'a array -> int -> int -> int
end
module Heap = struct
let parent i = i/2 - 1
let left i = 2 * i + 1
let right i = 2 * (i + 1)
let swap (arr : 'a array) (i : int) (j : int) =
let t = arr. (j) in
Array.set arr j (Array.get arr i);
Array.set arr i t
let rec max_heapify (arr : 'a array) ~(heap_size : int) (i : int) =
let l = left i in
let r = right i in
let largest =
if l < 0 then i
else if l >= heap_size then i
else if arr. (l) > arr. (i) then l
else i
in
let largest =
if r < 0 then largest
else if r >= heap_size then largest
else if arr. (r) > arr. (largest) then r
else largest
in
if largest <> i then (
swap arr i largest;
max_heapify arr ~heap_size largest
)
[ ] organizes [ arr ] into a max - heap .
let build_max_heap (arr : 'a array) =
let heap_size = Array.length arr in
for i = (heap_size - 1) / 2 - 1 downto 0 do
max_heapify arr ~heap_size i
done
let heap_sort (arr : 'a array) =
let heap_size = ref (Array.length arr) in
build_max_heap arr;
for i = Array.length arr - 1 downto 1 do
swap arr 0 i;
heap_size := !heap_size - 1;
max_heapify arr ~heap_size:!heap_size 0;
done
let heap_max (arr : 'a array) = arr. (0)
[ heap_extract_max arr heap_size ] removes and returns the element
of [ arr ] with the largest key . It is to be understood that the
returned heap is one element smaller .
of [arr] with the largest key. It is to be understood that the
returned heap is one element smaller. *)
let heap_extract_max (arr : 'a array) (heap_size : int) =
let () = if heap_size < 1 then failwith "heap underflow" else () in
let max = arr. (0) in
Array.set arr 0 (Array.get arr (heap_size - 1));
max_heapify arr ~heap_size:(heap_size - 1) 0;
max, (heap_size - 1)
let heap_increase_key (arr : 'a array) (i : int) (key : int) =
let () =
if key < arr. (i) then
failwith "new key is smaller than current key"
else () in
let i = ref i in
Array.set arr !i key;
while !i > 0 && arr. (parent !i) < arr. (!i ) do
swap arr !i (parent !i);
i := parent !i
done
[ max_heap_insert arr heap_size key ] inserts [ key ] into [ arr ] . It
is understood the size of the resulting heap is one greater than
the argument [ heap_size ] .
is understood the size of the resulting heap is one greater than
the argument [heap_size]. *)
let max_heap_insert (arr : 'a array) (heap_size : int) (key : int) =
let heap_size = heap_size + 1 in
Array.set arr (heap_size - 1) min_int;
heap_increase_key arr heap_size key;
heap_size
end
let () =
let arr = [| 5; 13; 2; 25; 7; 17; 20; 8; 4 |] in
Heap.heap_sort arr;
Array.iter (fun x -> Printf.printf "%d, " x) arr;
Printf.printf "\n";
flush stdout
|
9e7d68015af565967927877f67e4a2fdeb7f099815cf82a74db27746c88d7cd6 | alei76/java-blog-hxzon | monads_101.clj | ;; monads_101.clj
;;
Copyright ( c ) , 2009 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php)
;; By using this software in any fashion, you are agreeing to be bound
;; by the terms of this license. You must not remove this notice,
;; or any other, from this software.
(use 'clojure.contrib.monads)
(import 'java.net.URLDecoder)
;; ==========
(with-monad sequence-m
; a monadic function under the sequence-m monad
(defn f2 [n]
(list (inc n)))
(assert (= [2 6 8]
(mapcat f2 [1 5 7])
(m-bind [1 5 7] f2)))
(assert (= (m-result 6)
[6]))
(defn m-comp [f1 f2 f3]
(fn [x]
; the monad name is not needed if the 'domonad' is enclosed in a 'with-monad'
(domonad
[a (f3 x)
b (f2 a)
c (f1 b)]
c)))
(assert (= '([a 1] [a 2] [a 3] [b 1] [b 2] [b 3] [c 1] [c 2] [c 3])
(domonad
[letters ['a 'b 'c]
numbers [1 2 3]]
[letters numbers])
(for
[letters ['a 'b 'c]
numbers [1 2 3]]
[letters numbers])))
)
;; =============
(with-monad state-m
(defn g1 [state-int]
[:g1 (inc state-int)])
(defn g2 [state-int]
[:g2 (inc state-int)])
(defn g3 [state-int]
[:g3 (inc state-int)])
(def gs (domonad
[a g1
b g2
c g3]
[a b c]))
(assert (= '([:g1 :g2 :g3] 8)
(gs 5)))
(def gs1
(domonad
[a g1
x (fetch-state)
b g2]
[a x b]))
(assert (= '([:g1 4 :g2] 5)
(gs1 3)))
(def gs2
(domonad state-m
[a g1
x (set-state 50)
b g2]
[a x b]))
(assert (= '([:g1 4 :g2] 51)
(gs2 3)))
)
(assert (= '([:g1 :g2 :g3] 8)
(gs 5)))
(assert (= '([:g1 4 :g2] 5)
(gs1 3)))
(assert (= '([:g1 4 :g2] 51)
(gs2 3)))
;; =============
(defmonad parser-m
[m-result (fn [x]
(fn [strn]
(list x strn)))
m-bind (fn [parser func]
(fn [strn]
(let [result (parser strn)]
(when (not= nil result)
((func (first result)) (second result)))))) ;; 给func传入的是解析结果
m-zero (fn [strn]
nil)
m-plus (fn [& parsers] ;; 输入是一系列解析器,然后依次用这些解析器解析字符串,直到有成功的解析结果
(fn [strn] ;; m-plus 返回的是一个解析器
(first
(drop-while nil?
(map #(% strn) parsers)))))])
(with-monad parser-m
(defn any-char [strn] ;; 解析器,判断是否为空字符串,非空时取出第一个字符
(if (= "" strn)
nil
(list (first strn) (. strn (substring 1)))))
(defn char-test [pred] ;; 返回一个解析器
(domonad
[c any-char
:when (pred c)]
(str c)))
(defn is-char [c]
(char-test (partial = c)))
; just renaming is-char to be consistent later
(def match-char is-char)
(defn match-string [target-strn]
(if (= "" target-strn)
(m-result "")
(domonad
[c (is-char (first target-strn))
cs (match-string (. target-strn (substring 1)))]
(str c cs))))
;; 解析器组合子,返回一个新的解析器
(defn optional [parser]
(m-plus parser (m-result nil)))
(def match-one m-plus)
(defn match-all [& parsers]
(m-fmap (partial apply str)
(m-seq parsers)))
(def one-or-more)
(defn none-or-more [parser]
(optional (one-or-more parser)))
(defn one-or-more [parser]
(domonad
[a parser
as (none-or-more parser)]
(str a as)))
;; 常用解析器
(defn one-of [target-strn]
(let [str-chars (into #{} target-strn)]
(char-test #(contains? str-chars %))))
(def alpha (one-of "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
(def whitespace (one-of " \t\n\r"))
(def digit (one-of "0123456789"))
(def hexdigit (one-of "0123456789abcdefghABCDEFGH"))
;; 测试
(def is-n (is-char \n))
(assert (= ["n" "bc"]
(is-n "nbc")))
(assert (= nil
(is-n "xbc")))
(def this-string (match-string "this"))
(def is-space (is-char \space))
(def test-string (match-string "test"))
(assert (= ["this" " is a test"] ;; 匹配出 “this”
(this-string "this is a test")))
(def test-phrase ;; 依次解析出“this”,空格,“is a”,空格,“test”
(domonad
[this-var this-string
_ is-space
middle (match-string "is a")
_ is-space
test-var test-string]
(print-str this-var "resembles a" test-var)))
(assert (= ["this resembles a test" ""]
(test-phrase "this is a test")))
" is
(test-phrase "this is not a test")))
)
;; ==============
(with-monad parser-m
(def #^{:private true} method ;; 解析器,用来匹配 http方法
(match-one (match-string "PUT")
(match-string "HEAD")
(match-string "TRACE")
(match-string "OPTIONS")
(match-string "POST")
(match-string "DELETE")
(match-string "GET")))
匹配百分号,和两个十六进制字符
(match-all
(match-char \%)
hexdigit
hexdigit))
(def #^{:private true} path-char
(match-one
alpha
digit
pct-encoded
(one-of "-._~!$&'()*+,;=:@")))
(def #^{:private true} path
(match-one
(match-char \*)
(match-all
(match-char \/)
(none-or-more path-char)
(none-or-more
(match-all
(match-char \/)
(none-or-more path-char))))))
(def #^{:private true} query-char
(match-one
alpha
digit
pct-encoded
(one-of "!$'()*+,;:@/?&=")))
(def #^{:private true} query
(one-or-more query-char))
(def #^{:private true} version
(match-all
(match-string "HTTP/1.")
(match-one
(match-string "0")
(match-string "1"))))
(def #^{:private true} token
(one-or-more
(match-one
alpha
digit
(one-of "~`!#$%^&*-_+=|'."))))
(def #^{:private true} crlf
(match-all
hxzon注意
(match-char \newline)))
(def #^{:private true} spaces
(domonad
[ws (one-or-more
(match-one
(match-char \space)
(match-char \tab)))]
" "))
(def #^{:private true} field-value
(one-or-more
(one-of
(map char (range 32 127)))))
(def #^{:private true} value-continuation
(domonad
[linefeed crlf
ws spaces
value field-value]
(str ws value)))
(def #^{:private true} header-value
(match-all
field-value
(none-or-more value-continuation)))
(def #^{:private true} header
(match-all
token
(match-all (match-char \:) (none-or-more spaces))
(optional header-value)
crlf))
(defn- build-map [map-pairs]
(reduce #(assoc %1
(keyword (. (first %2) toLowerCase))
(second %2))
{}
map-pairs))
(defn- query-map [query-strn]
(let [query-strn (.substring query-strn 1)
queries (seq (.split query-strn "&"))
name-vals (map #(seq (.split % "=")) queries)]
(build-map name-vals)))
(defn- split-header [header-strn]
(let [split-index (.indexOf header-strn ":")]
[(.substring header-strn 0 split-index)
(.trim (.substring header-strn (inc split-index)))]))
(defn- build-header-map [headers-strn]
(when headers-strn
(let [headers (seq (.split headers-strn "\r\n"))]
(build-map
(map split-header headers)))))
(def http-request
(domonad
[method-str method
_ spaces
path-str path
query-str (optional query)
_ spaces
version-str version
_ crlf
header-str (none-or-more header)
_ crlf]
(let [header-map (build-header-map header-str)]
{:method (keyword (. method-str toLowerCase))
:path (. URLDecoder (decode path-str))
:query (when (not= "" query-str)
(query-map query-str))
:version version-str
:headers header-map
:host (get header-map :host)})))
)
; unit tests
(defn parse [parser strn]
(first (parser strn)))
(assert (= "GET"
(parse method "GET")))
(assert (= "PUT"
(parse method "PUT")))
(assert (= "/"
(parse path "/")))
(assert (= "*"
(parse path "*")))
(assert (= "/bogus/path"
(parse path "/bogus/path")))
(assert (= "bogus=value"
(parse query "bogus=value")))
(assert (= "another"
(parse query "another")))
(assert (= "bogus=value&another"
(parse query "bogus=value&another")))
(assert (= "HTTP/1.0"
(parse version "HTTP/1.0")))
(assert (= "HTTP/1.1"
(parse version "HTTP/1.1")))
(assert (= nil
(parse version "HTTP/1.2")))
(assert (= "Host: \r\n"
(parse header "Host: \r\n")))
(assert (= "Host: text\r\n"
(parse header "Host: text\r\n")))
(assert (= "Host: text more text\r\n"
(parse header "Host: text\r\n more text\r\n")))
(assert (= (str "Host: localhost:8000\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12\r\n")
(parse (none-or-more header) "Host: localhost:8000\r
U ; Linux x86_64 ; en - US ; rv:1.8.1.12)\r
Gecko/20080207 Ubuntu/7.10 (gutsy)\r
Firefox/2.0.0.12\r\n")))
(assert (= nil
(parse (none-or-more header) "\r\n")))
(def small-http (str
"GET /bogus?q1=a&q2=b HTTP/1.1\r\n"
"First: one\r\n"
"Only:\r\n"
"Host: l\r\n"
"User-Agent: More\r\n"
" Mozilla\r\n"
"Another: one\r\n"
"\r\n"
))
(assert (= {:version "HTTP/1.1"
:method :get
:query {:query "99"}
:path "/bogus/path"
:headers nil
:host nil}
(parse http-request "GET /bogus/path?query=99 HTTP/1.1\r\n\r\n")))
(assert (= {:version "HTTP/1.1"
:method :get
:query {:query "99"}
:path "/"
:headers nil
:host nil}
(parse http-request "GET /?query=99 HTTP/1.1\r\n\r\n")))
(def test-http (str "GET /bogus/path?query=99 HTTP/1.1\r\n"
"Host: localhost:8000\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12\r\n"
"Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
"Accept-Language: en-us,en;q=0.5\r\n"
"Accept-Encoding: gzip,deflate\r\n"
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
"Keep-Alive: 300\r\n"
"Connection: keep-alive\r\n"
"\r\n"
"this is the payload\r\n"
"\r\n"
))
(assert (= {:method :get
:path "/bogus/path"
:headers {:user-agent "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12"
:keep-alive "300"
:accept-charset "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
:accept "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
:host "localhost:8000"
:accept-encoding "gzip,deflate"
:accept-language "en-us,en;q=0.5"
:connection "keep-alive"}
:query {:query "99"}
:version "HTTP/1.1"
:host "localhost:8000"}
(parse http-request test-http)))
(def more-http (str
"BOGUS / HTTP/1.1\r\n"
"Host: localhost:8085\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.5) Gecko/2008121623 Ubuntu/8.10 (intrepid) Firefox/3.0.5\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: en-us,en;q=0.5\r\n"
"Accept-Encoding: gzip,deflate\r\n"
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
"Keep-Alive: 300\r\n"
"Connection: keep-alive\r\n"
"\r\n"
))
(assert (= nil
(parse http-request more-http)))
| null | https://raw.githubusercontent.com/alei76/java-blog-hxzon/ecde3517edccf632f8fa14da95f2f382387d3b39/1%EF%BC%8C%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/1%EF%BC%8Cclojure/monad/monads_101.clj | clojure | monads_101.clj
Public License 1.0 (-1.0.php)
By using this software in any fashion, you are agreeing to be bound
by the terms of this license. You must not remove this notice,
or any other, from this software.
==========
a monadic function under the sequence-m monad
the monad name is not needed if the 'domonad' is enclosed in a 'with-monad'
=============
=============
给func传入的是解析结果
输入是一系列解析器,然后依次用这些解析器解析字符串,直到有成功的解析结果
m-plus 返回的是一个解析器
解析器,判断是否为空字符串,非空时取出第一个字符
返回一个解析器
just renaming is-char to be consistent later
解析器组合子,返回一个新的解析器
常用解析器
测试
匹配出 “this”
依次解析出“this”,空格,“is a”,空格,“test”
==============
解析器,用来匹配 http方法
unit tests
Linux x86_64 ; en - US ; rv:1.8.1.12)\r |
Copyright ( c ) , 2009 . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
(use 'clojure.contrib.monads)
(import 'java.net.URLDecoder)
(with-monad sequence-m
(defn f2 [n]
(list (inc n)))
(assert (= [2 6 8]
(mapcat f2 [1 5 7])
(m-bind [1 5 7] f2)))
(assert (= (m-result 6)
[6]))
(defn m-comp [f1 f2 f3]
(fn [x]
(domonad
[a (f3 x)
b (f2 a)
c (f1 b)]
c)))
(assert (= '([a 1] [a 2] [a 3] [b 1] [b 2] [b 3] [c 1] [c 2] [c 3])
(domonad
[letters ['a 'b 'c]
numbers [1 2 3]]
[letters numbers])
(for
[letters ['a 'b 'c]
numbers [1 2 3]]
[letters numbers])))
)
(with-monad state-m
(defn g1 [state-int]
[:g1 (inc state-int)])
(defn g2 [state-int]
[:g2 (inc state-int)])
(defn g3 [state-int]
[:g3 (inc state-int)])
(def gs (domonad
[a g1
b g2
c g3]
[a b c]))
(assert (= '([:g1 :g2 :g3] 8)
(gs 5)))
(def gs1
(domonad
[a g1
x (fetch-state)
b g2]
[a x b]))
(assert (= '([:g1 4 :g2] 5)
(gs1 3)))
(def gs2
(domonad state-m
[a g1
x (set-state 50)
b g2]
[a x b]))
(assert (= '([:g1 4 :g2] 51)
(gs2 3)))
)
(assert (= '([:g1 :g2 :g3] 8)
(gs 5)))
(assert (= '([:g1 4 :g2] 5)
(gs1 3)))
(assert (= '([:g1 4 :g2] 51)
(gs2 3)))
(defmonad parser-m
[m-result (fn [x]
(fn [strn]
(list x strn)))
m-bind (fn [parser func]
(fn [strn]
(let [result (parser strn)]
(when (not= nil result)
m-zero (fn [strn]
nil)
(first
(drop-while nil?
(map #(% strn) parsers)))))])
(with-monad parser-m
(if (= "" strn)
nil
(list (first strn) (. strn (substring 1)))))
(domonad
[c any-char
:when (pred c)]
(str c)))
(defn is-char [c]
(char-test (partial = c)))
(def match-char is-char)
(defn match-string [target-strn]
(if (= "" target-strn)
(m-result "")
(domonad
[c (is-char (first target-strn))
cs (match-string (. target-strn (substring 1)))]
(str c cs))))
(defn optional [parser]
(m-plus parser (m-result nil)))
(def match-one m-plus)
(defn match-all [& parsers]
(m-fmap (partial apply str)
(m-seq parsers)))
(def one-or-more)
(defn none-or-more [parser]
(optional (one-or-more parser)))
(defn one-or-more [parser]
(domonad
[a parser
as (none-or-more parser)]
(str a as)))
(defn one-of [target-strn]
(let [str-chars (into #{} target-strn)]
(char-test #(contains? str-chars %))))
(def alpha (one-of "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
(def whitespace (one-of " \t\n\r"))
(def digit (one-of "0123456789"))
(def hexdigit (one-of "0123456789abcdefghABCDEFGH"))
(def is-n (is-char \n))
(assert (= ["n" "bc"]
(is-n "nbc")))
(assert (= nil
(is-n "xbc")))
(def this-string (match-string "this"))
(def is-space (is-char \space))
(def test-string (match-string "test"))
(this-string "this is a test")))
(domonad
[this-var this-string
_ is-space
middle (match-string "is a")
_ is-space
test-var test-string]
(print-str this-var "resembles a" test-var)))
(assert (= ["this resembles a test" ""]
(test-phrase "this is a test")))
" is
(test-phrase "this is not a test")))
)
(with-monad parser-m
(match-one (match-string "PUT")
(match-string "HEAD")
(match-string "TRACE")
(match-string "OPTIONS")
(match-string "POST")
(match-string "DELETE")
(match-string "GET")))
匹配百分号,和两个十六进制字符
(match-all
(match-char \%)
hexdigit
hexdigit))
(def #^{:private true} path-char
(match-one
alpha
digit
pct-encoded
(one-of "-._~!$&'()*+,;=:@")))
(def #^{:private true} path
(match-one
(match-char \*)
(match-all
(match-char \/)
(none-or-more path-char)
(none-or-more
(match-all
(match-char \/)
(none-or-more path-char))))))
(def #^{:private true} query-char
(match-one
alpha
digit
pct-encoded
(one-of "!$'()*+,;:@/?&=")))
(def #^{:private true} query
(one-or-more query-char))
(def #^{:private true} version
(match-all
(match-string "HTTP/1.")
(match-one
(match-string "0")
(match-string "1"))))
(def #^{:private true} token
(one-or-more
(match-one
alpha
digit
(one-of "~`!#$%^&*-_+=|'."))))
(def #^{:private true} crlf
(match-all
hxzon注意
(match-char \newline)))
(def #^{:private true} spaces
(domonad
[ws (one-or-more
(match-one
(match-char \space)
(match-char \tab)))]
" "))
(def #^{:private true} field-value
(one-or-more
(one-of
(map char (range 32 127)))))
(def #^{:private true} value-continuation
(domonad
[linefeed crlf
ws spaces
value field-value]
(str ws value)))
(def #^{:private true} header-value
(match-all
field-value
(none-or-more value-continuation)))
(def #^{:private true} header
(match-all
token
(match-all (match-char \:) (none-or-more spaces))
(optional header-value)
crlf))
(defn- build-map [map-pairs]
(reduce #(assoc %1
(keyword (. (first %2) toLowerCase))
(second %2))
{}
map-pairs))
(defn- query-map [query-strn]
(let [query-strn (.substring query-strn 1)
queries (seq (.split query-strn "&"))
name-vals (map #(seq (.split % "=")) queries)]
(build-map name-vals)))
(defn- split-header [header-strn]
(let [split-index (.indexOf header-strn ":")]
[(.substring header-strn 0 split-index)
(.trim (.substring header-strn (inc split-index)))]))
(defn- build-header-map [headers-strn]
(when headers-strn
(let [headers (seq (.split headers-strn "\r\n"))]
(build-map
(map split-header headers)))))
(def http-request
(domonad
[method-str method
_ spaces
path-str path
query-str (optional query)
_ spaces
version-str version
_ crlf
header-str (none-or-more header)
_ crlf]
(let [header-map (build-header-map header-str)]
{:method (keyword (. method-str toLowerCase))
:path (. URLDecoder (decode path-str))
:query (when (not= "" query-str)
(query-map query-str))
:version version-str
:headers header-map
:host (get header-map :host)})))
)
(defn parse [parser strn]
(first (parser strn)))
(assert (= "GET"
(parse method "GET")))
(assert (= "PUT"
(parse method "PUT")))
(assert (= "/"
(parse path "/")))
(assert (= "*"
(parse path "*")))
(assert (= "/bogus/path"
(parse path "/bogus/path")))
(assert (= "bogus=value"
(parse query "bogus=value")))
(assert (= "another"
(parse query "another")))
(assert (= "bogus=value&another"
(parse query "bogus=value&another")))
(assert (= "HTTP/1.0"
(parse version "HTTP/1.0")))
(assert (= "HTTP/1.1"
(parse version "HTTP/1.1")))
(assert (= nil
(parse version "HTTP/1.2")))
(assert (= "Host: \r\n"
(parse header "Host: \r\n")))
(assert (= "Host: text\r\n"
(parse header "Host: text\r\n")))
(assert (= "Host: text more text\r\n"
(parse header "Host: text\r\n more text\r\n")))
(assert (= (str "Host: localhost:8000\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12\r\n")
(parse (none-or-more header) "Host: localhost:8000\r
Gecko/20080207 Ubuntu/7.10 (gutsy)\r
Firefox/2.0.0.12\r\n")))
(assert (= nil
(parse (none-or-more header) "\r\n")))
(def small-http (str
"GET /bogus?q1=a&q2=b HTTP/1.1\r\n"
"First: one\r\n"
"Only:\r\n"
"Host: l\r\n"
"User-Agent: More\r\n"
" Mozilla\r\n"
"Another: one\r\n"
"\r\n"
))
(assert (= {:version "HTTP/1.1"
:method :get
:query {:query "99"}
:path "/bogus/path"
:headers nil
:host nil}
(parse http-request "GET /bogus/path?query=99 HTTP/1.1\r\n\r\n")))
(assert (= {:version "HTTP/1.1"
:method :get
:query {:query "99"}
:path "/"
:headers nil
:host nil}
(parse http-request "GET /?query=99 HTTP/1.1\r\n\r\n")))
(def test-http (str "GET /bogus/path?query=99 HTTP/1.1\r\n"
"Host: localhost:8000\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12\r\n"
"Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
"Accept-Language: en-us,en;q=0.5\r\n"
"Accept-Encoding: gzip,deflate\r\n"
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
"Keep-Alive: 300\r\n"
"Connection: keep-alive\r\n"
"\r\n"
"this is the payload\r\n"
"\r\n"
))
(assert (= {:method :get
:path "/bogus/path"
:headers {:user-agent "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.12) Gecko/20080207 Ubuntu/7.10 (gutsy) Firefox/2.0.0.12"
:keep-alive "300"
:accept-charset "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
:accept "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
:host "localhost:8000"
:accept-encoding "gzip,deflate"
:accept-language "en-us,en;q=0.5"
:connection "keep-alive"}
:query {:query "99"}
:version "HTTP/1.1"
:host "localhost:8000"}
(parse http-request test-http)))
(def more-http (str
"BOGUS / HTTP/1.1\r\n"
"Host: localhost:8085\r\n"
"User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.5) Gecko/2008121623 Ubuntu/8.10 (intrepid) Firefox/3.0.5\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: en-us,en;q=0.5\r\n"
"Accept-Encoding: gzip,deflate\r\n"
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
"Keep-Alive: 300\r\n"
"Connection: keep-alive\r\n"
"\r\n"
))
(assert (= nil
(parse http-request more-http)))
|
0d76e9acd429588cfee27c8fd9b5315498231c32febb04974ba83465676066bb | JoaoVasques/kafka-async | core_test.clj | (ns kafka-async.core-test
(:require [clojure.test :refer :all]
[kafka-async.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/JoaoVasques/kafka-async/fa548418c3b0e486d0d2c3586367ed8dd3935a4d/test/kafka_async/core_test.clj | clojure | (ns kafka-async.core-test
(:require [clojure.test :refer :all]
[kafka-async.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
|
62fc08fef1e16e8ef54a51fb14a8d6ef979fe4f1cb31768ed57187a5cfc0972b | owlbarn/owl_ode | symplectic_s.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 <>
*)
module Types = Owl_ode_base.Types
type mat = Owl_dense_matrix_s.mat
include Owl_ode_base.Symplectic_generic.Make (Owl_algodiff_primal_ops.S)
module Symplectic_Euler = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = symplectic_euler_s
let solve = prepare step
end
module PseudoLeapfrog = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = pseudoleapfrog_s
let solve = prepare step
end
module Leapfrog = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = leapfrog_s
let solve = prepare step
end
module Ruth3 = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = ruth3_s
let solve = prepare step
end
module Ruth4 = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = ruth4_s
let solve = prepare step
end
| null | https://raw.githubusercontent.com/owlbarn/owl_ode/5d934fbff87eea9f060d6c949bf78467024d8791/src/ode/symplectic/symplectic_s.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 <>
*)
module Types = Owl_ode_base.Types
type mat = Owl_dense_matrix_s.mat
include Owl_ode_base.Symplectic_generic.Make (Owl_algodiff_primal_ops.S)
module Symplectic_Euler = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = symplectic_euler_s
let solve = prepare step
end
module PseudoLeapfrog = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = pseudoleapfrog_s
let solve = prepare step
end
module Leapfrog = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = leapfrog_s
let solve = prepare step
end
module Ruth3 = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = ruth3_s
let solve = prepare step
end
module Ruth4 = struct
type state = mat * mat
type f = mat * mat -> float -> mat
type step_output = (mat * mat) * float
type solve_output = mat * mat * mat
let step = ruth4_s
let solve = prepare step
end
|
|
fd858da6b34a5f5720623de284fee2c6c7d8e0b844c2073fb09b258ebd6a90cf | ostera/serde.ml | de_record.ml | open Ppxlib
module Ast = Ast_builder.Default
open De_base
(** implementation *)
let gen_visit_map ~ctxt ~type_name:_ ?constructor ~field_visitor kvs parts =
let loc = loc ~ctxt in
let create_value =
let value = Ast.pexp_record ~loc kvs None in
let value =
match constructor with
| None -> value
| Some c ->
Ast.pexp_construct ~loc (longident ~ctxt c)
(Some (Ast.pexp_record ~loc kvs None))
in
[%expr Ok [%e value]]
in
let extract_fields =
List.fold_left
(fun body (name, pat, _ctyp, exp, _field_variant) ->
let op = var ~ctxt "let*" in
let exp =
[%expr
match ![%e exp] with
| Some value -> Ok value
| None -> Serde.De.Error.missing_field [%e name |> Ast.estring ~loc]]
in
let let_ = Ast.binding_op ~op ~loc ~pat ~exp in
Ast.letop ~let_ ~ands:[] ~body |> Ast.pexp_letop ~loc)
create_value (List.rev parts)
in
let fill_individual_field =
let cases =
List.map
(fun (_name, _pat, ctyp, var, field_variant) ->
let deser_value =
if is_primitive_type ctyp then
[%expr
[%e de_fun ~ctxt ctyp]
(module De)
[%e visitor_mod ~ctxt ctyp |> Option.get]]
else [%expr [%e de_fun ~ctxt ctyp] (module De)]
in
let assign_field =
[%expr
let* value =
Serde.De.Map_access.next_value map_access
~deser_value:(fun () -> [%e deser_value])
in
Ok ([%e var] := value)]
in
let constructor =
Ast.ppat_construct ~loc (longident ~ctxt field_variant) None
in
Ast.case ~lhs:[%pat? [%p constructor]] ~guard:None ~rhs:assign_field)
parts
in
let match_ = Ast.pexp_match ~loc [%expr f] cases in
[%expr
let* () = [%e match_] in
fill ()]
in
let fill_fields =
[%expr
let deser_key () =
Serde.De.deserialize_identifier (module De) [%e field_visitor]
in
let rec fill () =
let* key = Serde.De.Map_access.next_key map_access ~deser_key in
match key with None -> Ok () | Some f -> [%e fill_individual_field]
in
let* () = fill () in
[%e extract_fields]]
in
let initialize_fields =
List.fold_left
(fun body (_name, pat, _type, _var, _field_variant) ->
let expr = [%expr ref None] in
let vb = Ast.value_binding ~loc ~pat ~expr in
Ast.pexp_let ~loc Nonrecursive [ vb ] body)
fill_fields (List.rev parts)
in
[%stri
let visit_map :
type de_state.
value Serde.De.Visitor.t ->
de_state Serde.De.Deserializer.t ->
(value, 'error) Serde.De.Map_access.t ->
(value, 'error Serde.De.Error.de_error) result =
fun (module Self) (module De) map_access -> [%e initialize_fields]]
let gen_visit_seq ~ctxt ~type_name ?constructor kvs parts =
let loc = loc ~ctxt in
let create_value =
let value = Ast.pexp_record ~loc kvs None in
let value =
match constructor with
| None -> value
| Some c ->
Ast.pexp_construct ~loc (longident ~ctxt c)
(Some (Ast.pexp_record ~loc kvs None))
in
[%expr Ok [%e value]]
in
let exprs =
List.map
(fun (_field_name, pat, ctyp, _expr, _field_variant) ->
let err_msg =
Printf.sprintf "%s needs %d argument" type_name.txt
(List.length parts)
|> Ast.estring ~loc
in
let deser_element =
if is_primitive_type ctyp then
[%expr
[%e de_fun ~ctxt ctyp]
(module De)
[%e visitor_mod ~ctxt ctyp |> Option.get]]
else [%expr [%e de_fun ~ctxt ctyp] (module De)]
in
let body =
[%expr
let deser_element () = [%e deser_element] in
let* r =
Serde.De.Sequence_access.next_element seq_access ~deser_element
in
match r with
| None -> Serde.De.Error.message (Printf.sprintf [%e err_msg])
| Some f0 -> Ok f0]
in
(pat, body))
parts
in
let visit_seq =
List.fold_left
(fun body (pat, exp) ->
let op = var ~ctxt "let*" in
let let_ = Ast.binding_op ~op ~loc ~pat ~exp in
Ast.letop ~let_ ~ands:[] ~body |> Ast.pexp_letop ~loc)
create_value (List.rev exprs)
in
[%stri
let visit_seq :
type de_state.
(module Serde.De.Visitor.Intf with type value = value) ->
(module Serde.De.Deserializer with type state = de_state) ->
(value, 'error) Serde.De.Sequence_access.t ->
(value, 'error Serde.De.Error.de_error) result =
fun (module Self) (module De) seq_access -> [%e visit_seq]]
let gen_visitor ~ctxt ~type_name ~field_visitor
(label_declarations : (label_declaration * string) list) =
let loc = loc ~ctxt in
let visitor_module_name = "Visitor_for_" ^ type_name.txt in
let make_vars_and_pats i (ldecl, field_variant) =
let record_field_name = ldecl.pld_name.txt in
let f_idx = "f_" ^ Int.to_string i in
let pat = f_idx |> var ~ctxt |> Ast.ppat_var ~loc in
let var = f_idx |> Longident.parse |> var ~ctxt |> Ast.pexp_ident ~loc in
let kv = (longident ~ctxt record_field_name, var) in
(kv, (record_field_name, pat, ldecl.pld_type, var, field_variant))
in
let labels = label_declarations |> List.mapi make_vars_and_pats in
let kvs, parts = labels |> List.split in
let visitor_module =
[%str
include Serde.De.Visitor.Unimplemented
type value = [%t Ast.ptyp_constr ~loc (longident ~ctxt type_name.txt) []]
type tag = fields]
@ [
gen_visit_seq ~ctxt ~type_name kvs parts;
gen_visit_map ~ctxt ~type_name ~field_visitor kvs parts;
]
in
let visitor_module =
Ast.module_binding ~loc
~name:(var ~ctxt (Some visitor_module_name))
~expr:
(Ast.pmod_apply ~loc
(Ast.pmod_ident ~loc (longident ~ctxt "Serde.De.Visitor.Make"))
(Ast.pmod_structure ~loc visitor_module))
|> Ast.pstr_module ~loc
in
let ident =
let mod_name = Longident.parse visitor_module_name |> var ~ctxt in
Ast.pexp_pack ~loc (Ast.pmod_ident ~loc mod_name)
in
(ident, visitor_module)
let gen_field_visitor ~ctxt ~type_name ?fields_type constructors =
let loc = loc ~ctxt in
let field_visitor_module_name = "Field_visitor_for_" ^ type_name.txt in
let include_unimplemented = [%stri include Serde.De.Visitor.Unimplemented] in
let type_value =
match fields_type with
| Some t -> [%stri type value = [%t t]]
| None -> [%stri type value = fields]
in
let type_tag = [%stri type tag = unit] in
let visit_int =
let cases =
List.mapi
(fun idx (_field, constructor) ->
let idx = Ast.pint ~loc idx in
let constructor =
Ast.pexp_construct ~loc (longident ~ctxt constructor) None
in
Ast.case
~lhs:[%pat? [%p idx]]
~guard:None
~rhs:[%expr Ok [%e constructor]])
constructors
in
let cases =
cases
@ [
Ast.case
~lhs:[%pat? _]
~guard:None
~rhs:[%expr Serde.De.Error.invalid_variant_index ~idx];
]
in
let match_ = Ast.pexp_match ~loc [%expr idx] cases in
[%stri let visit_int idx = [%e match_]]
in
let visit_string =
let cases =
List.map
(fun (field, constructor) ->
let idx = Ast.pstring ~loc field.pld_name.txt in
let constructor =
Ast.pexp_construct ~loc (longident ~ctxt constructor) None
in
Ast.case
~lhs:[%pat? [%p idx]]
~guard:None
~rhs:[%expr Ok [%e constructor]])
constructors
in
let cases =
cases
@ [
Ast.case
~lhs:[%pat? _]
~guard:None
~rhs:[%expr Serde.De.Error.unknown_variant str];
]
in
let match_ = Ast.pexp_match ~loc [%expr str] cases in
[%stri let visit_string str = [%e match_]]
in
let visitor_module =
[ include_unimplemented; type_value; type_tag; visit_int; visit_string ]
in
let visitor_module =
Ast.module_binding ~loc
~name:(var ~ctxt (Some field_visitor_module_name))
~expr:
(Ast.pmod_apply ~loc
(Ast.pmod_ident ~loc (longident ~ctxt "Serde.De.Visitor.Make"))
(Ast.pmod_structure ~loc visitor_module))
|> Ast.pstr_module ~loc
in
let ident =
let mod_name = Longident.parse field_visitor_module_name |> var ~ctxt in
Ast.pexp_pack ~loc (Ast.pmod_ident ~loc mod_name)
in
(ident, visitor_module)
* Generate deserializer for record types . This generates :
1 module for the deserializer itself
1 visitor module for the fields
1 visitor module for the contents
1 module for the deserializer itself
1 visitor module for the fields
1 visitor module for the contents
*)
let gen_deserialize_record_impl ~ctxt type_name
(label_declarations : label_declaration list) =
let loc = loc ~ctxt in
let field_names = List.map (fun l -> l.pld_name.txt) label_declarations in
let field_constructors =
List.map (fun l -> (l, "Field_" ^ l.pld_name.txt)) label_declarations
in
let fields =
let kind =
Ptype_variant
(List.map
(fun (_loc, c) ->
let name = var ~ctxt c in
Ast.constructor_declaration ~loc ~name ~res:None
~args:(Pcstr_tuple []))
field_constructors)
in
[
Ast.type_declaration ~loc ~name:(var ~ctxt "fields") ~params:[] ~cstrs:[]
~kind ~manifest:None ~private_:Public;
]
|> Ast.pstr_type ~loc Nonrecursive
in
let constants =
[
[%stri let name = [%e type_name.txt |> Ast.estring ~loc]];
[%stri
let fields =
[%e field_names |> List.map (Ast.estring ~loc) |> Ast.elist ~loc]];
fields;
]
in
let field_visitor_for_t_name, field_visitor_for_t =
gen_field_visitor ~ctxt ~type_name field_constructors
in
let visitor_for_t_name, visitor_for_t =
gen_visitor ~ctxt ~type_name ~field_visitor:field_visitor_for_t_name
field_constructors
in
let str_items = constants @ [ field_visitor_for_t; visitor_for_t ] in
let deserialize_body =
[%expr
Serde.De.deserialize_record ~name ~fields
(module De)
[%e visitor_for_t_name] [%e field_visitor_for_t_name]]
in
(str_items, deserialize_body)
| null | https://raw.githubusercontent.com/ostera/serde.ml/88604884cf3e6a928916f33c4bca1444bc2e12a2/serde_derive/de_record.ml | ocaml | * implementation | open Ppxlib
module Ast = Ast_builder.Default
open De_base
let gen_visit_map ~ctxt ~type_name:_ ?constructor ~field_visitor kvs parts =
let loc = loc ~ctxt in
let create_value =
let value = Ast.pexp_record ~loc kvs None in
let value =
match constructor with
| None -> value
| Some c ->
Ast.pexp_construct ~loc (longident ~ctxt c)
(Some (Ast.pexp_record ~loc kvs None))
in
[%expr Ok [%e value]]
in
let extract_fields =
List.fold_left
(fun body (name, pat, _ctyp, exp, _field_variant) ->
let op = var ~ctxt "let*" in
let exp =
[%expr
match ![%e exp] with
| Some value -> Ok value
| None -> Serde.De.Error.missing_field [%e name |> Ast.estring ~loc]]
in
let let_ = Ast.binding_op ~op ~loc ~pat ~exp in
Ast.letop ~let_ ~ands:[] ~body |> Ast.pexp_letop ~loc)
create_value (List.rev parts)
in
let fill_individual_field =
let cases =
List.map
(fun (_name, _pat, ctyp, var, field_variant) ->
let deser_value =
if is_primitive_type ctyp then
[%expr
[%e de_fun ~ctxt ctyp]
(module De)
[%e visitor_mod ~ctxt ctyp |> Option.get]]
else [%expr [%e de_fun ~ctxt ctyp] (module De)]
in
let assign_field =
[%expr
let* value =
Serde.De.Map_access.next_value map_access
~deser_value:(fun () -> [%e deser_value])
in
Ok ([%e var] := value)]
in
let constructor =
Ast.ppat_construct ~loc (longident ~ctxt field_variant) None
in
Ast.case ~lhs:[%pat? [%p constructor]] ~guard:None ~rhs:assign_field)
parts
in
let match_ = Ast.pexp_match ~loc [%expr f] cases in
[%expr
let* () = [%e match_] in
fill ()]
in
let fill_fields =
[%expr
let deser_key () =
Serde.De.deserialize_identifier (module De) [%e field_visitor]
in
let rec fill () =
let* key = Serde.De.Map_access.next_key map_access ~deser_key in
match key with None -> Ok () | Some f -> [%e fill_individual_field]
in
let* () = fill () in
[%e extract_fields]]
in
let initialize_fields =
List.fold_left
(fun body (_name, pat, _type, _var, _field_variant) ->
let expr = [%expr ref None] in
let vb = Ast.value_binding ~loc ~pat ~expr in
Ast.pexp_let ~loc Nonrecursive [ vb ] body)
fill_fields (List.rev parts)
in
[%stri
let visit_map :
type de_state.
value Serde.De.Visitor.t ->
de_state Serde.De.Deserializer.t ->
(value, 'error) Serde.De.Map_access.t ->
(value, 'error Serde.De.Error.de_error) result =
fun (module Self) (module De) map_access -> [%e initialize_fields]]
let gen_visit_seq ~ctxt ~type_name ?constructor kvs parts =
let loc = loc ~ctxt in
let create_value =
let value = Ast.pexp_record ~loc kvs None in
let value =
match constructor with
| None -> value
| Some c ->
Ast.pexp_construct ~loc (longident ~ctxt c)
(Some (Ast.pexp_record ~loc kvs None))
in
[%expr Ok [%e value]]
in
let exprs =
List.map
(fun (_field_name, pat, ctyp, _expr, _field_variant) ->
let err_msg =
Printf.sprintf "%s needs %d argument" type_name.txt
(List.length parts)
|> Ast.estring ~loc
in
let deser_element =
if is_primitive_type ctyp then
[%expr
[%e de_fun ~ctxt ctyp]
(module De)
[%e visitor_mod ~ctxt ctyp |> Option.get]]
else [%expr [%e de_fun ~ctxt ctyp] (module De)]
in
let body =
[%expr
let deser_element () = [%e deser_element] in
let* r =
Serde.De.Sequence_access.next_element seq_access ~deser_element
in
match r with
| None -> Serde.De.Error.message (Printf.sprintf [%e err_msg])
| Some f0 -> Ok f0]
in
(pat, body))
parts
in
let visit_seq =
List.fold_left
(fun body (pat, exp) ->
let op = var ~ctxt "let*" in
let let_ = Ast.binding_op ~op ~loc ~pat ~exp in
Ast.letop ~let_ ~ands:[] ~body |> Ast.pexp_letop ~loc)
create_value (List.rev exprs)
in
[%stri
let visit_seq :
type de_state.
(module Serde.De.Visitor.Intf with type value = value) ->
(module Serde.De.Deserializer with type state = de_state) ->
(value, 'error) Serde.De.Sequence_access.t ->
(value, 'error Serde.De.Error.de_error) result =
fun (module Self) (module De) seq_access -> [%e visit_seq]]
let gen_visitor ~ctxt ~type_name ~field_visitor
(label_declarations : (label_declaration * string) list) =
let loc = loc ~ctxt in
let visitor_module_name = "Visitor_for_" ^ type_name.txt in
let make_vars_and_pats i (ldecl, field_variant) =
let record_field_name = ldecl.pld_name.txt in
let f_idx = "f_" ^ Int.to_string i in
let pat = f_idx |> var ~ctxt |> Ast.ppat_var ~loc in
let var = f_idx |> Longident.parse |> var ~ctxt |> Ast.pexp_ident ~loc in
let kv = (longident ~ctxt record_field_name, var) in
(kv, (record_field_name, pat, ldecl.pld_type, var, field_variant))
in
let labels = label_declarations |> List.mapi make_vars_and_pats in
let kvs, parts = labels |> List.split in
let visitor_module =
[%str
include Serde.De.Visitor.Unimplemented
type value = [%t Ast.ptyp_constr ~loc (longident ~ctxt type_name.txt) []]
type tag = fields]
@ [
gen_visit_seq ~ctxt ~type_name kvs parts;
gen_visit_map ~ctxt ~type_name ~field_visitor kvs parts;
]
in
let visitor_module =
Ast.module_binding ~loc
~name:(var ~ctxt (Some visitor_module_name))
~expr:
(Ast.pmod_apply ~loc
(Ast.pmod_ident ~loc (longident ~ctxt "Serde.De.Visitor.Make"))
(Ast.pmod_structure ~loc visitor_module))
|> Ast.pstr_module ~loc
in
let ident =
let mod_name = Longident.parse visitor_module_name |> var ~ctxt in
Ast.pexp_pack ~loc (Ast.pmod_ident ~loc mod_name)
in
(ident, visitor_module)
let gen_field_visitor ~ctxt ~type_name ?fields_type constructors =
let loc = loc ~ctxt in
let field_visitor_module_name = "Field_visitor_for_" ^ type_name.txt in
let include_unimplemented = [%stri include Serde.De.Visitor.Unimplemented] in
let type_value =
match fields_type with
| Some t -> [%stri type value = [%t t]]
| None -> [%stri type value = fields]
in
let type_tag = [%stri type tag = unit] in
let visit_int =
let cases =
List.mapi
(fun idx (_field, constructor) ->
let idx = Ast.pint ~loc idx in
let constructor =
Ast.pexp_construct ~loc (longident ~ctxt constructor) None
in
Ast.case
~lhs:[%pat? [%p idx]]
~guard:None
~rhs:[%expr Ok [%e constructor]])
constructors
in
let cases =
cases
@ [
Ast.case
~lhs:[%pat? _]
~guard:None
~rhs:[%expr Serde.De.Error.invalid_variant_index ~idx];
]
in
let match_ = Ast.pexp_match ~loc [%expr idx] cases in
[%stri let visit_int idx = [%e match_]]
in
let visit_string =
let cases =
List.map
(fun (field, constructor) ->
let idx = Ast.pstring ~loc field.pld_name.txt in
let constructor =
Ast.pexp_construct ~loc (longident ~ctxt constructor) None
in
Ast.case
~lhs:[%pat? [%p idx]]
~guard:None
~rhs:[%expr Ok [%e constructor]])
constructors
in
let cases =
cases
@ [
Ast.case
~lhs:[%pat? _]
~guard:None
~rhs:[%expr Serde.De.Error.unknown_variant str];
]
in
let match_ = Ast.pexp_match ~loc [%expr str] cases in
[%stri let visit_string str = [%e match_]]
in
let visitor_module =
[ include_unimplemented; type_value; type_tag; visit_int; visit_string ]
in
let visitor_module =
Ast.module_binding ~loc
~name:(var ~ctxt (Some field_visitor_module_name))
~expr:
(Ast.pmod_apply ~loc
(Ast.pmod_ident ~loc (longident ~ctxt "Serde.De.Visitor.Make"))
(Ast.pmod_structure ~loc visitor_module))
|> Ast.pstr_module ~loc
in
let ident =
let mod_name = Longident.parse field_visitor_module_name |> var ~ctxt in
Ast.pexp_pack ~loc (Ast.pmod_ident ~loc mod_name)
in
(ident, visitor_module)
* Generate deserializer for record types . This generates :
1 module for the deserializer itself
1 visitor module for the fields
1 visitor module for the contents
1 module for the deserializer itself
1 visitor module for the fields
1 visitor module for the contents
*)
let gen_deserialize_record_impl ~ctxt type_name
(label_declarations : label_declaration list) =
let loc = loc ~ctxt in
let field_names = List.map (fun l -> l.pld_name.txt) label_declarations in
let field_constructors =
List.map (fun l -> (l, "Field_" ^ l.pld_name.txt)) label_declarations
in
let fields =
let kind =
Ptype_variant
(List.map
(fun (_loc, c) ->
let name = var ~ctxt c in
Ast.constructor_declaration ~loc ~name ~res:None
~args:(Pcstr_tuple []))
field_constructors)
in
[
Ast.type_declaration ~loc ~name:(var ~ctxt "fields") ~params:[] ~cstrs:[]
~kind ~manifest:None ~private_:Public;
]
|> Ast.pstr_type ~loc Nonrecursive
in
let constants =
[
[%stri let name = [%e type_name.txt |> Ast.estring ~loc]];
[%stri
let fields =
[%e field_names |> List.map (Ast.estring ~loc) |> Ast.elist ~loc]];
fields;
]
in
let field_visitor_for_t_name, field_visitor_for_t =
gen_field_visitor ~ctxt ~type_name field_constructors
in
let visitor_for_t_name, visitor_for_t =
gen_visitor ~ctxt ~type_name ~field_visitor:field_visitor_for_t_name
field_constructors
in
let str_items = constants @ [ field_visitor_for_t; visitor_for_t ] in
let deserialize_body =
[%expr
Serde.De.deserialize_record ~name ~fields
(module De)
[%e visitor_for_t_name] [%e field_visitor_for_t_name]]
in
(str_items, deserialize_body)
|
536c237ff27a119f4c1a9276a2015d9afc535fa92ba3b8faced1826e411336ac | erikd/haskell-big-integer-experiment | Type.hs |
# LANGUAGE CPP , MagicHash , ForeignFunctionInterface ,
NoImplicitPrelude , BangPatterns , UnboxedTuples ,
UnliftedFFITypes #
NoImplicitPrelude, BangPatterns, UnboxedTuples,
UnliftedFFITypes #-}
-- Commentary of Integer library is located on the wiki:
--
--
-- It gives an in-depth description of implementation details and
-- decisions.
-----------------------------------------------------------------------------
-- |
-- Module : Simple.GHC.Integer.Type
Copyright : ( c ) 2007 - 2012
-- License : BSD3
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC Extensions )
--
-- An simple definition of the 'Integer' type.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module Simple.GHC.Integer.Type where
import GHC.Prim
import GHC.Classes
import GHC.Types
import GHC.Tuple ()
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
#if !defined(__HADDOCK__)
data Integer = Positive !Positive | Negative !Positive | Naught
-------------------------------------------------------------------
-- The hard work is done on positive numbers
Least significant bit is first
Positive 's have the property that they contain at least one Bit ,
and their last Bit is One .
type Positive = Digits
type Positives = List Positive
data Digits = Some !Digit !Digits
| None
type Digit = Word#
-- XXX Could move [] above us
data List a = Nil | Cons a (List a)
mkInteger :: Bool -- non-negative?
absolute value in 31 bit chunks , least significant first
ideally these would be Words rather than Ints , but
-- we don't have Word available at the moment.
-> Integer
mkInteger nonNegative is = let abs = f is
in if nonNegative then abs else negateInteger abs
where f [] = Naught
f (I# i : is') = smallInteger i `orInteger` shiftLInteger (f is') 31#
errorInteger :: Integer
errorInteger = Positive errorPositive
errorPositive :: Positive
errorPositive = Some 47## None -- Random number
# NOINLINE smallInteger #
smallInteger :: Int# -> Integer
smallInteger i = if isTrue# (i >=# 0#) then wordToInteger (int2Word# i)
else -- XXX is this right for -minBound?
negateInteger (wordToInteger (int2Word# (negateInt# i)))
# NOINLINE wordToInteger #
wordToInteger :: Word# -> Integer
wordToInteger w = if isTrue# (w `eqWord#` 0##)
then Naught
else Positive (Some w None)
# NOINLINE integerToWord #
integerToWord :: Integer -> Word#
integerToWord (Positive (Some w _)) = w
integerToWord (Negative (Some w _)) = 0## `minusWord#` w
-- Must be Naught by the invariant:
integerToWord _ = 0##
# NOINLINE integerToInt #
integerToInt :: Integer -> Int#
integerToInt i = word2Int# (integerToWord i)
#if WORD_SIZE_IN_BITS == 64
-- Nothing
#elif WORD_SIZE_IN_BITS == 32
# NOINLINE integerToWord64 #
integerToWord64 :: Integer -> Word64#
integerToWord64 i = int64ToWord64# (integerToInt64 i)
# NOINLINE word64ToInteger #
word64ToInteger:: Word64# -> Integer
word64ToInteger w = if isTrue# (w `eqWord64#` wordToWord64# 0##)
then Naught
else Positive (word64ToPositive w)
# NOINLINE integerToInt64 #
integerToInt64 :: Integer -> Int64#
integerToInt64 Naught = intToInt64# 0#
integerToInt64 (Positive p) = word64ToInt64# (positiveToWord64 p)
integerToInt64 (Negative p)
= negateInt64# (word64ToInt64# (positiveToWord64 p))
# NOINLINE int64ToInteger #
int64ToInteger :: Int64# -> Integer
int64ToInteger i
= if isTrue# (i `eqInt64#` intToInt64# 0#)
then Naught
else if isTrue# (i `gtInt64#` intToInt64# 0#)
then Positive (word64ToPositive (int64ToWord64# i))
else Negative (word64ToPositive (int64ToWord64# (negateInt64# i)))
#else
#error WORD_SIZE_IN_BITS not supported
#endif
oneInteger :: Integer
oneInteger = Positive onePositive
negativeOneInteger :: Integer
negativeOneInteger = Negative onePositive
twoToTheThirtytwoInteger :: Integer
twoToTheThirtytwoInteger = Positive twoToTheThirtytwoPositive
# NOINLINE encodeDoubleInteger #
encodeDoubleInteger :: Integer -> Int# -> Double#
encodeDoubleInteger (Positive ds0) e0 = f 0.0## ds0 e0
where f !acc None (!_) = acc
f !acc (Some d ds) !e = f (acc +## encodeDouble# d e)
ds
-- XXX We assume that this adding to e
-- isn't going to overflow
(e +# WORD_SIZE_IN_BITS#)
encodeDoubleInteger (Negative ds) e
= negateDouble# (encodeDoubleInteger (Positive ds) e)
encodeDoubleInteger Naught _ = 0.0##
foreign import ccall unsafe "__word_encodeDouble"
encodeDouble# :: Word# -> Int# -> Double#
# NOINLINE encodeFloatInteger #
encodeFloatInteger :: Integer -> Int# -> Float#
encodeFloatInteger (Positive ds0) e0 = f 0.0# ds0 e0
where f !acc None (!_) = acc
f !acc (Some d ds) !e = f (acc `plusFloat#` encodeFloat# d e)
ds
-- XXX We assume that this adding to e
-- isn't going to overflow
(e +# WORD_SIZE_IN_BITS#)
encodeFloatInteger (Negative ds) e
= negateFloat# (encodeFloatInteger (Positive ds) e)
encodeFloatInteger Naught _ = 0.0#
foreign import ccall unsafe "__word_encodeFloat"
encodeFloat# :: Word# -> Int# -> Float#
# NOINLINE decodeFloatInteger #
decodeFloatInteger :: Float# -> (# Integer, Int# #)
decodeFloatInteger f = case decodeFloat_Int# f of
(# mant, exp #) -> (# smallInteger mant, exp #)
-- XXX This could be optimised better, by either (word-size dependent)
-- using single 64bit value for the mantissa, or doing the multiplication
-- by just building the Digits directly
# NOINLINE decodeDoubleInteger #
decodeDoubleInteger :: Double# -> (# Integer, Int# #)
decodeDoubleInteger d
= case decodeDouble_2Int# d of
(# mantSign, mantHigh, mantLow, exp #) ->
(# (smallInteger mantSign) `timesInteger`
( (wordToInteger mantHigh `timesInteger` twoToTheThirtytwoInteger)
`plusInteger` wordToInteger mantLow),
exp #)
# NOINLINE doubleFromInteger #
doubleFromInteger :: Integer -> Double#
doubleFromInteger Naught = 0.0##
doubleFromInteger (Positive p) = doubleFromPositive p
doubleFromInteger (Negative p) = negateDouble# (doubleFromPositive p)
# NOINLINE floatFromInteger #
floatFromInteger :: Integer -> Float#
floatFromInteger Naught = 0.0#
floatFromInteger (Positive p) = floatFromPositive p
floatFromInteger (Negative p) = negateFloat# (floatFromPositive p)
{-# NOINLINE andInteger #-}
andInteger :: Integer -> Integer -> Integer
Naught `andInteger` (!_) = Naught
(!_) `andInteger` Naught = Naught
Positive x `andInteger` Positive y = digitsToInteger (x `andDigits` y)
To calculate x & -y we need to calculate
x & twosComplement y
The ( imaginary ) sign bits are 0 and 1 , so & ing them give 0 , i.e. positive .
Note that
twosComplement y
has infinitely many 1s , but x has a finite number of digits , so andDigits
will return a finite result .
To calculate x & -y we need to calculate
x & twosComplement y
The (imaginary) sign bits are 0 and 1, so &ing them give 0, i.e. positive.
Note that
twosComplement y
has infinitely many 1s, but x has a finite number of digits, so andDigits
will return a finite result.
-}
Positive x `andInteger` Negative y = let y' = twosComplementPositive y
z = y' `andDigitsOnes` x
in digitsToInteger z
Negative x `andInteger` Positive y = Positive y `andInteger` Negative x
To calculate -x & -y , naively we need to calculate
twosComplement ( twosComplement x & twosComplement y )
but
twosComplement x & twosComplement y
has infinitely many 1s , so this wo n't work . Thus we use de Morgan 's law
to get
-x & -y = ! ( ! ( -x ) | ! ( -y ) )
= ! ( ! ( twosComplement x ) | ! ( twosComplement y ) )
= ! ( ! ( ! x + 1 ) | ( ! y + 1 ) )
= ! ( ( x - 1 ) | ( y - 1 ) )
but the result is negative , so we need to take the two 's complement of
this in order to get the magnitude of the result .
twosComplement ! ( ( x - 1 ) | ( y - 1 ) )
= ! ( ! ( ( x - 1 ) | ( y - 1 ) ) ) + 1
= ( ( x - 1 ) | ( y - 1 ) ) + 1
To calculate -x & -y, naively we need to calculate
twosComplement (twosComplement x & twosComplement y)
but
twosComplement x & twosComplement y
has infinitely many 1s, so this won't work. Thus we use de Morgan's law
to get
-x & -y = !(!(-x) | !(-y))
= !(!(twosComplement x) | !(twosComplement y))
= !(!(!x + 1) | (!y + 1))
= !((x - 1) | (y - 1))
but the result is negative, so we need to take the two's complement of
this in order to get the magnitude of the result.
twosComplement !((x - 1) | (y - 1))
= !(!((x - 1) | (y - 1))) + 1
= ((x - 1) | (y - 1)) + 1
-}
-- We don't know that x and y are /strictly/ greater than 1, but
-- minusPositive gives us the required answer anyway.
Negative x `andInteger` Negative y = let x' = x `minusPositive` onePositive
y' = y `minusPositive` onePositive
z = x' `orDigits` y'
-- XXX Cheating the precondition:
z' = succPositive z
in digitsToNegativeInteger z'
# NOINLINE orInteger #
orInteger :: Integer -> Integer -> Integer
Naught `orInteger` (!i) = i
(!i) `orInteger` Naught = i
Positive x `orInteger` Positive y = Positive (x `orDigits` y)
x | -y = - ( twosComplement ( x | twosComplement y ) )
= - ( twosComplement ! ( ! x & ! ( twosComplement y ) ) )
= - ( twosComplement ! ( ! x & ! ( ! y + 1 ) ) )
= - ( twosComplement ! ( ! x & ( y - 1 ) ) )
= - ( ( ! x & ( y - 1 ) ) + 1 )
x | -y = - (twosComplement (x | twosComplement y))
= - (twosComplement !(!x & !(twosComplement y)))
= - (twosComplement !(!x & !(!y + 1)))
= - (twosComplement !(!x & (y - 1)))
= - ((!x & (y - 1)) + 1)
-}
Positive x `orInteger` Negative y = let x' = flipBits x
y' = y `minusPositive` onePositive
z = x' `andDigitsOnes` y'
z' = succPositive z
in digitsToNegativeInteger z'
Negative x `orInteger` Positive y = Positive y `orInteger` Negative x
-x | -y = - ( twosComplement ( twosComplement x | twosComplement y ) )
= - ( twosComplement ! ( ! ( twosComplement x ) & ! ( twosComplement y ) ) )
= - ( twosComplement ! ( ! ( ! x + 1 ) & ! ( ! y + 1 ) ) )
= - ( twosComplement ! ( ( x - 1 ) & ( y - 1 ) ) )
= - ( ( ( x - 1 ) & ( y - 1 ) ) + 1 )
-x | -y = - (twosComplement (twosComplement x | twosComplement y))
= - (twosComplement !(!(twosComplement x) & !(twosComplement y)))
= - (twosComplement !(!(!x + 1) & !(!y + 1)))
= - (twosComplement !((x - 1) & (y - 1)))
= - (((x - 1) & (y - 1)) + 1)
-}
Negative x `orInteger` Negative y = let x' = x `minusPositive` onePositive
y' = y `minusPositive` onePositive
z = x' `andDigits` y'
z' = succPositive z
in digitsToNegativeInteger z'
# NOINLINE xorInteger #
xorInteger :: Integer -> Integer -> Integer
Naught `xorInteger` (!i) = i
(!i) `xorInteger` Naught = i
Positive x `xorInteger` Positive y = digitsToInteger (x `xorDigits` y)
x ^ -y = - ( twosComplement ( x ^ twosComplement y ) )
= - ( twosComplement ! ( x ^ ! ( twosComplement y ) ) )
= - ( twosComplement ! ( x ^ ! ( ! y + 1 ) ) )
= - ( twosComplement ! ( x ^ ( y - 1 ) ) )
= - ( ( x ^ ( y - 1 ) ) + 1 )
x ^ -y = - (twosComplement (x ^ twosComplement y))
= - (twosComplement !(x ^ !(twosComplement y)))
= - (twosComplement !(x ^ !(!y + 1)))
= - (twosComplement !(x ^ (y - 1)))
= - ((x ^ (y - 1)) + 1)
-}
Positive x `xorInteger` Negative y = let y' = y `minusPositive` onePositive
z = x `xorDigits` y'
z' = succPositive z
in digitsToNegativeInteger z'
Negative x `xorInteger` Positive y = Positive y `xorInteger` Negative x
-x ^ -y = twosComplement x ^ y
= ( ! x + 1 ) ^ ( ! y + 1 )
= ( ! x + 1 ) ^ ( ! y + 1 )
= ! ( ! x + 1 ) ^ ! ( ! y + 1 )
= ( x - 1 ) ^ ( y - 1 )
-x ^ -y = twosComplement x ^ twosComplement y
= (!x + 1) ^ (!y + 1)
= (!x + 1) ^ (!y + 1)
= !(!x + 1) ^ !(!y + 1)
= (x - 1) ^ (y - 1)
-}
Negative x `xorInteger` Negative y = let x' = x `minusPositive` onePositive
y' = y `minusPositive` onePositive
z = x' `xorDigits` y'
in digitsToInteger z
# NOINLINE complementInteger #
complementInteger :: Integer -> Integer
complementInteger x = negativeOneInteger `minusInteger` x
# NOINLINE shiftLInteger #
shiftLInteger :: Integer -> Int# -> Integer
shiftLInteger (Positive p) i = Positive (shiftLPositive p i)
shiftLInteger (Negative n) i = Negative (shiftLPositive n i)
shiftLInteger Naught _ = Naught
{-# NOINLINE shiftRInteger #-}
shiftRInteger :: Integer -> Int# -> Integer
shiftRInteger (Positive p) i = shiftRPositive p i
shiftRInteger j@(Negative _) i
= complementInteger (shiftRInteger (complementInteger j) i)
shiftRInteger Naught _ = Naught
-- XXX this could be a lot more efficient, but this is a quick
-- reimplementation of the default Data.Bits instance, so that we can
implement the Integer interface
testBitInteger :: Integer -> Int# -> Bool
testBitInteger x i = (x `andInteger` (oneInteger `shiftLInteger` i))
`neqInteger` Naught
twosComplementPositive :: Positive -> DigitsOnes
twosComplementPositive p = flipBits (p `minusPositive` onePositive)
flipBits :: Digits -> DigitsOnes
flipBits ds = DigitsOnes (flipBitsDigits ds)
flipBitsDigits :: Digits -> Digits
flipBitsDigits None = None
flipBitsDigits (Some w ws) = Some (not# w) (flipBitsDigits ws)
# NOINLINE negateInteger #
negateInteger :: Integer -> Integer
negateInteger (Positive p) = Negative p
negateInteger (Negative p) = Positive p
negateInteger Naught = Naught
-- Note [Avoid patError]
# NOINLINE plusInteger #
plusInteger :: Integer -> Integer -> Integer
Positive p1 `plusInteger` Positive p2 = Positive (p1 `plusPositive` p2)
Negative p1 `plusInteger` Negative p2 = Negative (p1 `plusPositive` p2)
Positive p1 `plusInteger` Negative p2
= case p1 `comparePositive` p2 of
GT -> Positive (p1 `minusPositive` p2)
EQ -> Naught
LT -> Negative (p2 `minusPositive` p1)
Negative p1 `plusInteger` Positive p2
= Positive p2 `plusInteger` Negative p1
Naught `plusInteger` Naught = Naught
Naught `plusInteger` i@(Positive _) = i
Naught `plusInteger` i@(Negative _) = i
i@(Positive _) `plusInteger` Naught = i
i@(Negative _) `plusInteger` Naught = i
# NOINLINE minusInteger #
minusInteger :: Integer -> Integer -> Integer
i1 `minusInteger` i2 = i1 `plusInteger` negateInteger i2
# NOINLINE timesInteger #
timesInteger :: Integer -> Integer -> Integer
Positive p1 `timesInteger` Positive p2 = Positive (p1 `timesPositive` p2)
Negative p1 `timesInteger` Negative p2 = Positive (p1 `timesPositive` p2)
Positive p1 `timesInteger` Negative p2 = Negative (p1 `timesPositive` p2)
Negative p1 `timesInteger` Positive p2 = Negative (p1 `timesPositive` p2)
(!_) `timesInteger` (!_) = Naught
# NOINLINE divModInteger #
divModInteger :: Integer -> Integer -> (# Integer, Integer #)
n `divModInteger` d =
case n `quotRemInteger` d of
(# q, r #) ->
if signumInteger r `eqInteger`
negateInteger (signumInteger d)
then (# q `minusInteger` oneInteger, r `plusInteger` d #)
else (# q, r #)
# NOINLINE divInteger #
divInteger :: Integer -> Integer -> Integer
n `divInteger` d = quotient
where (# quotient, _ #) = n `divModInteger` d
# NOINLINE modInteger #
modInteger :: Integer -> Integer -> Integer
n `modInteger` d = modulus
where (# _, modulus #) = n `divModInteger` d
# NOINLINE quotRemInteger #
quotRemInteger :: Integer -> Integer -> (# Integer, Integer #)
Naught `quotRemInteger` (!_) = (# Naught, Naught #)
(!_) `quotRemInteger` Naught
= (# errorInteger, errorInteger #) -- XXX Can't happen
XXX _ ` quotRemInteger ` Naught = error " Division by zero "
Positive p1 `quotRemInteger` Positive p2 = p1 `quotRemPositive` p2
Negative p1 `quotRemInteger` Positive p2 = case p1 `quotRemPositive` p2 of
(# q, r #) ->
(# negateInteger q,
negateInteger r #)
Positive p1 `quotRemInteger` Negative p2 = case p1 `quotRemPositive` p2 of
(# q, r #) ->
(# negateInteger q, r #)
Negative p1 `quotRemInteger` Negative p2 = case p1 `quotRemPositive` p2 of
(# q, r #) ->
(# q, negateInteger r #)
# NOINLINE quotInteger #
quotInteger :: Integer -> Integer -> Integer
x `quotInteger` y = case x `quotRemInteger` y of
(# q, _ #) -> q
# NOINLINE remInteger #
remInteger :: Integer -> Integer -> Integer
x `remInteger` y = case x `quotRemInteger` y of
(# _, r #) -> r
# NOINLINE compareInteger #
compareInteger :: Integer -> Integer -> Ordering
Positive x `compareInteger` Positive y = x `comparePositive` y
Positive _ `compareInteger` (!_) = GT
Naught `compareInteger` Naught = EQ
Naught `compareInteger` Negative _ = GT
Negative x `compareInteger` Negative y = y `comparePositive` x
(!_) `compareInteger` (!_) = LT
# NOINLINE eqInteger # #
eqInteger# :: Integer -> Integer -> Int#
x `eqInteger#` y = case x `compareInteger` y of
EQ -> 1#
_ -> 0#
# NOINLINE neqInteger # #
neqInteger# :: Integer -> Integer -> Int#
x `neqInteger#` y = case x `compareInteger` y of
EQ -> 0#
_ -> 1#
{-# INLINE eqInteger #-}
# INLINE neqInteger #
eqInteger, neqInteger :: Integer -> Integer -> Bool
eqInteger a b = isTrue# (a `eqInteger#` b)
neqInteger a b = isTrue# (a `neqInteger#` b)
instance Eq Integer where
(==) = eqInteger
(/=) = neqInteger
# NOINLINE ltInteger # #
ltInteger# :: Integer -> Integer -> Int#
x `ltInteger#` y = case x `compareInteger` y of
LT -> 1#
_ -> 0#
# NOINLINE gtInteger # #
gtInteger# :: Integer -> Integer -> Int#
x `gtInteger#` y = case x `compareInteger` y of
GT -> 1#
_ -> 0#
# NOINLINE leInteger # #
leInteger# :: Integer -> Integer -> Int#
x `leInteger#` y = case x `compareInteger` y of
GT -> 0#
_ -> 1#
# NOINLINE geInteger # #
geInteger# :: Integer -> Integer -> Int#
x `geInteger#` y = case x `compareInteger` y of
LT -> 0#
_ -> 1#
# INLINE leInteger #
# INLINE ltInteger #
# INLINE geInteger #
# INLINE gtInteger #
leInteger, gtInteger, ltInteger, geInteger :: Integer -> Integer -> Bool
leInteger a b = isTrue# (a `leInteger#` b)
gtInteger a b = isTrue# (a `gtInteger#` b)
ltInteger a b = isTrue# (a `ltInteger#` b)
geInteger a b = isTrue# (a `geInteger#` b)
instance Ord Integer where
(<=) = leInteger
(>) = gtInteger
(<) = ltInteger
(>=) = geInteger
compare = compareInteger
{-# NOINLINE absInteger #-}
absInteger :: Integer -> Integer
absInteger (Negative x) = Positive x
absInteger x = x
# NOINLINE signumInteger #
signumInteger :: Integer -> Integer
signumInteger (Negative _) = negativeOneInteger
signumInteger Naught = Naught
signumInteger (Positive _) = oneInteger
# NOINLINE hashInteger #
hashInteger :: Integer -> Int#
hashInteger = integerToInt
-------------------------------------------------------------------
-- The hard work is done on positive numbers
onePositive :: Positive
onePositive = Some 1## None
halfBoundUp, fullBound :: () -> Digit
lowHalfMask :: () -> Digit
highHalfShift :: () -> Int#
twoToTheThirtytwoPositive :: Positive
#if WORD_SIZE_IN_BITS == 64
halfBoundUp () = 0x8000000000000000##
fullBound () = 0xFFFFFFFFFFFFFFFF##
lowHalfMask () = 0xFFFFFFFF##
highHalfShift () = 32#
twoToTheThirtytwoPositive = Some 0x100000000## None
#elif WORD_SIZE_IN_BITS == 32
halfBoundUp () = 0x80000000##
fullBound () = 0xFFFFFFFF##
lowHalfMask () = 0xFFFF##
highHalfShift () = 16#
twoToTheThirtytwoPositive = Some 0## (Some 1## None)
#else
#error Unhandled WORD_SIZE_IN_BITS
#endif
digitsMaybeZeroToInteger :: Digits -> Integer
digitsMaybeZeroToInteger None = Naught
digitsMaybeZeroToInteger ds = Positive ds
digitsToInteger :: Digits -> Integer
digitsToInteger ds = case removeZeroTails ds of
None -> Naught
ds' -> Positive ds'
digitsToNegativeInteger :: Digits -> Integer
digitsToNegativeInteger ds = case removeZeroTails ds of
None -> Naught
ds' -> Negative ds'
removeZeroTails :: Digits -> Digits
removeZeroTails (Some w ds) = if isTrue# (w `eqWord#` 0##)
then case removeZeroTails ds of
None -> None
ds' -> Some w ds'
else Some w (removeZeroTails ds)
removeZeroTails None = None
#if WORD_SIZE_IN_BITS < 64
word64ToPositive :: Word64# -> Positive
word64ToPositive w
= if isTrue# (w `eqWord64#` wordToWord64# 0##)
then None
else Some (word64ToWord# w) (word64ToPositive (w `uncheckedShiftRL64#` 32#))
positiveToWord64 :: Positive -> Word64#
positiveToWord64 None = wordToWord64# 0## -- XXX Can't happen
positiveToWord64 (Some w None) = wordToWord64# w
positiveToWord64 (Some low (Some high _))
= wordToWord64# low `or64#` (wordToWord64# high `uncheckedShiftL64#` 32#)
#endif
-- Note [Avoid patError]
comparePositive :: Positive -> Positive -> Ordering
Some x xs `comparePositive` Some y ys = case xs `comparePositive` ys of
EQ -> if isTrue# (x `ltWord#` y) then LT
else if isTrue# (x `gtWord#` y) then GT
else EQ
res -> res
None `comparePositive` None = EQ
(Some {}) `comparePositive` None = GT
None `comparePositive` (Some {}) = LT
plusPositive :: Positive -> Positive -> Positive
plusPositive x0 y0 = addWithCarry 0## x0 y0
digit ` elem ` [ 0 , 1 ]
-- Note [Avoid patError]
addWithCarry :: Digit -> Positive -> Positive -> Positive
addWithCarry c None None = addOnCarry c None
addWithCarry c xs@(Some {}) None = addOnCarry c xs
addWithCarry c None ys@(Some {}) = addOnCarry c ys
addWithCarry c xs@(Some x xs') ys@(Some y ys')
= if isTrue# (x `ltWord#` y) then addWithCarry c ys xs
-- Now x >= y
else if isTrue# (y `geWord#` halfBoundUp ())
-- So they are both at least halfBoundUp, so we subtract
halfBoundUp from each and thus carry 1
then case x `minusWord#` halfBoundUp () of
x' ->
case y `minusWord#` halfBoundUp () of
y' ->
case x' `plusWord#` y' `plusWord#` c of
this ->
Some this withCarry
else if isTrue# (x `geWord#` halfBoundUp ())
then case x `minusWord#` halfBoundUp () of
x' ->
case x' `plusWord#` y `plusWord#` c of
z ->
-- We've taken off halfBoundUp, so now we need to
-- add it back on
if isTrue# (z `ltWord#` halfBoundUp ())
then Some (z `plusWord#` halfBoundUp ()) withoutCarry
else Some (z `minusWord#` halfBoundUp ()) withCarry
else Some (x `plusWord#` y `plusWord#` c) withoutCarry
where withCarry = addWithCarry 1## xs' ys'
withoutCarry = addWithCarry 0## xs' ys'
digit ` elem ` [ 0 , 1 ]
addOnCarry :: Digit -> Positive -> Positive
addOnCarry (!c) (!ws) = if isTrue# (c `eqWord#` 0##)
then ws
else succPositive ws
digit ` elem ` [ 0 , 1 ]
succPositive :: Positive -> Positive
succPositive None = Some 1## None
succPositive (Some w ws) = if isTrue# (w `eqWord#` fullBound ())
then Some 0## (succPositive ws)
else Some (w `plusWord#` 1##) ws
-- Requires x > y
-- In recursive calls, x >= y and x == y => result is None
-- Note [Avoid patError]
minusPositive :: Positive -> Positive -> Positive
Some x xs `minusPositive` Some y ys
= if isTrue# (x `eqWord#` y)
then case xs `minusPositive` ys of
None -> None
s -> Some 0## s
else if isTrue# (x `gtWord#` y) then
Some (x `minusWord#` y) (xs `minusPositive` ys)
else case (fullBound () `minusWord#` y) `plusWord#` 1## of
z = 2^n - y , calculated without overflow
case z `plusWord#` x of
z = 2^n + ( x - y ) , calculated without overflow
Some z' ((xs `minusPositive` ys) `minusPositive` onePositive)
xs@(Some {}) `minusPositive` None = xs
None `minusPositive` None = None
None `minusPositive` (Some {}) = errorPositive -- XXX Can't happen
-- XXX None `minusPositive` _ = error "minusPositive: Requirement x > y not met"
-- Note [Avoid patError]
timesPositive :: Positive -> Positive -> Positive
-- XXX None's can't happen here:
None `timesPositive` None = errorPositive
None `timesPositive` (Some {}) = errorPositive
(Some {}) `timesPositive` None = errorPositive
-- x and y are the last digits in Positive numbers, so are not 0:
xs@(Some x xs') `timesPositive` ys@(Some y ys')
= case xs' of
None ->
case ys' of
None ->
x `timesDigit` y
Some {} ->
ys `timesPositive` xs
Some {} ->
case ys' of
None ->
-- y is the last digit in a Positive number, so is not 0.
let zs = Some 0## (xs' `timesPositive` ys)
in -- We could actually skip this test, and everything would
turn out OK . We already play tricks like that in timesPositive .
if isTrue# (x `eqWord#` 0##)
then zs
else (x `timesDigit` y) `plusPositive` zs
Some {} ->
(Some x None `timesPositive` ys) `plusPositive`
Some 0## (xs' `timesPositive` ys)
-- Requires arguments /= 0
Suppose we have 2n bits in a Word . Then
x = 2^n xh + xl
y = 2^n yh + yl
x * y = ( 2^n xh + xl ) * ( 2^n yh + yl )
= 2^(2n ) ( xh yh )
+ 2^n ( xh yl )
+ 2^n ( xl yh )
+ ( xl yl )
~~~~~~~ - all fit in 2n bits
-- Requires arguments /= 0
Suppose we have 2n bits in a Word. Then
x = 2^n xh + xl
y = 2^n yh + yl
x * y = (2^n xh + xl) * (2^n yh + yl)
= 2^(2n) (xh yh)
+ 2^n (xh yl)
+ 2^n (xl yh)
+ (xl yl)
~~~~~~~ - all fit in 2n bits
-}
timesDigit :: Digit -> Digit -> Positive
timesDigit (!x) (!y)
= case splitHalves x of
(# xh, xl #) ->
case splitHalves y of
(# yh, yl #) ->
case xh `timesWord#` yh of
xhyh ->
case splitHalves (xh `timesWord#` yl) of
(# xhylh, xhyll #) ->
case xhyll `uncheckedShiftL#` highHalfShift () of
xhyll' ->
case splitHalves (xl `timesWord#` yh) of
(# xlyhh, xlyhl #) ->
case xlyhl `uncheckedShiftL#` highHalfShift () of
xlyhl' ->
case xl `timesWord#` yl of
xlyl ->
-- Add up all the high word results. As the result fits in
4n bits this ca n't overflow .
case xhyh `plusWord#` xhylh `plusWord#` xlyhh of
high ->
-- low: xhyll<<n + xlyhl<<n + xlyl
-- From this point we might make (Some 0 None), but we know
-- that the final result will be positive and the addition
-- will work out OK, so everything will work out in the end.
One thing we do need to be careful of is avoiding returning
-- Some 0 (Some 0 None) + Some n None, as this will result in
-- Some n (Some 0 None) instead of Some n None.
let low = Some xhyll' None `plusPositive`
Some xlyhl' None `plusPositive`
Some xlyl None
in if isTrue# (high `eqWord#` 0##)
then low
else Some 0## (Some high None) `plusPositive` low
splitHalves :: Digit -> (# {- High -} Digit, {- Low -} Digit #)
splitHalves (!x) = (# x `uncheckedShiftRL#` highHalfShift (),
x `and#` lowHalfMask () #)
-- Assumes 0 <= i
shiftLPositive :: Positive -> Int# -> Positive
shiftLPositive p i
= if isTrue# (i >=# WORD_SIZE_IN_BITS#)
then shiftLPositive (Some 0## p) (i -# WORD_SIZE_IN_BITS#)
else smallShiftLPositive p i
-- Assumes 0 <= i < WORD_SIZE_IN_BITS#
smallShiftLPositive :: Positive -> Int# -> Positive
smallShiftLPositive (!p) 0# = p
smallShiftLPositive (!p) (!i) =
case WORD_SIZE_IN_BITS# -# i of
j -> let f carry None = if isTrue# (carry `eqWord#` 0##)
then None
else Some carry None
f carry (Some w ws) = case w `uncheckedShiftRL#` j of
carry' ->
case w `uncheckedShiftL#` i of
me ->
Some (me `or#` carry) (f carry' ws)
in f 0## p
-- Assumes 0 <= i
shiftRPositive :: Positive -> Int# -> Integer
shiftRPositive None _ = Naught
shiftRPositive p@(Some _ q) i
= if isTrue# (i >=# WORD_SIZE_IN_BITS#)
then shiftRPositive q (i -# WORD_SIZE_IN_BITS#)
else smallShiftRPositive p i
-- Assumes 0 <= i < WORD_SIZE_IN_BITS#
smallShiftRPositive :: Positive -> Int# -> Integer
smallShiftRPositive (!p) (!i) =
if isTrue# (i ==# 0#)
then Positive p
else case smallShiftLPositive p (WORD_SIZE_IN_BITS# -# i) of
Some _ p'@(Some _ _) -> Positive p'
_ -> Naught
-- Long division
quotRemPositive :: Positive -> Positive -> (# Integer, Integer #)
(!xs) `quotRemPositive` (!ys)
= case f xs of
(# d, m #) -> (# digitsMaybeZeroToInteger d,
digitsMaybeZeroToInteger m #)
where
subtractors :: Positives
subtractors = mkSubtractors (WORD_SIZE_IN_BITS# -# 1#)
mkSubtractors (!n) = if isTrue# (n ==# 0#)
then Cons ys Nil
else Cons (ys `smallShiftLPositive` n)
(mkSubtractors (n -# 1#))
The main function . Go the the end of xs , then walk
-- back trying to divide the number we accumulate by ys.
f :: Positive -> (# Digits, Digits #)
f None = (# None, None #)
f (Some z zs)
= case f zs of
(# ds, m #) ->
We need to avoid making ( Some Zero None ) here
m' = some z m
in case g 0## subtractors m' of
(# d, m'' #) ->
(# some d ds, m'' #)
g :: Digit -> Positives -> Digits -> (# Digit, Digits #)
g (!d) Nil (!m) = (# d, m #)
g (!d) (Cons sub subs) (!m)
= case d `uncheckedShiftL#` 1# of
d' ->
case m `comparePositive` sub of
LT -> g d' subs m
_ -> g (d' `plusWord#` 1##)
subs
(m `minusPositive` sub)
some :: Digit -> Digits -> Digits
some (!w) None = if isTrue# (w `eqWord#` 0##) then None else Some w None
some (!w) (!ws) = Some w ws
-- Note [Avoid patError]
andDigits :: Digits -> Digits -> Digits
andDigits None None = None
andDigits (Some {}) None = None
andDigits None (Some {}) = None
andDigits (Some w1 ws1) (Some w2 ws2) = Some (w1 `and#` w2) (andDigits ws1 ws2)
DigitsOnes is just like Digits , only None is really 0xFFFFFFF ... ,
-- i.e. ones off to infinity. This makes sense when we want to "and"
a DigitOnes with a Digits , as the latter will bound the size of the
-- result.
newtype DigitsOnes = DigitsOnes Digits
-- Note [Avoid patError]
andDigitsOnes :: DigitsOnes -> Digits -> Digits
andDigitsOnes (DigitsOnes None) None = None
andDigitsOnes (DigitsOnes None) ws2@(Some {}) = ws2
andDigitsOnes (DigitsOnes (Some {})) None = None
andDigitsOnes (DigitsOnes (Some w1 ws1)) (Some w2 ws2)
= Some (w1 `and#` w2) (andDigitsOnes (DigitsOnes ws1) ws2)
-- Note [Avoid patError]
orDigits :: Digits -> Digits -> Digits
orDigits None None = None
orDigits None ds@(Some {}) = ds
orDigits ds@(Some {}) None = ds
orDigits (Some w1 ds1) (Some w2 ds2) = Some (w1 `or#` w2) (orDigits ds1 ds2)
-- Note [Avoid patError]
xorDigits :: Digits -> Digits -> Digits
xorDigits None None = None
xorDigits None ds@(Some {}) = ds
xorDigits ds@(Some {}) None = ds
xorDigits (Some w1 ds1) (Some w2 ds2) = Some (w1 `xor#` w2) (xorDigits ds1 ds2)
-- XXX We'd really like word2Double# for this
doubleFromPositive :: Positive -> Double#
doubleFromPositive None = 0.0##
doubleFromPositive (Some w ds)
= case splitHalves w of
(# h, l #) ->
(doubleFromPositive ds *## (2.0## **## WORD_SIZE_IN_BITS_FLOAT##))
+## (int2Double# (word2Int# h) *##
(2.0## **## int2Double# (highHalfShift ())))
+## int2Double# (word2Int# l)
-- XXX We'd really like word2Float# for this
floatFromPositive :: Positive -> Float#
floatFromPositive None = 0.0#
floatFromPositive (Some w ds)
= case splitHalves w of
(# h, l #) ->
(floatFromPositive ds `timesFloat#` (2.0# `powerFloat#` WORD_SIZE_IN_BITS_FLOAT#))
`plusFloat#` (int2Float# (word2Int# h) `timesFloat#`
(2.0# `powerFloat#` int2Float# (highHalfShift ())))
`plusFloat#` int2Float# (word2Int# l)
#endif
Note [ Avoid patError ]
If we use the natural set of definitions for functions , e.g. :
orDigits None ds = ds
orDigits ds None = ds
orDigits ( Some w1 ds1 ) ( Some w2 ds2 ) = Some ... ...
then GHC may not be smart enough ( especially when compiling with -O0 )
to see that all the cases are handled , and will thus insert calls to
base : Control . Exception . . But we are below base in the
package hierarchy , so this causes build failure !
We therefore help GHC out , by being more explicit about what all the
cases are :
orDigits None None = None
orDigits None ds@(Some { } ) = ds
orDigits ds@(Some { } ) None = ds
orDigits ( Some w1 ds1 ) ( Some w2 ds2 ) = Some ... ...
Note [Avoid patError]
If we use the natural set of definitions for functions, e.g.:
orDigits None ds = ds
orDigits ds None = ds
orDigits (Some w1 ds1) (Some w2 ds2) = Some ... ...
then GHC may not be smart enough (especially when compiling with -O0)
to see that all the cases are handled, and will thus insert calls to
base:Control.Exception.Base.patError. But we are below base in the
package hierarchy, so this causes build failure!
We therefore help GHC out, by being more explicit about what all the
cases are:
orDigits None None = None
orDigits None ds@(Some {}) = ds
orDigits ds@(Some {}) None = ds
orDigits (Some w1 ds1) (Some w2 ds2) = Some ... ...
-}
| null | https://raw.githubusercontent.com/erikd/haskell-big-integer-experiment/7841ec3fcc5be219fa16963849bd12137112f8a9/Simple/GHC/Integer/Type.hs | haskell | Commentary of Integer library is located on the wiki:
It gives an in-depth description of implementation details and
decisions.
---------------------------------------------------------------------------
|
Module : Simple.GHC.Integer.Type
License : BSD3
Maintainer :
Stability : internal
An simple definition of the 'Integer' type.
---------------------------------------------------------------------------
-----------------------------------------------------------------
The hard work is done on positive numbers
XXX Could move [] above us
non-negative?
we don't have Word available at the moment.
Random number
XXX is this right for -minBound?
Must be Naught by the invariant:
Nothing
XXX We assume that this adding to e
isn't going to overflow
XXX We assume that this adding to e
isn't going to overflow
XXX This could be optimised better, by either (word-size dependent)
using single 64bit value for the mantissa, or doing the multiplication
by just building the Digits directly
# NOINLINE andInteger #
We don't know that x and y are /strictly/ greater than 1, but
minusPositive gives us the required answer anyway.
XXX Cheating the precondition:
# NOINLINE shiftRInteger #
XXX this could be a lot more efficient, but this is a quick
reimplementation of the default Data.Bits instance, so that we can
Note [Avoid patError]
XXX Can't happen
# INLINE eqInteger #
# NOINLINE absInteger #
-----------------------------------------------------------------
The hard work is done on positive numbers
XXX Can't happen
Note [Avoid patError]
Note [Avoid patError]
Now x >= y
So they are both at least halfBoundUp, so we subtract
We've taken off halfBoundUp, so now we need to
add it back on
Requires x > y
In recursive calls, x >= y and x == y => result is None
Note [Avoid patError]
XXX Can't happen
XXX None `minusPositive` _ = error "minusPositive: Requirement x > y not met"
Note [Avoid patError]
XXX None's can't happen here:
x and y are the last digits in Positive numbers, so are not 0:
y is the last digit in a Positive number, so is not 0.
We could actually skip this test, and everything would
Requires arguments /= 0
Requires arguments /= 0
Add up all the high word results. As the result fits in
low: xhyll<<n + xlyhl<<n + xlyl
From this point we might make (Some 0 None), but we know
that the final result will be positive and the addition
will work out OK, so everything will work out in the end.
Some 0 (Some 0 None) + Some n None, as this will result in
Some n (Some 0 None) instead of Some n None.
High
Low
Assumes 0 <= i
Assumes 0 <= i < WORD_SIZE_IN_BITS#
Assumes 0 <= i
Assumes 0 <= i < WORD_SIZE_IN_BITS#
Long division
back trying to divide the number we accumulate by ys.
Note [Avoid patError]
i.e. ones off to infinity. This makes sense when we want to "and"
result.
Note [Avoid patError]
Note [Avoid patError]
Note [Avoid patError]
XXX We'd really like word2Double# for this
XXX We'd really like word2Float# for this |
# LANGUAGE CPP , MagicHash , ForeignFunctionInterface ,
NoImplicitPrelude , BangPatterns , UnboxedTuples ,
UnliftedFFITypes #
NoImplicitPrelude, BangPatterns, UnboxedTuples,
UnliftedFFITypes #-}
Copyright : ( c ) 2007 - 2012
Portability : non - portable ( GHC Extensions )
#include "MachDeps.h"
module Simple.GHC.Integer.Type where
import GHC.Prim
import GHC.Classes
import GHC.Types
import GHC.Tuple ()
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
#if !defined(__HADDOCK__)
data Integer = Positive !Positive | Negative !Positive | Naught
Least significant bit is first
Positive 's have the property that they contain at least one Bit ,
and their last Bit is One .
type Positive = Digits
type Positives = List Positive
data Digits = Some !Digit !Digits
| None
type Digit = Word#
data List a = Nil | Cons a (List a)
absolute value in 31 bit chunks , least significant first
ideally these would be Words rather than Ints , but
-> Integer
mkInteger nonNegative is = let abs = f is
in if nonNegative then abs else negateInteger abs
where f [] = Naught
f (I# i : is') = smallInteger i `orInteger` shiftLInteger (f is') 31#
errorInteger :: Integer
errorInteger = Positive errorPositive
errorPositive :: Positive
# NOINLINE smallInteger #
smallInteger :: Int# -> Integer
smallInteger i = if isTrue# (i >=# 0#) then wordToInteger (int2Word# i)
negateInteger (wordToInteger (int2Word# (negateInt# i)))
# NOINLINE wordToInteger #
wordToInteger :: Word# -> Integer
wordToInteger w = if isTrue# (w `eqWord#` 0##)
then Naught
else Positive (Some w None)
# NOINLINE integerToWord #
integerToWord :: Integer -> Word#
integerToWord (Positive (Some w _)) = w
integerToWord (Negative (Some w _)) = 0## `minusWord#` w
integerToWord _ = 0##
# NOINLINE integerToInt #
integerToInt :: Integer -> Int#
integerToInt i = word2Int# (integerToWord i)
#if WORD_SIZE_IN_BITS == 64
#elif WORD_SIZE_IN_BITS == 32
# NOINLINE integerToWord64 #
integerToWord64 :: Integer -> Word64#
integerToWord64 i = int64ToWord64# (integerToInt64 i)
# NOINLINE word64ToInteger #
word64ToInteger:: Word64# -> Integer
word64ToInteger w = if isTrue# (w `eqWord64#` wordToWord64# 0##)
then Naught
else Positive (word64ToPositive w)
# NOINLINE integerToInt64 #
integerToInt64 :: Integer -> Int64#
integerToInt64 Naught = intToInt64# 0#
integerToInt64 (Positive p) = word64ToInt64# (positiveToWord64 p)
integerToInt64 (Negative p)
= negateInt64# (word64ToInt64# (positiveToWord64 p))
# NOINLINE int64ToInteger #
int64ToInteger :: Int64# -> Integer
int64ToInteger i
= if isTrue# (i `eqInt64#` intToInt64# 0#)
then Naught
else if isTrue# (i `gtInt64#` intToInt64# 0#)
then Positive (word64ToPositive (int64ToWord64# i))
else Negative (word64ToPositive (int64ToWord64# (negateInt64# i)))
#else
#error WORD_SIZE_IN_BITS not supported
#endif
oneInteger :: Integer
oneInteger = Positive onePositive
negativeOneInteger :: Integer
negativeOneInteger = Negative onePositive
twoToTheThirtytwoInteger :: Integer
twoToTheThirtytwoInteger = Positive twoToTheThirtytwoPositive
# NOINLINE encodeDoubleInteger #
encodeDoubleInteger :: Integer -> Int# -> Double#
encodeDoubleInteger (Positive ds0) e0 = f 0.0## ds0 e0
where f !acc None (!_) = acc
f !acc (Some d ds) !e = f (acc +## encodeDouble# d e)
ds
(e +# WORD_SIZE_IN_BITS#)
encodeDoubleInteger (Negative ds) e
= negateDouble# (encodeDoubleInteger (Positive ds) e)
encodeDoubleInteger Naught _ = 0.0##
foreign import ccall unsafe "__word_encodeDouble"
encodeDouble# :: Word# -> Int# -> Double#
# NOINLINE encodeFloatInteger #
encodeFloatInteger :: Integer -> Int# -> Float#
encodeFloatInteger (Positive ds0) e0 = f 0.0# ds0 e0
where f !acc None (!_) = acc
f !acc (Some d ds) !e = f (acc `plusFloat#` encodeFloat# d e)
ds
(e +# WORD_SIZE_IN_BITS#)
encodeFloatInteger (Negative ds) e
= negateFloat# (encodeFloatInteger (Positive ds) e)
encodeFloatInteger Naught _ = 0.0#
foreign import ccall unsafe "__word_encodeFloat"
encodeFloat# :: Word# -> Int# -> Float#
# NOINLINE decodeFloatInteger #
decodeFloatInteger :: Float# -> (# Integer, Int# #)
decodeFloatInteger f = case decodeFloat_Int# f of
(# mant, exp #) -> (# smallInteger mant, exp #)
# NOINLINE decodeDoubleInteger #
decodeDoubleInteger :: Double# -> (# Integer, Int# #)
decodeDoubleInteger d
= case decodeDouble_2Int# d of
(# mantSign, mantHigh, mantLow, exp #) ->
(# (smallInteger mantSign) `timesInteger`
( (wordToInteger mantHigh `timesInteger` twoToTheThirtytwoInteger)
`plusInteger` wordToInteger mantLow),
exp #)
# NOINLINE doubleFromInteger #
doubleFromInteger :: Integer -> Double#
doubleFromInteger Naught = 0.0##
doubleFromInteger (Positive p) = doubleFromPositive p
doubleFromInteger (Negative p) = negateDouble# (doubleFromPositive p)
# NOINLINE floatFromInteger #
floatFromInteger :: Integer -> Float#
floatFromInteger Naught = 0.0#
floatFromInteger (Positive p) = floatFromPositive p
floatFromInteger (Negative p) = negateFloat# (floatFromPositive p)
andInteger :: Integer -> Integer -> Integer
Naught `andInteger` (!_) = Naught
(!_) `andInteger` Naught = Naught
Positive x `andInteger` Positive y = digitsToInteger (x `andDigits` y)
To calculate x & -y we need to calculate
x & twosComplement y
The ( imaginary ) sign bits are 0 and 1 , so & ing them give 0 , i.e. positive .
Note that
twosComplement y
has infinitely many 1s , but x has a finite number of digits , so andDigits
will return a finite result .
To calculate x & -y we need to calculate
x & twosComplement y
The (imaginary) sign bits are 0 and 1, so &ing them give 0, i.e. positive.
Note that
twosComplement y
has infinitely many 1s, but x has a finite number of digits, so andDigits
will return a finite result.
-}
Positive x `andInteger` Negative y = let y' = twosComplementPositive y
z = y' `andDigitsOnes` x
in digitsToInteger z
Negative x `andInteger` Positive y = Positive y `andInteger` Negative x
To calculate -x & -y , naively we need to calculate
twosComplement ( twosComplement x & twosComplement y )
but
twosComplement x & twosComplement y
has infinitely many 1s , so this wo n't work . Thus we use de Morgan 's law
to get
-x & -y = ! ( ! ( -x ) | ! ( -y ) )
= ! ( ! ( twosComplement x ) | ! ( twosComplement y ) )
= ! ( ! ( ! x + 1 ) | ( ! y + 1 ) )
= ! ( ( x - 1 ) | ( y - 1 ) )
but the result is negative , so we need to take the two 's complement of
this in order to get the magnitude of the result .
twosComplement ! ( ( x - 1 ) | ( y - 1 ) )
= ! ( ! ( ( x - 1 ) | ( y - 1 ) ) ) + 1
= ( ( x - 1 ) | ( y - 1 ) ) + 1
To calculate -x & -y, naively we need to calculate
twosComplement (twosComplement x & twosComplement y)
but
twosComplement x & twosComplement y
has infinitely many 1s, so this won't work. Thus we use de Morgan's law
to get
-x & -y = !(!(-x) | !(-y))
= !(!(twosComplement x) | !(twosComplement y))
= !(!(!x + 1) | (!y + 1))
= !((x - 1) | (y - 1))
but the result is negative, so we need to take the two's complement of
this in order to get the magnitude of the result.
twosComplement !((x - 1) | (y - 1))
= !(!((x - 1) | (y - 1))) + 1
= ((x - 1) | (y - 1)) + 1
-}
Negative x `andInteger` Negative y = let x' = x `minusPositive` onePositive
y' = y `minusPositive` onePositive
z = x' `orDigits` y'
z' = succPositive z
in digitsToNegativeInteger z'
# NOINLINE orInteger #
orInteger :: Integer -> Integer -> Integer
Naught `orInteger` (!i) = i
(!i) `orInteger` Naught = i
Positive x `orInteger` Positive y = Positive (x `orDigits` y)
x | -y = - ( twosComplement ( x | twosComplement y ) )
= - ( twosComplement ! ( ! x & ! ( twosComplement y ) ) )
= - ( twosComplement ! ( ! x & ! ( ! y + 1 ) ) )
= - ( twosComplement ! ( ! x & ( y - 1 ) ) )
= - ( ( ! x & ( y - 1 ) ) + 1 )
x | -y = - (twosComplement (x | twosComplement y))
= - (twosComplement !(!x & !(twosComplement y)))
= - (twosComplement !(!x & !(!y + 1)))
= - (twosComplement !(!x & (y - 1)))
= - ((!x & (y - 1)) + 1)
-}
Positive x `orInteger` Negative y = let x' = flipBits x
y' = y `minusPositive` onePositive
z = x' `andDigitsOnes` y'
z' = succPositive z
in digitsToNegativeInteger z'
Negative x `orInteger` Positive y = Positive y `orInteger` Negative x
-x | -y = - ( twosComplement ( twosComplement x | twosComplement y ) )
= - ( twosComplement ! ( ! ( twosComplement x ) & ! ( twosComplement y ) ) )
= - ( twosComplement ! ( ! ( ! x + 1 ) & ! ( ! y + 1 ) ) )
= - ( twosComplement ! ( ( x - 1 ) & ( y - 1 ) ) )
= - ( ( ( x - 1 ) & ( y - 1 ) ) + 1 )
-x | -y = - (twosComplement (twosComplement x | twosComplement y))
= - (twosComplement !(!(twosComplement x) & !(twosComplement y)))
= - (twosComplement !(!(!x + 1) & !(!y + 1)))
= - (twosComplement !((x - 1) & (y - 1)))
= - (((x - 1) & (y - 1)) + 1)
-}
Negative x `orInteger` Negative y = let x' = x `minusPositive` onePositive
y' = y `minusPositive` onePositive
z = x' `andDigits` y'
z' = succPositive z
in digitsToNegativeInteger z'
# NOINLINE xorInteger #
xorInteger :: Integer -> Integer -> Integer
Naught `xorInteger` (!i) = i
(!i) `xorInteger` Naught = i
Positive x `xorInteger` Positive y = digitsToInteger (x `xorDigits` y)
x ^ -y = - ( twosComplement ( x ^ twosComplement y ) )
= - ( twosComplement ! ( x ^ ! ( twosComplement y ) ) )
= - ( twosComplement ! ( x ^ ! ( ! y + 1 ) ) )
= - ( twosComplement ! ( x ^ ( y - 1 ) ) )
= - ( ( x ^ ( y - 1 ) ) + 1 )
x ^ -y = - (twosComplement (x ^ twosComplement y))
= - (twosComplement !(x ^ !(twosComplement y)))
= - (twosComplement !(x ^ !(!y + 1)))
= - (twosComplement !(x ^ (y - 1)))
= - ((x ^ (y - 1)) + 1)
-}
Positive x `xorInteger` Negative y = let y' = y `minusPositive` onePositive
z = x `xorDigits` y'
z' = succPositive z
in digitsToNegativeInteger z'
Negative x `xorInteger` Positive y = Positive y `xorInteger` Negative x
-x ^ -y = twosComplement x ^ y
= ( ! x + 1 ) ^ ( ! y + 1 )
= ( ! x + 1 ) ^ ( ! y + 1 )
= ! ( ! x + 1 ) ^ ! ( ! y + 1 )
= ( x - 1 ) ^ ( y - 1 )
-x ^ -y = twosComplement x ^ twosComplement y
= (!x + 1) ^ (!y + 1)
= (!x + 1) ^ (!y + 1)
= !(!x + 1) ^ !(!y + 1)
= (x - 1) ^ (y - 1)
-}
Negative x `xorInteger` Negative y = let x' = x `minusPositive` onePositive
y' = y `minusPositive` onePositive
z = x' `xorDigits` y'
in digitsToInteger z
# NOINLINE complementInteger #
complementInteger :: Integer -> Integer
complementInteger x = negativeOneInteger `minusInteger` x
# NOINLINE shiftLInteger #
shiftLInteger :: Integer -> Int# -> Integer
shiftLInteger (Positive p) i = Positive (shiftLPositive p i)
shiftLInteger (Negative n) i = Negative (shiftLPositive n i)
shiftLInteger Naught _ = Naught
shiftRInteger :: Integer -> Int# -> Integer
shiftRInteger (Positive p) i = shiftRPositive p i
shiftRInteger j@(Negative _) i
= complementInteger (shiftRInteger (complementInteger j) i)
shiftRInteger Naught _ = Naught
implement the Integer interface
testBitInteger :: Integer -> Int# -> Bool
testBitInteger x i = (x `andInteger` (oneInteger `shiftLInteger` i))
`neqInteger` Naught
twosComplementPositive :: Positive -> DigitsOnes
twosComplementPositive p = flipBits (p `minusPositive` onePositive)
flipBits :: Digits -> DigitsOnes
flipBits ds = DigitsOnes (flipBitsDigits ds)
flipBitsDigits :: Digits -> Digits
flipBitsDigits None = None
flipBitsDigits (Some w ws) = Some (not# w) (flipBitsDigits ws)
# NOINLINE negateInteger #
negateInteger :: Integer -> Integer
negateInteger (Positive p) = Negative p
negateInteger (Negative p) = Positive p
negateInteger Naught = Naught
# NOINLINE plusInteger #
plusInteger :: Integer -> Integer -> Integer
Positive p1 `plusInteger` Positive p2 = Positive (p1 `plusPositive` p2)
Negative p1 `plusInteger` Negative p2 = Negative (p1 `plusPositive` p2)
Positive p1 `plusInteger` Negative p2
= case p1 `comparePositive` p2 of
GT -> Positive (p1 `minusPositive` p2)
EQ -> Naught
LT -> Negative (p2 `minusPositive` p1)
Negative p1 `plusInteger` Positive p2
= Positive p2 `plusInteger` Negative p1
Naught `plusInteger` Naught = Naught
Naught `plusInteger` i@(Positive _) = i
Naught `plusInteger` i@(Negative _) = i
i@(Positive _) `plusInteger` Naught = i
i@(Negative _) `plusInteger` Naught = i
# NOINLINE minusInteger #
minusInteger :: Integer -> Integer -> Integer
i1 `minusInteger` i2 = i1 `plusInteger` negateInteger i2
# NOINLINE timesInteger #
timesInteger :: Integer -> Integer -> Integer
Positive p1 `timesInteger` Positive p2 = Positive (p1 `timesPositive` p2)
Negative p1 `timesInteger` Negative p2 = Positive (p1 `timesPositive` p2)
Positive p1 `timesInteger` Negative p2 = Negative (p1 `timesPositive` p2)
Negative p1 `timesInteger` Positive p2 = Negative (p1 `timesPositive` p2)
(!_) `timesInteger` (!_) = Naught
# NOINLINE divModInteger #
divModInteger :: Integer -> Integer -> (# Integer, Integer #)
n `divModInteger` d =
case n `quotRemInteger` d of
(# q, r #) ->
if signumInteger r `eqInteger`
negateInteger (signumInteger d)
then (# q `minusInteger` oneInteger, r `plusInteger` d #)
else (# q, r #)
# NOINLINE divInteger #
divInteger :: Integer -> Integer -> Integer
n `divInteger` d = quotient
where (# quotient, _ #) = n `divModInteger` d
# NOINLINE modInteger #
modInteger :: Integer -> Integer -> Integer
n `modInteger` d = modulus
where (# _, modulus #) = n `divModInteger` d
# NOINLINE quotRemInteger #
quotRemInteger :: Integer -> Integer -> (# Integer, Integer #)
Naught `quotRemInteger` (!_) = (# Naught, Naught #)
(!_) `quotRemInteger` Naught
XXX _ ` quotRemInteger ` Naught = error " Division by zero "
Positive p1 `quotRemInteger` Positive p2 = p1 `quotRemPositive` p2
Negative p1 `quotRemInteger` Positive p2 = case p1 `quotRemPositive` p2 of
(# q, r #) ->
(# negateInteger q,
negateInteger r #)
Positive p1 `quotRemInteger` Negative p2 = case p1 `quotRemPositive` p2 of
(# q, r #) ->
(# negateInteger q, r #)
Negative p1 `quotRemInteger` Negative p2 = case p1 `quotRemPositive` p2 of
(# q, r #) ->
(# q, negateInteger r #)
# NOINLINE quotInteger #
quotInteger :: Integer -> Integer -> Integer
x `quotInteger` y = case x `quotRemInteger` y of
(# q, _ #) -> q
# NOINLINE remInteger #
remInteger :: Integer -> Integer -> Integer
x `remInteger` y = case x `quotRemInteger` y of
(# _, r #) -> r
# NOINLINE compareInteger #
compareInteger :: Integer -> Integer -> Ordering
Positive x `compareInteger` Positive y = x `comparePositive` y
Positive _ `compareInteger` (!_) = GT
Naught `compareInteger` Naught = EQ
Naught `compareInteger` Negative _ = GT
Negative x `compareInteger` Negative y = y `comparePositive` x
(!_) `compareInteger` (!_) = LT
# NOINLINE eqInteger # #
eqInteger# :: Integer -> Integer -> Int#
x `eqInteger#` y = case x `compareInteger` y of
EQ -> 1#
_ -> 0#
# NOINLINE neqInteger # #
neqInteger# :: Integer -> Integer -> Int#
x `neqInteger#` y = case x `compareInteger` y of
EQ -> 0#
_ -> 1#
# INLINE neqInteger #
eqInteger, neqInteger :: Integer -> Integer -> Bool
eqInteger a b = isTrue# (a `eqInteger#` b)
neqInteger a b = isTrue# (a `neqInteger#` b)
instance Eq Integer where
(==) = eqInteger
(/=) = neqInteger
# NOINLINE ltInteger # #
ltInteger# :: Integer -> Integer -> Int#
x `ltInteger#` y = case x `compareInteger` y of
LT -> 1#
_ -> 0#
# NOINLINE gtInteger # #
gtInteger# :: Integer -> Integer -> Int#
x `gtInteger#` y = case x `compareInteger` y of
GT -> 1#
_ -> 0#
# NOINLINE leInteger # #
leInteger# :: Integer -> Integer -> Int#
x `leInteger#` y = case x `compareInteger` y of
GT -> 0#
_ -> 1#
# NOINLINE geInteger # #
geInteger# :: Integer -> Integer -> Int#
x `geInteger#` y = case x `compareInteger` y of
LT -> 0#
_ -> 1#
# INLINE leInteger #
# INLINE ltInteger #
# INLINE geInteger #
# INLINE gtInteger #
leInteger, gtInteger, ltInteger, geInteger :: Integer -> Integer -> Bool
leInteger a b = isTrue# (a `leInteger#` b)
gtInteger a b = isTrue# (a `gtInteger#` b)
ltInteger a b = isTrue# (a `ltInteger#` b)
geInteger a b = isTrue# (a `geInteger#` b)
instance Ord Integer where
(<=) = leInteger
(>) = gtInteger
(<) = ltInteger
(>=) = geInteger
compare = compareInteger
absInteger :: Integer -> Integer
absInteger (Negative x) = Positive x
absInteger x = x
# NOINLINE signumInteger #
signumInteger :: Integer -> Integer
signumInteger (Negative _) = negativeOneInteger
signumInteger Naught = Naught
signumInteger (Positive _) = oneInteger
# NOINLINE hashInteger #
hashInteger :: Integer -> Int#
hashInteger = integerToInt
onePositive :: Positive
onePositive = Some 1## None
halfBoundUp, fullBound :: () -> Digit
lowHalfMask :: () -> Digit
highHalfShift :: () -> Int#
twoToTheThirtytwoPositive :: Positive
#if WORD_SIZE_IN_BITS == 64
halfBoundUp () = 0x8000000000000000##
fullBound () = 0xFFFFFFFFFFFFFFFF##
lowHalfMask () = 0xFFFFFFFF##
highHalfShift () = 32#
twoToTheThirtytwoPositive = Some 0x100000000## None
#elif WORD_SIZE_IN_BITS == 32
halfBoundUp () = 0x80000000##
fullBound () = 0xFFFFFFFF##
lowHalfMask () = 0xFFFF##
highHalfShift () = 16#
twoToTheThirtytwoPositive = Some 0## (Some 1## None)
#else
#error Unhandled WORD_SIZE_IN_BITS
#endif
digitsMaybeZeroToInteger :: Digits -> Integer
digitsMaybeZeroToInteger None = Naught
digitsMaybeZeroToInteger ds = Positive ds
digitsToInteger :: Digits -> Integer
digitsToInteger ds = case removeZeroTails ds of
None -> Naught
ds' -> Positive ds'
digitsToNegativeInteger :: Digits -> Integer
digitsToNegativeInteger ds = case removeZeroTails ds of
None -> Naught
ds' -> Negative ds'
removeZeroTails :: Digits -> Digits
removeZeroTails (Some w ds) = if isTrue# (w `eqWord#` 0##)
then case removeZeroTails ds of
None -> None
ds' -> Some w ds'
else Some w (removeZeroTails ds)
removeZeroTails None = None
#if WORD_SIZE_IN_BITS < 64
word64ToPositive :: Word64# -> Positive
word64ToPositive w
= if isTrue# (w `eqWord64#` wordToWord64# 0##)
then None
else Some (word64ToWord# w) (word64ToPositive (w `uncheckedShiftRL64#` 32#))
positiveToWord64 :: Positive -> Word64#
positiveToWord64 (Some w None) = wordToWord64# w
positiveToWord64 (Some low (Some high _))
= wordToWord64# low `or64#` (wordToWord64# high `uncheckedShiftL64#` 32#)
#endif
comparePositive :: Positive -> Positive -> Ordering
Some x xs `comparePositive` Some y ys = case xs `comparePositive` ys of
EQ -> if isTrue# (x `ltWord#` y) then LT
else if isTrue# (x `gtWord#` y) then GT
else EQ
res -> res
None `comparePositive` None = EQ
(Some {}) `comparePositive` None = GT
None `comparePositive` (Some {}) = LT
plusPositive :: Positive -> Positive -> Positive
plusPositive x0 y0 = addWithCarry 0## x0 y0
digit ` elem ` [ 0 , 1 ]
addWithCarry :: Digit -> Positive -> Positive -> Positive
addWithCarry c None None = addOnCarry c None
addWithCarry c xs@(Some {}) None = addOnCarry c xs
addWithCarry c None ys@(Some {}) = addOnCarry c ys
addWithCarry c xs@(Some x xs') ys@(Some y ys')
= if isTrue# (x `ltWord#` y) then addWithCarry c ys xs
else if isTrue# (y `geWord#` halfBoundUp ())
halfBoundUp from each and thus carry 1
then case x `minusWord#` halfBoundUp () of
x' ->
case y `minusWord#` halfBoundUp () of
y' ->
case x' `plusWord#` y' `plusWord#` c of
this ->
Some this withCarry
else if isTrue# (x `geWord#` halfBoundUp ())
then case x `minusWord#` halfBoundUp () of
x' ->
case x' `plusWord#` y `plusWord#` c of
z ->
if isTrue# (z `ltWord#` halfBoundUp ())
then Some (z `plusWord#` halfBoundUp ()) withoutCarry
else Some (z `minusWord#` halfBoundUp ()) withCarry
else Some (x `plusWord#` y `plusWord#` c) withoutCarry
where withCarry = addWithCarry 1## xs' ys'
withoutCarry = addWithCarry 0## xs' ys'
digit ` elem ` [ 0 , 1 ]
addOnCarry :: Digit -> Positive -> Positive
addOnCarry (!c) (!ws) = if isTrue# (c `eqWord#` 0##)
then ws
else succPositive ws
digit ` elem ` [ 0 , 1 ]
succPositive :: Positive -> Positive
succPositive None = Some 1## None
succPositive (Some w ws) = if isTrue# (w `eqWord#` fullBound ())
then Some 0## (succPositive ws)
else Some (w `plusWord#` 1##) ws
minusPositive :: Positive -> Positive -> Positive
Some x xs `minusPositive` Some y ys
= if isTrue# (x `eqWord#` y)
then case xs `minusPositive` ys of
None -> None
s -> Some 0## s
else if isTrue# (x `gtWord#` y) then
Some (x `minusWord#` y) (xs `minusPositive` ys)
else case (fullBound () `minusWord#` y) `plusWord#` 1## of
z = 2^n - y , calculated without overflow
case z `plusWord#` x of
z = 2^n + ( x - y ) , calculated without overflow
Some z' ((xs `minusPositive` ys) `minusPositive` onePositive)
xs@(Some {}) `minusPositive` None = xs
None `minusPositive` None = None
timesPositive :: Positive -> Positive -> Positive
None `timesPositive` None = errorPositive
None `timesPositive` (Some {}) = errorPositive
(Some {}) `timesPositive` None = errorPositive
xs@(Some x xs') `timesPositive` ys@(Some y ys')
= case xs' of
None ->
case ys' of
None ->
x `timesDigit` y
Some {} ->
ys `timesPositive` xs
Some {} ->
case ys' of
None ->
let zs = Some 0## (xs' `timesPositive` ys)
turn out OK . We already play tricks like that in timesPositive .
if isTrue# (x `eqWord#` 0##)
then zs
else (x `timesDigit` y) `plusPositive` zs
Some {} ->
(Some x None `timesPositive` ys) `plusPositive`
Some 0## (xs' `timesPositive` ys)
Suppose we have 2n bits in a Word . Then
x = 2^n xh + xl
y = 2^n yh + yl
x * y = ( 2^n xh + xl ) * ( 2^n yh + yl )
= 2^(2n ) ( xh yh )
+ 2^n ( xh yl )
+ 2^n ( xl yh )
+ ( xl yl )
~~~~~~~ - all fit in 2n bits
Suppose we have 2n bits in a Word. Then
x = 2^n xh + xl
y = 2^n yh + yl
x * y = (2^n xh + xl) * (2^n yh + yl)
= 2^(2n) (xh yh)
+ 2^n (xh yl)
+ 2^n (xl yh)
+ (xl yl)
~~~~~~~ - all fit in 2n bits
-}
timesDigit :: Digit -> Digit -> Positive
timesDigit (!x) (!y)
= case splitHalves x of
(# xh, xl #) ->
case splitHalves y of
(# yh, yl #) ->
case xh `timesWord#` yh of
xhyh ->
case splitHalves (xh `timesWord#` yl) of
(# xhylh, xhyll #) ->
case xhyll `uncheckedShiftL#` highHalfShift () of
xhyll' ->
case splitHalves (xl `timesWord#` yh) of
(# xlyhh, xlyhl #) ->
case xlyhl `uncheckedShiftL#` highHalfShift () of
xlyhl' ->
case xl `timesWord#` yl of
xlyl ->
4n bits this ca n't overflow .
case xhyh `plusWord#` xhylh `plusWord#` xlyhh of
high ->
One thing we do need to be careful of is avoiding returning
let low = Some xhyll' None `plusPositive`
Some xlyhl' None `plusPositive`
Some xlyl None
in if isTrue# (high `eqWord#` 0##)
then low
else Some 0## (Some high None) `plusPositive` low
splitHalves (!x) = (# x `uncheckedShiftRL#` highHalfShift (),
x `and#` lowHalfMask () #)
shiftLPositive :: Positive -> Int# -> Positive
shiftLPositive p i
= if isTrue# (i >=# WORD_SIZE_IN_BITS#)
then shiftLPositive (Some 0## p) (i -# WORD_SIZE_IN_BITS#)
else smallShiftLPositive p i
smallShiftLPositive :: Positive -> Int# -> Positive
smallShiftLPositive (!p) 0# = p
smallShiftLPositive (!p) (!i) =
case WORD_SIZE_IN_BITS# -# i of
j -> let f carry None = if isTrue# (carry `eqWord#` 0##)
then None
else Some carry None
f carry (Some w ws) = case w `uncheckedShiftRL#` j of
carry' ->
case w `uncheckedShiftL#` i of
me ->
Some (me `or#` carry) (f carry' ws)
in f 0## p
shiftRPositive :: Positive -> Int# -> Integer
shiftRPositive None _ = Naught
shiftRPositive p@(Some _ q) i
= if isTrue# (i >=# WORD_SIZE_IN_BITS#)
then shiftRPositive q (i -# WORD_SIZE_IN_BITS#)
else smallShiftRPositive p i
smallShiftRPositive :: Positive -> Int# -> Integer
smallShiftRPositive (!p) (!i) =
if isTrue# (i ==# 0#)
then Positive p
else case smallShiftLPositive p (WORD_SIZE_IN_BITS# -# i) of
Some _ p'@(Some _ _) -> Positive p'
_ -> Naught
quotRemPositive :: Positive -> Positive -> (# Integer, Integer #)
(!xs) `quotRemPositive` (!ys)
= case f xs of
(# d, m #) -> (# digitsMaybeZeroToInteger d,
digitsMaybeZeroToInteger m #)
where
subtractors :: Positives
subtractors = mkSubtractors (WORD_SIZE_IN_BITS# -# 1#)
mkSubtractors (!n) = if isTrue# (n ==# 0#)
then Cons ys Nil
else Cons (ys `smallShiftLPositive` n)
(mkSubtractors (n -# 1#))
The main function . Go the the end of xs , then walk
f :: Positive -> (# Digits, Digits #)
f None = (# None, None #)
f (Some z zs)
= case f zs of
(# ds, m #) ->
We need to avoid making ( Some Zero None ) here
m' = some z m
in case g 0## subtractors m' of
(# d, m'' #) ->
(# some d ds, m'' #)
g :: Digit -> Positives -> Digits -> (# Digit, Digits #)
g (!d) Nil (!m) = (# d, m #)
g (!d) (Cons sub subs) (!m)
= case d `uncheckedShiftL#` 1# of
d' ->
case m `comparePositive` sub of
LT -> g d' subs m
_ -> g (d' `plusWord#` 1##)
subs
(m `minusPositive` sub)
some :: Digit -> Digits -> Digits
some (!w) None = if isTrue# (w `eqWord#` 0##) then None else Some w None
some (!w) (!ws) = Some w ws
andDigits :: Digits -> Digits -> Digits
andDigits None None = None
andDigits (Some {}) None = None
andDigits None (Some {}) = None
andDigits (Some w1 ws1) (Some w2 ws2) = Some (w1 `and#` w2) (andDigits ws1 ws2)
DigitsOnes is just like Digits , only None is really 0xFFFFFFF ... ,
a DigitOnes with a Digits , as the latter will bound the size of the
newtype DigitsOnes = DigitsOnes Digits
andDigitsOnes :: DigitsOnes -> Digits -> Digits
andDigitsOnes (DigitsOnes None) None = None
andDigitsOnes (DigitsOnes None) ws2@(Some {}) = ws2
andDigitsOnes (DigitsOnes (Some {})) None = None
andDigitsOnes (DigitsOnes (Some w1 ws1)) (Some w2 ws2)
= Some (w1 `and#` w2) (andDigitsOnes (DigitsOnes ws1) ws2)
orDigits :: Digits -> Digits -> Digits
orDigits None None = None
orDigits None ds@(Some {}) = ds
orDigits ds@(Some {}) None = ds
orDigits (Some w1 ds1) (Some w2 ds2) = Some (w1 `or#` w2) (orDigits ds1 ds2)
xorDigits :: Digits -> Digits -> Digits
xorDigits None None = None
xorDigits None ds@(Some {}) = ds
xorDigits ds@(Some {}) None = ds
xorDigits (Some w1 ds1) (Some w2 ds2) = Some (w1 `xor#` w2) (xorDigits ds1 ds2)
doubleFromPositive :: Positive -> Double#
doubleFromPositive None = 0.0##
doubleFromPositive (Some w ds)
= case splitHalves w of
(# h, l #) ->
(doubleFromPositive ds *## (2.0## **## WORD_SIZE_IN_BITS_FLOAT##))
+## (int2Double# (word2Int# h) *##
(2.0## **## int2Double# (highHalfShift ())))
+## int2Double# (word2Int# l)
floatFromPositive :: Positive -> Float#
floatFromPositive None = 0.0#
floatFromPositive (Some w ds)
= case splitHalves w of
(# h, l #) ->
(floatFromPositive ds `timesFloat#` (2.0# `powerFloat#` WORD_SIZE_IN_BITS_FLOAT#))
`plusFloat#` (int2Float# (word2Int# h) `timesFloat#`
(2.0# `powerFloat#` int2Float# (highHalfShift ())))
`plusFloat#` int2Float# (word2Int# l)
#endif
Note [ Avoid patError ]
If we use the natural set of definitions for functions , e.g. :
orDigits None ds = ds
orDigits ds None = ds
orDigits ( Some w1 ds1 ) ( Some w2 ds2 ) = Some ... ...
then GHC may not be smart enough ( especially when compiling with -O0 )
to see that all the cases are handled , and will thus insert calls to
base : Control . Exception . . But we are below base in the
package hierarchy , so this causes build failure !
We therefore help GHC out , by being more explicit about what all the
cases are :
orDigits None None = None
orDigits None ds@(Some { } ) = ds
orDigits ds@(Some { } ) None = ds
orDigits ( Some w1 ds1 ) ( Some w2 ds2 ) = Some ... ...
Note [Avoid patError]
If we use the natural set of definitions for functions, e.g.:
orDigits None ds = ds
orDigits ds None = ds
orDigits (Some w1 ds1) (Some w2 ds2) = Some ... ...
then GHC may not be smart enough (especially when compiling with -O0)
to see that all the cases are handled, and will thus insert calls to
base:Control.Exception.Base.patError. But we are below base in the
package hierarchy, so this causes build failure!
We therefore help GHC out, by being more explicit about what all the
cases are:
orDigits None None = None
orDigits None ds@(Some {}) = ds
orDigits ds@(Some {}) None = ds
orDigits (Some w1 ds1) (Some w2 ds2) = Some ... ...
-}
|
2d63249f96bebed4d1fe37bb4dc9f213d74a5f03a9260206682404c749e85503 | zerowidth/hansel | text_interface.clj | (ns hansel.text-interface
(:require [clojure.string :as str])
(:use [hansel.grid :only [neighbors]]))
(defn graph-from-text
"Convert a text represenation of a graph to its node transitions, start point,
and dest point.
text - the text representation of a graph: a = start, z = dest, . = open.
. . . . . # . z
. . . . . # . .
. . # . . # . .
. . # . . . . .
a . # . . . . .
Returns a map with :start, :dest, and :transtions"
[text]
(let [lines (->> text str/split-lines (map #(remove #{\space} %)))
width (count (first lines))
height (count lines)
rows (zipmap (range (count lines)) lines)
map-nodes (apply merge-with into (for [y (range height)
x (range width)
:let [c ((vec (rows y)) x)]
:when (#{\. \a \z} c)]
{c [[x y]]}))
start (first (map-nodes \a))
dest (first (map-nodes \z))
nodes (set (apply concat (vals map-nodes)))]
{:start start
:dest dest
:nodes nodes
:neighbors (partial neighbors (set nodes))}))
| null | https://raw.githubusercontent.com/zerowidth/hansel/9bcac5dcbabc3af6b0378030bcbbb39d69a7331c/src/hansel/text_interface.clj | clojure | (ns hansel.text-interface
(:require [clojure.string :as str])
(:use [hansel.grid :only [neighbors]]))
(defn graph-from-text
"Convert a text represenation of a graph to its node transitions, start point,
and dest point.
text - the text representation of a graph: a = start, z = dest, . = open.
. . . . . # . z
. . . . . # . .
. . # . . # . .
. . # . . . . .
a . # . . . . .
Returns a map with :start, :dest, and :transtions"
[text]
(let [lines (->> text str/split-lines (map #(remove #{\space} %)))
width (count (first lines))
height (count lines)
rows (zipmap (range (count lines)) lines)
map-nodes (apply merge-with into (for [y (range height)
x (range width)
:let [c ((vec (rows y)) x)]
:when (#{\. \a \z} c)]
{c [[x y]]}))
start (first (map-nodes \a))
dest (first (map-nodes \z))
nodes (set (apply concat (vals map-nodes)))]
{:start start
:dest dest
:nodes nodes
:neighbors (partial neighbors (set nodes))}))
|
|
7abeb181fc74b4beab7084657ad69b99f1dc767ec48b772343da58b14b467608 | janestreet/memtrace_viewer | keyboard_scope.mli | open! Core
open Bonsai_web
type t =
{ view : Vdom.Node.t
; key_help : Vdom_keyboard.Help_text.t
}
val wrap : view:Vdom.Node.t -> key_handler:Vdom_keyboard.Keyboard_event_handler.t -> t
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer/46439f8bd16e77c5aa38632c9c4aa53175121d4d/client/src/keyboard_scope.mli | ocaml | open! Core
open Bonsai_web
type t =
{ view : Vdom.Node.t
; key_help : Vdom_keyboard.Help_text.t
}
val wrap : view:Vdom.Node.t -> key_handler:Vdom_keyboard.Keyboard_event_handler.t -> t
|
|
4891c491a38d2d5b9851ccd33af712da60431ff90412a78e02e3ff1b963cf915 | mhallin/graphql_ppx | enum_input.ml | open Test_shared
module MyQuery = [%graphql {|
query ($arg: SampleField!) {
enumInput(arg: $arg)
}
|}]
let encodes_arguments () =
Alcotest.check yojson "json"
(MyQuery.make ~arg:`FIRST ())#variables
(Yojson.Basic.from_string {| { "arg": "FIRST" } |})
let tests = [
"Encodes enum arguments to strings", `Quick, encodes_arguments;
]
| null | https://raw.githubusercontent.com/mhallin/graphql_ppx/5796b3759bdf0d29112f48e43a2f0623f7466e8a/tests_native/enum_input.ml | ocaml | open Test_shared
module MyQuery = [%graphql {|
query ($arg: SampleField!) {
enumInput(arg: $arg)
}
|}]
let encodes_arguments () =
Alcotest.check yojson "json"
(MyQuery.make ~arg:`FIRST ())#variables
(Yojson.Basic.from_string {| { "arg": "FIRST" } |})
let tests = [
"Encodes enum arguments to strings", `Quick, encodes_arguments;
]
|
|
77539d830675547748c5a44de3be92a5e2c35c643bbed44cc0ec95b9ee014d12 | MaskRay/OJHaskell | 131.hs | import Math.Sieve.Factor
main = print $ length $ filter (isPrime sie . f) $ takeWhile ((<=1000000) . f) [1..]
where sie = sieve 1000000
f x = 3*x*x+3*x+1 | null | https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Project%20Euler/131.hs | haskell | import Math.Sieve.Factor
main = print $ length $ filter (isPrime sie . f) $ takeWhile ((<=1000000) . f) [1..]
where sie = sieve 1000000
f x = 3*x*x+3*x+1 |
|
6c3396fdac8084b65e8eb7e4b3115ca102facae1b322bada089ab82592ae1dc1 | clojars/clojars-web | maven.clj | (ns clojars.maven
(:refer-clojure :exclude [parse-long])
(:require
[clojars.file-utils :as fu]
[clojure.edn :as edn]
[clojure.java.io :as io])
(:import
(org.apache.maven.artifact.repository.metadata
Metadata)
(org.apache.maven.artifact.repository.metadata.io.xpp3
MetadataXpp3Reader
MetadataXpp3Writer)
(org.apache.maven.model
License
Model
Scm)
org.apache.maven.model.io.xpp3.MavenXpp3Reader))
(defn without-nil-values
"Prunes a map of pairs that have nil values."
[m]
(reduce (fn [m entry]
(if (nil? (val entry))
m
(conj m entry)))
(empty m) m))
(defn scm-to-map [^Scm scm]
(when scm
(without-nil-values
{:connection (.getConnection scm)
:developer-connection (.getDeveloperConnection scm)
:tag (.getTag scm)
:url (.getUrl scm)})))
(defn license-to-map [^License license]
(without-nil-values
{:name (.getName license)
:url (.getUrl license)
:distribution (.getDistribution license)
:comments (.getComments license)}))
(defn model-to-map [^Model model]
(without-nil-values
{:name (or (.getArtifactId model)
(-> model .getParent .getArtifactId))
:group (or (.getGroupId model)
(-> model .getParent .getGroupId))
:version (or (.getVersion model)
(-> model .getParent .getVersion))
:description (.getDescription model)
:homepage (.getUrl model)
:url (.getUrl model)
:licenses (mapv license-to-map (.getLicenses model))
:scm (scm-to-map (.getScm model))
:authors (mapv #(.getName %) (.getContributors model))
:packaging (keyword (.getPackaging model))
:dependencies (mapv
(fn [d] {:group_name (.getGroupId d)
:jar_name (.getArtifactId d)
:version (or (.getVersion d) "")
:scope (or (.getScope d) "compile")})
(.getDependencies model))}))
(defn read-pom
"Reads a pom file returning a maven Model object."
[file]
(with-open [reader (io/reader file)]
(.read (MavenXpp3Reader.) reader)))
(def pom-to-map (comp model-to-map read-pom))
(defn read-metadata
"Reads a maven-metadata file returning a maven Metadata object."
^Metadata [file]
(with-open [reader (io/reader file)]
(.read (MetadataXpp3Reader.) reader)))
(defn write-metadata
"Writes the given metadata out to a file."
[^Metadata metadata file]
(with-open [writer (io/writer file)]
(.write (MetadataXpp3Writer.) writer metadata)))
(defn snapshot-timestamp-version
[filename]
(second (re-find #"-(\d{8}\.\d{6}-\d+)\." filename)))
(defn parse-long [^String s]
(when s
(Long/parseLong s)))
(defn parse-version
"Parse a Maven-style version number.
The basic format is major[.minor[.increment]][(-|.)(buildNumber|qualifier)]
The major, minor, increment and buildNumber are numeric with leading zeros
disallowed (except plain 0). If the value after the first - is non-numeric
then it is assumed to be a qualifier. If the format does not match then we
just treat the whole thing as a qualifier."
[s]
(let [[match major minor incremental _ _ build-number qualifier]
(re-matches #"(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*))?)?(?:(-|\.)((0|[1-9][0-9]*)|(.*)))?" s)]
(try
(without-nil-values
{:major (parse-long major)
:minor (parse-long minor)
:incremental (parse-long incremental)
:build-number (parse-long build-number)
:qualifier (if match qualifier s)})
(catch NumberFormatException _
{:qualifier s}))))
(defmacro numeric-or
"Evaluates exprs one at a time. Returns the first that returns non-zero."
([x] x)
([x & exprs]
`(let [value# ~x]
(if (zero? value#)
(numeric-or ~@exprs)
value#))))
(defn split-qualifier [s]
(when s
(when-let [[prefix counter suffix] (seq (rest (re-find #"^([^0-9.-]*?)[.-]?([0-9]*)[.-]?([^0-9.-]*?)$" s)))]
(let [to-lower (fn [s]
(when-not (empty? s) (.toLowerCase s)))]
[(to-lower (if (and (empty? prefix)
(empty? counter))
suffix
prefix))
(when-not (empty? counter)
(parse-long counter))
(when-not (and (empty? prefix)
(empty? counter))
(to-lower suffix))]))))
(def common-qualifiers
"common qualifiers in relative sort order"
["alpha" "beta" "cr" "rc" "snapshot" "final" "release"])
(defn compare-qualifier-fraction [x y]
(let [x-value (when (some #{x} common-qualifiers) (.indexOf common-qualifiers x))
y-value (when (some #{y} common-qualifiers) (.indexOf common-qualifiers y))]
(cond
(not (or x-value y-value)) 0 ;; neither are common. no winner
(and x-value (not y-value)) -1 ;; x is known, but y isn't. x wins
(and y-value (not x-value)) 1 ;; y is known, but x isn't. y wins
(< -1 x-value y-value) -1 ;; both fractions are common, x has a lower sort order
(< -1 y-value x-value) 1 ;; both fractions are common, y has a lower sort order
:else 0)))
(defn compare-qualifiers [qx qy]
(let [[qx-prefix qx-counter qx-suffix] (split-qualifier qx)
[qy-prefix qy-counter qy-suffix] (split-qualifier qy)
qx-counter (or qx-counter -1)
qy-counter (or qy-counter -1)]
(if qx
(if qy
(numeric-or
(compare-qualifier-fraction qx-prefix qy-prefix)
(compare qx-counter qy-counter)
(compare-qualifier-fraction qx-suffix qy-suffix)
(cond
(and (> (count qx) (count qy)) (.startsWith qx qy)) -1 ;; x is longer, it's older
(and (< (count qx) (count qy)) (.startsWith qy qx)) 1 ;; y is longer, it's older
:else (compare qx qy))) ;; same length, so string compare
-1) ;; y has no qualifier, it's younger
(if qy
1 ;; x has no qualifier, it's younger
0))) ;; no qualifiers
)
(defn compare-versions
"Compare two maven versions. Accepts either the string or parsed
representation."
[x y]
(let [x (if (string? x) (parse-version x) x)
y (if (string? y) (parse-version y) y)]
(numeric-or
(compare (:major x 0) (:major y 0))
(compare (:minor x 0) (:minor y 0))
(compare (:incremental x 0) (:incremental y 0))
(compare-qualifiers (:qualifier x) (:qualifier y))
(compare (:build-number x 0) (:build-number y 0)))))
(defn snapshot-version? [version]
(.endsWith version "-SNAPSHOT"))
(defn central-metadata
"Read the metadata from maven central for the given artifact."
[group name]
(try
(read-metadata
(format "-metadata.xml" (fu/group->path group) name))
(catch java.io.FileNotFoundException _)))
(defn exists-on-central?*
"Checks if any versions of the given artifact exist on central.
Makes at least one network call on every invocation."
[group-id artifact-id]
(loop [attempt 0]
(let [ret (try
(boolean (central-metadata group-id artifact-id))
(catch Exception _ :failure))]
(if (and
(= ret :failure)
(< attempt 9))
(do
(Thread/sleep (bit-shift-left 1 (inc attempt)))
(recur (inc attempt)))
ret))))
(def exists-on-central?
"Checks if any versions of the given artifact exist on central.
Memoized version of exists-on-central?*."
(memoize exists-on-central?*))
(def shadow-allowlist
(delay (-> "shadow-allowlist.edn" io/resource slurp edn/read-string)))
(defn can-shadow-maven? [group-id artifact-id]
(contains? @shadow-allowlist
(symbol (format "%s/%s" group-id artifact-id))))
| null | https://raw.githubusercontent.com/clojars/clojars-web/22f831c9e8749ac7933af48655764ad5f5bdc3e8/src/clojars/maven.clj | clojure | neither are common. no winner
x is known, but y isn't. x wins
y is known, but x isn't. y wins
both fractions are common, x has a lower sort order
both fractions are common, y has a lower sort order
x is longer, it's older
y is longer, it's older
same length, so string compare
y has no qualifier, it's younger
x has no qualifier, it's younger
no qualifiers | (ns clojars.maven
(:refer-clojure :exclude [parse-long])
(:require
[clojars.file-utils :as fu]
[clojure.edn :as edn]
[clojure.java.io :as io])
(:import
(org.apache.maven.artifact.repository.metadata
Metadata)
(org.apache.maven.artifact.repository.metadata.io.xpp3
MetadataXpp3Reader
MetadataXpp3Writer)
(org.apache.maven.model
License
Model
Scm)
org.apache.maven.model.io.xpp3.MavenXpp3Reader))
(defn without-nil-values
"Prunes a map of pairs that have nil values."
[m]
(reduce (fn [m entry]
(if (nil? (val entry))
m
(conj m entry)))
(empty m) m))
(defn scm-to-map [^Scm scm]
(when scm
(without-nil-values
{:connection (.getConnection scm)
:developer-connection (.getDeveloperConnection scm)
:tag (.getTag scm)
:url (.getUrl scm)})))
(defn license-to-map [^License license]
(without-nil-values
{:name (.getName license)
:url (.getUrl license)
:distribution (.getDistribution license)
:comments (.getComments license)}))
(defn model-to-map [^Model model]
(without-nil-values
{:name (or (.getArtifactId model)
(-> model .getParent .getArtifactId))
:group (or (.getGroupId model)
(-> model .getParent .getGroupId))
:version (or (.getVersion model)
(-> model .getParent .getVersion))
:description (.getDescription model)
:homepage (.getUrl model)
:url (.getUrl model)
:licenses (mapv license-to-map (.getLicenses model))
:scm (scm-to-map (.getScm model))
:authors (mapv #(.getName %) (.getContributors model))
:packaging (keyword (.getPackaging model))
:dependencies (mapv
(fn [d] {:group_name (.getGroupId d)
:jar_name (.getArtifactId d)
:version (or (.getVersion d) "")
:scope (or (.getScope d) "compile")})
(.getDependencies model))}))
(defn read-pom
"Reads a pom file returning a maven Model object."
[file]
(with-open [reader (io/reader file)]
(.read (MavenXpp3Reader.) reader)))
(def pom-to-map (comp model-to-map read-pom))
(defn read-metadata
"Reads a maven-metadata file returning a maven Metadata object."
^Metadata [file]
(with-open [reader (io/reader file)]
(.read (MetadataXpp3Reader.) reader)))
(defn write-metadata
"Writes the given metadata out to a file."
[^Metadata metadata file]
(with-open [writer (io/writer file)]
(.write (MetadataXpp3Writer.) writer metadata)))
(defn snapshot-timestamp-version
[filename]
(second (re-find #"-(\d{8}\.\d{6}-\d+)\." filename)))
(defn parse-long [^String s]
(when s
(Long/parseLong s)))
(defn parse-version
"Parse a Maven-style version number.
The basic format is major[.minor[.increment]][(-|.)(buildNumber|qualifier)]
The major, minor, increment and buildNumber are numeric with leading zeros
disallowed (except plain 0). If the value after the first - is non-numeric
then it is assumed to be a qualifier. If the format does not match then we
just treat the whole thing as a qualifier."
[s]
(let [[match major minor incremental _ _ build-number qualifier]
(re-matches #"(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*))?)?(?:(-|\.)((0|[1-9][0-9]*)|(.*)))?" s)]
(try
(without-nil-values
{:major (parse-long major)
:minor (parse-long minor)
:incremental (parse-long incremental)
:build-number (parse-long build-number)
:qualifier (if match qualifier s)})
(catch NumberFormatException _
{:qualifier s}))))
(defmacro numeric-or
"Evaluates exprs one at a time. Returns the first that returns non-zero."
([x] x)
([x & exprs]
`(let [value# ~x]
(if (zero? value#)
(numeric-or ~@exprs)
value#))))
(defn split-qualifier [s]
(when s
(when-let [[prefix counter suffix] (seq (rest (re-find #"^([^0-9.-]*?)[.-]?([0-9]*)[.-]?([^0-9.-]*?)$" s)))]
(let [to-lower (fn [s]
(when-not (empty? s) (.toLowerCase s)))]
[(to-lower (if (and (empty? prefix)
(empty? counter))
suffix
prefix))
(when-not (empty? counter)
(parse-long counter))
(when-not (and (empty? prefix)
(empty? counter))
(to-lower suffix))]))))
(def common-qualifiers
"common qualifiers in relative sort order"
["alpha" "beta" "cr" "rc" "snapshot" "final" "release"])
(defn compare-qualifier-fraction [x y]
(let [x-value (when (some #{x} common-qualifiers) (.indexOf common-qualifiers x))
y-value (when (some #{y} common-qualifiers) (.indexOf common-qualifiers y))]
(cond
:else 0)))
(defn compare-qualifiers [qx qy]
(let [[qx-prefix qx-counter qx-suffix] (split-qualifier qx)
[qy-prefix qy-counter qy-suffix] (split-qualifier qy)
qx-counter (or qx-counter -1)
qy-counter (or qy-counter -1)]
(if qx
(if qy
(numeric-or
(compare-qualifier-fraction qx-prefix qy-prefix)
(compare qx-counter qy-counter)
(compare-qualifier-fraction qx-suffix qy-suffix)
(cond
(if qy
)
(defn compare-versions
"Compare two maven versions. Accepts either the string or parsed
representation."
[x y]
(let [x (if (string? x) (parse-version x) x)
y (if (string? y) (parse-version y) y)]
(numeric-or
(compare (:major x 0) (:major y 0))
(compare (:minor x 0) (:minor y 0))
(compare (:incremental x 0) (:incremental y 0))
(compare-qualifiers (:qualifier x) (:qualifier y))
(compare (:build-number x 0) (:build-number y 0)))))
(defn snapshot-version? [version]
(.endsWith version "-SNAPSHOT"))
(defn central-metadata
"Read the metadata from maven central for the given artifact."
[group name]
(try
(read-metadata
(format "-metadata.xml" (fu/group->path group) name))
(catch java.io.FileNotFoundException _)))
(defn exists-on-central?*
"Checks if any versions of the given artifact exist on central.
Makes at least one network call on every invocation."
[group-id artifact-id]
(loop [attempt 0]
(let [ret (try
(boolean (central-metadata group-id artifact-id))
(catch Exception _ :failure))]
(if (and
(= ret :failure)
(< attempt 9))
(do
(Thread/sleep (bit-shift-left 1 (inc attempt)))
(recur (inc attempt)))
ret))))
(def exists-on-central?
"Checks if any versions of the given artifact exist on central.
Memoized version of exists-on-central?*."
(memoize exists-on-central?*))
(def shadow-allowlist
(delay (-> "shadow-allowlist.edn" io/resource slurp edn/read-string)))
(defn can-shadow-maven? [group-id artifact-id]
(contains? @shadow-allowlist
(symbol (format "%s/%s" group-id artifact-id))))
|
574caaf562bdb3dcca896123bc4f65f13253ff883ee59b38ed95c4377916c553 | lsrcz/grisette | InternedCtors.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
-- |
Module : . IR.SymPrim . Data . Prim . InternedTerm . InternedCtors
Copyright : ( c ) 2021 - 2023
-- License : BSD-3-Clause (see the LICENSE file)
--
-- Maintainer :
-- Stability : Experimental
Portability : GHC only
module Grisette.IR.SymPrim.Data.Prim.InternedTerm.InternedCtors
( constructUnary,
constructBinary,
constructTernary,
conTerm,
symTerm,
ssymTerm,
isymTerm,
sinfosymTerm,
iinfosymTerm,
notTerm,
orTerm,
andTerm,
eqvTerm,
iteTerm,
addNumTerm,
uminusNumTerm,
timesNumTerm,
absNumTerm,
signumNumTerm,
ltNumTerm,
leNumTerm,
andBitsTerm,
orBitsTerm,
xorBitsTerm,
complementBitsTerm,
shiftBitsTerm,
rotateBitsTerm,
bvconcatTerm,
bvselectTerm,
bvextendTerm,
bvsignExtendTerm,
bvzeroExtendTerm,
tabularFunApplyTerm,
generalFunApplyTerm,
divIntegralTerm,
modIntegralTerm,
quotIntegralTerm,
remIntegralTerm,
divBoundedIntegralTerm,
modBoundedIntegralTerm,
quotBoundedIntegralTerm,
remBoundedIntegralTerm,
)
where
import Control.DeepSeq
import Data.Array
import Data.Bits
import qualified Data.HashMap.Strict as M
import Data.Hashable
import Data.IORef (atomicModifyIORef')
import Data.Interned
import Data.Interned.Internal
import GHC.IO (unsafeDupablePerformIO)
import GHC.TypeNats
import Grisette.Core.Data.Class.BitVector
import Grisette.IR.SymPrim.Data.Prim.InternedTerm.Term
import {-# SOURCE #-} Grisette.IR.SymPrim.Data.TabularFun
import Language.Haskell.TH.Syntax
import Type.Reflection
internTerm :: forall t. (SupportedPrim t) => Uninterned (Term t) -> Term t
internTerm !bt = unsafeDupablePerformIO $ atomicModifyIORef' slot go
where
slot = getCache cache ! r
!dt = describe bt
!hdt = hash dt
!wid = cacheWidth dt
r = hdt `mod` wid
go (CacheState i m) = case M.lookup dt m of
Nothing -> let t = identify (wid * i + r) bt in (CacheState (i + 1) (M.insert dt t m), t)
Just t -> (CacheState i m, t)
constructUnary ::
forall tag arg t.
(SupportedPrim t, UnaryOp tag arg t, Typeable tag, Typeable t, Show tag) =>
tag ->
Term arg ->
Term t
constructUnary tag tm = let x = internTerm $ UUnaryTerm tag tm in x
# INLINE constructUnary #
constructBinary ::
forall tag arg1 arg2 t.
(SupportedPrim t, BinaryOp tag arg1 arg2 t, Typeable tag, Typeable t, Show tag) =>
tag ->
Term arg1 ->
Term arg2 ->
Term t
constructBinary tag tm1 tm2 = internTerm $ UBinaryTerm tag tm1 tm2
# INLINE constructBinary #
constructTernary ::
forall tag arg1 arg2 arg3 t.
(SupportedPrim t, TernaryOp tag arg1 arg2 arg3 t, Typeable tag, Typeable t, Show tag) =>
tag ->
Term arg1 ->
Term arg2 ->
Term arg3 ->
Term t
constructTernary tag tm1 tm2 tm3 = internTerm $ UTernaryTerm tag tm1 tm2 tm3
# INLINE constructTernary #
conTerm :: (SupportedPrim t, Typeable t, Hashable t, Eq t, Show t) => t -> Term t
conTerm t = internTerm $ UConTerm t
# INLINE conTerm #
symTerm :: forall t. (SupportedPrim t, Typeable t) => TypedSymbol t -> Term t
symTerm t = internTerm $ USymTerm t
# INLINE symTerm #
ssymTerm :: (SupportedPrim t, Typeable t) => String -> Term t
ssymTerm = symTerm . SimpleSymbol
# INLINE ssymTerm #
isymTerm :: (SupportedPrim t, Typeable t) => String -> Int -> Term t
isymTerm str idx = symTerm $ IndexedSymbol str idx
# INLINE isymTerm #
sinfosymTerm ::
(SupportedPrim t, Typeable t, Typeable a, Ord a, Lift a, NFData a, Show a, Hashable a) =>
String ->
a ->
Term t
sinfosymTerm s info = symTerm $ WithInfo (SimpleSymbol s) info
# INLINE sinfosymTerm #
iinfosymTerm ::
(SupportedPrim t, Typeable t, Typeable a, Ord a, Lift a, NFData a, Show a, Hashable a) =>
String ->
Int ->
a ->
Term t
iinfosymTerm str idx info = symTerm $ WithInfo (IndexedSymbol str idx) info
# INLINE iinfosymTerm #
notTerm :: Term Bool -> Term Bool
notTerm = internTerm . UNotTerm
# INLINE notTerm #
orTerm :: Term Bool -> Term Bool -> Term Bool
orTerm l r = internTerm $ UOrTerm l r
# INLINE orTerm #
andTerm :: Term Bool -> Term Bool -> Term Bool
andTerm l r = internTerm $ UAndTerm l r
# INLINE andTerm #
eqvTerm :: SupportedPrim a => Term a -> Term a -> Term Bool
eqvTerm l r = internTerm $ UEqvTerm l r
# INLINE eqvTerm #
iteTerm :: SupportedPrim a => Term Bool -> Term a -> Term a -> Term a
iteTerm c l r = internTerm $ UITETerm c l r
{-# INLINE iteTerm #-}
addNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a -> Term a
addNumTerm l r = internTerm $ UAddNumTerm l r
# INLINE addNumTerm #
uminusNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a
uminusNumTerm = internTerm . UUMinusNumTerm
# INLINE uminusNumTerm #
timesNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a -> Term a
timesNumTerm l r = internTerm $ UTimesNumTerm l r
# INLINE timesNumTerm #
absNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a
absNumTerm = internTerm . UAbsNumTerm
# INLINE absNumTerm #
signumNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a
signumNumTerm = internTerm . USignumNumTerm
{-# INLINE signumNumTerm #-}
ltNumTerm :: (SupportedPrim a, Num a, Ord a) => Term a -> Term a -> Term Bool
ltNumTerm l r = internTerm $ ULTNumTerm l r
# INLINE ltNumTerm #
leNumTerm :: (SupportedPrim a, Num a, Ord a) => Term a -> Term a -> Term Bool
leNumTerm l r = internTerm $ ULENumTerm l r
# INLINE leNumTerm #
andBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a -> Term a
andBitsTerm l r = internTerm $ UAndBitsTerm l r
# INLINE andBitsTerm #
orBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a -> Term a
orBitsTerm l r = internTerm $ UOrBitsTerm l r
# INLINE orBitsTerm #
xorBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a -> Term a
xorBitsTerm l r = internTerm $ UXorBitsTerm l r
# INLINE xorBitsTerm #
complementBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a
complementBitsTerm = internTerm . UComplementBitsTerm
# INLINE complementBitsTerm #
shiftBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Int -> Term a
shiftBitsTerm t n = internTerm $ UShiftBitsTerm t n
# INLINE shiftBitsTerm #
rotateBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Int -> Term a
rotateBitsTerm t n = internTerm $ URotateBitsTerm t n
# INLINE rotateBitsTerm #
bvconcatTerm ::
( SupportedPrim (bv a),
SupportedPrim (bv b),
SupportedPrim (bv (a + b)),
KnownNat a,
KnownNat b,
1 <= a,
1 <= b,
SizedBV bv
) =>
Term (bv a) ->
Term (bv b) ->
Term (bv (a + b))
bvconcatTerm l r = internTerm $ UBVConcatTerm l r
# INLINE bvconcatTerm #
bvselectTerm ::
forall bv n ix w proxy.
( SupportedPrim (bv n),
SupportedPrim (bv w),
KnownNat n,
KnownNat ix,
KnownNat w,
1 <= n,
1 <= w,
ix + w <= n,
SizedBV bv
) =>
proxy ix ->
proxy w ->
Term (bv n) ->
Term (bv w)
bvselectTerm _ _ v = internTerm $ UBVSelectTerm (typeRep @ix) (typeRep @w) v
# INLINE bvselectTerm #
bvextendTerm ::
forall bv l r proxy.
( SupportedPrim (bv l),
SupportedPrim (bv r),
KnownNat l,
KnownNat r,
1 <= l,
l <= r,
SizedBV bv
) =>
Bool ->
proxy r ->
Term (bv l) ->
Term (bv r)
bvextendTerm signed _ v = internTerm $ UBVExtendTerm signed (typeRep @r) v
# INLINE bvextendTerm #
bvsignExtendTerm ::
forall bv l r proxy.
( SupportedPrim (bv l),
SupportedPrim (bv r),
KnownNat l,
KnownNat r,
1 <= l,
l <= r,
SizedBV bv
) =>
proxy r ->
Term (bv l) ->
Term (bv r)
bvsignExtendTerm _ v = internTerm $ UBVExtendTerm True (typeRep @r) v
# INLINE bvsignExtendTerm #
bvzeroExtendTerm ::
forall bv l r proxy.
( SupportedPrim (bv l),
SupportedPrim (bv r),
KnownNat l,
KnownNat r,
1 <= l,
l <= r,
SizedBV bv
) =>
proxy r ->
Term (bv l) ->
Term (bv r)
bvzeroExtendTerm _ v = internTerm $ UBVExtendTerm False (typeRep @r) v
# INLINE bvzeroExtendTerm #
tabularFunApplyTerm :: (SupportedPrim a, SupportedPrim b) => Term (a =-> b) -> Term a -> Term b
tabularFunApplyTerm f a = internTerm $ UTabularFunApplyTerm f a
# INLINE tabularFunApplyTerm #
generalFunApplyTerm :: (SupportedPrim a, SupportedPrim b) => Term (a --> b) -> Term a -> Term b
generalFunApplyTerm f a = internTerm $ UGeneralFunApplyTerm f a
# INLINE generalFunApplyTerm #
divIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
divIntegralTerm l r = internTerm $ UDivIntegralTerm l r
# INLINE divIntegralTerm #
modIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
modIntegralTerm l r = internTerm $ UModIntegralTerm l r
# INLINE modIntegralTerm #
quotIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
quotIntegralTerm l r = internTerm $ UQuotIntegralTerm l r
# INLINE quotIntegralTerm #
remIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
remIntegralTerm l r = internTerm $ URemIntegralTerm l r
# INLINE remIntegralTerm #
divBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
divBoundedIntegralTerm l r = internTerm $ UDivBoundedIntegralTerm l r
# INLINE divBoundedIntegralTerm #
modBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
modBoundedIntegralTerm l r = internTerm $ UModBoundedIntegralTerm l r
# INLINE modBoundedIntegralTerm #
quotBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
quotBoundedIntegralTerm l r = internTerm $ UQuotBoundedIntegralTerm l r
# INLINE quotBoundedIntegralTerm #
remBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
remBoundedIntegralTerm l r = internTerm $ URemBoundedIntegralTerm l r
# INLINE remBoundedIntegralTerm #
| null | https://raw.githubusercontent.com/lsrcz/grisette/1d2fab89acb160ee263a41741454a5825094bd33/src/Grisette/IR/SymPrim/Data/Prim/InternedTerm/InternedCtors.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
|
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : Experimental
# SOURCE #
# INLINE iteTerm #
# INLINE signumNumTerm #
> b) -> Term a -> Term b | # LANGUAGE DataKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
Module : . IR.SymPrim . Data . Prim . InternedTerm . InternedCtors
Copyright : ( c ) 2021 - 2023
Portability : GHC only
module Grisette.IR.SymPrim.Data.Prim.InternedTerm.InternedCtors
( constructUnary,
constructBinary,
constructTernary,
conTerm,
symTerm,
ssymTerm,
isymTerm,
sinfosymTerm,
iinfosymTerm,
notTerm,
orTerm,
andTerm,
eqvTerm,
iteTerm,
addNumTerm,
uminusNumTerm,
timesNumTerm,
absNumTerm,
signumNumTerm,
ltNumTerm,
leNumTerm,
andBitsTerm,
orBitsTerm,
xorBitsTerm,
complementBitsTerm,
shiftBitsTerm,
rotateBitsTerm,
bvconcatTerm,
bvselectTerm,
bvextendTerm,
bvsignExtendTerm,
bvzeroExtendTerm,
tabularFunApplyTerm,
generalFunApplyTerm,
divIntegralTerm,
modIntegralTerm,
quotIntegralTerm,
remIntegralTerm,
divBoundedIntegralTerm,
modBoundedIntegralTerm,
quotBoundedIntegralTerm,
remBoundedIntegralTerm,
)
where
import Control.DeepSeq
import Data.Array
import Data.Bits
import qualified Data.HashMap.Strict as M
import Data.Hashable
import Data.IORef (atomicModifyIORef')
import Data.Interned
import Data.Interned.Internal
import GHC.IO (unsafeDupablePerformIO)
import GHC.TypeNats
import Grisette.Core.Data.Class.BitVector
import Grisette.IR.SymPrim.Data.Prim.InternedTerm.Term
import Language.Haskell.TH.Syntax
import Type.Reflection
internTerm :: forall t. (SupportedPrim t) => Uninterned (Term t) -> Term t
internTerm !bt = unsafeDupablePerformIO $ atomicModifyIORef' slot go
where
slot = getCache cache ! r
!dt = describe bt
!hdt = hash dt
!wid = cacheWidth dt
r = hdt `mod` wid
go (CacheState i m) = case M.lookup dt m of
Nothing -> let t = identify (wid * i + r) bt in (CacheState (i + 1) (M.insert dt t m), t)
Just t -> (CacheState i m, t)
constructUnary ::
forall tag arg t.
(SupportedPrim t, UnaryOp tag arg t, Typeable tag, Typeable t, Show tag) =>
tag ->
Term arg ->
Term t
constructUnary tag tm = let x = internTerm $ UUnaryTerm tag tm in x
# INLINE constructUnary #
constructBinary ::
forall tag arg1 arg2 t.
(SupportedPrim t, BinaryOp tag arg1 arg2 t, Typeable tag, Typeable t, Show tag) =>
tag ->
Term arg1 ->
Term arg2 ->
Term t
constructBinary tag tm1 tm2 = internTerm $ UBinaryTerm tag tm1 tm2
# INLINE constructBinary #
constructTernary ::
forall tag arg1 arg2 arg3 t.
(SupportedPrim t, TernaryOp tag arg1 arg2 arg3 t, Typeable tag, Typeable t, Show tag) =>
tag ->
Term arg1 ->
Term arg2 ->
Term arg3 ->
Term t
constructTernary tag tm1 tm2 tm3 = internTerm $ UTernaryTerm tag tm1 tm2 tm3
# INLINE constructTernary #
conTerm :: (SupportedPrim t, Typeable t, Hashable t, Eq t, Show t) => t -> Term t
conTerm t = internTerm $ UConTerm t
# INLINE conTerm #
symTerm :: forall t. (SupportedPrim t, Typeable t) => TypedSymbol t -> Term t
symTerm t = internTerm $ USymTerm t
# INLINE symTerm #
ssymTerm :: (SupportedPrim t, Typeable t) => String -> Term t
ssymTerm = symTerm . SimpleSymbol
# INLINE ssymTerm #
isymTerm :: (SupportedPrim t, Typeable t) => String -> Int -> Term t
isymTerm str idx = symTerm $ IndexedSymbol str idx
# INLINE isymTerm #
sinfosymTerm ::
(SupportedPrim t, Typeable t, Typeable a, Ord a, Lift a, NFData a, Show a, Hashable a) =>
String ->
a ->
Term t
sinfosymTerm s info = symTerm $ WithInfo (SimpleSymbol s) info
# INLINE sinfosymTerm #
iinfosymTerm ::
(SupportedPrim t, Typeable t, Typeable a, Ord a, Lift a, NFData a, Show a, Hashable a) =>
String ->
Int ->
a ->
Term t
iinfosymTerm str idx info = symTerm $ WithInfo (IndexedSymbol str idx) info
# INLINE iinfosymTerm #
notTerm :: Term Bool -> Term Bool
notTerm = internTerm . UNotTerm
# INLINE notTerm #
orTerm :: Term Bool -> Term Bool -> Term Bool
orTerm l r = internTerm $ UOrTerm l r
# INLINE orTerm #
andTerm :: Term Bool -> Term Bool -> Term Bool
andTerm l r = internTerm $ UAndTerm l r
# INLINE andTerm #
eqvTerm :: SupportedPrim a => Term a -> Term a -> Term Bool
eqvTerm l r = internTerm $ UEqvTerm l r
# INLINE eqvTerm #
iteTerm :: SupportedPrim a => Term Bool -> Term a -> Term a -> Term a
iteTerm c l r = internTerm $ UITETerm c l r
addNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a -> Term a
addNumTerm l r = internTerm $ UAddNumTerm l r
# INLINE addNumTerm #
uminusNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a
uminusNumTerm = internTerm . UUMinusNumTerm
# INLINE uminusNumTerm #
timesNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a -> Term a
timesNumTerm l r = internTerm $ UTimesNumTerm l r
# INLINE timesNumTerm #
absNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a
absNumTerm = internTerm . UAbsNumTerm
# INLINE absNumTerm #
signumNumTerm :: (SupportedPrim a, Num a) => Term a -> Term a
signumNumTerm = internTerm . USignumNumTerm
ltNumTerm :: (SupportedPrim a, Num a, Ord a) => Term a -> Term a -> Term Bool
ltNumTerm l r = internTerm $ ULTNumTerm l r
# INLINE ltNumTerm #
leNumTerm :: (SupportedPrim a, Num a, Ord a) => Term a -> Term a -> Term Bool
leNumTerm l r = internTerm $ ULENumTerm l r
# INLINE leNumTerm #
andBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a -> Term a
andBitsTerm l r = internTerm $ UAndBitsTerm l r
# INLINE andBitsTerm #
orBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a -> Term a
orBitsTerm l r = internTerm $ UOrBitsTerm l r
# INLINE orBitsTerm #
xorBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a -> Term a
xorBitsTerm l r = internTerm $ UXorBitsTerm l r
# INLINE xorBitsTerm #
complementBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Term a
complementBitsTerm = internTerm . UComplementBitsTerm
# INLINE complementBitsTerm #
shiftBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Int -> Term a
shiftBitsTerm t n = internTerm $ UShiftBitsTerm t n
# INLINE shiftBitsTerm #
rotateBitsTerm :: (SupportedPrim a, Bits a) => Term a -> Int -> Term a
rotateBitsTerm t n = internTerm $ URotateBitsTerm t n
# INLINE rotateBitsTerm #
bvconcatTerm ::
( SupportedPrim (bv a),
SupportedPrim (bv b),
SupportedPrim (bv (a + b)),
KnownNat a,
KnownNat b,
1 <= a,
1 <= b,
SizedBV bv
) =>
Term (bv a) ->
Term (bv b) ->
Term (bv (a + b))
bvconcatTerm l r = internTerm $ UBVConcatTerm l r
# INLINE bvconcatTerm #
bvselectTerm ::
forall bv n ix w proxy.
( SupportedPrim (bv n),
SupportedPrim (bv w),
KnownNat n,
KnownNat ix,
KnownNat w,
1 <= n,
1 <= w,
ix + w <= n,
SizedBV bv
) =>
proxy ix ->
proxy w ->
Term (bv n) ->
Term (bv w)
bvselectTerm _ _ v = internTerm $ UBVSelectTerm (typeRep @ix) (typeRep @w) v
# INLINE bvselectTerm #
bvextendTerm ::
forall bv l r proxy.
( SupportedPrim (bv l),
SupportedPrim (bv r),
KnownNat l,
KnownNat r,
1 <= l,
l <= r,
SizedBV bv
) =>
Bool ->
proxy r ->
Term (bv l) ->
Term (bv r)
bvextendTerm signed _ v = internTerm $ UBVExtendTerm signed (typeRep @r) v
# INLINE bvextendTerm #
bvsignExtendTerm ::
forall bv l r proxy.
( SupportedPrim (bv l),
SupportedPrim (bv r),
KnownNat l,
KnownNat r,
1 <= l,
l <= r,
SizedBV bv
) =>
proxy r ->
Term (bv l) ->
Term (bv r)
bvsignExtendTerm _ v = internTerm $ UBVExtendTerm True (typeRep @r) v
# INLINE bvsignExtendTerm #
bvzeroExtendTerm ::
forall bv l r proxy.
( SupportedPrim (bv l),
SupportedPrim (bv r),
KnownNat l,
KnownNat r,
1 <= l,
l <= r,
SizedBV bv
) =>
proxy r ->
Term (bv l) ->
Term (bv r)
bvzeroExtendTerm _ v = internTerm $ UBVExtendTerm False (typeRep @r) v
# INLINE bvzeroExtendTerm #
tabularFunApplyTerm :: (SupportedPrim a, SupportedPrim b) => Term (a =-> b) -> Term a -> Term b
tabularFunApplyTerm f a = internTerm $ UTabularFunApplyTerm f a
# INLINE tabularFunApplyTerm #
generalFunApplyTerm f a = internTerm $ UGeneralFunApplyTerm f a
# INLINE generalFunApplyTerm #
divIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
divIntegralTerm l r = internTerm $ UDivIntegralTerm l r
# INLINE divIntegralTerm #
modIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
modIntegralTerm l r = internTerm $ UModIntegralTerm l r
# INLINE modIntegralTerm #
quotIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
quotIntegralTerm l r = internTerm $ UQuotIntegralTerm l r
# INLINE quotIntegralTerm #
remIntegralTerm :: (SupportedPrim a, Integral a) => Term a -> Term a -> Term a
remIntegralTerm l r = internTerm $ URemIntegralTerm l r
# INLINE remIntegralTerm #
divBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
divBoundedIntegralTerm l r = internTerm $ UDivBoundedIntegralTerm l r
# INLINE divBoundedIntegralTerm #
modBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
modBoundedIntegralTerm l r = internTerm $ UModBoundedIntegralTerm l r
# INLINE modBoundedIntegralTerm #
quotBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
quotBoundedIntegralTerm l r = internTerm $ UQuotBoundedIntegralTerm l r
# INLINE quotBoundedIntegralTerm #
remBoundedIntegralTerm :: (SupportedPrim a, Bounded a, Integral a) => Term a -> Term a -> Term a
remBoundedIntegralTerm l r = internTerm $ URemBoundedIntegralTerm l r
# INLINE remBoundedIntegralTerm #
|
84f2dd3569a7a070cc694a5530c62ce8ed992bb38fdc7c80f4ac3a95c171ee1c | ocaml/ocaml-lsp | import.ml | All modules from [ ] should be in the struct below . The modules are
listed alphabetically . Try to keep the order .
listed alphabetically. Try to keep the order. *)
include struct
open Stdune
module Array = struct
include Array
let common_prefix_len ~equal (a : 'a array) (b : 'a array) : int =
let i = ref 0 in
let min_len = min (Array.length a) (Array.length b) in
while !i < min_len && equal (Array.get a !i) (Array.get b !i) do
incr i
done;
!i
end
module Code_error = Code_error
module Comparable = Comparable
module Exn_with_backtrace = Exn_with_backtrace
module Fdecl = Fdecl
module Fpath = Path
module Int = Int
module List = List
module Map = Map
module Monoid = Monoid
module Option = Option
module Ordering = Ordering
module Pid = Pid
module Poly = Poly
module Result = Result
module Queue = Queue
module String = struct
include String
let findi =
let rec loop s len ~f i =
if i >= len then None
else if f (String.unsafe_get s i) then Some i
else loop s len ~f (i + 1)
in
fun ?from s ~f ->
let len = String.length s in
let from =
match from with
| None -> 0
| Some i ->
if i > len - 1 then Code_error.raise "findi: invalid from" [] else i
in
loop s len ~f from
let rfindi =
let rec loop s ~f i =
if i < 0 then None
else if f (String.unsafe_get s i) then Some i
else loop s ~f (i - 1)
in
fun ?from s ~f ->
let from =
let len = String.length s in
match from with
| None -> len - 1
| Some i ->
if i > len - 1 then Code_error.raise "rfindi: invalid from" []
else i
in
loop s ~f from
end
module Table = Table
module Tuple = Tuple
module Unix_env = Env
module Io = Io
let sprintf = sprintf
end
(* All modules from [Lsp] should be in the struct below. The modules are listed
alphabetically. Try to keep the order. *)
include struct
open Lsp
module Client_notification = Client_notification
module Client_request = Client_request
module Server_request = Server_request
module Text_document = Text_document
module Uri = struct
include Uri
let to_dyn t = Dyn.string (to_string t)
end
end
(* Misc modules *)
module Drpc = Dune_rpc.V1
(* OCaml frontend *)
module Ast_iterator = Ocaml_parsing.Ast_iterator
module Asttypes = Ocaml_parsing.Asttypes
module Cmt_format = Ocaml_typing.Cmt_format
module Ident = Ocaml_typing.Ident
module Env = Ocaml_typing.Env
module Loc = struct
module T = struct
include Ocaml_parsing.Location
include Ocaml_parsing.Location_aux
end
include T
module Map = Map.Make (struct
include T
let compare x x' = Ordering.of_int (compare x x')
let position_to_dyn (pos : Lexing.position) =
Dyn.Record
[ ("pos_fname", Dyn.String pos.pos_fname)
; ("pos_lnum", Dyn.Int pos.pos_lnum)
; ("pos_bol", Dyn.Int pos.pos_bol)
; ("pos_cnum", Dyn.Int pos.pos_cnum)
]
let to_dyn loc =
Dyn.Record
[ ("loc_start", position_to_dyn loc.loc_start)
; ("loc_end", position_to_dyn loc.loc_end)
; ("loc_ghost", Dyn.Bool loc.loc_ghost)
]
end)
end
module Longident = Ocaml_parsing.Longident
module Parsetree = Ocaml_parsing.Parsetree
module Path = Ocaml_typing.Path
module Pprintast = Ocaml_parsing.Pprintast
module Typedtree = Ocaml_typing.Typedtree
module Types = Ocaml_typing.Types
module Warnings = Ocaml_utils.Warnings
module Mconfig = Merlin_kernel.Mconfig
module Msource = Merlin_kernel.Msource
module Mbrowse = Merlin_kernel.Mbrowse
module Mpipeline = Merlin_kernel.Mpipeline
module Mreader = Merlin_kernel.Mreader
module Mtyper = Merlin_kernel.Mtyper
module Browse_raw = Merlin_specific.Browse_raw
(* All modules from [Lsp_fiber] should be in the struct below. The modules are
listed alphabetically. Try to keep the order. *)
include struct
open Lsp_fiber
module Log = Private.Log
module Reply = Rpc.Reply
module Server = Server
module Lazy_fiber = Lsp_fiber.Lazy_fiber
module Json = Json
end
(* All modules from [Lsp.Types] should be in the struct below. The modules are
listed alphabetically. Try to keep the order. *)
include struct
open Lsp.Types
module ClientCapabilities = struct
include ClientCapabilities
let markdown_support (client_capabilities : ClientCapabilities.t) ~field =
match client_capabilities.textDocument with
| None -> false
| Some td -> (
match field td with
| None -> false
| Some format ->
let set = Option.value format ~default:[ MarkupKind.Markdown ] in
List.mem set MarkupKind.Markdown ~equal:Poly.equal)
end
module CodeAction = CodeAction
module CodeActionKind = CodeActionKind
module CodeActionOptions = CodeActionOptions
module CodeActionParams = CodeActionParams
module CodeActionResult = CodeActionResult
module CodeActionRegistrationOptions = CodeActionRegistrationOptions
module CodeLens = CodeLens
module CodeLensOptions = CodeLensOptions
module CodeLensParams = CodeLensParams
module Command = Command
module CompletionItem = CompletionItem
module CompletionItemKind = CompletionItemKind
module CompletionList = CompletionList
module CompletionOptions = CompletionOptions
module CompletionParams = CompletionParams
module ConfigurationParams = ConfigurationParams
module CreateFile = CreateFile
module Diagnostic = Diagnostic
module DiagnosticRelatedInformation = DiagnosticRelatedInformation
module DiagnosticSeverity = DiagnosticSeverity
module DiagnosticTag = DiagnosticTag
module DidChangeConfigurationParams = DidChangeConfigurationParams
module DidChangeWorkspaceFoldersParams = DidChangeWorkspaceFoldersParams
module DidOpenTextDocumentParams = DidOpenTextDocumentParams
module Diff = Lsp.Diff
module DocumentFilter = DocumentFilter
module DocumentHighlight = DocumentHighlight
module DocumentHighlightKind = DocumentHighlightKind
module DocumentHighlightParams = DocumentHighlightParams
module DocumentSymbol = DocumentSymbol
module DocumentUri = DocumentUri
module ExecuteCommandOptions = ExecuteCommandOptions
module ExecuteCommandParams = ExecuteCommandParams
module FoldingRange = FoldingRange
module FoldingRangeParams = FoldingRangeParams
module Hover = Hover
module HoverParams = HoverParams
module InitializeParams = InitializeParams
module InitializeResult = InitializeResult
module Location = Location
module LogMessageParams = LogMessageParams
module MarkupContent = MarkupContent
module MarkupKind = MarkupKind
module MessageType = MessageType
module OptionalVersionedTextDocumentIdentifier =
OptionalVersionedTextDocumentIdentifier
module ParameterInformation = ParameterInformation
module PositionEncodingKind = PositionEncodingKind
module ProgressParams = ProgressParams
module ProgressToken = ProgressToken
module PublishDiagnosticsParams = PublishDiagnosticsParams
module PublishDiagnosticsClientCapabilities =
PublishDiagnosticsClientCapabilities
module ReferenceParams = ReferenceParams
module Registration = Registration
module RegistrationParams = RegistrationParams
module RenameOptions = RenameOptions
module RenameParams = RenameParams
module SaveOptions = SaveOptions
module SelectionRange = SelectionRange
module SelectionRangeParams = SelectionRangeParams
module SemanticTokens = SemanticTokens
module SemanticTokensEdit = SemanticTokensEdit
module SemanticTokensLegend = SemanticTokensLegend
module SemanticTokensDelta = SemanticTokensDelta
module SemanticTokensDeltaParams = SemanticTokensDeltaParams
module SemanticTokenModifiers = SemanticTokenModifiers
module SemanticTokensOptions = SemanticTokensOptions
module SemanticTokensParams = SemanticTokensParams
module SemanticTokenTypes = SemanticTokenTypes
module ServerCapabilities = ServerCapabilities
module Server_notification = Lsp.Server_notification
module SetTraceParams = SetTraceParams
module ShowDocumentClientCapabilities = ShowDocumentClientCapabilities
module ShowDocumentParams = ShowDocumentParams
module ShowDocumentResult = ShowDocumentResult
module ShowMessageParams = ShowMessageParams
module SignatureHelp = SignatureHelp
module SignatureHelpOptions = SignatureHelpOptions
module SignatureHelpParams = SignatureHelpParams
module SignatureInformation = SignatureInformation
module SymbolInformation = SymbolInformation
module SymbolKind = SymbolKind
module TextDocumentClientCapabilities = TextDocumentClientCapabilities
module TextDocumentContentChangeEvent = TextDocumentContentChangeEvent
module TextDocumentEdit = TextDocumentEdit
module TextDocumentFilter = TextDocumentFilter
module TextDocumentIdentifier = TextDocumentIdentifier
module TextDocumentItem = TextDocumentItem
module TextDocumentRegistrationOptions = TextDocumentRegistrationOptions
module TextDocumentSyncKind = TextDocumentSyncKind
module TextDocumentSyncOptions = TextDocumentSyncOptions
module TextDocumentSyncClientCapabilities = TextDocumentSyncClientCapabilities
module TextEdit = TextEdit
(** deprecated *)
module TraceValue = TraceValues
module TraceValues = TraceValues
module Unregistration = Unregistration
module UnregistrationParams = UnregistrationParams
module VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier
module WorkDoneProgressBegin = WorkDoneProgressBegin
module WorkDoneProgressCreateParams = WorkDoneProgressCreateParams
module WorkDoneProgressEnd = WorkDoneProgressEnd
module WorkDoneProgressReport = WorkDoneProgressReport
module WorkspaceEdit = WorkspaceEdit
module WorkspaceFolder = WorkspaceFolder
module WorkspaceFoldersChangeEvent = WorkspaceFoldersChangeEvent
module WorkspaceSymbolParams = WorkspaceSymbolParams
module WorkspaceFoldersServerCapabilities = WorkspaceFoldersServerCapabilities
end
let task_if_running pool ~f =
let open Fiber.O in
let* running = Fiber.Pool.running pool in
match running with
| false -> Fiber.return ()
| true -> Fiber.Pool.task pool ~f
let inside_test = Env_vars._TEST () |> Option.value ~default:false
| null | https://raw.githubusercontent.com/ocaml/ocaml-lsp/8367f37bab3fb036e19892e46843d3807e25b3a8/ocaml-lsp-server/src/import.ml | ocaml | All modules from [Lsp] should be in the struct below. The modules are listed
alphabetically. Try to keep the order.
Misc modules
OCaml frontend
All modules from [Lsp_fiber] should be in the struct below. The modules are
listed alphabetically. Try to keep the order.
All modules from [Lsp.Types] should be in the struct below. The modules are
listed alphabetically. Try to keep the order.
* deprecated | All modules from [ ] should be in the struct below . The modules are
listed alphabetically . Try to keep the order .
listed alphabetically. Try to keep the order. *)
include struct
open Stdune
module Array = struct
include Array
let common_prefix_len ~equal (a : 'a array) (b : 'a array) : int =
let i = ref 0 in
let min_len = min (Array.length a) (Array.length b) in
while !i < min_len && equal (Array.get a !i) (Array.get b !i) do
incr i
done;
!i
end
module Code_error = Code_error
module Comparable = Comparable
module Exn_with_backtrace = Exn_with_backtrace
module Fdecl = Fdecl
module Fpath = Path
module Int = Int
module List = List
module Map = Map
module Monoid = Monoid
module Option = Option
module Ordering = Ordering
module Pid = Pid
module Poly = Poly
module Result = Result
module Queue = Queue
module String = struct
include String
let findi =
let rec loop s len ~f i =
if i >= len then None
else if f (String.unsafe_get s i) then Some i
else loop s len ~f (i + 1)
in
fun ?from s ~f ->
let len = String.length s in
let from =
match from with
| None -> 0
| Some i ->
if i > len - 1 then Code_error.raise "findi: invalid from" [] else i
in
loop s len ~f from
let rfindi =
let rec loop s ~f i =
if i < 0 then None
else if f (String.unsafe_get s i) then Some i
else loop s ~f (i - 1)
in
fun ?from s ~f ->
let from =
let len = String.length s in
match from with
| None -> len - 1
| Some i ->
if i > len - 1 then Code_error.raise "rfindi: invalid from" []
else i
in
loop s ~f from
end
module Table = Table
module Tuple = Tuple
module Unix_env = Env
module Io = Io
let sprintf = sprintf
end
include struct
open Lsp
module Client_notification = Client_notification
module Client_request = Client_request
module Server_request = Server_request
module Text_document = Text_document
module Uri = struct
include Uri
let to_dyn t = Dyn.string (to_string t)
end
end
module Drpc = Dune_rpc.V1
module Ast_iterator = Ocaml_parsing.Ast_iterator
module Asttypes = Ocaml_parsing.Asttypes
module Cmt_format = Ocaml_typing.Cmt_format
module Ident = Ocaml_typing.Ident
module Env = Ocaml_typing.Env
module Loc = struct
module T = struct
include Ocaml_parsing.Location
include Ocaml_parsing.Location_aux
end
include T
module Map = Map.Make (struct
include T
let compare x x' = Ordering.of_int (compare x x')
let position_to_dyn (pos : Lexing.position) =
Dyn.Record
[ ("pos_fname", Dyn.String pos.pos_fname)
; ("pos_lnum", Dyn.Int pos.pos_lnum)
; ("pos_bol", Dyn.Int pos.pos_bol)
; ("pos_cnum", Dyn.Int pos.pos_cnum)
]
let to_dyn loc =
Dyn.Record
[ ("loc_start", position_to_dyn loc.loc_start)
; ("loc_end", position_to_dyn loc.loc_end)
; ("loc_ghost", Dyn.Bool loc.loc_ghost)
]
end)
end
module Longident = Ocaml_parsing.Longident
module Parsetree = Ocaml_parsing.Parsetree
module Path = Ocaml_typing.Path
module Pprintast = Ocaml_parsing.Pprintast
module Typedtree = Ocaml_typing.Typedtree
module Types = Ocaml_typing.Types
module Warnings = Ocaml_utils.Warnings
module Mconfig = Merlin_kernel.Mconfig
module Msource = Merlin_kernel.Msource
module Mbrowse = Merlin_kernel.Mbrowse
module Mpipeline = Merlin_kernel.Mpipeline
module Mreader = Merlin_kernel.Mreader
module Mtyper = Merlin_kernel.Mtyper
module Browse_raw = Merlin_specific.Browse_raw
include struct
open Lsp_fiber
module Log = Private.Log
module Reply = Rpc.Reply
module Server = Server
module Lazy_fiber = Lsp_fiber.Lazy_fiber
module Json = Json
end
include struct
open Lsp.Types
module ClientCapabilities = struct
include ClientCapabilities
let markdown_support (client_capabilities : ClientCapabilities.t) ~field =
match client_capabilities.textDocument with
| None -> false
| Some td -> (
match field td with
| None -> false
| Some format ->
let set = Option.value format ~default:[ MarkupKind.Markdown ] in
List.mem set MarkupKind.Markdown ~equal:Poly.equal)
end
module CodeAction = CodeAction
module CodeActionKind = CodeActionKind
module CodeActionOptions = CodeActionOptions
module CodeActionParams = CodeActionParams
module CodeActionResult = CodeActionResult
module CodeActionRegistrationOptions = CodeActionRegistrationOptions
module CodeLens = CodeLens
module CodeLensOptions = CodeLensOptions
module CodeLensParams = CodeLensParams
module Command = Command
module CompletionItem = CompletionItem
module CompletionItemKind = CompletionItemKind
module CompletionList = CompletionList
module CompletionOptions = CompletionOptions
module CompletionParams = CompletionParams
module ConfigurationParams = ConfigurationParams
module CreateFile = CreateFile
module Diagnostic = Diagnostic
module DiagnosticRelatedInformation = DiagnosticRelatedInformation
module DiagnosticSeverity = DiagnosticSeverity
module DiagnosticTag = DiagnosticTag
module DidChangeConfigurationParams = DidChangeConfigurationParams
module DidChangeWorkspaceFoldersParams = DidChangeWorkspaceFoldersParams
module DidOpenTextDocumentParams = DidOpenTextDocumentParams
module Diff = Lsp.Diff
module DocumentFilter = DocumentFilter
module DocumentHighlight = DocumentHighlight
module DocumentHighlightKind = DocumentHighlightKind
module DocumentHighlightParams = DocumentHighlightParams
module DocumentSymbol = DocumentSymbol
module DocumentUri = DocumentUri
module ExecuteCommandOptions = ExecuteCommandOptions
module ExecuteCommandParams = ExecuteCommandParams
module FoldingRange = FoldingRange
module FoldingRangeParams = FoldingRangeParams
module Hover = Hover
module HoverParams = HoverParams
module InitializeParams = InitializeParams
module InitializeResult = InitializeResult
module Location = Location
module LogMessageParams = LogMessageParams
module MarkupContent = MarkupContent
module MarkupKind = MarkupKind
module MessageType = MessageType
module OptionalVersionedTextDocumentIdentifier =
OptionalVersionedTextDocumentIdentifier
module ParameterInformation = ParameterInformation
module PositionEncodingKind = PositionEncodingKind
module ProgressParams = ProgressParams
module ProgressToken = ProgressToken
module PublishDiagnosticsParams = PublishDiagnosticsParams
module PublishDiagnosticsClientCapabilities =
PublishDiagnosticsClientCapabilities
module ReferenceParams = ReferenceParams
module Registration = Registration
module RegistrationParams = RegistrationParams
module RenameOptions = RenameOptions
module RenameParams = RenameParams
module SaveOptions = SaveOptions
module SelectionRange = SelectionRange
module SelectionRangeParams = SelectionRangeParams
module SemanticTokens = SemanticTokens
module SemanticTokensEdit = SemanticTokensEdit
module SemanticTokensLegend = SemanticTokensLegend
module SemanticTokensDelta = SemanticTokensDelta
module SemanticTokensDeltaParams = SemanticTokensDeltaParams
module SemanticTokenModifiers = SemanticTokenModifiers
module SemanticTokensOptions = SemanticTokensOptions
module SemanticTokensParams = SemanticTokensParams
module SemanticTokenTypes = SemanticTokenTypes
module ServerCapabilities = ServerCapabilities
module Server_notification = Lsp.Server_notification
module SetTraceParams = SetTraceParams
module ShowDocumentClientCapabilities = ShowDocumentClientCapabilities
module ShowDocumentParams = ShowDocumentParams
module ShowDocumentResult = ShowDocumentResult
module ShowMessageParams = ShowMessageParams
module SignatureHelp = SignatureHelp
module SignatureHelpOptions = SignatureHelpOptions
module SignatureHelpParams = SignatureHelpParams
module SignatureInformation = SignatureInformation
module SymbolInformation = SymbolInformation
module SymbolKind = SymbolKind
module TextDocumentClientCapabilities = TextDocumentClientCapabilities
module TextDocumentContentChangeEvent = TextDocumentContentChangeEvent
module TextDocumentEdit = TextDocumentEdit
module TextDocumentFilter = TextDocumentFilter
module TextDocumentIdentifier = TextDocumentIdentifier
module TextDocumentItem = TextDocumentItem
module TextDocumentRegistrationOptions = TextDocumentRegistrationOptions
module TextDocumentSyncKind = TextDocumentSyncKind
module TextDocumentSyncOptions = TextDocumentSyncOptions
module TextDocumentSyncClientCapabilities = TextDocumentSyncClientCapabilities
module TextEdit = TextEdit
module TraceValue = TraceValues
module TraceValues = TraceValues
module Unregistration = Unregistration
module UnregistrationParams = UnregistrationParams
module VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier
module WorkDoneProgressBegin = WorkDoneProgressBegin
module WorkDoneProgressCreateParams = WorkDoneProgressCreateParams
module WorkDoneProgressEnd = WorkDoneProgressEnd
module WorkDoneProgressReport = WorkDoneProgressReport
module WorkspaceEdit = WorkspaceEdit
module WorkspaceFolder = WorkspaceFolder
module WorkspaceFoldersChangeEvent = WorkspaceFoldersChangeEvent
module WorkspaceSymbolParams = WorkspaceSymbolParams
module WorkspaceFoldersServerCapabilities = WorkspaceFoldersServerCapabilities
end
let task_if_running pool ~f =
let open Fiber.O in
let* running = Fiber.Pool.running pool in
match running with
| false -> Fiber.return ()
| true -> Fiber.Pool.task pool ~f
let inside_test = Env_vars._TEST () |> Option.value ~default:false
|
a73767f1c804345092d0d8524fe9fc76e9e9362b04305a60c969e8f2be02aad3 | rtoy/cmucl | cp1254.lisp | ;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: STREAM -*-
;;;
;;; **********************************************************************
This code was written by and has been placed in the public
;;; domain.
;;;
(ext:file-comment "$Header: src/pcl/simple-streams/external-formats/cp1254.lisp $")
(in-package "STREAM")
(intl:textdomain "cmucl")
;; See
;;
;; For undefined characters we use U+FFFE
(defconstant +ms-cp1254+
(make-array 128
:element-type '(unsigned-byte 16)
:initial-contents #(8364 65534 8218 402 8222 8230 8224 8225
710 8240 352 8249 338 65534 65534 65534
65534 8216 8217 8220 8221 8226 8211 8212
732 8482 353 8250 339 65534 65534 376
160 161 162 163 164 165 166 167 168 169
170 171 172 173 174 175 176 177 178 179
180 181 182 183 184 185 186 187 188 189
190 191 192 193 194 195 196 197 198 199
200 201 202 203 204 205 206 207 286 209
210 211 212 213 214 215 216 217 218 219
220 304 350 223 224 225 226 227 228 229
230 231 232 233 234 235 236 237 238 239
287 241 242 243 244 245 246 247 248 249
250 251 252 305 351 255)))
(define-external-format :cp1254 (:base :mac-roman :documentation
"CP1254 is a Windows code page for Turkish.
By default, illegal inputs are replaced by the Unicode replacement
character and illegal outputs are replaced by a question mark.")
((table +ms-cp1254+)))
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/pcl/simple-streams/external-formats/cp1254.lisp | lisp | -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: STREAM -*-
**********************************************************************
domain.
See
For undefined characters we use U+FFFE | This code was written by and has been placed in the public
(ext:file-comment "$Header: src/pcl/simple-streams/external-formats/cp1254.lisp $")
(in-package "STREAM")
(intl:textdomain "cmucl")
(defconstant +ms-cp1254+
(make-array 128
:element-type '(unsigned-byte 16)
:initial-contents #(8364 65534 8218 402 8222 8230 8224 8225
710 8240 352 8249 338 65534 65534 65534
65534 8216 8217 8220 8221 8226 8211 8212
732 8482 353 8250 339 65534 65534 376
160 161 162 163 164 165 166 167 168 169
170 171 172 173 174 175 176 177 178 179
180 181 182 183 184 185 186 187 188 189
190 191 192 193 194 195 196 197 198 199
200 201 202 203 204 205 206 207 286 209
210 211 212 213 214 215 216 217 218 219
220 304 350 223 224 225 226 227 228 229
230 231 232 233 234 235 236 237 238 239
287 241 242 243 244 245 246 247 248 249
250 251 252 305 351 255)))
(define-external-format :cp1254 (:base :mac-roman :documentation
"CP1254 is a Windows code page for Turkish.
By default, illegal inputs are replaced by the Unicode replacement
character and illegal outputs are replaced by a question mark.")
((table +ms-cp1254+)))
|
54157ed8a3e68e328ea22522e0e7f7b88b420c9efddd0faae1ad1d5b10dbdf90 | drewc/gerbil-swank | mit.scm | (declare (usual-integrations))
srfi 13
(define (string-start+end str start end)
(let ((s (if (eq? #!default start)
0 start))
(e (if (eq? #!default end)
(string-length str) end)))
(values s e)))
(define (string-start+end+start+end s1 start1 end1 s2 start2 end2)
(let ((s (if (eq? #!default start1)
0 start1))
(e (if (eq? #!default end1)
(string-length s1) end1))
(sx (if (eq? #!default start2)
0 start2))
(ex (if (eq? #!default end2)
(string-length s2) end2)))
(values s e sx ex)))
(define (string-map proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let* ((len (- end start))
(ans (make-string len)))
(do ((i (- end 1) (- i 1))
(j (- len 1) (- j 1)))
((< j 0))
(string-set! ans j (proc (string-ref s i))))
ans)))
(define (string-map! proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(do ((i (- end 1) (- i 1)))
((< i start))
(string-set! s i (proc (string-ref s i))))))
(define (string-fold kons knil s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((v knil) (i start))
(if (< i end) (lp (kons (string-ref s i) v) (+ i 1))
v))))
(define (string-fold-right kons knil s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((v knil) (i (- end 1)))
(if (>= i start) (lp (kons (string-ref s i) v) (- i 1))
v))))
(define (string-tabulate proc len)
(let ((s (make-string len)))
(do ((i (- len 1) (- i 1)))
((< i 0))
(string-set! s i (proc i)))
s))
(define (string-for-each proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((i start))
(if (< i end)
(begin (proc (string-ref s i))
(lp (+ i 1)))))))
(define (string-for-each-index proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((i start))
(if (< i end) (begin (proc i) (lp (+ i 1)))))))
;;(define string-hash-ci string-ci-hash)
(define string= string=?)
(define string< string<?)
(define string> string>?)
(define string<= string<=?)
(define string>= string>=?)
(define (string<> a b) (not (string= a b)))
(define string-ci= string-ci=?)
(define string-ci< string-ci<?)
(define string-ci> string-ci>?)
(define string-ci<= string-ci<=?)
(define string-ci>= string-ci>=?)
(define (string-ci<> a b) (not (string-ci= a b)))
(define (substring/shared s #!optional start end)
(receive (start end)
(string-start+end s start end)
(if (and (zero? start) (= end (string-length s))) s
(substring s start end))))
(define (string-take s n)
(substring/shared s 0 n))
(define (string-take-right s n)
(let ((len (string-length s)))
(substring/shared s (- len n) len)))
(define (string-drop s n)
(let ((len (string-length s)))
(substring/shared s n len)))
(define (string-drop-right s n)
(let ((len (string-length s)))
(substring/shared s 0 (- len n))))
(define (string-pad s n #!optional char start end)
(receive (start end)
(string-start+end s start end)
(let ((char (if (eq? #!default char) #\space char)))
(let ((len (- end start)))
(if (<= n len)
(substring/shared s (- end n) end)
(let ((ans (make-string n char)))
(string-copy! ans (- n len) s start end)
ans))))))
(define (string-copy! to tstart from #!optional fstart fend)
(receive (fstart fend)
(string-start+end from fstart fend)
(if (> fstart tstart)
(do ((i fstart (+ i 1))
(j tstart (+ j 1)))
((>= i fend))
(string-set! to j (string-ref from i)))
(do ((i (- fend 1) (- i 1))
(j (+ -1 tstart (- fend fstart)) (- j 1)))
((< i fstart))
(string-set! to j (string-ref from i))))))
(define (string-skip str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i start))
(and (< i end)
(if (char=? criterion (string-ref str i))
(lp (+ i 1))
i))))
((char-set? criterion)
(let lp ((i start))
(and (< i end)
(if (char-in-set? (string-ref str i) criterion)
(lp (+ i 1))
i))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (string-ref str i)) (lp (+ i 1))
i))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-skip criterion)))))
(define (string-skip-right str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char=? criterion (string-ref str i))
(lp (- i 1))
i))))
((char-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char-in-set? (string-ref str i) criterion)
(lp (- i 1))
i))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (string-ref str i)) (lp (- i 1))
i))))
(else (error "CRITERION param is neither char-set or char."
string-skip-right criterion)))))
(define (string-trim-both s #!optional criterion start end)
(receive (start end)
(string-start+end s start end)
(let ((criterion (if (eq? #!default criterion) char-set:whitespace criterion)))
(cond ((string-skip s criterion start end) =>
(lambda (i)
(substring/shared s i (+ 1 (string-skip-right s criterion i end)))))
(else "")))))
(define (string-filter criterion s #!optional start end)
(receive (start end)
(string-start+end s start end)
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-string slen))
(ans-len (string-fold (lambda (c i)
(if (criterion c)
(begin (string-set! temp i c)
(+ i 1))
i))
0 s start end)))
(if (= ans-len slen) temp (substring temp 0 ans-len)))
(let* ((cset (cond ((char-set? criterion) criterion)
((char? criterion) (char-set criterion))
(else (error "string-delete criterion not predicate, char or char-set" criterion))))
(len (string-fold (lambda (c i) (if (char-in-set? c cset)
(+ i 1)
i))
0 s start end))
(ans (make-string len)))
(string-fold (lambda (c i) (if (char-in-set? c cset)
(begin (string-set! ans i c)
(+ i 1))
i))
0 s start end)
ans))))
(define (string-count s criterion #!optional start end)
(receive (start end)
(string-start+end s start end)
(cond ((char? criterion)
(do ((i start (+ i 1))
(count 0 (if (char=? criterion (string-ref s i))
(+ count 1)
count)))
((>= i end) count)))
((char-set? criterion)
(do ((i start (+ i 1))
(count 0 (if (char-in-set? (string-ref s i) criterion)
(+ count 1)
count)))
((>= i end) count)))
((procedure? criterion)
(do ((i start (+ i 1))
(count 0 (if (criterion (string-ref s i)) (+ count 1) count)))
((>= i end) count)))
(else (error "CRITERION param is neither char-set or char."
string-count criterion)))))
(define (reverse-list->string clist)
(let* ((len (length clist))
(s (make-string len)))
(do ((i (- len 1) (- i 1)) (clist clist (cdr clist)))
((not (pair? clist)))
(string-set! s i (car clist)))
s))
(define (string-index str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i start))
(and (< i end)
(if (char=? criterion (string-ref str i)) i
(lp (+ i 1))))))
((char-set? criterion)
(let lp ((i start))
(and (< i end)
(if (char-in-set? (string-ref str i) criterion) i
(lp (+ i 1))))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (string-ref str i)) i
(lp (+ i 1))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-index criterion)))))
(define (string-index-right str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char=? criterion (string-ref str i)) i
(lp (- i 1))))))
((char-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char-in-set? (string-ref str i) criterion) i
(lp (- i 1))))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (string-ref str i)) i
(lp (- i 1))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-index-right criterion)))))
(define (string-concatenate strings)
(let* ((total (do ((strings strings (cdr strings))
(i 0 (+ i (string-length (car strings)))))
((not (pair? strings)) i)))
(ans (make-string total)))
(let lp ((i 0) (strings strings))
(if (pair? strings)
(let* ((s (car strings))
(slen (string-length s)))
(string-copy! ans i s 0 slen)
(lp (+ i slen) (cdr strings)))))
ans))
(define (string-concatenate-reverse string-list #!optional final end)
(let* ((final (if (string? final) final ""))
(end (if (and (integer? end)
(exact? end)
(<= 0 end (string-length final)))
end
(string-length final))))
(let ((len (let lp ((sum 0) (lis string-list))
(if (pair? lis)
(lp (+ sum (string-length (car lis))) (cdr lis))
sum))))
(%finish-string-concatenate-reverse len string-list final end))))
(define (%finish-string-concatenate-reverse len string-list final end)
(let ((ans (make-string (+ end len))))
(string-copy! ans len final 0 end)
(let lp ((i len) (lis string-list))
(if (pair? lis)
(let* ((s (car lis))
(lis (cdr lis))
(slen (string-length s))
(i (- i slen)))
(string-copy! ans i s 0 slen)
(lp i lis))))
ans))
(define char-set:graphic-no-whitespace
(char-set-difference char-set:graphic char-set:whitespace))
(define (string-tokenize s #!optional token-chars start end)
(receive (start end)
(string-start+end s start end)
(let ((token-chars (if (char-set? token-chars) token-chars char-set:graphic-no-whitespace)))
(let lp ((i end) (ans '()))
(cond ((and (< start i) (string-index-right s token-chars start i)) =>
(lambda (tend-1)
(let ((tend (+ 1 tend-1)))
(cond ((string-skip-right s token-chars start tend-1) =>
(lambda (tstart-1)
(lp tstart-1
(cons (substring s (+ 1 tstart-1) tend)
ans))))
(else (cons (substring s start tend) ans))))))
(else ans))))))
(define (string-contains text pattern #!optional start1 end1 start2 end2)
(receive (t-start t-end p-start p-end)
(string-start+end+start+end text start1 end1 pattern start2 end2)
(%kmp-search pattern text char=? p-start p-end t-start t-end)))
(define (string-contains-ci text pattern #!optional start1 end1 start2 end2)
(receive (t-start t-end p-start p-end)
(string-start+end+start+end text start1 end1 pattern start2 end2)
(%kmp-search pattern text char-ci=? p-start p-end t-start t-end)))
(define (%kmp-search pattern text c= p-start p-end t-start t-end)
(let ((plen (- p-end p-start))
(rv (make-kmp-restart-vector pattern c= p-start p-end)))
The search loop . TJ & PJ are redundant state .
(let lp ((ti t-start) (pi 0)
(tj (- t-end t-start)) ; (- tlen ti) -- how many chars left.
(pj plen)) ; (- plen pi) -- how many chars left.
(if (= pi plen)
(- ti plen) ; Win.
(and (<= pj tj) ; Lose.
Search .
(string-ref pattern (+ p-start pi)))
Advance .
(let ((pi (vector-ref rv pi))) ; Retreat.
(if (= pi -1)
Punt .
(lp ti pi tj (- plen pi))))))))))
(define (make-kmp-restart-vector pattern #!optional c= start end)
(receive (start end)
(string-start+end pattern start end)
(let ((c= (if (procedure? c=) c= char=?)))
(let* ((rvlen (- end start))
(rv (make-vector rvlen -1)))
(if (> rvlen 0)
(let ((rvlen-1 (- rvlen 1))
(c0 (string-ref pattern start)))
;; Here's the main loop. We have set rv[0] ... rv[i].
K = I + START -- it is the corresponding index into PATTERN .
(let lp1 ((i 0) (j -1) (k start))
(if (< i rvlen-1)
;; lp2 invariant:
;; pat[(k-j) .. k-1] matches pat[start .. start+j-1]
;; or j = -1.
(let lp2 ((j j))
(cond ((= j -1)
(let ((i1 (+ 1 i)))
(if (not (c= (string-ref pattern (+ k 1)) c0))
(vector-set! rv i1 0))
(lp1 i1 0 (+ k 1))))
;; pat[(k-j) .. k] matches pat[start..start+j].
((c= (string-ref pattern k) (string-ref pattern (+ j start)))
(let* ((i1 (+ 1 i))
(j1 (+ 1 j)))
(vector-set! rv i1 j1)
(lp1 i1 j1 (+ k 1))))
(else (lp2 (vector-ref rv j)))))))))
rv))))
(define (string-xreplace s1 s2 start1 end1 #!optional start2 end2)
(receive (start2 end2)
(string-start+end s2 start2 end2)
(let* ((slen1 (string-length s1))
(sublen2 (- end2 start2))
(alen (+ (- slen1 (- end1 start1)) sublen2))
(ans (make-string alen)))
(%string-copy! ans 0 s1 0 start1)
(%string-copy! ans start1 s2 start2 end2)
(%string-copy! ans (+ start1 sublen2) s1 end1 slen1)
ans)))
(define (%string-copy! to tstart from fstart fend)
(if (> fstart tstart)
(do ((i fstart (+ i 1))
(j tstart (+ j 1)))
((>= i fend))
(string-set! to j (string-ref from i)))
(do ((i (- fend 1) (- i 1))
(j (+ -1 tstart (- fend fstart)) (- j 1)))
((< i fstart))
(string-set! to j (string-ref from i)))))
(define (string-delete criterion s #!optional start end)
(receive (start end)
(string-start+end s start end)
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-string slen))
(ans-len (string-fold (lambda (c i)
(if (criterion c) i
(begin (string-set! temp i c)
(+ i 1))))
0 s start end)))
(if (= ans-len slen) temp (substring temp 0 ans-len)))
(let* ((cset (cond ((char-set? criterion) criterion)
((char? criterion) (char-set criterion))
(else (error "string-delete criterion not predicate, char or char-set" criterion))))
(len (string-fold (lambda (c i) (if (char-in-set? c cset)
i
(+ i 1)))
0 s start end))
(ans (make-string len)))
(string-fold (lambda (c i) (if (char-in-set? c cset)
i
(begin (string-set! ans i c)
(+ i 1))))
0 s start end)
ans))))
;; added
(define (string-subst str from to)
(let ((from-len (string-length from))
(to-len (string-length to)))
(let loop ((str str)
(start 0))
(let ((pos (string-contains str from start)))
(if (not pos) str
(loop (string-xreplace str to pos (+ pos from-len))
(+ pos to-len)))))))
end of srfi-13
;; still no proper multiple values :-/
(define-syntax let-values
(syntax-rules ()
((let-values ((vals form)) body0 body ...)
(receive vals (let ((r form))
TODO this is a total hack , which does n't even work well ...
(if (and (compiled-closure? r)
(let ((di (compiled-code-block/debugging-info (compiled-entry/block (compiled-closure->entry r)))))
(if (and di (vector? di) (eq? (vector-ref di 0) 'debugging-info-wrapper))
(string=? "runtime/global.inf" (vector-ref di 3))
#t ;; hm... anything simpler to do?
)))
r
(apply values (list r))))
(begin body0 body ...)))))
(define ($scheme-name)
"mit-scheme")
(define (fluid a)
(a))
(define ($open-tcp-server port-number port-file handler)
(let* ((n (or port-number (+ 10000 (random-integer 50000)))) ;; TODO: pass 0, then somehow read the actual port from the socket
(socket (open-tcp-server-socket n (host-address-loopback))))
(handler n socket)))
(define ($tcp-server-accept socket handler)
(let ((p (tcp-server-binary-connection-accept socket #t #f)))
(handler p p)))
(define hash-table-set! hash-table/put!)
(define hash-table-ref/default hash-table/get)
(define ($all-package-names)
(map (lambda (package) (env->pstring (package/environment package)))
(all-packages)))
(define ($handle-condition exception)
(invoke-sldb exception))
(define ($condition-msg condition)
(condition/report-string condition))
(define ($condition-location condition)
"Return (PATH POSITION LINE COLUMN) for CONDITION."
#f)
(define ($condition-links condition)
TODO
(map (lambda (x) 'foo) ($condition-trace condition)))
(define (pp-to-string o)
(string-trim (with-output-to-string (lambda () (pp o)))))
(define debugger-hide-system-code? #f)
(define (system-frame? stack-frame)
(stack-frame/repl-eval-boundary? stack-frame))
(define (stack-frame->subproblem frame number)
(receive (expression environment subexpression)
(stack-frame/debugging-info frame)
(make-subproblem frame expression environment subexpression number)))
(define-record-type <subproblem>
(make-subproblem stack-frame expression environment subexpression number)
subproblem?
(stack-frame subproblem/stack-frame)
(expression subproblem/expression)
(environment subproblem/environment)
(subexpression subproblem/subexpression)
(number subproblem/number))
(define-record-type <browser-line>
(%make-bline start-mark object type parent depth next prev offset
properties)
bline?
;; Index of this bline within browser lines vector. #F if line is
;; invisible.
(index bline/index set-bline/index!)
;; Line start within browser buffer. #F if line is invisible.
(start-mark bline/start-mark set-bline/start-mark!)
;; Object that this line represents.
(object bline/object)
;; Type of OBJECT. This type is specific to the browser; it tells
;; the browser how to manipulate OBJECT.
(type bline/type)
;; BLINE representing the object that this object is a component of,
;; or #F if none.
(parent bline/parent)
Nonnegative integer indicating the depth of this object in the
;; component nesting.
(depth bline/depth)
;; BLINEs representing the objects that are adjacent to this one in
;; the component ordering, or #F if none.
(next bline/next set-bline/next!)
(prev bline/prev)
Nonnegative integer indicating the position of this object in the
;; component ordering.
(offset bline/offset)
(properties bline/properties))
(define (make-bline object type parent prev)
(let ((bline
(%make-bline #f
object
type
parent
(if parent (+ (bline/depth parent) 1) 0)
#f
prev
(if prev (+ (bline/offset prev) 1) 0)
(make-1d-table))))
(if prev
(set-bline/next! prev bline))
bline))
(define-record-type <reduction>
(make-reduction subproblem expression environment number)
reduction?
(subproblem reduction/subproblem)
(expression reduction/expression)
(environment reduction/environment)
(number reduction/number))
(define (subproblem/reductions subproblem)
(let ((frame (subproblem/stack-frame subproblem)))
(let loop ((reductions (stack-frame/reductions frame)) (n 0))
(if (pair? reductions)
(cons (make-reduction subproblem
(caar reductions)
(cadar reductions)
n)
(loop (cdr reductions) (+ n 1)))
'()))))
(define (continuation->blines continuation)
(let ((beyond-system-code #f))
(let loop ((frame (continuation/first-subproblem continuation))
(prev #f)
(n 0))
(if (not frame)
'()
(let* ((next-subproblem
(lambda (bline)
(loop (stack-frame/next-subproblem frame)
bline
(+ n 1))))
(walk-reductions
(lambda (bline reductions)
(cons bline
(let loop ((reductions reductions) (prev #f))
(if (null? reductions)
(next-subproblem bline)
(let ((bline
(make-bline (car reductions)
'bline-type:reduction
bline
prev)))
(cons bline
(loop (cdr reductions) bline))))))))
(continue
(lambda ()
(let* ((subproblem (stack-frame->subproblem frame n)))
(if debugger:student-walk?
(let ((reductions
(subproblem/reductions subproblem)))
(if (null? reductions)
(let ((bline
(make-bline subproblem
'bline-type:subproblem
#f
prev)))
(cons bline
(next-subproblem bline)))
(let ((bline
(make-bline (car reductions)
'bline-type:reduction
#f
prev)))
(walk-reductions bline
(if (> n 0)
'()
(cdr reductions))))))
(walk-reductions
(make-bline subproblem
'bline-type:subproblem
#f
prev)
(subproblem/reductions subproblem)))))))
(cond ((and (not debugger-hide-system-code?)
(system-frame? frame))
(loop (stack-frame/next-subproblem frame)
prev
n))
((or ;; (and limit (>= n limit))
(if (system-frame? frame)
(begin (set! beyond-system-code #t) #t)
#f)
beyond-system-code)
(list (make-continuation-bline continue #f prev)))
(else (continue))))))))
(define ($condition-trace condition)
(define from 0)
(define (combination->list c)
(read-from-string (pp-to-string c)))
(let* ((blines (drop (continuation->blines (condition/continuation condition)) from))
(blines-count (length blines))
(count (take (iota blines-count from) blines-count)))
(append (map (lambda (i bline)
(let ((o (bline/object bline)))
(cond ((reduction? o) (string "R" (reduction/number o) ": " (pp-to-string (reduction/expression o))))
((subproblem? o) (string "S" (subproblem/number o) ": " (pp-to-string (subproblem/subexpression o)) "\nin " (pp-to-string (subproblem/expression o))))
(else (pp-to-string o)))))
count
blines))))
(define (procedure-parameters symbol env)
(let ((type (environment-reference-type env symbol)))
(let ((ans (if (eq? type 'normal)
(let ((binding (environment-lookup env symbol)))
(if (and binding
(procedure? binding))
(cons symbol (read-from-string (string-trim (with-output-to-string
(lambda () (pa binding))))))
#f))
#f)))
ans)))
(define ($binding-documentation p)
;; same as (inspect object), then hitting c
#f)
(define ($function-parameters-and-documentation name)
TODO
(let ((binding #f))
(cons (procedure-parameters (string->symbol name) ($environment param:environment))
($binding-documentation binding))))
(define (string-replace s1 s2 start1 end1) ;; . start2+end2
(let* ((s1-before (substring s1 0 start1))
(s1-after (substring s1 end1 (string-length s1))))
(string-append s1-before s2 s1-after)))
(define ($inspect-fallback object)
(cond ((record? object)
(let* ((type (record-type-descriptor object))
(field-names (record-type-field-names type))
(len (length field-names))
(field-values (map (lambda (i) ((record-accessor type i) object)) field-names)))
(let loop ((n field-names)
(v field-values))
(if (null? n)
(stream)
(stream-cons (inspector-line (car n) (car v))
(loop (cdr n) (cdr v)))))))
(else #f)))
(define ($environment env-name)
TODO
(interaction-environment))
(define ($error-description condition)
(condition/report-string condition))
(define (all-packages)
(let loop ((package (name->package '()))) ;; system-global-package
(cons package
(append-map loop (package/children package)))))
(define anonymous-package-prefix "environment-")
(define unknown-environment (cons 'unknown 'environment))
(define (env->pstring env)
(if (eq? unknown-environment env)
"unknown environment"
(let ((package (environment->package env)))
(if package
(write-to-string (package/name package))
(string anonymous-package-prefix (object-hash env))))))
(define (with-exception-handler handler thunk)
(bind-condition-handler (list condition-type:serious-condition)
handler
thunk))
(define ($output-to-repl thunk)
;; basic implementation, print all output at the end, this should
;; be replaced with a custom output port
(let ((o (open-output-string)))
(parameterize ((current-output-port o))
(begin0
(thunk)
(swank/write-string (get-output-string o) #f)))))
(define ($completions prefix env-name)
(let ((strings (all-completions prefix (pstring->env env-name))))
(cons (sort strings string<?)
(longest-common-prefix strings))))
(define (longest-common-prefix strings)
(reduce (lambda (s1 s2)
(substring s1 0 (string-match-forward s1 s2)))
""
strings))
(define *buffer-pstring* (make-parameter #f))
(define (pstring->env pstring)
(cond ((or (not (string? pstring))
(not (string? (fluid *buffer-pstring*)))
(string-ci=? (fluid *buffer-pstring*) "COMMON-LISP-USER"))
(nearest-repl/environment))
((string-prefix? anonymous-package-prefix pstring)
(let ((object
(object-unhash
(string->number (string-tail pstring
(string-length
anonymous-package-prefix))
10
#t))))
(if (not (environment? object))
(error:wrong-type-datum object "environment"))
object))
(else
(package/environment (find-package (read-from-string pstring) #t)))))
(define (all-completions prefix environment)
(let ((prefix
(if (fluid (environment-lookup environment 'PARAM:PARSER-CANONICALIZE-SYMBOLS?))
(string-downcase prefix)
prefix))
(completions '()))
(for-each-interned-symbol
(lambda (symbol)
(if (and (string-prefix? prefix (symbol-name symbol))
(environment-bound? environment symbol))
(set! completions (cons (symbol-name symbol) completions)))
unspecific))
completions))
(define-record-type <istate>
(make-istate object parts actions next previous content)
istate?
(object istate-object)
(parts istate-parts)
(actions istate-actions)
(next istate-next set-istate-next!)
(previous istate-previous)
(content istate-content))
(define ($frame-locals-and-catch-tags nr)
`(nil
nil))
| null | https://raw.githubusercontent.com/drewc/gerbil-swank/b772d84bb2dc54e1ac80136e9300c3c051980d1d/gerbil-swank/r7rs/specific/mit.scm | scheme | (define string-hash-ci string-ci-hash)
(- tlen ti) -- how many chars left.
(- plen pi) -- how many chars left.
Win.
Lose.
Retreat.
Here's the main loop. We have set rv[0] ... rv[i].
lp2 invariant:
pat[(k-j) .. k-1] matches pat[start .. start+j-1]
or j = -1.
pat[(k-j) .. k] matches pat[start..start+j].
added
still no proper multiple values :-/
hm... anything simpler to do?
TODO: pass 0, then somehow read the actual port from the socket
Index of this bline within browser lines vector. #F if line is
invisible.
Line start within browser buffer. #F if line is invisible.
Object that this line represents.
Type of OBJECT. This type is specific to the browser; it tells
the browser how to manipulate OBJECT.
BLINE representing the object that this object is a component of,
or #F if none.
component nesting.
BLINEs representing the objects that are adjacent to this one in
the component ordering, or #F if none.
component ordering.
(and limit (>= n limit))
same as (inspect object), then hitting c
. start2+end2
system-global-package
basic implementation, print all output at the end, this should
be replaced with a custom output port | (declare (usual-integrations))
srfi 13
(define (string-start+end str start end)
(let ((s (if (eq? #!default start)
0 start))
(e (if (eq? #!default end)
(string-length str) end)))
(values s e)))
(define (string-start+end+start+end s1 start1 end1 s2 start2 end2)
(let ((s (if (eq? #!default start1)
0 start1))
(e (if (eq? #!default end1)
(string-length s1) end1))
(sx (if (eq? #!default start2)
0 start2))
(ex (if (eq? #!default end2)
(string-length s2) end2)))
(values s e sx ex)))
(define (string-map proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let* ((len (- end start))
(ans (make-string len)))
(do ((i (- end 1) (- i 1))
(j (- len 1) (- j 1)))
((< j 0))
(string-set! ans j (proc (string-ref s i))))
ans)))
(define (string-map! proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(do ((i (- end 1) (- i 1)))
((< i start))
(string-set! s i (proc (string-ref s i))))))
(define (string-fold kons knil s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((v knil) (i start))
(if (< i end) (lp (kons (string-ref s i) v) (+ i 1))
v))))
(define (string-fold-right kons knil s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((v knil) (i (- end 1)))
(if (>= i start) (lp (kons (string-ref s i) v) (- i 1))
v))))
(define (string-tabulate proc len)
(let ((s (make-string len)))
(do ((i (- len 1) (- i 1)))
((< i 0))
(string-set! s i (proc i)))
s))
(define (string-for-each proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((i start))
(if (< i end)
(begin (proc (string-ref s i))
(lp (+ i 1)))))))
(define (string-for-each-index proc s #!optional start end)
(receive (start end)
(string-start+end s start end)
(let lp ((i start))
(if (< i end) (begin (proc i) (lp (+ i 1)))))))
(define string= string=?)
(define string< string<?)
(define string> string>?)
(define string<= string<=?)
(define string>= string>=?)
(define (string<> a b) (not (string= a b)))
(define string-ci= string-ci=?)
(define string-ci< string-ci<?)
(define string-ci> string-ci>?)
(define string-ci<= string-ci<=?)
(define string-ci>= string-ci>=?)
(define (string-ci<> a b) (not (string-ci= a b)))
(define (substring/shared s #!optional start end)
(receive (start end)
(string-start+end s start end)
(if (and (zero? start) (= end (string-length s))) s
(substring s start end))))
(define (string-take s n)
(substring/shared s 0 n))
(define (string-take-right s n)
(let ((len (string-length s)))
(substring/shared s (- len n) len)))
(define (string-drop s n)
(let ((len (string-length s)))
(substring/shared s n len)))
(define (string-drop-right s n)
(let ((len (string-length s)))
(substring/shared s 0 (- len n))))
(define (string-pad s n #!optional char start end)
(receive (start end)
(string-start+end s start end)
(let ((char (if (eq? #!default char) #\space char)))
(let ((len (- end start)))
(if (<= n len)
(substring/shared s (- end n) end)
(let ((ans (make-string n char)))
(string-copy! ans (- n len) s start end)
ans))))))
(define (string-copy! to tstart from #!optional fstart fend)
(receive (fstart fend)
(string-start+end from fstart fend)
(if (> fstart tstart)
(do ((i fstart (+ i 1))
(j tstart (+ j 1)))
((>= i fend))
(string-set! to j (string-ref from i)))
(do ((i (- fend 1) (- i 1))
(j (+ -1 tstart (- fend fstart)) (- j 1)))
((< i fstart))
(string-set! to j (string-ref from i))))))
(define (string-skip str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i start))
(and (< i end)
(if (char=? criterion (string-ref str i))
(lp (+ i 1))
i))))
((char-set? criterion)
(let lp ((i start))
(and (< i end)
(if (char-in-set? (string-ref str i) criterion)
(lp (+ i 1))
i))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (string-ref str i)) (lp (+ i 1))
i))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-skip criterion)))))
(define (string-skip-right str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char=? criterion (string-ref str i))
(lp (- i 1))
i))))
((char-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char-in-set? (string-ref str i) criterion)
(lp (- i 1))
i))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (string-ref str i)) (lp (- i 1))
i))))
(else (error "CRITERION param is neither char-set or char."
string-skip-right criterion)))))
(define (string-trim-both s #!optional criterion start end)
(receive (start end)
(string-start+end s start end)
(let ((criterion (if (eq? #!default criterion) char-set:whitespace criterion)))
(cond ((string-skip s criterion start end) =>
(lambda (i)
(substring/shared s i (+ 1 (string-skip-right s criterion i end)))))
(else "")))))
(define (string-filter criterion s #!optional start end)
(receive (start end)
(string-start+end s start end)
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-string slen))
(ans-len (string-fold (lambda (c i)
(if (criterion c)
(begin (string-set! temp i c)
(+ i 1))
i))
0 s start end)))
(if (= ans-len slen) temp (substring temp 0 ans-len)))
(let* ((cset (cond ((char-set? criterion) criterion)
((char? criterion) (char-set criterion))
(else (error "string-delete criterion not predicate, char or char-set" criterion))))
(len (string-fold (lambda (c i) (if (char-in-set? c cset)
(+ i 1)
i))
0 s start end))
(ans (make-string len)))
(string-fold (lambda (c i) (if (char-in-set? c cset)
(begin (string-set! ans i c)
(+ i 1))
i))
0 s start end)
ans))))
(define (string-count s criterion #!optional start end)
(receive (start end)
(string-start+end s start end)
(cond ((char? criterion)
(do ((i start (+ i 1))
(count 0 (if (char=? criterion (string-ref s i))
(+ count 1)
count)))
((>= i end) count)))
((char-set? criterion)
(do ((i start (+ i 1))
(count 0 (if (char-in-set? (string-ref s i) criterion)
(+ count 1)
count)))
((>= i end) count)))
((procedure? criterion)
(do ((i start (+ i 1))
(count 0 (if (criterion (string-ref s i)) (+ count 1) count)))
((>= i end) count)))
(else (error "CRITERION param is neither char-set or char."
string-count criterion)))))
(define (reverse-list->string clist)
(let* ((len (length clist))
(s (make-string len)))
(do ((i (- len 1) (- i 1)) (clist clist (cdr clist)))
((not (pair? clist)))
(string-set! s i (car clist)))
s))
(define (string-index str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i start))
(and (< i end)
(if (char=? criterion (string-ref str i)) i
(lp (+ i 1))))))
((char-set? criterion)
(let lp ((i start))
(and (< i end)
(if (char-in-set? (string-ref str i) criterion) i
(lp (+ i 1))))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (string-ref str i)) i
(lp (+ i 1))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-index criterion)))))
(define (string-index-right str criterion #!optional start end)
(receive (start end)
(string-start+end str start end)
(cond ((char? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char=? criterion (string-ref str i)) i
(lp (- i 1))))))
((char-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char-in-set? (string-ref str i) criterion) i
(lp (- i 1))))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (string-ref str i)) i
(lp (- i 1))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-index-right criterion)))))
(define (string-concatenate strings)
(let* ((total (do ((strings strings (cdr strings))
(i 0 (+ i (string-length (car strings)))))
((not (pair? strings)) i)))
(ans (make-string total)))
(let lp ((i 0) (strings strings))
(if (pair? strings)
(let* ((s (car strings))
(slen (string-length s)))
(string-copy! ans i s 0 slen)
(lp (+ i slen) (cdr strings)))))
ans))
(define (string-concatenate-reverse string-list #!optional final end)
(let* ((final (if (string? final) final ""))
(end (if (and (integer? end)
(exact? end)
(<= 0 end (string-length final)))
end
(string-length final))))
(let ((len (let lp ((sum 0) (lis string-list))
(if (pair? lis)
(lp (+ sum (string-length (car lis))) (cdr lis))
sum))))
(%finish-string-concatenate-reverse len string-list final end))))
(define (%finish-string-concatenate-reverse len string-list final end)
(let ((ans (make-string (+ end len))))
(string-copy! ans len final 0 end)
(let lp ((i len) (lis string-list))
(if (pair? lis)
(let* ((s (car lis))
(lis (cdr lis))
(slen (string-length s))
(i (- i slen)))
(string-copy! ans i s 0 slen)
(lp i lis))))
ans))
(define char-set:graphic-no-whitespace
(char-set-difference char-set:graphic char-set:whitespace))
(define (string-tokenize s #!optional token-chars start end)
(receive (start end)
(string-start+end s start end)
(let ((token-chars (if (char-set? token-chars) token-chars char-set:graphic-no-whitespace)))
(let lp ((i end) (ans '()))
(cond ((and (< start i) (string-index-right s token-chars start i)) =>
(lambda (tend-1)
(let ((tend (+ 1 tend-1)))
(cond ((string-skip-right s token-chars start tend-1) =>
(lambda (tstart-1)
(lp tstart-1
(cons (substring s (+ 1 tstart-1) tend)
ans))))
(else (cons (substring s start tend) ans))))))
(else ans))))))
(define (string-contains text pattern #!optional start1 end1 start2 end2)
(receive (t-start t-end p-start p-end)
(string-start+end+start+end text start1 end1 pattern start2 end2)
(%kmp-search pattern text char=? p-start p-end t-start t-end)))
(define (string-contains-ci text pattern #!optional start1 end1 start2 end2)
(receive (t-start t-end p-start p-end)
(string-start+end+start+end text start1 end1 pattern start2 end2)
(%kmp-search pattern text char-ci=? p-start p-end t-start t-end)))
(define (%kmp-search pattern text c= p-start p-end t-start t-end)
(let ((plen (- p-end p-start))
(rv (make-kmp-restart-vector pattern c= p-start p-end)))
The search loop . TJ & PJ are redundant state .
(let lp ((ti t-start) (pi 0)
(if (= pi plen)
Search .
(string-ref pattern (+ p-start pi)))
Advance .
(if (= pi -1)
Punt .
(lp ti pi tj (- plen pi))))))))))
(define (make-kmp-restart-vector pattern #!optional c= start end)
(receive (start end)
(string-start+end pattern start end)
(let ((c= (if (procedure? c=) c= char=?)))
(let* ((rvlen (- end start))
(rv (make-vector rvlen -1)))
(if (> rvlen 0)
(let ((rvlen-1 (- rvlen 1))
(c0 (string-ref pattern start)))
K = I + START -- it is the corresponding index into PATTERN .
(let lp1 ((i 0) (j -1) (k start))
(if (< i rvlen-1)
(let lp2 ((j j))
(cond ((= j -1)
(let ((i1 (+ 1 i)))
(if (not (c= (string-ref pattern (+ k 1)) c0))
(vector-set! rv i1 0))
(lp1 i1 0 (+ k 1))))
((c= (string-ref pattern k) (string-ref pattern (+ j start)))
(let* ((i1 (+ 1 i))
(j1 (+ 1 j)))
(vector-set! rv i1 j1)
(lp1 i1 j1 (+ k 1))))
(else (lp2 (vector-ref rv j)))))))))
rv))))
(define (string-xreplace s1 s2 start1 end1 #!optional start2 end2)
(receive (start2 end2)
(string-start+end s2 start2 end2)
(let* ((slen1 (string-length s1))
(sublen2 (- end2 start2))
(alen (+ (- slen1 (- end1 start1)) sublen2))
(ans (make-string alen)))
(%string-copy! ans 0 s1 0 start1)
(%string-copy! ans start1 s2 start2 end2)
(%string-copy! ans (+ start1 sublen2) s1 end1 slen1)
ans)))
(define (%string-copy! to tstart from fstart fend)
(if (> fstart tstart)
(do ((i fstart (+ i 1))
(j tstart (+ j 1)))
((>= i fend))
(string-set! to j (string-ref from i)))
(do ((i (- fend 1) (- i 1))
(j (+ -1 tstart (- fend fstart)) (- j 1)))
((< i fstart))
(string-set! to j (string-ref from i)))))
(define (string-delete criterion s #!optional start end)
(receive (start end)
(string-start+end s start end)
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-string slen))
(ans-len (string-fold (lambda (c i)
(if (criterion c) i
(begin (string-set! temp i c)
(+ i 1))))
0 s start end)))
(if (= ans-len slen) temp (substring temp 0 ans-len)))
(let* ((cset (cond ((char-set? criterion) criterion)
((char? criterion) (char-set criterion))
(else (error "string-delete criterion not predicate, char or char-set" criterion))))
(len (string-fold (lambda (c i) (if (char-in-set? c cset)
i
(+ i 1)))
0 s start end))
(ans (make-string len)))
(string-fold (lambda (c i) (if (char-in-set? c cset)
i
(begin (string-set! ans i c)
(+ i 1))))
0 s start end)
ans))))
(define (string-subst str from to)
(let ((from-len (string-length from))
(to-len (string-length to)))
(let loop ((str str)
(start 0))
(let ((pos (string-contains str from start)))
(if (not pos) str
(loop (string-xreplace str to pos (+ pos from-len))
(+ pos to-len)))))))
end of srfi-13
(define-syntax let-values
(syntax-rules ()
((let-values ((vals form)) body0 body ...)
(receive vals (let ((r form))
TODO this is a total hack , which does n't even work well ...
(if (and (compiled-closure? r)
(let ((di (compiled-code-block/debugging-info (compiled-entry/block (compiled-closure->entry r)))))
(if (and di (vector? di) (eq? (vector-ref di 0) 'debugging-info-wrapper))
(string=? "runtime/global.inf" (vector-ref di 3))
)))
r
(apply values (list r))))
(begin body0 body ...)))))
(define ($scheme-name)
"mit-scheme")
(define (fluid a)
(a))
(define ($open-tcp-server port-number port-file handler)
(socket (open-tcp-server-socket n (host-address-loopback))))
(handler n socket)))
(define ($tcp-server-accept socket handler)
(let ((p (tcp-server-binary-connection-accept socket #t #f)))
(handler p p)))
(define hash-table-set! hash-table/put!)
(define hash-table-ref/default hash-table/get)
(define ($all-package-names)
(map (lambda (package) (env->pstring (package/environment package)))
(all-packages)))
(define ($handle-condition exception)
(invoke-sldb exception))
(define ($condition-msg condition)
(condition/report-string condition))
(define ($condition-location condition)
"Return (PATH POSITION LINE COLUMN) for CONDITION."
#f)
(define ($condition-links condition)
TODO
(map (lambda (x) 'foo) ($condition-trace condition)))
(define (pp-to-string o)
(string-trim (with-output-to-string (lambda () (pp o)))))
(define debugger-hide-system-code? #f)
(define (system-frame? stack-frame)
(stack-frame/repl-eval-boundary? stack-frame))
(define (stack-frame->subproblem frame number)
(receive (expression environment subexpression)
(stack-frame/debugging-info frame)
(make-subproblem frame expression environment subexpression number)))
(define-record-type <subproblem>
(make-subproblem stack-frame expression environment subexpression number)
subproblem?
(stack-frame subproblem/stack-frame)
(expression subproblem/expression)
(environment subproblem/environment)
(subexpression subproblem/subexpression)
(number subproblem/number))
(define-record-type <browser-line>
(%make-bline start-mark object type parent depth next prev offset
properties)
bline?
(index bline/index set-bline/index!)
(start-mark bline/start-mark set-bline/start-mark!)
(object bline/object)
(type bline/type)
(parent bline/parent)
Nonnegative integer indicating the depth of this object in the
(depth bline/depth)
(next bline/next set-bline/next!)
(prev bline/prev)
Nonnegative integer indicating the position of this object in the
(offset bline/offset)
(properties bline/properties))
(define (make-bline object type parent prev)
(let ((bline
(%make-bline #f
object
type
parent
(if parent (+ (bline/depth parent) 1) 0)
#f
prev
(if prev (+ (bline/offset prev) 1) 0)
(make-1d-table))))
(if prev
(set-bline/next! prev bline))
bline))
(define-record-type <reduction>
(make-reduction subproblem expression environment number)
reduction?
(subproblem reduction/subproblem)
(expression reduction/expression)
(environment reduction/environment)
(number reduction/number))
(define (subproblem/reductions subproblem)
(let ((frame (subproblem/stack-frame subproblem)))
(let loop ((reductions (stack-frame/reductions frame)) (n 0))
(if (pair? reductions)
(cons (make-reduction subproblem
(caar reductions)
(cadar reductions)
n)
(loop (cdr reductions) (+ n 1)))
'()))))
(define (continuation->blines continuation)
(let ((beyond-system-code #f))
(let loop ((frame (continuation/first-subproblem continuation))
(prev #f)
(n 0))
(if (not frame)
'()
(let* ((next-subproblem
(lambda (bline)
(loop (stack-frame/next-subproblem frame)
bline
(+ n 1))))
(walk-reductions
(lambda (bline reductions)
(cons bline
(let loop ((reductions reductions) (prev #f))
(if (null? reductions)
(next-subproblem bline)
(let ((bline
(make-bline (car reductions)
'bline-type:reduction
bline
prev)))
(cons bline
(loop (cdr reductions) bline))))))))
(continue
(lambda ()
(let* ((subproblem (stack-frame->subproblem frame n)))
(if debugger:student-walk?
(let ((reductions
(subproblem/reductions subproblem)))
(if (null? reductions)
(let ((bline
(make-bline subproblem
'bline-type:subproblem
#f
prev)))
(cons bline
(next-subproblem bline)))
(let ((bline
(make-bline (car reductions)
'bline-type:reduction
#f
prev)))
(walk-reductions bline
(if (> n 0)
'()
(cdr reductions))))))
(walk-reductions
(make-bline subproblem
'bline-type:subproblem
#f
prev)
(subproblem/reductions subproblem)))))))
(cond ((and (not debugger-hide-system-code?)
(system-frame? frame))
(loop (stack-frame/next-subproblem frame)
prev
n))
(if (system-frame? frame)
(begin (set! beyond-system-code #t) #t)
#f)
beyond-system-code)
(list (make-continuation-bline continue #f prev)))
(else (continue))))))))
(define ($condition-trace condition)
(define from 0)
(define (combination->list c)
(read-from-string (pp-to-string c)))
(let* ((blines (drop (continuation->blines (condition/continuation condition)) from))
(blines-count (length blines))
(count (take (iota blines-count from) blines-count)))
(append (map (lambda (i bline)
(let ((o (bline/object bline)))
(cond ((reduction? o) (string "R" (reduction/number o) ": " (pp-to-string (reduction/expression o))))
((subproblem? o) (string "S" (subproblem/number o) ": " (pp-to-string (subproblem/subexpression o)) "\nin " (pp-to-string (subproblem/expression o))))
(else (pp-to-string o)))))
count
blines))))
(define (procedure-parameters symbol env)
(let ((type (environment-reference-type env symbol)))
(let ((ans (if (eq? type 'normal)
(let ((binding (environment-lookup env symbol)))
(if (and binding
(procedure? binding))
(cons symbol (read-from-string (string-trim (with-output-to-string
(lambda () (pa binding))))))
#f))
#f)))
ans)))
(define ($binding-documentation p)
#f)
(define ($function-parameters-and-documentation name)
TODO
(let ((binding #f))
(cons (procedure-parameters (string->symbol name) ($environment param:environment))
($binding-documentation binding))))
(let* ((s1-before (substring s1 0 start1))
(s1-after (substring s1 end1 (string-length s1))))
(string-append s1-before s2 s1-after)))
(define ($inspect-fallback object)
(cond ((record? object)
(let* ((type (record-type-descriptor object))
(field-names (record-type-field-names type))
(len (length field-names))
(field-values (map (lambda (i) ((record-accessor type i) object)) field-names)))
(let loop ((n field-names)
(v field-values))
(if (null? n)
(stream)
(stream-cons (inspector-line (car n) (car v))
(loop (cdr n) (cdr v)))))))
(else #f)))
(define ($environment env-name)
TODO
(interaction-environment))
(define ($error-description condition)
(condition/report-string condition))
(define (all-packages)
(cons package
(append-map loop (package/children package)))))
(define anonymous-package-prefix "environment-")
(define unknown-environment (cons 'unknown 'environment))
(define (env->pstring env)
(if (eq? unknown-environment env)
"unknown environment"
(let ((package (environment->package env)))
(if package
(write-to-string (package/name package))
(string anonymous-package-prefix (object-hash env))))))
(define (with-exception-handler handler thunk)
(bind-condition-handler (list condition-type:serious-condition)
handler
thunk))
(define ($output-to-repl thunk)
(let ((o (open-output-string)))
(parameterize ((current-output-port o))
(begin0
(thunk)
(swank/write-string (get-output-string o) #f)))))
(define ($completions prefix env-name)
(let ((strings (all-completions prefix (pstring->env env-name))))
(cons (sort strings string<?)
(longest-common-prefix strings))))
(define (longest-common-prefix strings)
(reduce (lambda (s1 s2)
(substring s1 0 (string-match-forward s1 s2)))
""
strings))
(define *buffer-pstring* (make-parameter #f))
(define (pstring->env pstring)
(cond ((or (not (string? pstring))
(not (string? (fluid *buffer-pstring*)))
(string-ci=? (fluid *buffer-pstring*) "COMMON-LISP-USER"))
(nearest-repl/environment))
((string-prefix? anonymous-package-prefix pstring)
(let ((object
(object-unhash
(string->number (string-tail pstring
(string-length
anonymous-package-prefix))
10
#t))))
(if (not (environment? object))
(error:wrong-type-datum object "environment"))
object))
(else
(package/environment (find-package (read-from-string pstring) #t)))))
(define (all-completions prefix environment)
(let ((prefix
(if (fluid (environment-lookup environment 'PARAM:PARSER-CANONICALIZE-SYMBOLS?))
(string-downcase prefix)
prefix))
(completions '()))
(for-each-interned-symbol
(lambda (symbol)
(if (and (string-prefix? prefix (symbol-name symbol))
(environment-bound? environment symbol))
(set! completions (cons (symbol-name symbol) completions)))
unspecific))
completions))
(define-record-type <istate>
(make-istate object parts actions next previous content)
istate?
(object istate-object)
(parts istate-parts)
(actions istate-actions)
(next istate-next set-istate-next!)
(previous istate-previous)
(content istate-content))
(define ($frame-locals-and-catch-tags nr)
`(nil
nil))
|
f6e0558c066f9a4e50fb48ec35fc27aadecb12fb0b4d8ccb5d203aef8c7fc805 | strymonas/strymonas-ocaml | benchmark_seq.ml | module Seqb = struct
open Seq
type 'a cde = 'a code
type 'a stream_raw = 'a t
type 'a stream = 'a t cde
let lift_tr1 : (('a -> 'b ) -> 'a stream_raw -> 'c stream_raw) cde
-> ('a cde -> 'b cde) -> 'a stream -> 'c stream =
fun tr f st -> .<.~tr (fun x -> .~(f .<x>.)) .~st>.
let lift_tr2 : (('a -> 'b -> 'c) -> ('a stream_raw -> 'b stream_raw -> 'c stream_raw) )cde
-> ('a cde -> 'b cde -> 'c cde) -> 'a stream -> 'b stream -> 'c stream =
fun tr f st1 st2 -> .<.~tr (fun x y -> .~(f .<x>. .<y>.)) .~st1 .~st2>.
let of_arr : 'a array cde -> 'a stream = fun x -> .<Array.to_seq .~x>.
let fold : ('z cde -> 'a cde -> 'z cde) -> 'z cde -> 'a stream -> 'z cde =
fun f z st -> .<fold_left (fun z x -> .~(f .<z>. .<x>.)) .~z .~st>.
let map : ('a cde -> 'b cde) -> 'a stream -> 'b stream =
fun f st -> lift_tr1 .<map>. f st
let flat_map : ('a cde -> 'b stream) -> 'a stream -> 'b stream =
fun f st -> lift_tr1 .<flat_map>. f st
let filter : ('a cde -> bool cde) -> 'a stream -> 'a stream =
fun f st -> lift_tr1 .<filter>. f st
let take : int cde -> 'a stream -> 'a stream =
fun n st -> .<Util.take .~n .~st>.
let zip_with : ('a cde -> 'b cde -> 'c cde) -> ('a stream -> 'b stream -> 'c stream) =
fun f st1 st2 -> lift_tr2 .<Util.map2>. f st1 st2
type byte = int
let byte_max = 255
let decode = fun st ->
st |> flat_map (fun el -> .<
unfold (fun i ->
if i < .~el then Some (false, i + 1)
else (
if i > .~el then None
else (
if i < byte_max then Some (true, i + 1)
else failwith "wrong sequence"
)
)
) 0>.)
end
module Benchmark_seq = struct
open Benchmark_types
open Benchmark
open Benchmark_abstract.Benchmark(Benchmark_abstract.CodeBasic)(Seqb)
(* Arrays used for benchmarking *)
let v = .< Array.init 100_000_000 (fun i -> i mod 10) >.;;
let vHi = .< Array.init 10_000_000 (fun i -> i mod 10) >.;;
let vLo = .< Array.init 10 (fun i -> i mod 10) >.;;
let vFaZ = .< Array.init 10_000 (fun i -> i) >.;;
let vZaF = .< Array.init 10_000_000 (fun i -> i) >.;;
let options = {
repetitions = 20;
final_f = (fun _ -> .<()>.);
}
let pr_int = {options with
final_f = fun x -> .<Printf.printf ""; Printf.printf "Result %d\n" .~x>.}
let check_int n = {options with
final_f = fun x -> .<Printf.printf ""; assert (.~x = n) >.}
let script =[|
perfS "sum_seq" v sum options;
perfS "sumOfSquares_seq" v sumOfSquares options;
perfS "sumOfSquaresEven_seq" v sumOfSquaresEven options;
perfS "mapsMegamorphic_seq" v maps options;
perfS "filtersMegamorphic_seq" v filters options;
perfS2 "cart_seq" vHi vLo cart options;
perfS2 "dotProduct_seq" vHi vHi dotProduct options;
perfS2 "flatMapAfterZip_seq" vFaZ vFaZ flatMap_after_zipWith options;
perfS2 "zipAfterFlatMap_seq" vZaF vZaF zipWith_after_flatMap options;
perfS2 "flatMapTake_seq" vHi vLo flat_map_take options;
perfS2 "zipFilterFilter_seq" v vHi zip_filter_filter options;
perfS2 "zipFlatMapFlatMap_seq" v vLo zip_flat_flat options;
perfS2 "runLengthDecoding_seq" v v decoding options;
|];;
let test = .<
print_endline "Last checked: Sep 9, 2022";
assert (.~(sum v) == 450000000);
assert (.~(sumOfSquares v) == 2850000000);
assert (.~(sumOfSquaresEven v) == 1200000000);
assert (.~(maps v) == 2268000000000);
assert (.~(filters v) == 170000000);
assert (.~(cart (vHi, vLo)) == 2025000000);
assert (.~(dotProduct (vHi, vHi)) == 285000000);
assert (.~(flatMap_after_zipWith (vFaZ, vFaZ)) == 1499850000000);
assert (.~(zipWith_after_flatMap (vZaF, vZaF)) == 99999990000000);
assert (.~(flat_map_take (vHi, vLo)) == 405000000);
assert (.~(zip_filter_filter (v, vHi)) == 64000000);
assert (.~(zip_flat_flat (v, vLo)) == 3250000000);
assert (.~(decoding (v, v)) == 100000000);
print_endline "All done"
>.
end
module M = Benchmark_seq
let main () =
let compiler = "ocamlfind ocamlopt -O2 -unsafe -nodynlink -linkpkg util.cmx" in
match Sys.argv with
| [|_;"test"|] ->
Benchmark.run_natively M.test
~compiler
(* ~save:true *)
| _ ->
Benchmark.run_script M.script
~compiler
let _ = main ()
| null | https://raw.githubusercontent.com/strymonas/strymonas-ocaml/29d83505b50a7dbb5d84b6a7d501b62ddadb92d4/benchmarks/benchmark_seq.ml | ocaml | Arrays used for benchmarking
~save:true | module Seqb = struct
open Seq
type 'a cde = 'a code
type 'a stream_raw = 'a t
type 'a stream = 'a t cde
let lift_tr1 : (('a -> 'b ) -> 'a stream_raw -> 'c stream_raw) cde
-> ('a cde -> 'b cde) -> 'a stream -> 'c stream =
fun tr f st -> .<.~tr (fun x -> .~(f .<x>.)) .~st>.
let lift_tr2 : (('a -> 'b -> 'c) -> ('a stream_raw -> 'b stream_raw -> 'c stream_raw) )cde
-> ('a cde -> 'b cde -> 'c cde) -> 'a stream -> 'b stream -> 'c stream =
fun tr f st1 st2 -> .<.~tr (fun x y -> .~(f .<x>. .<y>.)) .~st1 .~st2>.
let of_arr : 'a array cde -> 'a stream = fun x -> .<Array.to_seq .~x>.
let fold : ('z cde -> 'a cde -> 'z cde) -> 'z cde -> 'a stream -> 'z cde =
fun f z st -> .<fold_left (fun z x -> .~(f .<z>. .<x>.)) .~z .~st>.
let map : ('a cde -> 'b cde) -> 'a stream -> 'b stream =
fun f st -> lift_tr1 .<map>. f st
let flat_map : ('a cde -> 'b stream) -> 'a stream -> 'b stream =
fun f st -> lift_tr1 .<flat_map>. f st
let filter : ('a cde -> bool cde) -> 'a stream -> 'a stream =
fun f st -> lift_tr1 .<filter>. f st
let take : int cde -> 'a stream -> 'a stream =
fun n st -> .<Util.take .~n .~st>.
let zip_with : ('a cde -> 'b cde -> 'c cde) -> ('a stream -> 'b stream -> 'c stream) =
fun f st1 st2 -> lift_tr2 .<Util.map2>. f st1 st2
type byte = int
let byte_max = 255
let decode = fun st ->
st |> flat_map (fun el -> .<
unfold (fun i ->
if i < .~el then Some (false, i + 1)
else (
if i > .~el then None
else (
if i < byte_max then Some (true, i + 1)
else failwith "wrong sequence"
)
)
) 0>.)
end
module Benchmark_seq = struct
open Benchmark_types
open Benchmark
open Benchmark_abstract.Benchmark(Benchmark_abstract.CodeBasic)(Seqb)
let v = .< Array.init 100_000_000 (fun i -> i mod 10) >.;;
let vHi = .< Array.init 10_000_000 (fun i -> i mod 10) >.;;
let vLo = .< Array.init 10 (fun i -> i mod 10) >.;;
let vFaZ = .< Array.init 10_000 (fun i -> i) >.;;
let vZaF = .< Array.init 10_000_000 (fun i -> i) >.;;
let options = {
repetitions = 20;
final_f = (fun _ -> .<()>.);
}
let pr_int = {options with
final_f = fun x -> .<Printf.printf ""; Printf.printf "Result %d\n" .~x>.}
let check_int n = {options with
final_f = fun x -> .<Printf.printf ""; assert (.~x = n) >.}
let script =[|
perfS "sum_seq" v sum options;
perfS "sumOfSquares_seq" v sumOfSquares options;
perfS "sumOfSquaresEven_seq" v sumOfSquaresEven options;
perfS "mapsMegamorphic_seq" v maps options;
perfS "filtersMegamorphic_seq" v filters options;
perfS2 "cart_seq" vHi vLo cart options;
perfS2 "dotProduct_seq" vHi vHi dotProduct options;
perfS2 "flatMapAfterZip_seq" vFaZ vFaZ flatMap_after_zipWith options;
perfS2 "zipAfterFlatMap_seq" vZaF vZaF zipWith_after_flatMap options;
perfS2 "flatMapTake_seq" vHi vLo flat_map_take options;
perfS2 "zipFilterFilter_seq" v vHi zip_filter_filter options;
perfS2 "zipFlatMapFlatMap_seq" v vLo zip_flat_flat options;
perfS2 "runLengthDecoding_seq" v v decoding options;
|];;
let test = .<
print_endline "Last checked: Sep 9, 2022";
assert (.~(sum v) == 450000000);
assert (.~(sumOfSquares v) == 2850000000);
assert (.~(sumOfSquaresEven v) == 1200000000);
assert (.~(maps v) == 2268000000000);
assert (.~(filters v) == 170000000);
assert (.~(cart (vHi, vLo)) == 2025000000);
assert (.~(dotProduct (vHi, vHi)) == 285000000);
assert (.~(flatMap_after_zipWith (vFaZ, vFaZ)) == 1499850000000);
assert (.~(zipWith_after_flatMap (vZaF, vZaF)) == 99999990000000);
assert (.~(flat_map_take (vHi, vLo)) == 405000000);
assert (.~(zip_filter_filter (v, vHi)) == 64000000);
assert (.~(zip_flat_flat (v, vLo)) == 3250000000);
assert (.~(decoding (v, v)) == 100000000);
print_endline "All done"
>.
end
module M = Benchmark_seq
let main () =
let compiler = "ocamlfind ocamlopt -O2 -unsafe -nodynlink -linkpkg util.cmx" in
match Sys.argv with
| [|_;"test"|] ->
Benchmark.run_natively M.test
~compiler
| _ ->
Benchmark.run_script M.script
~compiler
let _ = main ()
|
cb6c32fc9c3f7fe9a9fd2789a4330ee4d98f303038eacfa9a8b518e8f9ac5d84 | slipstream/SlipStreamServer | scheduler.clj | (ns sixsq.slipstream.metering.scheduler
(:import (java.util.concurrent ScheduledThreadPoolExecutor TimeUnit)))
(def ^:const immediately 0)
(def ^:private num-threads 1)
(def ^:private pool (atom nil))
(defn- thread-pool []
(swap! pool (fn [p] (or p (ScheduledThreadPoolExecutor. num-threads)))))
(defn periodically
"Schedules function f to run every 'delay' milliseconds after a
delay of 'initial-delay'."
[f period]
(.scheduleAtFixedRate (thread-pool)
f
immediately period TimeUnit/MINUTES))
(defn shutdown
"Terminates all periodic tasks."
[]
(swap! pool (fn [p] (when p (.shutdown p)))))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/metering/src/sixsq/slipstream/metering/scheduler.clj | clojure | (ns sixsq.slipstream.metering.scheduler
(:import (java.util.concurrent ScheduledThreadPoolExecutor TimeUnit)))
(def ^:const immediately 0)
(def ^:private num-threads 1)
(def ^:private pool (atom nil))
(defn- thread-pool []
(swap! pool (fn [p] (or p (ScheduledThreadPoolExecutor. num-threads)))))
(defn periodically
"Schedules function f to run every 'delay' milliseconds after a
delay of 'initial-delay'."
[f period]
(.scheduleAtFixedRate (thread-pool)
f
immediately period TimeUnit/MINUTES))
(defn shutdown
"Terminates all periodic tasks."
[]
(swap! pool (fn [p] (when p (.shutdown p)))))
|
|
bcd9b1244018b834d11ba1a755d9d5d2a61117a9ac661b62e43ecbb05b144005 | bmeurer/ocamljit2 | viewer.ml | (*************************************************************************)
(* *)
(* Objective Caml LablTk library *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
(* General Public License, with the special exception on linking *)
(* described in file ../../../LICENSE. *)
(* *)
(*************************************************************************)
$ Id$
open StdLabels
open Tk
open Jg_tk
open Mytypes
open Longident
open Types
open Typedtree
open Env
open Searchpos
open Searchid
(* Managing the module list *)
let list_modules ~path =
List.fold_left path ~init:[] ~f:
begin fun modules dir ->
let l =
List.filter (Useunix.get_files_in_directory dir)
~f:(fun x -> Filename.check_suffix x ".cmi") in
let l = List.map l ~f:
begin fun x ->
String.capitalize (Filename.chop_suffix x ".cmi")
end in
List.fold_left l ~init:modules
~f:(fun modules item ->
if List.mem item modules then modules else item :: modules)
end
let reset_modules box =
Listbox.delete box ~first:(`Num 0) ~last:`End;
module_list := Sort.list (Jg_completion.lt_string ~nocase:true)
(list_modules ~path:!Config.load_path);
Listbox.insert box ~index:`End ~texts:!module_list;
Jg_box.recenter box ~index:(`Num 0)
(* How to display a symbol *)
let view_symbol ~kind ~env ?path id =
let name = match id with
Lident x -> x
| Ldot (_, x) -> x
| _ -> match kind with Pvalue | Ptype | Plabel -> "z" | _ -> "Z"
in
match kind with
Pvalue ->
let path, vd = lookup_value id env in
view_signature_item ~path ~env [Tsig_value (Ident.create name, vd)]
| Ptype -> view_type_id id ~env
| Plabel -> let ld = lookup_label id env in
begin match ld.lbl_res.desc with
Tconstr (path, _, _) -> view_type_decl path ~env
| _ -> ()
end
| Pconstructor ->
let cd = lookup_constructor id env in
begin match cd.cstr_res.desc with
Tconstr (cpath, _, _) ->
if Path.same cpath Predef.path_exn then
view_signature ~title:(string_of_longident id) ~env ?path
[Tsig_exception (Ident.create name, cd.cstr_args)]
else
view_type_decl cpath ~env
| _ -> ()
end
| Pmodule -> view_module_id id ~env
| Pmodtype -> view_modtype_id id ~env
| Pclass -> view_class_id id ~env
| Pcltype -> view_cltype_id id ~env
(* Create a list of symbols you can choose from *)
let choose_symbol ~title ~env ?signature ?path l =
if match path with
None -> false
| Some path -> is_shown_module path
then () else
let tl = Jg_toplevel.titled title in
Jg_bind.escape_destroy tl;
top_widgets := coe tl :: !top_widgets;
let buttons = Frame.create tl in
let all = Button.create buttons ~text:"Show all" ~padx:20
and ok = Jg_button.create_destroyer tl ~parent:buttons
and detach = Button.create buttons ~text:"Detach"
and edit = Button.create buttons ~text:"Impl"
and intf = Button.create buttons ~text:"Intf" in
let l = List.sort l ~cmp:(fun (li1, _) (li2,_) -> compare li1 li2) in
let nl = List.map l ~f:
begin fun (li, k) ->
string_of_longident li ^ " (" ^ string_of_kind k ^ ")"
end in
let fb = Frame.create tl in
let box =
new Jg_multibox.c fb ~cols:3 ~texts:nl ~maxheight:3 ~width:21 in
box#init;
box#bind_kbd ~events:[`KeyPressDetail"Escape"]
~action:(fun _ ~index -> destroy tl; break ());
if List.length nl > 9 then ignore (Jg_multibox.add_scrollbar box);
Jg_multibox.add_completion box ~action:
begin fun pos ->
let li, k = List.nth l pos in
let path =
match path, li with
None, Ldot (lip, _) ->
begin try
Some (fst (lookup_module lip env))
with Not_found -> None
end
| _ -> path
in view_symbol li ~kind:k ~env ?path
end;
pack [buttons] ~side:`Bottom ~fill:`X;
pack [fb] ~side:`Top ~fill:`Both ~expand:true;
begin match signature with
None -> pack [ok] ~fill:`X ~expand:true
| Some signature ->
Button.configure all ~command:
begin fun () ->
view_signature signature ~title ~env ?path
end;
pack [ok; all] ~side:`Right ~fill:`X ~expand:true
end;
begin match path with None -> ()
| Some path ->
let frame = Frame.create tl in
pack [frame] ~side:`Bottom ~fill:`X;
add_shown_module path
~widgets:{ mw_frame = frame; mw_title = None; mw_detach = detach;
mw_edit = edit; mw_intf = intf }
end
let choose_symbol_ref = ref choose_symbol
Search , both by type and name
let guess_search_mode s : [`Type | `Long | `Pattern] =
let is_type = ref false and is_long = ref false in
for i = 0 to String.length s - 2 do
if s.[i] = '-' && s.[i+1] = '>' then is_type := true;
if s.[i] = '.' then is_long := true
done;
if !is_type then `Type else if !is_long then `Long else `Pattern
let search_string ?(mode="symbol") ew =
let text = Entry.get ew in
try
if text = "" then () else
let l = match mode with
"Name" ->
begin match guess_search_mode text with
`Long -> search_string_symbol text
| `Pattern -> search_pattern_symbol text
| `Type -> search_string_type text ~mode:`Included
end
| "Type" -> search_string_type text ~mode:`Included
| "Exact" -> search_string_type text ~mode:`Exact
| _ -> assert false
in
match l with [] -> ()
| [lid,kind] -> view_symbol lid ~kind ~env:!start_env
| l -> choose_symbol ~title:"Choose symbol" ~env:!start_env l
with Searchid.Error (s,e) ->
Entry.icursor ew ~index:(`Num s)
let search_which = ref "Name"
let search_symbol () =
if !module_list = [] then
module_list := List.sort ~cmp:compare (list_modules ~path:!Config.load_path);
let tl = Jg_toplevel.titled "Search symbol" in
Jg_bind.escape_destroy tl;
let ew = Entry.create tl ~width:30 in
let choice = Frame.create tl
and which = Textvariable.create ~on:tl () in
let itself = Radiobutton.create choice ~text:"Itself"
~variable:which ~value:"Name"
and extype = Radiobutton.create choice ~text:"Exact type"
~variable:which ~value:"Exact"
and iotype = Radiobutton.create choice ~text:"Included type"
~variable:which ~value:"Type"
and buttons = Frame.create tl in
let search = Button.create buttons ~text:"Search" ~command:
begin fun () ->
search_which := Textvariable.get which;
search_string ew ~mode:!search_which
end
and ok = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel" in
Focus.set ew;
Jg_bind.return_invoke ew ~button:search;
Textvariable.set which !search_which;
pack [itself; extype; iotype] ~side:`Left ~anchor:`W;
pack [search; ok] ~side:`Left ~fill:`X ~expand:true;
pack [coe ew; coe choice; coe buttons]
~side:`Top ~fill:`X ~expand:true
(* Display the contents of a module *)
let ident_of_decl ~modlid = function
Tsig_value (id, _) -> Lident (Ident.name id), Pvalue
| Tsig_type (id, _, _) -> Lident (Ident.name id), Ptype
| Tsig_exception (id, _) -> Ldot (modlid, Ident.name id), Pconstructor
| Tsig_module (id, _, _) -> Lident (Ident.name id), Pmodule
| Tsig_modtype (id, _) -> Lident (Ident.name id), Pmodtype
| Tsig_class (id, _, _) -> Lident (Ident.name id), Pclass
| Tsig_cltype (id, _, _) -> Lident (Ident.name id), Pcltype
let view_defined ~env ?(show_all=false) modlid =
try match lookup_module modlid env with path, Tmty_signature sign ->
let rec iter_sign sign idents =
match sign with
[] -> List.rev idents
| decl :: rem ->
let rem = match decl, rem with
Tsig_class _, cty :: ty1 :: ty2 :: rem -> rem
| Tsig_cltype _, ty1 :: ty2 :: rem -> rem
| _, rem -> rem
in iter_sign rem (ident_of_decl ~modlid decl :: idents)
in
let l = iter_sign sign [] in
let title = string_of_path path in
let env = open_signature path sign env in
!choose_symbol_ref l ~title ~signature:sign ~env ~path;
if show_all then view_signature sign ~title ~env ~path
| _ -> ()
with Not_found -> ()
| Env.Error err ->
let tl, tw, finish = Jg_message.formatted ~title:"Error!" () in
Env.report_error Format.std_formatter err;
finish ()
(* Manage toplevel windows *)
let close_all_views () =
List.iter !top_widgets
~f:(fun tl -> try destroy tl with Protocol.TkError _ -> ());
top_widgets := []
(* Launch a shell *)
let shell_counter = ref 1
let default_shell = ref "ocaml"
let start_shell master =
let tl = Jg_toplevel.titled "Start New Shell" in
Wm.transient_set tl ~master;
let input = Frame.create tl
and buttons = Frame.create tl in
let ok = Button.create buttons ~text:"Ok"
and cancel = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel"
and labels = Frame.create input
and entries = Frame.create input in
let l1 = Label.create labels ~text:"Command:"
and l2 = Label.create labels ~text:"Title:"
and e1 =
Jg_entry.create entries ~command:(fun _ -> Button.invoke ok)
and e2 =
Jg_entry.create entries ~command:(fun _ -> Button.invoke ok)
and names = List.map ~f:fst (Shell.get_all ()) in
Entry.insert e1 ~index:`End ~text:!default_shell;
let shell_name () = "Shell #" ^ string_of_int !shell_counter in
while List.mem (shell_name ()) names do
incr shell_counter
done;
Entry.insert e2 ~index:`End ~text:(shell_name ());
Button.configure ok ~command:(fun () ->
if not (List.mem (Entry.get e2) names) then begin
default_shell := Entry.get e1;
Shell.f ~prog:!default_shell ~title:(Entry.get e2);
destroy tl
end);
pack [l1;l2] ~side:`Top ~anchor:`W;
pack [e1;e2] ~side:`Top ~fill:`X ~expand:true;
pack [labels;entries] ~side:`Left ~fill:`X ~expand:true;
pack [ok;cancel] ~side:`Left ~fill:`X ~expand:true;
pack [input;buttons] ~side:`Top ~fill:`X ~expand:true
(* Help window *)
let show_help () =
let tl = Jg_toplevel.titled "OCamlBrowser Help" in
Jg_bind.escape_destroy tl;
let fw, tw, sb = Jg_text.create_with_scrollbar tl in
let ok = Jg_button.create_destroyer ~parent:tl ~text:"Ok" tl in
Text.insert tw ~index:tend ~text:Help.text;
Text.configure tw ~state:`Disabled;
Jg_bind.enter_focus tw;
pack [tw] ~side:`Left ~fill:`Both ~expand:true;
pack [sb] ~side:`Right ~fill:`Y;
pack [fw] ~side:`Top ~expand:true ~fill:`Both;
pack [ok] ~side:`Bottom ~fill:`X
(* Launch the classical viewer *)
let f ?(dir=Unix.getcwd()) ?on () =
let (top, tl) = match on with
None ->
let tl = Jg_toplevel.titled "Module viewer" in
ignore (Jg_bind.escape_destroy tl); (tl, coe tl)
| Some top ->
Wm.title_set top "OCamlBrowser";
Wm.iconname_set top "OCamlBrowser";
let tl = Frame.create top in
bind tl ~events:[`Destroy] ~action:(fun _ -> exit 0);
pack [tl] ~expand:true ~fill:`Both;
(top, coe tl)
in
let menus = Jg_menu.menubar top in
let filemenu = new Jg_menu.c "File" ~parent:menus
and modmenu = new Jg_menu.c "Modules" ~parent:menus in
let fmbox, mbox, msb = Jg_box.create_with_scrollbar tl in
Jg_box.add_completion mbox ~nocase:true ~action:
begin fun index ->
view_defined (Lident (Listbox.get mbox ~index)) ~env:!start_env
end;
Setpath.add_update_hook (fun () -> reset_modules mbox);
let ew = Entry.create tl in
let buttons = Frame.create tl in
let search = Button.create buttons ~text:"Search" ~pady:1
~command:(fun () -> search_string ew)
and close =
Button.create buttons ~text:"Close all" ~pady:1 ~command:close_all_views
in
(* bindings *)
Jg_bind.enter_focus ew;
Jg_bind.return_invoke ew ~button:search;
bind close ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~action:(fun _ -> destroy tl);
(* File menu *)
filemenu#add_command "Open..."
~command:(fun () -> !editor_ref ~opendialog:true ());
filemenu#add_command "Editor..." ~command:(fun () -> !editor_ref ());
filemenu#add_command "Shell..." ~command:(fun () -> start_shell tl);
filemenu#add_command "Quit" ~command:(fun () -> destroy tl);
(* modules menu *)
modmenu#add_command "Path editor..."
~command:(fun () -> Setpath.set ~dir);
modmenu#add_command "Reset cache"
~command:(fun () -> reset_modules mbox; Env.reset_cache ());
modmenu#add_command "Search symbol..." ~command:search_symbol;
pack [close; search] ~fill:`X ~side:`Right ~expand:true;
pack [coe buttons; coe ew] ~fill:`X ~side:`Bottom;
pack [msb] ~side:`Right ~fill:`Y;
pack [mbox] ~side:`Left ~fill:`Both ~expand:true;
pack [fmbox] ~fill:`Both ~expand:true ~side:`Top;
reset_modules mbox
(* Smalltalk-like version *)
class st_viewer ?(dir=Unix.getcwd()) ?on () =
let (top, tl) = match on with
None ->
let tl = Jg_toplevel.titled "Module viewer" in
ignore (Jg_bind.escape_destroy tl); (tl, coe tl)
| Some top ->
Wm.title_set top "OCamlBrowser";
Wm.iconname_set top "OCamlBrowser";
let tl = Frame.create top in
bind tl ~events:[`Destroy] ~action:(fun _ -> exit 0);
pack [tl] ~side:`Bottom ~expand:true ~fill:`Both;
(top, coe tl)
in
let menus = Menu.create top ~name:"menubar" ~typ:`Menubar in
let () = Toplevel.configure top ~menu:menus in
let filemenu = new Jg_menu.c "File" ~parent:menus
and modmenu = new Jg_menu.c "Modules" ~parent:menus
and viewmenu = new Jg_menu.c "View" ~parent:menus
and helpmenu = new Jg_menu.c "Help" ~parent:menus in
let search_frame = Frame.create tl in
let boxes_frame = Frame.create tl ~name:"boxes" in
let label = Label.create tl ~anchor:`W ~padx:5 in
let view = Frame.create tl in
let buttons = Frame.create tl in
let _all = Button.create buttons ~text:"Show all" ~padx:20
and close = Button.create buttons ~text:"Close all" ~command:close_all_views
and detach = Button.create buttons ~text:"Detach"
and edit = Button.create buttons ~text:"Impl"
and intf = Button.create buttons ~text:"Intf" in
object (self)
val mutable boxes = []
val mutable show_all = fun () -> ()
method create_box =
let fmbox, mbox, sb = Jg_box.create_with_scrollbar boxes_frame in
bind mbox ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~action:(fun _ -> show_all ());
bind mbox ~events:[`Modified([`Double], `KeyPressDetail "Return")]
~action:(fun _ -> show_all ());
boxes <- boxes @ [fmbox, mbox];
pack [sb] ~side:`Right ~fill:`Y;
pack [mbox] ~side:`Left ~fill:`Both ~expand:true;
pack [fmbox] ~side:`Left ~fill:`Both ~expand:true;
fmbox, mbox
initializer
Search
let ew = Entry.create search_frame
and searchtype = Textvariable.create ~on:tl () in
bind ew ~events:[`KeyPressDetail "Return"] ~action:
(fun _ -> search_string ew ~mode:(Textvariable.get searchtype));
Jg_bind.enter_focus ew;
let search_button ?value text =
Radiobutton.create search_frame
~text ~variable:searchtype ~value:text in
let symbol = search_button "Name"
and atype = search_button "Type" in
Radiobutton.select symbol;
pack [Label.create search_frame ~text:"Search"] ~side:`Left ~ipadx:5;
pack [ew] ~fill:`X ~expand:true ~side:`Left;
pack [Label.create search_frame ~text:"by"] ~side:`Left ~ipadx:5;
pack [symbol; atype] ~side:`Left;
pack [Label.create search_frame] ~side:`Right
initializer
(* Boxes *)
let fmbox, mbox = self#create_box in
Jg_box.add_completion mbox ~nocase:true ~double:false ~action:
begin fun index ->
view_defined (Lident (Listbox.get mbox ~index)) ~env:!start_env
end;
Setpath.add_update_hook (fun () -> reset_modules mbox; self#hide_after 1);
List.iter [1;2] ~f:(fun _ -> ignore self#create_box);
Searchpos.default_frame := Some
{ mw_frame = view; mw_title = Some label;
mw_detach = detach; mw_edit = edit; mw_intf = intf };
Searchpos.set_path := self#set_path;
(* Buttons *)
pack [close] ~side:`Right ~fill:`X ~expand:true;
bind close ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~action:(fun _ -> destroy tl);
(* File menu *)
filemenu#add_command "Open..."
~command:(fun () -> !editor_ref ~opendialog:true ());
filemenu#add_command "Editor..." ~command:(fun () -> !editor_ref ());
filemenu#add_command "Shell..." ~command:(fun () -> start_shell tl);
filemenu#add_command "Quit" ~command:(fun () -> destroy tl);
(* View menu *)
viewmenu#add_command "Show all defs" ~command:(fun () -> show_all ());
let show_search = Textvariable.create ~on:tl () in
Textvariable.set show_search "1";
Menu.add_checkbutton viewmenu#menu ~label:"Search Entry"
~variable:show_search ~indicatoron:true ~state:`Active
~command:
begin fun () ->
let v = Textvariable.get show_search in
if v = "1" then begin
pack [search_frame] ~after:menus ~fill:`X
end else Pack.forget [search_frame]
end;
(* modules menu *)
modmenu#add_command "Path editor..."
~command:(fun () -> Setpath.set ~dir);
modmenu#add_command "Reset cache"
~command:(fun () -> reset_modules mbox; Env.reset_cache ());
modmenu#add_command "Search symbol..." ~command:search_symbol;
(* Help menu *)
helpmenu#add_command "Manual..." ~command:show_help;
pack [search_frame] ~fill:`X;
pack [boxes_frame] ~fill:`Both ~expand:true;
pack [buttons] ~fill:`X ~side:`Bottom;
pack [view] ~fill:`Both ~side:`Bottom ~expand:true;
reset_modules mbox
val mutable shown_paths = []
method hide_after n =
for i = n to List.length boxes - 1 do
let fm, box = List.nth boxes i in
if i < 3 then Listbox.delete box ~first:(`Num 0) ~last:`End
else destroy fm
done;
let rec firsts n = function [] -> []
| a :: l -> if n > 0 then a :: firsts (pred n) l else [] in
shown_paths <- firsts (n-1) shown_paths;
boxes <- firsts (max 3 n) boxes
method get_box ~path =
let rec path_index p = function
[] -> raise Not_found
| a :: l -> if Path.same p a then 1 else path_index p l + 1 in
try
let n = path_index path shown_paths in
self#hide_after (n+1);
n
with Not_found ->
match path with
Path.Pdot (path', _, _) ->
let n = self#get_box ~path:path' in
shown_paths <- shown_paths @ [path];
if n + 1 >= List.length boxes then ignore self#create_box;
n+1
| _ ->
self#hide_after 2;
shown_paths <- [path];
1
method set_path path ~sign =
let rec path_elems l path =
match path with
Path.Pdot (path, _, _) -> path_elems (path::l) path
| _ -> []
in
let path_elems path =
match path with
| Path.Pident _ -> [path]
| _ -> path_elems [] path
in
let see_path ~box:n ?(sign=[]) path =
let (_, box) = List.nth boxes n in
let texts = Listbox.get_range box ~first:(`Num 0) ~last:`End in
let rec index s = function
[] -> raise Not_found
| a :: l -> if a = s then 0 else 1 + index s l
in
try
let modlid, s =
match path with
Path.Pdot (p, s, _) -> longident_of_path p, s
| Path.Pident i -> Longident.Lident "M", Ident.name i
| _ -> assert false
in
let li, k =
if sign = [] then Longident.Lident s, Pmodule else
ident_of_decl ~modlid (List.hd sign) in
let s =
if n = 0 then string_of_longident li else
string_of_longident li ^ " (" ^ string_of_kind k ^ ")" in
let n = index s texts in
Listbox.see box (`Num n);
Listbox.activate box (`Num n)
with Not_found -> ()
in
let l = path_elems path in
if l <> [] then begin
List.iter l ~f:
begin fun path ->
if not (List.mem path shown_paths) then
view_symbol (longident_of_path path) ~kind:Pmodule
~env:Env.initial ~path;
let n = self#get_box path - 1 in
see_path path ~box:n
end;
see_path path ~box:(self#get_box path) ~sign
end
method choose_symbol ~title ~env ?signature ?path l =
let n =
match path with None -> 1
| Some path -> self#get_box ~path
in
let l = List.sort l ~cmp:(fun (li1, _) (li2,_) -> compare li1 li2) in
let nl = List.map l ~f:
begin fun (li, k) ->
string_of_longident li ^ " (" ^ string_of_kind k ^ ")"
end in
let _, box = List.nth boxes n in
Listbox.delete box ~first:(`Num 0) ~last:`End;
Listbox.insert box ~index:`End ~texts:nl;
let current = ref None in
let display index =
let `Num pos = Listbox.index box ~index in
try
let li, k = List.nth l pos in
self#hide_after (n+1);
if !current = Some (li,k) then () else
let path =
match path, li with
None, Ldot (lip, _) ->
begin try
Some (fst (lookup_module lip env))
with Not_found -> None
end
| _ -> path
in
current := Some (li,k);
view_symbol li ~kind:k ~env ?path
with Failure "nth" -> ()
in
Jg_box.add_completion box ~double:false ~action:display;
bind box ~events:[`KeyRelease] ~fields:[`Char]
~action:(fun ev -> display `Active);
begin match signature with
None -> ()
| Some signature ->
show_all <-
begin fun () ->
current := None;
view_signature signature ~title ~env ?path
end
end
end
let st_viewer ?dir ?on () =
let viewer = new st_viewer ?dir ?on () in
choose_symbol_ref := viewer#choose_symbol
| null | https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/otherlibs/labltk/browser/viewer.ml | ocaml | ***********************************************************************
Objective Caml LablTk library
General Public License, with the special exception on linking
described in file ../../../LICENSE.
***********************************************************************
Managing the module list
How to display a symbol
Create a list of symbols you can choose from
Display the contents of a module
Manage toplevel windows
Launch a shell
Help window
Launch the classical viewer
bindings
File menu
modules menu
Smalltalk-like version
Boxes
Buttons
File menu
View menu
modules menu
Help menu | , Kyoto University RIMS
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
$ Id$
open StdLabels
open Tk
open Jg_tk
open Mytypes
open Longident
open Types
open Typedtree
open Env
open Searchpos
open Searchid
let list_modules ~path =
List.fold_left path ~init:[] ~f:
begin fun modules dir ->
let l =
List.filter (Useunix.get_files_in_directory dir)
~f:(fun x -> Filename.check_suffix x ".cmi") in
let l = List.map l ~f:
begin fun x ->
String.capitalize (Filename.chop_suffix x ".cmi")
end in
List.fold_left l ~init:modules
~f:(fun modules item ->
if List.mem item modules then modules else item :: modules)
end
let reset_modules box =
Listbox.delete box ~first:(`Num 0) ~last:`End;
module_list := Sort.list (Jg_completion.lt_string ~nocase:true)
(list_modules ~path:!Config.load_path);
Listbox.insert box ~index:`End ~texts:!module_list;
Jg_box.recenter box ~index:(`Num 0)
let view_symbol ~kind ~env ?path id =
let name = match id with
Lident x -> x
| Ldot (_, x) -> x
| _ -> match kind with Pvalue | Ptype | Plabel -> "z" | _ -> "Z"
in
match kind with
Pvalue ->
let path, vd = lookup_value id env in
view_signature_item ~path ~env [Tsig_value (Ident.create name, vd)]
| Ptype -> view_type_id id ~env
| Plabel -> let ld = lookup_label id env in
begin match ld.lbl_res.desc with
Tconstr (path, _, _) -> view_type_decl path ~env
| _ -> ()
end
| Pconstructor ->
let cd = lookup_constructor id env in
begin match cd.cstr_res.desc with
Tconstr (cpath, _, _) ->
if Path.same cpath Predef.path_exn then
view_signature ~title:(string_of_longident id) ~env ?path
[Tsig_exception (Ident.create name, cd.cstr_args)]
else
view_type_decl cpath ~env
| _ -> ()
end
| Pmodule -> view_module_id id ~env
| Pmodtype -> view_modtype_id id ~env
| Pclass -> view_class_id id ~env
| Pcltype -> view_cltype_id id ~env
let choose_symbol ~title ~env ?signature ?path l =
if match path with
None -> false
| Some path -> is_shown_module path
then () else
let tl = Jg_toplevel.titled title in
Jg_bind.escape_destroy tl;
top_widgets := coe tl :: !top_widgets;
let buttons = Frame.create tl in
let all = Button.create buttons ~text:"Show all" ~padx:20
and ok = Jg_button.create_destroyer tl ~parent:buttons
and detach = Button.create buttons ~text:"Detach"
and edit = Button.create buttons ~text:"Impl"
and intf = Button.create buttons ~text:"Intf" in
let l = List.sort l ~cmp:(fun (li1, _) (li2,_) -> compare li1 li2) in
let nl = List.map l ~f:
begin fun (li, k) ->
string_of_longident li ^ " (" ^ string_of_kind k ^ ")"
end in
let fb = Frame.create tl in
let box =
new Jg_multibox.c fb ~cols:3 ~texts:nl ~maxheight:3 ~width:21 in
box#init;
box#bind_kbd ~events:[`KeyPressDetail"Escape"]
~action:(fun _ ~index -> destroy tl; break ());
if List.length nl > 9 then ignore (Jg_multibox.add_scrollbar box);
Jg_multibox.add_completion box ~action:
begin fun pos ->
let li, k = List.nth l pos in
let path =
match path, li with
None, Ldot (lip, _) ->
begin try
Some (fst (lookup_module lip env))
with Not_found -> None
end
| _ -> path
in view_symbol li ~kind:k ~env ?path
end;
pack [buttons] ~side:`Bottom ~fill:`X;
pack [fb] ~side:`Top ~fill:`Both ~expand:true;
begin match signature with
None -> pack [ok] ~fill:`X ~expand:true
| Some signature ->
Button.configure all ~command:
begin fun () ->
view_signature signature ~title ~env ?path
end;
pack [ok; all] ~side:`Right ~fill:`X ~expand:true
end;
begin match path with None -> ()
| Some path ->
let frame = Frame.create tl in
pack [frame] ~side:`Bottom ~fill:`X;
add_shown_module path
~widgets:{ mw_frame = frame; mw_title = None; mw_detach = detach;
mw_edit = edit; mw_intf = intf }
end
let choose_symbol_ref = ref choose_symbol
Search , both by type and name
let guess_search_mode s : [`Type | `Long | `Pattern] =
let is_type = ref false and is_long = ref false in
for i = 0 to String.length s - 2 do
if s.[i] = '-' && s.[i+1] = '>' then is_type := true;
if s.[i] = '.' then is_long := true
done;
if !is_type then `Type else if !is_long then `Long else `Pattern
let search_string ?(mode="symbol") ew =
let text = Entry.get ew in
try
if text = "" then () else
let l = match mode with
"Name" ->
begin match guess_search_mode text with
`Long -> search_string_symbol text
| `Pattern -> search_pattern_symbol text
| `Type -> search_string_type text ~mode:`Included
end
| "Type" -> search_string_type text ~mode:`Included
| "Exact" -> search_string_type text ~mode:`Exact
| _ -> assert false
in
match l with [] -> ()
| [lid,kind] -> view_symbol lid ~kind ~env:!start_env
| l -> choose_symbol ~title:"Choose symbol" ~env:!start_env l
with Searchid.Error (s,e) ->
Entry.icursor ew ~index:(`Num s)
let search_which = ref "Name"
let search_symbol () =
if !module_list = [] then
module_list := List.sort ~cmp:compare (list_modules ~path:!Config.load_path);
let tl = Jg_toplevel.titled "Search symbol" in
Jg_bind.escape_destroy tl;
let ew = Entry.create tl ~width:30 in
let choice = Frame.create tl
and which = Textvariable.create ~on:tl () in
let itself = Radiobutton.create choice ~text:"Itself"
~variable:which ~value:"Name"
and extype = Radiobutton.create choice ~text:"Exact type"
~variable:which ~value:"Exact"
and iotype = Radiobutton.create choice ~text:"Included type"
~variable:which ~value:"Type"
and buttons = Frame.create tl in
let search = Button.create buttons ~text:"Search" ~command:
begin fun () ->
search_which := Textvariable.get which;
search_string ew ~mode:!search_which
end
and ok = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel" in
Focus.set ew;
Jg_bind.return_invoke ew ~button:search;
Textvariable.set which !search_which;
pack [itself; extype; iotype] ~side:`Left ~anchor:`W;
pack [search; ok] ~side:`Left ~fill:`X ~expand:true;
pack [coe ew; coe choice; coe buttons]
~side:`Top ~fill:`X ~expand:true
let ident_of_decl ~modlid = function
Tsig_value (id, _) -> Lident (Ident.name id), Pvalue
| Tsig_type (id, _, _) -> Lident (Ident.name id), Ptype
| Tsig_exception (id, _) -> Ldot (modlid, Ident.name id), Pconstructor
| Tsig_module (id, _, _) -> Lident (Ident.name id), Pmodule
| Tsig_modtype (id, _) -> Lident (Ident.name id), Pmodtype
| Tsig_class (id, _, _) -> Lident (Ident.name id), Pclass
| Tsig_cltype (id, _, _) -> Lident (Ident.name id), Pcltype
let view_defined ~env ?(show_all=false) modlid =
try match lookup_module modlid env with path, Tmty_signature sign ->
let rec iter_sign sign idents =
match sign with
[] -> List.rev idents
| decl :: rem ->
let rem = match decl, rem with
Tsig_class _, cty :: ty1 :: ty2 :: rem -> rem
| Tsig_cltype _, ty1 :: ty2 :: rem -> rem
| _, rem -> rem
in iter_sign rem (ident_of_decl ~modlid decl :: idents)
in
let l = iter_sign sign [] in
let title = string_of_path path in
let env = open_signature path sign env in
!choose_symbol_ref l ~title ~signature:sign ~env ~path;
if show_all then view_signature sign ~title ~env ~path
| _ -> ()
with Not_found -> ()
| Env.Error err ->
let tl, tw, finish = Jg_message.formatted ~title:"Error!" () in
Env.report_error Format.std_formatter err;
finish ()
let close_all_views () =
List.iter !top_widgets
~f:(fun tl -> try destroy tl with Protocol.TkError _ -> ());
top_widgets := []
let shell_counter = ref 1
let default_shell = ref "ocaml"
let start_shell master =
let tl = Jg_toplevel.titled "Start New Shell" in
Wm.transient_set tl ~master;
let input = Frame.create tl
and buttons = Frame.create tl in
let ok = Button.create buttons ~text:"Ok"
and cancel = Jg_button.create_destroyer tl ~parent:buttons ~text:"Cancel"
and labels = Frame.create input
and entries = Frame.create input in
let l1 = Label.create labels ~text:"Command:"
and l2 = Label.create labels ~text:"Title:"
and e1 =
Jg_entry.create entries ~command:(fun _ -> Button.invoke ok)
and e2 =
Jg_entry.create entries ~command:(fun _ -> Button.invoke ok)
and names = List.map ~f:fst (Shell.get_all ()) in
Entry.insert e1 ~index:`End ~text:!default_shell;
let shell_name () = "Shell #" ^ string_of_int !shell_counter in
while List.mem (shell_name ()) names do
incr shell_counter
done;
Entry.insert e2 ~index:`End ~text:(shell_name ());
Button.configure ok ~command:(fun () ->
if not (List.mem (Entry.get e2) names) then begin
default_shell := Entry.get e1;
Shell.f ~prog:!default_shell ~title:(Entry.get e2);
destroy tl
end);
pack [l1;l2] ~side:`Top ~anchor:`W;
pack [e1;e2] ~side:`Top ~fill:`X ~expand:true;
pack [labels;entries] ~side:`Left ~fill:`X ~expand:true;
pack [ok;cancel] ~side:`Left ~fill:`X ~expand:true;
pack [input;buttons] ~side:`Top ~fill:`X ~expand:true
let show_help () =
let tl = Jg_toplevel.titled "OCamlBrowser Help" in
Jg_bind.escape_destroy tl;
let fw, tw, sb = Jg_text.create_with_scrollbar tl in
let ok = Jg_button.create_destroyer ~parent:tl ~text:"Ok" tl in
Text.insert tw ~index:tend ~text:Help.text;
Text.configure tw ~state:`Disabled;
Jg_bind.enter_focus tw;
pack [tw] ~side:`Left ~fill:`Both ~expand:true;
pack [sb] ~side:`Right ~fill:`Y;
pack [fw] ~side:`Top ~expand:true ~fill:`Both;
pack [ok] ~side:`Bottom ~fill:`X
let f ?(dir=Unix.getcwd()) ?on () =
let (top, tl) = match on with
None ->
let tl = Jg_toplevel.titled "Module viewer" in
ignore (Jg_bind.escape_destroy tl); (tl, coe tl)
| Some top ->
Wm.title_set top "OCamlBrowser";
Wm.iconname_set top "OCamlBrowser";
let tl = Frame.create top in
bind tl ~events:[`Destroy] ~action:(fun _ -> exit 0);
pack [tl] ~expand:true ~fill:`Both;
(top, coe tl)
in
let menus = Jg_menu.menubar top in
let filemenu = new Jg_menu.c "File" ~parent:menus
and modmenu = new Jg_menu.c "Modules" ~parent:menus in
let fmbox, mbox, msb = Jg_box.create_with_scrollbar tl in
Jg_box.add_completion mbox ~nocase:true ~action:
begin fun index ->
view_defined (Lident (Listbox.get mbox ~index)) ~env:!start_env
end;
Setpath.add_update_hook (fun () -> reset_modules mbox);
let ew = Entry.create tl in
let buttons = Frame.create tl in
let search = Button.create buttons ~text:"Search" ~pady:1
~command:(fun () -> search_string ew)
and close =
Button.create buttons ~text:"Close all" ~pady:1 ~command:close_all_views
in
Jg_bind.enter_focus ew;
Jg_bind.return_invoke ew ~button:search;
bind close ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~action:(fun _ -> destroy tl);
filemenu#add_command "Open..."
~command:(fun () -> !editor_ref ~opendialog:true ());
filemenu#add_command "Editor..." ~command:(fun () -> !editor_ref ());
filemenu#add_command "Shell..." ~command:(fun () -> start_shell tl);
filemenu#add_command "Quit" ~command:(fun () -> destroy tl);
modmenu#add_command "Path editor..."
~command:(fun () -> Setpath.set ~dir);
modmenu#add_command "Reset cache"
~command:(fun () -> reset_modules mbox; Env.reset_cache ());
modmenu#add_command "Search symbol..." ~command:search_symbol;
pack [close; search] ~fill:`X ~side:`Right ~expand:true;
pack [coe buttons; coe ew] ~fill:`X ~side:`Bottom;
pack [msb] ~side:`Right ~fill:`Y;
pack [mbox] ~side:`Left ~fill:`Both ~expand:true;
pack [fmbox] ~fill:`Both ~expand:true ~side:`Top;
reset_modules mbox
class st_viewer ?(dir=Unix.getcwd()) ?on () =
let (top, tl) = match on with
None ->
let tl = Jg_toplevel.titled "Module viewer" in
ignore (Jg_bind.escape_destroy tl); (tl, coe tl)
| Some top ->
Wm.title_set top "OCamlBrowser";
Wm.iconname_set top "OCamlBrowser";
let tl = Frame.create top in
bind tl ~events:[`Destroy] ~action:(fun _ -> exit 0);
pack [tl] ~side:`Bottom ~expand:true ~fill:`Both;
(top, coe tl)
in
let menus = Menu.create top ~name:"menubar" ~typ:`Menubar in
let () = Toplevel.configure top ~menu:menus in
let filemenu = new Jg_menu.c "File" ~parent:menus
and modmenu = new Jg_menu.c "Modules" ~parent:menus
and viewmenu = new Jg_menu.c "View" ~parent:menus
and helpmenu = new Jg_menu.c "Help" ~parent:menus in
let search_frame = Frame.create tl in
let boxes_frame = Frame.create tl ~name:"boxes" in
let label = Label.create tl ~anchor:`W ~padx:5 in
let view = Frame.create tl in
let buttons = Frame.create tl in
let _all = Button.create buttons ~text:"Show all" ~padx:20
and close = Button.create buttons ~text:"Close all" ~command:close_all_views
and detach = Button.create buttons ~text:"Detach"
and edit = Button.create buttons ~text:"Impl"
and intf = Button.create buttons ~text:"Intf" in
object (self)
val mutable boxes = []
val mutable show_all = fun () -> ()
method create_box =
let fmbox, mbox, sb = Jg_box.create_with_scrollbar boxes_frame in
bind mbox ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~action:(fun _ -> show_all ());
bind mbox ~events:[`Modified([`Double], `KeyPressDetail "Return")]
~action:(fun _ -> show_all ());
boxes <- boxes @ [fmbox, mbox];
pack [sb] ~side:`Right ~fill:`Y;
pack [mbox] ~side:`Left ~fill:`Both ~expand:true;
pack [fmbox] ~side:`Left ~fill:`Both ~expand:true;
fmbox, mbox
initializer
Search
let ew = Entry.create search_frame
and searchtype = Textvariable.create ~on:tl () in
bind ew ~events:[`KeyPressDetail "Return"] ~action:
(fun _ -> search_string ew ~mode:(Textvariable.get searchtype));
Jg_bind.enter_focus ew;
let search_button ?value text =
Radiobutton.create search_frame
~text ~variable:searchtype ~value:text in
let symbol = search_button "Name"
and atype = search_button "Type" in
Radiobutton.select symbol;
pack [Label.create search_frame ~text:"Search"] ~side:`Left ~ipadx:5;
pack [ew] ~fill:`X ~expand:true ~side:`Left;
pack [Label.create search_frame ~text:"by"] ~side:`Left ~ipadx:5;
pack [symbol; atype] ~side:`Left;
pack [Label.create search_frame] ~side:`Right
initializer
let fmbox, mbox = self#create_box in
Jg_box.add_completion mbox ~nocase:true ~double:false ~action:
begin fun index ->
view_defined (Lident (Listbox.get mbox ~index)) ~env:!start_env
end;
Setpath.add_update_hook (fun () -> reset_modules mbox; self#hide_after 1);
List.iter [1;2] ~f:(fun _ -> ignore self#create_box);
Searchpos.default_frame := Some
{ mw_frame = view; mw_title = Some label;
mw_detach = detach; mw_edit = edit; mw_intf = intf };
Searchpos.set_path := self#set_path;
pack [close] ~side:`Right ~fill:`X ~expand:true;
bind close ~events:[`Modified([`Double], `ButtonPressDetail 1)]
~action:(fun _ -> destroy tl);
filemenu#add_command "Open..."
~command:(fun () -> !editor_ref ~opendialog:true ());
filemenu#add_command "Editor..." ~command:(fun () -> !editor_ref ());
filemenu#add_command "Shell..." ~command:(fun () -> start_shell tl);
filemenu#add_command "Quit" ~command:(fun () -> destroy tl);
viewmenu#add_command "Show all defs" ~command:(fun () -> show_all ());
let show_search = Textvariable.create ~on:tl () in
Textvariable.set show_search "1";
Menu.add_checkbutton viewmenu#menu ~label:"Search Entry"
~variable:show_search ~indicatoron:true ~state:`Active
~command:
begin fun () ->
let v = Textvariable.get show_search in
if v = "1" then begin
pack [search_frame] ~after:menus ~fill:`X
end else Pack.forget [search_frame]
end;
modmenu#add_command "Path editor..."
~command:(fun () -> Setpath.set ~dir);
modmenu#add_command "Reset cache"
~command:(fun () -> reset_modules mbox; Env.reset_cache ());
modmenu#add_command "Search symbol..." ~command:search_symbol;
helpmenu#add_command "Manual..." ~command:show_help;
pack [search_frame] ~fill:`X;
pack [boxes_frame] ~fill:`Both ~expand:true;
pack [buttons] ~fill:`X ~side:`Bottom;
pack [view] ~fill:`Both ~side:`Bottom ~expand:true;
reset_modules mbox
val mutable shown_paths = []
method hide_after n =
for i = n to List.length boxes - 1 do
let fm, box = List.nth boxes i in
if i < 3 then Listbox.delete box ~first:(`Num 0) ~last:`End
else destroy fm
done;
let rec firsts n = function [] -> []
| a :: l -> if n > 0 then a :: firsts (pred n) l else [] in
shown_paths <- firsts (n-1) shown_paths;
boxes <- firsts (max 3 n) boxes
method get_box ~path =
let rec path_index p = function
[] -> raise Not_found
| a :: l -> if Path.same p a then 1 else path_index p l + 1 in
try
let n = path_index path shown_paths in
self#hide_after (n+1);
n
with Not_found ->
match path with
Path.Pdot (path', _, _) ->
let n = self#get_box ~path:path' in
shown_paths <- shown_paths @ [path];
if n + 1 >= List.length boxes then ignore self#create_box;
n+1
| _ ->
self#hide_after 2;
shown_paths <- [path];
1
method set_path path ~sign =
let rec path_elems l path =
match path with
Path.Pdot (path, _, _) -> path_elems (path::l) path
| _ -> []
in
let path_elems path =
match path with
| Path.Pident _ -> [path]
| _ -> path_elems [] path
in
let see_path ~box:n ?(sign=[]) path =
let (_, box) = List.nth boxes n in
let texts = Listbox.get_range box ~first:(`Num 0) ~last:`End in
let rec index s = function
[] -> raise Not_found
| a :: l -> if a = s then 0 else 1 + index s l
in
try
let modlid, s =
match path with
Path.Pdot (p, s, _) -> longident_of_path p, s
| Path.Pident i -> Longident.Lident "M", Ident.name i
| _ -> assert false
in
let li, k =
if sign = [] then Longident.Lident s, Pmodule else
ident_of_decl ~modlid (List.hd sign) in
let s =
if n = 0 then string_of_longident li else
string_of_longident li ^ " (" ^ string_of_kind k ^ ")" in
let n = index s texts in
Listbox.see box (`Num n);
Listbox.activate box (`Num n)
with Not_found -> ()
in
let l = path_elems path in
if l <> [] then begin
List.iter l ~f:
begin fun path ->
if not (List.mem path shown_paths) then
view_symbol (longident_of_path path) ~kind:Pmodule
~env:Env.initial ~path;
let n = self#get_box path - 1 in
see_path path ~box:n
end;
see_path path ~box:(self#get_box path) ~sign
end
method choose_symbol ~title ~env ?signature ?path l =
let n =
match path with None -> 1
| Some path -> self#get_box ~path
in
let l = List.sort l ~cmp:(fun (li1, _) (li2,_) -> compare li1 li2) in
let nl = List.map l ~f:
begin fun (li, k) ->
string_of_longident li ^ " (" ^ string_of_kind k ^ ")"
end in
let _, box = List.nth boxes n in
Listbox.delete box ~first:(`Num 0) ~last:`End;
Listbox.insert box ~index:`End ~texts:nl;
let current = ref None in
let display index =
let `Num pos = Listbox.index box ~index in
try
let li, k = List.nth l pos in
self#hide_after (n+1);
if !current = Some (li,k) then () else
let path =
match path, li with
None, Ldot (lip, _) ->
begin try
Some (fst (lookup_module lip env))
with Not_found -> None
end
| _ -> path
in
current := Some (li,k);
view_symbol li ~kind:k ~env ?path
with Failure "nth" -> ()
in
Jg_box.add_completion box ~double:false ~action:display;
bind box ~events:[`KeyRelease] ~fields:[`Char]
~action:(fun ev -> display `Active);
begin match signature with
None -> ()
| Some signature ->
show_all <-
begin fun () ->
current := None;
view_signature signature ~title ~env ?path
end
end
end
let st_viewer ?dir ?on () =
let viewer = new st_viewer ?dir ?on () in
choose_symbol_ref := viewer#choose_symbol
|
9a58dd4b40cb0e9592e21fefcea994c5625420ee3702a545a266a9026d11c6ac | borodust/bodge-ui | packages.lisp | (bodge-util:define-package :bodge-ui
(:use :cl :bodge-memory :bodge-util :bodge-math :cffi-c-ref)
(:export #:make-ui
#:push-compose-task
#:with-ui-access
#:compose-ui
#:root-panel
#:custom-font
#:calculate-text-width
#:text-line-height
#:renderer-canvas-width
#:renderer-canvas-height
#:renderer-default-font
#:render-ui
#:defpanel
#:find-element
#:hiddenp
#:minimizedp
#:on-close
#:on-minimize
#:on-restore
#:on-move
#:update-panel-position
#:panel-position
#:with-panel-position
#:update-panel-size
#:with-panel-dimensions
#:panel-size
#:add-panel
#:remove-panel
#:remove-all-panels
#:minimize-panel
#:restore-panel
#:name-of
#:vertical-layout
#:horizontal-layout
#:button
#:label
#:text-edit
#:combo-box
#:color-box
#:spacing
#:color-picker
#:float-property
#:radio
#:activated
#:radio-group
#:active-radio-button-of
#:check-box
#:checked
#:notebook
#:tab
#:styled-group
#:scroll-area
#:update-area-scroll-position
#:with-area-scroll-position
#:area-scroll-position
#:text-of
#:deflayout
#:custom-widget
#:render-custom-widget
#:initialize-custom-layout
#:custom-widget-width
#:custom-widget-height
#:custom-widget-on-hover
#:custom-widget-on-leave
#:custom-widget-on-click
#:custom-widget-on-move
#:custom-widget-on-mouse-press
#:custom-widget-on-mouse-release
#:custom-widget-hovered-p
#:custom-widget-clicked-p
#:custom-widget-pressed-p
#:discard-custom-widget-state
#:transition-custom-widget-to
#:custom-widget-instance
#:next-keyboard-interaction
#:next-mouse-interaction
#:last-cursor-position
#:next-character
#:next-scroll
#:docommands
#:command-type
#:scissor-origin
#:scissor-width
#:scissor-height
#:line-origin
#:line-end
#:line-color
#:line-thickness
#:curve-origin
#:curve-end
#:curve-first-control-point
#:curve-second-control-point
#:curve-color
#:curve-thickness
#:rect-origin
#:rect-width
#:rect-height
#:rect-stroke-color
#:rect-stroke-thickness
#:rect-rounding
#:filled-rect-origin
#:filled-rect-width
#:filled-rect-height
#:filled-rect-color
#:filled-rect-rounding
#:multi-color-rect-origin
#:multi-color-rect-width
#:multi-color-rect-height
#:multi-color-rect-left-color
#:multi-color-rect-top-color
#:multi-color-rect-bottom-color
#:multi-color-rect-right-color
#:ellipse-origin
#:ellipse-radius-x
#:ellipse-radius-y
#:ellipse-stroke-color
#:ellipse-stroke-thickness
#:filled-ellipse-origin
#:filled-ellipse-radius-x
#:filled-ellipse-radius-y
#:filled-ellipse-color
#:arc-origin
#:arc-radius
#:arc-start-angle
#:arc-end-angle
#:arc-stroke-color
#:arc-stroke-thickness
#:filled-arc-origin
#:filled-arc-radius
#:filled-arc-start-angle
#:filled-arc-end-angle
#:filled-arc-color
#:triangle-origin
#:triangle-second-vertex
#:triangle-third-vertex
#:triangle-stroke-color
#:triangle-stroke-thickness
#:filled-triangle-origin
#:filled-triangle-second-vertex
#:filled-triangle-third-vertex
#:filled-triangle-color
#:polygon-vertices
#:polygon-stroke-color
#:polygon-stroke-thickness
#:filled-polygon-vertices
#:filled-polygon-color
#:polyline-vertices
#:polyline-color
#:polyline-thickness
#:text-box-origin
#:text-background-color
#:text-foreground-color
#:text-box-width
#:text-box-height
#:text-string
#:image-origin
#:image-width
#:image-height
#:image-color))
| null | https://raw.githubusercontent.com/borodust/bodge-ui/94fb37de3dcfe18f97945a29c70f451ebfb6966b/src/packages.lisp | lisp | (bodge-util:define-package :bodge-ui
(:use :cl :bodge-memory :bodge-util :bodge-math :cffi-c-ref)
(:export #:make-ui
#:push-compose-task
#:with-ui-access
#:compose-ui
#:root-panel
#:custom-font
#:calculate-text-width
#:text-line-height
#:renderer-canvas-width
#:renderer-canvas-height
#:renderer-default-font
#:render-ui
#:defpanel
#:find-element
#:hiddenp
#:minimizedp
#:on-close
#:on-minimize
#:on-restore
#:on-move
#:update-panel-position
#:panel-position
#:with-panel-position
#:update-panel-size
#:with-panel-dimensions
#:panel-size
#:add-panel
#:remove-panel
#:remove-all-panels
#:minimize-panel
#:restore-panel
#:name-of
#:vertical-layout
#:horizontal-layout
#:button
#:label
#:text-edit
#:combo-box
#:color-box
#:spacing
#:color-picker
#:float-property
#:radio
#:activated
#:radio-group
#:active-radio-button-of
#:check-box
#:checked
#:notebook
#:tab
#:styled-group
#:scroll-area
#:update-area-scroll-position
#:with-area-scroll-position
#:area-scroll-position
#:text-of
#:deflayout
#:custom-widget
#:render-custom-widget
#:initialize-custom-layout
#:custom-widget-width
#:custom-widget-height
#:custom-widget-on-hover
#:custom-widget-on-leave
#:custom-widget-on-click
#:custom-widget-on-move
#:custom-widget-on-mouse-press
#:custom-widget-on-mouse-release
#:custom-widget-hovered-p
#:custom-widget-clicked-p
#:custom-widget-pressed-p
#:discard-custom-widget-state
#:transition-custom-widget-to
#:custom-widget-instance
#:next-keyboard-interaction
#:next-mouse-interaction
#:last-cursor-position
#:next-character
#:next-scroll
#:docommands
#:command-type
#:scissor-origin
#:scissor-width
#:scissor-height
#:line-origin
#:line-end
#:line-color
#:line-thickness
#:curve-origin
#:curve-end
#:curve-first-control-point
#:curve-second-control-point
#:curve-color
#:curve-thickness
#:rect-origin
#:rect-width
#:rect-height
#:rect-stroke-color
#:rect-stroke-thickness
#:rect-rounding
#:filled-rect-origin
#:filled-rect-width
#:filled-rect-height
#:filled-rect-color
#:filled-rect-rounding
#:multi-color-rect-origin
#:multi-color-rect-width
#:multi-color-rect-height
#:multi-color-rect-left-color
#:multi-color-rect-top-color
#:multi-color-rect-bottom-color
#:multi-color-rect-right-color
#:ellipse-origin
#:ellipse-radius-x
#:ellipse-radius-y
#:ellipse-stroke-color
#:ellipse-stroke-thickness
#:filled-ellipse-origin
#:filled-ellipse-radius-x
#:filled-ellipse-radius-y
#:filled-ellipse-color
#:arc-origin
#:arc-radius
#:arc-start-angle
#:arc-end-angle
#:arc-stroke-color
#:arc-stroke-thickness
#:filled-arc-origin
#:filled-arc-radius
#:filled-arc-start-angle
#:filled-arc-end-angle
#:filled-arc-color
#:triangle-origin
#:triangle-second-vertex
#:triangle-third-vertex
#:triangle-stroke-color
#:triangle-stroke-thickness
#:filled-triangle-origin
#:filled-triangle-second-vertex
#:filled-triangle-third-vertex
#:filled-triangle-color
#:polygon-vertices
#:polygon-stroke-color
#:polygon-stroke-thickness
#:filled-polygon-vertices
#:filled-polygon-color
#:polyline-vertices
#:polyline-color
#:polyline-thickness
#:text-box-origin
#:text-background-color
#:text-foreground-color
#:text-box-width
#:text-box-height
#:text-string
#:image-origin
#:image-width
#:image-height
#:image-color))
|
|
5223d5a936ce429e947cade8f4890abecc5ccf0fb2c56f74aa4b2c76ca2f0542 | diagrams/diagrams-contrib | Grid.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Layout.Grid
Copyright : ( c ) 2014 Pontus
-- License : BSD-style (see LICENSE)
-- Maintainer :
--
-- Functions for effortlessly putting lists of diagrams in a grid layout.
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Layout.Grid
(
gridCat
, gridCat'
, gridSnake
, gridSnake'
, gridWith
, sameBoundingRect
, sameBoundingSquare
) where
import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.List.Split (chunksOf)
import Diagrams.Prelude
-- * Grid Layout
-- | Puts a list of diagrams in a grid, left-to-right, top-to-bottom.
-- The grid is as close to square as possible.
--
-- > import Diagrams.TwoD.Layout.Grid
> gridCatExample = gridCat $ map ( flip regPoly 1 ) [ 3 .. 10 ]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridCatExample.svg#diagram=gridCatExample&width=200>>
gridCat
:: TypeableFloat n
=> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridCat [] = mempty
gridCat diagrams = gridCat' (intSqrt $ length diagrams) diagrams
-- | Same as 'gridCat', but with a specified number of columns.
--
-- > import Diagrams.TwoD.Layout.Grid
> gridCatExample ' = gridCat ' 4 $ map ( flip regPoly 1 ) [ 3 .. 10 ]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridCatExample'.svg#diagram=gridCatExample'&width=200>>
gridCat'
:: TypeableFloat n
=> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridCat' = gridAnimal id
-- | Puts a list of diagrams in a grid, alternating left-to-right
-- and right-to-left. Useful for comparing sequences of diagrams.
-- The grid is as close to square as possible.
--
-- > import Diagrams.TwoD.Layout.Grid
> gridSnakeExample = gridSnake $ map ( flip regPoly 1 ) [ 3 .. 10 ]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridSnakeExample.svg#diagram=gridSnakeExample&width=200>>
gridSnake
:: TypeableFloat n
=> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridSnake [] = mempty
gridSnake diagrams = gridSnake' (intSqrt $ length diagrams) diagrams
-- | Same as 'gridSnake', but with a specified number of columns.
--
-- > import Diagrams.TwoD.Layout.Grid
> gridSnakeExample ' = gridSnake ' 4 $ map ( flip regPoly 1 ) [ 3 .. 10 ]
--
-- <<diagrams/src_Diagrams_TwoD_Layout_Grid_gridSnakeExample'.svg#diagram=gridSnakeExample'&width=200>>
gridSnake'
:: TypeableFloat n
=> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridSnake' = gridAnimal (everyOther reverse)
-- | Generalisation of gridCat and gridSnake to not repeat code.
gridAnimal
:: TypeableFloat n
=> ([[QDiagram b V2 n Any]] -> [[QDiagram b V2 n Any]]) -> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridAnimal rowFunction cols = vcat . map hcat . rowFunction
. chunksOf cols . sameBoundingRect . padList cols mempty
| ` gridWith f ( cols , rows ) ` uses ` f ` , a function of two
zero - indexed integer coordinates , to generate a grid of diagrams
-- with the specified dimensions.
gridWith
:: TypeableFloat n
=> (Int -> Int -> QDiagram b V2 n Any) -> (Int, Int)
-> QDiagram b V2 n Any
gridWith f (cols, rows) = gridCat' cols diagrams
where
diagrams = [ f x y | y <- [0..rows - 1] , x <- [0..cols - 1] ]
-- * Bounding boxes
-- | Make all diagrams have the same bounding square,
-- one that bounds them all.
sameBoundingSquare
:: forall b n. TypeableFloat n
=> [QDiagram b V2 n Any]
-> [QDiagram b V2 n Any]
sameBoundingSquare diagrams = map frameOne diagrams
where
biggest = maximumBy (comparing maxDim) diagrams
maxDim diagram = max (width diagram) (height diagram)
centerP = centerPoint biggest
padSquare = (square (maxDim biggest) :: D V2 n) # phantom
frameOne = atop padSquare . moveOriginTo centerP
-- | Make all diagrams have the same bounding rect,
-- one that bounds them all.
sameBoundingRect
:: forall n b. TypeableFloat n
=> [QDiagram b V2 n Any]
-> [QDiagram b V2 n Any]
sameBoundingRect diagrams = map frameOne diagrams
where
widest = maximumBy (comparing width) diagrams
tallest = maximumBy (comparing height) diagrams
(xCenter :& _) = coords (centerPoint widest)
(_ :& yCenter) = coords (centerPoint tallest)
padRect = (rect (width widest) (height tallest) :: D V2 n) # phantom
frameOne = atop padRect . moveOriginTo (xCenter ^& yCenter)
-- * Helper functions.
intSqrt :: Int -> Int
intSqrt = round . sqrt . (fromIntegral :: Int -> Float)
everyOther :: (a -> a) -> [a] -> [a]
everyOther f = zipWith ($) (cycle [id, f])
padList :: Int -> a -> [a] -> [a]
padList m padding xs = xs ++ replicate (mod (- length xs) m) padding
| null | https://raw.githubusercontent.com/diagrams/diagrams-contrib/6b1e5f9802e8f2a5c3ea97cb0c29fd15912450ce/src/Diagrams/TwoD/Layout/Grid.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
---------------------------------------------------------------------------
|
Module : Diagrams.TwoD.Layout.Grid
License : BSD-style (see LICENSE)
Maintainer :
Functions for effortlessly putting lists of diagrams in a grid layout.
---------------------------------------------------------------------------
* Grid Layout
| Puts a list of diagrams in a grid, left-to-right, top-to-bottom.
The grid is as close to square as possible.
> import Diagrams.TwoD.Layout.Grid
<<diagrams/src_Diagrams_TwoD_Layout_Grid_gridCatExample.svg#diagram=gridCatExample&width=200>>
| Same as 'gridCat', but with a specified number of columns.
> import Diagrams.TwoD.Layout.Grid
<<diagrams/src_Diagrams_TwoD_Layout_Grid_gridCatExample'.svg#diagram=gridCatExample'&width=200>>
| Puts a list of diagrams in a grid, alternating left-to-right
and right-to-left. Useful for comparing sequences of diagrams.
The grid is as close to square as possible.
> import Diagrams.TwoD.Layout.Grid
<<diagrams/src_Diagrams_TwoD_Layout_Grid_gridSnakeExample.svg#diagram=gridSnakeExample&width=200>>
| Same as 'gridSnake', but with a specified number of columns.
> import Diagrams.TwoD.Layout.Grid
<<diagrams/src_Diagrams_TwoD_Layout_Grid_gridSnakeExample'.svg#diagram=gridSnakeExample'&width=200>>
| Generalisation of gridCat and gridSnake to not repeat code.
with the specified dimensions.
* Bounding boxes
| Make all diagrams have the same bounding square,
one that bounds them all.
| Make all diagrams have the same bounding rect,
one that bounds them all.
* Helper functions. | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
Copyright : ( c ) 2014 Pontus
module Diagrams.TwoD.Layout.Grid
(
gridCat
, gridCat'
, gridSnake
, gridSnake'
, gridWith
, sameBoundingRect
, sameBoundingSquare
) where
import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.List.Split (chunksOf)
import Diagrams.Prelude
> gridCatExample = gridCat $ map ( flip regPoly 1 ) [ 3 .. 10 ]
gridCat
:: TypeableFloat n
=> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridCat [] = mempty
gridCat diagrams = gridCat' (intSqrt $ length diagrams) diagrams
> gridCatExample ' = gridCat ' 4 $ map ( flip regPoly 1 ) [ 3 .. 10 ]
gridCat'
:: TypeableFloat n
=> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridCat' = gridAnimal id
> gridSnakeExample = gridSnake $ map ( flip regPoly 1 ) [ 3 .. 10 ]
gridSnake
:: TypeableFloat n
=> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridSnake [] = mempty
gridSnake diagrams = gridSnake' (intSqrt $ length diagrams) diagrams
> gridSnakeExample ' = gridSnake ' 4 $ map ( flip regPoly 1 ) [ 3 .. 10 ]
gridSnake'
:: TypeableFloat n
=> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridSnake' = gridAnimal (everyOther reverse)
gridAnimal
:: TypeableFloat n
=> ([[QDiagram b V2 n Any]] -> [[QDiagram b V2 n Any]]) -> Int -> [QDiagram b V2 n Any]
-> QDiagram b V2 n Any
gridAnimal rowFunction cols = vcat . map hcat . rowFunction
. chunksOf cols . sameBoundingRect . padList cols mempty
| ` gridWith f ( cols , rows ) ` uses ` f ` , a function of two
zero - indexed integer coordinates , to generate a grid of diagrams
gridWith
:: TypeableFloat n
=> (Int -> Int -> QDiagram b V2 n Any) -> (Int, Int)
-> QDiagram b V2 n Any
gridWith f (cols, rows) = gridCat' cols diagrams
where
diagrams = [ f x y | y <- [0..rows - 1] , x <- [0..cols - 1] ]
sameBoundingSquare
:: forall b n. TypeableFloat n
=> [QDiagram b V2 n Any]
-> [QDiagram b V2 n Any]
sameBoundingSquare diagrams = map frameOne diagrams
where
biggest = maximumBy (comparing maxDim) diagrams
maxDim diagram = max (width diagram) (height diagram)
centerP = centerPoint biggest
padSquare = (square (maxDim biggest) :: D V2 n) # phantom
frameOne = atop padSquare . moveOriginTo centerP
sameBoundingRect
:: forall n b. TypeableFloat n
=> [QDiagram b V2 n Any]
-> [QDiagram b V2 n Any]
sameBoundingRect diagrams = map frameOne diagrams
where
widest = maximumBy (comparing width) diagrams
tallest = maximumBy (comparing height) diagrams
(xCenter :& _) = coords (centerPoint widest)
(_ :& yCenter) = coords (centerPoint tallest)
padRect = (rect (width widest) (height tallest) :: D V2 n) # phantom
frameOne = atop padRect . moveOriginTo (xCenter ^& yCenter)
intSqrt :: Int -> Int
intSqrt = round . sqrt . (fromIntegral :: Int -> Float)
everyOther :: (a -> a) -> [a] -> [a]
everyOther f = zipWith ($) (cycle [id, f])
padList :: Int -> a -> [a] -> [a]
padList m padding xs = xs ++ replicate (mod (- length xs) m) padding
|
9a2e5bcb7050c95a219ea0fc20456ebf410aff9ec922f3f1d5470ce71306903d | dangtv/BIRDS | fol.mli |
type term =
| Var of string
| Fn of string * term list
type fol =
| R of string * term list
val fv : fol Formulas.formula -> string list
val variant : string -> string list -> string
val subst : (string, term) Lib.func -> fol Formulas.formula -> fol Formulas.formula
val generalize : fol Formulas.formula -> fol Formulas.formula
| null | https://raw.githubusercontent.com/dangtv/BIRDS/fdf9263df9bbb7ba836674e9f1ff1a0ec78634e7/src/logic/fol.mli | ocaml |
type term =
| Var of string
| Fn of string * term list
type fol =
| R of string * term list
val fv : fol Formulas.formula -> string list
val variant : string -> string list -> string
val subst : (string, term) Lib.func -> fol Formulas.formula -> fol Formulas.formula
val generalize : fol Formulas.formula -> fol Formulas.formula
|
|
a332011444a047861d1b7bcf4cdce368d7fb708e6fdabedaaa17ece112b187b2 | ypyf/fscm | r5rs_test.scm | (define (is a b) (display (equal? a b)) (newline))
应该等价于(list 1),所以输出的是 = = > ( 1 )
在某些错误的实现中(比如tinyscheme 1.41),等价于(quote if),所以输出的是 = = > if
(is ((lambda (quote if) (quote if)) list 1) '(1))
; procedure application
(is 1 (call/cc (lambda (c) (0 (c 1)))))
shadowing syntatic keywords , bug in MIT Scheme ?
(is '(x)
((lambda lambda lambda) 'x))
(is '(1 2 3)
((lambda (begin) (begin 1 2 3)) (lambda lambda lambda)))
(is '(1)
((lambda (quote if) (quote if)) list 1))
;; '1 => (- 1)
( is # f
; (let ((quote -)) (eqv? '1 1)))
;;
(define a 100)
(define func +)
(define (foo func) (lambda (a b) (set! a 100) (func a b)))
(is ((foo *) 1 2) 200)
;;
(define bar
(lambda (x)
(+ x ((lambda () (set! x 11) x)) x)))
(is (bar 1) 23)
(is ((lambda (a b) (define a 1) a) 99 98) 1)
;;
(define f
(lambda (x)
(g x)))
(define g
(lambda (x)
(+ x x)))
(is (f 3) 6)
;; test defineVar bug
(define count 0)
(define jj (lambda () (if (< count 1000) (begin (set! count (+ count 1)) (jj)) count)))
(jj)
(define count 0)
(jj)
(is count 1000) | null | https://raw.githubusercontent.com/ypyf/fscm/4e6a31665051d51bbcfc823ac8d85dcc3491a6ef/test/r5rs_test.scm | scheme | procedure application
'1 => (- 1)
(let ((quote -)) (eqv? '1 1)))
test defineVar bug
| (define (is a b) (display (equal? a b)) (newline))
应该等价于(list 1),所以输出的是 = = > ( 1 )
在某些错误的实现中(比如tinyscheme 1.41),等价于(quote if),所以输出的是 = = > if
(is ((lambda (quote if) (quote if)) list 1) '(1))
(is 1 (call/cc (lambda (c) (0 (c 1)))))
shadowing syntatic keywords , bug in MIT Scheme ?
(is '(x)
((lambda lambda lambda) 'x))
(is '(1 2 3)
((lambda (begin) (begin 1 2 3)) (lambda lambda lambda)))
(is '(1)
((lambda (quote if) (quote if)) list 1))
( is # f
(define a 100)
(define func +)
(define (foo func) (lambda (a b) (set! a 100) (func a b)))
(is ((foo *) 1 2) 200)
(define bar
(lambda (x)
(+ x ((lambda () (set! x 11) x)) x)))
(is (bar 1) 23)
(is ((lambda (a b) (define a 1) a) 99 98) 1)
(define f
(lambda (x)
(g x)))
(define g
(lambda (x)
(+ x x)))
(is (f 3) 6)
(define count 0)
(define jj (lambda () (if (< count 1000) (begin (set! count (+ count 1)) (jj)) count)))
(jj)
(define count 0)
(jj)
(is count 1000) |
f74f97365456eec98358dc771d7fe3698dbf6e64ef202531e30186edf2d49f31 | nitrogen/simple_bridge | webmachine_simple_bridge_static.erl | @author < >
@author < >
@author < >
2008 - 2009 Basho Technologies , Inc.
-module(webmachine_simple_bridge_static).
-include("compat.hrl").
-export([init/1]).
-export([ping/2,
allowed_methods/2,
resource_exists/2,
last_modified/2,
content_types_provided/2,
content_types_accepted/2,
delete_resource/2,
post_is_create/2,
create_path/2,
provide_content/2,
accept_content/2,
generate_etag/2]).
-record(context, {root,response_body=undefined,metadata=[]}).
ping(Req, State) ->
{pong, Req, State}.
init(ConfigProps) ->
{root, Root} = proplists:lookup(root, ConfigProps),
{ok, #context{root=Root}}.
allowed_methods(ReqData, Context) ->
{['HEAD', 'GET', 'PUT', 'DELETE', 'POST'], ReqData, Context}.
file_path(Context, "") ->
Context#context.root;
file_path(Context, "/" ++ Name) ->
file_path(Context, Name);
file_path(Context,Name) ->
filename:join([Context#context.root, Name]).
file_exists(Context, Name) ->
NamePath = file_path(Context, Name),
case filelib:is_regular(NamePath) of
true ->
{true, NamePath};
false ->
false
end.
resource_exists(ReqData, Context) ->
Path = wrq:disp_path(ReqData),
case file_exists(Context, Path) of
{true, _} ->
{true, ReqData, Context};
_ ->
case Path of
"p" -> {true, ReqData, Context};
_ -> {false, ReqData, Context}
end
end.
maybe_fetch_object(Context, Path) ->
if returns { true , NewContext } then NewContext has response_body
case Context#context.response_body of
undefined ->
case file_exists(Context, Path) of
{true, FullPath} ->
{ok, Value} = file:read_file(FullPath),
{true, Context#context{response_body=Value}};
false ->
{false, Context}
end;
_Body ->
{true, Context}
end.
content_types_provided(ReqData, Context) ->
CT = webmachine_util:guess_mime(wrq:disp_path(ReqData)),
{[{CT, provide_content}], ReqData,
Context#context{metadata=[{'content-type', CT}|Context#context.metadata]}}.
content_types_accepted(ReqData, Context) ->
CT = case wrq:get_req_header("content-type", ReqData) of
undefined -> "application/octet-stream";
X -> X
end,
{MT, _Params} = webmachine_util:media_type_to_detail(CT),
{[{MT, accept_content}], ReqData,
Context#context{metadata=[{'content-type', MT}|Context#context.metadata]}}.
accept_content(ReqData, Context) ->
Path = wrq:disp_path(ReqData),
FP = file_path(Context, Path),
ok = filelib:ensure_dir(filename:dirname(FP)),
ReqData1 = case file_exists(Context, Path) of
{true, _} ->
ReqData;
_ ->
LOC = "http://" ++
wrq:get_req_header("host", ReqData) ++
"/fs/" ++ Path,
wrq:set_resp_header("Location", LOC, ReqData)
end,
Value = wrq:req_body(ReqData1),
case file:write_file(FP, Value) of
ok ->
{true, wrq:set_resp_body(Value, ReqData1), Context};
Err ->
{{error, Err}, ReqData1, Context}
end.
post_is_create(ReqData, Context) ->
{true, ReqData, Context}.
create_path(ReqData, Context) ->
case wrq:get_req_header("slug", ReqData) of
undefined -> {undefined, ReqData, Context};
Slug ->
case file_exists(Context, Slug) of
{true, _} -> {undefined, ReqData, Context};
_ -> {Slug, ReqData, Context}
end
end.
delete_resource(ReqData, Context) ->
case file:delete(file_path(
Context, wrq:disp_path(ReqData))) of
ok -> {true, ReqData, Context};
_ -> {false, ReqData, Context}
end.
provide_content(ReqData, Context) ->
case maybe_fetch_object(Context, wrq:disp_path(ReqData)) of
{true, NewContext} ->
Body = NewContext#context.response_body,
{Body, ReqData, Context};
{false, NewContext} ->
{error, ReqData, NewContext}
end.
last_modified(ReqData, Context) ->
{true, FullPath} = file_exists(Context,
wrq:disp_path(ReqData)),
LMod = filelib:last_modified(FullPath),
{LMod, ReqData, Context#context{metadata=[{'last-modified',
httpd_util:rfc1123_date(LMod)}|Context#context.metadata]}}.
hash_body(Body) -> mochihex:to_hex(binary_to_list(?HASH(Body))).
generate_etag(ReqData, Context) ->
case maybe_fetch_object(Context, wrq:disp_path(ReqData)) of
{true, BodyContext} ->
ETag = hash_body(BodyContext#context.response_body),
{ETag, ReqData,
BodyContext#context{metadata=[{etag,ETag}|
BodyContext#context.metadata]}};
_ ->
{undefined, ReqData, Context}
end.
| null | https://raw.githubusercontent.com/nitrogen/simple_bridge/b94dba61e3b6057cd04e461749b3a5c19944a74c/src/webmachine_bridge_modules/webmachine_simple_bridge_static.erl | erlang | @author < >
@author < >
@author < >
2008 - 2009 Basho Technologies , Inc.
-module(webmachine_simple_bridge_static).
-include("compat.hrl").
-export([init/1]).
-export([ping/2,
allowed_methods/2,
resource_exists/2,
last_modified/2,
content_types_provided/2,
content_types_accepted/2,
delete_resource/2,
post_is_create/2,
create_path/2,
provide_content/2,
accept_content/2,
generate_etag/2]).
-record(context, {root,response_body=undefined,metadata=[]}).
ping(Req, State) ->
{pong, Req, State}.
init(ConfigProps) ->
{root, Root} = proplists:lookup(root, ConfigProps),
{ok, #context{root=Root}}.
allowed_methods(ReqData, Context) ->
{['HEAD', 'GET', 'PUT', 'DELETE', 'POST'], ReqData, Context}.
file_path(Context, "") ->
Context#context.root;
file_path(Context, "/" ++ Name) ->
file_path(Context, Name);
file_path(Context,Name) ->
filename:join([Context#context.root, Name]).
file_exists(Context, Name) ->
NamePath = file_path(Context, Name),
case filelib:is_regular(NamePath) of
true ->
{true, NamePath};
false ->
false
end.
resource_exists(ReqData, Context) ->
Path = wrq:disp_path(ReqData),
case file_exists(Context, Path) of
{true, _} ->
{true, ReqData, Context};
_ ->
case Path of
"p" -> {true, ReqData, Context};
_ -> {false, ReqData, Context}
end
end.
maybe_fetch_object(Context, Path) ->
if returns { true , NewContext } then NewContext has response_body
case Context#context.response_body of
undefined ->
case file_exists(Context, Path) of
{true, FullPath} ->
{ok, Value} = file:read_file(FullPath),
{true, Context#context{response_body=Value}};
false ->
{false, Context}
end;
_Body ->
{true, Context}
end.
content_types_provided(ReqData, Context) ->
CT = webmachine_util:guess_mime(wrq:disp_path(ReqData)),
{[{CT, provide_content}], ReqData,
Context#context{metadata=[{'content-type', CT}|Context#context.metadata]}}.
content_types_accepted(ReqData, Context) ->
CT = case wrq:get_req_header("content-type", ReqData) of
undefined -> "application/octet-stream";
X -> X
end,
{MT, _Params} = webmachine_util:media_type_to_detail(CT),
{[{MT, accept_content}], ReqData,
Context#context{metadata=[{'content-type', MT}|Context#context.metadata]}}.
accept_content(ReqData, Context) ->
Path = wrq:disp_path(ReqData),
FP = file_path(Context, Path),
ok = filelib:ensure_dir(filename:dirname(FP)),
ReqData1 = case file_exists(Context, Path) of
{true, _} ->
ReqData;
_ ->
LOC = "http://" ++
wrq:get_req_header("host", ReqData) ++
"/fs/" ++ Path,
wrq:set_resp_header("Location", LOC, ReqData)
end,
Value = wrq:req_body(ReqData1),
case file:write_file(FP, Value) of
ok ->
{true, wrq:set_resp_body(Value, ReqData1), Context};
Err ->
{{error, Err}, ReqData1, Context}
end.
post_is_create(ReqData, Context) ->
{true, ReqData, Context}.
create_path(ReqData, Context) ->
case wrq:get_req_header("slug", ReqData) of
undefined -> {undefined, ReqData, Context};
Slug ->
case file_exists(Context, Slug) of
{true, _} -> {undefined, ReqData, Context};
_ -> {Slug, ReqData, Context}
end
end.
delete_resource(ReqData, Context) ->
case file:delete(file_path(
Context, wrq:disp_path(ReqData))) of
ok -> {true, ReqData, Context};
_ -> {false, ReqData, Context}
end.
provide_content(ReqData, Context) ->
case maybe_fetch_object(Context, wrq:disp_path(ReqData)) of
{true, NewContext} ->
Body = NewContext#context.response_body,
{Body, ReqData, Context};
{false, NewContext} ->
{error, ReqData, NewContext}
end.
last_modified(ReqData, Context) ->
{true, FullPath} = file_exists(Context,
wrq:disp_path(ReqData)),
LMod = filelib:last_modified(FullPath),
{LMod, ReqData, Context#context{metadata=[{'last-modified',
httpd_util:rfc1123_date(LMod)}|Context#context.metadata]}}.
hash_body(Body) -> mochihex:to_hex(binary_to_list(?HASH(Body))).
generate_etag(ReqData, Context) ->
case maybe_fetch_object(Context, wrq:disp_path(ReqData)) of
{true, BodyContext} ->
ETag = hash_body(BodyContext#context.response_body),
{ETag, ReqData,
BodyContext#context{metadata=[{etag,ETag}|
BodyContext#context.metadata]}};
_ ->
{undefined, ReqData, Context}
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.