_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 |
|---|---|---|---|---|---|---|---|---|
f113c4c68977f93318eb4f59dc91e07f25f7dddee70337162887b1fd3b9dcf9c | mtolly/onyxite-customs | ShiftJIS.hs | # LANGUAGE CPP #
module Onyx.Util.ShiftJIS (decodeShiftJIS, kakasi) where
import qualified Data.ByteString as B
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromMaybe)
import Data.Tuple (swap)
import Onyx.Kakasi
import Onyx.Resources (itaijidict, kanwadict, shiftJISTable)
#ifdef WINDOWS
import Control.Monad (when)
import Foreign.C (CInt (..), CString, withCString)
#else
import System.Environment (setEnv)
#endif
kakasi :: [String] -> String -> IO String
kakasi args str = do
kanwadict >>= setEnvKakasi "KANWADICT"
itaijidict >>= setEnvKakasi "ITAIJIDICT"
n <- kakasiArgs $ "onyx-kakasi" : "-i" : "sjis" : args
case n of
0 -> decodeShiftJIS <$> kakasiDo (encodeShiftJIS str)
_ -> error $ "DTXMania.ShiftJIS.kakasi: got non-zero error code " <> show n
hack to fix crash on windows .
haskell setEnv on windows tries to be good and call SetEnvironmentVariableW.
but then on the C side , kakasi calls , and it does not see the variable change
( the variable remains whatever it was on process launch ) .
according to -us/cpp/c-runtime-library/reference/getenv-wgetenv
these two tables ( char * and wchar_t * ) do n't necessarily stay in sync ...
so instead , we use putenv , which seems to update both methods .
hack to fix crash on windows.
haskell setEnv on windows tries to be good and call SetEnvironmentVariableW.
but then on the C side, kakasi calls getenv, and it does not see the variable change
(the variable remains whatever it was on process launch).
according to -us/cpp/c-runtime-library/reference/getenv-wgetenv
these two tables (char* and wchar_t*) don't necessarily stay in sync...
so instead, we use putenv, which seems to update both methods.
-}
setEnvKakasi :: String -> String -> IO ()
#ifdef WINDOWS
setEnvKakasi k v = withCString (k <> "=" <> v) $ \cstr -> do
res <- c_putenv cstr
when (res /= 0) $ fail $ "setEnvKakasi: couldn't set variable, code " <> show res
foreign import ccall unsafe "putenv"
c_putenv :: CString -> IO CInt
#else
setEnvKakasi = setEnv
#endif
encodeShiftJIS :: String -> B.ByteString
encodeShiftJIS = B.concat . map
(\c -> fromMaybe (B.pack [0x81, 0xA1]) -- black square (■)
$ HM.lookup c shiftJISReverse
)
decodeShiftJIS :: B.ByteString -> String
decodeShiftJIS b = if B.null b
then ""
else case B.splitAt 1 b of
(h1, t1) -> case HM.lookup h1 shiftJISTable of
Just c -> c : decodeShiftJIS t1
Nothing -> if B.length b >= 2
then case B.splitAt 2 b of
(h2, t2) -> case HM.lookup h2 shiftJISTable of
Just c -> c : decodeShiftJIS t2
Nothing -> '�' : decodeShiftJIS t1
else "�"
shiftJISReverse :: HM.HashMap Char B.ByteString
shiftJISReverse = HM.fromList $ map swap $ HM.toList shiftJISTable
| null | https://raw.githubusercontent.com/mtolly/onyxite-customs/0c8acd6248fe92ea0d994b18b551973816adf85b/haskell/packages/onyx-lib/src/Onyx/Util/ShiftJIS.hs | haskell | black square (■) | # LANGUAGE CPP #
module Onyx.Util.ShiftJIS (decodeShiftJIS, kakasi) where
import qualified Data.ByteString as B
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromMaybe)
import Data.Tuple (swap)
import Onyx.Kakasi
import Onyx.Resources (itaijidict, kanwadict, shiftJISTable)
#ifdef WINDOWS
import Control.Monad (when)
import Foreign.C (CInt (..), CString, withCString)
#else
import System.Environment (setEnv)
#endif
kakasi :: [String] -> String -> IO String
kakasi args str = do
kanwadict >>= setEnvKakasi "KANWADICT"
itaijidict >>= setEnvKakasi "ITAIJIDICT"
n <- kakasiArgs $ "onyx-kakasi" : "-i" : "sjis" : args
case n of
0 -> decodeShiftJIS <$> kakasiDo (encodeShiftJIS str)
_ -> error $ "DTXMania.ShiftJIS.kakasi: got non-zero error code " <> show n
hack to fix crash on windows .
haskell setEnv on windows tries to be good and call SetEnvironmentVariableW.
but then on the C side , kakasi calls , and it does not see the variable change
( the variable remains whatever it was on process launch ) .
according to -us/cpp/c-runtime-library/reference/getenv-wgetenv
these two tables ( char * and wchar_t * ) do n't necessarily stay in sync ...
so instead , we use putenv , which seems to update both methods .
hack to fix crash on windows.
haskell setEnv on windows tries to be good and call SetEnvironmentVariableW.
but then on the C side, kakasi calls getenv, and it does not see the variable change
(the variable remains whatever it was on process launch).
according to -us/cpp/c-runtime-library/reference/getenv-wgetenv
these two tables (char* and wchar_t*) don't necessarily stay in sync...
so instead, we use putenv, which seems to update both methods.
-}
setEnvKakasi :: String -> String -> IO ()
#ifdef WINDOWS
setEnvKakasi k v = withCString (k <> "=" <> v) $ \cstr -> do
res <- c_putenv cstr
when (res /= 0) $ fail $ "setEnvKakasi: couldn't set variable, code " <> show res
foreign import ccall unsafe "putenv"
c_putenv :: CString -> IO CInt
#else
setEnvKakasi = setEnv
#endif
encodeShiftJIS :: String -> B.ByteString
encodeShiftJIS = B.concat . map
$ HM.lookup c shiftJISReverse
)
decodeShiftJIS :: B.ByteString -> String
decodeShiftJIS b = if B.null b
then ""
else case B.splitAt 1 b of
(h1, t1) -> case HM.lookup h1 shiftJISTable of
Just c -> c : decodeShiftJIS t1
Nothing -> if B.length b >= 2
then case B.splitAt 2 b of
(h2, t2) -> case HM.lookup h2 shiftJISTable of
Just c -> c : decodeShiftJIS t2
Nothing -> '�' : decodeShiftJIS t1
else "�"
shiftJISReverse :: HM.HashMap Char B.ByteString
shiftJISReverse = HM.fromList $ map swap $ HM.toList shiftJISTable
|
181b75ab4397ca5676f63bcdf754620de0259ea215a9299b1cbd8c07df83998f | shmookey/solpb | Types.hs | {-# LANGUAGE OverloadedStrings #-}
module Types where
import Data.Map (Map)
import Data.Text (Text)
import Data.Semigroup ((<>))
import qualified Data.Map as Map
import qualified Data.Text as T
import Control.Monad.Resultant
type App = ResultantT IO Options String
type Name = Text
type Code = Text
data Field = Field
{ fieldID :: Int -- the protobuf field number, may skip values
, fieldIndex :: Int -- consecutive index of the fields
, fieldName :: Name
, fieldType :: ValueType
, fieldLabel :: Label
} deriving (Show)
data Label
= Optional
| Required
| Repeated
deriving (Show)
data Struct = Struct
{ structName :: Name
, structFields :: [Field]
}
data ValueType
= VarintType VarintType
| Fixed64Type Fixed64Type
| LenDelim LenDelimType
| Fixed32Type Fixed32Type
| StartGroup
| EndGroup
deriving (Eq, Show)
data VarintType
= Int32 | Int64 | UInt32 | UInt64
| SInt32 | SInt64 | Bool | Enum
deriving (Eq, Show)
data Fixed64Type
= Fixed64 | SFixed64 | Double
deriving (Eq, Show)
data LenDelimType
= String | Bytes | Message Message | Packed
deriving (Eq, Show)
data Fixed32Type
= Fixed32 | SFixed32 | Float
deriving (Eq, Show)
data Message
= User Name Name -- Basic type name, library name
Native type name
deriving (Eq, Show)
data TypeContext
= Scalar | Normal | Quote
deriving (Eq, Show)
formatValueType :: TypeContext -> ValueType -> Name
formatValueType ctx typ =
let
formatMessageType :: Message -> Name
formatMessageType msg = case (msg, ctx) of
(User name _, Quote) -> name
(User name lib, _) -> lib <> "." <> name
(Sol name, _) -> name
in case typ of
VarintType x -> case x of
Int32 -> "int32"
Int64 -> "int64"
UInt32 -> "uint32"
UInt64 -> "uint64"
SInt32 -> "int32"
SInt64 -> "int64"
Bool -> "bool"
Enum -> error "internal error: enums not yet supported"
Fixed64Type x -> case x of
Fixed64 -> "uint64"
SFixed64 -> "int64"
Double -> error "internal error: floating point numbers not supported"
LenDelim x -> case x of
String -> "string"
Bytes -> "bytes"
Message m -> formatMessageType m
Packed -> error "internal error: packed encodings not yet supported"
Fixed32Type x -> case x of
Fixed32 -> "uint32"
SFixed32 -> "int32"
Float -> error "internal error: floating point numbers not supported"
StartGroup -> error "internal error: groups not supported"
EndGroup -> error "internal error: groups not supported"
formatFieldType :: TypeContext -> Field -> Name
formatFieldType ctx fld =
let
base = formatValueType ctx $ fieldType fld
in
case (ctx, isRepeated fld) of
(Normal, True) -> base <> "[]"
_ -> base
formatEncoding :: ValueType -> Name
formatEncoding typ = case typ of
VarintType x -> case x of
Int32 -> "int32"
Int64 -> "int64"
UInt32 -> "uint32"
UInt64 -> "uint64"
SInt32 -> "sint32"
SInt64 -> "sint64"
Bool -> "bool"
Enum -> error "internal error: enums not yet supported"
Fixed64Type x -> case x of
Fixed64 -> "fixed64"
SFixed64 -> "sfixed64"
Double -> error "internal error: floating point numbers not supported"
LenDelim x -> case x of
Message (Sol x) -> "sol_" <> x
Message (User x _) -> x
String -> "string"
Bytes -> "bytes"
Packed -> error "internal error: packed encodings not yet supported"
Fixed32Type x -> case x of
Fixed32 -> "fixed32"
SFixed32 -> "sfixed32"
Float -> error "internal error: floating point numbers not supported"
StartGroup -> error "internal error: groups not supported"
EndGroup -> error "internal error: groups not supported"
formatWireType :: ValueType -> Name
formatWireType typ = case typ of
VarintType _ -> "_pb.WireType.Varint"
Fixed64Type _ -> "_pb.WireType.Fixed64"
LenDelim _ -> "_pb.WireType.LengthDelim"
Fixed32Type _ -> "_pb.WireType.Fixed32"
StartGroup -> error "internal error: groups not supported"
EndGroup -> error "internal error: groups not supported"
formatLibrary :: ValueType -> Name
formatLibrary typ = case typ of
LenDelim (Message (User _ x)) -> x
_ -> ""
isRepeated :: Field -> Bool
isRepeated fld = case fieldLabel fld of
Repeated -> True
_ -> False
isStruct :: Field -> Bool
isStruct fld = case fieldType fld of
LenDelim (Message (User _ _)) -> True
_ -> False
-- Config state
-- ---------------------------------------------------------------------
data Options = Options
{ optDir :: FilePath
, optLibName :: String
, optIncludeDirs :: [FilePath]
, optSeparate :: Bool
, optSuffix :: String
, optNoPragma :: Bool
, optNoRuntime :: Bool
, optNoCombine :: Bool
, optRuntimeOut :: Maybe FilePath
, optInputs :: [FilePath]
} deriving (Show)
initState :: Options
initState = Options
{ optDir = "."
, optLibName = "pb"
, optIncludeDirs = ["."]
, optSeparate = False
, optSuffix = "_pb"
, optNoPragma = False
, optNoRuntime = False
, optNoCombine = False
, optRuntimeOut = Nothing
, optInputs = []
}
getConfig :: App Options
getConfig = getState
setConfig :: Options -> App ()
setConfig = setState
| null | https://raw.githubusercontent.com/shmookey/solpb/4263050f9436e0a1d541ac99ab52970e9c2132c6/src/Types.hs | haskell | # LANGUAGE OverloadedStrings #
the protobuf field number, may skip values
consecutive index of the fields
Basic type name, library name
Config state
--------------------------------------------------------------------- |
module Types where
import Data.Map (Map)
import Data.Text (Text)
import Data.Semigroup ((<>))
import qualified Data.Map as Map
import qualified Data.Text as T
import Control.Monad.Resultant
type App = ResultantT IO Options String
type Name = Text
type Code = Text
data Field = Field
, fieldName :: Name
, fieldType :: ValueType
, fieldLabel :: Label
} deriving (Show)
data Label
= Optional
| Required
| Repeated
deriving (Show)
data Struct = Struct
{ structName :: Name
, structFields :: [Field]
}
data ValueType
= VarintType VarintType
| Fixed64Type Fixed64Type
| LenDelim LenDelimType
| Fixed32Type Fixed32Type
| StartGroup
| EndGroup
deriving (Eq, Show)
data VarintType
= Int32 | Int64 | UInt32 | UInt64
| SInt32 | SInt64 | Bool | Enum
deriving (Eq, Show)
data Fixed64Type
= Fixed64 | SFixed64 | Double
deriving (Eq, Show)
data LenDelimType
= String | Bytes | Message Message | Packed
deriving (Eq, Show)
data Fixed32Type
= Fixed32 | SFixed32 | Float
deriving (Eq, Show)
data Message
Native type name
deriving (Eq, Show)
data TypeContext
= Scalar | Normal | Quote
deriving (Eq, Show)
formatValueType :: TypeContext -> ValueType -> Name
formatValueType ctx typ =
let
formatMessageType :: Message -> Name
formatMessageType msg = case (msg, ctx) of
(User name _, Quote) -> name
(User name lib, _) -> lib <> "." <> name
(Sol name, _) -> name
in case typ of
VarintType x -> case x of
Int32 -> "int32"
Int64 -> "int64"
UInt32 -> "uint32"
UInt64 -> "uint64"
SInt32 -> "int32"
SInt64 -> "int64"
Bool -> "bool"
Enum -> error "internal error: enums not yet supported"
Fixed64Type x -> case x of
Fixed64 -> "uint64"
SFixed64 -> "int64"
Double -> error "internal error: floating point numbers not supported"
LenDelim x -> case x of
String -> "string"
Bytes -> "bytes"
Message m -> formatMessageType m
Packed -> error "internal error: packed encodings not yet supported"
Fixed32Type x -> case x of
Fixed32 -> "uint32"
SFixed32 -> "int32"
Float -> error "internal error: floating point numbers not supported"
StartGroup -> error "internal error: groups not supported"
EndGroup -> error "internal error: groups not supported"
formatFieldType :: TypeContext -> Field -> Name
formatFieldType ctx fld =
let
base = formatValueType ctx $ fieldType fld
in
case (ctx, isRepeated fld) of
(Normal, True) -> base <> "[]"
_ -> base
formatEncoding :: ValueType -> Name
formatEncoding typ = case typ of
VarintType x -> case x of
Int32 -> "int32"
Int64 -> "int64"
UInt32 -> "uint32"
UInt64 -> "uint64"
SInt32 -> "sint32"
SInt64 -> "sint64"
Bool -> "bool"
Enum -> error "internal error: enums not yet supported"
Fixed64Type x -> case x of
Fixed64 -> "fixed64"
SFixed64 -> "sfixed64"
Double -> error "internal error: floating point numbers not supported"
LenDelim x -> case x of
Message (Sol x) -> "sol_" <> x
Message (User x _) -> x
String -> "string"
Bytes -> "bytes"
Packed -> error "internal error: packed encodings not yet supported"
Fixed32Type x -> case x of
Fixed32 -> "fixed32"
SFixed32 -> "sfixed32"
Float -> error "internal error: floating point numbers not supported"
StartGroup -> error "internal error: groups not supported"
EndGroup -> error "internal error: groups not supported"
formatWireType :: ValueType -> Name
formatWireType typ = case typ of
VarintType _ -> "_pb.WireType.Varint"
Fixed64Type _ -> "_pb.WireType.Fixed64"
LenDelim _ -> "_pb.WireType.LengthDelim"
Fixed32Type _ -> "_pb.WireType.Fixed32"
StartGroup -> error "internal error: groups not supported"
EndGroup -> error "internal error: groups not supported"
formatLibrary :: ValueType -> Name
formatLibrary typ = case typ of
LenDelim (Message (User _ x)) -> x
_ -> ""
isRepeated :: Field -> Bool
isRepeated fld = case fieldLabel fld of
Repeated -> True
_ -> False
isStruct :: Field -> Bool
isStruct fld = case fieldType fld of
LenDelim (Message (User _ _)) -> True
_ -> False
data Options = Options
{ optDir :: FilePath
, optLibName :: String
, optIncludeDirs :: [FilePath]
, optSeparate :: Bool
, optSuffix :: String
, optNoPragma :: Bool
, optNoRuntime :: Bool
, optNoCombine :: Bool
, optRuntimeOut :: Maybe FilePath
, optInputs :: [FilePath]
} deriving (Show)
initState :: Options
initState = Options
{ optDir = "."
, optLibName = "pb"
, optIncludeDirs = ["."]
, optSeparate = False
, optSuffix = "_pb"
, optNoPragma = False
, optNoRuntime = False
, optNoCombine = False
, optRuntimeOut = Nothing
, optInputs = []
}
getConfig :: App Options
getConfig = getState
setConfig :: Options -> App ()
setConfig = setState
|
c90229e184f0bef691846190a0f5a62a5aa814b9f6519efeb053beb23fa217b7 | err0r500/realworld-app-simple-haskell | Lib.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE RankNTypes #-}
module Adapter.Http.Lib where
import Data.Aeson
import Data.List (stripPrefix)
import qualified Domain.User as D
import qualified Network.Wai as Wai
import RIO
import qualified Usecase.Interactor as UC
import qualified Usecase.LogicHandler as UC
the shared Router type
type Router m =
(MonadUnliftIO m, UC.Logger m) =>
UC.LogicHandler m ->
(forall a. m a -> IO a) ->
IO Wai.Application
-- User (wrapper)
newtype User a = User a
deriving (Eq, Show, Generic)
instance ToJSON a => ToJSON (User a) where
toJSON (User a) = object ["user" .= a]
instance FromJSON a => FromJSON (User a) where
parseJSON (Object o) = User <$> o .: "user"
parseJSON _ = fail "user must be an object"
UserDetails
data UserDetails = UserDetails
{ user_username :: D.Name,
user_email :: D.Email
}
deriving (Eq, Show, Generic)
instance FromJSON UserDetails where
parseJSON = genericParseJSON $ stripping "user_"
instance ToJSON UserDetails where
toJSON = genericToJSON $ stripping "user_"
fromDomain :: D.User -> UserDetails
fromDomain user = UserDetails (D._name user) (D._email user)
RegisterDetails
data RegisterDetails = RegisterDetails
{ register_email :: D.Email,
register_username :: D.Name,
register_password :: D.Password
}
deriving (Eq, Show, Generic)
instance FromJSON RegisterDetails where
parseJSON = genericParseJSON $ stripping "register_"
instance ToJSON RegisterDetails where
toJSON = genericToJSON $ stripping "register_"
LoginDetails
data LoginDetails = LoginDetails
{ login_email :: D.Email,
login_password :: D.Password
}
deriving (Eq, Show, Generic)
instance FromJSON LoginDetails where
parseJSON = genericParseJSON $ stripping "login_"
instance ToJSON LoginDetails where
toJSON = genericToJSON $ stripping "register_"
-- helper
-- removes the given prefix from field names
stripping :: String -> Options
stripping str = defaultOptions {fieldLabelModifier = strip str}
where
strip pref s = fromMaybe "" (stripPrefix pref s)
| null | https://raw.githubusercontent.com/err0r500/realworld-app-simple-haskell/e499fd2eb03f6bcde5ac99a136d1907700cf026d/src/Adapter/Http/Lib.hs | haskell | # LANGUAGE RankNTypes #
User (wrapper)
helper
removes the given prefix from field names | # LANGUAGE DeriveGeneric #
module Adapter.Http.Lib where
import Data.Aeson
import Data.List (stripPrefix)
import qualified Domain.User as D
import qualified Network.Wai as Wai
import RIO
import qualified Usecase.Interactor as UC
import qualified Usecase.LogicHandler as UC
the shared Router type
type Router m =
(MonadUnliftIO m, UC.Logger m) =>
UC.LogicHandler m ->
(forall a. m a -> IO a) ->
IO Wai.Application
newtype User a = User a
deriving (Eq, Show, Generic)
instance ToJSON a => ToJSON (User a) where
toJSON (User a) = object ["user" .= a]
instance FromJSON a => FromJSON (User a) where
parseJSON (Object o) = User <$> o .: "user"
parseJSON _ = fail "user must be an object"
UserDetails
data UserDetails = UserDetails
{ user_username :: D.Name,
user_email :: D.Email
}
deriving (Eq, Show, Generic)
instance FromJSON UserDetails where
parseJSON = genericParseJSON $ stripping "user_"
instance ToJSON UserDetails where
toJSON = genericToJSON $ stripping "user_"
fromDomain :: D.User -> UserDetails
fromDomain user = UserDetails (D._name user) (D._email user)
RegisterDetails
data RegisterDetails = RegisterDetails
{ register_email :: D.Email,
register_username :: D.Name,
register_password :: D.Password
}
deriving (Eq, Show, Generic)
instance FromJSON RegisterDetails where
parseJSON = genericParseJSON $ stripping "register_"
instance ToJSON RegisterDetails where
toJSON = genericToJSON $ stripping "register_"
LoginDetails
data LoginDetails = LoginDetails
{ login_email :: D.Email,
login_password :: D.Password
}
deriving (Eq, Show, Generic)
instance FromJSON LoginDetails where
parseJSON = genericParseJSON $ stripping "login_"
instance ToJSON LoginDetails where
toJSON = genericToJSON $ stripping "register_"
stripping :: String -> Options
stripping str = defaultOptions {fieldLabelModifier = strip str}
where
strip pref s = fromMaybe "" (stripPrefix pref s)
|
c52981346ded5d38ea80ed50ea0f73624b4ac3ac5c1b88e7ea62fed556abb218 | 2600hz-archive/whistle | ecallmgr_diagnostics.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2010 , VoIP , INC
%%% @doc
%%% Given a diagnostics record, create a diagnostics proplist to return
%%% @end
Created : 25 Oct 2010 by < >
%%%-------------------------------------------------------------------
-module(ecallmgr_diagnostics).
-export([get_diagnostics/1]).
-include("ecallmgr.hrl").
-spec get_diagnostics/1 :: (Stats) -> [{'active_channels' |
'created_channels' |
'destroyed_channels' |
'last_heartbeat' |
'lookups_failed' |
'lookups_requested' |
'lookups_success' |
'lookups_timeout' |
'uptime'
,integer()},...] when
Stats :: #handler_stats{} | #node_stats{}.
get_diagnostics(#handler_stats{lookups_success=LS, lookups_failed=LF, lookups_timeout=LT, lookups_requested=LR, started=Started}) ->
[{lookups_success, LS}
,{lookups_failed, LF}
,{lookups_timeout, LT}
,{lookups_requested, LR}
,{uptime, timer:now_diff(erlang:now(), Started)}
];
get_diagnostics(#node_stats{last_heartbeat=LH, created_channels=CC, destroyed_channels=DC, started=Started}) ->
[{last_heartbeat, timer:now_diff(erlang:now(), LH)}
,{active_channels, CC - DC}
,{created_channels, CC}
,{destroyed_channels, DC}
,{uptime, timer:now_diff(erlang:now(), Started)}
].
| null | https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/ecallmgr/src/ecallmgr_diagnostics.erl | erlang | -------------------------------------------------------------------
@doc
Given a diagnostics record, create a diagnostics proplist to return
@end
------------------------------------------------------------------- | @author < >
( C ) 2010 , VoIP , INC
Created : 25 Oct 2010 by < >
-module(ecallmgr_diagnostics).
-export([get_diagnostics/1]).
-include("ecallmgr.hrl").
-spec get_diagnostics/1 :: (Stats) -> [{'active_channels' |
'created_channels' |
'destroyed_channels' |
'last_heartbeat' |
'lookups_failed' |
'lookups_requested' |
'lookups_success' |
'lookups_timeout' |
'uptime'
,integer()},...] when
Stats :: #handler_stats{} | #node_stats{}.
get_diagnostics(#handler_stats{lookups_success=LS, lookups_failed=LF, lookups_timeout=LT, lookups_requested=LR, started=Started}) ->
[{lookups_success, LS}
,{lookups_failed, LF}
,{lookups_timeout, LT}
,{lookups_requested, LR}
,{uptime, timer:now_diff(erlang:now(), Started)}
];
get_diagnostics(#node_stats{last_heartbeat=LH, created_channels=CC, destroyed_channels=DC, started=Started}) ->
[{last_heartbeat, timer:now_diff(erlang:now(), LH)}
,{active_channels, CC - DC}
,{created_channels, CC}
,{destroyed_channels, DC}
,{uptime, timer:now_diff(erlang:now(), Started)}
].
|
5e689766a33d7e673cdb05f56646085c4ca1be68cc8f9b7a37db741fa537c3e2 | bobzhang/fan | test_fan_patt.ml | open Format;
#load "fan_patt.cma";
open Fan_patt;
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/test_fan_patt.ml | ocaml | open Format;
#load "fan_patt.cma";
open Fan_patt;
| |
bf6cf0c28f9de34660f221b94e059d619e63de128932e8852d9e089fd01458d2 | lem-project/lem | typeout.lisp | (in-package :lem)
(define-minor-mode typeout-mode
(:name "typeout"
:keymap *typeout-mode-keymap*
:enable-hook (lambda ()
(setf (variable-value 'line-wrap :buffer (current-buffer)) nil))))
(define-key *typeout-mode-keymap* "q" 'dismiss-typeout-window)
(define-key *typeout-mode-keymap* "Space" 'next-page-or-dismiss-typeout-window)
(define-key *typeout-mode-keymap* "Backspace" 'previous-page)
(defvar *enable-piece-of-paper* t)
(defvar *typeout-window* nil)
(defvar *typeout-before-window* nil)
(defvar *typeout-window-rewinding-values* nil)
(defun pop-up-typeout-window* (buffer function &key focus erase (read-only t))
(declare (ignore focus))
(let ((window (display-buffer buffer)))
(with-buffer-read-only buffer nil
(when erase
(erase-buffer buffer))
(with-open-stream (out (make-buffer-output-stream (buffer-end-point buffer)))
(when function
(save-excursion
(funcall function out)))
(format out "~%--- Press Space to continue ---~%")))
(setf (buffer-read-only-p buffer) read-only)
(setf *typeout-before-window* (current-window))
(setf *typeout-window* window)
(setf (current-window) window)
(typeout-mode t)
(values)))
(defun pop-up-typeout-window (buffer function &key focus erase (read-only t))
(unless *enable-piece-of-paper*
(return-from pop-up-typeout-window
(pop-up-typeout-window* buffer function
:focus focus
:erase erase
:read-only read-only)))
(when (and *typeout-window*
(not (eq buffer (window-buffer *typeout-window*))))
(dismiss-typeout-window)
(redraw-display))
(with-buffer-read-only buffer nil
(when erase
(erase-buffer buffer))
(when function
(with-open-stream (out (make-buffer-output-stream (buffer-end-point buffer)))
(funcall function out)
(fresh-line out))))
(when read-only
(setf (buffer-read-only-p buffer) t))
(let* ((window-height
(min (floor (display-height) 1.1) (1+ (buffer-nlines buffer))))
(window
(cond (*typeout-window*
(lem::window-set-size *typeout-window* (display-width) window-height)
*typeout-window*)
(t
(let ((typeout-buffer-p (buffer-value buffer 'typeout-buffer-p))
(not-switchable-buffer-p (not-switchable-buffer-p buffer)))
(setf *typeout-window-rewinding-values*
(list typeout-buffer-p
not-switchable-buffer-p)))
(let ((window (make-floating-window :buffer buffer
:x 0
:y 0
:width (display-width)
:height window-height
:use-modeline-p t)))
(setf (window-modeline-format window) '(typeout-window-modeline))
(add-hook (window-delete-hook window)
'delete-typeout-window-hook)
(add-hook (window-switch-to-buffer-hook window)
'typeout-window-switch-to-buffer-hook)
(setf *typeout-window* window
*typeout-before-window* (current-window))
window)))))
(setf (buffer-value buffer 'typeout-buffer-p) t)
( setf ( not - switchable - buffer - p buffer ) t )
(bury-buffer buffer)
(setf (current-window) window)
(typeout-mode t)
(redraw-display)
(values)))
(defun typeout-window-modeline (typeout-window)
(values (let* ((posline (string-trim " " (modeline-posline typeout-window)))
(text (cond ((member posline '("All" "Bot") :test #'string=)
"Press Space to continue")
(t posline)))
(line (concatenate 'string
(make-string (- (floor (display-width) 2)
(floor (length text) 2)
1)
:initial-element #\_)
" "
text
" "))
(line (concatenate 'string
line
(make-string (- (display-width) (length text))
:initial-element #\_))))
line)
(make-attribute)
nil))
(defun delete-typeout-window-hook ()
(setf *typeout-window* nil
*typeout-before-window* nil))
(defun typeout-window-switch-to-buffer-hook (&rest args)
(declare (ignore args))
(dismiss-typeout-window))
(define-command dismiss-typeout-window () ()
(if *enable-piece-of-paper*
(dismiss-typeout-window-1)
(dismiss-typeout-window-2)))
(defun dismiss-typeout-window-1 ()
(unless (deleted-window-p *typeout-window*)
(setf (current-window) *typeout-window*)
(typeout-mode nil)
(when (deleted-window-p *typeout-before-window*)
(setf *typeout-before-window* (first (window-list))))
(setf (current-window) *typeout-before-window*)
(when *typeout-window-rewinding-values*
(let ((buffer (window-buffer *typeout-window*)))
(destructuring-bind (typeout-buffer-p
not-switchable-buffer-p)
*typeout-window-rewinding-values*
(setf (buffer-value buffer 'typeout-buffer-p) typeout-buffer-p)
(setf (not-switchable-buffer-p buffer) not-switchable-buffer-p))))
(delete-window *typeout-window*)))
(defun dismiss-typeout-window-2 ()
(when (and (eq (current-buffer) (window-buffer (current-window)))
(find 'typeout-mode (buffer-minor-modes (current-buffer))))
(typeout-mode nil)
(quit-active-window)))
(define-command next-page-or-dismiss-typeout-window () ()
(unless (deleted-window-p *typeout-window*)
(setf (current-window) *typeout-window*)
(move-point (current-point) (window-view-point (current-window)))
(unless (line-offset (current-point) (window-height (current-window)))
(dismiss-typeout-window))))
(define-condition dismiss-typeout-window-if-getout (after-executing-command) ())
(defmethod handle-signal ((condition dismiss-typeout-window-if-getout))
(when (and (not (mode-active-p (window-buffer (current-window)) 'typeout-mode))
*typeout-window*)
(dismiss-typeout-window)))
| null | https://raw.githubusercontent.com/lem-project/lem/cceb43508b7c17aaa8a7176ada7c92af38243062/src/typeout.lisp | lisp | (in-package :lem)
(define-minor-mode typeout-mode
(:name "typeout"
:keymap *typeout-mode-keymap*
:enable-hook (lambda ()
(setf (variable-value 'line-wrap :buffer (current-buffer)) nil))))
(define-key *typeout-mode-keymap* "q" 'dismiss-typeout-window)
(define-key *typeout-mode-keymap* "Space" 'next-page-or-dismiss-typeout-window)
(define-key *typeout-mode-keymap* "Backspace" 'previous-page)
(defvar *enable-piece-of-paper* t)
(defvar *typeout-window* nil)
(defvar *typeout-before-window* nil)
(defvar *typeout-window-rewinding-values* nil)
(defun pop-up-typeout-window* (buffer function &key focus erase (read-only t))
(declare (ignore focus))
(let ((window (display-buffer buffer)))
(with-buffer-read-only buffer nil
(when erase
(erase-buffer buffer))
(with-open-stream (out (make-buffer-output-stream (buffer-end-point buffer)))
(when function
(save-excursion
(funcall function out)))
(format out "~%--- Press Space to continue ---~%")))
(setf (buffer-read-only-p buffer) read-only)
(setf *typeout-before-window* (current-window))
(setf *typeout-window* window)
(setf (current-window) window)
(typeout-mode t)
(values)))
(defun pop-up-typeout-window (buffer function &key focus erase (read-only t))
(unless *enable-piece-of-paper*
(return-from pop-up-typeout-window
(pop-up-typeout-window* buffer function
:focus focus
:erase erase
:read-only read-only)))
(when (and *typeout-window*
(not (eq buffer (window-buffer *typeout-window*))))
(dismiss-typeout-window)
(redraw-display))
(with-buffer-read-only buffer nil
(when erase
(erase-buffer buffer))
(when function
(with-open-stream (out (make-buffer-output-stream (buffer-end-point buffer)))
(funcall function out)
(fresh-line out))))
(when read-only
(setf (buffer-read-only-p buffer) t))
(let* ((window-height
(min (floor (display-height) 1.1) (1+ (buffer-nlines buffer))))
(window
(cond (*typeout-window*
(lem::window-set-size *typeout-window* (display-width) window-height)
*typeout-window*)
(t
(let ((typeout-buffer-p (buffer-value buffer 'typeout-buffer-p))
(not-switchable-buffer-p (not-switchable-buffer-p buffer)))
(setf *typeout-window-rewinding-values*
(list typeout-buffer-p
not-switchable-buffer-p)))
(let ((window (make-floating-window :buffer buffer
:x 0
:y 0
:width (display-width)
:height window-height
:use-modeline-p t)))
(setf (window-modeline-format window) '(typeout-window-modeline))
(add-hook (window-delete-hook window)
'delete-typeout-window-hook)
(add-hook (window-switch-to-buffer-hook window)
'typeout-window-switch-to-buffer-hook)
(setf *typeout-window* window
*typeout-before-window* (current-window))
window)))))
(setf (buffer-value buffer 'typeout-buffer-p) t)
( setf ( not - switchable - buffer - p buffer ) t )
(bury-buffer buffer)
(setf (current-window) window)
(typeout-mode t)
(redraw-display)
(values)))
(defun typeout-window-modeline (typeout-window)
(values (let* ((posline (string-trim " " (modeline-posline typeout-window)))
(text (cond ((member posline '("All" "Bot") :test #'string=)
"Press Space to continue")
(t posline)))
(line (concatenate 'string
(make-string (- (floor (display-width) 2)
(floor (length text) 2)
1)
:initial-element #\_)
" "
text
" "))
(line (concatenate 'string
line
(make-string (- (display-width) (length text))
:initial-element #\_))))
line)
(make-attribute)
nil))
(defun delete-typeout-window-hook ()
(setf *typeout-window* nil
*typeout-before-window* nil))
(defun typeout-window-switch-to-buffer-hook (&rest args)
(declare (ignore args))
(dismiss-typeout-window))
(define-command dismiss-typeout-window () ()
(if *enable-piece-of-paper*
(dismiss-typeout-window-1)
(dismiss-typeout-window-2)))
(defun dismiss-typeout-window-1 ()
(unless (deleted-window-p *typeout-window*)
(setf (current-window) *typeout-window*)
(typeout-mode nil)
(when (deleted-window-p *typeout-before-window*)
(setf *typeout-before-window* (first (window-list))))
(setf (current-window) *typeout-before-window*)
(when *typeout-window-rewinding-values*
(let ((buffer (window-buffer *typeout-window*)))
(destructuring-bind (typeout-buffer-p
not-switchable-buffer-p)
*typeout-window-rewinding-values*
(setf (buffer-value buffer 'typeout-buffer-p) typeout-buffer-p)
(setf (not-switchable-buffer-p buffer) not-switchable-buffer-p))))
(delete-window *typeout-window*)))
(defun dismiss-typeout-window-2 ()
(when (and (eq (current-buffer) (window-buffer (current-window)))
(find 'typeout-mode (buffer-minor-modes (current-buffer))))
(typeout-mode nil)
(quit-active-window)))
(define-command next-page-or-dismiss-typeout-window () ()
(unless (deleted-window-p *typeout-window*)
(setf (current-window) *typeout-window*)
(move-point (current-point) (window-view-point (current-window)))
(unless (line-offset (current-point) (window-height (current-window)))
(dismiss-typeout-window))))
(define-condition dismiss-typeout-window-if-getout (after-executing-command) ())
(defmethod handle-signal ((condition dismiss-typeout-window-if-getout))
(when (and (not (mode-active-p (window-buffer (current-window)) 'typeout-mode))
*typeout-window*)
(dismiss-typeout-window)))
| |
43574d16eb98cbf2f4df22c4db9b1701fc7f9e975f16364d57e9f36f8bdc31d3 | josefs/Gradualizer | gradualizer_cli.erl | %% @doc
%% Gradualizer command line interface.
%% @end
-module(gradualizer_cli).
-export([main/1, handle_args/1]).
-spec main([string()]) -> ok.
main(Args) ->
case handle_args(Args) of
help -> print_usage();
version -> print_version();
{error, Message} ->
io:format(standard_error, "~s~n", [Message]),
halt(1);
{ok, Files, Opts} ->
start_application(Opts),
CheckResult = gradualizer:type_check_files(Files, Opts),
gradualizer_tracer:flush(),
case CheckResult of
ok -> ok;
nok -> halt(1)
end
end.
start_application(Opts) ->
%% An explicit load makes sure any options defined in a *.config file are set before
%% we call `application:set_env/3'.
%% A load after set_env overrides anything set with set_env.
If gradualizer is run as an escript this should not be necessary , but better safe than sorry .
ok = application:load(gradualizer),
application:set_env(gradualizer, options, Opts),
%% We could start the tracer based on a CLI flag, but it's config is compile-time anyway.
%gradualizer_tracer:start(),
{ok, _} = application:ensure_all_started(gradualizer).
-spec handle_args([string()]) -> help | version | {error, string()} |
{ok, [string()], gradualizer:options()}.
handle_args([]) -> help;
handle_args(Args) ->
try parse_opts(Args, []) of
{Rest, Opts} ->
HasHelp = proplists:get_bool(help, Opts),
HasVersion = proplists:get_bool(version, Opts),
if
HasHelp -> help;
HasVersion -> version;
Rest =:= [] -> {error, "No files specified to check (try --)"};
true ->
{ok, Rest, Opts}
end
catch
error:Message when is_list(Message) ->
{error, Message}
end.
-spec get_ver(atom()) -> string().
get_ver(App) ->
{_, _, Ver} = lists:keyfind(App, 1, application:loaded_applications()),
Ver.
print_version() ->
application:load(gradualizer),
io:format("Gradualizer v~s~n", [get_ver(gradualizer)]).
print_usage() ->
io:format("Usage: gradualizer [options] [PATH...]~n"),
io:format("A type checker for Erlang/Elixir~n~n"),
io:format(" PATH Files or directories to type check~n"),
io:format(" -- Signals that no more options will follow. The following~n"),
io:format(" arguments are treated as filenames, even if~n"),
io:format(" they start with hyphens.~n"),
io:format(" -h, --help display this help and exit~n"),
io:format(" --infer Infer type information from literals and other~n"),
io:format(" language constructs~n"),
io:format(" --no_infer Only use type information from function specs~n"),
io:format(" - the default behaviour~n"),
io:format(" --verbose Show what Gradualizer is doing~n"),
io:format(" -pa, --path_add Add the specified directory to the beginning of~n"),
io:format(" the code path; see erl -pa [string]~n"),
io:format(" -I Include path for Erlang source files; see -I in~n"),
io:format(" the manual page erlc(1)~n"),
io:format(" --stop_on_first_error stop type checking at the first error~n"),
io:format(" --no_stop_on_first_error inverse of --stop-on-first-error~n"),
io:format(" - the default behaviour~n"),
io:format(" --no_prelude Do not override OTP specs.~n"),
io:format(" --specs_override_dir Add specs overrides from the *.specs.erl files in~n"),
io:format(" this directory.~n"),
io:format(" --fmt_location How to format location when pretty printing errors~n"),
io:format(" (Column is only available if analyzing from source)~n"),
io:format(" - 'none': no location for easier comparison~n"),
io:format(" - 'brief': for machine processing~n"),
io:format(" (\"LINE:COLUMN:\" before message text)~n"),
io:format(" - 'verbose' (default): for human readers~n"),
io:format(" (\"on line LINE at column COLUMN\" within the message text)~n"),
io:format(" --color [ COLOR ] - Use colors when printing fancy messages. An optional~n"),
io:format(" argument is `always | never | auto'. However, auto-~n"),
io:format(" detection of a TTY doesn't work when running as an escript.~n"),
io:format(" --no_color - Alias for `--color never'~n"),
io:format(" --fancy - Use fancy error messages when possible (on by default)~n"),
io:format(" --no_fancy - Don't use fancy error messages.~n"),
io:format(" --union_size_limit - Performance hack: Unions larger than this value~n"),
io:format(" are replaced by any() in normalization (default: 30)~n"),
io:format(" --solve_constraints - Use the experimental constraint solver (off by default)~n").
-spec parse_opts([string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
parse_opts([], Opts) ->
{[], Opts};
parse_opts([A | Args], Opts) ->
case A of
"-h" -> {[], [help]};
"--help" -> {[], [help]};
"--infer" -> parse_opts(Args, [infer | Opts]);
"--no_infer" -> parse_opts(Args, [{infer, false} | Opts]);
"--verbose" -> parse_opts(Args, [verbose | Opts]);
"-pa" -> handle_path_add(A, Args, Opts);
"--path_add" -> handle_path_add(A, Args, Opts);
"-I" -> handle_include_path(A, Args, Opts);
"--stop_on_first_error" -> parse_opts(Args, [stop_on_first_error | Opts]);
"--no_stop_on_first_error" -> parse_opts(Args, [{stop_on_first_error, false} | Opts]);
"--crash_on_error" -> parse_opts(Args, [crash_on_error | Opts]);
"--no_crash_on_error" -> parse_opts(Args, [{crash_on_error, false} | Opts]);
"--version" -> {[], [version]};
"--no_prelude" -> parse_opts(Args, [{prelude, false}| Opts]);
"--specs_override_dir" -> handle_specs_override(A, Args, Opts);
"--fmt_location" -> handle_fmt_location(Args, Opts);
"--color" -> handle_color(Args, Opts);
"--no_color" -> parse_opts(Args, [{color, never} | Opts]);
"--fancy" -> parse_opts(Args, [fancy | Opts]);
"--no_fancy" -> parse_opts(Args, [{fancy, false} | Opts]);
"--union_size_limit" -> handle_union_size_limit(A, Args, Opts);
"--solve_constraints" -> parse_opts(Args, [solve_constraints | Opts]);
"--" -> {Args, Opts};
"-" ++ _ -> erlang:error(string:join(["Unknown parameter:", A], " "));
_ -> {[A | Args], Opts}
end.
-spec handle_path_add(string(), [string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_path_add(A, Args, Opts) ->
{Paths, RestArgs} = lists:splitwith(fun no_start_dash/1, Args),
case Paths of
[] ->
erlang:error(string:join(["Missing argument for", A], " "));
_ ->
code:add_pathsa(Paths)
end,
parse_opts(RestArgs, Opts).
-spec handle_include_path(string(), [string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_include_path(_, [Dir | Args], Opts) ->
parse_opts(Args, [{i, Dir} | Opts]);
handle_include_path(A, [], _Opts) ->
erlang:error(string:join(["Missing argument for", A], " ")).
-spec handle_specs_override(string(), [string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_specs_override(_, [Dir | Args], Opts) ->
parse_opts(Args, [{specs_override, Dir} | Opts]);
handle_specs_override(A, [], _Opts) ->
erlang:error(string:join(["Missing argument for", A], " ")).
handle_fmt_location([FmtTypeStr | Args], Opts) ->
try list_to_existing_atom(FmtTypeStr) of
FmtType when FmtType =:= none;
FmtType =:= brief;
FmtType =:= verbose ->
parse_opts(Args, [{fmt_location, FmtType}|Opts]);
_ ->
erlang:error(lists:append(["Bad value for fmt-location: ", FmtTypeStr]))
catch _:_ ->
erlang:error(lists:append(["Bad value for fmt-location: ", FmtTypeStr]))
end.
%% Handle Args after --color.
-spec handle_color([string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_color(["always"|Args], Opts) -> parse_opts(Args, [{color, always} | Opts]);
handle_color(["never" |Args], Opts) -> parse_opts(Args, [{color, never} | Opts]);
handle_color(["auto" |Args], Opts) -> parse_opts(Args, [{color, auto} | Opts]);
handle_color(Args, Opts) -> parse_opts(Args, [{color, always} | Opts]).
handle_union_size_limit(_, [LimitS | Args], _Opts) ->
Limit = list_to_integer(LimitS),
parse_opts(Args, [{union_size_limit, Limit}]);
handle_union_size_limit(A, [], _Opts) ->
erlang:error(string:join(["Missing argument for", A], " ")).
no_start_dash("-" ++ _) ->
false;
no_start_dash(_) ->
true.
| null | https://raw.githubusercontent.com/josefs/Gradualizer/22a8e19f1c88a00399eaeda41cf8ddde302061bd/src/gradualizer_cli.erl | erlang | @doc
Gradualizer command line interface.
@end
An explicit load makes sure any options defined in a *.config file are set before
we call `application:set_env/3'.
A load after set_env overrides anything set with set_env.
We could start the tracer based on a CLI flag, but it's config is compile-time anyway.
gradualizer_tracer:start(),
Handle Args after --color. | -module(gradualizer_cli).
-export([main/1, handle_args/1]).
-spec main([string()]) -> ok.
main(Args) ->
case handle_args(Args) of
help -> print_usage();
version -> print_version();
{error, Message} ->
io:format(standard_error, "~s~n", [Message]),
halt(1);
{ok, Files, Opts} ->
start_application(Opts),
CheckResult = gradualizer:type_check_files(Files, Opts),
gradualizer_tracer:flush(),
case CheckResult of
ok -> ok;
nok -> halt(1)
end
end.
start_application(Opts) ->
If gradualizer is run as an escript this should not be necessary , but better safe than sorry .
ok = application:load(gradualizer),
application:set_env(gradualizer, options, Opts),
{ok, _} = application:ensure_all_started(gradualizer).
-spec handle_args([string()]) -> help | version | {error, string()} |
{ok, [string()], gradualizer:options()}.
handle_args([]) -> help;
handle_args(Args) ->
try parse_opts(Args, []) of
{Rest, Opts} ->
HasHelp = proplists:get_bool(help, Opts),
HasVersion = proplists:get_bool(version, Opts),
if
HasHelp -> help;
HasVersion -> version;
Rest =:= [] -> {error, "No files specified to check (try --)"};
true ->
{ok, Rest, Opts}
end
catch
error:Message when is_list(Message) ->
{error, Message}
end.
-spec get_ver(atom()) -> string().
get_ver(App) ->
{_, _, Ver} = lists:keyfind(App, 1, application:loaded_applications()),
Ver.
print_version() ->
application:load(gradualizer),
io:format("Gradualizer v~s~n", [get_ver(gradualizer)]).
print_usage() ->
io:format("Usage: gradualizer [options] [PATH...]~n"),
io:format("A type checker for Erlang/Elixir~n~n"),
io:format(" PATH Files or directories to type check~n"),
io:format(" -- Signals that no more options will follow. The following~n"),
io:format(" arguments are treated as filenames, even if~n"),
io:format(" they start with hyphens.~n"),
io:format(" -h, --help display this help and exit~n"),
io:format(" --infer Infer type information from literals and other~n"),
io:format(" language constructs~n"),
io:format(" --no_infer Only use type information from function specs~n"),
io:format(" - the default behaviour~n"),
io:format(" --verbose Show what Gradualizer is doing~n"),
io:format(" -pa, --path_add Add the specified directory to the beginning of~n"),
io:format(" the code path; see erl -pa [string]~n"),
io:format(" -I Include path for Erlang source files; see -I in~n"),
io:format(" the manual page erlc(1)~n"),
io:format(" --stop_on_first_error stop type checking at the first error~n"),
io:format(" --no_stop_on_first_error inverse of --stop-on-first-error~n"),
io:format(" - the default behaviour~n"),
io:format(" --no_prelude Do not override OTP specs.~n"),
io:format(" --specs_override_dir Add specs overrides from the *.specs.erl files in~n"),
io:format(" this directory.~n"),
io:format(" --fmt_location How to format location when pretty printing errors~n"),
io:format(" (Column is only available if analyzing from source)~n"),
io:format(" - 'none': no location for easier comparison~n"),
io:format(" - 'brief': for machine processing~n"),
io:format(" (\"LINE:COLUMN:\" before message text)~n"),
io:format(" - 'verbose' (default): for human readers~n"),
io:format(" (\"on line LINE at column COLUMN\" within the message text)~n"),
io:format(" --color [ COLOR ] - Use colors when printing fancy messages. An optional~n"),
io:format(" argument is `always | never | auto'. However, auto-~n"),
io:format(" detection of a TTY doesn't work when running as an escript.~n"),
io:format(" --no_color - Alias for `--color never'~n"),
io:format(" --fancy - Use fancy error messages when possible (on by default)~n"),
io:format(" --no_fancy - Don't use fancy error messages.~n"),
io:format(" --union_size_limit - Performance hack: Unions larger than this value~n"),
io:format(" are replaced by any() in normalization (default: 30)~n"),
io:format(" --solve_constraints - Use the experimental constraint solver (off by default)~n").
-spec parse_opts([string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
parse_opts([], Opts) ->
{[], Opts};
parse_opts([A | Args], Opts) ->
case A of
"-h" -> {[], [help]};
"--help" -> {[], [help]};
"--infer" -> parse_opts(Args, [infer | Opts]);
"--no_infer" -> parse_opts(Args, [{infer, false} | Opts]);
"--verbose" -> parse_opts(Args, [verbose | Opts]);
"-pa" -> handle_path_add(A, Args, Opts);
"--path_add" -> handle_path_add(A, Args, Opts);
"-I" -> handle_include_path(A, Args, Opts);
"--stop_on_first_error" -> parse_opts(Args, [stop_on_first_error | Opts]);
"--no_stop_on_first_error" -> parse_opts(Args, [{stop_on_first_error, false} | Opts]);
"--crash_on_error" -> parse_opts(Args, [crash_on_error | Opts]);
"--no_crash_on_error" -> parse_opts(Args, [{crash_on_error, false} | Opts]);
"--version" -> {[], [version]};
"--no_prelude" -> parse_opts(Args, [{prelude, false}| Opts]);
"--specs_override_dir" -> handle_specs_override(A, Args, Opts);
"--fmt_location" -> handle_fmt_location(Args, Opts);
"--color" -> handle_color(Args, Opts);
"--no_color" -> parse_opts(Args, [{color, never} | Opts]);
"--fancy" -> parse_opts(Args, [fancy | Opts]);
"--no_fancy" -> parse_opts(Args, [{fancy, false} | Opts]);
"--union_size_limit" -> handle_union_size_limit(A, Args, Opts);
"--solve_constraints" -> parse_opts(Args, [solve_constraints | Opts]);
"--" -> {Args, Opts};
"-" ++ _ -> erlang:error(string:join(["Unknown parameter:", A], " "));
_ -> {[A | Args], Opts}
end.
-spec handle_path_add(string(), [string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_path_add(A, Args, Opts) ->
{Paths, RestArgs} = lists:splitwith(fun no_start_dash/1, Args),
case Paths of
[] ->
erlang:error(string:join(["Missing argument for", A], " "));
_ ->
code:add_pathsa(Paths)
end,
parse_opts(RestArgs, Opts).
-spec handle_include_path(string(), [string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_include_path(_, [Dir | Args], Opts) ->
parse_opts(Args, [{i, Dir} | Opts]);
handle_include_path(A, [], _Opts) ->
erlang:error(string:join(["Missing argument for", A], " ")).
-spec handle_specs_override(string(), [string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_specs_override(_, [Dir | Args], Opts) ->
parse_opts(Args, [{specs_override, Dir} | Opts]);
handle_specs_override(A, [], _Opts) ->
erlang:error(string:join(["Missing argument for", A], " ")).
handle_fmt_location([FmtTypeStr | Args], Opts) ->
try list_to_existing_atom(FmtTypeStr) of
FmtType when FmtType =:= none;
FmtType =:= brief;
FmtType =:= verbose ->
parse_opts(Args, [{fmt_location, FmtType}|Opts]);
_ ->
erlang:error(lists:append(["Bad value for fmt-location: ", FmtTypeStr]))
catch _:_ ->
erlang:error(lists:append(["Bad value for fmt-location: ", FmtTypeStr]))
end.
-spec handle_color([string()], gradualizer:options()) -> {[string()], gradualizer:options()}.
handle_color(["always"|Args], Opts) -> parse_opts(Args, [{color, always} | Opts]);
handle_color(["never" |Args], Opts) -> parse_opts(Args, [{color, never} | Opts]);
handle_color(["auto" |Args], Opts) -> parse_opts(Args, [{color, auto} | Opts]);
handle_color(Args, Opts) -> parse_opts(Args, [{color, always} | Opts]).
handle_union_size_limit(_, [LimitS | Args], _Opts) ->
Limit = list_to_integer(LimitS),
parse_opts(Args, [{union_size_limit, Limit}]);
handle_union_size_limit(A, [], _Opts) ->
erlang:error(string:join(["Missing argument for", A], " ")).
no_start_dash("-" ++ _) ->
false;
no_start_dash(_) ->
true.
|
580e728368e38b14e755b9b1812710c72d9e4dee905fdb59d3caafada52aea0d | basho/riak-erlang-client | riakc_utils_tests.erl | %% -------------------------------------------------------------------
%%
%% riakc_utils_tests
%%
Copyright ( c ) 2016 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-ifdef(TEST).
-module(riakc_utils_tests).
-compile([export_all, nowarn_export_all]).
-include_lib("eunit/include/eunit.hrl").
bad_unicode_binary_test() ->
S = <<"\xa0\xa1">>,
?assertThrow({unicode_error, _Msg}, riakc_utils:characters_to_unicode_binary(S)).
-endif.
| null | https://raw.githubusercontent.com/basho/riak-erlang-client/ea4fcd062f55a67e31c7294a1b8b8ccd957526c8/test/riakc_utils_tests.erl | erlang | -------------------------------------------------------------------
riakc_utils_tests
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
------------------------------------------------------------------- | Copyright ( c ) 2016 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-ifdef(TEST).
-module(riakc_utils_tests).
-compile([export_all, nowarn_export_all]).
-include_lib("eunit/include/eunit.hrl").
bad_unicode_binary_test() ->
S = <<"\xa0\xa1">>,
?assertThrow({unicode_error, _Msg}, riakc_utils:characters_to_unicode_binary(S)).
-endif.
|
560985ee5861cce7a254e231f309517fd6ff19e47e7c8a62d5b4ebaac645c05b | cwearl/fulmar | core-chunk-tests.rkt | #lang racket
(require rackunit)
(require "../private/fulmar-core.rkt")
(require "../private/core-chunk.rkt")
;unit tests for core-chunk.rkt
;helper functions
(define/provide-test-suite test-combine-strings
(test-case
"Test combine-strings"
(check-equal? (combine-strings "asdf") "asdf")
(check-equal? (combine-strings 'asdf) "asdf")
(check-equal? (combine-strings "asdf" "jkl") "asdfjkl")
(check-equal? (combine-strings "asdf" 'jkl) "asdfjkl")
(check-equal? (combine-strings 'asdf "jkl") "asdfjkl")
(check-equal? (combine-strings 'asdf 'jkl) "asdfjkl")))
(define/provide-test-suite test-length-equals-one
(test-case
"Test length-equals-one"
(check-true (length-equals-one (list "")))
(check-true (length-equals-one (list " ")))
(check-true (length-equals-one (list "abcd")))
(check-false (length-equals-one (list "" "")))
(check-false (length-equals-one (list "" " ")))
(check-false (length-equals-one (list " " "")))
(check-false (length-equals-one (list " " " ")))
(check-false (length-equals-one (list "abcd" "")))
(check-false (length-equals-one (list "" "abcd")))
(check-false (length-equals-one (list "abcd" "abcd")))))
(define/provide-test-suite test-chunk-transform
(test-case
"Test chunk-transform - tests only implicit chunks (not structured chunks)"
(check-equal? (write-chunk "asdf")
'("asdf"))
(check-equal? (write-chunk 'asdf)
'("asdf"))
(check-equal? (write-chunk 1)
'("1"))
(check-equal? (write-chunk 4)
'("4"))))
;nekot-building chunks
(define/provide-test-suite test-literal
(test-case
"Test literal"
(check-equal? (write-chunk (literal "asdf"))
'("asdf"))
(check-equal? (write-chunk (literal 'asdf))
'("asdf"))
(check-equal? (write-chunk (literal "asdf" "jkl"))
'("asdfjkl"))
(check-equal? (write-chunk (literal "asdf" 'jkl))
'("asdfjkl"))
(check-equal? (write-chunk (literal 'asdf "jkl"))
'("asdfjkl"))
(check-equal? (write-chunk (literal 'asdf 'jkl))
'("asdfjkl"))))
(define/provide-test-suite test-space
(test-case
"Test space"
(check-equal? (write-chunk space)
'(" "))))
(define/provide-test-suite test-new-line
(test-case
"Test new-line"
(check-equal? (write-chunk new-line)
'("" ""))
(check-equal? (write-chunk new-line)
'("" ""))))
(define/provide-test-suite test-pp-directive
(test-case
"Test pp-directive"
(check-equal? (write-chunk pp-directive)
'("#"))))
meta - nekot - building chunks
(define/provide-test-suite test-empty
(test-case
"Test empty"
(check-equal? (write-chunk empty)
'(""))
(check-equal? (write-chunk (concat empty
"asdf"))
'("asdf"))))
(define/provide-test-suite test-concat
(test-case
"Test concat"
(check-equal? (write-chunk (concat 'asdf 'jkl))
'("asdfjkl"))
(check-equal? (write-chunk (concat (list 'asdf 'jkl)))
'("asdfjkl"))
(check-equal? (write-chunk (concat 'asdf 4 'jkl))
'("asdf4jkl"))))
(define/provide-test-suite test-immediate
(test-case
"Test immediate"
(check-equal? (write-chunk (immediate 'asdf))
'("asdf"))
(check-equal? (write-chunk (immediate 4))
'("4"))
(check-equal? (write-chunk (immediate (concat 4 'asdf)))
'("4asdf"))))
(define/provide-test-suite test-speculative
(test-case
"Test speculative"
(define test-success? (λ (any) #false))
(define check-length (λ (lst) (= 1 (length lst))))
(check-equal? (write-chunk (speculative 'asdf test-success? 'jkl))
'("jkl"))
(check-equal? (write-chunk (speculative new-line check-length 4))
'("4"))))
(define/provide-test-suite test-position-indent
(test-case
"Test position-indent"
(define test 'asdf)
(define test-2 'jkl)
(check-equal? (write-chunk (position-indent 'asdf))
'("asdf"))
(check-equal? (write-chunk (concat 'asdf (position-indent (concat new-line 'jkl))))
'(" jkl"
"asdf"))))
;context-aware chunks
(define/provide-test-suite test-indent
(test-case
"Test indent"
(check-equal? (write-chunk (indent 0 (concat 'asdf new-line 'jkl)))
'("jkl"
"asdf"))
(check-equal? (write-chunk (indent 2 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 5 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 2 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 5 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 2 (indent 1 (concat 'asdf new-line 'jkl))))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (indent 2 (concat 'asdf new-line 'jkl))))
'(" jkl"
" asdf")))
(test-case
"Test indent - interaction with position-indent tests"
(check-equal? (write-chunk (concat 123 (position-indent (concat 'asdf new-line 'jkl))))
'(" jkl"
"123asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line 'jkl)))))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line 'jkl new-line "123")))))
'(" 123"
" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line 'jkl new-line (indent 1 "123"))))))
'(" 123"
" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line
(indent 1 'jkl)
new-line
"123")))))
'(" 123"
" jkl"
" asdf"))))
(define/provide-test-suite test-comment-env-chunk
(test-case
"Test comment-env-chunk"
(check-equal? (write-chunk (comment-env-chunk 'asdf #\*))
'("/**asdf */"))
(check-equal? (write-chunk (comment-env-chunk 'asdf #\ ))
'("/* asdf */"))
(check-equal? (write-chunk (comment-env-chunk 'asdf))
'("/* asdf */"))
(check-equal? (write-chunk (comment-env-chunk (indent 2 (comment-env-chunk 'asdf))))
'("/* /* asdf ** */"))
(check-equal? (write-chunk (comment-env-chunk (concat new-line (indent 2 (comment-env-chunk 'asdf)))))
'(" /* asdf ** */"
"/*"))
(check-equal? (write-chunk (comment-env-chunk (concat 'asdf new-line 'jkl)))
'(" jkl */"
"/* asdf"))))
| null | https://raw.githubusercontent.com/cwearl/fulmar/4cf60699558b3bb28fa813443456993d1563bfb2/tests/core-chunk-tests.rkt | racket | unit tests for core-chunk.rkt
helper functions
nekot-building chunks
context-aware chunks | #lang racket
(require rackunit)
(require "../private/fulmar-core.rkt")
(require "../private/core-chunk.rkt")
(define/provide-test-suite test-combine-strings
(test-case
"Test combine-strings"
(check-equal? (combine-strings "asdf") "asdf")
(check-equal? (combine-strings 'asdf) "asdf")
(check-equal? (combine-strings "asdf" "jkl") "asdfjkl")
(check-equal? (combine-strings "asdf" 'jkl) "asdfjkl")
(check-equal? (combine-strings 'asdf "jkl") "asdfjkl")
(check-equal? (combine-strings 'asdf 'jkl) "asdfjkl")))
(define/provide-test-suite test-length-equals-one
(test-case
"Test length-equals-one"
(check-true (length-equals-one (list "")))
(check-true (length-equals-one (list " ")))
(check-true (length-equals-one (list "abcd")))
(check-false (length-equals-one (list "" "")))
(check-false (length-equals-one (list "" " ")))
(check-false (length-equals-one (list " " "")))
(check-false (length-equals-one (list " " " ")))
(check-false (length-equals-one (list "abcd" "")))
(check-false (length-equals-one (list "" "abcd")))
(check-false (length-equals-one (list "abcd" "abcd")))))
(define/provide-test-suite test-chunk-transform
(test-case
"Test chunk-transform - tests only implicit chunks (not structured chunks)"
(check-equal? (write-chunk "asdf")
'("asdf"))
(check-equal? (write-chunk 'asdf)
'("asdf"))
(check-equal? (write-chunk 1)
'("1"))
(check-equal? (write-chunk 4)
'("4"))))
(define/provide-test-suite test-literal
(test-case
"Test literal"
(check-equal? (write-chunk (literal "asdf"))
'("asdf"))
(check-equal? (write-chunk (literal 'asdf))
'("asdf"))
(check-equal? (write-chunk (literal "asdf" "jkl"))
'("asdfjkl"))
(check-equal? (write-chunk (literal "asdf" 'jkl))
'("asdfjkl"))
(check-equal? (write-chunk (literal 'asdf "jkl"))
'("asdfjkl"))
(check-equal? (write-chunk (literal 'asdf 'jkl))
'("asdfjkl"))))
(define/provide-test-suite test-space
(test-case
"Test space"
(check-equal? (write-chunk space)
'(" "))))
(define/provide-test-suite test-new-line
(test-case
"Test new-line"
(check-equal? (write-chunk new-line)
'("" ""))
(check-equal? (write-chunk new-line)
'("" ""))))
(define/provide-test-suite test-pp-directive
(test-case
"Test pp-directive"
(check-equal? (write-chunk pp-directive)
'("#"))))
meta - nekot - building chunks
(define/provide-test-suite test-empty
(test-case
"Test empty"
(check-equal? (write-chunk empty)
'(""))
(check-equal? (write-chunk (concat empty
"asdf"))
'("asdf"))))
(define/provide-test-suite test-concat
(test-case
"Test concat"
(check-equal? (write-chunk (concat 'asdf 'jkl))
'("asdfjkl"))
(check-equal? (write-chunk (concat (list 'asdf 'jkl)))
'("asdfjkl"))
(check-equal? (write-chunk (concat 'asdf 4 'jkl))
'("asdf4jkl"))))
(define/provide-test-suite test-immediate
(test-case
"Test immediate"
(check-equal? (write-chunk (immediate 'asdf))
'("asdf"))
(check-equal? (write-chunk (immediate 4))
'("4"))
(check-equal? (write-chunk (immediate (concat 4 'asdf)))
'("4asdf"))))
(define/provide-test-suite test-speculative
(test-case
"Test speculative"
(define test-success? (λ (any) #false))
(define check-length (λ (lst) (= 1 (length lst))))
(check-equal? (write-chunk (speculative 'asdf test-success? 'jkl))
'("jkl"))
(check-equal? (write-chunk (speculative new-line check-length 4))
'("4"))))
(define/provide-test-suite test-position-indent
(test-case
"Test position-indent"
(define test 'asdf)
(define test-2 'jkl)
(check-equal? (write-chunk (position-indent 'asdf))
'("asdf"))
(check-equal? (write-chunk (concat 'asdf (position-indent (concat new-line 'jkl))))
'(" jkl"
"asdf"))))
(define/provide-test-suite test-indent
(test-case
"Test indent"
(check-equal? (write-chunk (indent 0 (concat 'asdf new-line 'jkl)))
'("jkl"
"asdf"))
(check-equal? (write-chunk (indent 2 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 5 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 2 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 5 (concat 'asdf new-line 'jkl)))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 2 (indent 1 (concat 'asdf new-line 'jkl))))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (indent 2 (concat 'asdf new-line 'jkl))))
'(" jkl"
" asdf")))
(test-case
"Test indent - interaction with position-indent tests"
(check-equal? (write-chunk (concat 123 (position-indent (concat 'asdf new-line 'jkl))))
'(" jkl"
"123asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line 'jkl)))))
'(" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line 'jkl new-line "123")))))
'(" 123"
" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line 'jkl new-line (indent 1 "123"))))))
'(" 123"
" jkl"
" asdf"))
(check-equal? (write-chunk (indent 3 (concat 'asdf (position-indent (concat new-line
(indent 1 'jkl)
new-line
"123")))))
'(" 123"
" jkl"
" asdf"))))
(define/provide-test-suite test-comment-env-chunk
(test-case
"Test comment-env-chunk"
(check-equal? (write-chunk (comment-env-chunk 'asdf #\*))
'("/**asdf */"))
(check-equal? (write-chunk (comment-env-chunk 'asdf #\ ))
'("/* asdf */"))
(check-equal? (write-chunk (comment-env-chunk 'asdf))
'("/* asdf */"))
(check-equal? (write-chunk (comment-env-chunk (indent 2 (comment-env-chunk 'asdf))))
'("/* /* asdf ** */"))
(check-equal? (write-chunk (comment-env-chunk (concat new-line (indent 2 (comment-env-chunk 'asdf)))))
'(" /* asdf ** */"
"/*"))
(check-equal? (write-chunk (comment-env-chunk (concat 'asdf new-line 'jkl)))
'(" jkl */"
"/* asdf"))))
|
0da75fd9cf5c3f997b19081e155874dfdcd2f2ae441b8a7665342dabbb46ed6e | fpottier/mpri-2.4-projet-2022-2023 | Linear2Surface.ml | open Surface
(* -------------------------------------------------------------------------- *)
(* Variable and function names. *)
let translate_var (Linear.U x) =
x
let translate_vars uxs =
List.map translate_var uxs
let translate_binding (ux, _ty) =
translate_var ux
let translate_bindings ubs =
List.map translate_binding ubs
let transport_binding (ux, ty) =
translate_var ux, ty
let transport_bindings ubs =
List.map transport_binding ubs
(* -------------------------------------------------------------------------- *)
(* Expressions. *)
A multi - result of arity 1 is translated to an ordinary result .
A multi - result of arity other than 1 is translated to a tuple .
A multi-result of arity other than 1 is translated to a tuple. *)
let rec translate (e : Linear.expr) : expr =
match e with
| Linear.Ret ([ux], lxs) ->
assert (lxs = []);
Var (translate_var ux)
| Linear.Ret (uxs, lxs) ->
assert (lxs = []);
TupleIntro (vars (translate_vars uxs))
| Linear.Let ([ub], lbs, e1, e2) ->
assert (lbs = []);
Let (translate_binding ub, translate e1, translate e2)
| Linear.Let (ubs, lbs, e1, e2) ->
assert (lbs = []);
TupleElim (translate_bindings ubs, translate e1, translate e2)
| Linear.ULiteral c ->
Literal c
| Linear.UUnOp (op, x) ->
UnOp (op, var (translate_var x))
| Linear.UBinOp (x1, op, x2) ->
BinOp (var (translate_var x1), op, var (translate_var x2))
| Linear.LZero _
| Linear.LAdd _
| Linear.LMul _
| Linear.Drop _
| Linear.Dup _
| Linear.LTupleIntro _
| Linear.LTupleElim _
-> assert false
| Linear.UTupleIntro uxs ->
TupleIntro (vars (translate_vars uxs))
| Linear.UTupleElim (ubs, ux1, e2) ->
TupleElim (translate_bindings ubs, var (translate_var ux1), translate e2)
| Linear.FunCall (f, uxs, lxs) ->
assert (lxs = []);
FunCall (f, vars (translate_vars uxs))
| Linear.Loc (e, loc) ->
(match loc with
| Linear.Virtual _ ->
translate e
| Linear.Source range ->
Loc (translate e, range)
)
(* -------------------------------------------------------------------------- *)
(* Declarations. *)
let translate_decl decl =
match decl with
| Linear.Decl (_range, f, ubs, lbs, e) ->
assert (lbs = []);
Decl (f, transport_bindings ubs, translate e, dummy)
let translate decls =
List.map translate_decl decls
| null | https://raw.githubusercontent.com/fpottier/mpri-2.4-projet-2022-2023/1ce08cadfb3a8ec8bc72609bc82873b29d2ce241/src/Linear2Surface.ml | ocaml | --------------------------------------------------------------------------
Variable and function names.
--------------------------------------------------------------------------
Expressions.
--------------------------------------------------------------------------
Declarations. | open Surface
let translate_var (Linear.U x) =
x
let translate_vars uxs =
List.map translate_var uxs
let translate_binding (ux, _ty) =
translate_var ux
let translate_bindings ubs =
List.map translate_binding ubs
let transport_binding (ux, ty) =
translate_var ux, ty
let transport_bindings ubs =
List.map transport_binding ubs
A multi - result of arity 1 is translated to an ordinary result .
A multi - result of arity other than 1 is translated to a tuple .
A multi-result of arity other than 1 is translated to a tuple. *)
let rec translate (e : Linear.expr) : expr =
match e with
| Linear.Ret ([ux], lxs) ->
assert (lxs = []);
Var (translate_var ux)
| Linear.Ret (uxs, lxs) ->
assert (lxs = []);
TupleIntro (vars (translate_vars uxs))
| Linear.Let ([ub], lbs, e1, e2) ->
assert (lbs = []);
Let (translate_binding ub, translate e1, translate e2)
| Linear.Let (ubs, lbs, e1, e2) ->
assert (lbs = []);
TupleElim (translate_bindings ubs, translate e1, translate e2)
| Linear.ULiteral c ->
Literal c
| Linear.UUnOp (op, x) ->
UnOp (op, var (translate_var x))
| Linear.UBinOp (x1, op, x2) ->
BinOp (var (translate_var x1), op, var (translate_var x2))
| Linear.LZero _
| Linear.LAdd _
| Linear.LMul _
| Linear.Drop _
| Linear.Dup _
| Linear.LTupleIntro _
| Linear.LTupleElim _
-> assert false
| Linear.UTupleIntro uxs ->
TupleIntro (vars (translate_vars uxs))
| Linear.UTupleElim (ubs, ux1, e2) ->
TupleElim (translate_bindings ubs, var (translate_var ux1), translate e2)
| Linear.FunCall (f, uxs, lxs) ->
assert (lxs = []);
FunCall (f, vars (translate_vars uxs))
| Linear.Loc (e, loc) ->
(match loc with
| Linear.Virtual _ ->
translate e
| Linear.Source range ->
Loc (translate e, range)
)
let translate_decl decl =
match decl with
| Linear.Decl (_range, f, ubs, lbs, e) ->
assert (lbs = []);
Decl (f, transport_bindings ubs, translate e, dummy)
let translate decls =
List.map translate_decl decls
|
c001385c58c535e33f05e271f6c03cc2bf078bb0fb8576d96a755124b0d7a1dc | roelvandijk/numerals | Exp.hs | {-# language CPP #-}
module Text.Numeral.Exp
( Exp(..)
, showExp
-- , eval
, evalScale
, Side(L, R)
) where
-------------------------------------------------------------------------------
-- Imports
-------------------------------------------------------------------------------
#if !(MIN_VERSION_base(4,8,0))
import "base" Control.Applicative ( (<$>) )
#endif
import qualified "this" Text.Numeral.Grammar as G
-------------------------------------------------------------------------------
-- Expression type
-------------------------------------------------------------------------------
-- | An expression that represents the structure of a numeral.
data Exp
= Unknown
-- ^ An unknown value. This is used to signal that a value can
-- not be represented in the expression language.
| Lit Integer
-- ^ A literal value.
--
Example in English :
--
> " three " = Lit 3
| Neg Exp
-- ^ Negation of an expression.
--
Example in English :
--
> " minus two " = Neg ( Lit 2 )
| Add Exp Exp
^ Addition of two expressions .
--
Example in English :
--
> " fifteen " = Lit 5 ` Add ` Lit 10
| Mul Exp Exp
^ Multiplication of two expressions .
--
Example in English :
--
> " thirty " = Lit 3 ` Mul ` Lit 10
| Sub Exp Exp
^ One expression subtracted from another expression .
--
Example in Latin :
--
-- > "duodēvīgintī" = Lit 2 `Sub` (Lit 2 `Mul` Lit 10)
| Frac Exp Exp
-- ^ A fraction.
--
Example in English :
--
> " two thirds " = ` Frac ` ( Lit 2 ) ( Lit 3 )
| Scale Integer Integer Exp
-- ^ A step in a scale of large values.
--
Should be interpreted as @10 ^ ( rank * base + offset)@.
--
Example in English :
--
> " quadrillion " = Scale 3 3 4
| ChangeCase (Maybe G.Case ) Exp
| ChangeGender (Maybe G.Gender) Exp
-- ^ A change of grammatical gender.
--
This is used in a language like Spanish where the inflection
-- of a number word is not always constant. Specifically, in
Spanish , large number names always have the masculine
gender . So ' millón ' , ' ' and the like are all
-- masculine. This can result in the following number word:
10000001 = " un ( masculine ) millón una ( feminine ) "
--
Example in Spanish ( with the context being Feminine ):
--
> " " = ChangeGender ( Just Masculine ) ( Lit 1 ) ` Mul ` Scale 3 3 1 ` Add ` Lit 1
| ChangeNumber (Maybe G.Number) Exp
infixl 6 `Add`
infixl 6 `Sub`
infixl 7 `Mul`
showExp :: Exp -> String
showExp Unknown = "Unknown"
showExp (Lit n) = "Lit " ++ show n
showExp (Neg x) = "Neg (" ++ showExp x ++ ")"
showExp (Add x y) = "Add (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Mul x y) = "Mul (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Sub x y) = "Sub (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Frac x y) = "Frac (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Scale b o r) = "Scale " ++ show b ++ " " ++ show o ++ " (" ++ showExp r ++ ")"
showExp (ChangeCase mbC x) = "Case is " ++ show mbC ++ " in (" ++ showExp x ++ ")"
showExp (ChangeGender mbG x) = "Gender is " ++ show mbG ++ " in (" ++ showExp x ++ ")"
showExp (ChangeNumber mbN x) = "Number is " ++ show mbN ++ " in (" ++ showExp x ++ ")"
evalScale :: (Integral a) => a -> a -> a -> a
evalScale b o r = 10 ^ (r*b + o)
-- eval :: (Fractional a) => Exp -> Maybe a
-- eval (Lit x) = pure x
-- eval (Add x y) = (+) <$> eval x <*> eval y
-- eval (Mul x y) = (*) <$> eval x <*> eval y
-- eval (Sub x y) = subtract <$> eval x <*> eval y
-- eval (Neg x) = negate <$> eval x
eval ( Frac n d ) = ( / ) < $ > eval n < * > eval d
eval ( Scale b o r ) = evalScale ( fromInteger b ) ( fromInteger o ) < $ > eval r
-- eval (ChangeCase _ x) = eval x
-- eval (ChangeGender _ x) = eval x
-- eval (ChangeNumber _ x) = eval x
-- eval Unknown = Nothing
-------------------------------------------------------------------------------
-- Side
-------------------------------------------------------------------------------
| A side or direction , either ' L'eft or ' R'ight .
data Side = L -- ^ Left.
| R -- ^ Right.
deriving (Eq, Show)
| null | https://raw.githubusercontent.com/roelvandijk/numerals/b1e4121e0824ac0646a3230bd311818e159ec127/src/Text/Numeral/Exp.hs | haskell | # language CPP #
, eval
-----------------------------------------------------------------------------
Imports
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Expression type
-----------------------------------------------------------------------------
| An expression that represents the structure of a numeral.
^ An unknown value. This is used to signal that a value can
not be represented in the expression language.
^ A literal value.
^ Negation of an expression.
> "duodēvīgintī" = Lit 2 `Sub` (Lit 2 `Mul` Lit 10)
^ A fraction.
^ A step in a scale of large values.
^ A change of grammatical gender.
of a number word is not always constant. Specifically, in
masculine. This can result in the following number word:
eval :: (Fractional a) => Exp -> Maybe a
eval (Lit x) = pure x
eval (Add x y) = (+) <$> eval x <*> eval y
eval (Mul x y) = (*) <$> eval x <*> eval y
eval (Sub x y) = subtract <$> eval x <*> eval y
eval (Neg x) = negate <$> eval x
eval (ChangeCase _ x) = eval x
eval (ChangeGender _ x) = eval x
eval (ChangeNumber _ x) = eval x
eval Unknown = Nothing
-----------------------------------------------------------------------------
Side
-----------------------------------------------------------------------------
^ Left.
^ Right. |
module Text.Numeral.Exp
( Exp(..)
, showExp
, evalScale
, Side(L, R)
) where
#if !(MIN_VERSION_base(4,8,0))
import "base" Control.Applicative ( (<$>) )
#endif
import qualified "this" Text.Numeral.Grammar as G
data Exp
= Unknown
| Lit Integer
Example in English :
> " three " = Lit 3
| Neg Exp
Example in English :
> " minus two " = Neg ( Lit 2 )
| Add Exp Exp
^ Addition of two expressions .
Example in English :
> " fifteen " = Lit 5 ` Add ` Lit 10
| Mul Exp Exp
^ Multiplication of two expressions .
Example in English :
> " thirty " = Lit 3 ` Mul ` Lit 10
| Sub Exp Exp
^ One expression subtracted from another expression .
Example in Latin :
| Frac Exp Exp
Example in English :
> " two thirds " = ` Frac ` ( Lit 2 ) ( Lit 3 )
| Scale Integer Integer Exp
Should be interpreted as @10 ^ ( rank * base + offset)@.
Example in English :
> " quadrillion " = Scale 3 3 4
| ChangeCase (Maybe G.Case ) Exp
| ChangeGender (Maybe G.Gender) Exp
This is used in a language like Spanish where the inflection
Spanish , large number names always have the masculine
gender . So ' millón ' , ' ' and the like are all
10000001 = " un ( masculine ) millón una ( feminine ) "
Example in Spanish ( with the context being Feminine ):
> " " = ChangeGender ( Just Masculine ) ( Lit 1 ) ` Mul ` Scale 3 3 1 ` Add ` Lit 1
| ChangeNumber (Maybe G.Number) Exp
infixl 6 `Add`
infixl 6 `Sub`
infixl 7 `Mul`
showExp :: Exp -> String
showExp Unknown = "Unknown"
showExp (Lit n) = "Lit " ++ show n
showExp (Neg x) = "Neg (" ++ showExp x ++ ")"
showExp (Add x y) = "Add (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Mul x y) = "Mul (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Sub x y) = "Sub (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Frac x y) = "Frac (" ++ showExp x ++ ") (" ++ showExp y ++ ")"
showExp (Scale b o r) = "Scale " ++ show b ++ " " ++ show o ++ " (" ++ showExp r ++ ")"
showExp (ChangeCase mbC x) = "Case is " ++ show mbC ++ " in (" ++ showExp x ++ ")"
showExp (ChangeGender mbG x) = "Gender is " ++ show mbG ++ " in (" ++ showExp x ++ ")"
showExp (ChangeNumber mbN x) = "Number is " ++ show mbN ++ " in (" ++ showExp x ++ ")"
evalScale :: (Integral a) => a -> a -> a -> a
evalScale b o r = 10 ^ (r*b + o)
eval ( Frac n d ) = ( / ) < $ > eval n < * > eval d
eval ( Scale b o r ) = evalScale ( fromInteger b ) ( fromInteger o ) < $ > eval r
| A side or direction , either ' L'eft or ' R'ight .
deriving (Eq, Show)
|
46b6ded8ff638093808ceaea820df500076cdeabda29741d397426f634c181a3 | epgsql/epgsql | epgsql_codec_hstore.erl | %%% @doc
%%% Codec for `hstore' type.
%%%
%%% Hstore codec can take a jiffy-style object or map() as input.
%%% Output format can be changed by providing `return' option. See {@link return_format()}.
%%% Values of hstore can be `NULL'. NULL representation can be changed by providing
%%% `nulls' option, semantics is similar to {@link epgsql:connect_opts()} `nulls' option.
%%%
XXX : is not a part of postgresql builtin datatypes , it 's in contrib .
It should be enabled in postgresql by command ` CREATE EXTENSION hstore ' .
%%% <ul>
%%% <li>[]</li>
%%% <li>$PG$/contrib/hstore/</li>
%%% </ul>
%%% @end
Created : 14 Oct 2017 by < >
-module(epgsql_codec_hstore).
-behaviour(epgsql_codec).
-export([init/2, names/0, encode/3, decode/3, decode_text/3]).
-include("protocol.hrl").
-export_type([data/0, options/0, return_format/0]).
-type data() :: data_in() | data_out().
-type key_in() :: list() | binary() | atom() | integer() | float().
-type data_in() :: { [{key_in(), binary()}] } |
#{key_in() => binary() | atom()}.
jiffy
proplist
#{binary() => binary() | atom()}. % map
-type return_format() :: map | jiffy | proplist.
-type options() :: #{return => return_format(),
nulls => [atom(), ...]}.
-record(st,
{return :: return_format(),
nulls :: [atom(), ...]}).
-dialyzer([{nowarn_function, [encode/3]}, no_improper_lists]).
init(Opts0, _) ->
Opts = epgsql:to_map(Opts0),
#st{return = maps:get(return, Opts, jiffy),
nulls = maps:get(nulls, Opts, [null, undefined])}.
names() ->
[hstore].
encode({KV}, hstore, #st{nulls = Nulls}) when is_list(KV) ->
Size = length(KV),
encode_kv(KV, Size, Nulls);
encode(Map, hstore, #st{nulls = Nulls}) when is_map(Map) ->
Size = map_size(Map),
encode_kv(maps:to_list(Map), Size, Nulls).
decode(<<Size:?int32, Elements/binary>>, hstore, #st{return = Return, nulls = Nulls}) ->
KV = do_decode(Size, Elements, hd(Nulls)),
case Return of
jiffy ->
{KV};
map ->
maps:from_list(KV);
proplist ->
KV
end.
decode_text(V, _, _) -> V.
Internal
encode_kv(KV, Size, Nulls) ->
%% TODO: construct improper list when support for Erl 17 will be dropped
Body = [[encode_key(K), encode_value(V, Nulls)]
|| {K, V} <- KV],
[<<Size:?int32>> | Body].
encode_key(K) ->
encode_string(K).
encode_value(V, Nulls) ->
case lists:member(V, Nulls) of
true -> <<-1:?int32>>;
false -> encode_string(V)
end.
encode_string(Str) when is_binary(Str) ->
<<(byte_size(Str)):?int32, Str/binary>>;
encode_string(Str) when is_list(Str) ->
encode_string(list_to_binary(Str));
encode_string(Str) when is_atom(Str) ->
encode_string(atom_to_binary(Str, utf8));
encode_string(Str) when is_integer(Str) ->
encode_string(integer_to_binary(Str));
encode_string(Str) when is_float(Str) ->
encode_string(io_lib:format("~w", [Str])).
%% encode_string(erlang:float_to_binary(Str)).
do_decode(0, _, _) -> [];
do_decode(N, <<KeyLen:?int32, Key:KeyLen/binary, -1:?int32, Rest/binary>>, Null) ->
[{Key, Null} | do_decode(N - 1, Rest, Null)];
do_decode(N, <<KeyLen:?int32, Key:KeyLen/binary,
ValLen:?int32, Value:ValLen/binary, Rest/binary>>, Null) ->
[{Key, Value} | do_decode(N - 1, Rest, Null)].
| null | https://raw.githubusercontent.com/epgsql/epgsql/f811a09926892dbd1359afe44a9bfa8f6907b322/src/datatypes/epgsql_codec_hstore.erl | erlang | @doc
Codec for `hstore' type.
Hstore codec can take a jiffy-style object or map() as input.
Output format can be changed by providing `return' option. See {@link return_format()}.
Values of hstore can be `NULL'. NULL representation can be changed by providing
`nulls' option, semantics is similar to {@link epgsql:connect_opts()} `nulls' option.
<ul>
<li>[]</li>
<li>$PG$/contrib/hstore/</li>
</ul>
@end
map
TODO: construct improper list when support for Erl 17 will be dropped
encode_string(erlang:float_to_binary(Str)). | XXX : is not a part of postgresql builtin datatypes , it 's in contrib .
It should be enabled in postgresql by command ` CREATE EXTENSION hstore ' .
Created : 14 Oct 2017 by < >
-module(epgsql_codec_hstore).
-behaviour(epgsql_codec).
-export([init/2, names/0, encode/3, decode/3, decode_text/3]).
-include("protocol.hrl").
-export_type([data/0, options/0, return_format/0]).
-type data() :: data_in() | data_out().
-type key_in() :: list() | binary() | atom() | integer() | float().
-type data_in() :: { [{key_in(), binary()}] } |
#{key_in() => binary() | atom()}.
jiffy
proplist
-type return_format() :: map | jiffy | proplist.
-type options() :: #{return => return_format(),
nulls => [atom(), ...]}.
-record(st,
{return :: return_format(),
nulls :: [atom(), ...]}).
-dialyzer([{nowarn_function, [encode/3]}, no_improper_lists]).
init(Opts0, _) ->
Opts = epgsql:to_map(Opts0),
#st{return = maps:get(return, Opts, jiffy),
nulls = maps:get(nulls, Opts, [null, undefined])}.
names() ->
[hstore].
encode({KV}, hstore, #st{nulls = Nulls}) when is_list(KV) ->
Size = length(KV),
encode_kv(KV, Size, Nulls);
encode(Map, hstore, #st{nulls = Nulls}) when is_map(Map) ->
Size = map_size(Map),
encode_kv(maps:to_list(Map), Size, Nulls).
decode(<<Size:?int32, Elements/binary>>, hstore, #st{return = Return, nulls = Nulls}) ->
KV = do_decode(Size, Elements, hd(Nulls)),
case Return of
jiffy ->
{KV};
map ->
maps:from_list(KV);
proplist ->
KV
end.
decode_text(V, _, _) -> V.
Internal
encode_kv(KV, Size, Nulls) ->
Body = [[encode_key(K), encode_value(V, Nulls)]
|| {K, V} <- KV],
[<<Size:?int32>> | Body].
encode_key(K) ->
encode_string(K).
encode_value(V, Nulls) ->
case lists:member(V, Nulls) of
true -> <<-1:?int32>>;
false -> encode_string(V)
end.
encode_string(Str) when is_binary(Str) ->
<<(byte_size(Str)):?int32, Str/binary>>;
encode_string(Str) when is_list(Str) ->
encode_string(list_to_binary(Str));
encode_string(Str) when is_atom(Str) ->
encode_string(atom_to_binary(Str, utf8));
encode_string(Str) when is_integer(Str) ->
encode_string(integer_to_binary(Str));
encode_string(Str) when is_float(Str) ->
encode_string(io_lib:format("~w", [Str])).
do_decode(0, _, _) -> [];
do_decode(N, <<KeyLen:?int32, Key:KeyLen/binary, -1:?int32, Rest/binary>>, Null) ->
[{Key, Null} | do_decode(N - 1, Rest, Null)];
do_decode(N, <<KeyLen:?int32, Key:KeyLen/binary,
ValLen:?int32, Value:ValLen/binary, Rest/binary>>, Null) ->
[{Key, Value} | do_decode(N - 1, Rest, Null)].
|
4eff86413ac154d15be8264711f5053da07fe4389de99f18ccc8d79e5a563b7e | bobzhang/ocaml-book | test.mli | type 'a tree = Leaf of 'a | Node of 'a * 'a tree * 'a tree
module Show_tree :
functor (M_a : Deriving_Show.Show) ->
sig
type a = M_a.a tree
val format : Format.formatter -> a -> unit
val format_list : Format.formatter -> a list -> unit
val show : a -> string
val show_list : a list -> string
end
module Eq_tree :
functor (M_a : Deriving_Eq.Eq) ->
sig type a = M_a.a tree val eq : a -> a -> bool end
module Typeable_tree :
functor (M_a : Deriving_Typeable.Typeable) ->
sig
type a = M_a.a tree
val type_rep : Deriving_Typeable.TypeRep.t Lazy.t
val has_type : Deriving_Typeable.dynamic -> bool
val cast : Deriving_Typeable.dynamic -> a option
val throwing_cast : Deriving_Typeable.dynamic -> a
val make_dynamic : a -> Deriving_Typeable.dynamic
val mk : a -> Deriving_Typeable.dynamic
end
module rec Functor_tree :
sig type 'a f = 'a tree val map : ('a -> 'b) -> 'a tree -> 'b tree end
| null | https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/library/code/deriving/_build/test.mli | ocaml | type 'a tree = Leaf of 'a | Node of 'a * 'a tree * 'a tree
module Show_tree :
functor (M_a : Deriving_Show.Show) ->
sig
type a = M_a.a tree
val format : Format.formatter -> a -> unit
val format_list : Format.formatter -> a list -> unit
val show : a -> string
val show_list : a list -> string
end
module Eq_tree :
functor (M_a : Deriving_Eq.Eq) ->
sig type a = M_a.a tree val eq : a -> a -> bool end
module Typeable_tree :
functor (M_a : Deriving_Typeable.Typeable) ->
sig
type a = M_a.a tree
val type_rep : Deriving_Typeable.TypeRep.t Lazy.t
val has_type : Deriving_Typeable.dynamic -> bool
val cast : Deriving_Typeable.dynamic -> a option
val throwing_cast : Deriving_Typeable.dynamic -> a
val make_dynamic : a -> Deriving_Typeable.dynamic
val mk : a -> Deriving_Typeable.dynamic
end
module rec Functor_tree :
sig type 'a f = 'a tree val map : ('a -> 'b) -> 'a tree -> 'b tree end
| |
64603549b1646363f81809578b4e2e0e4fbdefa9e0aaee22b2b2072d593b3609 | walkable-server/realworld-fulcro | account.cljs | (ns conduit.ui.account
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[conduit.handler.mutations :as mutations]
[conduit.session :as session]
[com.fulcrologic.fulcro.dom :as dom]))
(defsc LoginForm [this {:ui/keys [email password current-user] :as props}]
{:query [:ui/email :ui/password [::uism/asm-id '_]
{:ui/current-user (comp/get-query session/CurrentUser)}]
:ident (fn [] [:component/id :login])
:route-segment ["login"]
:initial-state (fn [_] {:ui/email "" :ui/password ""
:ui/current-user (comp/get-initial-state session/CurrentUser)})}
(let [current-state (uism/get-active-state this ::session/sessions)
busy? (= :state/checking-credentials current-state)
bad-credentials? (= :state/bad-credentials current-state)
error? (= :state/server-failed current-state)
{:user/keys [name valid?]} current-user]
(dom/div :.auth-page
(dom/div :.container.page
(dom/div :.row
(if valid?
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/p :.text-xs-center
"You have logged in as " (or name (:user/email current-user))))
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/h1 :.text-xs-center
"Log in")
(dom/p :.text-xs-center
(dom/a {:href "/sign-up"}
"Don't have an account?"))
(when bad-credentials?
(dom/ul :.error-messages
(dom/li "Incorrect username or password!")))
(when error?
(dom/ul :.error-messages
(dom/li "Server is down")))
(dom/form {:classes [(when bad-credentials? "error")]
:onSubmit
#(do (.preventDefault %)
(uism/trigger! this
::session/sessions :event/login
{:user/email email
:user/password password}))}
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:disabled busy?
:onChange #(m/set-string! this :ui/email :event %)
:placeholder "Email"
:type "text"
:value (or email "")}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:type "password"
:disabled busy?
:onChange #(m/set-string! this :ui/password :event %)
:placeholder "Password"
:value (or password "")}))
(dom/button :.btn.btn-lg.btn-primary.pull-xs-right
{:classes [(when busy? "disabled")]
:type "submit" :value "submit"}
"Log in")))))))))
(defsc SignUpForm [this {:ui/keys [name email password current-user]}]
{:query [:ui/name :ui/email :ui/password [::uism/asm-id '_]
{:ui/current-user (comp/get-query session/CurrentUser)}]
:ident (fn [] [:component/id :sign-up])
:route-segment ["sign-up"]
:initial-state (fn [_] {:ui/name ""
:ui/email ""
:ui/password ""
:ui/current-user (comp/get-initial-state session/CurrentUser)})}
(let [current-state (uism/get-active-state this ::session/sessions)
busy? (= :state/checking-credentials current-state)
email-taken? (= :state/email-taken current-state)
error? (= :state/server-failed current-state)
{:user/keys [valid?]} current-user]
(dom/div :.auth-page
(dom/div :.container.page
(dom/div :.row
(if valid?
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/p :.text-xs-center
"You have logged in as " (or (:user/name current-user) (:user/email current-user))))
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/h1 :.text-xs-center
"Sign up")
(dom/p :.text-xs-center
(dom/a {:href "/login"}
"Don't have an account?"))
(when email-taken?
(dom/ul :.error-messages
(dom/li "Email is taken")))
(when error?
(dom/ul :.error-messages
(dom/li "Server is down")))
(dom/form {:classes [(when email-taken? "error")]
:onSubmit
#(do (.preventDefault %)
(uism/trigger! this
::session/sessions :event/sign-up
{:user/name name
:user/email email
:user/password password}))}
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:disabled busy?
:onChange #(m/set-string! this :ui/name :event %)
:placeholder "Name"
:type "text"
:value (or name "")}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:disabled busy?
:onChange #(m/set-string! this :ui/email :event %)
:placeholder "Email"
:type "text"
:value (or email "")}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:type "password"
:disabled busy?
:onChange #(m/set-string! this :ui/password :event %)
:placeholder "Password"
:value (or password "")}))
(dom/button :.btn.btn-lg.btn-primary.pull-xs-right
{:classes [(when busy? "disabled")]
:type "submit" :value "submit"}
"Sign up")))))))))
(defsc SettingsForm
[this {:user/keys [image name bio email password] :as props}]
{:query [:user/id :user/image :user/name :user/bio :user/email :user/password
fs/form-config-join]
:initial-state {:user/id :nobody}
:ident (fn [_] [:session/session :current-user])
:form-fields #{:user/image :user/name :user/bio :user/email :user/password}}
(dom/div :.settings-page
(dom/div :.container.page
(dom/div :.row
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/h1 :.text-xs-center
"Your Settings")
(dom/form {:onSubmit
#(do (.preventDefault %)
(comp/transact! this [(mutations/submit-settings (fs/dirty-fields props false))]))}
(dom/fieldset
(dom/fieldset :.form-group
(dom/input :.form-control
{:placeholder "URL of profile picture",
:type "text"
:value (or image "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/image})])
:onChange #(m/set-string! this :user/image :event %)}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:placeholder "Your Name",
:type "text"
:value (or name "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/name})])
:onChange #(m/set-string! this :user/name :event %)}))
(dom/fieldset :.form-group
(dom/textarea :.form-control.form-control-lg
{:rows "8",
:placeholder "Short bio about you"
:value (or bio "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/bio})])
:onChange #(m/set-string! this :user/bio :event %)}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:placeholder "Email",
:type "text"
:value (or email "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/email})])
:onChange #(m/set-string! this :user/email :event %)}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:placeholder "Password",
:type "password"
:value (or password "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/password})])
:onChange #(m/set-string! this :user/password :event %)}))
(dom/button :.btn.btn-lg.btn-primary.pull-xs-right
{:type "submit" :value "submit"}
"Update Settings"))))))))
(def ui-settings-form (comp/factory SettingsForm))
(defmutation use-settings-as-form [_]
(action [{:keys [app state] :as env}]
(swap! state #(-> %
(assoc-in [:session/session :current-user :user/password] "")
(fs/add-form-config* SettingsForm [:session/session :current-user])
(fs/mark-complete* [:session/session :current-user])))
(dr/target-ready! app [:component/id :settings])))
(defsc Settings [this {:keys [settings]}]
{:query [{:settings (comp/get-query SettingsForm)}]
:initial-state (fn [_] {:settings (comp/get-initial-state SettingsForm {})})
:route-segment ["settings"]
:will-enter (fn [app _route-params]
(dr/route-deferred [:component/id :settings]
#(comp/transact! app [(use-settings-as-form {})])))
:ident (fn [] [:component/id :settings])}
(ui-settings-form settings))
| null | https://raw.githubusercontent.com/walkable-server/realworld-fulcro/91c73e3a27621b528906d12bc22971caa9ea8d13/src/conduit/ui/account.cljs | clojure | (ns conduit.ui.account
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[conduit.handler.mutations :as mutations]
[conduit.session :as session]
[com.fulcrologic.fulcro.dom :as dom]))
(defsc LoginForm [this {:ui/keys [email password current-user] :as props}]
{:query [:ui/email :ui/password [::uism/asm-id '_]
{:ui/current-user (comp/get-query session/CurrentUser)}]
:ident (fn [] [:component/id :login])
:route-segment ["login"]
:initial-state (fn [_] {:ui/email "" :ui/password ""
:ui/current-user (comp/get-initial-state session/CurrentUser)})}
(let [current-state (uism/get-active-state this ::session/sessions)
busy? (= :state/checking-credentials current-state)
bad-credentials? (= :state/bad-credentials current-state)
error? (= :state/server-failed current-state)
{:user/keys [name valid?]} current-user]
(dom/div :.auth-page
(dom/div :.container.page
(dom/div :.row
(if valid?
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/p :.text-xs-center
"You have logged in as " (or name (:user/email current-user))))
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/h1 :.text-xs-center
"Log in")
(dom/p :.text-xs-center
(dom/a {:href "/sign-up"}
"Don't have an account?"))
(when bad-credentials?
(dom/ul :.error-messages
(dom/li "Incorrect username or password!")))
(when error?
(dom/ul :.error-messages
(dom/li "Server is down")))
(dom/form {:classes [(when bad-credentials? "error")]
:onSubmit
#(do (.preventDefault %)
(uism/trigger! this
::session/sessions :event/login
{:user/email email
:user/password password}))}
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:disabled busy?
:onChange #(m/set-string! this :ui/email :event %)
:placeholder "Email"
:type "text"
:value (or email "")}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:type "password"
:disabled busy?
:onChange #(m/set-string! this :ui/password :event %)
:placeholder "Password"
:value (or password "")}))
(dom/button :.btn.btn-lg.btn-primary.pull-xs-right
{:classes [(when busy? "disabled")]
:type "submit" :value "submit"}
"Log in")))))))))
(defsc SignUpForm [this {:ui/keys [name email password current-user]}]
{:query [:ui/name :ui/email :ui/password [::uism/asm-id '_]
{:ui/current-user (comp/get-query session/CurrentUser)}]
:ident (fn [] [:component/id :sign-up])
:route-segment ["sign-up"]
:initial-state (fn [_] {:ui/name ""
:ui/email ""
:ui/password ""
:ui/current-user (comp/get-initial-state session/CurrentUser)})}
(let [current-state (uism/get-active-state this ::session/sessions)
busy? (= :state/checking-credentials current-state)
email-taken? (= :state/email-taken current-state)
error? (= :state/server-failed current-state)
{:user/keys [valid?]} current-user]
(dom/div :.auth-page
(dom/div :.container.page
(dom/div :.row
(if valid?
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/p :.text-xs-center
"You have logged in as " (or (:user/name current-user) (:user/email current-user))))
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/h1 :.text-xs-center
"Sign up")
(dom/p :.text-xs-center
(dom/a {:href "/login"}
"Don't have an account?"))
(when email-taken?
(dom/ul :.error-messages
(dom/li "Email is taken")))
(when error?
(dom/ul :.error-messages
(dom/li "Server is down")))
(dom/form {:classes [(when email-taken? "error")]
:onSubmit
#(do (.preventDefault %)
(uism/trigger! this
::session/sessions :event/sign-up
{:user/name name
:user/email email
:user/password password}))}
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:disabled busy?
:onChange #(m/set-string! this :ui/name :event %)
:placeholder "Name"
:type "text"
:value (or name "")}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:disabled busy?
:onChange #(m/set-string! this :ui/email :event %)
:placeholder "Email"
:type "text"
:value (or email "")}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:type "password"
:disabled busy?
:onChange #(m/set-string! this :ui/password :event %)
:placeholder "Password"
:value (or password "")}))
(dom/button :.btn.btn-lg.btn-primary.pull-xs-right
{:classes [(when busy? "disabled")]
:type "submit" :value "submit"}
"Sign up")))))))))
(defsc SettingsForm
[this {:user/keys [image name bio email password] :as props}]
{:query [:user/id :user/image :user/name :user/bio :user/email :user/password
fs/form-config-join]
:initial-state {:user/id :nobody}
:ident (fn [_] [:session/session :current-user])
:form-fields #{:user/image :user/name :user/bio :user/email :user/password}}
(dom/div :.settings-page
(dom/div :.container.page
(dom/div :.row
(dom/div :.col-md-6.offset-md-3.col-xs-12
(dom/h1 :.text-xs-center
"Your Settings")
(dom/form {:onSubmit
#(do (.preventDefault %)
(comp/transact! this [(mutations/submit-settings (fs/dirty-fields props false))]))}
(dom/fieldset
(dom/fieldset :.form-group
(dom/input :.form-control
{:placeholder "URL of profile picture",
:type "text"
:value (or image "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/image})])
:onChange #(m/set-string! this :user/image :event %)}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:placeholder "Your Name",
:type "text"
:value (or name "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/name})])
:onChange #(m/set-string! this :user/name :event %)}))
(dom/fieldset :.form-group
(dom/textarea :.form-control.form-control-lg
{:rows "8",
:placeholder "Short bio about you"
:value (or bio "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/bio})])
:onChange #(m/set-string! this :user/bio :event %)}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:placeholder "Email",
:type "text"
:value (or email "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/email})])
:onChange #(m/set-string! this :user/email :event %)}))
(dom/fieldset :.form-group
(dom/input :.form-control.form-control-lg
{:placeholder "Password",
:type "password"
:value (or password "")
:onBlur #(comp/transact! this
[(fs/mark-complete! {:field :user/password})])
:onChange #(m/set-string! this :user/password :event %)}))
(dom/button :.btn.btn-lg.btn-primary.pull-xs-right
{:type "submit" :value "submit"}
"Update Settings"))))))))
(def ui-settings-form (comp/factory SettingsForm))
(defmutation use-settings-as-form [_]
(action [{:keys [app state] :as env}]
(swap! state #(-> %
(assoc-in [:session/session :current-user :user/password] "")
(fs/add-form-config* SettingsForm [:session/session :current-user])
(fs/mark-complete* [:session/session :current-user])))
(dr/target-ready! app [:component/id :settings])))
(defsc Settings [this {:keys [settings]}]
{:query [{:settings (comp/get-query SettingsForm)}]
:initial-state (fn [_] {:settings (comp/get-initial-state SettingsForm {})})
:route-segment ["settings"]
:will-enter (fn [app _route-params]
(dr/route-deferred [:component/id :settings]
#(comp/transact! app [(use-settings-as-form {})])))
:ident (fn [] [:component/id :settings])}
(ui-settings-form settings))
| |
88d994b4fa423200de68900db1e2d5ef8ffa459deb7df8e9ce37fb1bb476c69f | waymonad/waymonad | Keyboard.hs |
waymonad A wayland compositor in the spirit of xmonad
Copyright ( C ) 2017
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
Reach us at
waymonad A wayland compositor in the spirit of xmonad
Copyright (C) 2017 Markus Ongyerth
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Reach us at
-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE LambdaCase #
module Waymonad.Input.Keyboard
where
import Control.Monad.IO.Class (liftIO)
import Data.Bits ((.&.), complement)
import Data.IORef (readIORef, modifyIORef)
import Data.Maybe (isJust)
import Data.Word (Word32)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable (Storable(..))
import Graphics.Wayland.Signal (removeListener)
import Graphics.Wayland.WlRoots.Backend.Session (changeVT)
import Graphics.Wayland.WlRoots.Backend (Backend, getSession)
import Graphics.Wayland.WlRoots.Input (InputDevice, getCleanDeviceName)
import Graphics.Wayland.WlRoots.Input.Keyboard
( WlrKeyboard
, KeyboardSignals (..)
, getKeySignals
, getKeyDataPtr
, EventKey (..)
, KeyState (..)
, setKeymap
, getKeystate
, getKeymap
, WlrModifier
, getModifiers
, getModifierPtr
, fieldToModifiers
, modifierInField
)
import Graphics.Wayland.WlRoots.Seat
( seatSetKeyboard
, keyboardNotifyKey
, seatSetKeyboard
, keyboardNotifyModifiers
)
import Foreign.StablePtr
( newStablePtr
, castStablePtrToPtr
, freeStablePtr
, castPtrToStablePtr
, deRefStablePtr
)
import Control.Monad (forM, when, unless)
import Waymonad
( withSeat
, WayLoggers (..)
, getState
, getSeat
)
import Waymonad.Types
( Compositor (compBackend)
, WayBindingState (wayCompositor, wayXKBMap)
, Way (..)
)
import Waymonad.Types.Core (WayKeyState (..), Seat(seatKeymap, seatKeyboards, seatRoots))
import Waymonad.Utility.Signal (setSignalHandler)
import Waymonad.Utility.Log (logPutStr, LogPriority (..))
import {-# SOURCE #-} Waymonad.Protocols.InputInhibit (getInhibitingClient)
import Text.XkbCommon.Context
import Text.XkbCommon.KeyboardState
import Text.XkbCommon.KeycodeList
import Text.XkbCommon.Keymap
import Text.XkbCommon.Keysym
import Text.XkbCommon.KeysymPatterns
import Text.XkbCommon.Types
import qualified Data.Set as S
data Keyboard = Keyboard
{ keyboardDevice :: Ptr WlrKeyboard
, keyboardIDevice :: Ptr InputDevice
} deriving (Eq, Show, Ord)
tryRunKeybind :: WayKeyState -> Way vs ws Bool
tryRunKeybind keyState = (fmap seatKeymap <$> getSeat) >>= \case
Just bindRef -> liftIO $ do
keybindings <- readIORef bindRef
keybindings keyState
Nothing -> pure False
keyStateToDirection :: KeyState -> Direction
keyStateToDirection KeyReleased = keyUp
keyStateToDirection KeyPressed = keyDown
switchVT :: Ptr Backend -> Word -> IO ()
switchVT backend vt = do
mSession <- getSession backend
case mSession of
Nothing -> pure ()
Just s -> changeVT s vt
handleKeyPress :: Word32 -> Keysym -> Way vs a Bool
handleKeyPress modifiers sym@(Keysym key) = do
logPutStr loggerKeybinds Trace $ "Checking for keybind: " ++ (show $ fieldToModifiers modifiers) ++ ":" ++ keysymName sym
backend <- compBackend . wayCompositor <$> getState
case sym of
Would be cooler if this was n't a listing of VTs ( probably TH )
Keysym_XF86Switch_VT_1 -> liftIO (switchVT backend 1 ) >> pure True
Keysym_XF86Switch_VT_2 -> liftIO (switchVT backend 2 ) >> pure True
Keysym_XF86Switch_VT_3 -> liftIO (switchVT backend 3 ) >> pure True
Keysym_XF86Switch_VT_4 -> liftIO (switchVT backend 4 ) >> pure True
Keysym_XF86Switch_VT_5 -> liftIO (switchVT backend 5 ) >> pure True
Keysym_XF86Switch_VT_6 -> liftIO (switchVT backend 6 ) >> pure True
Keysym_XF86Switch_VT_7 -> liftIO (switchVT backend 7 ) >> pure True
Keysym_XF86Switch_VT_8 -> liftIO (switchVT backend 8 ) >> pure True
Keysym_XF86Switch_VT_9 -> liftIO (switchVT backend 9 ) >> pure True
Keysym_XF86Switch_VT_10 -> liftIO (switchVT backend 10) >> pure True
Keysym_XF86Switch_VT_11 -> liftIO (switchVT backend 11) >> pure True
Keysym_XF86Switch_VT_12 -> liftIO (switchVT backend 12) >> pure True
_ -> tryRunKeybind $ WayKeyState (fromIntegral modifiers) (fromIntegral key)
tellClient :: Seat -> Keyboard -> EventKey -> IO ()
tellClient seat keyboard event = do
seatSetKeyboard (seatRoots seat) $ keyboardIDevice keyboard
keyboardNotifyKey (seatRoots seat) (timeSec event) (keyCode event) (state event)
handleKeySimple :: Keyboard -> CKeycode -> Way vs a Bool
handleKeySimple keyboard keycode = do
keystate <- liftIO . getKeystate $ keyboardDevice keyboard
keymap <- liftIO . getKeymap $ keyboardDevice keyboard
modifiers <- liftIO $ getModifiers $ keyboardDevice keyboard
layoutL <- liftIO $ keyGetLayoutI keystate keycode
syms <- liftIO $ keymapSymsByLevelI keymap keycode layoutL (CLevelIndex 0)
handled <- forM syms $
handleKeyPress modifiers
pure $ or handled
isModifierPressed :: Ptr WlrKeyboard -> WlrModifier -> IO Bool
isModifierPressed ptr modi = do
modifiers <- getModifiers ptr
pure $ modifierInField modi modifiers
handleKeyXkb :: Keyboard -> CKeycode -> Way vs a Bool
handleKeyXkb keyboard keycode = do
keystate <- liftIO . getKeystate $ keyboardDevice keyboard
modifiers <- liftIO $ getModifiers $ keyboardDevice keyboard
consumed <- liftIO $ keyGetConsumedMods2 keystate keycode
let usedMods = modifiers .&. complement (fromIntegral consumed)
syms <- liftIO $ getStateSymsI keystate keycode
handled <- forM syms $
handleKeyPress usedMods
pure $ or handled
-- This handler is called for every key pressed on a keyboard.
-- We dispatch keybinds from this handler.
--
-- To prevent weirdness that X had with keyboard layouts, this uses an approach
with two checks .
1 ) Use xkb processed modifiers and keys .
-- If [Win]+[Shift]+2 is pressed this will match:
-- [Win]+@ on us layout
[ Win]+ " on german layout
-- Though other keys are generated here, e.g. the keys used for switching
-- TTYs are bound as "Keysym_XF86Switch_VT_#" not [Alt]+[Shift]+[F#].
2 ) If the xkb version did not match any keybinds , match without xkb
-- processing. With the same keys pressed as above this will match:
-- [Win]+[Shift]+2 on all layouts and configurations.
-- This allows to bind this for managing workspaces, and switch keyboard
-- layouts without interfering with keybinds.
-- If neither approach matches a keybind, the key-press is forwarded to the
-- focused client.
handleKeyEvent :: Keyboard -> Seat -> Ptr EventKey -> Way vs ws ()
handleKeyEvent keyboard seat ptr = withSeat (Just seat) $ do
event <- liftIO $ peek ptr
let keycode = fromEvdev . fromIntegral . keyCode $ event
inhib <- isJust <$> getInhibitingClient
handled <- if inhib
then pure False
else case state event of
-- We currently don't do anything special for releases
KeyReleased -> pure False
KeyPressed -> do
handled <- handleKeyXkb keyboard keycode
if handled
then pure handled
else handleKeySimple keyboard keycode
liftIO . unless handled $ tellClient seat keyboard event
handleModifiers :: Keyboard -> Seat -> Ptr a -> Way vs ws ()
handleModifiers keyboard seat _ = liftIO $ do
seatSetKeyboard (seatRoots seat) $ keyboardIDevice keyboard
keyboardNotifyModifiers (seatRoots seat) (getModifierPtr $ keyboardDevice keyboard)
handleKeyboardAdd :: Seat -> Ptr InputDevice -> Ptr WlrKeyboard -> Way vs a ()
handleKeyboardAdd seat dev ptr = do
liftIO $ modifyIORef (seatKeyboards seat) (S.insert ptr)
let signals = getKeySignals ptr
rmlvoMap <- wayXKBMap <$> getState
liftIO $ do
name <- getCleanDeviceName dev
(Just cxt) <- newContext defaultFlags
(Just keymap) <- newKeymapFromNamesI cxt $ rmlvoMap name
setKeymap ptr keymap
let keyboard = Keyboard ptr dev
kh <- setSignalHandler
(keySignalKey signals)
(handleKeyEvent keyboard seat)
mh <- setSignalHandler
(keySignalModifiers signals)
(handleModifiers keyboard seat)
liftIO $ do
sptr <- newStablePtr (kh, mh)
poke (getKeyDataPtr ptr) (castStablePtrToPtr sptr)
detachKeyboard :: Seat -> Ptr WlrKeyboard -> IO ()
detachKeyboard seat ptr = do
handleKeyboardRemove seat ptr
poke (getKeyDataPtr ptr) nullPtr
handleKeyboardRemove :: Seat -> Ptr WlrKeyboard -> IO ()
handleKeyboardRemove seat ptr = do
dptr <- peek (getKeyDataPtr ptr)
liftIO $ modifyIORef (seatKeyboards seat) (S.delete ptr)
when (dptr /= nullPtr) (do
let sptr = castPtrToStablePtr dptr
(kh, mh) <- deRefStablePtr sptr
removeListener kh
removeListener mh
freeStablePtr sptr
)
| null | https://raw.githubusercontent.com/waymonad/waymonad/18ab493710dd54c330fb4d122ed35bc3a59585df/src/Waymonad/Input/Keyboard.hs | haskell | # LANGUAGE OverloadedStrings #
# SOURCE #
This handler is called for every key pressed on a keyboard.
We dispatch keybinds from this handler.
To prevent weirdness that X had with keyboard layouts, this uses an approach
If [Win]+[Shift]+2 is pressed this will match:
[Win]+@ on us layout
Though other keys are generated here, e.g. the keys used for switching
TTYs are bound as "Keysym_XF86Switch_VT_#" not [Alt]+[Shift]+[F#].
processing. With the same keys pressed as above this will match:
[Win]+[Shift]+2 on all layouts and configurations.
This allows to bind this for managing workspaces, and switch keyboard
layouts without interfering with keybinds.
If neither approach matches a keybind, the key-press is forwarded to the
focused client.
We currently don't do anything special for releases |
waymonad A wayland compositor in the spirit of xmonad
Copyright ( C ) 2017
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
Reach us at
waymonad A wayland compositor in the spirit of xmonad
Copyright (C) 2017 Markus Ongyerth
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Reach us at
-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE LambdaCase #
module Waymonad.Input.Keyboard
where
import Control.Monad.IO.Class (liftIO)
import Data.Bits ((.&.), complement)
import Data.IORef (readIORef, modifyIORef)
import Data.Maybe (isJust)
import Data.Word (Word32)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable (Storable(..))
import Graphics.Wayland.Signal (removeListener)
import Graphics.Wayland.WlRoots.Backend.Session (changeVT)
import Graphics.Wayland.WlRoots.Backend (Backend, getSession)
import Graphics.Wayland.WlRoots.Input (InputDevice, getCleanDeviceName)
import Graphics.Wayland.WlRoots.Input.Keyboard
( WlrKeyboard
, KeyboardSignals (..)
, getKeySignals
, getKeyDataPtr
, EventKey (..)
, KeyState (..)
, setKeymap
, getKeystate
, getKeymap
, WlrModifier
, getModifiers
, getModifierPtr
, fieldToModifiers
, modifierInField
)
import Graphics.Wayland.WlRoots.Seat
( seatSetKeyboard
, keyboardNotifyKey
, seatSetKeyboard
, keyboardNotifyModifiers
)
import Foreign.StablePtr
( newStablePtr
, castStablePtrToPtr
, freeStablePtr
, castPtrToStablePtr
, deRefStablePtr
)
import Control.Monad (forM, when, unless)
import Waymonad
( withSeat
, WayLoggers (..)
, getState
, getSeat
)
import Waymonad.Types
( Compositor (compBackend)
, WayBindingState (wayCompositor, wayXKBMap)
, Way (..)
)
import Waymonad.Types.Core (WayKeyState (..), Seat(seatKeymap, seatKeyboards, seatRoots))
import Waymonad.Utility.Signal (setSignalHandler)
import Waymonad.Utility.Log (logPutStr, LogPriority (..))
import Text.XkbCommon.Context
import Text.XkbCommon.KeyboardState
import Text.XkbCommon.KeycodeList
import Text.XkbCommon.Keymap
import Text.XkbCommon.Keysym
import Text.XkbCommon.KeysymPatterns
import Text.XkbCommon.Types
import qualified Data.Set as S
data Keyboard = Keyboard
{ keyboardDevice :: Ptr WlrKeyboard
, keyboardIDevice :: Ptr InputDevice
} deriving (Eq, Show, Ord)
tryRunKeybind :: WayKeyState -> Way vs ws Bool
tryRunKeybind keyState = (fmap seatKeymap <$> getSeat) >>= \case
Just bindRef -> liftIO $ do
keybindings <- readIORef bindRef
keybindings keyState
Nothing -> pure False
keyStateToDirection :: KeyState -> Direction
keyStateToDirection KeyReleased = keyUp
keyStateToDirection KeyPressed = keyDown
switchVT :: Ptr Backend -> Word -> IO ()
switchVT backend vt = do
mSession <- getSession backend
case mSession of
Nothing -> pure ()
Just s -> changeVT s vt
handleKeyPress :: Word32 -> Keysym -> Way vs a Bool
handleKeyPress modifiers sym@(Keysym key) = do
logPutStr loggerKeybinds Trace $ "Checking for keybind: " ++ (show $ fieldToModifiers modifiers) ++ ":" ++ keysymName sym
backend <- compBackend . wayCompositor <$> getState
case sym of
Would be cooler if this was n't a listing of VTs ( probably TH )
Keysym_XF86Switch_VT_1 -> liftIO (switchVT backend 1 ) >> pure True
Keysym_XF86Switch_VT_2 -> liftIO (switchVT backend 2 ) >> pure True
Keysym_XF86Switch_VT_3 -> liftIO (switchVT backend 3 ) >> pure True
Keysym_XF86Switch_VT_4 -> liftIO (switchVT backend 4 ) >> pure True
Keysym_XF86Switch_VT_5 -> liftIO (switchVT backend 5 ) >> pure True
Keysym_XF86Switch_VT_6 -> liftIO (switchVT backend 6 ) >> pure True
Keysym_XF86Switch_VT_7 -> liftIO (switchVT backend 7 ) >> pure True
Keysym_XF86Switch_VT_8 -> liftIO (switchVT backend 8 ) >> pure True
Keysym_XF86Switch_VT_9 -> liftIO (switchVT backend 9 ) >> pure True
Keysym_XF86Switch_VT_10 -> liftIO (switchVT backend 10) >> pure True
Keysym_XF86Switch_VT_11 -> liftIO (switchVT backend 11) >> pure True
Keysym_XF86Switch_VT_12 -> liftIO (switchVT backend 12) >> pure True
_ -> tryRunKeybind $ WayKeyState (fromIntegral modifiers) (fromIntegral key)
tellClient :: Seat -> Keyboard -> EventKey -> IO ()
tellClient seat keyboard event = do
seatSetKeyboard (seatRoots seat) $ keyboardIDevice keyboard
keyboardNotifyKey (seatRoots seat) (timeSec event) (keyCode event) (state event)
handleKeySimple :: Keyboard -> CKeycode -> Way vs a Bool
handleKeySimple keyboard keycode = do
keystate <- liftIO . getKeystate $ keyboardDevice keyboard
keymap <- liftIO . getKeymap $ keyboardDevice keyboard
modifiers <- liftIO $ getModifiers $ keyboardDevice keyboard
layoutL <- liftIO $ keyGetLayoutI keystate keycode
syms <- liftIO $ keymapSymsByLevelI keymap keycode layoutL (CLevelIndex 0)
handled <- forM syms $
handleKeyPress modifiers
pure $ or handled
isModifierPressed :: Ptr WlrKeyboard -> WlrModifier -> IO Bool
isModifierPressed ptr modi = do
modifiers <- getModifiers ptr
pure $ modifierInField modi modifiers
handleKeyXkb :: Keyboard -> CKeycode -> Way vs a Bool
handleKeyXkb keyboard keycode = do
keystate <- liftIO . getKeystate $ keyboardDevice keyboard
modifiers <- liftIO $ getModifiers $ keyboardDevice keyboard
consumed <- liftIO $ keyGetConsumedMods2 keystate keycode
let usedMods = modifiers .&. complement (fromIntegral consumed)
syms <- liftIO $ getStateSymsI keystate keycode
handled <- forM syms $
handleKeyPress usedMods
pure $ or handled
with two checks .
1 ) Use xkb processed modifiers and keys .
[ Win]+ " on german layout
2 ) If the xkb version did not match any keybinds , match without xkb
handleKeyEvent :: Keyboard -> Seat -> Ptr EventKey -> Way vs ws ()
handleKeyEvent keyboard seat ptr = withSeat (Just seat) $ do
event <- liftIO $ peek ptr
let keycode = fromEvdev . fromIntegral . keyCode $ event
inhib <- isJust <$> getInhibitingClient
handled <- if inhib
then pure False
else case state event of
KeyReleased -> pure False
KeyPressed -> do
handled <- handleKeyXkb keyboard keycode
if handled
then pure handled
else handleKeySimple keyboard keycode
liftIO . unless handled $ tellClient seat keyboard event
handleModifiers :: Keyboard -> Seat -> Ptr a -> Way vs ws ()
handleModifiers keyboard seat _ = liftIO $ do
seatSetKeyboard (seatRoots seat) $ keyboardIDevice keyboard
keyboardNotifyModifiers (seatRoots seat) (getModifierPtr $ keyboardDevice keyboard)
handleKeyboardAdd :: Seat -> Ptr InputDevice -> Ptr WlrKeyboard -> Way vs a ()
handleKeyboardAdd seat dev ptr = do
liftIO $ modifyIORef (seatKeyboards seat) (S.insert ptr)
let signals = getKeySignals ptr
rmlvoMap <- wayXKBMap <$> getState
liftIO $ do
name <- getCleanDeviceName dev
(Just cxt) <- newContext defaultFlags
(Just keymap) <- newKeymapFromNamesI cxt $ rmlvoMap name
setKeymap ptr keymap
let keyboard = Keyboard ptr dev
kh <- setSignalHandler
(keySignalKey signals)
(handleKeyEvent keyboard seat)
mh <- setSignalHandler
(keySignalModifiers signals)
(handleModifiers keyboard seat)
liftIO $ do
sptr <- newStablePtr (kh, mh)
poke (getKeyDataPtr ptr) (castStablePtrToPtr sptr)
detachKeyboard :: Seat -> Ptr WlrKeyboard -> IO ()
detachKeyboard seat ptr = do
handleKeyboardRemove seat ptr
poke (getKeyDataPtr ptr) nullPtr
handleKeyboardRemove :: Seat -> Ptr WlrKeyboard -> IO ()
handleKeyboardRemove seat ptr = do
dptr <- peek (getKeyDataPtr ptr)
liftIO $ modifyIORef (seatKeyboards seat) (S.delete ptr)
when (dptr /= nullPtr) (do
let sptr = castPtrToStablePtr dptr
(kh, mh) <- deRefStablePtr sptr
removeListener kh
removeListener mh
freeStablePtr sptr
)
|
5036f959fc9b591721762c014ac73ab498b45e831be494a06f767338a6334e47 | bevuta/pepa | tasks.clj | (ns pepa.tasks
(:require [pepa.tasks.schema :as schema])
(:gen-class))
(def tasks
{"schema" schema/run})
(defn -main [task & args]
(if-let [run-task (get tasks task)]
(run-task args)
(binding [*out* *err*]
(print "Invalid pepa task")
(when (seq (str task))
(print (str " '" task "'")))
(newline)
(newline)
(println "Available tasks:")
(doseq [task (sort (keys tasks))]
(println " " task)))))
| null | https://raw.githubusercontent.com/bevuta/pepa/0a9991de0fd1714515ca3def645aec30e21cd671/src/pepa/tasks.clj | clojure | (ns pepa.tasks
(:require [pepa.tasks.schema :as schema])
(:gen-class))
(def tasks
{"schema" schema/run})
(defn -main [task & args]
(if-let [run-task (get tasks task)]
(run-task args)
(binding [*out* *err*]
(print "Invalid pepa task")
(when (seq (str task))
(print (str " '" task "'")))
(newline)
(newline)
(println "Available tasks:")
(doseq [task (sort (keys tasks))]
(println " " task)))))
| |
12572ca3bdba5ac3d8ac041b716112b0a778de147128674faf1026cd0e28b227 | ligurio/elle-cli | comments.clj | (ns elle-cli.comments
"Checks for a strict serializability anomaly in which T1 < T2, but T2 is
visible without T1.
We perform concurrent blind inserts across n tables, and meanwhile, perform
reads of both tables in a transaction. To verify, we replay the history,
tracking the writes which were known to have completed before the invocation
of any write w_i. If w_i is visible, and some w_j < w_i is *not* visible,
we've found a violation of strict serializability.
Splits keys up onto different tables to make sure they fall in different
shard ranges"
(:require [jepsen.checker :as checker]
[knossos.model :as model]
[knossos.op :as op]
[clojure.core.reducers :as r]
[clojure.set :as set]))
Source : -io/jepsen/blob/main/cockroachdb/src/jepsen/cockroach/comments.clj
(defn checker
[]
(reify checker/Checker
(check [this test history opts]
Determine first - order write precedence graph
(let [expected (loop [completed (sorted-set)
expected {}
[op & more :as history] history]
(cond
; Done
(not (seq history))
expected
; We know this value is definitely written
(= :write (:f op))
(cond ; Write is beginning; record precedence
(op/invoke? op)
(recur completed
(assoc expected (:value op) completed)
more)
; Write is completing; we can now expect to see
; it
(op/ok? op)
(recur (conj completed (:value op))
expected more)
true
(recur completed expected more))
true
(recur completed expected more)))
errors (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(reduce (fn [errors op]
(let [seen (:value op)
our-expected (->> seen
(map expected)
(reduce set/union))
missing (set/difference our-expected
seen)]
(if (empty? missing)
errors
(conj errors
(-> op
(dissoc :value)
(assoc :missing missing)
(assoc :expected-count
(count our-expected)))))))
[]))]
{:valid? (empty? errors)
:errors errors}))))
| null | https://raw.githubusercontent.com/ligurio/elle-cli/c660bce8c10041aa3353f4fb8269eca7f3ffb228/src/elle_cli/comments.clj | clojure | Done
We know this value is definitely written
Write is beginning; record precedence
Write is completing; we can now expect to see
it | (ns elle-cli.comments
"Checks for a strict serializability anomaly in which T1 < T2, but T2 is
visible without T1.
We perform concurrent blind inserts across n tables, and meanwhile, perform
reads of both tables in a transaction. To verify, we replay the history,
tracking the writes which were known to have completed before the invocation
of any write w_i. If w_i is visible, and some w_j < w_i is *not* visible,
we've found a violation of strict serializability.
Splits keys up onto different tables to make sure they fall in different
shard ranges"
(:require [jepsen.checker :as checker]
[knossos.model :as model]
[knossos.op :as op]
[clojure.core.reducers :as r]
[clojure.set :as set]))
Source : -io/jepsen/blob/main/cockroachdb/src/jepsen/cockroach/comments.clj
(defn checker
[]
(reify checker/Checker
(check [this test history opts]
Determine first - order write precedence graph
(let [expected (loop [completed (sorted-set)
expected {}
[op & more :as history] history]
(cond
(not (seq history))
expected
(= :write (:f op))
(op/invoke? op)
(recur completed
(assoc expected (:value op) completed)
more)
(op/ok? op)
(recur (conj completed (:value op))
expected more)
true
(recur completed expected more))
true
(recur completed expected more)))
errors (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(reduce (fn [errors op]
(let [seen (:value op)
our-expected (->> seen
(map expected)
(reduce set/union))
missing (set/difference our-expected
seen)]
(if (empty? missing)
errors
(conj errors
(-> op
(dissoc :value)
(assoc :missing missing)
(assoc :expected-count
(count our-expected)))))))
[]))]
{:valid? (empty? errors)
:errors errors}))))
|
171404508c955e66b0d3273f2fcb20b7f20450b9265cd3d40ea10dd887b42401 | yesodweb/yesod | Fields.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE TypeFamilies #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE CPP #
-- | Field functions allow you to easily create and validate forms, cleanly handling the uncertainty of parsing user input.
--
When possible , the field functions use a specific input type ( e.g. " number " ) , allowing supporting browsers to validate the input before form submission . Browsers can also improve usability with this information ; for example , mobile browsers might present a specialized keyboard for an input of type " email " or " number " .
--
See the Yesod book < chapter on forms > for a broader overview of forms in Yesod .
module Yesod.Form.Fields
( -- * i18n
FormMessage (..)
, defaultFormMessage
-- * Fields
, textField
, passwordField
, textareaField
, hiddenField
, intField
, dayField
, timeField
, timeFieldTypeTime
, timeFieldTypeText
, htmlField
, emailField
, multiEmailField
, searchField
, AutoFocus
, urlField
, doubleField
, parseDate
, parseTime
, Textarea (..)
, boolField
, checkBoxField
, fileField
* File ' AForm 's
, fileAFormReq
, fileAFormOpt
-- * Options
-- $optionsOverview
, selectFieldHelper
, selectField
, selectFieldList
, selectFieldListGrouped
, radioField
, radioFieldList
, withRadioField
, checkboxesField
, checkboxesFieldList
, multiSelectField
, multiSelectFieldList
, Option (..)
, OptionList (..)
, mkOptionList
, mkOptionListGrouped
, optionsPersist
, optionsPersistKey
, optionsPairs
, optionsPairsGrouped
, optionsEnum
, colorField
) where
import Yesod.Form.Types
import Yesod.Form.I18n.English
import Yesod.Form.Functions (parseHelper)
import Yesod.Core
import Text.Blaze (ToMarkup (toMarkup), unsafeByteString)
#define ToHtml ToMarkup
#define toHtml toMarkup
#define preEscapedText preEscapedToMarkup
import Data.Time (Day, TimeOfDay(..))
import qualified Text.Email.Validate as Email
import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Network.URI (parseURI)
import Database.Persist.Sql (PersistField, PersistFieldSql (..))
#if MIN_VERSION_persistent(2,5,0)
import Database.Persist (Entity (..), SqlType (SqlString), PersistRecordBackend, PersistQueryRead)
#else
import Database.Persist (Entity (..), SqlType (SqlString), PersistEntity, PersistQuery, PersistEntityBackend)
#endif
import Text.HTML.SanitizeXSS (sanitizeBalance)
import Control.Monad (when, unless, forM_)
import Data.Either (partitionEithers)
import Data.Maybe (listToMaybe, fromMaybe)
import qualified Blaze.ByteString.Builder.Html.Utf8 as B
import Blaze.ByteString.Builder (writeByteString, toLazyByteString)
import Blaze.ByteString.Builder.Internal.Write (fromWriteList)
import Text.Blaze.Html.Renderer.String (renderHtml)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Text as T ( Text, append, concat, cons, head
, intercalate, isPrefixOf, null, unpack, pack, splitOn
)
import qualified Data.Text as T (drop, dropWhile)
import qualified Data.Text.Read
import qualified Data.Map as Map
import Yesod.Persist (selectList, Filter, SelectOpt, Key)
import Control.Arrow ((&&&))
import Control.Applicative ((<$>), (<|>))
import Data.Attoparsec.Text (Parser, char, string, digit, skipSpace, endOfInput, parseOnly)
import Yesod.Persist.Core
import Data.String (IsString)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
#endif
import Data.Char (isHexDigit)
defaultFormMessage :: FormMessage -> Text
defaultFormMessage = englishFormMessage
| Creates a input with @type="number"@ and @step=1@.
intField :: (Monad m, Integral i, RenderMessage (HandlerSite m) FormMessage) => Field m i
intField = Field
{ fieldParse = parseHelper $ \s ->
case Data.Text.Read.signed Data.Text.Read.decimal s of
Right (a, "") -> Right a
_ -> Left $ MsgInvalidInteger s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="number" step=1 :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . showI)
showI x = show (fromIntegral x :: Integer)
| Creates a input with @type="number"@ and @step = any@.
doubleField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Double
doubleField = Field
{ fieldParse = parseHelper $ \s ->
case Data.Text.Read.double (prependZero s) of
Right (a, "") -> Right a
_ -> Left $ MsgInvalidNumber s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="number" step=any :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . show)
-- | Creates an input with @type="date"@, validating the input using the 'parseDate' function.
--
Add the @time@ package and import the " Data . Time . Calendar " module to use this function .
dayField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Day
dayField = Field
{ fieldParse = parseHelper $ parseDate . unpack
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="date" :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . show)
-- | An alias for 'timeFieldTypeTime'.
timeField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeField = timeFieldTypeTime
| Creates an input with @type="time"@. < /#search=time%20input%20type Browsers not supporting this type > will fallback to a text field , and Yesod will parse the time as described in ' timeFieldTypeText ' .
--
-- Add the @time@ package and import the "Data.Time.LocalTime" module to use this function.
--
@since 1.4.2
timeFieldTypeTime :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeFieldTypeTime = timeFieldOfType "time"
| Creates an input with , parsing the time from an [ H]H : MM[:SS ] format , with an optional AM or PM ( if not given , AM is assumed for compatibility with the 24 hour clock system ) .
--
This function exists for backwards compatibility with the old implementation of ' ' , which used to use @type="text"@. Consider using ' ' or ' timeFieldTypeTime ' for improved UX and validation from the browser .
--
-- Add the @time@ package and import the "Data.Time.LocalTime" module to use this function.
--
@since 1.4.2
timeFieldTypeText :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeFieldTypeText = timeFieldOfType "text"
timeFieldOfType :: Monad m => RenderMessage (HandlerSite m) FormMessage => Text -> Field m TimeOfDay
timeFieldOfType inputType = Field
{ fieldParse = parseHelper parseTime
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="#{inputType}" :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . show . roundFullSeconds)
roundFullSeconds tod =
TimeOfDay (todHour tod) (todMin tod) fullSec
where
fullSec = fromInteger $ floor $ todSec tod
-- | Creates a @\<textarea>@ tag whose input is sanitized to prevent XSS attacks and is validated for having balanced tags.
htmlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Html
htmlField = Field
{ fieldParse = parseHelper $ Right . preEscapedText . sanitizeBalance
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<textarea :isReq:required="" id="#{theId}" name="#{name}" *{attrs}>#{showVal val}
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . renderHtml)
| A newtype wrapper around a ' Text ' whose ' ToMarkup ' instance converts newlines to HTML @\<br>@ tags .
--
-- (When text is entered into a @\<textarea>@, newline characters are used to separate lines.
-- If this text is then placed verbatim into HTML, the lines won't be separated, thus the need for replacing with @\<br>@ tags).
-- If you don't need this functionality, simply use 'unTextarea' to access the raw text.
newtype Textarea = Textarea { unTextarea :: Text }
deriving (Show, Read, Eq, PersistField, Ord, ToJSON, FromJSON, IsString)
instance PersistFieldSql Textarea where
sqlType _ = SqlString
instance ToHtml Textarea where
toHtml =
unsafeByteString
. S.concat
. L.toChunks
. toLazyByteString
. fromWriteList writeHtmlEscapedChar
. unpack
. unTextarea
where
-- Taken from blaze-builder and modified with newline handling.
writeHtmlEscapedChar '\r' = mempty
writeHtmlEscapedChar '\n' = writeByteString "<br>"
writeHtmlEscapedChar c = B.writeHtmlEscapedChar c
| Creates a @\<textarea>@ tag whose returned value is wrapped in a ' ' ; see ' ' for details .
textareaField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Textarea
textareaField = Field
{ fieldParse = parseHelper $ Right . Textarea
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<textarea id="#{theId}" name="#{name}" :isReq:required="" *{attrs}>#{either id unTextarea val}
|]
, fieldEnctype = UrlEncoded
}
| Creates an input with @type="hidden"@ ; you can use this to store information in a form that users should n't see ( for example , Yesod stores CSRF tokens in a hidden field ) .
hiddenField :: (Monad m, PathPiece p, RenderMessage (HandlerSite m) FormMessage)
=> Field m p
hiddenField = Field
{ fieldParse = parseHelper $ maybe (Left MsgValueRequired) Right . fromPathPiece
, fieldView = \theId name attrs val _isReq -> toWidget [hamlet|
$newline never
<input type="hidden" id="#{theId}" name="#{name}" *{attrs} value="#{either id toPathPiece val}">
|]
, fieldEnctype = UrlEncoded
}
-- | Creates a input with @type="text"@.
textField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
textField = Field
{ fieldParse = parseHelper $ Right
, fieldView = \theId name attrs val isReq ->
[whamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="text" :isReq:required value="#{either id id val}">
|]
, fieldEnctype = UrlEncoded
}
-- | Creates an input with @type="password"@.
passwordField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
passwordField = Field
{ fieldParse = parseHelper $ Right
, fieldView = \theId name attrs _ isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="password" :isReq:required="">
|]
, fieldEnctype = UrlEncoded
}
readMay :: Read a => String -> Maybe a
readMay s = case filter (Prelude.null . snd) $ reads s of
(x, _):_ -> Just x
[] -> Nothing
| Parses a ' Day ' from a ' String ' .
parseDate :: String -> Either FormMessage Day
parseDate = maybe (Left MsgInvalidDay) Right
. readMay . replace '/' '-'
-- | Replaces all instances of a value in a list by another value.
from -CGI-Protocol.html#replace
replace :: Eq a => a -> a -> [a] -> [a]
replace x y = map (\z -> if z == x then y else z)
parseTime :: Text -> Either FormMessage TimeOfDay
parseTime = either (Left . fromMaybe MsgInvalidTimeFormat . readMay . drop 2 . dropWhile (/= ':')) Right . parseOnly timeParser
timeParser :: Parser TimeOfDay
timeParser = do
skipSpace
h <- hour
_ <- char ':'
m <- minsec MsgInvalidMinute
hasSec <- (char ':' >> return True) <|> return False
s <- if hasSec then minsec MsgInvalidSecond else return 0
skipSpace
isPM <-
(string "am" >> return (Just False)) <|>
(string "AM" >> return (Just False)) <|>
(string "pm" >> return (Just True)) <|>
(string "PM" >> return (Just True)) <|>
return Nothing
h' <-
case isPM of
Nothing -> return h
Just x
| h <= 0 || h > 12 -> fail $ show $ MsgInvalidHour $ pack $ show h
| h == 12 -> return $ if x then 12 else 0
| otherwise -> return $ h + (if x then 12 else 0)
skipSpace
endOfInput
return $ TimeOfDay h' m s
where
hour = do
x <- digit
y <- (return Control.Applicative.<$> digit) <|> return []
let xy = x : y
let i = read xy
if i < 0 || i >= 24
then fail $ show $ MsgInvalidHour $ pack xy
else return i
minsec :: Num a => (Text -> FormMessage) -> Parser a
minsec msg = do
x <- digit
y <- digit <|> fail (show $ msg $ pack [x])
let xy = [x, y]
let i = read xy
if i < 0 || i >= 60
then fail $ show $ msg $ pack xy
else return $ fromIntegral (i :: Int)
| Creates an input with @type="email"@. Yesod will validate the email 's correctness according to RFC5322 and canonicalize it by removing comments and whitespace ( see " Text . Email . Validate " ) .
emailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
emailField = Field
{ fieldParse = parseHelper $
\s ->
case Email.canonicalizeEmail $ encodeUtf8 s of
Just e -> Right $ decodeUtf8With lenientDecode e
Nothing -> Left $ MsgInvalidEmail s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="email" :isReq:required="" value="#{either id id val}">
|]
, fieldEnctype = UrlEncoded
}
-- | Creates an input with @type="email"@ with the <-forms.html#the-multiple-attribute multiple> attribute; browsers might implement this as taking a comma separated list of emails. Each email address is validated as described in 'emailField'.
--
-- @since 1.3.7
multiEmailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m [Text]
multiEmailField = Field
{ fieldParse = parseHelper $
\s ->
let addrs = map validate $ splitOn "," s
in case partitionEithers addrs of
([], good) -> Right good
(bad, _) -> Left $ MsgInvalidEmail $ cat bad
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="email" multiple :isReq:required="" value="#{either id cat val}">
|]
, fieldEnctype = UrlEncoded
}
where
-- report offending address along with error
validate a = case Email.validate $ encodeUtf8 a of
Left e -> Left $ T.concat [a, " (", pack e, ")"]
Right r -> Right $ emailToText r
cat = intercalate ", "
emailToText = decodeUtf8With lenientDecode . Email.toByteString
type AutoFocus = Bool
| Creates an input with @type="search"@. For < /#search=autofocus browsers without autofocus support > , a JS fallback is used if @AutoFocus@ is true .
searchField :: Monad m => RenderMessage (HandlerSite m) FormMessage => AutoFocus -> Field m Text
searchField autoFocus = Field
{ fieldParse = parseHelper Right
, fieldView = \theId name attrs val isReq -> do
[whamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="search" :isReq:required="" :autoFocus:autofocus="" value="#{either id id val}">
|]
when autoFocus $ do
-- we want this javascript to be placed immediately after the field
[whamlet|
$newline never
<script>if (!('autofocus' in document.createElement('input'))) {document.getElementById('#{theId}').focus();}
|]
toWidget [cassius|
##{theId}
-webkit-appearance: textfield
|]
, fieldEnctype = UrlEncoded
}
| Creates an input with @type="url"@ , validating the URL according to .
urlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
urlField = Field
{ fieldParse = parseHelper $ \s ->
case parseURI $ unpack s of
Nothing -> Left $ MsgInvalidUrl s
Just _ -> Right s
, fieldView = \theId name attrs val isReq ->
[whamlet|<input ##{theId} name=#{name} *{attrs} type=url :isReq:required value=#{either id id val}>|]
, fieldEnctype = UrlEncoded
}
| Creates a @\<select>@ tag for selecting one option . Example usage :
--
> areq ( selectFieldList [ ( " Value 1 " : : Text , " value1"),("Value 2 " , " value2 " ) ] ) " Which value ? " Nothing
selectFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) a
selectFieldList = selectField . optionsPairs
| Creates a @\<select>@ tag with for selecting one option .
--
@since 1.7.0
selectFieldListGrouped :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, [(msg, a)])]
-> Field (HandlerFor site) a
selectFieldListGrouped = selectField . optionsPairsGrouped
| Creates a @\<select>@ tag with optional @\<optgroup>@s for selecting one option . Example usage :
--
> areq ( selectField $ optionsPairs [ ( , " value1"),(MsgValue2 , " value2 " ) ] ) " Which value ? " Nothing
selectField :: (Eq a, RenderMessage site FormMessage)
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
selectField = selectFieldHelper
(\theId name attrs inside -> [whamlet|
$newline never
<select ##{theId} name=#{name} *{attrs}>^{inside}
|]) -- outside
(\_theId _name isSel -> [whamlet|
$newline never
<option value=none :isSel:selected>_{MsgSelectNone}
|]) -- onOpt
(\_theId _name _attrs value isSel text -> [whamlet|
$newline never
<option value=#{value} :isSel:selected>#{text}
|]) -- inside
(Just $ \label -> [whamlet|
<optgroup label=#{label}>
|]) -- group label
| Creates a @\<select>@ tag for selecting multiple options .
multiSelectFieldList :: (Eq a, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) [a]
multiSelectFieldList = multiSelectField . optionsPairs
| Creates a @\<select>@ tag for selecting multiple options .
multiSelectField :: Eq a
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) [a]
multiSelectField ioptlist =
Field parse view UrlEncoded
where
parse [] _ = return $ Right Nothing
parse optlist _ = do
mapopt <- olReadExternal <$> ioptlist
case mapM mapopt optlist of
Nothing -> return $ Left "Error parsing values"
Just res -> return $ Right $ Just res
view theId name attrs val isReq = do
opts <- fmap olOptions $ handlerToWidget ioptlist
let selOpts = map (id &&& (optselected val)) opts
[whamlet|
<select ##{theId} name=#{name} :isReq:required multiple *{attrs}>
$forall (opt, optsel) <- selOpts
<option value=#{optionExternalValue opt} :optsel:selected>#{optionDisplay opt}
|]
where
optselected (Left _) _ = False
optselected (Right vals) opt = (optionInternalValue opt) `elem` vals
| Creates an input with @type="radio"@ for selecting one option .
radioFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) a
radioFieldList = radioField . optionsPairs
-- | Creates an input with @type="checkbox"@ for selecting multiple options.
checkboxesFieldList :: (Eq a, RenderMessage site msg) => [(msg, a)]
-> Field (HandlerFor site) [a]
checkboxesFieldList = checkboxesField . optionsPairs
-- | Creates an input with @type="checkbox"@ for selecting multiple options.
checkboxesField :: Eq a
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) [a]
checkboxesField ioptlist = (multiSelectField ioptlist)
{ fieldView =
\theId name attrs val _isReq -> do
opts <- fmap olOptions $ handlerToWidget ioptlist
let optselected (Left _) _ = False
optselected (Right vals) opt = (optionInternalValue opt) `elem` vals
[whamlet|
<span ##{theId}>
$forall opt <- opts
<label>
<input type=checkbox name=#{name} value=#{optionExternalValue opt} *{attrs} :optselected val opt:checked>
#{optionDisplay opt}
|]
}
| Creates an input with @type="radio"@ for selecting one option .
radioField :: (Eq a, RenderMessage site FormMessage)
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
radioField = withRadioField
(\theId optionWidget -> [whamlet|
$newline never
<div .radio>
<label for=#{theId}-none>
<div>
^{optionWidget}
_{MsgSelectNone}
|])
(\theId value _isSel text optionWidget -> [whamlet|
$newline never
<div .radio>
<label for=#{theId}-#{value}>
<div>
^{optionWidget}
\#{text}
|])
-- | Allows the user to place the option radio widget somewhere in
-- the template.
-- For example: If you want a table of radio options to select.
' ' is an example on how to use this function .
--
-- @since 1.7.2
withRadioField :: (Eq a, RenderMessage site FormMessage)
^ nothing case for mopt
-> (Text -> Text -> Bool -> Text -> WidgetFor site () -> WidgetFor site ()) -- ^ cases for values
-> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
withRadioField nothingFun optFun =
selectFieldHelper outside onOpt inside Nothing
where
outside theId _name _attrs inside' = [whamlet|
$newline never
<div ##{theId}>^{inside'}
|]
onOpt theId name isSel = nothingFun theId $ [whamlet|
$newline never
<input id=#{theId}-none type=radio name=#{name} value=none :isSel:checked>
|]
inside theId name attrs value isSel display =
optFun theId value isSel display [whamlet|
<input id=#{theId}-#{(value)} type=radio name=#{name} value=#{(value)} :isSel:checked *{attrs}>
|]
-- | Creates a group of radio buttons to answer the question given in the message. Radio buttons are used to allow differentiating between an empty response (@Nothing@) and a no response (@Just False@). Consider using the simpler 'checkBoxField' if you don't need to make this distinction.
--
If this field is optional , the first radio button is labeled " \<None > " , the second \"Yes " and the third \"No " .
--
If this field is required , the first radio button is labeled \"Yes " and the second \"No " .
--
-- (Exact label titles will depend on localization).
boolField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Bool
boolField = Field
{ fieldParse = \e _ -> return $ boolParser e
, fieldView = \theId name attrs val isReq -> [whamlet|
$newline never
$if not isReq
<input id=#{theId}-none *{attrs} type=radio name=#{name} value=none checked>
<label for=#{theId}-none>_{MsgSelectNone}
<input id=#{theId}-yes *{attrs} type=radio name=#{name} value=yes :showVal id val:checked>
<label for=#{theId}-yes>_{MsgBoolYes}
<input id=#{theId}-no *{attrs} type=radio name=#{name} value=no :showVal not val:checked>
<label for=#{theId}-no>_{MsgBoolNo}
|]
, fieldEnctype = UrlEncoded
}
where
boolParser [] = Right Nothing
boolParser (x:_) = case x of
"" -> Right Nothing
"none" -> Right Nothing
"yes" -> Right $ Just True
"on" -> Right $ Just True
"no" -> Right $ Just False
"true" -> Right $ Just True
"false" -> Right $ Just False
t -> Left $ SomeMessage $ MsgInvalidBool t
showVal = either (\_ -> False)
-- | Creates an input with @type="checkbox"@.
While the default @'boolField'@ implements a radio button so you
-- can differentiate between an empty response (@Nothing@) and a no
-- response (@Just False@), this simpler checkbox field returns an empty
-- response as @Just False@.
--
-- Note that this makes the field always optional.
--
checkBoxField :: Monad m => Field m Bool
checkBoxField = Field
{ fieldParse = \e _ -> return $ checkBoxParser e
, fieldView = \theId name attrs val _ -> [whamlet|
$newline never
<input id=#{theId} *{attrs} type=checkbox name=#{name} value=yes :showVal id val:checked>
|]
, fieldEnctype = UrlEncoded
}
where
checkBoxParser [] = Right $ Just False
checkBoxParser (x:_) = case x of
"yes" -> Right $ Just True
"on" -> Right $ Just True
_ -> Right $ Just False
showVal = either (\_ -> False)
-- | A structure holding a list of options. Typically you can use a convenience function like 'mkOptionList' or 'optionsPairs' instead of creating this directly.
--
Extended by ' OptionListGrouped ' in 1.7.0 .
data OptionList a
= OptionList
{ olOptions :: [Option a]
^ A function mapping from the form 's value ( ' optionExternalValue ' ) to the selected value ( ' optionInternalValue ' ) .
}
| OptionListGrouped
{ olOptionsGrouped :: [(Text, [Option a])]
^ A function mapping from the form 's value ( ' optionExternalValue ' ) to the selected value ( ' optionInternalValue ' ) .
}
| Convert grouped ' OptionList ' to a normal one .
--
@since 1.7.0
flattenOptionList :: OptionList a -> OptionList a
flattenOptionList (OptionListGrouped os re) = OptionList (concatMap snd os) re
flattenOptionList ol = ol
| @since 1.4.6
instance Functor OptionList where
fmap f (OptionList options readExternal) =
OptionList ((fmap.fmap) f options) (fmap f . readExternal)
fmap f (OptionListGrouped options readExternal) =
OptionListGrouped (map (\(g, os) -> (g, (fmap.fmap) f os)) options) (fmap f . readExternal)
| Creates an ' OptionList ' , using a ' Map ' to implement the ' olReadExternal ' function .
mkOptionList :: [Option a] -> OptionList a
mkOptionList os = OptionList
{ olOptions = os
, olReadExternal = flip Map.lookup $ Map.fromList $ map (optionExternalValue &&& optionInternalValue) os
}
| Creates an ' OptionList ' , using a ' Map ' to implement the ' olReadExternalGrouped ' function .
--
@since 1.7.0
mkOptionListGrouped :: [(Text, [Option a])] -> OptionList a
mkOptionListGrouped os = OptionListGrouped
{ olOptionsGrouped = os
, olReadExternalGrouped = flip Map.lookup $ Map.fromList $ map (optionExternalValue &&& optionInternalValue) $ concatMap snd os
}
data Option a = Option
{ optionDisplay :: Text -- ^ The user-facing label.
^ The value being selected .
, optionExternalValue :: Text -- ^ The representation of this value stored in the form.
}
| @since 1.4.6
instance Functor Option where
fmap f (Option display internal external) = Option display (f internal) external
| Creates an ' OptionList ' from a list of ( display - value , internal value ) pairs .
optionsPairs :: (MonadHandler m, RenderMessage (HandlerSite m) msg)
=> [(msg, a)] -> m (OptionList a)
optionsPairs opts = do
mr <- getMessageRender
let mkOption external (display, internal) =
Option { optionDisplay = mr display
, optionInternalValue = internal
, optionExternalValue = pack $ show external
}
return $ mkOptionList (zipWith mkOption [1 :: Int ..] opts)
| Creates an ' OptionList ' from a list of ( display - value , internal value ) pairs .
--
@since 1.7.0
optionsPairsGrouped
:: forall m msg a. (MonadHandler m, RenderMessage (HandlerSite m) msg)
=> [(msg, [(msg, a)])] -> m (OptionList a)
optionsPairsGrouped opts = do
mr <- getMessageRender
let mkOption (external, (display, internal)) =
Option { optionDisplay = mr display
, optionInternalValue = internal
, optionExternalValue = pack $ show external
}
opts' = enumerateSublists opts :: [(msg, [(Int, (msg, a))])]
opts'' = map (\(x, ys) -> (mr x, map mkOption ys)) opts'
return $ mkOptionListGrouped opts''
| Helper to enumerate sublists with one consecutive index .
enumerateSublists :: forall a b. [(a, [b])] -> [(a, [(Int, b)])]
enumerateSublists xss =
let yss :: [(Int, (a, [b]))]
yss = snd $ foldl (\(i, res) xs -> (i + (length.snd) xs, res ++ [(i, xs)])) (1, []) xss
in map (\(i, (x, ys)) -> (x, zip [i :: Int ..] ys)) yss
| Creates an ' OptionList ' from an ' ' , using its ' Show ' instance for the user - facing value .
optionsEnum :: (MonadHandler m, Show a, Enum a, Bounded a) => m (OptionList a)
optionsEnum = optionsPairs $ map (\x -> (pack $ show x, x)) [minBound..maxBound]
| Selects a list of ' Entity 's with the given ' Filter ' and ' SelectOpt 's . The @(a - > msg)@ function is then used to derive the display value for an ' OptionList ' . Example usage :
--
-- > Country
-- > name Text
> deriving -- Must derive Eq
--
> data CountryForm = CountryForm
-- > { country :: Entity Country
-- > }
-- >
> countryNameForm : : AForm Handler CountryForm
> countryNameForm = CountryForm
> < $ > areq ( selectField countries ) " Which country do you live in ? " Nothing
-- > where
> countries = optionsPersist [ ] [ ] countryName
#if MIN_VERSION_persistent(2,5,0)
optionsPersist :: ( YesodPersist site
, PersistQueryRead backend
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ backend
, PersistRecordBackend a backend
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Entity a))
#else
optionsPersist :: ( YesodPersist site, PersistEntity a
, PersistQuery (PersistEntityBackend a)
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ PersistEntityBackend a
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Entity a))
#endif
optionsPersist filts ords toDisplay = fmap mkOptionList $ do
mr <- getMessageRender
pairs <- runDB $ selectList filts ords
return $ map (\(Entity key value) -> Option
{ optionDisplay = mr (toDisplay value)
, optionInternalValue = Entity key value
, optionExternalValue = toPathPiece key
}) pairs
-- | An alternative to 'optionsPersist' which returns just the 'Key' instead of
-- the entire 'Entity'.
--
@since 1.3.2
#if MIN_VERSION_persistent(2,5,0)
optionsPersistKey
:: (YesodPersist site
, PersistQueryRead backend
, PathPiece (Key a)
, RenderMessage site msg
, backend ~ YesodPersistBackend site
, PersistRecordBackend a backend
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Key a))
#else
optionsPersistKey
:: (YesodPersist site
, PersistEntity a
, PersistQuery (PersistEntityBackend a)
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ PersistEntityBackend a
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Key a))
#endif
optionsPersistKey filts ords toDisplay = fmap mkOptionList $ do
mr <- getMessageRender
pairs <- runDB $ selectList filts ords
return $ map (\(Entity key value) -> Option
{ optionDisplay = mr (toDisplay value)
, optionInternalValue = key
, optionExternalValue = toPathPiece key
}) pairs
-- |
A helper function for constucting ' 's with optional option groups . You may want to use this when you define your custom ' 's or ' radioField 's .
--
@since 1.6.2
selectFieldHelper
:: (Eq a, RenderMessage site FormMessage)
=> (Text -> Text -> [(Text, Text)] -> WidgetFor site () -> WidgetFor site ()) -- ^ Outermost part of the field
-> (Text -> Text -> Bool -> WidgetFor site ()) -- ^ An option for None if the field is optional
-> (Text -> Text -> [(Text, Text)] -> Text -> Bool -> Text -> WidgetFor site ()) -- ^ Other options
-> (Maybe (Text -> WidgetFor site ())) -- ^ Group headers placed inbetween options
-> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
selectFieldHelper outside onOpt inside grpHdr opts' = Field
{ fieldParse = \x _ -> do
opts <- fmap flattenOptionList opts'
return $ selectParser opts x
, fieldView = \theId name attrs val isReq -> do
outside theId name attrs $ do
optsFlat <- fmap (olOptions.flattenOptionList) $ handlerToWidget opts'
unless isReq $ onOpt theId name $ render optsFlat val `notElem` map optionExternalValue optsFlat
opts'' <- handlerToWidget opts'
case opts'' of
OptionList{} -> constructOptions theId name attrs val isReq optsFlat
OptionListGrouped{olOptionsGrouped=grps} -> do
forM_ grps $ \(grp, opts) -> do
case grpHdr of
Just hdr -> hdr grp
Nothing -> return ()
constructOptions theId name attrs val isReq opts
, fieldEnctype = UrlEncoded
}
where
render _ (Left x) = x
render opts (Right a) = maybe "" optionExternalValue $ listToMaybe $ filter ((== a) . optionInternalValue) opts
selectParser _ [] = Right Nothing
selectParser opts (s:_) = case s of
"" -> Right Nothing
"none" -> Right Nothing
x -> case olReadExternal opts x of
Nothing -> Left $ SomeMessage $ MsgInvalidEntry x
Just y -> Right $ Just y
constructOptions theId name attrs val isReq opts =
forM_ opts $ \opt -> inside
theId
name
((if isReq then (("required", "required"):) else id) attrs)
(optionExternalValue opt)
(render opts val == optionExternalValue opt)
(optionDisplay opt)
| Creates an input with
fileField :: Monad m
=> Field m FileInfo
fileField = Field
{ fieldParse = \_ files -> return $
case files of
[] -> Right Nothing
file:_ -> Right $ Just file
, fieldView = \id' name attrs _ isReq -> toWidget [hamlet|
<input id=#{id'} name=#{name} *{attrs} type=file :isReq:required>
|]
, fieldEnctype = Multipart
}
fileAFormReq :: (MonadHandler m, RenderMessage (HandlerSite m) FormMessage)
=> FieldSettings (HandlerSite m) -> AForm m FileInfo
fileAFormReq fs = AForm $ \(site, langs) menvs ints -> do
let (name, ints') =
case fsName fs of
Just x -> (x, ints)
Nothing ->
let i' = incrInts ints
in (pack $ 'f' : show i', i')
id' <- maybe newIdent return $ fsId fs
let (res, errs) =
case menvs of
Nothing -> (FormMissing, Nothing)
Just (_, fenv) ->
case Map.lookup name fenv of
Just (fi:_) -> (FormSuccess fi, Nothing)
_ ->
let t = renderMessage site langs MsgValueRequired
in (FormFailure [t], Just $ toHtml t)
let fv = FieldView
{ fvLabel = toHtml $ renderMessage site langs $ fsLabel fs
, fvTooltip = fmap (toHtml . renderMessage site langs) $ fsTooltip fs
, fvId = id'
, fvInput = [whamlet|
$newline never
<input type=file name=#{name} ##{id'} *{fsAttrs fs}>
|]
, fvErrors = errs
, fvRequired = True
}
return (res, (fv :), ints', Multipart)
fileAFormOpt :: MonadHandler m
=> FieldSettings (HandlerSite m)
-> AForm m (Maybe FileInfo)
fileAFormOpt fs = AForm $ \(master, langs) menvs ints -> do
let (name, ints') =
case fsName fs of
Just x -> (x, ints)
Nothing ->
let i' = incrInts ints
in (pack $ 'f' : show i', i')
id' <- maybe newIdent return $ fsId fs
let (res, errs) =
case menvs of
Nothing -> (FormMissing, Nothing)
Just (_, fenv) ->
case Map.lookup name fenv of
Just (fi:_) -> (FormSuccess $ Just fi, Nothing)
_ -> (FormSuccess Nothing, Nothing)
let fv = FieldView
{ fvLabel = toHtml $ renderMessage master langs $ fsLabel fs
, fvTooltip = fmap (toHtml . renderMessage master langs) $ fsTooltip fs
, fvId = id'
, fvInput = [whamlet|
$newline never
<input type=file name=#{name} ##{id'} *{fsAttrs fs}>
|]
, fvErrors = errs
, fvRequired = False
}
return (res, (fv :), ints', Multipart)
incrInts :: Ints -> Ints
incrInts (IntSingle i) = IntSingle $ i + 1
incrInts (IntCons i is) = (i + 1) `IntCons` is
-- | Adds a '0' to some text so that it may be recognized as a double.
The read ftn does not recognize " .3 " as 0.3 nor " -.3 " as -0.3 , so this
function changes " .xxx " to " 0.xxx " and " -.xxx " to " -0.xxx "
prependZero :: Text -> Text
prependZero t0 = if T.null t1
then t1
else if T.head t1 == '.'
then '0' `T.cons` t1
else if "-." `T.isPrefixOf` t1
then "-0." `T.append` (T.drop 2 t1)
else t1
where t1 = T.dropWhile (==' ') t0
-- $optionsOverview
These functions create inputs where one or more options can be selected from a list .
--
The basic datastructure used is an ' Option ' , which combines a user - facing display value , the internal value being selected , and an external ' Text ' stored as the @value@ in the form ( used to map back to the internal value ) . A list of these , together with a function mapping from an external value back to a value , form an ' OptionList ' , which several of these functions take as an argument .
--
Typically , you wo n't need to create an ' OptionList ' directly and can instead make one with functions like ' optionsPairs ' or ' optionsEnum ' . Alternatively , you can use functions like ' selectFieldList ' , which use their @[(msg , a)]@ parameter to create an ' OptionList ' themselves .
-- | Creates an input with @type="color"@.
The input value must be provided in hexadecimal format # rrggbb .
--
-- @since 1.7.1
colorField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
colorField = Field
{ fieldParse = parseHelper $ \s ->
if isHexColor $ unpack s then Right s
else Left $ MsgInvalidHexColorFormat s
, fieldView = \theId name attrs val _ -> [whamlet|
$newline never
<input ##{theId} name=#{name} *{attrs} type=color value=#{either id id val}>
|]
, fieldEnctype = UrlEncoded
}
where
isHexColor :: String -> Bool
isHexColor ['#',a,b,c,d,e,f] = all isHexDigit [a,b,c,d,e,f]
isHexColor _ = False
| null | https://raw.githubusercontent.com/yesodweb/yesod/e3381d590fd706f9edd9940d233779945b4a49df/yesod-form/Yesod/Form/Fields.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings #
| Field functions allow you to easily create and validate forms, cleanly handling the uncertainty of parsing user input.
* i18n
* Fields
* Options
$optionsOverview
| Creates an input with @type="date"@, validating the input using the 'parseDate' function.
| An alias for 'timeFieldTypeTime'.
Add the @time@ package and import the "Data.Time.LocalTime" module to use this function.
Add the @time@ package and import the "Data.Time.LocalTime" module to use this function.
| Creates a @\<textarea>@ tag whose input is sanitized to prevent XSS attacks and is validated for having balanced tags.
(When text is entered into a @\<textarea>@, newline characters are used to separate lines.
If this text is then placed verbatim into HTML, the lines won't be separated, thus the need for replacing with @\<br>@ tags).
If you don't need this functionality, simply use 'unTextarea' to access the raw text.
Taken from blaze-builder and modified with newline handling.
| Creates a input with @type="text"@.
| Creates an input with @type="password"@.
| Replaces all instances of a value in a list by another value.
| Creates an input with @type="email"@ with the <-forms.html#the-multiple-attribute multiple> attribute; browsers might implement this as taking a comma separated list of emails. Each email address is validated as described in 'emailField'.
@since 1.3.7
report offending address along with error
we want this javascript to be placed immediately after the field
outside
onOpt
inside
group label
| Creates an input with @type="checkbox"@ for selecting multiple options.
| Creates an input with @type="checkbox"@ for selecting multiple options.
| Allows the user to place the option radio widget somewhere in
the template.
For example: If you want a table of radio options to select.
@since 1.7.2
^ cases for values
| Creates a group of radio buttons to answer the question given in the message. Radio buttons are used to allow differentiating between an empty response (@Nothing@) and a no response (@Just False@). Consider using the simpler 'checkBoxField' if you don't need to make this distinction.
(Exact label titles will depend on localization).
| Creates an input with @type="checkbox"@.
can differentiate between an empty response (@Nothing@) and a no
response (@Just False@), this simpler checkbox field returns an empty
response as @Just False@.
Note that this makes the field always optional.
| A structure holding a list of options. Typically you can use a convenience function like 'mkOptionList' or 'optionsPairs' instead of creating this directly.
^ The user-facing label.
^ The representation of this value stored in the form.
> Country
> name Text
Must derive Eq
> { country :: Entity Country
> }
>
> where
| An alternative to 'optionsPersist' which returns just the 'Key' instead of
the entire 'Entity'.
|
^ Outermost part of the field
^ An option for None if the field is optional
^ Other options
^ Group headers placed inbetween options
| Adds a '0' to some text so that it may be recognized as a double.
$optionsOverview
| Creates an input with @type="color"@.
@since 1.7.1 | # LANGUAGE QuasiQuotes #
# LANGUAGE TypeFamilies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE CPP #
When possible , the field functions use a specific input type ( e.g. " number " ) , allowing supporting browsers to validate the input before form submission . Browsers can also improve usability with this information ; for example , mobile browsers might present a specialized keyboard for an input of type " email " or " number " .
See the Yesod book < chapter on forms > for a broader overview of forms in Yesod .
module Yesod.Form.Fields
FormMessage (..)
, defaultFormMessage
, textField
, passwordField
, textareaField
, hiddenField
, intField
, dayField
, timeField
, timeFieldTypeTime
, timeFieldTypeText
, htmlField
, emailField
, multiEmailField
, searchField
, AutoFocus
, urlField
, doubleField
, parseDate
, parseTime
, Textarea (..)
, boolField
, checkBoxField
, fileField
* File ' AForm 's
, fileAFormReq
, fileAFormOpt
, selectFieldHelper
, selectField
, selectFieldList
, selectFieldListGrouped
, radioField
, radioFieldList
, withRadioField
, checkboxesField
, checkboxesFieldList
, multiSelectField
, multiSelectFieldList
, Option (..)
, OptionList (..)
, mkOptionList
, mkOptionListGrouped
, optionsPersist
, optionsPersistKey
, optionsPairs
, optionsPairsGrouped
, optionsEnum
, colorField
) where
import Yesod.Form.Types
import Yesod.Form.I18n.English
import Yesod.Form.Functions (parseHelper)
import Yesod.Core
import Text.Blaze (ToMarkup (toMarkup), unsafeByteString)
#define ToHtml ToMarkup
#define toHtml toMarkup
#define preEscapedText preEscapedToMarkup
import Data.Time (Day, TimeOfDay(..))
import qualified Text.Email.Validate as Email
import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Network.URI (parseURI)
import Database.Persist.Sql (PersistField, PersistFieldSql (..))
#if MIN_VERSION_persistent(2,5,0)
import Database.Persist (Entity (..), SqlType (SqlString), PersistRecordBackend, PersistQueryRead)
#else
import Database.Persist (Entity (..), SqlType (SqlString), PersistEntity, PersistQuery, PersistEntityBackend)
#endif
import Text.HTML.SanitizeXSS (sanitizeBalance)
import Control.Monad (when, unless, forM_)
import Data.Either (partitionEithers)
import Data.Maybe (listToMaybe, fromMaybe)
import qualified Blaze.ByteString.Builder.Html.Utf8 as B
import Blaze.ByteString.Builder (writeByteString, toLazyByteString)
import Blaze.ByteString.Builder.Internal.Write (fromWriteList)
import Text.Blaze.Html.Renderer.String (renderHtml)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Text as T ( Text, append, concat, cons, head
, intercalate, isPrefixOf, null, unpack, pack, splitOn
)
import qualified Data.Text as T (drop, dropWhile)
import qualified Data.Text.Read
import qualified Data.Map as Map
import Yesod.Persist (selectList, Filter, SelectOpt, Key)
import Control.Arrow ((&&&))
import Control.Applicative ((<$>), (<|>))
import Data.Attoparsec.Text (Parser, char, string, digit, skipSpace, endOfInput, parseOnly)
import Yesod.Persist.Core
import Data.String (IsString)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
#endif
import Data.Char (isHexDigit)
defaultFormMessage :: FormMessage -> Text
defaultFormMessage = englishFormMessage
| Creates a input with @type="number"@ and @step=1@.
intField :: (Monad m, Integral i, RenderMessage (HandlerSite m) FormMessage) => Field m i
intField = Field
{ fieldParse = parseHelper $ \s ->
case Data.Text.Read.signed Data.Text.Read.decimal s of
Right (a, "") -> Right a
_ -> Left $ MsgInvalidInteger s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="number" step=1 :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . showI)
showI x = show (fromIntegral x :: Integer)
| Creates a input with @type="number"@ and @step = any@.
doubleField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Double
doubleField = Field
{ fieldParse = parseHelper $ \s ->
case Data.Text.Read.double (prependZero s) of
Right (a, "") -> Right a
_ -> Left $ MsgInvalidNumber s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="number" step=any :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . show)
Add the @time@ package and import the " Data . Time . Calendar " module to use this function .
dayField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Day
dayField = Field
{ fieldParse = parseHelper $ parseDate . unpack
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="date" :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . show)
timeField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeField = timeFieldTypeTime
| Creates an input with @type="time"@. < /#search=time%20input%20type Browsers not supporting this type > will fallback to a text field , and Yesod will parse the time as described in ' timeFieldTypeText ' .
@since 1.4.2
timeFieldTypeTime :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeFieldTypeTime = timeFieldOfType "time"
| Creates an input with , parsing the time from an [ H]H : MM[:SS ] format , with an optional AM or PM ( if not given , AM is assumed for compatibility with the 24 hour clock system ) .
This function exists for backwards compatibility with the old implementation of ' ' , which used to use @type="text"@. Consider using ' ' or ' timeFieldTypeTime ' for improved UX and validation from the browser .
@since 1.4.2
timeFieldTypeText :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m TimeOfDay
timeFieldTypeText = timeFieldOfType "text"
timeFieldOfType :: Monad m => RenderMessage (HandlerSite m) FormMessage => Text -> Field m TimeOfDay
timeFieldOfType inputType = Field
{ fieldParse = parseHelper parseTime
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="#{inputType}" :isReq:required="" value="#{showVal val}">
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . show . roundFullSeconds)
roundFullSeconds tod =
TimeOfDay (todHour tod) (todMin tod) fullSec
where
fullSec = fromInteger $ floor $ todSec tod
htmlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Html
htmlField = Field
{ fieldParse = parseHelper $ Right . preEscapedText . sanitizeBalance
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<textarea :isReq:required="" id="#{theId}" name="#{name}" *{attrs}>#{showVal val}
|]
, fieldEnctype = UrlEncoded
}
where showVal = either id (pack . renderHtml)
| A newtype wrapper around a ' Text ' whose ' ToMarkup ' instance converts newlines to HTML @\<br>@ tags .
newtype Textarea = Textarea { unTextarea :: Text }
deriving (Show, Read, Eq, PersistField, Ord, ToJSON, FromJSON, IsString)
instance PersistFieldSql Textarea where
sqlType _ = SqlString
instance ToHtml Textarea where
toHtml =
unsafeByteString
. S.concat
. L.toChunks
. toLazyByteString
. fromWriteList writeHtmlEscapedChar
. unpack
. unTextarea
where
writeHtmlEscapedChar '\r' = mempty
writeHtmlEscapedChar '\n' = writeByteString "<br>"
writeHtmlEscapedChar c = B.writeHtmlEscapedChar c
| Creates a @\<textarea>@ tag whose returned value is wrapped in a ' ' ; see ' ' for details .
textareaField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Textarea
textareaField = Field
{ fieldParse = parseHelper $ Right . Textarea
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<textarea id="#{theId}" name="#{name}" :isReq:required="" *{attrs}>#{either id unTextarea val}
|]
, fieldEnctype = UrlEncoded
}
| Creates an input with @type="hidden"@ ; you can use this to store information in a form that users should n't see ( for example , Yesod stores CSRF tokens in a hidden field ) .
hiddenField :: (Monad m, PathPiece p, RenderMessage (HandlerSite m) FormMessage)
=> Field m p
hiddenField = Field
{ fieldParse = parseHelper $ maybe (Left MsgValueRequired) Right . fromPathPiece
, fieldView = \theId name attrs val _isReq -> toWidget [hamlet|
$newline never
<input type="hidden" id="#{theId}" name="#{name}" *{attrs} value="#{either id toPathPiece val}">
|]
, fieldEnctype = UrlEncoded
}
textField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
textField = Field
{ fieldParse = parseHelper $ Right
, fieldView = \theId name attrs val isReq ->
[whamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="text" :isReq:required value="#{either id id val}">
|]
, fieldEnctype = UrlEncoded
}
passwordField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
passwordField = Field
{ fieldParse = parseHelper $ Right
, fieldView = \theId name attrs _ isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="password" :isReq:required="">
|]
, fieldEnctype = UrlEncoded
}
readMay :: Read a => String -> Maybe a
readMay s = case filter (Prelude.null . snd) $ reads s of
(x, _):_ -> Just x
[] -> Nothing
| Parses a ' Day ' from a ' String ' .
parseDate :: String -> Either FormMessage Day
parseDate = maybe (Left MsgInvalidDay) Right
. readMay . replace '/' '-'
from -CGI-Protocol.html#replace
replace :: Eq a => a -> a -> [a] -> [a]
replace x y = map (\z -> if z == x then y else z)
parseTime :: Text -> Either FormMessage TimeOfDay
parseTime = either (Left . fromMaybe MsgInvalidTimeFormat . readMay . drop 2 . dropWhile (/= ':')) Right . parseOnly timeParser
timeParser :: Parser TimeOfDay
timeParser = do
skipSpace
h <- hour
_ <- char ':'
m <- minsec MsgInvalidMinute
hasSec <- (char ':' >> return True) <|> return False
s <- if hasSec then minsec MsgInvalidSecond else return 0
skipSpace
isPM <-
(string "am" >> return (Just False)) <|>
(string "AM" >> return (Just False)) <|>
(string "pm" >> return (Just True)) <|>
(string "PM" >> return (Just True)) <|>
return Nothing
h' <-
case isPM of
Nothing -> return h
Just x
| h <= 0 || h > 12 -> fail $ show $ MsgInvalidHour $ pack $ show h
| h == 12 -> return $ if x then 12 else 0
| otherwise -> return $ h + (if x then 12 else 0)
skipSpace
endOfInput
return $ TimeOfDay h' m s
where
hour = do
x <- digit
y <- (return Control.Applicative.<$> digit) <|> return []
let xy = x : y
let i = read xy
if i < 0 || i >= 24
then fail $ show $ MsgInvalidHour $ pack xy
else return i
minsec :: Num a => (Text -> FormMessage) -> Parser a
minsec msg = do
x <- digit
y <- digit <|> fail (show $ msg $ pack [x])
let xy = [x, y]
let i = read xy
if i < 0 || i >= 60
then fail $ show $ msg $ pack xy
else return $ fromIntegral (i :: Int)
| Creates an input with @type="email"@. Yesod will validate the email 's correctness according to RFC5322 and canonicalize it by removing comments and whitespace ( see " Text . Email . Validate " ) .
emailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
emailField = Field
{ fieldParse = parseHelper $
\s ->
case Email.canonicalizeEmail $ encodeUtf8 s of
Just e -> Right $ decodeUtf8With lenientDecode e
Nothing -> Left $ MsgInvalidEmail s
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="email" :isReq:required="" value="#{either id id val}">
|]
, fieldEnctype = UrlEncoded
}
multiEmailField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m [Text]
multiEmailField = Field
{ fieldParse = parseHelper $
\s ->
let addrs = map validate $ splitOn "," s
in case partitionEithers addrs of
([], good) -> Right good
(bad, _) -> Left $ MsgInvalidEmail $ cat bad
, fieldView = \theId name attrs val isReq -> toWidget [hamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="email" multiple :isReq:required="" value="#{either id cat val}">
|]
, fieldEnctype = UrlEncoded
}
where
validate a = case Email.validate $ encodeUtf8 a of
Left e -> Left $ T.concat [a, " (", pack e, ")"]
Right r -> Right $ emailToText r
cat = intercalate ", "
emailToText = decodeUtf8With lenientDecode . Email.toByteString
type AutoFocus = Bool
| Creates an input with @type="search"@. For < /#search=autofocus browsers without autofocus support > , a JS fallback is used if @AutoFocus@ is true .
searchField :: Monad m => RenderMessage (HandlerSite m) FormMessage => AutoFocus -> Field m Text
searchField autoFocus = Field
{ fieldParse = parseHelper Right
, fieldView = \theId name attrs val isReq -> do
[whamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="search" :isReq:required="" :autoFocus:autofocus="" value="#{either id id val}">
|]
when autoFocus $ do
[whamlet|
$newline never
<script>if (!('autofocus' in document.createElement('input'))) {document.getElementById('#{theId}').focus();}
|]
toWidget [cassius|
##{theId}
-webkit-appearance: textfield
|]
, fieldEnctype = UrlEncoded
}
| Creates an input with @type="url"@ , validating the URL according to .
urlField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
urlField = Field
{ fieldParse = parseHelper $ \s ->
case parseURI $ unpack s of
Nothing -> Left $ MsgInvalidUrl s
Just _ -> Right s
, fieldView = \theId name attrs val isReq ->
[whamlet|<input ##{theId} name=#{name} *{attrs} type=url :isReq:required value=#{either id id val}>|]
, fieldEnctype = UrlEncoded
}
| Creates a @\<select>@ tag for selecting one option . Example usage :
> areq ( selectFieldList [ ( " Value 1 " : : Text , " value1"),("Value 2 " , " value2 " ) ] ) " Which value ? " Nothing
selectFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) a
selectFieldList = selectField . optionsPairs
| Creates a @\<select>@ tag with for selecting one option .
@since 1.7.0
selectFieldListGrouped :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, [(msg, a)])]
-> Field (HandlerFor site) a
selectFieldListGrouped = selectField . optionsPairsGrouped
| Creates a @\<select>@ tag with optional @\<optgroup>@s for selecting one option . Example usage :
> areq ( selectField $ optionsPairs [ ( , " value1"),(MsgValue2 , " value2 " ) ] ) " Which value ? " Nothing
selectField :: (Eq a, RenderMessage site FormMessage)
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
selectField = selectFieldHelper
(\theId name attrs inside -> [whamlet|
$newline never
<select ##{theId} name=#{name} *{attrs}>^{inside}
(\_theId _name isSel -> [whamlet|
$newline never
<option value=none :isSel:selected>_{MsgSelectNone}
(\_theId _name _attrs value isSel text -> [whamlet|
$newline never
<option value=#{value} :isSel:selected>#{text}
(Just $ \label -> [whamlet|
<optgroup label=#{label}>
| Creates a @\<select>@ tag for selecting multiple options .
multiSelectFieldList :: (Eq a, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) [a]
multiSelectFieldList = multiSelectField . optionsPairs
| Creates a @\<select>@ tag for selecting multiple options .
multiSelectField :: Eq a
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) [a]
multiSelectField ioptlist =
Field parse view UrlEncoded
where
parse [] _ = return $ Right Nothing
parse optlist _ = do
mapopt <- olReadExternal <$> ioptlist
case mapM mapopt optlist of
Nothing -> return $ Left "Error parsing values"
Just res -> return $ Right $ Just res
view theId name attrs val isReq = do
opts <- fmap olOptions $ handlerToWidget ioptlist
let selOpts = map (id &&& (optselected val)) opts
[whamlet|
<select ##{theId} name=#{name} :isReq:required multiple *{attrs}>
$forall (opt, optsel) <- selOpts
<option value=#{optionExternalValue opt} :optsel:selected>#{optionDisplay opt}
|]
where
optselected (Left _) _ = False
optselected (Right vals) opt = (optionInternalValue opt) `elem` vals
| Creates an input with @type="radio"@ for selecting one option .
radioFieldList :: (Eq a, RenderMessage site FormMessage, RenderMessage site msg)
=> [(msg, a)]
-> Field (HandlerFor site) a
radioFieldList = radioField . optionsPairs
checkboxesFieldList :: (Eq a, RenderMessage site msg) => [(msg, a)]
-> Field (HandlerFor site) [a]
checkboxesFieldList = checkboxesField . optionsPairs
checkboxesField :: Eq a
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) [a]
checkboxesField ioptlist = (multiSelectField ioptlist)
{ fieldView =
\theId name attrs val _isReq -> do
opts <- fmap olOptions $ handlerToWidget ioptlist
let optselected (Left _) _ = False
optselected (Right vals) opt = (optionInternalValue opt) `elem` vals
[whamlet|
<span ##{theId}>
$forall opt <- opts
<label>
<input type=checkbox name=#{name} value=#{optionExternalValue opt} *{attrs} :optselected val opt:checked>
#{optionDisplay opt}
|]
}
| Creates an input with @type="radio"@ for selecting one option .
radioField :: (Eq a, RenderMessage site FormMessage)
=> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
radioField = withRadioField
(\theId optionWidget -> [whamlet|
$newline never
<div .radio>
<label for=#{theId}-none>
<div>
^{optionWidget}
_{MsgSelectNone}
|])
(\theId value _isSel text optionWidget -> [whamlet|
$newline never
<div .radio>
<label for=#{theId}-#{value}>
<div>
^{optionWidget}
\#{text}
|])
' ' is an example on how to use this function .
withRadioField :: (Eq a, RenderMessage site FormMessage)
^ nothing case for mopt
-> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
withRadioField nothingFun optFun =
selectFieldHelper outside onOpt inside Nothing
where
outside theId _name _attrs inside' = [whamlet|
$newline never
<div ##{theId}>^{inside'}
|]
onOpt theId name isSel = nothingFun theId $ [whamlet|
$newline never
<input id=#{theId}-none type=radio name=#{name} value=none :isSel:checked>
|]
inside theId name attrs value isSel display =
optFun theId value isSel display [whamlet|
<input id=#{theId}-#{(value)} type=radio name=#{name} value=#{(value)} :isSel:checked *{attrs}>
|]
If this field is optional , the first radio button is labeled " \<None > " , the second \"Yes " and the third \"No " .
If this field is required , the first radio button is labeled \"Yes " and the second \"No " .
boolField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Bool
boolField = Field
{ fieldParse = \e _ -> return $ boolParser e
, fieldView = \theId name attrs val isReq -> [whamlet|
$newline never
$if not isReq
<input id=#{theId}-none *{attrs} type=radio name=#{name} value=none checked>
<label for=#{theId}-none>_{MsgSelectNone}
<input id=#{theId}-yes *{attrs} type=radio name=#{name} value=yes :showVal id val:checked>
<label for=#{theId}-yes>_{MsgBoolYes}
<input id=#{theId}-no *{attrs} type=radio name=#{name} value=no :showVal not val:checked>
<label for=#{theId}-no>_{MsgBoolNo}
|]
, fieldEnctype = UrlEncoded
}
where
boolParser [] = Right Nothing
boolParser (x:_) = case x of
"" -> Right Nothing
"none" -> Right Nothing
"yes" -> Right $ Just True
"on" -> Right $ Just True
"no" -> Right $ Just False
"true" -> Right $ Just True
"false" -> Right $ Just False
t -> Left $ SomeMessage $ MsgInvalidBool t
showVal = either (\_ -> False)
While the default @'boolField'@ implements a radio button so you
checkBoxField :: Monad m => Field m Bool
checkBoxField = Field
{ fieldParse = \e _ -> return $ checkBoxParser e
, fieldView = \theId name attrs val _ -> [whamlet|
$newline never
<input id=#{theId} *{attrs} type=checkbox name=#{name} value=yes :showVal id val:checked>
|]
, fieldEnctype = UrlEncoded
}
where
checkBoxParser [] = Right $ Just False
checkBoxParser (x:_) = case x of
"yes" -> Right $ Just True
"on" -> Right $ Just True
_ -> Right $ Just False
showVal = either (\_ -> False)
Extended by ' OptionListGrouped ' in 1.7.0 .
data OptionList a
= OptionList
{ olOptions :: [Option a]
^ A function mapping from the form 's value ( ' optionExternalValue ' ) to the selected value ( ' optionInternalValue ' ) .
}
| OptionListGrouped
{ olOptionsGrouped :: [(Text, [Option a])]
^ A function mapping from the form 's value ( ' optionExternalValue ' ) to the selected value ( ' optionInternalValue ' ) .
}
| Convert grouped ' OptionList ' to a normal one .
@since 1.7.0
flattenOptionList :: OptionList a -> OptionList a
flattenOptionList (OptionListGrouped os re) = OptionList (concatMap snd os) re
flattenOptionList ol = ol
| @since 1.4.6
instance Functor OptionList where
fmap f (OptionList options readExternal) =
OptionList ((fmap.fmap) f options) (fmap f . readExternal)
fmap f (OptionListGrouped options readExternal) =
OptionListGrouped (map (\(g, os) -> (g, (fmap.fmap) f os)) options) (fmap f . readExternal)
| Creates an ' OptionList ' , using a ' Map ' to implement the ' olReadExternal ' function .
mkOptionList :: [Option a] -> OptionList a
mkOptionList os = OptionList
{ olOptions = os
, olReadExternal = flip Map.lookup $ Map.fromList $ map (optionExternalValue &&& optionInternalValue) os
}
| Creates an ' OptionList ' , using a ' Map ' to implement the ' olReadExternalGrouped ' function .
@since 1.7.0
mkOptionListGrouped :: [(Text, [Option a])] -> OptionList a
mkOptionListGrouped os = OptionListGrouped
{ olOptionsGrouped = os
, olReadExternalGrouped = flip Map.lookup $ Map.fromList $ map (optionExternalValue &&& optionInternalValue) $ concatMap snd os
}
data Option a = Option
^ The value being selected .
}
| @since 1.4.6
instance Functor Option where
fmap f (Option display internal external) = Option display (f internal) external
| Creates an ' OptionList ' from a list of ( display - value , internal value ) pairs .
optionsPairs :: (MonadHandler m, RenderMessage (HandlerSite m) msg)
=> [(msg, a)] -> m (OptionList a)
optionsPairs opts = do
mr <- getMessageRender
let mkOption external (display, internal) =
Option { optionDisplay = mr display
, optionInternalValue = internal
, optionExternalValue = pack $ show external
}
return $ mkOptionList (zipWith mkOption [1 :: Int ..] opts)
| Creates an ' OptionList ' from a list of ( display - value , internal value ) pairs .
@since 1.7.0
optionsPairsGrouped
:: forall m msg a. (MonadHandler m, RenderMessage (HandlerSite m) msg)
=> [(msg, [(msg, a)])] -> m (OptionList a)
optionsPairsGrouped opts = do
mr <- getMessageRender
let mkOption (external, (display, internal)) =
Option { optionDisplay = mr display
, optionInternalValue = internal
, optionExternalValue = pack $ show external
}
opts' = enumerateSublists opts :: [(msg, [(Int, (msg, a))])]
opts'' = map (\(x, ys) -> (mr x, map mkOption ys)) opts'
return $ mkOptionListGrouped opts''
| Helper to enumerate sublists with one consecutive index .
enumerateSublists :: forall a b. [(a, [b])] -> [(a, [(Int, b)])]
enumerateSublists xss =
let yss :: [(Int, (a, [b]))]
yss = snd $ foldl (\(i, res) xs -> (i + (length.snd) xs, res ++ [(i, xs)])) (1, []) xss
in map (\(i, (x, ys)) -> (x, zip [i :: Int ..] ys)) yss
| Creates an ' OptionList ' from an ' ' , using its ' Show ' instance for the user - facing value .
optionsEnum :: (MonadHandler m, Show a, Enum a, Bounded a) => m (OptionList a)
optionsEnum = optionsPairs $ map (\x -> (pack $ show x, x)) [minBound..maxBound]
| Selects a list of ' Entity 's with the given ' Filter ' and ' SelectOpt 's . The @(a - > msg)@ function is then used to derive the display value for an ' OptionList ' . Example usage :
> data CountryForm = CountryForm
> countryNameForm : : AForm Handler CountryForm
> countryNameForm = CountryForm
> < $ > areq ( selectField countries ) " Which country do you live in ? " Nothing
> countries = optionsPersist [ ] [ ] countryName
#if MIN_VERSION_persistent(2,5,0)
optionsPersist :: ( YesodPersist site
, PersistQueryRead backend
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ backend
, PersistRecordBackend a backend
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Entity a))
#else
optionsPersist :: ( YesodPersist site, PersistEntity a
, PersistQuery (PersistEntityBackend a)
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ PersistEntityBackend a
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Entity a))
#endif
optionsPersist filts ords toDisplay = fmap mkOptionList $ do
mr <- getMessageRender
pairs <- runDB $ selectList filts ords
return $ map (\(Entity key value) -> Option
{ optionDisplay = mr (toDisplay value)
, optionInternalValue = Entity key value
, optionExternalValue = toPathPiece key
}) pairs
@since 1.3.2
#if MIN_VERSION_persistent(2,5,0)
optionsPersistKey
:: (YesodPersist site
, PersistQueryRead backend
, PathPiece (Key a)
, RenderMessage site msg
, backend ~ YesodPersistBackend site
, PersistRecordBackend a backend
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Key a))
#else
optionsPersistKey
:: (YesodPersist site
, PersistEntity a
, PersistQuery (PersistEntityBackend a)
, PathPiece (Key a)
, RenderMessage site msg
, YesodPersistBackend site ~ PersistEntityBackend a
)
=> [Filter a]
-> [SelectOpt a]
-> (a -> msg)
-> HandlerFor site (OptionList (Key a))
#endif
optionsPersistKey filts ords toDisplay = fmap mkOptionList $ do
mr <- getMessageRender
pairs <- runDB $ selectList filts ords
return $ map (\(Entity key value) -> Option
{ optionDisplay = mr (toDisplay value)
, optionInternalValue = key
, optionExternalValue = toPathPiece key
}) pairs
A helper function for constucting ' 's with optional option groups . You may want to use this when you define your custom ' 's or ' radioField 's .
@since 1.6.2
selectFieldHelper
:: (Eq a, RenderMessage site FormMessage)
-> HandlerFor site (OptionList a)
-> Field (HandlerFor site) a
selectFieldHelper outside onOpt inside grpHdr opts' = Field
{ fieldParse = \x _ -> do
opts <- fmap flattenOptionList opts'
return $ selectParser opts x
, fieldView = \theId name attrs val isReq -> do
outside theId name attrs $ do
optsFlat <- fmap (olOptions.flattenOptionList) $ handlerToWidget opts'
unless isReq $ onOpt theId name $ render optsFlat val `notElem` map optionExternalValue optsFlat
opts'' <- handlerToWidget opts'
case opts'' of
OptionList{} -> constructOptions theId name attrs val isReq optsFlat
OptionListGrouped{olOptionsGrouped=grps} -> do
forM_ grps $ \(grp, opts) -> do
case grpHdr of
Just hdr -> hdr grp
Nothing -> return ()
constructOptions theId name attrs val isReq opts
, fieldEnctype = UrlEncoded
}
where
render _ (Left x) = x
render opts (Right a) = maybe "" optionExternalValue $ listToMaybe $ filter ((== a) . optionInternalValue) opts
selectParser _ [] = Right Nothing
selectParser opts (s:_) = case s of
"" -> Right Nothing
"none" -> Right Nothing
x -> case olReadExternal opts x of
Nothing -> Left $ SomeMessage $ MsgInvalidEntry x
Just y -> Right $ Just y
constructOptions theId name attrs val isReq opts =
forM_ opts $ \opt -> inside
theId
name
((if isReq then (("required", "required"):) else id) attrs)
(optionExternalValue opt)
(render opts val == optionExternalValue opt)
(optionDisplay opt)
| Creates an input with
fileField :: Monad m
=> Field m FileInfo
fileField = Field
{ fieldParse = \_ files -> return $
case files of
[] -> Right Nothing
file:_ -> Right $ Just file
, fieldView = \id' name attrs _ isReq -> toWidget [hamlet|
<input id=#{id'} name=#{name} *{attrs} type=file :isReq:required>
|]
, fieldEnctype = Multipart
}
fileAFormReq :: (MonadHandler m, RenderMessage (HandlerSite m) FormMessage)
=> FieldSettings (HandlerSite m) -> AForm m FileInfo
fileAFormReq fs = AForm $ \(site, langs) menvs ints -> do
let (name, ints') =
case fsName fs of
Just x -> (x, ints)
Nothing ->
let i' = incrInts ints
in (pack $ 'f' : show i', i')
id' <- maybe newIdent return $ fsId fs
let (res, errs) =
case menvs of
Nothing -> (FormMissing, Nothing)
Just (_, fenv) ->
case Map.lookup name fenv of
Just (fi:_) -> (FormSuccess fi, Nothing)
_ ->
let t = renderMessage site langs MsgValueRequired
in (FormFailure [t], Just $ toHtml t)
let fv = FieldView
{ fvLabel = toHtml $ renderMessage site langs $ fsLabel fs
, fvTooltip = fmap (toHtml . renderMessage site langs) $ fsTooltip fs
, fvId = id'
, fvInput = [whamlet|
$newline never
<input type=file name=#{name} ##{id'} *{fsAttrs fs}>
|]
, fvErrors = errs
, fvRequired = True
}
return (res, (fv :), ints', Multipart)
fileAFormOpt :: MonadHandler m
=> FieldSettings (HandlerSite m)
-> AForm m (Maybe FileInfo)
fileAFormOpt fs = AForm $ \(master, langs) menvs ints -> do
let (name, ints') =
case fsName fs of
Just x -> (x, ints)
Nothing ->
let i' = incrInts ints
in (pack $ 'f' : show i', i')
id' <- maybe newIdent return $ fsId fs
let (res, errs) =
case menvs of
Nothing -> (FormMissing, Nothing)
Just (_, fenv) ->
case Map.lookup name fenv of
Just (fi:_) -> (FormSuccess $ Just fi, Nothing)
_ -> (FormSuccess Nothing, Nothing)
let fv = FieldView
{ fvLabel = toHtml $ renderMessage master langs $ fsLabel fs
, fvTooltip = fmap (toHtml . renderMessage master langs) $ fsTooltip fs
, fvId = id'
, fvInput = [whamlet|
$newline never
<input type=file name=#{name} ##{id'} *{fsAttrs fs}>
|]
, fvErrors = errs
, fvRequired = False
}
return (res, (fv :), ints', Multipart)
incrInts :: Ints -> Ints
incrInts (IntSingle i) = IntSingle $ i + 1
incrInts (IntCons i is) = (i + 1) `IntCons` is
The read ftn does not recognize " .3 " as 0.3 nor " -.3 " as -0.3 , so this
function changes " .xxx " to " 0.xxx " and " -.xxx " to " -0.xxx "
prependZero :: Text -> Text
prependZero t0 = if T.null t1
then t1
else if T.head t1 == '.'
then '0' `T.cons` t1
else if "-." `T.isPrefixOf` t1
then "-0." `T.append` (T.drop 2 t1)
else t1
where t1 = T.dropWhile (==' ') t0
These functions create inputs where one or more options can be selected from a list .
The basic datastructure used is an ' Option ' , which combines a user - facing display value , the internal value being selected , and an external ' Text ' stored as the @value@ in the form ( used to map back to the internal value ) . A list of these , together with a function mapping from an external value back to a value , form an ' OptionList ' , which several of these functions take as an argument .
Typically , you wo n't need to create an ' OptionList ' directly and can instead make one with functions like ' optionsPairs ' or ' optionsEnum ' . Alternatively , you can use functions like ' selectFieldList ' , which use their @[(msg , a)]@ parameter to create an ' OptionList ' themselves .
The input value must be provided in hexadecimal format # rrggbb .
colorField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Text
colorField = Field
{ fieldParse = parseHelper $ \s ->
if isHexColor $ unpack s then Right s
else Left $ MsgInvalidHexColorFormat s
, fieldView = \theId name attrs val _ -> [whamlet|
$newline never
<input ##{theId} name=#{name} *{attrs} type=color value=#{either id id val}>
|]
, fieldEnctype = UrlEncoded
}
where
isHexColor :: String -> Bool
isHexColor ['#',a,b,c,d,e,f] = all isHexDigit [a,b,c,d,e,f]
isHexColor _ = False
|
b32e901f753f2875df897d502255f159f66d2d6f371c890fca092184a6ffe914 | rjray/advent-2020-clojure | day07_test.clj | (ns advent-of-code.day07-test
(:require [clojure.test :refer [deftest testing is]]
[advent-of-code.day07 :refer [part-1 part-2]]
[clojure.java.io :refer [resource]]))
(deftest part1
(let [expected 4]
(is (= expected (part-1 (slurp (resource "day07-example.txt")))))))
(deftest part2
(let [expected 32]
(is (= expected (part-2 (slurp (resource "day07-example.txt")))))))
| null | https://raw.githubusercontent.com/rjray/advent-2020-clojure/631b36545ae1efdebd11ca3dd4dca032346e8601/test/advent_of_code/day07_test.clj | clojure | (ns advent-of-code.day07-test
(:require [clojure.test :refer [deftest testing is]]
[advent-of-code.day07 :refer [part-1 part-2]]
[clojure.java.io :refer [resource]]))
(deftest part1
(let [expected 4]
(is (= expected (part-1 (slurp (resource "day07-example.txt")))))))
(deftest part2
(let [expected 32]
(is (= expected (part-2 (slurp (resource "day07-example.txt")))))))
| |
b3f9a121d68db87a22757898a17d765d66af477b96bf737613a9c38005ac41f1 | patoline/patoline | TableOfContents.ml |
Copyright Florian Hatat , , ,
Pierre - Etienne Meunier , , 2012 .
This file is part of Patoline .
Patoline 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 .
Patoline 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 Patoline . If not , see < / > .
Copyright Florian Hatat, Tom Hirschowitz, Pierre Hyvernat,
Pierre-Etienne Meunier, Christophe Raffalli, Guillaume Theyssier 2012.
This file is part of Patoline.
Patoline 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.
Patoline 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 Patoline. If not, see </>.
*)
open Patoraw
open Patfonts
open Patutil
open Document
open FTypes
open Box
open Extra
let centered parameters str tree _=
str := newPar !str ~environment:(fun x->{x with par_indent=[]}) Complete.normal parameters [
bB (
fun env->
let spacing=1. in
let r=0.3 in
let x_height=
let x=Fonts.loadGlyph env.font ({empty_glyph with glyph_index=Fonts.glyph_of_char env.font 'x'}) in
(Fonts.glyph_y1 x)/.1000.
in
let orn=RawContent.translate 0. (env.size*.x_height/.2.-.r) (RawContent.Path
({RawContent.default_path_param with RawContent.fillColor=Some Color.black;RawContent.strokingColor=None }, [RawContent.circle r])) in
let (orn_x0,_,orn_x1,_)=RawContent.bounding_box [orn] in
let max_name=ref 0. in
let max_w=ref 0. in
let y=orn_x1-.orn_x0 in
let rec toc env0 path tree=
match tree with
| Paragraph _ -> []
| FigureDef _ -> []
| Node s when (List.length path) <= 1-> (
let rec flat_children env1=function
[]->[]
| (_,(FigureDef _))::s
| (_,(Paragraph _))::s->flat_children env1 s
| (k,(Node h as tr))::s->(
let env'=h.node_env env1 in
let chi1 = toc env' (k::path) tr in
chi1@flat_children (h.node_post_env env1 env') s
)
in
let chi=if List.mem_assoc "numbered" s.node_tags then flat_children env0 (IntMap.bindings s.children) else [] in
let _,b=(try StrMap.find "_structure" (env0.counters) with _-> -1,[0]) in
let count = List.drop 1 b in
let in_toc=List.mem_assoc "intoc" s.node_tags in
if in_toc && count<>[] then (
let labl=String.concat "_" ("_"::List.map string_of_int path) in
let page=try
(1+layout_page (MarkerMap.find (Label labl) (user_positions env0)))
with Not_found -> 0
in
let fenv env={ env with
substitutions=
(fun glyphs->
Fonts.apply_features
env.font
(Fonts.select_features env.font [ Opentype.oldStyleFigures ])
(env.substitutions glyphs)
)}
in
let env'=fenv env0 in
let name= boxify_scoped env' s.displayname in
let pagenum=((boxify_scoped (fenv (envItalic true env0))
[tT (Printf.sprintf "page %d" page)]))
in
let w_name=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. name in
let w_page=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. pagenum in
let cont=
(List.map (RawContent.translate (-.w_name-.spacing) 0.) (draw_boxes env name))@
orn::
(List.map (RawContent.translate (y+.spacing) 0.) (draw_boxes env pagenum))
in
max_w:=max !max_w (w_name+.w_page+.2.*.spacing);
max_name:=max !max_name (w_name+.spacing);
let (_,b,_,d)=RawContent.bounding_box cont in
Drawing {
drawing_min_width=env.normalMeasure;
drawing_nominal_width=env.normalMeasure;
drawing_max_width=env.normalMeasure;
drawing_width_fixed = true;
drawing_adjust_before = false;
drawing_y0=b;
drawing_y1=d;
drawing_break_badness=0.;
drawing_badness=(fun _->0.);
drawing_states=[];
drawing_contents=(fun _->cont)
}::(glue 0. 0. 0.)::chi
)
else chi
)
| Node _->[]
in
let table=toc { env with counters=StrMap.add "_structure" (-1,[0]) env.counters }
[] (fst (top !tree))
in
let x0=if !max_name<env.normalMeasure*.1./.3. then env.normalMeasure/.2.
else !max_name+.(env.normalMeasure-. !max_w)/.2.
in
List.map (function
Drawing d->
Drawing {d with drawing_contents=
(fun x->List.map (RawContent.translate x0 0.)
(d.drawing_contents x))
}
| x->x) table
)]
let these parameters str tree max_level=
let params a b c d e f g line=
parameters a b c d e f g line
in
str := newPar !str ~environment:(fun x->{x with par_indent=[]}) Complete.normal params [
bB (
fun env->
let margin=env.size*.phi in
let rec toc env0 path tree=
let level=List.length path in
match tree with
| Paragraph _ -> []
| FigureDef _ -> []
| Node s when level <= max_level && List.mem_assoc "intoc" s.node_tags-> (
let rec flat_children env1=function
[]->[]
| (_,(FigureDef _))::s
| (_,(Paragraph _))::s->flat_children env1 s
| (k,(Node h as tr))::s->(
let env'=h.node_env env1 in
(toc env' (k::path) tr)@
flat_children (h.node_post_env env1 env') s
)
in
let chi=if List.mem_assoc "numbered" s.node_tags || path=[] then flat_children env0 (IntMap.bindings s.children) else [] in
let _,b=(try StrMap.find "_structure" (env0.counters) with _-> -1,[0]) in
let count = List.rev (List.drop 1 b) in
let spacing=env.size/.phi in
let in_toc=List.mem_assoc "intoc" s.node_tags in
let numbered=List.mem_assoc "numbered" s.node_tags in
if in_toc && numbered && count<>[] then (
let labl=String.concat "_" ("_"::List.map string_of_int path) in
let page=try
(1+layout_page (MarkerMap.find (Label labl) (user_positions env0)))
with Not_found -> 0
in
let env'=add_features [Opentype.oldStyleFigures] env in
let num=boxify_scoped { env' with fontColor=
if level=1 then Color.rgb 1. 0. 0. else Color.black }
[tT (String.concat "." (List.map (fun x->string_of_int (x+1)) count))] in
let name=boxify_scoped env' s.displayname in
let w=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. num in
let w'=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. name in
let cont=
(if numbered then List.map (RawContent.translate (-.w-.spacing) 0.)
(draw_boxes env num) else [])@
(List.map (RawContent.translate 0. 0.) (draw_boxes env name))@
List.map (RawContent.translate (w'+.spacing) 0.)
(draw_boxes env (boxify_scoped (envItalic true env') [tT (string_of_int page)]))
in
let (_,b,_,d)=RawContent.bounding_box cont in
Marker (BeginLink (Intern labl))::
Drawing {
drawing_min_width=env.normalMeasure;
drawing_nominal_width=env.normalMeasure;
drawing_max_width=env.normalMeasure;
drawing_width_fixed = true;
drawing_adjust_before = false;
drawing_y0=b;
drawing_y1=d;
drawing_break_badness=0.;
drawing_badness=(fun _->0.);
drawing_states=[];
drawing_contents=
(fun _->
List.map (RawContent.translate
(margin+.spacing*.3.*.(float_of_int (level-1)))
0.) cont)
}::Marker EndLink::(glue 0. 0. 0.)::chi
)
else chi
)
| Node _->[]
in
toc { env with counters=StrMap.add "_structure" (-1,[0]) env.counters }
[] (fst (top !tree))
)]
let slides ?(hidden_color=Color.rgb 0.8 0.8 0.8) parameters str tree max_level=
str := newPar !str ~environment:(fun x->{x with par_indent=[]; lead=phi*.x.lead }) Complete.normal parameters [
bB (
fun env->
let _,b0=try StrMap.find "_structure" env.counters with Not_found -> -1,[] in
let rec prefix u v=match u,v with
| [],_->true
| hu::_,hv::_ when hu<>hv->false
| _::su,_::sv->prefix su sv
| _,[]->false
in
let rec toc env0 path tree=
let level=List.length path in
match tree with
| Paragraph _ -> []
| FigureDef _ -> []
| Node s when level <= max_level->(
let rec flat_children env1=function
[]->[]
| (_,(FigureDef _))::s
| (_,(Paragraph _))::s->flat_children env1 s
| (k,(Node h as tr))::s->(
let env'=h.node_env env1 in
(toc env' (k::path) tr)@
flat_children (h.node_post_env env1 env') s
)
in
let chi=if List.mem_assoc "numbered" s.node_tags || path=[] then flat_children env0 (IntMap.bindings s.children) else [] in
let _,b=(try StrMap.find "_structure" (env0.counters) with _-> -1,[0]) in
let count = List.rev (List.drop 1 b) in
let spacing=env.size in
let in_toc=List.mem_assoc "intoc" s.node_tags in
let numbered=List.mem_assoc "numbered" s.node_tags in
if in_toc && count<>[] then (
let labl=String.concat "_" ("_"::List.map string_of_int path) in
let env'=add_features [Opentype.oldStyleFigures] env in
let env_num=if b0=[] || prefix (List.rev b) (List.rev b0) && level=1 then
{ env' with fontColor=Color.rgb 1. 0. 0. }
else
{ env' with fontColor=hidden_color }
in
let env_name=if b0=[] || prefix (List.rev b) (List.rev b0) && level=1 then
{ env' with fontColor=Color.rgb 0. 0. 0. }
else
{ env' with fontColor=hidden_color }
in
let num=boxify_scoped env_num
[tT (String.concat "." (List.map (fun x->string_of_int (x+1)) count))] in
let name=boxify_scoped env_name s.displayname in
let w=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. num in
let w0=2.*.env.size in
let cont=
(if numbered then List.map (RawContent.translate (w0-.w-.spacing) 0.)
(draw_boxes env_num num)
else [])@
(List.map (RawContent.translate w0 0.) (draw_boxes env' name))
in
let (_,b,_,d)=RawContent.bounding_box cont in
Marker (BeginLink (Intern labl))::
Drawing {
drawing_min_width=env.normalMeasure;
drawing_nominal_width=env.normalMeasure;
drawing_max_width=env.normalMeasure;
drawing_width_fixed = true;
drawing_adjust_before = false;
drawing_y0=b;
drawing_y1=d;
drawing_break_badness=0.;
drawing_badness=(fun _->0.);
drawing_states=[];
drawing_contents=
(fun _->
List.map (RawContent.translate
(spacing*.3.*.(float_of_int (level-1)))
0.) cont)
}::Marker EndLink::(glue 0. 0. 0.)::chi
)
else chi
)
| Node _->[]
in
toc { env with counters=StrMap.add "_structure" (-1,[0]) env.counters }
[] (fst (top !tree))
)]
| null | https://raw.githubusercontent.com/patoline/patoline/3dcd41fdff64895d795d4a78baa27d572b161081/typography/TableOfContents.ml | ocaml |
Copyright Florian Hatat , , ,
Pierre - Etienne Meunier , , 2012 .
This file is part of Patoline .
Patoline 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 .
Patoline 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 Patoline . If not , see < / > .
Copyright Florian Hatat, Tom Hirschowitz, Pierre Hyvernat,
Pierre-Etienne Meunier, Christophe Raffalli, Guillaume Theyssier 2012.
This file is part of Patoline.
Patoline 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.
Patoline 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 Patoline. If not, see </>.
*)
open Patoraw
open Patfonts
open Patutil
open Document
open FTypes
open Box
open Extra
let centered parameters str tree _=
str := newPar !str ~environment:(fun x->{x with par_indent=[]}) Complete.normal parameters [
bB (
fun env->
let spacing=1. in
let r=0.3 in
let x_height=
let x=Fonts.loadGlyph env.font ({empty_glyph with glyph_index=Fonts.glyph_of_char env.font 'x'}) in
(Fonts.glyph_y1 x)/.1000.
in
let orn=RawContent.translate 0. (env.size*.x_height/.2.-.r) (RawContent.Path
({RawContent.default_path_param with RawContent.fillColor=Some Color.black;RawContent.strokingColor=None }, [RawContent.circle r])) in
let (orn_x0,_,orn_x1,_)=RawContent.bounding_box [orn] in
let max_name=ref 0. in
let max_w=ref 0. in
let y=orn_x1-.orn_x0 in
let rec toc env0 path tree=
match tree with
| Paragraph _ -> []
| FigureDef _ -> []
| Node s when (List.length path) <= 1-> (
let rec flat_children env1=function
[]->[]
| (_,(FigureDef _))::s
| (_,(Paragraph _))::s->flat_children env1 s
| (k,(Node h as tr))::s->(
let env'=h.node_env env1 in
let chi1 = toc env' (k::path) tr in
chi1@flat_children (h.node_post_env env1 env') s
)
in
let chi=if List.mem_assoc "numbered" s.node_tags then flat_children env0 (IntMap.bindings s.children) else [] in
let _,b=(try StrMap.find "_structure" (env0.counters) with _-> -1,[0]) in
let count = List.drop 1 b in
let in_toc=List.mem_assoc "intoc" s.node_tags in
if in_toc && count<>[] then (
let labl=String.concat "_" ("_"::List.map string_of_int path) in
let page=try
(1+layout_page (MarkerMap.find (Label labl) (user_positions env0)))
with Not_found -> 0
in
let fenv env={ env with
substitutions=
(fun glyphs->
Fonts.apply_features
env.font
(Fonts.select_features env.font [ Opentype.oldStyleFigures ])
(env.substitutions glyphs)
)}
in
let env'=fenv env0 in
let name= boxify_scoped env' s.displayname in
let pagenum=((boxify_scoped (fenv (envItalic true env0))
[tT (Printf.sprintf "page %d" page)]))
in
let w_name=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. name in
let w_page=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. pagenum in
let cont=
(List.map (RawContent.translate (-.w_name-.spacing) 0.) (draw_boxes env name))@
orn::
(List.map (RawContent.translate (y+.spacing) 0.) (draw_boxes env pagenum))
in
max_w:=max !max_w (w_name+.w_page+.2.*.spacing);
max_name:=max !max_name (w_name+.spacing);
let (_,b,_,d)=RawContent.bounding_box cont in
Drawing {
drawing_min_width=env.normalMeasure;
drawing_nominal_width=env.normalMeasure;
drawing_max_width=env.normalMeasure;
drawing_width_fixed = true;
drawing_adjust_before = false;
drawing_y0=b;
drawing_y1=d;
drawing_break_badness=0.;
drawing_badness=(fun _->0.);
drawing_states=[];
drawing_contents=(fun _->cont)
}::(glue 0. 0. 0.)::chi
)
else chi
)
| Node _->[]
in
let table=toc { env with counters=StrMap.add "_structure" (-1,[0]) env.counters }
[] (fst (top !tree))
in
let x0=if !max_name<env.normalMeasure*.1./.3. then env.normalMeasure/.2.
else !max_name+.(env.normalMeasure-. !max_w)/.2.
in
List.map (function
Drawing d->
Drawing {d with drawing_contents=
(fun x->List.map (RawContent.translate x0 0.)
(d.drawing_contents x))
}
| x->x) table
)]
let these parameters str tree max_level=
let params a b c d e f g line=
parameters a b c d e f g line
in
str := newPar !str ~environment:(fun x->{x with par_indent=[]}) Complete.normal params [
bB (
fun env->
let margin=env.size*.phi in
let rec toc env0 path tree=
let level=List.length path in
match tree with
| Paragraph _ -> []
| FigureDef _ -> []
| Node s when level <= max_level && List.mem_assoc "intoc" s.node_tags-> (
let rec flat_children env1=function
[]->[]
| (_,(FigureDef _))::s
| (_,(Paragraph _))::s->flat_children env1 s
| (k,(Node h as tr))::s->(
let env'=h.node_env env1 in
(toc env' (k::path) tr)@
flat_children (h.node_post_env env1 env') s
)
in
let chi=if List.mem_assoc "numbered" s.node_tags || path=[] then flat_children env0 (IntMap.bindings s.children) else [] in
let _,b=(try StrMap.find "_structure" (env0.counters) with _-> -1,[0]) in
let count = List.rev (List.drop 1 b) in
let spacing=env.size/.phi in
let in_toc=List.mem_assoc "intoc" s.node_tags in
let numbered=List.mem_assoc "numbered" s.node_tags in
if in_toc && numbered && count<>[] then (
let labl=String.concat "_" ("_"::List.map string_of_int path) in
let page=try
(1+layout_page (MarkerMap.find (Label labl) (user_positions env0)))
with Not_found -> 0
in
let env'=add_features [Opentype.oldStyleFigures] env in
let num=boxify_scoped { env' with fontColor=
if level=1 then Color.rgb 1. 0. 0. else Color.black }
[tT (String.concat "." (List.map (fun x->string_of_int (x+1)) count))] in
let name=boxify_scoped env' s.displayname in
let w=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. num in
let w'=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. name in
let cont=
(if numbered then List.map (RawContent.translate (-.w-.spacing) 0.)
(draw_boxes env num) else [])@
(List.map (RawContent.translate 0. 0.) (draw_boxes env name))@
List.map (RawContent.translate (w'+.spacing) 0.)
(draw_boxes env (boxify_scoped (envItalic true env') [tT (string_of_int page)]))
in
let (_,b,_,d)=RawContent.bounding_box cont in
Marker (BeginLink (Intern labl))::
Drawing {
drawing_min_width=env.normalMeasure;
drawing_nominal_width=env.normalMeasure;
drawing_max_width=env.normalMeasure;
drawing_width_fixed = true;
drawing_adjust_before = false;
drawing_y0=b;
drawing_y1=d;
drawing_break_badness=0.;
drawing_badness=(fun _->0.);
drawing_states=[];
drawing_contents=
(fun _->
List.map (RawContent.translate
(margin+.spacing*.3.*.(float_of_int (level-1)))
0.) cont)
}::Marker EndLink::(glue 0. 0. 0.)::chi
)
else chi
)
| Node _->[]
in
toc { env with counters=StrMap.add "_structure" (-1,[0]) env.counters }
[] (fst (top !tree))
)]
let slides ?(hidden_color=Color.rgb 0.8 0.8 0.8) parameters str tree max_level=
str := newPar !str ~environment:(fun x->{x with par_indent=[]; lead=phi*.x.lead }) Complete.normal parameters [
bB (
fun env->
let _,b0=try StrMap.find "_structure" env.counters with Not_found -> -1,[] in
let rec prefix u v=match u,v with
| [],_->true
| hu::_,hv::_ when hu<>hv->false
| _::su,_::sv->prefix su sv
| _,[]->false
in
let rec toc env0 path tree=
let level=List.length path in
match tree with
| Paragraph _ -> []
| FigureDef _ -> []
| Node s when level <= max_level->(
let rec flat_children env1=function
[]->[]
| (_,(FigureDef _))::s
| (_,(Paragraph _))::s->flat_children env1 s
| (k,(Node h as tr))::s->(
let env'=h.node_env env1 in
(toc env' (k::path) tr)@
flat_children (h.node_post_env env1 env') s
)
in
let chi=if List.mem_assoc "numbered" s.node_tags || path=[] then flat_children env0 (IntMap.bindings s.children) else [] in
let _,b=(try StrMap.find "_structure" (env0.counters) with _-> -1,[0]) in
let count = List.rev (List.drop 1 b) in
let spacing=env.size in
let in_toc=List.mem_assoc "intoc" s.node_tags in
let numbered=List.mem_assoc "numbered" s.node_tags in
if in_toc && count<>[] then (
let labl=String.concat "_" ("_"::List.map string_of_int path) in
let env'=add_features [Opentype.oldStyleFigures] env in
let env_num=if b0=[] || prefix (List.rev b) (List.rev b0) && level=1 then
{ env' with fontColor=Color.rgb 1. 0. 0. }
else
{ env' with fontColor=hidden_color }
in
let env_name=if b0=[] || prefix (List.rev b) (List.rev b0) && level=1 then
{ env' with fontColor=Color.rgb 0. 0. 0. }
else
{ env' with fontColor=hidden_color }
in
let num=boxify_scoped env_num
[tT (String.concat "." (List.map (fun x->string_of_int (x+1)) count))] in
let name=boxify_scoped env_name s.displayname in
let w=List.fold_left (fun w b->let (_,w',_)=box_interval b in w+.w') 0. num in
let w0=2.*.env.size in
let cont=
(if numbered then List.map (RawContent.translate (w0-.w-.spacing) 0.)
(draw_boxes env_num num)
else [])@
(List.map (RawContent.translate w0 0.) (draw_boxes env' name))
in
let (_,b,_,d)=RawContent.bounding_box cont in
Marker (BeginLink (Intern labl))::
Drawing {
drawing_min_width=env.normalMeasure;
drawing_nominal_width=env.normalMeasure;
drawing_max_width=env.normalMeasure;
drawing_width_fixed = true;
drawing_adjust_before = false;
drawing_y0=b;
drawing_y1=d;
drawing_break_badness=0.;
drawing_badness=(fun _->0.);
drawing_states=[];
drawing_contents=
(fun _->
List.map (RawContent.translate
(spacing*.3.*.(float_of_int (level-1)))
0.) cont)
}::Marker EndLink::(glue 0. 0. 0.)::chi
)
else chi
)
| Node _->[]
in
toc { env with counters=StrMap.add "_structure" (-1,[0]) env.counters }
[] (fst (top !tree))
)]
| |
7a9ce9223bee5781f0ad7f7173198a4edb746cfe7f11c953257bd6b50c62c4ea | kafka4beam/kflow | kflow_wf_chunks_to_local_file.erl | %%%===================================================================
2019 Klarna Bank AB ( publ )
%%%
%%% @doc This workflow assembles chunked transmissions into local
%%% files.
%%%
%%% @end
%%%===================================================================
-module(kflow_wf_chunks_to_local_file).
-include("kflow_int.hrl").
%% API
-export([workflow/2]).
-export_type([config/0, predicate/0]).
%%%===================================================================
%%% Types
%%%===================================================================
-type predicate() :: fun((Key :: binary()) -> boolean()).
-type config() ::
#{ kafka_client => atom()
, consumer_config => proplists:proplist()
, kafka_topic := brod:topic()
, group_id := brod:group_id()
, location := file:filename_all()
, filter => predicate()
}.
%%%===================================================================
%%% API
%%%===================================================================
%% @doc Create a workflow specification
-spec workflow(atom(), config()) -> kflow:workflow().
workflow(Id, Config) ->
kflow:mk_kafka_workflow(Id, pipe_spec(Config), Config).
%%%===================================================================
Internal functions
%%%===================================================================
-spec pipe_spec(config()) -> kflow:pipe().
pipe_spec(Config) ->
Preprocess = maps:get(preprocess, Config, []),
Preprocess ++
1 . Create a dedicated substream for each file :
{demux, fun(_Offset, #{key := Key}) -> Key end}
2 . Assemble chunks :
, {assemble_chunks, kflow_chunks_to_file, Config}
].
| null | https://raw.githubusercontent.com/kafka4beam/kflow/2c44379a2934385a17fb504e7a933c859da7ab06/src/workflows/kflow_wf_chunks_to_local_file.erl | erlang | ===================================================================
@doc This workflow assembles chunked transmissions into local
files.
@end
===================================================================
API
===================================================================
Types
===================================================================
===================================================================
API
===================================================================
@doc Create a workflow specification
===================================================================
=================================================================== | 2019 Klarna Bank AB ( publ )
-module(kflow_wf_chunks_to_local_file).
-include("kflow_int.hrl").
-export([workflow/2]).
-export_type([config/0, predicate/0]).
-type predicate() :: fun((Key :: binary()) -> boolean()).
-type config() ::
#{ kafka_client => atom()
, consumer_config => proplists:proplist()
, kafka_topic := brod:topic()
, group_id := brod:group_id()
, location := file:filename_all()
, filter => predicate()
}.
-spec workflow(atom(), config()) -> kflow:workflow().
workflow(Id, Config) ->
kflow:mk_kafka_workflow(Id, pipe_spec(Config), Config).
Internal functions
-spec pipe_spec(config()) -> kflow:pipe().
pipe_spec(Config) ->
Preprocess = maps:get(preprocess, Config, []),
Preprocess ++
1 . Create a dedicated substream for each file :
{demux, fun(_Offset, #{key := Key}) -> Key end}
2 . Assemble chunks :
, {assemble_chunks, kflow_chunks_to_file, Config}
].
|
7d16aeb125bc91dd08f41e2f8699e9bc3812fa0d809de0b7efc6b4a73966825d | Elzair/nazghul | fields.scm | ;;----------------------------------------------------------------------------
;; fields.scm - field types supported by the game
;;----------------------------------------------------------------------------
;;----------------------------------------------------------------------------
;; kern-mk-field-type <tag> <name> <sprite> <light> <dur> <pmask> <effect>
;;
;; 'effect' is a procedure called whenever an object is positioned over the
;; field. Its only parameter is the object.
;;
;; 'light' is the amount of light radiated by the field.
;;
;; 'dur' is the number of turns the field will exist before disappearing.
;;
;; 'pmask' is the objective pmask (the passability it permits to cross it)
;;
;; 'effect' is an optional procedure to run on an object which steps on the
;; field. See effects.scm.
;;----------------------------------------------------------------------------
(kern-mk-field-type 'F_illum "glowing mote" s_magic 1024 5 pclass-none nil mmode-field)
(kern-mk-field-type 'F_fire "fire field" s_field_fire 512 20 pclass-none 'burn mmode-field)
(kern-mk-field-type 'F_poison "poison field" s_field_poison 256 20 pclass-none 'apply-poison mmode-field)
(kern-mk-field-type 'F_sleep "sleep field" s_field_sleep 256 20 pclass-none 'apply-sleep mmode-field)
(kern-mk-field-type 'F_energy "energy field" s_field_energy 512 20 pclass-repel 'apply-lightning mmode-field)
(kern-mk-field-type 'web-type "spider web" s_spider_web 0 20 pclass-none 'ensnare mmode-field)
(kern-mk-field-type 'F_poison_perm "poison field" s_field_poison 256 -1 pclass-none 'apply-poison mmode-field)
(kern-mk-field-type 'F_sleep_perm "sleep field" s_field_sleep 256 -1 pclass-none 'apply-sleep mmode-field)
(kern-mk-field-type 'F_energy_perm "energy field" s_field_energy 512 -1 pclass-repel 'apply-lightning mmode-field)
(kern-mk-field-type 'F_fire_perm "fire field" s_field_fire 512 -1 pclass-none 'burn mmode-field)
(kern-mk-field-type 'F_web_perm "spider web" s_spider_web 0 -1 pclass-none 'ensnare mmode-field)
(define all-field-types
(list F_fire F_poison F_sleep F_energy web-type
F_fire_perm F_poison_perm F_sleep_perm F_energy_perm F_web_perm))
(define (is-field-type? ktype)
(foldr (lambda (x field-type) (or x (eqv? ktype field-type)))
#f
all-field-types))
(define (is-field? kobj)
(kern-obj-is-field? kobj))
(define (is-fire-field? ktype)
(or (eqv? ktype F_fire)
(eqv? ktype F_fire_perm)))
(define (is-poison-field? ktype)
(or (eqv? ktype F_poison)
(eqv? ktype F_poison_perm)))
(define (is-sleep-field? ktype)
(or (eqv? ktype F_sleep)
(eqv? ktype F_sleep_perm)))
(define (is-energy-field? ktype)
(or (eqv? ktype F_energy)
(eqv? ktype F_energy_perm)))
(define (is-immune-to-field? kchar kfield)
(let ((ktype (kern-obj-get-type kfield)))
(cond ((is-fire-field? ktype) (has-fire-immunity? kchar))
((is-poison-field? ktype) (has-poison-immunity? kchar))
((is-sleep-field? ktype) (has-sleep-immunity? kchar))
(else #f)))) | null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/template/lib/fields.scm | scheme | ----------------------------------------------------------------------------
fields.scm - field types supported by the game
----------------------------------------------------------------------------
----------------------------------------------------------------------------
kern-mk-field-type <tag> <name> <sprite> <light> <dur> <pmask> <effect>
'effect' is a procedure called whenever an object is positioned over the
field. Its only parameter is the object.
'light' is the amount of light radiated by the field.
'dur' is the number of turns the field will exist before disappearing.
'pmask' is the objective pmask (the passability it permits to cross it)
'effect' is an optional procedure to run on an object which steps on the
field. See effects.scm.
---------------------------------------------------------------------------- |
(kern-mk-field-type 'F_illum "glowing mote" s_magic 1024 5 pclass-none nil mmode-field)
(kern-mk-field-type 'F_fire "fire field" s_field_fire 512 20 pclass-none 'burn mmode-field)
(kern-mk-field-type 'F_poison "poison field" s_field_poison 256 20 pclass-none 'apply-poison mmode-field)
(kern-mk-field-type 'F_sleep "sleep field" s_field_sleep 256 20 pclass-none 'apply-sleep mmode-field)
(kern-mk-field-type 'F_energy "energy field" s_field_energy 512 20 pclass-repel 'apply-lightning mmode-field)
(kern-mk-field-type 'web-type "spider web" s_spider_web 0 20 pclass-none 'ensnare mmode-field)
(kern-mk-field-type 'F_poison_perm "poison field" s_field_poison 256 -1 pclass-none 'apply-poison mmode-field)
(kern-mk-field-type 'F_sleep_perm "sleep field" s_field_sleep 256 -1 pclass-none 'apply-sleep mmode-field)
(kern-mk-field-type 'F_energy_perm "energy field" s_field_energy 512 -1 pclass-repel 'apply-lightning mmode-field)
(kern-mk-field-type 'F_fire_perm "fire field" s_field_fire 512 -1 pclass-none 'burn mmode-field)
(kern-mk-field-type 'F_web_perm "spider web" s_spider_web 0 -1 pclass-none 'ensnare mmode-field)
(define all-field-types
(list F_fire F_poison F_sleep F_energy web-type
F_fire_perm F_poison_perm F_sleep_perm F_energy_perm F_web_perm))
(define (is-field-type? ktype)
(foldr (lambda (x field-type) (or x (eqv? ktype field-type)))
#f
all-field-types))
(define (is-field? kobj)
(kern-obj-is-field? kobj))
(define (is-fire-field? ktype)
(or (eqv? ktype F_fire)
(eqv? ktype F_fire_perm)))
(define (is-poison-field? ktype)
(or (eqv? ktype F_poison)
(eqv? ktype F_poison_perm)))
(define (is-sleep-field? ktype)
(or (eqv? ktype F_sleep)
(eqv? ktype F_sleep_perm)))
(define (is-energy-field? ktype)
(or (eqv? ktype F_energy)
(eqv? ktype F_energy_perm)))
(define (is-immune-to-field? kchar kfield)
(let ((ktype (kern-obj-get-type kfield)))
(cond ((is-fire-field? ktype) (has-fire-immunity? kchar))
((is-poison-field? ktype) (has-poison-immunity? kchar))
((is-sleep-field? ktype) (has-sleep-immunity? kchar))
(else #f)))) |
a9978cb3cb4ebea6b0f1da36e0daf04b1a1a99ac3fc005cb1a973375ab83d823 | meooow25/haccepted | KMPBench.hs | module KMPBench where
import qualified Data.ByteString.Char8 as C
import Criterion
import KMP ( prefixFuncBS )
import Util ( evalR, randASCIIString, sizedBench )
benchmark :: Benchmark
benchmark = bgroup "KMP"
Generate the KMP prefix function for a string of size n
bgroup "prefixFuncBS" $ map benchPrefixFuncBS sizes
]
sizes :: [Int]
sizes = [100, 10000, 1000000]
benchPrefixFuncBS :: Int -> Benchmark
benchPrefixFuncBS n = sizedBench n gen $ whnf prefixFuncBS where
gen = C.pack $ evalR $ randASCIIString n
| null | https://raw.githubusercontent.com/meooow25/haccepted/2bc153ca95038de3b8bac83eee4419b3ecc116c5/bench/KMPBench.hs | haskell | module KMPBench where
import qualified Data.ByteString.Char8 as C
import Criterion
import KMP ( prefixFuncBS )
import Util ( evalR, randASCIIString, sizedBench )
benchmark :: Benchmark
benchmark = bgroup "KMP"
Generate the KMP prefix function for a string of size n
bgroup "prefixFuncBS" $ map benchPrefixFuncBS sizes
]
sizes :: [Int]
sizes = [100, 10000, 1000000]
benchPrefixFuncBS :: Int -> Benchmark
benchPrefixFuncBS n = sizedBench n gen $ whnf prefixFuncBS where
gen = C.pack $ evalR $ randASCIIString n
| |
96075fba0ffe59bc60ea03153bc96560010fde17f0f168d3aa3881c6299a59b0 | Decentralized-Pictures/T4L3NT | op.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Protocol
open Alpha_context
let sign ?(watermark = Signature.Generic_operation) sk ctxt contents =
let branch = Context.branch ctxt in
let unsigned =
Data_encoding.Binary.to_bytes_exn
Operation.unsigned_encoding
({branch}, Contents_list contents)
in
let signature = Some (Signature.sign ~watermark sk unsigned) in
({shell = {branch}; protocol_data = {contents; signature}} : _ Operation.t)
(** Generates the block payload hash based on the hash [pred_hash] of
the predecessor block and the hash of non-consensus operations of
the current block [b]. *)
let mk_block_payload_hash pred_hash payload_round (b : Block.t) =
let ops = Block.Forge.classify_operations b.operations in
let non_consensus_operations =
List.concat (match List.tl ops with None -> [] | Some l -> l)
in
let hashes = List.map Operation.hash_packed non_consensus_operations in
let non_consensus_operations_hash = Operation_list_hash.compute hashes in
Block_payload.hash
~predecessor:pred_hash
payload_round
non_consensus_operations_hash
(* ctxt is used for getting the branch in sign *)
let endorsement ?delegate ?slot ?level ?round ?block_payload_hash
~endorsed_block ctxt ?(signing_context = ctxt) () =
let pred_hash = match ctxt with Context.B b -> b.hash | _ -> assert false in
(match delegate with
| None -> Context.get_endorser (B endorsed_block)
| Some v -> return v)
>>=? fun (delegate_pkh, slots) ->
let slot =
match slot with None -> Stdlib.List.hd slots | Some slot -> slot
in
(match level with
| None -> Context.get_level (B endorsed_block)
| Some level -> ok level)
>>?= fun level ->
(match round with
| None -> Block.get_round endorsed_block
| Some round -> ok round)
>>?= fun round ->
let block_payload_hash =
match block_payload_hash with
| None -> mk_block_payload_hash pred_hash round endorsed_block
| Some block_payload_hash -> block_payload_hash
in
let consensus_content = {slot; level; round; block_payload_hash} in
let op = Single (Endorsement consensus_content) in
Account.find delegate_pkh >>=? fun delegate ->
return
(sign
~watermark:Operation.(to_watermark (Endorsement Chain_id.zero))
delegate.sk
signing_context
op)
let preendorsement ?delegate ?slot ?level ?round ?block_payload_hash
~endorsed_block ctxt ?(signing_context = ctxt) () =
let pred_hash = match ctxt with Context.B b -> b.hash | _ -> assert false in
(match delegate with
| None -> Context.get_endorser (B endorsed_block)
| Some v -> return v)
>>=? fun (delegate_pkh, slots) ->
let slot =
match slot with None -> Stdlib.List.hd slots | Some slot -> slot
in
(match level with
| None -> Context.get_level (B endorsed_block)
| Some level -> ok level)
>>?= fun level ->
(match round with
| None -> Block.get_round endorsed_block
| Some round -> ok round)
>>?= fun round ->
let block_payload_hash =
match block_payload_hash with
| None -> mk_block_payload_hash pred_hash round endorsed_block
| Some block_payload_hash -> block_payload_hash
in
let consensus_content = {slot; level; round; block_payload_hash} in
let op = Single (Preendorsement consensus_content) in
Account.find delegate_pkh >>=? fun delegate ->
return
(sign
~watermark:Operation.(to_watermark (Preendorsement Chain_id.zero))
delegate.sk
signing_context
op)
let sign ?watermark sk ctxt (Contents_list contents) =
Operation.pack (sign ?watermark sk ctxt contents)
let combine_operations ?public_key ?counter ?spurious_operation ~source ctxt
(packed_operations : packed_operation list) =
assert (match packed_operations with [] -> false | _ :: _ -> true) ;
(* Hypothesis : each operation must have the same branch (is this really true?) *)
let {Tezos_base.Operation.branch} =
(WithExceptions.Option.get ~loc:__LOC__ @@ List.hd packed_operations).shell
in
assert (
List.for_all
(fun {shell = {Tezos_base.Operation.branch = b; _}; _} ->
Block_hash.(branch = b))
packed_operations) ;
(* TODO? : check signatures consistency *)
let unpacked_operations =
List.map
(function
| {Alpha_context.protocol_data = Operation_data {contents; _}; _} -> (
match Contents_list contents with
| Contents_list (Single o) -> Contents o
| Contents_list
(Cons (Manager_operation {operation = Reveal _; _}, Single o))
->
Contents o
| _ -> (* TODO : decent error *) assert false))
packed_operations
in
(match counter with
| Some counter -> return counter
| None -> Context.Contract.counter ctxt source)
>>=? fun counter ->
(* We increment the counter *)
let counter = Z.succ counter in
Context.Contract.manager ctxt source >>=? fun account ->
let public_key = Option.value ~default:account.pk public_key in
(Context.Contract.is_manager_key_revealed ctxt source >|=? function
| false ->
let reveal_op =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee = Tez.zero;
counter;
operation = Reveal public_key;
gas_limit = Gas.Arith.integral_of_int_exn 10_000;
storage_limit = Z.zero;
}
in
(Some (Contents reveal_op), Z.succ counter)
| true -> (None, counter))
>>=? fun (manager_op, counter) ->
Update counters and transform into a contents_list
let operations =
List.fold_left
(fun (counter, acc) -> function
| Contents (Manager_operation m) ->
( Z.succ counter,
Contents (Manager_operation {m with counter}) :: acc )
| x -> (counter, x :: acc))
(counter, match manager_op with None -> [] | Some op -> [op])
unpacked_operations
|> snd |> List.rev
in
(* patch a random operation with a corrupted pkh *)
let operations =
match spurious_operation with
| None -> operations
| Some op -> (
let op =
match op with
| {protocol_data; shell = _} -> (
match protocol_data with
| Operation_data {contents; _} -> (
match contents with
| Cons _ -> assert false
| Single op -> Alpha_context.Contents op))
in
(* Select where to insert spurious op *)
let legit_ops = List.length operations in
let index = Random.int legit_ops in
match List.split_n index operations with
| (preserved_prefix, preserved_suffix) ->
preserved_prefix @ op :: preserved_suffix)
in
Environment.wrap_tzresult @@ Operation.of_list operations
>>?= fun operations -> return @@ sign account.sk ctxt operations
let manager_operation ?counter ?(fee = Tez.zero) ?gas_limit ?storage_limit
?public_key ~source ctxt operation =
(match counter with
| Some counter -> return counter
| None -> Context.Contract.counter ctxt source)
>>=? fun counter ->
Context.get_constants ctxt >>=? fun c ->
let gas_limit =
let default = c.parametric.hard_gas_limit_per_operation in
Option.value ~default gas_limit
in
let storage_limit =
Option.value
~default:c.parametric.hard_storage_limit_per_operation
storage_limit
in
Context.Contract.manager ctxt source >>=? fun account ->
let public_key = Option.value ~default:account.pk public_key in
let counter = Z.succ counter in
Context.Contract.is_manager_key_revealed ctxt source >|=? function
| true ->
let op =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee;
counter;
operation;
gas_limit;
storage_limit;
}
in
Contents_list (Single op)
| false ->
let op_reveal =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee = Tez.zero;
counter;
operation = Reveal public_key;
gas_limit = Gas.Arith.integral_of_int_exn 10000;
storage_limit = Z.zero;
}
in
let op =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee;
counter = Z.succ counter;
operation;
gas_limit;
storage_limit;
}
in
Contents_list (Cons (op_reveal, Single op))
let revelation ?(fee = Tez.zero) ctxt public_key =
let pkh = Signature.Public_key.hash public_key in
let source = Contract.implicit_contract pkh in
Context.Contract.counter ctxt source >>=? fun counter ->
Context.Contract.manager ctxt source >|=? fun account ->
let counter = Z.succ counter in
let sop =
Contents_list
(Single
(Manager_operation
{
source = Signature.Public_key.hash public_key;
fee;
counter;
operation = Reveal public_key;
gas_limit = Gas.Arith.integral_of_int_exn 10000;
storage_limit = Z.zero;
}))
in
sign account.sk ctxt sop
let failing_noop ctxt source arbitrary =
let op = Contents_list (Single (Failing_noop arbitrary)) in
Account.find source >>=? fun account -> return @@ sign account.sk ctxt op
let originated_contract op =
let nonce =
Origination_nonce.Internal_for_tests.initial (Operation.hash_packed op)
in
Contract.Internal_for_tests.originated_contract nonce
exception Impossible
let contract_origination ?counter ?delegate ~script ?(preorigination = None)
?public_key ?credit ?fee ?gas_limit ?storage_limit ctxt source =
Context.Contract.manager ctxt source >>=? fun account ->
let default_credit = Tez.of_mutez @@ Int64.of_int 1000001 in
let default_credit =
WithExceptions.Option.to_exn ~none:Impossible default_credit
in
let credit = Option.value ~default:default_credit credit in
let operation = Origination {delegate; script; credit; preorigination} in
manager_operation
?counter
?public_key
?fee
?gas_limit
?storage_limit
~source
ctxt
operation
>|=? fun sop ->
let op = sign account.sk ctxt sop in
(op, originated_contract op)
let register_global_constant ?counter ?public_key ?fee ?gas_limit ?storage_limit
ctxt ~source ~value =
Context.Contract.manager ctxt source >>=? fun account ->
let operation = Register_global_constant {value} in
manager_operation
?counter
?public_key
?fee
?gas_limit
?storage_limit
~source
ctxt
operation
>|=? fun sop -> sign account.sk ctxt sop
let miss_signed_endorsement ?level ~endorsed_block ctxt =
(match level with None -> Context.get_level ctxt | Some level -> ok level)
>>?= fun level ->
Context.get_endorser ctxt >>=? fun (real_delegate_pkh, slots) ->
let delegate = Account.find_alternate real_delegate_pkh in
endorsement ~delegate:(delegate.pkh, slots) ~level ~endorsed_block ctxt ()
let transaction ?counter ?fee ?gas_limit ?storage_limit
?(parameters = Script.unit_parameter) ?(entrypoint = "default") ctxt
(src : Contract.t) (dst : Contract.t) (amount : Tez.t) =
let top = Transaction {amount; parameters; destination = dst; entrypoint} in
manager_operation ?counter ?fee ?gas_limit ?storage_limit ~source:src ctxt top
>>=? fun sop ->
Context.Contract.manager ctxt src >|=? fun account -> sign account.sk ctxt sop
let delegation ?fee ctxt source dst =
let top = Delegation dst in
manager_operation
?fee
~gas_limit:(Gas.Arith.integral_of_int_exn 1000)
~source
ctxt
top
>>=? fun sop ->
Context.Contract.manager ctxt source >|=? fun account ->
sign account.sk ctxt sop
let set_deposits_limit ?fee ctxt source limit =
let top = Set_deposits_limit limit in
manager_operation
?fee
~gas_limit:(Gas.Arith.integral_of_int_exn 1000)
~source
ctxt
top
>>=? fun sop ->
Context.Contract.manager ctxt source >|=? fun account ->
sign account.sk ctxt sop
let activation ctxt (pkh : Signature.Public_key_hash.t) activation_code =
(match pkh with
| Ed25519 edpkh -> return edpkh
| _ ->
failwith
"Wrong public key hash : %a - Commitments must be activated with an \
Ed25519 encrypted public key hash"
Signature.Public_key_hash.pp
pkh)
>|=? fun id ->
let contents = Single (Activate_account {id; activation_code}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let double_endorsement ctxt op1 op2 =
let contents = Single (Double_endorsement_evidence {op1; op2}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let double_preendorsement ctxt op1 op2 =
let contents = Single (Double_preendorsement_evidence {op1; op2}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let double_baking ctxt bh1 bh2 =
let contents = Single (Double_baking_evidence {bh1; bh2}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let seed_nonce_revelation ctxt level nonce =
{
shell = {branch = Context.branch ctxt};
protocol_data =
Operation_data
{
contents = Single (Seed_nonce_revelation {level; nonce});
signature = None;
};
}
let proposals ctxt (pkh : Contract.t) proposals =
Context.Contract.pkh pkh >>=? fun source ->
Context.Vote.get_current_period ctxt
>>=? fun {voting_period = {index; _}; _} ->
let op = Proposals {source; period = index; proposals} in
Account.find source >|=? fun account ->
sign account.sk ctxt (Contents_list (Single op))
let ballot ctxt (pkh : Contract.t) proposal ballot =
Context.Contract.pkh pkh >>=? fun source ->
Context.Vote.get_current_period ctxt
>>=? fun {voting_period = {index; _}; _} ->
let op = Ballot {source; period = index; proposal; ballot} in
Account.find source >|=? fun account ->
sign account.sk ctxt (Contents_list (Single op))
let dummy_script =
let open Micheline in
Script.
{
code =
lazy_expr
(strip_locations
(Seq
( (),
[
Prim ((), K_parameter, [Prim ((), T_unit, [], [])], []);
Prim ((), K_storage, [Prim ((), T_unit, [], [])], []);
Prim
( (),
K_code,
[
Seq
( (),
[
Prim ((), I_CDR, [], []);
Prim
( (),
I_NIL,
[Prim ((), T_operation, [], [])],
[] );
Prim ((), I_PAIR, [], []);
] );
],
[] );
] )));
storage = lazy_expr (strip_locations (Prim ((), D_Unit, [], [])));
}
let dummy_script_cost = Test_tez.of_mutez_exn 9_500L
let originated_tx_rollup op =
let nonce =
Origination_nonce.Internal_for_tests.initial (Operation.hash_packed op)
in
(nonce, Tx_rollup.Internal_for_tests.originated_tx_rollup nonce)
let tx_rollup_origination ?counter ?fee ?gas_limit ?storage_limit ctxt
(src : Contract.t) =
manager_operation
?counter
?fee
?gas_limit
?storage_limit
~source:src
ctxt
Tx_rollup_origination
>>=? fun to_sign_op ->
Context.Contract.manager ctxt src >|=? fun account ->
let op = sign account.sk ctxt to_sign_op in
(op, originated_tx_rollup op |> snd)
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_alpha/lib_protocol/test/helpers/op.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Generates the block payload hash based on the hash [pred_hash] of
the predecessor block and the hash of non-consensus operations of
the current block [b].
ctxt is used for getting the branch in sign
Hypothesis : each operation must have the same branch (is this really true?)
TODO? : check signatures consistency
TODO : decent error
We increment the counter
patch a random operation with a corrupted pkh
Select where to insert spurious op | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol
open Alpha_context
let sign ?(watermark = Signature.Generic_operation) sk ctxt contents =
let branch = Context.branch ctxt in
let unsigned =
Data_encoding.Binary.to_bytes_exn
Operation.unsigned_encoding
({branch}, Contents_list contents)
in
let signature = Some (Signature.sign ~watermark sk unsigned) in
({shell = {branch}; protocol_data = {contents; signature}} : _ Operation.t)
let mk_block_payload_hash pred_hash payload_round (b : Block.t) =
let ops = Block.Forge.classify_operations b.operations in
let non_consensus_operations =
List.concat (match List.tl ops with None -> [] | Some l -> l)
in
let hashes = List.map Operation.hash_packed non_consensus_operations in
let non_consensus_operations_hash = Operation_list_hash.compute hashes in
Block_payload.hash
~predecessor:pred_hash
payload_round
non_consensus_operations_hash
let endorsement ?delegate ?slot ?level ?round ?block_payload_hash
~endorsed_block ctxt ?(signing_context = ctxt) () =
let pred_hash = match ctxt with Context.B b -> b.hash | _ -> assert false in
(match delegate with
| None -> Context.get_endorser (B endorsed_block)
| Some v -> return v)
>>=? fun (delegate_pkh, slots) ->
let slot =
match slot with None -> Stdlib.List.hd slots | Some slot -> slot
in
(match level with
| None -> Context.get_level (B endorsed_block)
| Some level -> ok level)
>>?= fun level ->
(match round with
| None -> Block.get_round endorsed_block
| Some round -> ok round)
>>?= fun round ->
let block_payload_hash =
match block_payload_hash with
| None -> mk_block_payload_hash pred_hash round endorsed_block
| Some block_payload_hash -> block_payload_hash
in
let consensus_content = {slot; level; round; block_payload_hash} in
let op = Single (Endorsement consensus_content) in
Account.find delegate_pkh >>=? fun delegate ->
return
(sign
~watermark:Operation.(to_watermark (Endorsement Chain_id.zero))
delegate.sk
signing_context
op)
let preendorsement ?delegate ?slot ?level ?round ?block_payload_hash
~endorsed_block ctxt ?(signing_context = ctxt) () =
let pred_hash = match ctxt with Context.B b -> b.hash | _ -> assert false in
(match delegate with
| None -> Context.get_endorser (B endorsed_block)
| Some v -> return v)
>>=? fun (delegate_pkh, slots) ->
let slot =
match slot with None -> Stdlib.List.hd slots | Some slot -> slot
in
(match level with
| None -> Context.get_level (B endorsed_block)
| Some level -> ok level)
>>?= fun level ->
(match round with
| None -> Block.get_round endorsed_block
| Some round -> ok round)
>>?= fun round ->
let block_payload_hash =
match block_payload_hash with
| None -> mk_block_payload_hash pred_hash round endorsed_block
| Some block_payload_hash -> block_payload_hash
in
let consensus_content = {slot; level; round; block_payload_hash} in
let op = Single (Preendorsement consensus_content) in
Account.find delegate_pkh >>=? fun delegate ->
return
(sign
~watermark:Operation.(to_watermark (Preendorsement Chain_id.zero))
delegate.sk
signing_context
op)
let sign ?watermark sk ctxt (Contents_list contents) =
Operation.pack (sign ?watermark sk ctxt contents)
let combine_operations ?public_key ?counter ?spurious_operation ~source ctxt
(packed_operations : packed_operation list) =
assert (match packed_operations with [] -> false | _ :: _ -> true) ;
let {Tezos_base.Operation.branch} =
(WithExceptions.Option.get ~loc:__LOC__ @@ List.hd packed_operations).shell
in
assert (
List.for_all
(fun {shell = {Tezos_base.Operation.branch = b; _}; _} ->
Block_hash.(branch = b))
packed_operations) ;
let unpacked_operations =
List.map
(function
| {Alpha_context.protocol_data = Operation_data {contents; _}; _} -> (
match Contents_list contents with
| Contents_list (Single o) -> Contents o
| Contents_list
(Cons (Manager_operation {operation = Reveal _; _}, Single o))
->
Contents o
packed_operations
in
(match counter with
| Some counter -> return counter
| None -> Context.Contract.counter ctxt source)
>>=? fun counter ->
let counter = Z.succ counter in
Context.Contract.manager ctxt source >>=? fun account ->
let public_key = Option.value ~default:account.pk public_key in
(Context.Contract.is_manager_key_revealed ctxt source >|=? function
| false ->
let reveal_op =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee = Tez.zero;
counter;
operation = Reveal public_key;
gas_limit = Gas.Arith.integral_of_int_exn 10_000;
storage_limit = Z.zero;
}
in
(Some (Contents reveal_op), Z.succ counter)
| true -> (None, counter))
>>=? fun (manager_op, counter) ->
Update counters and transform into a contents_list
let operations =
List.fold_left
(fun (counter, acc) -> function
| Contents (Manager_operation m) ->
( Z.succ counter,
Contents (Manager_operation {m with counter}) :: acc )
| x -> (counter, x :: acc))
(counter, match manager_op with None -> [] | Some op -> [op])
unpacked_operations
|> snd |> List.rev
in
let operations =
match spurious_operation with
| None -> operations
| Some op -> (
let op =
match op with
| {protocol_data; shell = _} -> (
match protocol_data with
| Operation_data {contents; _} -> (
match contents with
| Cons _ -> assert false
| Single op -> Alpha_context.Contents op))
in
let legit_ops = List.length operations in
let index = Random.int legit_ops in
match List.split_n index operations with
| (preserved_prefix, preserved_suffix) ->
preserved_prefix @ op :: preserved_suffix)
in
Environment.wrap_tzresult @@ Operation.of_list operations
>>?= fun operations -> return @@ sign account.sk ctxt operations
let manager_operation ?counter ?(fee = Tez.zero) ?gas_limit ?storage_limit
?public_key ~source ctxt operation =
(match counter with
| Some counter -> return counter
| None -> Context.Contract.counter ctxt source)
>>=? fun counter ->
Context.get_constants ctxt >>=? fun c ->
let gas_limit =
let default = c.parametric.hard_gas_limit_per_operation in
Option.value ~default gas_limit
in
let storage_limit =
Option.value
~default:c.parametric.hard_storage_limit_per_operation
storage_limit
in
Context.Contract.manager ctxt source >>=? fun account ->
let public_key = Option.value ~default:account.pk public_key in
let counter = Z.succ counter in
Context.Contract.is_manager_key_revealed ctxt source >|=? function
| true ->
let op =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee;
counter;
operation;
gas_limit;
storage_limit;
}
in
Contents_list (Single op)
| false ->
let op_reveal =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee = Tez.zero;
counter;
operation = Reveal public_key;
gas_limit = Gas.Arith.integral_of_int_exn 10000;
storage_limit = Z.zero;
}
in
let op =
Manager_operation
{
source = Signature.Public_key.hash public_key;
fee;
counter = Z.succ counter;
operation;
gas_limit;
storage_limit;
}
in
Contents_list (Cons (op_reveal, Single op))
let revelation ?(fee = Tez.zero) ctxt public_key =
let pkh = Signature.Public_key.hash public_key in
let source = Contract.implicit_contract pkh in
Context.Contract.counter ctxt source >>=? fun counter ->
Context.Contract.manager ctxt source >|=? fun account ->
let counter = Z.succ counter in
let sop =
Contents_list
(Single
(Manager_operation
{
source = Signature.Public_key.hash public_key;
fee;
counter;
operation = Reveal public_key;
gas_limit = Gas.Arith.integral_of_int_exn 10000;
storage_limit = Z.zero;
}))
in
sign account.sk ctxt sop
let failing_noop ctxt source arbitrary =
let op = Contents_list (Single (Failing_noop arbitrary)) in
Account.find source >>=? fun account -> return @@ sign account.sk ctxt op
let originated_contract op =
let nonce =
Origination_nonce.Internal_for_tests.initial (Operation.hash_packed op)
in
Contract.Internal_for_tests.originated_contract nonce
exception Impossible
let contract_origination ?counter ?delegate ~script ?(preorigination = None)
?public_key ?credit ?fee ?gas_limit ?storage_limit ctxt source =
Context.Contract.manager ctxt source >>=? fun account ->
let default_credit = Tez.of_mutez @@ Int64.of_int 1000001 in
let default_credit =
WithExceptions.Option.to_exn ~none:Impossible default_credit
in
let credit = Option.value ~default:default_credit credit in
let operation = Origination {delegate; script; credit; preorigination} in
manager_operation
?counter
?public_key
?fee
?gas_limit
?storage_limit
~source
ctxt
operation
>|=? fun sop ->
let op = sign account.sk ctxt sop in
(op, originated_contract op)
let register_global_constant ?counter ?public_key ?fee ?gas_limit ?storage_limit
ctxt ~source ~value =
Context.Contract.manager ctxt source >>=? fun account ->
let operation = Register_global_constant {value} in
manager_operation
?counter
?public_key
?fee
?gas_limit
?storage_limit
~source
ctxt
operation
>|=? fun sop -> sign account.sk ctxt sop
let miss_signed_endorsement ?level ~endorsed_block ctxt =
(match level with None -> Context.get_level ctxt | Some level -> ok level)
>>?= fun level ->
Context.get_endorser ctxt >>=? fun (real_delegate_pkh, slots) ->
let delegate = Account.find_alternate real_delegate_pkh in
endorsement ~delegate:(delegate.pkh, slots) ~level ~endorsed_block ctxt ()
let transaction ?counter ?fee ?gas_limit ?storage_limit
?(parameters = Script.unit_parameter) ?(entrypoint = "default") ctxt
(src : Contract.t) (dst : Contract.t) (amount : Tez.t) =
let top = Transaction {amount; parameters; destination = dst; entrypoint} in
manager_operation ?counter ?fee ?gas_limit ?storage_limit ~source:src ctxt top
>>=? fun sop ->
Context.Contract.manager ctxt src >|=? fun account -> sign account.sk ctxt sop
let delegation ?fee ctxt source dst =
let top = Delegation dst in
manager_operation
?fee
~gas_limit:(Gas.Arith.integral_of_int_exn 1000)
~source
ctxt
top
>>=? fun sop ->
Context.Contract.manager ctxt source >|=? fun account ->
sign account.sk ctxt sop
let set_deposits_limit ?fee ctxt source limit =
let top = Set_deposits_limit limit in
manager_operation
?fee
~gas_limit:(Gas.Arith.integral_of_int_exn 1000)
~source
ctxt
top
>>=? fun sop ->
Context.Contract.manager ctxt source >|=? fun account ->
sign account.sk ctxt sop
let activation ctxt (pkh : Signature.Public_key_hash.t) activation_code =
(match pkh with
| Ed25519 edpkh -> return edpkh
| _ ->
failwith
"Wrong public key hash : %a - Commitments must be activated with an \
Ed25519 encrypted public key hash"
Signature.Public_key_hash.pp
pkh)
>|=? fun id ->
let contents = Single (Activate_account {id; activation_code}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let double_endorsement ctxt op1 op2 =
let contents = Single (Double_endorsement_evidence {op1; op2}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let double_preendorsement ctxt op1 op2 =
let contents = Single (Double_preendorsement_evidence {op1; op2}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let double_baking ctxt bh1 bh2 =
let contents = Single (Double_baking_evidence {bh1; bh2}) in
let branch = Context.branch ctxt in
{
shell = {branch};
protocol_data = Operation_data {contents; signature = None};
}
let seed_nonce_revelation ctxt level nonce =
{
shell = {branch = Context.branch ctxt};
protocol_data =
Operation_data
{
contents = Single (Seed_nonce_revelation {level; nonce});
signature = None;
};
}
let proposals ctxt (pkh : Contract.t) proposals =
Context.Contract.pkh pkh >>=? fun source ->
Context.Vote.get_current_period ctxt
>>=? fun {voting_period = {index; _}; _} ->
let op = Proposals {source; period = index; proposals} in
Account.find source >|=? fun account ->
sign account.sk ctxt (Contents_list (Single op))
let ballot ctxt (pkh : Contract.t) proposal ballot =
Context.Contract.pkh pkh >>=? fun source ->
Context.Vote.get_current_period ctxt
>>=? fun {voting_period = {index; _}; _} ->
let op = Ballot {source; period = index; proposal; ballot} in
Account.find source >|=? fun account ->
sign account.sk ctxt (Contents_list (Single op))
let dummy_script =
let open Micheline in
Script.
{
code =
lazy_expr
(strip_locations
(Seq
( (),
[
Prim ((), K_parameter, [Prim ((), T_unit, [], [])], []);
Prim ((), K_storage, [Prim ((), T_unit, [], [])], []);
Prim
( (),
K_code,
[
Seq
( (),
[
Prim ((), I_CDR, [], []);
Prim
( (),
I_NIL,
[Prim ((), T_operation, [], [])],
[] );
Prim ((), I_PAIR, [], []);
] );
],
[] );
] )));
storage = lazy_expr (strip_locations (Prim ((), D_Unit, [], [])));
}
let dummy_script_cost = Test_tez.of_mutez_exn 9_500L
let originated_tx_rollup op =
let nonce =
Origination_nonce.Internal_for_tests.initial (Operation.hash_packed op)
in
(nonce, Tx_rollup.Internal_for_tests.originated_tx_rollup nonce)
let tx_rollup_origination ?counter ?fee ?gas_limit ?storage_limit ctxt
(src : Contract.t) =
manager_operation
?counter
?fee
?gas_limit
?storage_limit
~source:src
ctxt
Tx_rollup_origination
>>=? fun to_sign_op ->
Context.Contract.manager ctxt src >|=? fun account ->
let op = sign account.sk ctxt to_sign_op in
(op, originated_tx_rollup op |> snd)
|
32301cfd8a39cffe999f71a2d345c60050e12f60db8d5039f3507e20a7b04a2c | shayan-najd/QFeldspar | Lifting.hs | module QFeldspar.Expression.Conversions.Lifting (cnvHOFOF,cnvFOHO,cnvFOHOF) where
import QFeldspar.MyPrelude
import QFeldspar.Conversion
import QFeldspar.Singleton
import QFeldspar.Variable.Typed as VT
import QFeldspar.Environment.Typed as ET
import qualified QFeldspar.Expression.GADTFirstOrder as GFO
import qualified QFeldspar.Expression.GADTHigherOrder as GHO
import qualified QFeldspar.Type.GADT as TG
import qualified QFeldspar.Environment.Plain as EP
import qualified QFeldspar.Nat.ADT as NA
import QFeldspar.Variable.Conversion ()
instance (a ~ a' , s ~ s') =>
Cnv (GFO.Exp s '[] a , r) (GHO.Exp s' a') where
cnv (e , _) = pure (cnvFOHO e)
instance (TG.Type a , a ~ a' , s ~ s') =>
Cnv (GHO.Exp s a , Env TG.Typ s) (GFO.Exp s' '[] a') where
cnv (e , s) = pure (cnvHOFO s e)
cnvFOHO :: GFO.Exp s '[] a -> GHO.Exp s a
cnvFOHO e = cnvFOHO' Emp e
cnvFOHOF :: GFO.Exp s '[a] b ->
(GHO.Exp s a -> GHO.Exp s b)
cnvFOHOF e = cnvFOHO'F Emp e
cnvHOFO :: TG.Type a =>
Env TG.Typ s -> GHO.Exp s a -> GFO.Exp s '[] a
cnvHOFO s e = cnvHOFO' [] s e
cnvHOFOF :: (TG.Type a, TG.Type b) =>
Env TG.Typ s -> (GHO.Exp s a -> GHO.Exp s b) -> GFO.Exp s '[a] b
cnvHOFOF s f = cnvHOFO'F [] s f
type VarEnv g = EP.Env (Exs1 (Var g) TG.Typ)
incEP :: VarEnv g -> VarEnv (a ': g)
incEP [] = []
incEP ((Exs1 v t) : vs) = (Exs1 (Suc v) t) : incEP vs
cnvFOHO' :: forall s g a.
Env (GHO.Exp s) g -> GFO.Exp s g a -> GHO.Exp s a
cnvFOHO' g ee = case ee of
GFO.Var x -> ET.get x g
_ -> $(biGenOverloaded 'ee ''GFO.Exp "GHO" ['GFO.Var]
(\ tt -> if
| matchQ tt [t| Env (GFO.Exp a a) a |] -> [| ET.fmap (cnvFOHO' g) |]
| matchQ tt [t| GFO.Exp a (a ': a) a |] -> [| cnvFOHO'F g |]
| matchQ tt [t| GFO.Exp a a a |] -> [| cnvFOHO' g |]
| otherwise -> [| id |]))
cnvFOHO'F :: Env (GHO.Exp s) g -> GFO.Exp s (a ': g) b ->
(GHO.Exp s a -> GHO.Exp s b)
cnvFOHO'F g f = (\ x -> cnvFOHO' (Ext x g) f)
cnvHOFO' :: forall s g a. TG.Type a =>
VarEnv g -> Env TG.Typ s -> GHO.Exp s a -> GFO.Exp s g a
cnvHOFO' g s ee = let t = sin :: TG.Typ a in case ee of
GHO.Tmp x -> case frmRgt (EP.get (let v' :: NA.Nat = NA.natStr x
in ((EP.len g) `NA.sub` (NA.Suc NA.Zro)) `NA.sub` v') g) of
Exs1 v' t' -> case frmRgt (eqlSin t t') of
Rfl -> GFO.Var v'
GHO.Prm v es -> GFO.Prm v (TG.mapC (cnvHOFO' g s) es)
_ -> $(biGenOverloaded 'ee ''GHO.Exp "GFO" ['GHO.Prm,'GHO.Tmp]
(\ tt -> if
| matchQ tt [t| GHO.Exp a a -> GHO.Exp a a |] -> [| cnvHOFO'F g s |]
| matchQ tt [t| GHO.Exp a a |] -> [| cnvHOFO' g s |]
| otherwise -> [| id |]))
cnvHOFO'F :: forall a b s g.
(TG.Type a, TG.Type b) =>
VarEnv g -> Env TG.Typ s -> (GHO.Exp s a -> GHO.Exp s b) -> GFO.Exp s (a ': g) b
cnvHOFO'F g s f = let tag = GHO.Tmp (show (EP.len g))
in cnvHOFO' (EP.Ext (Exs1 Zro (sin :: TG.Typ a)) (incEP g)) s (f tag)
| null | https://raw.githubusercontent.com/shayan-najd/QFeldspar/ed60ce02794a548833317388f6e82e2ab1eabc1c/QFeldspar/Expression/Conversions/Lifting.hs | haskell | module QFeldspar.Expression.Conversions.Lifting (cnvHOFOF,cnvFOHO,cnvFOHOF) where
import QFeldspar.MyPrelude
import QFeldspar.Conversion
import QFeldspar.Singleton
import QFeldspar.Variable.Typed as VT
import QFeldspar.Environment.Typed as ET
import qualified QFeldspar.Expression.GADTFirstOrder as GFO
import qualified QFeldspar.Expression.GADTHigherOrder as GHO
import qualified QFeldspar.Type.GADT as TG
import qualified QFeldspar.Environment.Plain as EP
import qualified QFeldspar.Nat.ADT as NA
import QFeldspar.Variable.Conversion ()
instance (a ~ a' , s ~ s') =>
Cnv (GFO.Exp s '[] a , r) (GHO.Exp s' a') where
cnv (e , _) = pure (cnvFOHO e)
instance (TG.Type a , a ~ a' , s ~ s') =>
Cnv (GHO.Exp s a , Env TG.Typ s) (GFO.Exp s' '[] a') where
cnv (e , s) = pure (cnvHOFO s e)
cnvFOHO :: GFO.Exp s '[] a -> GHO.Exp s a
cnvFOHO e = cnvFOHO' Emp e
cnvFOHOF :: GFO.Exp s '[a] b ->
(GHO.Exp s a -> GHO.Exp s b)
cnvFOHOF e = cnvFOHO'F Emp e
cnvHOFO :: TG.Type a =>
Env TG.Typ s -> GHO.Exp s a -> GFO.Exp s '[] a
cnvHOFO s e = cnvHOFO' [] s e
cnvHOFOF :: (TG.Type a, TG.Type b) =>
Env TG.Typ s -> (GHO.Exp s a -> GHO.Exp s b) -> GFO.Exp s '[a] b
cnvHOFOF s f = cnvHOFO'F [] s f
type VarEnv g = EP.Env (Exs1 (Var g) TG.Typ)
incEP :: VarEnv g -> VarEnv (a ': g)
incEP [] = []
incEP ((Exs1 v t) : vs) = (Exs1 (Suc v) t) : incEP vs
cnvFOHO' :: forall s g a.
Env (GHO.Exp s) g -> GFO.Exp s g a -> GHO.Exp s a
cnvFOHO' g ee = case ee of
GFO.Var x -> ET.get x g
_ -> $(biGenOverloaded 'ee ''GFO.Exp "GHO" ['GFO.Var]
(\ tt -> if
| matchQ tt [t| Env (GFO.Exp a a) a |] -> [| ET.fmap (cnvFOHO' g) |]
| matchQ tt [t| GFO.Exp a (a ': a) a |] -> [| cnvFOHO'F g |]
| matchQ tt [t| GFO.Exp a a a |] -> [| cnvFOHO' g |]
| otherwise -> [| id |]))
cnvFOHO'F :: Env (GHO.Exp s) g -> GFO.Exp s (a ': g) b ->
(GHO.Exp s a -> GHO.Exp s b)
cnvFOHO'F g f = (\ x -> cnvFOHO' (Ext x g) f)
cnvHOFO' :: forall s g a. TG.Type a =>
VarEnv g -> Env TG.Typ s -> GHO.Exp s a -> GFO.Exp s g a
cnvHOFO' g s ee = let t = sin :: TG.Typ a in case ee of
GHO.Tmp x -> case frmRgt (EP.get (let v' :: NA.Nat = NA.natStr x
in ((EP.len g) `NA.sub` (NA.Suc NA.Zro)) `NA.sub` v') g) of
Exs1 v' t' -> case frmRgt (eqlSin t t') of
Rfl -> GFO.Var v'
GHO.Prm v es -> GFO.Prm v (TG.mapC (cnvHOFO' g s) es)
_ -> $(biGenOverloaded 'ee ''GHO.Exp "GFO" ['GHO.Prm,'GHO.Tmp]
(\ tt -> if
| matchQ tt [t| GHO.Exp a a -> GHO.Exp a a |] -> [| cnvHOFO'F g s |]
| matchQ tt [t| GHO.Exp a a |] -> [| cnvHOFO' g s |]
| otherwise -> [| id |]))
cnvHOFO'F :: forall a b s g.
(TG.Type a, TG.Type b) =>
VarEnv g -> Env TG.Typ s -> (GHO.Exp s a -> GHO.Exp s b) -> GFO.Exp s (a ': g) b
cnvHOFO'F g s f = let tag = GHO.Tmp (show (EP.len g))
in cnvHOFO' (EP.Ext (Exs1 Zro (sin :: TG.Typ a)) (incEP g)) s (f tag)
| |
674fad9ce83dcd92596ac2dad82035041c1a701e2b1f750bc254dcad229571f9 | mzp/coq-for-ipad | jg_config.mli | (*************************************************************************)
(* *)
(* 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. *)
(* *)
(*************************************************************************)
$ I d : 2001 - 12 - 07 13:41:02Z xleroy $
val init: unit -> unit
| null | https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/otherlibs/labltk/browser/jg_config.mli | ocaml | ***********************************************************************
Objective Caml LablTk library
General Public License, with the special exception on linking
described in file ../../../LICENSE.
*********************************************************************** | , 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
$ I d : 2001 - 12 - 07 13:41:02Z xleroy $
val init: unit -> unit
|
203d916cede670f328ce1f4455a9d64532be73f459ca310a950e7ef996b52bfe | pascal-knodel/haskell-craft | SelfComposition.hs | -- Self composition of an unary function. Primitive Recursion.
module SelfComposition where
selfCompose :: Integer -> (a -> a) -> (a -> a)
selfCompose 0 _ = id
selfCompose times function
= function . selfCompose (times - 1) function
GHCi >
( selfCompose 0 ( + 1 ) ) 1
( selfCompose 1 ( + 1 ) ) 1
( selfCompose 2 ( + 1 ) ) 1
( selfCompose 0 (+ 1) ) 1
( selfCompose 1 (+ 1) ) 1
( selfCompose 2 (+ 1) ) 1
-}
1
2
3
| null | https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/Examples/%C2%B7%C2%A0Recursion/%C2%B7%20Primitive%20Recursion/Higher%20Order%20Functions/SelfComposition.hs | haskell | Self composition of an unary function. Primitive Recursion. | module SelfComposition where
selfCompose :: Integer -> (a -> a) -> (a -> a)
selfCompose 0 _ = id
selfCompose times function
= function . selfCompose (times - 1) function
GHCi >
( selfCompose 0 ( + 1 ) ) 1
( selfCompose 1 ( + 1 ) ) 1
( selfCompose 2 ( + 1 ) ) 1
( selfCompose 0 (+ 1) ) 1
( selfCompose 1 (+ 1) ) 1
( selfCompose 2 (+ 1) ) 1
-}
1
2
3
|
4e2755f25a0889cbb7110afe6a8c1f6abc2588ce98b8db2884472caff1fbb9c4 | arttuka/reagent-material-ui | face_4.cljs | (ns reagent-mui.icons.face-4
"Imports @mui/icons-material/Face4 as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def face-4 (create-svg-icon [(e "path" #js {"d" "M12 2c-.96 0-1.88.14-2.75.39C8.37.96 6.8 0 5 0 2.24 0 0 2.24 0 5c0 1.8.96 3.37 2.39 4.25C2.14 10.12 2 11.04 2 12c0 5.52 4.48 10 10 10s10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8 0-.05.01-.1.01-.15 2.6-.98 4.68-2.99 5.74-5.55 1.83 2.26 4.62 3.7 7.75 3.7.75 0 1.47-.09 2.17-.24.21.71.33 1.46.33 2.24 0 4.41-3.59 8-8 8z"}) (e "circle" #js {"cx" "9", "cy" "13", "r" "1.25"}) (e "circle" #js {"cx" "15", "cy" "13", "r" "1.25"})]
"Face4"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/face_4.cljs | clojure | (ns reagent-mui.icons.face-4
"Imports @mui/icons-material/Face4 as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def face-4 (create-svg-icon [(e "path" #js {"d" "M12 2c-.96 0-1.88.14-2.75.39C8.37.96 6.8 0 5 0 2.24 0 0 2.24 0 5c0 1.8.96 3.37 2.39 4.25C2.14 10.12 2 11.04 2 12c0 5.52 4.48 10 10 10s10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8 0-.05.01-.1.01-.15 2.6-.98 4.68-2.99 5.74-5.55 1.83 2.26 4.62 3.7 7.75 3.7.75 0 1.47-.09 2.17-.24.21.71.33 1.46.33 2.24 0 4.41-3.59 8-8 8z"}) (e "circle" #js {"cx" "9", "cy" "13", "r" "1.25"}) (e "circle" #js {"cx" "15", "cy" "13", "r" "1.25"})]
"Face4"))
| |
b2f7c46fd32f237747271b90c4fd11f79e29ccaf9dc7d2004eb12779b55c8427 | futurice/haskell-mega-repo | ScheduleEmployee.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE InstanceSigs #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
-- | TODO move to personio-proxy
module Personio.Types.ScheduleEmployee where
import FUM.Types.Login
import Futurice.Email
import Futurice.Generics
import Futurice.Prelude
import Prelude ()
import Personio.Types.Employee
import Personio.Types.EmployeeId
import qualified Data.Map.Strict as Map
data ScheduleEmployee = ScheduleEmployee
{ _seEmployeeId :: !EmployeeId
, _seLogin :: !Login
, _seName :: !Text
, _seEmail :: !(Maybe Email)
, _seSupervisorLogin :: !(Maybe Login)
, _seSupervisorName :: !(Maybe Text)
, _seSupervisorEmail :: !(Maybe Email)
, _seHrnumber :: !(Maybe Int)
, _seFutubuddy :: !(Maybe Email)
}
deriving (Show, Typeable, GhcGeneric, SopGeneric, HasDatatypeInfo)
deriving (ToJSON, FromJSON) via (Sopica ScheduleEmployee)
makeLenses ''ScheduleEmployee
instance ToSchema ScheduleEmployee where declareNamedSchema = sopDeclareNamedSchema
fromPersonio :: [Employee] -> [ScheduleEmployee]
fromPersonio es = map mk es
where
m :: Map EmployeeId Employee
m = Map.fromList $ map (\e -> (e ^. employeeId, e)) es
mk :: Employee -> ScheduleEmployee
mk e = ScheduleEmployee
{ _seEmployeeId = e ^. employeeId
, _seLogin = e ^. employeeLogin
, _seName = e ^. employeeFullname
, _seEmail = e ^. employeeEmail
, _seSupervisorLogin = withSupervisor $ \s -> Just $ s ^. employeeLogin
, _seSupervisorName = withSupervisor $ \s -> s ^? employeeFullname
, _seSupervisorEmail = withSupervisor $ \s -> s ^. employeeEmail
, _seHrnumber = e ^. employeeHRNumber
, _seFutubuddy = e ^. employeeFutubuddy
}
where
withSupervisor :: (Employee -> Maybe a) -> Maybe a
withSupervisor f = do
sid <- e ^. employeeSupervisorId
s <- m ^? ix sid
f s
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/95fe8e33ad6426eb6e52a9c23db4aeffd443b3e5/personio-client/src/Personio/Types/ScheduleEmployee.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
| TODO move to personio-proxy | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE InstanceSigs #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
module Personio.Types.ScheduleEmployee where
import FUM.Types.Login
import Futurice.Email
import Futurice.Generics
import Futurice.Prelude
import Prelude ()
import Personio.Types.Employee
import Personio.Types.EmployeeId
import qualified Data.Map.Strict as Map
data ScheduleEmployee = ScheduleEmployee
{ _seEmployeeId :: !EmployeeId
, _seLogin :: !Login
, _seName :: !Text
, _seEmail :: !(Maybe Email)
, _seSupervisorLogin :: !(Maybe Login)
, _seSupervisorName :: !(Maybe Text)
, _seSupervisorEmail :: !(Maybe Email)
, _seHrnumber :: !(Maybe Int)
, _seFutubuddy :: !(Maybe Email)
}
deriving (Show, Typeable, GhcGeneric, SopGeneric, HasDatatypeInfo)
deriving (ToJSON, FromJSON) via (Sopica ScheduleEmployee)
makeLenses ''ScheduleEmployee
instance ToSchema ScheduleEmployee where declareNamedSchema = sopDeclareNamedSchema
fromPersonio :: [Employee] -> [ScheduleEmployee]
fromPersonio es = map mk es
where
m :: Map EmployeeId Employee
m = Map.fromList $ map (\e -> (e ^. employeeId, e)) es
mk :: Employee -> ScheduleEmployee
mk e = ScheduleEmployee
{ _seEmployeeId = e ^. employeeId
, _seLogin = e ^. employeeLogin
, _seName = e ^. employeeFullname
, _seEmail = e ^. employeeEmail
, _seSupervisorLogin = withSupervisor $ \s -> Just $ s ^. employeeLogin
, _seSupervisorName = withSupervisor $ \s -> s ^? employeeFullname
, _seSupervisorEmail = withSupervisor $ \s -> s ^. employeeEmail
, _seHrnumber = e ^. employeeHRNumber
, _seFutubuddy = e ^. employeeFutubuddy
}
where
withSupervisor :: (Employee -> Maybe a) -> Maybe a
withSupervisor f = do
sid <- e ^. employeeSupervisorId
s <- m ^? ix sid
f s
|
7270f85ccfb10afd99f38bf450deee506f04ba7a0491822aa101057f7299fb35 | matijapretnar/eff | graphs.ml | open Bechamel
open Toolkit
let instance = Instance.monotonic_clock
let limit = 5000
let second_quota = 10.0
module StringMap = Map.Make (String)
module IntMap = Map.Make (Int)
let measure_benchmark benchmark baseline =
let ols =
Analyze.ols ~bootstrap:0 ~r_square:true ~predictors:Measure.[| run |]
in
let cfg = Benchmark.cfg ~limit ~quota:(Time.second second_quota) () in
let raw_results = Benchmark.all cfg [ instance ] benchmark in
let analyzed_results =
List.map (fun instance -> Analyze.all ols instance raw_results) [ instance ]
in
let merged_results = Analyze.merge ols [ instance ] analyzed_results in
let benchmark_results =
Hashtbl.fold
(fun instance_label instance_result benchmark_results ->
let instance_results =
Hashtbl.fold
(fun case_label case_estimates instance_results ->
match Analyze.OLS.estimates case_estimates with
| Some [ case_result ] ->
StringMap.add case_label case_result instance_results
| _ -> assert false)
instance_result StringMap.empty
in
(instance_label, instance_results) :: benchmark_results)
merged_results []
in
let instance_results =
match benchmark_results with
| [ (_instance_label, instance_results) ] -> instance_results
| _ -> assert false
in
let baseline_result = StringMap.find baseline instance_results in
let slowdowns =
StringMap.map (fun result -> result /. baseline_result) instance_results
in
slowdowns
let transpose_nested_map map_by_a_by_b =
IntMap.fold
(fun a of_a map_by_b_by_a ->
StringMap.fold
(fun b v map_by_b_by_a ->
let of_b =
StringMap.find_opt b map_by_b_by_a
|> Option.value ~default:IntMap.empty
in
let of_b' = IntMap.add a v of_b in
StringMap.add b of_b' map_by_b_by_a)
of_a map_by_b_by_a)
map_by_a_by_b StringMap.empty
let measure_benchmark_set
(benchmark_set : 'a Benchmark_suite.Benchmark_config.benchmark_set) =
let baseline =
match benchmark_set.benchmarks with
| (baseline, _) :: _ -> baseline
| _ -> assert false
in
let measure_at_param param =
print_int param;
flush_all ();
let benchmark_at_param =
Test.make_grouped ~name:"" ~fmt:"%s%s"
(List.map
(fun (name, fn) ->
Test.make ~name (Staged.stage (fun () -> ignore (fn param))))
benchmark_set.benchmarks)
in
measure_benchmark benchmark_at_param baseline
in
let results_by_param =
List.fold_left
(fun measurements param ->
IntMap.add param (measure_at_param param) measurements)
IntMap.empty benchmark_set.parameters
in
transpose_nested_map results_by_param
let display_benchmark_set_results
(set : 'a Benchmark_suite.Benchmark_config.benchmark_set) benchmark_results
=
StringMap.iter
(fun test_label test_results ->
let chan =
open_out (Printf.sprintf "tables/%s-%s.table" set.filename test_label)
in
Printf.fprintf chan "# %s: %s\n" set.name test_label;
IntMap.iter
(fun param slowdown -> Printf.fprintf chan "%d %.2f\n" param slowdown)
test_results;
close_out chan)
benchmark_results;
print_newline ()
let run_benchmark_set (set : 'a Benchmark_suite.Benchmark_config.benchmark_set)
=
print_endline set.name;
let results = measure_benchmark_set set in
display_benchmark_set_results set results
let suite = Benchmark_suite.Config.test_suite
let _ = run_benchmark_set suite.loop_benchmarks
let _ = run_benchmark_set suite.loop_latent_benchmarks
let _ = run_benchmark_set suite.loop_incr_benchmark
let _ = run_benchmark_set suite.loop_incr'_benchmark
let _ = run_benchmark_set suite.loop_state_benchmark
let _ = run_benchmark_set suite.queens_one_benchmark
let _ = run_benchmark_set suite.queens_all_benchmark
let _ = run_benchmark_set suite.interpreter_benchmark
let _ = run_benchmark_set suite.interpreter_state_benchmark
let _ = run_benchmark_set suite.range_benchmarks
let _ = run_benchmark_set suite.tree_benchmark
let _ = run_benchmark_set suite.loop_pure_optimizer
let _ = run_benchmark_set suite.loop_incr_optimizer
let _ = run_benchmark_set suite.loop_latent_optimizer
let _ = run_benchmark_set suite.loop_state_optimizer
| null | https://raw.githubusercontent.com/matijapretnar/eff/0b0ec7a83e7db4d040ed8fdfc1ac6e3c0f344be1/misc/code-generation-benchmarks/generate-graphs/graphs.ml | ocaml | open Bechamel
open Toolkit
let instance = Instance.monotonic_clock
let limit = 5000
let second_quota = 10.0
module StringMap = Map.Make (String)
module IntMap = Map.Make (Int)
let measure_benchmark benchmark baseline =
let ols =
Analyze.ols ~bootstrap:0 ~r_square:true ~predictors:Measure.[| run |]
in
let cfg = Benchmark.cfg ~limit ~quota:(Time.second second_quota) () in
let raw_results = Benchmark.all cfg [ instance ] benchmark in
let analyzed_results =
List.map (fun instance -> Analyze.all ols instance raw_results) [ instance ]
in
let merged_results = Analyze.merge ols [ instance ] analyzed_results in
let benchmark_results =
Hashtbl.fold
(fun instance_label instance_result benchmark_results ->
let instance_results =
Hashtbl.fold
(fun case_label case_estimates instance_results ->
match Analyze.OLS.estimates case_estimates with
| Some [ case_result ] ->
StringMap.add case_label case_result instance_results
| _ -> assert false)
instance_result StringMap.empty
in
(instance_label, instance_results) :: benchmark_results)
merged_results []
in
let instance_results =
match benchmark_results with
| [ (_instance_label, instance_results) ] -> instance_results
| _ -> assert false
in
let baseline_result = StringMap.find baseline instance_results in
let slowdowns =
StringMap.map (fun result -> result /. baseline_result) instance_results
in
slowdowns
let transpose_nested_map map_by_a_by_b =
IntMap.fold
(fun a of_a map_by_b_by_a ->
StringMap.fold
(fun b v map_by_b_by_a ->
let of_b =
StringMap.find_opt b map_by_b_by_a
|> Option.value ~default:IntMap.empty
in
let of_b' = IntMap.add a v of_b in
StringMap.add b of_b' map_by_b_by_a)
of_a map_by_b_by_a)
map_by_a_by_b StringMap.empty
let measure_benchmark_set
(benchmark_set : 'a Benchmark_suite.Benchmark_config.benchmark_set) =
let baseline =
match benchmark_set.benchmarks with
| (baseline, _) :: _ -> baseline
| _ -> assert false
in
let measure_at_param param =
print_int param;
flush_all ();
let benchmark_at_param =
Test.make_grouped ~name:"" ~fmt:"%s%s"
(List.map
(fun (name, fn) ->
Test.make ~name (Staged.stage (fun () -> ignore (fn param))))
benchmark_set.benchmarks)
in
measure_benchmark benchmark_at_param baseline
in
let results_by_param =
List.fold_left
(fun measurements param ->
IntMap.add param (measure_at_param param) measurements)
IntMap.empty benchmark_set.parameters
in
transpose_nested_map results_by_param
let display_benchmark_set_results
(set : 'a Benchmark_suite.Benchmark_config.benchmark_set) benchmark_results
=
StringMap.iter
(fun test_label test_results ->
let chan =
open_out (Printf.sprintf "tables/%s-%s.table" set.filename test_label)
in
Printf.fprintf chan "# %s: %s\n" set.name test_label;
IntMap.iter
(fun param slowdown -> Printf.fprintf chan "%d %.2f\n" param slowdown)
test_results;
close_out chan)
benchmark_results;
print_newline ()
let run_benchmark_set (set : 'a Benchmark_suite.Benchmark_config.benchmark_set)
=
print_endline set.name;
let results = measure_benchmark_set set in
display_benchmark_set_results set results
let suite = Benchmark_suite.Config.test_suite
let _ = run_benchmark_set suite.loop_benchmarks
let _ = run_benchmark_set suite.loop_latent_benchmarks
let _ = run_benchmark_set suite.loop_incr_benchmark
let _ = run_benchmark_set suite.loop_incr'_benchmark
let _ = run_benchmark_set suite.loop_state_benchmark
let _ = run_benchmark_set suite.queens_one_benchmark
let _ = run_benchmark_set suite.queens_all_benchmark
let _ = run_benchmark_set suite.interpreter_benchmark
let _ = run_benchmark_set suite.interpreter_state_benchmark
let _ = run_benchmark_set suite.range_benchmarks
let _ = run_benchmark_set suite.tree_benchmark
let _ = run_benchmark_set suite.loop_pure_optimizer
let _ = run_benchmark_set suite.loop_incr_optimizer
let _ = run_benchmark_set suite.loop_latent_optimizer
let _ = run_benchmark_set suite.loop_state_optimizer
| |
2042203be8fdc818c5366df6cc473350ae1dc2dafa709fbe4524be8633724210 | afiniate/aws_async | awsa_sign.ml | open Core.Std
open Cryptokit
let algo = "AWS4-HMAC-SHA256"
let hex_encode x =
let nibble x =
char_of_int (if x < 10
then int_of_char '0' + x
else int_of_char 'a' + (x - 10)) in
let result = String.make (String.length x * 2) ' ' in
for i = 0 to String.length x - 1 do
let byte = int_of_char x.[i] in
result.[i * 2 + 0] <- nibble((byte lsr 4) land 15);
result.[i * 2 + 1] <- nibble((byte lsr 0) land 15);
done;
result
let hash value =
let hasher = Hash.sha256 () in
hasher#add_string value;
hex_encode hasher#result
let sign key value =
let hash_fun = MAC.hmac_sha256 key in
hash_string hash_fun value
let sys_sign sys body =
let hashed_body = sign sys.Awsa_base.secret_access_key body in
hex_encode hashed_body
let sign_encode key value =
hex_encode (sign key value)
| null | https://raw.githubusercontent.com/afiniate/aws_async/44c27bf9f18f76e9e6405c2252098c4aa3d9a8bc/lib/auth/awsa_sign.ml | ocaml | open Core.Std
open Cryptokit
let algo = "AWS4-HMAC-SHA256"
let hex_encode x =
let nibble x =
char_of_int (if x < 10
then int_of_char '0' + x
else int_of_char 'a' + (x - 10)) in
let result = String.make (String.length x * 2) ' ' in
for i = 0 to String.length x - 1 do
let byte = int_of_char x.[i] in
result.[i * 2 + 0] <- nibble((byte lsr 4) land 15);
result.[i * 2 + 1] <- nibble((byte lsr 0) land 15);
done;
result
let hash value =
let hasher = Hash.sha256 () in
hasher#add_string value;
hex_encode hasher#result
let sign key value =
let hash_fun = MAC.hmac_sha256 key in
hash_string hash_fun value
let sys_sign sys body =
let hashed_body = sign sys.Awsa_base.secret_access_key body in
hex_encode hashed_body
let sign_encode key value =
hex_encode (sign key value)
| |
f1483edd623aa1d969ceff70dc2d28e65cdcdb9a50d4853dd4e5749a55045f60 | ghc/ghc | T19847a.hs | # LANGUAGE LambdaCase , GADTs , ScopedTypeVariables , TypeAbstractions #
module T19847a where
data T a b c where
MkT :: forall c y x b. (x~y, c~[x], Ord x) => x -> y -> T (x,y) b c
f :: forall b c. (T (Int,Int) b c -> Bool) -> (b,c)
f = error "urk"
h = f (\case { MkT @_ @_ @_ @Int p q -> True })
-- Check that the @Int argument can affect
-- the type at which `f` is instantiated
-- So h :: forall c. (Int,c)
| null | https://raw.githubusercontent.com/ghc/ghc/354aa47d313113855aff9e5c5476fcb56f80e3bf/testsuite/tests/gadt/T19847a.hs | haskell | Check that the @Int argument can affect
the type at which `f` is instantiated
So h :: forall c. (Int,c) | # LANGUAGE LambdaCase , GADTs , ScopedTypeVariables , TypeAbstractions #
module T19847a where
data T a b c where
MkT :: forall c y x b. (x~y, c~[x], Ord x) => x -> y -> T (x,y) b c
f :: forall b c. (T (Int,Int) b c -> Bool) -> (b,c)
f = error "urk"
h = f (\case { MkT @_ @_ @_ @Int p q -> True })
|
e3b0190fab13fc6d7688fc23129344153277b5189ea0196f2f6fd0a2da7f9c8b | coalton-lang/coalton | red-black-tests.lisp | (cl:in-package #:coalton-native-tests)
;; invariant checking
(coalton-toplevel
(define-type (InvariantError :elt)
(RedWithRedLeftChild (red-black/tree:Tree :elt))
(RedWithRedRightChild (red-black/tree:Tree :elt))
(DifferentCountToBlack UFix (red-black/tree:Tree :elt)
UFix (red-black/tree:Tree :elt))
(BothChildrenErrors (InvariantError :elt) (InvariantError :elt))
(IllegalColor (red-black/tree:Tree :elt)))
(declare count-blacks-to-leaf ((red-black/tree:Tree :elt) -> (Result (InvariantError :elt) UFix)))
(define (count-blacks-to-leaf tre)
(match tre
((red-black/tree:Empty) (Ok 0))
((red-black/tree::Branch (red-black/tree::Red)
(red-black/tree::Branch (red-black/tree::Red) _ _ _)
_
_)
(Err (RedWithRedLeftChild tre)))
((red-black/tree::Branch (red-black/tree::Red)
_
_
(red-black/tree::Branch (red-black/tree::Red) _ _ _))
(Err (RedWithRedRightChild tre)))
((red-black/tree::Branch c left _ right)
(match (Tuple (count-blacks-to-leaf left)
(count-blacks-to-leaf right))
((Tuple (Err left-err) (Err right-err))
(Err (BothChildrenErrors left-err right-err)))
((Tuple (Err left-err) _)
(Err left-err))
((Tuple _ (Err right-err))
(Err right-err))
((Tuple (Ok left-ct) (Ok right-ct))
(if (== left-ct right-ct)
(match c
((red-black/tree::Black) (Ok (+ left-ct 1)))
((red-black/tree::Red) (Ok left-ct))
(_ (Err (IllegalColor tre))))
(Err (DifferentCountToBlack left-ct left
right-ct right))))))
(_ (Err (IllegalColor tre))))))
(coalton-toplevel
(declare random-below! (UFix -> UFix))
(define (random-below! limit)
(lisp UFix (limit)
(cl:random limit)))
(declare random! (Unit -> UFix))
(define (random!)
(random-below! (lisp UFix () cl:most-positive-fixnum)))
(declare random-iter! (UFix -> (iter:Iterator UFix)))
(define (random-iter! length)
(map (fn (_) (random!))
(iter:up-to length))))
(define-test tree-from-iter-equiv-to-manual-construction ()
(let manual = (red-black/tree:insert-or-replace
(red-black/tree:insert-or-replace
(red-black/tree:insert-or-replace red-black/tree:Empty
5)
11)
2))
(let iterated = (red-black/tree:collect! (iter:into-iter (the (List Integer)
(make-list 5 11 2)))))
(is (== manual iterated))
(is (== (hash manual) (hash iterated))))
(define-test tree-always-increasing-order ()
(let increasing? = (fn (lst)
(== (list:sort lst) lst)))
(let random-tree! = (fn (size)
(the (red-black/tree:Tree Ufix)
(iter:collect! (random-iter! size)))))
(let increasing-list = (fn (tree)
(iter:collect! (red-black/tree:increasing-order tree))))
(let decreasing-list = (fn (tree)
(iter:collect! (red-black/tree:decreasing-order tree))))
(let tree-good? = (fn (tree)
(let increasing = (increasing-list tree))
(let decreasing = (decreasing-list tree))
(is (increasing? increasing))
(is (== (reverse decreasing) increasing))))
(iter:for-each!
(fn (length)
(pipe length
random-tree!
tree-good?))
(iter:up-to 128)))
(cl:eval-when (:compile-toplevel :load-toplevel :execute)
(cl:defmacro is-ok (check cl:&optional (message (cl:format cl:nil "~A returned Err" check)))
`(is (result:ok? ,check)
,message)))
(define-test insertion-upholds-invariants ()
(let insert-and-check-invariants =
(fn (tre new-elt)
(let new-tre = (red-black/tree:insert-or-replace tre new-elt))
(is-ok (count-blacks-to-leaf new-tre))
new-tre))
(let collect-tree-checking-invariants =
(fn (iter)
(iter:fold! insert-and-check-invariants red-black/tree:Empty iter)))
(let up-to-1024 =
(collect-tree-checking-invariants (iter:up-to 1024)))
(let down-from-1024 =
(collect-tree-checking-invariants (iter:down-from 1024)))
(is (== up-to-1024 down-from-1024))
(is (== (hash up-to-1024) (hash down-from-1024)))
(let range-1024 = (the (List Integer)
(iter:collect! (iter:up-to 1024))))
(let range-shuffled = (lisp (List Integer) (range-1024)
(alexandria:shuffle range-1024)))
(let shuffled =
(collect-tree-checking-invariants (iter:into-iter range-shuffled)))
(is (== up-to-1024 shuffled))
(is (== (hash up-to-1024) (hash shuffled))))
(coalton-toplevel
(declare tree-4 (red-black/tree:Tree Integer))
(define tree-4 (red-black/tree:collect! (iter:up-to (the Integer 4))))
(declare tree-1024 (red-black/tree:Tree Integer))
(define tree-1024 (red-black/tree:collect! (iter:up-to (the Integer 1024))))
(declare remove-and-check-invariants ((red-black/tree:Tree Integer) -> Integer -> (red-black/tree:Tree Integer)))
(define (remove-and-check-invariants tre elt-to-remove)
(match (red-black/tree:remove tre elt-to-remove)
((None) (error "Tried to remove non-present element in `remove-and-check-invariants'"))
((Some new-tre)
(is-ok (count-blacks-to-leaf new-tre))
new-tre)))
(declare destroy-tree-checking-invariants ((red-black/tree:Tree Integer) -> (iter:Iterator Integer) -> Unit))
(define (destroy-tree-checking-invariants start iter)
(let should-be-empty = (iter:fold! remove-and-check-invariants start iter))
(matches (red-black/tree:Empty) should-be-empty "Non-empty tree after removing all elements")))
(define-test removal-upholds-invariants-small-upward ()
(destroy-tree-checking-invariants tree-4 (iter:up-to 4)))
(define-test removal-upholds-invariants-large-upward ()
(destroy-tree-checking-invariants tree-1024 (iter:up-to 1024)))
(define-test removal-upholds-invariants-small-downward ()
(destroy-tree-checking-invariants tree-4 (iter:down-from 4)))
(define-test removal-upholds-invariants-large-downward ()
(destroy-tree-checking-invariants tree-1024 (iter:down-from 1024)))
(define-test removal-upholds-invariants-shuffled ()
(let range-1024 = (the (List Integer)
(iter:collect-list! (iter:up-to 1024))))
(let range-shuffled = (lisp (List Integer) (range-1024)
(alexandria:shuffle range-1024)))
(destroy-tree-checking-invariants tree-1024 (iter:into-iter range-shuffled)))
(define-test detect-bad-tree ()
(let red-with-red-child = (red-black/tree::Branch red-black/tree::Red
(red-black/tree::Branch red-black/tree::Red red-black/tree:Empty 0 red-black/tree:Empty)
1
red-black/tree:Empty))
(matches (Err (RedWithRedLeftChild _)) (count-blacks-to-leaf red-with-red-child))
(let unbalanced = (red-black/tree::Branch red-black/tree::Black
(red-black/tree::Branch red-black/tree::Black red-black/tree:Empty 0 red-black/tree:Empty)
1
red-black/tree:Empty))
(matches (Err (DifferentCountToBlack _ _ _ _)) (count-blacks-to-leaf unbalanced)))
(define-test map-from-iter-equiv-to-manual-construction ()
(let manual = (the (red-black/map:Map Integer String)
(red-black/map:insert-or-replace
(red-black/map:insert-or-replace
(red-black/map:insert-or-replace red-black/map:empty 0 "zero")
11 "eleven")
5 "five")))
(let iterated = (iter:collect! (iter:into-iter (the (List (Tuple Integer String))
(make-list (Tuple 0 "zero")
(Tuple 11 "eleven")
(Tuple 5 "five"))))))
(is (== manual iterated))
(is (== (hash manual) (hash iterated))))
(define-test map-non-equal ()
(let map-012 = (the (red-black/map:Map Integer String)
(iter:collect! (iter:into-iter (make-list (Tuple 0 "zero")
(Tuple 1 "one")
(Tuple 2 "two"))))))
(let map-01 = (iter:collect! (iter:into-iter (make-list (Tuple 0 "zero")
(Tuple 1 "one")))))
(let map-wrong-names = (iter:collect! (iter:into-iter (make-list (Tuple 0 "one")
(Tuple 1 "zero")))))
(is (/= map-012 map-01))
(is (/= (hash map-012) (hash map-01)))
(is (/= map-01 map-wrong-names))
(is (/= (hash map-01) (hash map-wrong-names)))
(is (/= map-012 map-wrong-names))
(is (/= (hash map-012) (hash map-wrong-names))))
| null | https://raw.githubusercontent.com/coalton-lang/coalton/57e5622346add6aca753e3c4830afaed65e6d6df/tests/red-black-tests.lisp | lisp | invariant checking | (cl:in-package #:coalton-native-tests)
(coalton-toplevel
(define-type (InvariantError :elt)
(RedWithRedLeftChild (red-black/tree:Tree :elt))
(RedWithRedRightChild (red-black/tree:Tree :elt))
(DifferentCountToBlack UFix (red-black/tree:Tree :elt)
UFix (red-black/tree:Tree :elt))
(BothChildrenErrors (InvariantError :elt) (InvariantError :elt))
(IllegalColor (red-black/tree:Tree :elt)))
(declare count-blacks-to-leaf ((red-black/tree:Tree :elt) -> (Result (InvariantError :elt) UFix)))
(define (count-blacks-to-leaf tre)
(match tre
((red-black/tree:Empty) (Ok 0))
((red-black/tree::Branch (red-black/tree::Red)
(red-black/tree::Branch (red-black/tree::Red) _ _ _)
_
_)
(Err (RedWithRedLeftChild tre)))
((red-black/tree::Branch (red-black/tree::Red)
_
_
(red-black/tree::Branch (red-black/tree::Red) _ _ _))
(Err (RedWithRedRightChild tre)))
((red-black/tree::Branch c left _ right)
(match (Tuple (count-blacks-to-leaf left)
(count-blacks-to-leaf right))
((Tuple (Err left-err) (Err right-err))
(Err (BothChildrenErrors left-err right-err)))
((Tuple (Err left-err) _)
(Err left-err))
((Tuple _ (Err right-err))
(Err right-err))
((Tuple (Ok left-ct) (Ok right-ct))
(if (== left-ct right-ct)
(match c
((red-black/tree::Black) (Ok (+ left-ct 1)))
((red-black/tree::Red) (Ok left-ct))
(_ (Err (IllegalColor tre))))
(Err (DifferentCountToBlack left-ct left
right-ct right))))))
(_ (Err (IllegalColor tre))))))
(coalton-toplevel
(declare random-below! (UFix -> UFix))
(define (random-below! limit)
(lisp UFix (limit)
(cl:random limit)))
(declare random! (Unit -> UFix))
(define (random!)
(random-below! (lisp UFix () cl:most-positive-fixnum)))
(declare random-iter! (UFix -> (iter:Iterator UFix)))
(define (random-iter! length)
(map (fn (_) (random!))
(iter:up-to length))))
(define-test tree-from-iter-equiv-to-manual-construction ()
(let manual = (red-black/tree:insert-or-replace
(red-black/tree:insert-or-replace
(red-black/tree:insert-or-replace red-black/tree:Empty
5)
11)
2))
(let iterated = (red-black/tree:collect! (iter:into-iter (the (List Integer)
(make-list 5 11 2)))))
(is (== manual iterated))
(is (== (hash manual) (hash iterated))))
(define-test tree-always-increasing-order ()
(let increasing? = (fn (lst)
(== (list:sort lst) lst)))
(let random-tree! = (fn (size)
(the (red-black/tree:Tree Ufix)
(iter:collect! (random-iter! size)))))
(let increasing-list = (fn (tree)
(iter:collect! (red-black/tree:increasing-order tree))))
(let decreasing-list = (fn (tree)
(iter:collect! (red-black/tree:decreasing-order tree))))
(let tree-good? = (fn (tree)
(let increasing = (increasing-list tree))
(let decreasing = (decreasing-list tree))
(is (increasing? increasing))
(is (== (reverse decreasing) increasing))))
(iter:for-each!
(fn (length)
(pipe length
random-tree!
tree-good?))
(iter:up-to 128)))
(cl:eval-when (:compile-toplevel :load-toplevel :execute)
(cl:defmacro is-ok (check cl:&optional (message (cl:format cl:nil "~A returned Err" check)))
`(is (result:ok? ,check)
,message)))
(define-test insertion-upholds-invariants ()
(let insert-and-check-invariants =
(fn (tre new-elt)
(let new-tre = (red-black/tree:insert-or-replace tre new-elt))
(is-ok (count-blacks-to-leaf new-tre))
new-tre))
(let collect-tree-checking-invariants =
(fn (iter)
(iter:fold! insert-and-check-invariants red-black/tree:Empty iter)))
(let up-to-1024 =
(collect-tree-checking-invariants (iter:up-to 1024)))
(let down-from-1024 =
(collect-tree-checking-invariants (iter:down-from 1024)))
(is (== up-to-1024 down-from-1024))
(is (== (hash up-to-1024) (hash down-from-1024)))
(let range-1024 = (the (List Integer)
(iter:collect! (iter:up-to 1024))))
(let range-shuffled = (lisp (List Integer) (range-1024)
(alexandria:shuffle range-1024)))
(let shuffled =
(collect-tree-checking-invariants (iter:into-iter range-shuffled)))
(is (== up-to-1024 shuffled))
(is (== (hash up-to-1024) (hash shuffled))))
(coalton-toplevel
(declare tree-4 (red-black/tree:Tree Integer))
(define tree-4 (red-black/tree:collect! (iter:up-to (the Integer 4))))
(declare tree-1024 (red-black/tree:Tree Integer))
(define tree-1024 (red-black/tree:collect! (iter:up-to (the Integer 1024))))
(declare remove-and-check-invariants ((red-black/tree:Tree Integer) -> Integer -> (red-black/tree:Tree Integer)))
(define (remove-and-check-invariants tre elt-to-remove)
(match (red-black/tree:remove tre elt-to-remove)
((None) (error "Tried to remove non-present element in `remove-and-check-invariants'"))
((Some new-tre)
(is-ok (count-blacks-to-leaf new-tre))
new-tre)))
(declare destroy-tree-checking-invariants ((red-black/tree:Tree Integer) -> (iter:Iterator Integer) -> Unit))
(define (destroy-tree-checking-invariants start iter)
(let should-be-empty = (iter:fold! remove-and-check-invariants start iter))
(matches (red-black/tree:Empty) should-be-empty "Non-empty tree after removing all elements")))
(define-test removal-upholds-invariants-small-upward ()
(destroy-tree-checking-invariants tree-4 (iter:up-to 4)))
(define-test removal-upholds-invariants-large-upward ()
(destroy-tree-checking-invariants tree-1024 (iter:up-to 1024)))
(define-test removal-upholds-invariants-small-downward ()
(destroy-tree-checking-invariants tree-4 (iter:down-from 4)))
(define-test removal-upholds-invariants-large-downward ()
(destroy-tree-checking-invariants tree-1024 (iter:down-from 1024)))
(define-test removal-upholds-invariants-shuffled ()
(let range-1024 = (the (List Integer)
(iter:collect-list! (iter:up-to 1024))))
(let range-shuffled = (lisp (List Integer) (range-1024)
(alexandria:shuffle range-1024)))
(destroy-tree-checking-invariants tree-1024 (iter:into-iter range-shuffled)))
(define-test detect-bad-tree ()
(let red-with-red-child = (red-black/tree::Branch red-black/tree::Red
(red-black/tree::Branch red-black/tree::Red red-black/tree:Empty 0 red-black/tree:Empty)
1
red-black/tree:Empty))
(matches (Err (RedWithRedLeftChild _)) (count-blacks-to-leaf red-with-red-child))
(let unbalanced = (red-black/tree::Branch red-black/tree::Black
(red-black/tree::Branch red-black/tree::Black red-black/tree:Empty 0 red-black/tree:Empty)
1
red-black/tree:Empty))
(matches (Err (DifferentCountToBlack _ _ _ _)) (count-blacks-to-leaf unbalanced)))
(define-test map-from-iter-equiv-to-manual-construction ()
(let manual = (the (red-black/map:Map Integer String)
(red-black/map:insert-or-replace
(red-black/map:insert-or-replace
(red-black/map:insert-or-replace red-black/map:empty 0 "zero")
11 "eleven")
5 "five")))
(let iterated = (iter:collect! (iter:into-iter (the (List (Tuple Integer String))
(make-list (Tuple 0 "zero")
(Tuple 11 "eleven")
(Tuple 5 "five"))))))
(is (== manual iterated))
(is (== (hash manual) (hash iterated))))
(define-test map-non-equal ()
(let map-012 = (the (red-black/map:Map Integer String)
(iter:collect! (iter:into-iter (make-list (Tuple 0 "zero")
(Tuple 1 "one")
(Tuple 2 "two"))))))
(let map-01 = (iter:collect! (iter:into-iter (make-list (Tuple 0 "zero")
(Tuple 1 "one")))))
(let map-wrong-names = (iter:collect! (iter:into-iter (make-list (Tuple 0 "one")
(Tuple 1 "zero")))))
(is (/= map-012 map-01))
(is (/= (hash map-012) (hash map-01)))
(is (/= map-01 map-wrong-names))
(is (/= (hash map-01) (hash map-wrong-names)))
(is (/= map-012 map-wrong-names))
(is (/= (hash map-012) (hash map-wrong-names))))
|
ae7700d0b97d86d2c0c4de314afd7b1c5691de439083b5775d5f30a345283c80 | OCamlPro/ez_api | ezReq_lwt.ml | (**************************************************************************)
(* *)
Copyright 2018 - 2022 OCamlPro
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
GNU Lesser General Public License version 2.1 , with the special
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
include EzCurl_lwt
| null | https://raw.githubusercontent.com/OCamlPro/ez_api/5253f7dd8936e923290aa969ee43ebd3dc6fce2d/src/request/unix/curl/ezReq_lwt.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************ | Copyright 2018 - 2022 OCamlPro
GNU Lesser General Public License version 2.1 , with the special
include EzCurl_lwt
|
e05eb71d598a97d9548f8864a3fddf130eebb643ffa3711e71fdbbafd15ba7b7 | Chris00/mesh | export.ml | open Bigarray
let pi = acos(-1.)
let pslg_disk =
let n = 100 in
let point = Array2.create float64 fortran_layout 2 n in
let segment = Array2.create int fortran_layout 2 n in
let dt = 2. *. pi /. float n in
for i = 1 to n do
let t = float(i - 1) *. dt in
point.{1,i} <- cos t;
point.{2,i} <- sin t;
segment.{1,i} <- i;
segment.{2,i} <- if i = n then 1 else i + 1;
done;
Mesh_triangle.pslg point segment
let disk, _ = Mesh_triangle.triangulate pslg_disk ~max_area:1e-3
Export to Matlab , Scilab , and Mathematica .
let () =
let f x y =
let r = x**2. +. y**2. in
cos(10. *. r) /. (r +. 0.1) in
let v = Array1.create float64 fortran_layout (Array2.dim2 disk#point) in
for i = 1 to Array2.dim2 disk#point do
v.{i} <- f disk#point.{1,i} disk#point.{2,i};
done;
let fname = Filename.concat (Filename.get_temp_dir_name()) "disk" in
Mesh.scilab disk v (fname ^ "_scilab");
Mesh.matlab disk v (fname ^ "_matlab");
Mesh.mathematica disk v (fname ^ "Mathematica")
| null | https://raw.githubusercontent.com/Chris00/mesh/305efa28209c6d5b081459338d84bcd985254bca/tests/export.ml | ocaml | open Bigarray
let pi = acos(-1.)
let pslg_disk =
let n = 100 in
let point = Array2.create float64 fortran_layout 2 n in
let segment = Array2.create int fortran_layout 2 n in
let dt = 2. *. pi /. float n in
for i = 1 to n do
let t = float(i - 1) *. dt in
point.{1,i} <- cos t;
point.{2,i} <- sin t;
segment.{1,i} <- i;
segment.{2,i} <- if i = n then 1 else i + 1;
done;
Mesh_triangle.pslg point segment
let disk, _ = Mesh_triangle.triangulate pslg_disk ~max_area:1e-3
Export to Matlab , Scilab , and Mathematica .
let () =
let f x y =
let r = x**2. +. y**2. in
cos(10. *. r) /. (r +. 0.1) in
let v = Array1.create float64 fortran_layout (Array2.dim2 disk#point) in
for i = 1 to Array2.dim2 disk#point do
v.{i} <- f disk#point.{1,i} disk#point.{2,i};
done;
let fname = Filename.concat (Filename.get_temp_dir_name()) "disk" in
Mesh.scilab disk v (fname ^ "_scilab");
Mesh.matlab disk v (fname ^ "_matlab");
Mesh.mathematica disk v (fname ^ "Mathematica")
| |
e30aea0dd36dec91a9b2815e33981a642637f864809e93a37ac6b1b828d2be5b | jwiegley/notes | memoize-edwardk.hs | {-# LANGUAGE BangPatterns #-}
module Main where
import Control.Monad.Instances
import Data.List
import Data.Function (fix)
col :: (Int -> (Int,Integer)) -> Int -> (Int,Integer)
col mf 1 = (1,0)
col mf !n
| mod n 2 == 0 = let (x,y) = mf (n `div` 2) in (x+1,y+1)
| otherwise = let (x,y) = mf (n * 3 + 1) in (x+1,y+1)
f_list :: [(Int,Integer)]
f_list = map (col faster_f) [0..]
faster_f :: Int -> (Int,Integer)
faster_f n = f_list !! n
data Tree a = Tree (Tree a) a (Tree a)
instance Functor Tree where
fmap f (Tree l m r) = Tree (fmap f l) (f m) (fmap f r)
index :: Tree a -> Int -> a
index (Tree _ m _) 0 = m
index (Tree l _ r) n = case (n - 1) `divMod` 2 of
(q,0) -> index l q
(q,1) -> index r q
nats :: Tree Int
nats = go 0 1
where
go !n !s = Tree (go l s') n (go r s')
where
l = n + s
r = l + s
s' = s * 2
toList :: Tree a -> [a]
toList as = map (index as) [0..]
f_tree :: Tree (Int,Integer)
f_tree = fmap (col fastest_f) nats
fastest_f :: Int -> (Int,Integer)
fastest_f = index f_tree
collatz :: Int -> [(Int,Integer)]
collatz m = foldr (\n rest ->
let y@(_,x) = fastest_f n in x `seq` y:rest) [] [1..m]
solution :: (Int, Integer)
solution = foldl' (\acc@(lg,_) x@(dep,_) -> if dep > lg then x else acc)
(0,0) (collatz 999999)
main :: IO ()
main = print solution | null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/memoize-edwardk.hs | haskell | # LANGUAGE BangPatterns # |
module Main where
import Control.Monad.Instances
import Data.List
import Data.Function (fix)
col :: (Int -> (Int,Integer)) -> Int -> (Int,Integer)
col mf 1 = (1,0)
col mf !n
| mod n 2 == 0 = let (x,y) = mf (n `div` 2) in (x+1,y+1)
| otherwise = let (x,y) = mf (n * 3 + 1) in (x+1,y+1)
f_list :: [(Int,Integer)]
f_list = map (col faster_f) [0..]
faster_f :: Int -> (Int,Integer)
faster_f n = f_list !! n
data Tree a = Tree (Tree a) a (Tree a)
instance Functor Tree where
fmap f (Tree l m r) = Tree (fmap f l) (f m) (fmap f r)
index :: Tree a -> Int -> a
index (Tree _ m _) 0 = m
index (Tree l _ r) n = case (n - 1) `divMod` 2 of
(q,0) -> index l q
(q,1) -> index r q
nats :: Tree Int
nats = go 0 1
where
go !n !s = Tree (go l s') n (go r s')
where
l = n + s
r = l + s
s' = s * 2
toList :: Tree a -> [a]
toList as = map (index as) [0..]
f_tree :: Tree (Int,Integer)
f_tree = fmap (col fastest_f) nats
fastest_f :: Int -> (Int,Integer)
fastest_f = index f_tree
collatz :: Int -> [(Int,Integer)]
collatz m = foldr (\n rest ->
let y@(_,x) = fastest_f n in x `seq` y:rest) [] [1..m]
solution :: (Int, Integer)
solution = foldl' (\acc@(lg,_) x@(dep,_) -> if dep > lg then x else acc)
(0,0) (collatz 999999)
main :: IO ()
main = print solution |
9205503b7add5ad5874ef7307f608778936a7afc857ff7911a64a62fac1ed5e8 | TiltMeSenpai/Discord.hs | hello_world.hs | {-# LANGUAGE OverloadedStrings #-}
import Data.Maybe
import Network.URL
import Pipes.Core ((+>>))
import Network.Discord.Types
import Network.Discord.Gateway
import Network.Discord.Rest
data LogClient = LClient
instance Client LogClient where
getAuth _ = Bot "TOKEN"
main :: IO ()
main = runWebsocket (fromJust $ importURL "wss") LClient $ do
fetch' (CreateMessage 188134500411244545 "Hello, World!" Nothing)
fetch' (CreateMessage 188134500411244545 "I'm running discord.hs!" Nothing)
| null | https://raw.githubusercontent.com/TiltMeSenpai/Discord.hs/91f688f03813982bbf7c37d048bd7bcc08671d8e/examples/hello_world.hs | haskell | # LANGUAGE OverloadedStrings # |
import Data.Maybe
import Network.URL
import Pipes.Core ((+>>))
import Network.Discord.Types
import Network.Discord.Gateway
import Network.Discord.Rest
data LogClient = LClient
instance Client LogClient where
getAuth _ = Bot "TOKEN"
main :: IO ()
main = runWebsocket (fromJust $ importURL "wss") LClient $ do
fetch' (CreateMessage 188134500411244545 "Hello, World!" Nothing)
fetch' (CreateMessage 188134500411244545 "I'm running discord.hs!" Nothing)
|
9cd65710e2bb1727a12bf7f6938f70a6441212b009ea276da5ff98958b93afcf | everpeace/programming-erlang-code | server1.erl | -module(server1).
-export([start/2, rpc/2]).
start(Name, Mod) ->
register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)).
rpc(Name, Request) ->
Name ! {self(), Request},
receive
{Name, Response} -> Response
end.
loop(Name, Mod, State) ->
receive
{From, Request} ->
{Response, State1} = Mod:handle(Request, State),
From ! {Name, Response},
loop(Name, Mod, State1)
end.
| null | https://raw.githubusercontent.com/everpeace/programming-erlang-code/8ef31aa13d15b41754dda225c50284915c29cb48/code/server1.erl | erlang | -module(server1).
-export([start/2, rpc/2]).
start(Name, Mod) ->
register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)).
rpc(Name, Request) ->
Name ! {self(), Request},
receive
{Name, Response} -> Response
end.
loop(Name, Mod, State) ->
receive
{From, Request} ->
{Response, State1} = Mod:handle(Request, State),
From ! {Name, Response},
loop(Name, Mod, State1)
end.
| |
9ced417320a272d6b71b124d6688359cee2bddfaf658a304298a5ee705099ac1 | lamdu/lamdu | BuiltinEdit.hs | module Lamdu.GUI.Expr.BuiltinEdit
( make
) where
import qualified Control.Lens as Lens
import Data.Property (Property(..))
import qualified Data.Text as Text
import GUI.Momentu (noMods)
import qualified GUI.Momentu as M
import GUI.Momentu.Element.Id (ElemId)
import qualified GUI.Momentu.EventMap as E
import qualified GUI.Momentu.I18N as MomentuTexts
import qualified GUI.Momentu.ModKey as ModKey
import qualified GUI.Momentu.State as GuiState
import qualified GUI.Momentu.Widgets.FocusDelegator as FocusDelegator
import qualified GUI.Momentu.Widgets.Label as Label
import qualified GUI.Momentu.Widgets.TextEdit as TextEdit
import qualified GUI.Momentu.Widgets.TextEdit.Property as TextEdits
import qualified GUI.Momentu.Widgets.TextView as TextView
import qualified Lamdu.Config.Theme as Theme
import qualified Lamdu.Config.Theme.TextColors as TextColors
import qualified Lamdu.Data.Definition as Definition
import qualified Lamdu.I18N.CodeUI as Texts
import qualified Lamdu.Sugar.Types as Sugar
import Lamdu.Prelude
builtinFDConfig :: _ => env -> FocusDelegator.Config
builtinFDConfig env = FocusDelegator.Config
{ FocusDelegator.focusChildKeys = [noMods ModKey.Key'Enter]
, FocusDelegator.focusChildDoc = doc Texts.changeImportedName
, FocusDelegator.focusParentKeys = [noMods ModKey.Key'Escape]
, FocusDelegator.focusParentDoc = doc Texts.doneChangingImportedName
}
where
doc lens = E.toDoc env [has . MomentuTexts.edit, has . lens]
builtinFFIPath :: ElemId -> ElemId
builtinFFIPath = (<> "FFIPath")
builtinFFIName :: ElemId -> ElemId
builtinFFIName = (<> "FFIName")
makeNamePartEditor ::
_ => M.Color -> Text -> (Text -> f ()) -> ElemId -> m (M.TextWidget f)
makeNamePartEditor color namePartStr setter myId =
(FocusDelegator.make
<*> (Lens.view id <&> builtinFDConfig)
?? FocusDelegator.FocusEntryParent
?? myId <&> (M.tValue %~))
<*> ( TextEdits.makeWordEdit ?? empty ?? Property namePartStr setter ??
myId <> "textedit"
)
& local (TextView.color .~ color)
where
empty =
TextEdit.Modes
{ TextEdit._unfocused = "(?)"
, TextEdit._focused = ""
}
make :: _ => Sugar.DefinitionBuiltin name o -> ElemId -> f (M.TextWidget o)
make def myId =
do
colors <- Lens.view (has . Theme.textColors)
makeNamePartEditor (colors ^. TextColors.foreignModuleColor)
modulePathStr modulePathSetter (builtinFFIPath myId)
M./|/ Label.make "."
M./|/ makeNamePartEditor (colors ^. TextColors.foreignVarColor) name
nameSetter (builtinFFIName myId)
& GuiState.assignCursor myId (builtinFFIName myId)
where
Sugar.DefinitionBuiltin
(Definition.FFIName modulePath name) setFFIName _ = def
modulePathStr = Text.intercalate "." modulePath
modulePathSetter = setFFIName . (`Definition.FFIName` name) . Text.splitOn "."
nameSetter = setFFIName . Definition.FFIName modulePath
| null | https://raw.githubusercontent.com/lamdu/lamdu/5b15688e53ccbf7448ff11134b3e51ed082c6b6c/src/Lamdu/GUI/Expr/BuiltinEdit.hs | haskell | module Lamdu.GUI.Expr.BuiltinEdit
( make
) where
import qualified Control.Lens as Lens
import Data.Property (Property(..))
import qualified Data.Text as Text
import GUI.Momentu (noMods)
import qualified GUI.Momentu as M
import GUI.Momentu.Element.Id (ElemId)
import qualified GUI.Momentu.EventMap as E
import qualified GUI.Momentu.I18N as MomentuTexts
import qualified GUI.Momentu.ModKey as ModKey
import qualified GUI.Momentu.State as GuiState
import qualified GUI.Momentu.Widgets.FocusDelegator as FocusDelegator
import qualified GUI.Momentu.Widgets.Label as Label
import qualified GUI.Momentu.Widgets.TextEdit as TextEdit
import qualified GUI.Momentu.Widgets.TextEdit.Property as TextEdits
import qualified GUI.Momentu.Widgets.TextView as TextView
import qualified Lamdu.Config.Theme as Theme
import qualified Lamdu.Config.Theme.TextColors as TextColors
import qualified Lamdu.Data.Definition as Definition
import qualified Lamdu.I18N.CodeUI as Texts
import qualified Lamdu.Sugar.Types as Sugar
import Lamdu.Prelude
builtinFDConfig :: _ => env -> FocusDelegator.Config
builtinFDConfig env = FocusDelegator.Config
{ FocusDelegator.focusChildKeys = [noMods ModKey.Key'Enter]
, FocusDelegator.focusChildDoc = doc Texts.changeImportedName
, FocusDelegator.focusParentKeys = [noMods ModKey.Key'Escape]
, FocusDelegator.focusParentDoc = doc Texts.doneChangingImportedName
}
where
doc lens = E.toDoc env [has . MomentuTexts.edit, has . lens]
builtinFFIPath :: ElemId -> ElemId
builtinFFIPath = (<> "FFIPath")
builtinFFIName :: ElemId -> ElemId
builtinFFIName = (<> "FFIName")
makeNamePartEditor ::
_ => M.Color -> Text -> (Text -> f ()) -> ElemId -> m (M.TextWidget f)
makeNamePartEditor color namePartStr setter myId =
(FocusDelegator.make
<*> (Lens.view id <&> builtinFDConfig)
?? FocusDelegator.FocusEntryParent
?? myId <&> (M.tValue %~))
<*> ( TextEdits.makeWordEdit ?? empty ?? Property namePartStr setter ??
myId <> "textedit"
)
& local (TextView.color .~ color)
where
empty =
TextEdit.Modes
{ TextEdit._unfocused = "(?)"
, TextEdit._focused = ""
}
make :: _ => Sugar.DefinitionBuiltin name o -> ElemId -> f (M.TextWidget o)
make def myId =
do
colors <- Lens.view (has . Theme.textColors)
makeNamePartEditor (colors ^. TextColors.foreignModuleColor)
modulePathStr modulePathSetter (builtinFFIPath myId)
M./|/ Label.make "."
M./|/ makeNamePartEditor (colors ^. TextColors.foreignVarColor) name
nameSetter (builtinFFIName myId)
& GuiState.assignCursor myId (builtinFFIName myId)
where
Sugar.DefinitionBuiltin
(Definition.FFIName modulePath name) setFFIName _ = def
modulePathStr = Text.intercalate "." modulePath
modulePathSetter = setFFIName . (`Definition.FFIName` name) . Text.splitOn "."
nameSetter = setFFIName . Definition.FFIName modulePath
| |
612bedb4de7c015068a417a8ada4efbfccb5ce77efead2ece5ca4a2c809d72fd | appleshan/cl-http | sysdcl.lisp | -*- Syntax : Ansi - Common - Lisp ; Package : cl - user ; Base : 10 ; Mode : lisp -*-
;;; File: sysdcl.lisp
Last edited by smishra on Thu Oct 22 17:27:33 1998
( c ) Copyright 1996 - 98 , ( )
;;; All Rights Reserved
(in-package :cl-user)
#-(or Allegro LispWorks Genera MCL)
(error "System definitions included here are for the following platforms:
* Allegro
* LispWorks
* Genera
* MCL
If you write a system definition for another setup, please send
me a copy for inclusion.")
(pushnew :html-parser *features*)
;;;-------------------------------------------------------------------
;;;
Allegro system definition
;;;
#+Allegro
(unless (ignore-errors (logical-pathname-translations "HTML-PARSER"))
(setf (logical-pathname-translations "HTML-PARSER")
`(("**;*.*.*"
,(make-pathname :directory (pathname-directory *load-truename*))))))
#+Allegro
(defsystem :html-parser
(:default-pathname "HTML-PARSER:")
(:serial
"packages"
#-CL-HTTP "tokenizer"
#-CL-HTTP "plist"
"defs"
"patmatch"
"rewrite-engine"
"rewrite-rules"
"html-tags"
"html-reader"
"html-parser"
"html-utilities"))
;;;-------------------------------------------------------------------
;;;
LispWorks system definition
;;;
#+LispWorks
(unless (ignore-errors (logical-pathname-translations "HTML-PARSER"))
(setf (logical-pathname-translations "HTML-PARSER")
`(("**;*.*.*"
,(merge-pathnames "**/*.*"
(truename #+Lispworks4(lw:current-pathname ".")
#-Lispworks4(lw:current-directory ".")))))))
#+LispWorks
(defsystem html-parser (:default-pathname "HTML-PARSER:")
:members ("packages"
#-CL-HTTP "tokenizer"
#-CL-HTTP "plist"
"defs"
"patmatch"
"rewrite-engine"
"rewrite-rules"
"html-tags"
"html-reader"
"html-parser"
"html-utilities")
:rules ((:in-order-to :compile :all
(:requires (:load :previous)))))
#+LispWorks (compile-system 'html-parser :load t)
;;;-------------------------------------------------------------------
;;;
;;; Genera system definition
;;;
#+ignore
(unless (fs:get-logical-pathname-host "HTML-PARSER" t)
(fs:make-logical-pathname-host "HTML-PARSER"))
#+Genera
(sct:defsystem HTML-Parser
(:pretty-name "HTML Parser"
:default-pathname "html-parser:html-parser;"
:journal-directory "html-parser:journal;"
:initial-status :released
:patchable t
:source-category :basic)
(:module pointers
("sys:site;html-parser.translations"
"sys:site;html-parser.system")
(:type :lisp-example))
(:module examples
("html-parser:html-parser;readme.text")
(:type :lisp-example))
(:serial
"packages"
#-CL-HTTP "tokenizer"
#-CL-HTTP "plist"
"defs"
"patmatch"
"rewrite-engine"
"rewrite-rules"
"html-tags"
"html-reader"
"html-parser"
"html-utilities"))
;;;-------------------------------------------------------------------
;;;
MCL system definition
;;;
#+MCL (load "html-parser:mac-sysdcl")
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/html-parser/v10/sysdcl.lisp | lisp | Package : cl - user ; Base : 10 ; Mode : lisp -*-
File: sysdcl.lisp
All Rights Reserved
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
Genera system definition
-------------------------------------------------------------------
|
Last edited by smishra on Thu Oct 22 17:27:33 1998
( c ) Copyright 1996 - 98 , ( )
(in-package :cl-user)
#-(or Allegro LispWorks Genera MCL)
(error "System definitions included here are for the following platforms:
* Allegro
* LispWorks
* Genera
* MCL
If you write a system definition for another setup, please send
me a copy for inclusion.")
(pushnew :html-parser *features*)
Allegro system definition
#+Allegro
(unless (ignore-errors (logical-pathname-translations "HTML-PARSER"))
(setf (logical-pathname-translations "HTML-PARSER")
`(("**;*.*.*"
,(make-pathname :directory (pathname-directory *load-truename*))))))
#+Allegro
(defsystem :html-parser
(:default-pathname "HTML-PARSER:")
(:serial
"packages"
#-CL-HTTP "tokenizer"
#-CL-HTTP "plist"
"defs"
"patmatch"
"rewrite-engine"
"rewrite-rules"
"html-tags"
"html-reader"
"html-parser"
"html-utilities"))
LispWorks system definition
#+LispWorks
(unless (ignore-errors (logical-pathname-translations "HTML-PARSER"))
(setf (logical-pathname-translations "HTML-PARSER")
`(("**;*.*.*"
,(merge-pathnames "**/*.*"
(truename #+Lispworks4(lw:current-pathname ".")
#-Lispworks4(lw:current-directory ".")))))))
#+LispWorks
(defsystem html-parser (:default-pathname "HTML-PARSER:")
:members ("packages"
#-CL-HTTP "tokenizer"
#-CL-HTTP "plist"
"defs"
"patmatch"
"rewrite-engine"
"rewrite-rules"
"html-tags"
"html-reader"
"html-parser"
"html-utilities")
:rules ((:in-order-to :compile :all
(:requires (:load :previous)))))
#+LispWorks (compile-system 'html-parser :load t)
#+ignore
(unless (fs:get-logical-pathname-host "HTML-PARSER" t)
(fs:make-logical-pathname-host "HTML-PARSER"))
#+Genera
(sct:defsystem HTML-Parser
(:pretty-name "HTML Parser"
:default-pathname "html-parser:html-parser;"
:journal-directory "html-parser:journal;"
:initial-status :released
:patchable t
:source-category :basic)
(:module pointers
("sys:site;html-parser.translations"
"sys:site;html-parser.system")
(:type :lisp-example))
(:module examples
("html-parser:html-parser;readme.text")
(:type :lisp-example))
(:serial
"packages"
#-CL-HTTP "tokenizer"
#-CL-HTTP "plist"
"defs"
"patmatch"
"rewrite-engine"
"rewrite-rules"
"html-tags"
"html-reader"
"html-parser"
"html-utilities"))
MCL system definition
#+MCL (load "html-parser:mac-sysdcl")
|
df102b5197227cff4a9e8380151130ff5331783763fc2122f675e23f57fc5b68 | lingnand/VIMonad | Types.hs | {-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Util.Types
Copyright : ( c ) ( 2009 )
-- License : BSD3-style (see LICENSE)
--
Maintainer : < >
-- Stability : unstable
-- Portability : unportable
--
-- Miscellaneous commonly used types.
--
-----------------------------------------------------------------------------
module XMonad.Util.Types (Direction1D(..)
,Direction2D(..)
) where
import Data.Typeable (Typeable)
| One - dimensional directions :
data Direction1D = Next | Prev deriving (Eq,Read,Show,Typeable)
| Two - dimensional directions :
data Direction2D = U -- ^ Up
| D -- ^ Down
| R -- ^ Right
| L -- ^ Left
deriving (Eq,Read,Show,Ord,Enum,Bounded,Typeable)
| null | https://raw.githubusercontent.com/lingnand/VIMonad/048e419fc4ef57a5235dbaeef8890faf6956b574/XMonadContrib/XMonad/Util/Types.hs | haskell | # LANGUAGE DeriveDataTypeable #
---------------------------------------------------------------------------
|
Module : XMonad.Util.Types
License : BSD3-style (see LICENSE)
Stability : unstable
Portability : unportable
Miscellaneous commonly used types.
---------------------------------------------------------------------------
^ Up
^ Down
^ Right
^ Left | Copyright : ( c ) ( 2009 )
Maintainer : < >
module XMonad.Util.Types (Direction1D(..)
,Direction2D(..)
) where
import Data.Typeable (Typeable)
| One - dimensional directions :
data Direction1D = Next | Prev deriving (Eq,Read,Show,Typeable)
| Two - dimensional directions :
deriving (Eq,Read,Show,Ord,Enum,Bounded,Typeable)
|
23320c41baab81fe9fcd6c1914621987e5020c17dddc6e124478a50a980cbed9 | digitallyinduced/ihp | Edit.hs | module IHP.IDE.SchemaDesigner.View.Enums.Edit where
import IHP.ViewPrelude
import IHP.IDE.SchemaDesigner.Types
import IHP.IDE.ToolServer.Types
import IHP.IDE.SchemaDesigner.View.Layout
data EditEnumView = EditEnumView
{ statements :: [Statement]
, enumName :: Text
, enumId :: Int
}
instance View EditEnumView where
html EditEnumView { .. } = [hsx|
<div class="row no-gutters bg-white" id="schema-designer-viewer">
{renderObjectSelector (zip [0..] statements) Nothing}
{emptyColumnSelectorContainer}
</div>
{migrationStatus}
{renderModal modal}
|]
where
modalContent = [hsx|
<form method="POST" action={UpdateEnumAction}>
<input type="hidden" name="enumId" value={tshow enumId}/>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Name:</label>
<div class="col-sm-10">
<input id="nameInput" name="enumName" type="text" class="form-control" autofocus="autofocus" value={enumName}/>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">Edit Table</button>
</div>
</form>
|]
modalFooter = mempty
modalCloseUrl = pathTo TablesAction
modalTitle = "Edit Enum"
modal = Modal { modalContent, modalFooter, modalCloseUrl, modalTitle }
| null | https://raw.githubusercontent.com/digitallyinduced/ihp/756c95328bdfea3bd8bc7d087a8d45303da40a60/IHP/IDE/SchemaDesigner/View/Enums/Edit.hs | haskell | module IHP.IDE.SchemaDesigner.View.Enums.Edit where
import IHP.ViewPrelude
import IHP.IDE.SchemaDesigner.Types
import IHP.IDE.ToolServer.Types
import IHP.IDE.SchemaDesigner.View.Layout
data EditEnumView = EditEnumView
{ statements :: [Statement]
, enumName :: Text
, enumId :: Int
}
instance View EditEnumView where
html EditEnumView { .. } = [hsx|
<div class="row no-gutters bg-white" id="schema-designer-viewer">
{renderObjectSelector (zip [0..] statements) Nothing}
{emptyColumnSelectorContainer}
</div>
{migrationStatus}
{renderModal modal}
|]
where
modalContent = [hsx|
<form method="POST" action={UpdateEnumAction}>
<input type="hidden" name="enumId" value={tshow enumId}/>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Name:</label>
<div class="col-sm-10">
<input id="nameInput" name="enumName" type="text" class="form-control" autofocus="autofocus" value={enumName}/>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">Edit Table</button>
</div>
</form>
|]
modalFooter = mempty
modalCloseUrl = pathTo TablesAction
modalTitle = "Edit Enum"
modal = Modal { modalContent, modalFooter, modalCloseUrl, modalTitle }
| |
62ac14143ead4d138ba9befb462e51649422572e15f00d1dd307487b1c1cfef4 | pirapira/coq2rust | wg_Notebook.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
class ['a] typed_notebook :
('a -> GObj.widget option * GObj.widget option * GObj.widget) ->
('a -> unit) ->
Gtk.notebook Gtk.obj ->
object
inherit GPack.notebook
method append_term : 'a -> int
method prepend_term : 'a -> int
method set_term : 'a -> unit
method get_nth_term : int -> 'a
method term_num : ('a -> 'a -> bool) -> 'a -> int
method pages : 'a list
method remove_page : int -> unit
method current_term : 'a
end
val create :
('a -> GObj.widget option * GObj.widget option * GObj.widget) ->
('a -> unit) ->
?enable_popup:bool ->
?homogeneous_tabs:bool ->
?scrollable:bool ->
?show_border:bool ->
?show_tabs:bool ->
?tab_border:int ->
?tab_pos:Gtk.Tags.position ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(GObj.widget -> unit) -> ?show:bool -> unit -> 'a typed_notebook
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/ide/wg_Notebook.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
class ['a] typed_notebook :
('a -> GObj.widget option * GObj.widget option * GObj.widget) ->
('a -> unit) ->
Gtk.notebook Gtk.obj ->
object
inherit GPack.notebook
method append_term : 'a -> int
method prepend_term : 'a -> int
method set_term : 'a -> unit
method get_nth_term : int -> 'a
method term_num : ('a -> 'a -> bool) -> 'a -> int
method pages : 'a list
method remove_page : int -> unit
method current_term : 'a
end
val create :
('a -> GObj.widget option * GObj.widget option * GObj.widget) ->
('a -> unit) ->
?enable_popup:bool ->
?homogeneous_tabs:bool ->
?scrollable:bool ->
?show_border:bool ->
?show_tabs:bool ->
?tab_border:int ->
?tab_pos:Gtk.Tags.position ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(GObj.widget -> unit) -> ?show:bool -> unit -> 'a typed_notebook
|
85bed7642d3f3d13fd2cc0630790db3980da4cdfe237d77243207c47e91f5fa9 | Octachron/codept | b.ml | module C = struct end
| null | https://raw.githubusercontent.com/Octachron/codept/2d2a95fde3f67cdd0f5a1b68d8b8b47aefef9290/ocamlbuild/src/b.ml | ocaml | module C = struct end
| |
84b24c871a2ae538aeb2efad6b5b2f4ead29c50625ca366b6a2d1e5260581c58 | SjVer/Lamb | lower.ml | open Anf
module SMap = Map.Make(String)
let ctx = Llvm.create_context ()
let bld = Llvm.builder ctx
let mdl = Llvm.create_module ctx "module"
let i64 = Llvm.i64_type ctx
let malloc =
let fty = Llvm.function_type (Llvm.pointer_type i64) [|i64|] in
Llvm.declare_function "malloc" fty mdl
let func_ty arity =
let args = Array.make arity i64 in
Llvm.function_type i64 args
let tuple_ty len =
let els = Array.make len i64 in
Llvm.struct_type ctx els
let get_const i = Llvm.const_int i64 i
let get_var env v = SMap.find v env
let get_func_ptr g = Option.get (Llvm.lookup_function g mdl)
let lower_atom env = function
| Int i ->get_const i
| Var v -> get_var env v
| Glob g -> Llvm.build_ptrtoint (get_func_ptr g) i64 "casted" bld
let lower_bop =
let open Lang in function
| Add -> Llvm.build_add
| Sub -> Llvm.build_sub
| Mul -> Llvm.build_mul
| Div -> Llvm.build_sdiv
let rec lower_expr env = function
| Return a -> Llvm.build_ret (lower_atom env a) bld
| Break a ->
let bb = SMap.find "\b" env in
let bb' = Llvm.block_of_value bb in
let _ = Llvm.build_br bb' bld in
lower_atom env a
| Tuple (d, es, b) ->
(* malloc the tuple *)
let size = get_const (List.length es * 8) in
let tup = Llvm.build_call malloc [|size|] "tup" bld in
let tup = Llvm.build_malloc ( tuple_ty ( ) ) " tup " bld in
(* set each of the tuple's items *)
let set i v =
let gep = Llvm.build_gep tup [|get_const i|] "gep" bld in
ignore (Llvm.build_store v gep bld);
in
List.iteri (fun i e -> set i (lower_atom env e)) es;
(* convert the tuple to an i64 so it can be used *)
let tup' = Llvm.build_ptrtoint tup i64 d bld in
lower_expr (SMap.add d tup' env) b
| App (d, f, es, b) ->
let es' = List.map (lower_atom env) es in
let ptr = get_var env f in
let fty = Llvm.pointer_type (func_ty (List.length es)) in
let func = Llvm.build_inttoptr ptr fty "func" bld in
let res = Llvm.build_call func (Array.of_list es') "res" bld in
lower_expr (SMap.add d res env) b
| Bop (d, op, x, y, b) ->
let build_op = lower_bop op in
let x' = lower_atom env x in
let y' = lower_atom env y in
let r = build_op x' y' "bopr" bld in
lower_expr (SMap.add d r env) b
| If (d, c, t, e, b) ->
let currf = Llvm.block_parent (Llvm.insertion_block bld) in
let tbb = Llvm.append_block ctx "then" currf in
let ebb = Llvm.append_block ctx "else" currf in
let pbb = Llvm.append_block ctx "phi" currf in
let c' = Llvm.build_is_not_null (lower_atom env c) "cond" bld in
let _ = Llvm.build_cond_br c' tbb ebb bld in
let env' = SMap.add "\b" (Llvm.value_of_block pbb) env in
Llvm.position_at_end tbb bld;
let t' = lower_expr env' t in
let tbb' = Llvm.insertion_block bld in
Llvm.position_at_end ebb bld;
let e' = lower_expr env' e in
let ebb' = Llvm.insertion_block bld in
Llvm.move_block_after ebb' pbb;
Llvm.position_at_end pbb bld;
let p = Llvm.build_phi [t', tbb'; e', ebb'] "phi" bld in
lower_expr (SMap.add d p env) b
| Get (d, t, i, b) ->
let int_to_ptr v n = Llvm.build_inttoptr v (Llvm.pointer_type i64) n bld in
let tup = int_to_ptr (get_var env t) "tup" in
let gep = Llvm.build_gep tup [|get_const i|] "ptr" bld in
let v = Llvm.build_load gep d bld in
lower_expr (SMap.add d v env) b
| _ -> Llvm.build_unreachable bld
failwith " Invalid expression survived hoisting phase ! "
let lower_fn (f, xs, e) =
(* create function *)
let ty = func_ty (List.length xs) in
let fn = Llvm.define_function f ty mdl in
(* gather args *)
let params = Array.to_list (Llvm.params fn) in
let rec bind env = function
| x :: xs, v :: vs ->
Llvm.set_value_name x v;
bind (SMap.add x v env) (xs, vs)
| _ -> env
in let env = bind SMap.empty (xs, params) in
(* build blocks *)
let entry = Llvm.entry_block fn in
Llvm.position_at_end entry bld;
ignore (lower_expr env e)
let lower fns =
List.iter lower_fn fns;
mdl | null | https://raw.githubusercontent.com/SjVer/Lamb/1e901d8ae14d969a65da52e9f5f141b3fd260462/bin/lower.ml | ocaml | malloc the tuple
set each of the tuple's items
convert the tuple to an i64 so it can be used
create function
gather args
build blocks | open Anf
module SMap = Map.Make(String)
let ctx = Llvm.create_context ()
let bld = Llvm.builder ctx
let mdl = Llvm.create_module ctx "module"
let i64 = Llvm.i64_type ctx
let malloc =
let fty = Llvm.function_type (Llvm.pointer_type i64) [|i64|] in
Llvm.declare_function "malloc" fty mdl
let func_ty arity =
let args = Array.make arity i64 in
Llvm.function_type i64 args
let tuple_ty len =
let els = Array.make len i64 in
Llvm.struct_type ctx els
let get_const i = Llvm.const_int i64 i
let get_var env v = SMap.find v env
let get_func_ptr g = Option.get (Llvm.lookup_function g mdl)
let lower_atom env = function
| Int i ->get_const i
| Var v -> get_var env v
| Glob g -> Llvm.build_ptrtoint (get_func_ptr g) i64 "casted" bld
let lower_bop =
let open Lang in function
| Add -> Llvm.build_add
| Sub -> Llvm.build_sub
| Mul -> Llvm.build_mul
| Div -> Llvm.build_sdiv
let rec lower_expr env = function
| Return a -> Llvm.build_ret (lower_atom env a) bld
| Break a ->
let bb = SMap.find "\b" env in
let bb' = Llvm.block_of_value bb in
let _ = Llvm.build_br bb' bld in
lower_atom env a
| Tuple (d, es, b) ->
let size = get_const (List.length es * 8) in
let tup = Llvm.build_call malloc [|size|] "tup" bld in
let tup = Llvm.build_malloc ( tuple_ty ( ) ) " tup " bld in
let set i v =
let gep = Llvm.build_gep tup [|get_const i|] "gep" bld in
ignore (Llvm.build_store v gep bld);
in
List.iteri (fun i e -> set i (lower_atom env e)) es;
let tup' = Llvm.build_ptrtoint tup i64 d bld in
lower_expr (SMap.add d tup' env) b
| App (d, f, es, b) ->
let es' = List.map (lower_atom env) es in
let ptr = get_var env f in
let fty = Llvm.pointer_type (func_ty (List.length es)) in
let func = Llvm.build_inttoptr ptr fty "func" bld in
let res = Llvm.build_call func (Array.of_list es') "res" bld in
lower_expr (SMap.add d res env) b
| Bop (d, op, x, y, b) ->
let build_op = lower_bop op in
let x' = lower_atom env x in
let y' = lower_atom env y in
let r = build_op x' y' "bopr" bld in
lower_expr (SMap.add d r env) b
| If (d, c, t, e, b) ->
let currf = Llvm.block_parent (Llvm.insertion_block bld) in
let tbb = Llvm.append_block ctx "then" currf in
let ebb = Llvm.append_block ctx "else" currf in
let pbb = Llvm.append_block ctx "phi" currf in
let c' = Llvm.build_is_not_null (lower_atom env c) "cond" bld in
let _ = Llvm.build_cond_br c' tbb ebb bld in
let env' = SMap.add "\b" (Llvm.value_of_block pbb) env in
Llvm.position_at_end tbb bld;
let t' = lower_expr env' t in
let tbb' = Llvm.insertion_block bld in
Llvm.position_at_end ebb bld;
let e' = lower_expr env' e in
let ebb' = Llvm.insertion_block bld in
Llvm.move_block_after ebb' pbb;
Llvm.position_at_end pbb bld;
let p = Llvm.build_phi [t', tbb'; e', ebb'] "phi" bld in
lower_expr (SMap.add d p env) b
| Get (d, t, i, b) ->
let int_to_ptr v n = Llvm.build_inttoptr v (Llvm.pointer_type i64) n bld in
let tup = int_to_ptr (get_var env t) "tup" in
let gep = Llvm.build_gep tup [|get_const i|] "ptr" bld in
let v = Llvm.build_load gep d bld in
lower_expr (SMap.add d v env) b
| _ -> Llvm.build_unreachable bld
failwith " Invalid expression survived hoisting phase ! "
let lower_fn (f, xs, e) =
let ty = func_ty (List.length xs) in
let fn = Llvm.define_function f ty mdl in
let params = Array.to_list (Llvm.params fn) in
let rec bind env = function
| x :: xs, v :: vs ->
Llvm.set_value_name x v;
bind (SMap.add x v env) (xs, vs)
| _ -> env
in let env = bind SMap.empty (xs, params) in
let entry = Llvm.entry_block fn in
Llvm.position_at_end entry bld;
ignore (lower_expr env e)
let lower fns =
List.iter lower_fn fns;
mdl |
1c699001a40a94c34b41fdec5a5cc9900ae52442ad29c9b97a4e361122f057d8 | GaloisInc/renovate | ISA.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE TypeInType #-}
# LANGUAGE UndecidableInstances #
| This module defines the interface required for describing an ' ISA '
-- to the rewriter.
--
Implementations of ' ISA 's are in separate @renovate-<arch>@ packages .
module Renovate.ISA
( ISA(..)
, JumpType(..)
, JumpCondition(..)
, StackAddress(..)
, HasModifiableTarget
, NoModifiableTarget
, isaDefaultInstructionArchRepr
, ArchConstraints
) where
import qualified Data.List.NonEmpty as DLN
import Data.Word ( Word8, Word64 )
import qualified Data.Macaw.CFG as MM
import qualified Data.Macaw.Discovery as MD
import qualified Data.Parameterized.Classes as PC
import Data.Parameterized.Some ( Some(..) )
import qualified Renovate.Core.Address as RA
import qualified Renovate.Core.Instruction as RCI
import qualified Renovate.Core.Relocation as RCR
-- | Constraints that must be available for an architecture
--
-- Note that this differs from 'RCI.InstructionConstraints' in that these
-- constraints do not (and cannot) mention the @tp@ type parameter marking the
-- sub-ISA.
type ArchConstraints arch =
( PC.OrdF (RCI.RegisterType arch)
, MM.MemWidth (MM.ArchAddrWidth arch)
, PC.TestEquality (RCI.InstructionArchRepr arch)
, PC.OrdF (RCI.InstructionArchRepr arch)
)
-- | The variety of a jump: either conditional or unconditional. This
is used as a tag for ' JumpType 's . One day , we could model the type
-- of condition here if it began to matter.
data JumpCondition = Unconditional
| Conditional
deriving (Show, Eq)
data JumpKind = HasModifiableTarget
| NoModifiableTarget
-- | A tag denoting a jump type where we can modify the target by modifying the
-- instruction (i.e., where the target is encoded as an immediate operand in
-- some way, either as an address or an offset)
type HasModifiableTarget = 'HasModifiableTarget
-- | A tag denoting a jump that does not have a target that we can modify by
-- changing an operand
type NoModifiableTarget = 'NoModifiableTarget
-- | Metadata about jump instructions
--
-- Note that we model calls as conditional jumps. That isn't exactly
-- right, but it captures the important aspect of calls for basic
-- block recovery: execution continues after the return.
data JumpType arch k where
-- | A relative jump by some offset in bytes, which could be negative. The
-- 'RA.ConcreteAddress' is the address from which the jump was issued.
RelativeJump :: JumpCondition -> RA.ConcreteAddress arch -> MM.MemWord (MM.ArchAddrWidth arch) -> JumpType arch HasModifiableTarget
-- | A jump to an absolute address
AbsoluteJump :: JumpCondition -> RA.ConcreteAddress arch -> JumpType arch HasModifiableTarget
-- | A jump type for indirect jumps, which end blocks but do not let us find
-- new code.
IndirectJump :: JumpCondition -> JumpType arch NoModifiableTarget
-- | A call to a known location expressed as an offset from the jump location
-- (note, this might be difficult to fill in for RISC architectures - macaw
-- would be better suited to finding this information)
DirectCall :: RA.ConcreteAddress arch -> MM.MemWord (MM.ArchAddrWidth arch) -> JumpType arch HasModifiableTarget
-- | A call to an unknown location
IndirectCall :: JumpType arch NoModifiableTarget
-- | A possibly conditional return
Return :: JumpCondition -> JumpType arch NoModifiableTarget
-- | The instruction is not a jump
NoJump :: JumpType arch NoModifiableTarget
-- | The instruction is a recognized control flow transfer, but not one that
-- can be rewritten (and thus is not permitted to be instrumented)
--
-- The address is the address of the instruction
NotInstrumentable :: RA.ConcreteAddress arch -> JumpType arch NoModifiableTarget
deriving instance (MM.MemWidth (MM.ArchAddrWidth arch)) => Show (JumpType arch k)
deriving instance Eq (JumpType arch k)
instance (MM.MemWidth (MM.ArchAddrWidth arch)) => PC.ShowF (JumpType arch)
| Information about an ISA .
--
The @Instruction arch@ type family is the underlying instruction
-- type, which accepts an annotation parameter.
--
-- The @InstructionAnnotation arch@ type family is the type of the
-- annotations of /symbolic/ instructions, and contains information to
-- link control flow transfer instructions to their symbolic targets.
The information required can vary by ISA , so this is a parameter .
--
Concrete instructions have @()@ as their annotation , while symbolic
instructions have ' R.Relocation 's as their annotation .
--
-- The functions `isaSymbolizeAddress` and `isaConcretizeAddress`
-- convert between concrete and symbolic instructions.
--
See separate @renovate-<arch>@ packages for actual ' ISA '
-- definitions.
data ISA arch = ISA
{ isaInstructionSize :: forall t tp . RCI.Instruction arch tp t -> Word8
-- ^ Compute the size of an instruction in bytes
, isaInstructionRepr :: forall t tp . RCI.Instruction arch tp t -> RCI.InstructionArchRepr arch tp
-- ^ Return the type representative for an instruction
, isaSymbolizeAddresses :: forall tp ids
. MM.Memory (MM.ArchAddrWidth arch)
-> (RA.ConcreteAddress arch -> RA.SymbolicAddress arch)
-> MD.ParsedBlock arch ids
-> RA.ConcreteAddress arch
-> RCI.Instruction arch tp ()
-> [RCI.Instruction arch tp (RCR.Relocation arch)]
-- ^ Abstract instructions and annotate them with relocations
--
-- * The function converts concrete (absolute) addresses into symbolic addresses, which will be wrapped up in relocations
--
-- * The 'RA.ConcreteAddress' is the address of the instruction
--
-- NOTE: This function is allowed to return larger instructions now and,
-- in fact, may return extra instructions. We also now allow the
-- concretization phase to increase the size of the instructions, provided
-- that concretizing to targets that are 'isaMaxRelativeJumpSize' far away
-- has the worst case size behavior.
, isaConcretizeAddresses :: forall tp
. MM.Memory (MM.ArchAddrWidth arch)
-> (RA.SymbolicAddress arch -> RA.ConcreteAddress arch)
-> RA.ConcreteAddress arch
-> RCI.Instruction arch tp (RCR.Relocation arch)
-> DLN.NonEmpty (RCI.Instruction arch tp ())
-- ^ Remove the annotation, with possible post-processing.
--
-- This is intended to fix up PC-relative memory references in operands and
-- modify relative jump targets to point to the proper locations.
--
-- NOTE: It is allowed to return extra instructions to accomplish these things.
, isaJumpType :: forall t tp ids
. RCI.Instruction arch tp t
-> MM.Memory (MM.ArchAddrWidth arch)
-> RA.ConcreteAddress arch
-> MD.ParsedBlock arch ids
-> Some (JumpType arch)
-- ^ Test if an instruction is a jump; if it is, return some
-- metadata about the jump (destination or offset).
--
-- The 'MC.Memory' parameter is the memory space containing
-- the known code region. Jumps outside of the known code
-- region are treated as library code and are not
-- followed.
--
-- The 'Address' parameter is the address of the instruction,
-- which is needed to resolve relative jumps.
, isaMakeRelativeJumpTo :: forall tp
. RA.ConcreteAddress arch
-> RA.ConcreteAddress arch
-> RCI.InstructionArchRepr arch tp
-> DLN.NonEmpty (RCI.Instruction arch tp ())
^ Create a relative jump from the first ' RA.ConcreteAddress '
to the second . This will call error if the range is too
-- far (see 'isaMaxRelativeJumpSize').
, isaMaxRelativeJumpSize :: forall tp . RCI.InstructionArchRepr arch tp -> Word64
-- ^ How far can this architecture's unconditional relative jumps reach?
-- New code blocks will be laid out in virtual address space within this
many bytes of the original code blocks , so that the two can jump to each
-- other as necessary.
, isaInstructionArchReprs :: DLN.NonEmpty (RCI.SomeInstructionArchRepr arch)
-- ^ The default arch repr to use if there is nothing else, used in particular
-- in the creation of padding.
, isaMakePadding :: forall tp . Word64 -> RCI.InstructionArchRepr arch tp -> [RCI.Instruction arch tp ()]
-- ^ Make the given number of bytes of padding instructions.
-- The semantics of the instruction stream should either be
-- no-ops or halts (i.e., not meant to be executed).
, isaPrettyInstruction :: forall t tp. RCI.Instruction arch tp t -> String
-- ^ Pretty print an instruction for diagnostic purposes
}
data StackAddress arch (tp :: RCI.InstructionArchReprKind arch) = StackAddress
{ saBase :: RCI.RegisterType arch tp
, saOffset :: Integer
}
deriving instance Eq (RCI.RegisterType arch tp) => Eq (StackAddress arch tp)
deriving instance Ord (RCI.RegisterType arch tp) => Ord (StackAddress arch tp)
deriving instance Show (RCI.RegisterType arch tp) => Show (StackAddress arch tp)
isaDefaultInstructionArchRepr :: ISA arch -> RCI.SomeInstructionArchRepr arch
isaDefaultInstructionArchRepr isa = DLN.head (isaInstructionArchReprs isa)
{-
With the jump type test, we probably want to make a distinction
between intra-segment jumps and inter-segment jumps. We can rewrite
the former. The latter are best left alone for now... though shared
libraries will make that interesting.
-}
| null | https://raw.githubusercontent.com/GaloisInc/renovate/c85c7c472c8ed9b45656e9555093a35dd819c550/renovate/src/Renovate/ISA.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE TypeInType #
to the rewriter.
| Constraints that must be available for an architecture
Note that this differs from 'RCI.InstructionConstraints' in that these
constraints do not (and cannot) mention the @tp@ type parameter marking the
sub-ISA.
| The variety of a jump: either conditional or unconditional. This
of condition here if it began to matter.
| A tag denoting a jump type where we can modify the target by modifying the
instruction (i.e., where the target is encoded as an immediate operand in
some way, either as an address or an offset)
| A tag denoting a jump that does not have a target that we can modify by
changing an operand
| Metadata about jump instructions
Note that we model calls as conditional jumps. That isn't exactly
right, but it captures the important aspect of calls for basic
block recovery: execution continues after the return.
| A relative jump by some offset in bytes, which could be negative. The
'RA.ConcreteAddress' is the address from which the jump was issued.
| A jump to an absolute address
| A jump type for indirect jumps, which end blocks but do not let us find
new code.
| A call to a known location expressed as an offset from the jump location
(note, this might be difficult to fill in for RISC architectures - macaw
would be better suited to finding this information)
| A call to an unknown location
| A possibly conditional return
| The instruction is not a jump
| The instruction is a recognized control flow transfer, but not one that
can be rewritten (and thus is not permitted to be instrumented)
The address is the address of the instruction
type, which accepts an annotation parameter.
The @InstructionAnnotation arch@ type family is the type of the
annotations of /symbolic/ instructions, and contains information to
link control flow transfer instructions to their symbolic targets.
The functions `isaSymbolizeAddress` and `isaConcretizeAddress`
convert between concrete and symbolic instructions.
definitions.
^ Compute the size of an instruction in bytes
^ Return the type representative for an instruction
^ Abstract instructions and annotate them with relocations
* The function converts concrete (absolute) addresses into symbolic addresses, which will be wrapped up in relocations
* The 'RA.ConcreteAddress' is the address of the instruction
NOTE: This function is allowed to return larger instructions now and,
in fact, may return extra instructions. We also now allow the
concretization phase to increase the size of the instructions, provided
that concretizing to targets that are 'isaMaxRelativeJumpSize' far away
has the worst case size behavior.
^ Remove the annotation, with possible post-processing.
This is intended to fix up PC-relative memory references in operands and
modify relative jump targets to point to the proper locations.
NOTE: It is allowed to return extra instructions to accomplish these things.
^ Test if an instruction is a jump; if it is, return some
metadata about the jump (destination or offset).
The 'MC.Memory' parameter is the memory space containing
the known code region. Jumps outside of the known code
region are treated as library code and are not
followed.
The 'Address' parameter is the address of the instruction,
which is needed to resolve relative jumps.
far (see 'isaMaxRelativeJumpSize').
^ How far can this architecture's unconditional relative jumps reach?
New code blocks will be laid out in virtual address space within this
other as necessary.
^ The default arch repr to use if there is nothing else, used in particular
in the creation of padding.
^ Make the given number of bytes of padding instructions.
The semantics of the instruction stream should either be
no-ops or halts (i.e., not meant to be executed).
^ Pretty print an instruction for diagnostic purposes
With the jump type test, we probably want to make a distinction
between intra-segment jumps and inter-segment jumps. We can rewrite
the former. The latter are best left alone for now... though shared
libraries will make that interesting.
| # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
# LANGUAGE StandaloneDeriving #
# LANGUAGE UndecidableInstances #
| This module defines the interface required for describing an ' ISA '
Implementations of ' ISA 's are in separate @renovate-<arch>@ packages .
module Renovate.ISA
( ISA(..)
, JumpType(..)
, JumpCondition(..)
, StackAddress(..)
, HasModifiableTarget
, NoModifiableTarget
, isaDefaultInstructionArchRepr
, ArchConstraints
) where
import qualified Data.List.NonEmpty as DLN
import Data.Word ( Word8, Word64 )
import qualified Data.Macaw.CFG as MM
import qualified Data.Macaw.Discovery as MD
import qualified Data.Parameterized.Classes as PC
import Data.Parameterized.Some ( Some(..) )
import qualified Renovate.Core.Address as RA
import qualified Renovate.Core.Instruction as RCI
import qualified Renovate.Core.Relocation as RCR
type ArchConstraints arch =
( PC.OrdF (RCI.RegisterType arch)
, MM.MemWidth (MM.ArchAddrWidth arch)
, PC.TestEquality (RCI.InstructionArchRepr arch)
, PC.OrdF (RCI.InstructionArchRepr arch)
)
is used as a tag for ' JumpType 's . One day , we could model the type
data JumpCondition = Unconditional
| Conditional
deriving (Show, Eq)
data JumpKind = HasModifiableTarget
| NoModifiableTarget
type HasModifiableTarget = 'HasModifiableTarget
type NoModifiableTarget = 'NoModifiableTarget
data JumpType arch k where
RelativeJump :: JumpCondition -> RA.ConcreteAddress arch -> MM.MemWord (MM.ArchAddrWidth arch) -> JumpType arch HasModifiableTarget
AbsoluteJump :: JumpCondition -> RA.ConcreteAddress arch -> JumpType arch HasModifiableTarget
IndirectJump :: JumpCondition -> JumpType arch NoModifiableTarget
DirectCall :: RA.ConcreteAddress arch -> MM.MemWord (MM.ArchAddrWidth arch) -> JumpType arch HasModifiableTarget
IndirectCall :: JumpType arch NoModifiableTarget
Return :: JumpCondition -> JumpType arch NoModifiableTarget
NoJump :: JumpType arch NoModifiableTarget
NotInstrumentable :: RA.ConcreteAddress arch -> JumpType arch NoModifiableTarget
deriving instance (MM.MemWidth (MM.ArchAddrWidth arch)) => Show (JumpType arch k)
deriving instance Eq (JumpType arch k)
instance (MM.MemWidth (MM.ArchAddrWidth arch)) => PC.ShowF (JumpType arch)
| Information about an ISA .
The @Instruction arch@ type family is the underlying instruction
The information required can vary by ISA , so this is a parameter .
Concrete instructions have @()@ as their annotation , while symbolic
instructions have ' R.Relocation 's as their annotation .
See separate @renovate-<arch>@ packages for actual ' ISA '
data ISA arch = ISA
{ isaInstructionSize :: forall t tp . RCI.Instruction arch tp t -> Word8
, isaInstructionRepr :: forall t tp . RCI.Instruction arch tp t -> RCI.InstructionArchRepr arch tp
, isaSymbolizeAddresses :: forall tp ids
. MM.Memory (MM.ArchAddrWidth arch)
-> (RA.ConcreteAddress arch -> RA.SymbolicAddress arch)
-> MD.ParsedBlock arch ids
-> RA.ConcreteAddress arch
-> RCI.Instruction arch tp ()
-> [RCI.Instruction arch tp (RCR.Relocation arch)]
, isaConcretizeAddresses :: forall tp
. MM.Memory (MM.ArchAddrWidth arch)
-> (RA.SymbolicAddress arch -> RA.ConcreteAddress arch)
-> RA.ConcreteAddress arch
-> RCI.Instruction arch tp (RCR.Relocation arch)
-> DLN.NonEmpty (RCI.Instruction arch tp ())
, isaJumpType :: forall t tp ids
. RCI.Instruction arch tp t
-> MM.Memory (MM.ArchAddrWidth arch)
-> RA.ConcreteAddress arch
-> MD.ParsedBlock arch ids
-> Some (JumpType arch)
, isaMakeRelativeJumpTo :: forall tp
. RA.ConcreteAddress arch
-> RA.ConcreteAddress arch
-> RCI.InstructionArchRepr arch tp
-> DLN.NonEmpty (RCI.Instruction arch tp ())
^ Create a relative jump from the first ' RA.ConcreteAddress '
to the second . This will call error if the range is too
, isaMaxRelativeJumpSize :: forall tp . RCI.InstructionArchRepr arch tp -> Word64
many bytes of the original code blocks , so that the two can jump to each
, isaInstructionArchReprs :: DLN.NonEmpty (RCI.SomeInstructionArchRepr arch)
, isaMakePadding :: forall tp . Word64 -> RCI.InstructionArchRepr arch tp -> [RCI.Instruction arch tp ()]
, isaPrettyInstruction :: forall t tp. RCI.Instruction arch tp t -> String
}
data StackAddress arch (tp :: RCI.InstructionArchReprKind arch) = StackAddress
{ saBase :: RCI.RegisterType arch tp
, saOffset :: Integer
}
deriving instance Eq (RCI.RegisterType arch tp) => Eq (StackAddress arch tp)
deriving instance Ord (RCI.RegisterType arch tp) => Ord (StackAddress arch tp)
deriving instance Show (RCI.RegisterType arch tp) => Show (StackAddress arch tp)
isaDefaultInstructionArchRepr :: ISA arch -> RCI.SomeInstructionArchRepr arch
isaDefaultInstructionArchRepr isa = DLN.head (isaInstructionArchReprs isa)
|
db4313df07bd7032c5d7ce5a4924403e9538a470f90e07acb63d813eeb3c34b4 | codinuum/volt | simple.ml | let main () =
LOG "entering main" LEVEL TRACE;
if (Array.length Sys.argv) = 0 then
LOG "no %s" "argument" LEVEL WARN;
for i = 1 to pred (Array.length Sys.argv) do
try
LOG "getting variable " LEVEL DEBUG;
print_endline (Sys.getenv Sys.argv.(i))
with
| Not_found ->
LOG "undefined variable" PROPERTIES ["var", Sys.argv.(i)] LEVEL ERROR
done;
LOG "leaving main" LEVEL TRACE
let () =
LOG "start ..." NAME "App" LEVEL INFO;
(try
main ()
with e ->
LOG "uncaught exception" EXCEPTION e LEVEL FATAL;
Printexc.print_backtrace stdout);
LOG "end ..." NAME "App" LEVEL INFO
| null | https://raw.githubusercontent.com/codinuum/volt/546207693ef102a2f02c85af935f64a8f16882e6/tests/01-syntax/simple.ml | ocaml | let main () =
LOG "entering main" LEVEL TRACE;
if (Array.length Sys.argv) = 0 then
LOG "no %s" "argument" LEVEL WARN;
for i = 1 to pred (Array.length Sys.argv) do
try
LOG "getting variable " LEVEL DEBUG;
print_endline (Sys.getenv Sys.argv.(i))
with
| Not_found ->
LOG "undefined variable" PROPERTIES ["var", Sys.argv.(i)] LEVEL ERROR
done;
LOG "leaving main" LEVEL TRACE
let () =
LOG "start ..." NAME "App" LEVEL INFO;
(try
main ()
with e ->
LOG "uncaught exception" EXCEPTION e LEVEL FATAL;
Printexc.print_backtrace stdout);
LOG "end ..." NAME "App" LEVEL INFO
| |
6ae50840e99941daf2b09377d8631f8fe0a5bc320440b22dffc13126adadb2ff | facebook/duckling | Rules.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
# LANGUAGE NoRebindableSyntax #
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.NL.BE.Rules
( rules
) where
import Duckling.Time.Helpers
import Duckling.Types
ruleHolidays :: [Rule]
ruleHolidays = mkRuleHolidays
[ ( "Sinterklaas", "sinterklaas", monthDay 12 6 )
]
rules :: [Rule]
rules = ruleHolidays
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Time/NL/BE/Rules.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
# LANGUAGE NoRebindableSyntax #
module Duckling.Time.NL.BE.Rules
( rules
) where
import Duckling.Time.Helpers
import Duckling.Types
ruleHolidays :: [Rule]
ruleHolidays = mkRuleHolidays
[ ( "Sinterklaas", "sinterklaas", monthDay 12 6 )
]
rules :: [Rule]
rules = ruleHolidays
|
1c5a9e436d42a0c2dc932fba87d387bf2aba2272f9654c11e973dbc41aa7f9d6 | softwarelanguageslab/maf | R5RS_scp1_josephus-problem-4.scm | ; Changes:
* removed : 1
* added : 5
* swaps : 1
; * negated predicates: 0
* swapped branches : 1
* calls to i d fun : 2
(letrec ((result ())
(output (lambda (i)
(set! result (cons i result))))
(make-ring (lambda (n)
(let ((last (cons 0 ())))
(letrec ((build-list (lambda (n)
(if (= n 0) last (cons n (build-list (- n 1)))))))
(let ((ring (build-list n)))
(set-cdr! last ring)
ring)))))
(print-ring (lambda (r)
(letrec ((aux (lambda (l)
(if (not (null? l))
(if (eq? (cdr l) r)
(begin
(<change>
()
l)
(output " ")
(<change>
(output (car l))
(output "..."))
(<change>
(output "...")
(output (car l))))
(begin
(<change>
(output " ")
())
(output (car l))
(aux (cdr l))))
#f))))
(<change>
()
r)
(aux r)
#t)))
(copy-ring (lambda (r)
(letrec ((last ())
(aux (lambda (l)
(<change>
()
(cdr l))
(if (eq? (cdr l) r)
(<change>
(begin
(set! last (cons (car l) ()))
last)
(cons (car l) (aux (cdr l))))
(<change>
(cons (car l) (aux (cdr l)))
(begin
(set! last (cons (car l) ()))
last))))))
(<change>
()
set-cdr!)
(let ((first (aux r)))
(set-cdr! last first)
first))))
(right-rotate (lambda (r)
(letrec ((iter (lambda (l)
(if (eq? (cdr l) r) l (iter (cdr l))))))
(iter r))))
(Josephus (lambda (r n)
(letrec ((remove-nth! (lambda (l n)
(<change>
(if (<= n 2)
(begin
(set-cdr! l (cddr l))
(cdr l))
(remove-nth! (cdr l) (- n 1)))
((lambda (x) x) (if (<= n 2) (begin (set-cdr! l (cddr l)) (cdr l)) (remove-nth! (cdr l) (- n 1)))))))
(iter (lambda (l)
(print-ring l)
(if (eq? l (cdr l))
(car l)
(iter (remove-nth! l n))))))
(if (= n 1)
(car (right-rotate r))
(iter (copy-ring r))))))
(ring (make-ring 5)))
(Josephus ring 5)
(<change>
(print-ring ring)
((lambda (x) x) (print-ring ring)))
(<change>
()
__toplevel_cons)
(equal?
result
(__toplevel_cons
"..."
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
1
(__toplevel_cons
" "
(__toplevel_cons
2
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
2
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
1
(__toplevel_cons
" "
(__toplevel_cons
2
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons 4 (__toplevel_cons " " (__toplevel_cons 5 (__toplevel_cons " " ()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_josephus-problem-4.scm | scheme | Changes:
* negated predicates: 0 | * removed : 1
* added : 5
* swaps : 1
* swapped branches : 1
* calls to i d fun : 2
(letrec ((result ())
(output (lambda (i)
(set! result (cons i result))))
(make-ring (lambda (n)
(let ((last (cons 0 ())))
(letrec ((build-list (lambda (n)
(if (= n 0) last (cons n (build-list (- n 1)))))))
(let ((ring (build-list n)))
(set-cdr! last ring)
ring)))))
(print-ring (lambda (r)
(letrec ((aux (lambda (l)
(if (not (null? l))
(if (eq? (cdr l) r)
(begin
(<change>
()
l)
(output " ")
(<change>
(output (car l))
(output "..."))
(<change>
(output "...")
(output (car l))))
(begin
(<change>
(output " ")
())
(output (car l))
(aux (cdr l))))
#f))))
(<change>
()
r)
(aux r)
#t)))
(copy-ring (lambda (r)
(letrec ((last ())
(aux (lambda (l)
(<change>
()
(cdr l))
(if (eq? (cdr l) r)
(<change>
(begin
(set! last (cons (car l) ()))
last)
(cons (car l) (aux (cdr l))))
(<change>
(cons (car l) (aux (cdr l)))
(begin
(set! last (cons (car l) ()))
last))))))
(<change>
()
set-cdr!)
(let ((first (aux r)))
(set-cdr! last first)
first))))
(right-rotate (lambda (r)
(letrec ((iter (lambda (l)
(if (eq? (cdr l) r) l (iter (cdr l))))))
(iter r))))
(Josephus (lambda (r n)
(letrec ((remove-nth! (lambda (l n)
(<change>
(if (<= n 2)
(begin
(set-cdr! l (cddr l))
(cdr l))
(remove-nth! (cdr l) (- n 1)))
((lambda (x) x) (if (<= n 2) (begin (set-cdr! l (cddr l)) (cdr l)) (remove-nth! (cdr l) (- n 1)))))))
(iter (lambda (l)
(print-ring l)
(if (eq? l (cdr l))
(car l)
(iter (remove-nth! l n))))))
(if (= n 1)
(car (right-rotate r))
(iter (copy-ring r))))))
(ring (make-ring 5)))
(Josephus ring 5)
(<change>
(print-ring ring)
((lambda (x) x) (print-ring ring)))
(<change>
()
__toplevel_cons)
(equal?
result
(__toplevel_cons
"..."
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
1
(__toplevel_cons
" "
(__toplevel_cons
2
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
2
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons
4
(__toplevel_cons
" "
(__toplevel_cons
5
(__toplevel_cons
" "
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
"..."
(__toplevel_cons
0
(__toplevel_cons
" "
(__toplevel_cons
1
(__toplevel_cons
" "
(__toplevel_cons
2
(__toplevel_cons
" "
(__toplevel_cons
3
(__toplevel_cons
" "
(__toplevel_cons 4 (__toplevel_cons " " (__toplevel_cons 5 (__toplevel_cons " " ()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) |
2e6d2b7a6f98b2b09798be884860e859ce258e82828e6ac90abefb176cf4bc2c | ghc/ghc | Desugar.hs |
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
# LANGUAGE DisambiguateRecordFields #
| Desugaring step of the
-- [Lower Your Guards paper]().
--
source syntax into guard tree variants Pm * .
In terms of the paper , this module is concerned with Sections 3.1 , Figure 4 ,
-- in particular.
module GHC.HsToCore.Pmc.Desugar (
desugarPatBind, desugarGRHSs, desugarMatches, desugarEmptyCase
) where
import GHC.Prelude
import GHC.HsToCore.Pmc.Types
import GHC.HsToCore.Pmc.Utils
import GHC.Core (Expr(Var,App))
import GHC.Data.FastString (unpackFS, lengthFS)
import GHC.Data.Bag (bagToList)
import GHC.Driver.Session
import GHC.Hs
import GHC.Tc.Utils.Zonk (shortCutLit)
import GHC.Types.Id
import GHC.Core.ConLike
import GHC.Types.Name
import GHC.Builtin.Types
import GHC.Builtin.Names (rationalTyConName)
import GHC.Types.SrcLoc
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Core.DataCon
import GHC.Types.Var (EvVar)
import GHC.Core.Coercion
import GHC.Tc.Types.Evidence (HsWrapper(..), isIdHsWrapper)
import {-# SOURCE #-} GHC.HsToCore.Expr (dsExpr, dsLExpr, dsSyntaxExpr)
import {-# SOURCE #-} GHC.HsToCore.Binds (dsHsWrapper)
import GHC.HsToCore.Utils (isTrueLHsExpr, selectMatchVar, decideBangHood)
import GHC.HsToCore.Match.Literal (dsLit, dsOverLit)
import GHC.HsToCore.Monad
import GHC.Core.TyCo.Rep
import GHC.Core.TyCo.Compare( eqType )
import GHC.Core.Type
import GHC.Data.Maybe
import qualified GHC.LanguageExtensions as LangExt
import GHC.Utils.Monad (concatMapM)
import GHC.Types.SourceText (FractionalLit(..))
import Control.Monad (zipWithM, replicateM)
import Data.List (elemIndex)
import Data.List.NonEmpty ( NonEmpty(..) )
import qualified Data.List.NonEmpty as NE
import GHC.Driver . Ppr
-- | Smart constructor that eliminates trivial lets
mkPmLetVar :: Id -> Id -> [PmGrd]
mkPmLetVar x y | x == y = []
mkPmLetVar x y = [PmLet x (Var y)]
| ADT constructor pattern = > no existentials , no local constraints
vanillaConGrd :: Id -> DataCon -> [Id] -> PmGrd
vanillaConGrd scrut con arg_ids =
PmCon { pm_id = scrut, pm_con_con = PmAltConLike (RealDataCon con)
, pm_con_tvs = [], pm_con_dicts = [], pm_con_args = arg_ids }
| Creates a ' [ PmGrd ] ' refining a match var of list type to a list ,
where list fields are matched against the incoming tagged ' [ PmGrd ] 's .
-- For example:
-- @mkListGrds "a" "[(x, True <- x),(y, !y)]"@
-- to
-- @"[(x:b) <- a, True <- x, (y:c) <- b, !y, [] <- c]"@
where @b@ and @c@ are freshly allocated in @mkListGrds@ and @a@ is the match
-- variable.
mkListGrds :: Id -> [(Id, [PmGrd])] -> DsM [PmGrd]
-- See Note [Order of guards matters] for why we need to intertwine guards
-- on list elements.
mkListGrds a [] = pure [vanillaConGrd a nilDataCon []]
mkListGrds a ((x, head_grds):xs) = do
b <- mkPmId (idType a)
tail_grds <- mkListGrds b xs
pure $ vanillaConGrd a consDataCon [x, b] : head_grds ++ tail_grds
| Create a ' [ PmGrd ] ' refining a match variable to a ' PmLit ' .
mkPmLitGrds :: Id -> PmLit -> DsM [PmGrd]
mkPmLitGrds x (PmLit _ (PmLitString s)) = do
-- We desugar String literals to list literals for better overlap reasoning.
-- It's a little unfortunate we do this here rather than in
-- 'GHC.HsToCore.Pmc.Solver.trySolve' and
' GHC.HsToCore . Pmc . ' , but it 's so much simpler
here . See Note [ Representation of Strings in ] in
-- GHC.HsToCore.Pmc.Solver
vars <- replicateM (lengthFS s) (mkPmId charTy)
let mk_char_lit y c = mkPmLitGrds y (PmLit charTy (PmLitChar c))
char_grdss <- zipWithM mk_char_lit vars (unpackFS s)
mkListGrds x (zip vars char_grdss)
mkPmLitGrds x lit = do
let grd = PmCon { pm_id = x
, pm_con_con = PmAltLit lit
, pm_con_tvs = []
, pm_con_dicts = []
, pm_con_args = [] }
pure [grd]
| @desugarPat _ x pat@ transforms into a ' [ PmGrd ] ' , where
the variable representing the match is @x@.
desugarPat :: Id -> Pat GhcTc -> DsM [PmGrd]
desugarPat x pat = case pat of
WildPat _ty -> pure []
VarPat _ y -> pure (mkPmLetVar (unLoc y) x)
ParPat _ _ p _ -> desugarLPat x p
LazyPat _ _ -> pure [] -- like a wildcard
BangPat _ p@(L l p') ->
-- Add the bang in front of the list, because it will happen before any
-- nested stuff.
(PmBang x pm_loc :) <$> desugarLPat x p
where pm_loc = Just (SrcInfo (L (locA l) (ppr p')))
( x@pat ) = = > pat with x as match var and handle impedance
-- mismatch with incoming match var
AsPat _ (L _ y) _ p -> (mkPmLetVar y x ++) <$> desugarLPat y p
SigPat _ p _ty -> desugarLPat x p
XPat ext -> case ext of
ExpansionPat orig expansion -> do
dflags <- getDynFlags
case orig of
-- We add special logic for overloaded list patterns. When:
- a ViewPat is the expansion of a ListPat ,
-- - RebindableSyntax is off,
-- - the type of the pattern is the built-in list type,
-- then we assume that the view function, 'toList', is the identity.
-- This improves pattern-match overload checks, as this will allow
-- the pattern match checker to directly inspect the inner pattern.
See # 14547 , and Note [ Desugaring overloaded list patterns ] ( Wrinkle ) .
ListPat {}
| ViewPat arg_ty _lexpr pat <- expansion
, not (xopt LangExt.RebindableSyntax dflags)
, Just tc <- tyConAppTyCon_maybe arg_ty
, tc == listTyCon
-> desugarLPat x pat
_ -> desugarPat x expansion
See Note [ ]
-- Generally the translation is
-- pat |> co ===> let y = x |> co, pat <- y where y is a match var of pat
CoPat wrapper p _ty
| isIdHsWrapper wrapper -> desugarPat x p
| WpCast co <- wrapper, isReflexiveCo co -> desugarPat x p
| otherwise -> do
(y, grds) <- desugarPatV p
dsHsWrapper wrapper $ \wrap_rhs_y ->
pure (PmLet y (wrap_rhs_y (Var x)) : grds)
-- (n + k) ===> let b = x >= k, True <- b, let n = x-k
NPlusKPat _pat_ty (L _ n) k1 k2 ge minus -> do
b <- mkPmId boolTy
let grd_b = vanillaConGrd b trueDataCon []
[ke1, ke2] <- traverse dsOverLit [unLoc k1, k2]
rhs_b <- dsSyntaxExpr ge [Var x, ke1]
rhs_n <- dsSyntaxExpr minus [Var x, ke2]
pure [PmLet b rhs_b, grd_b, PmLet n rhs_n]
( fun - > pat ) = = = > let y = fun x , where y is a match var of pat
ViewPat _arg_ty lexpr pat -> do
(y, grds) <- desugarLPatV pat
fun <- dsLExpr lexpr
pure $ PmLet y (App fun (Var x)) : grds
-- list
ListPat _ ps ->
desugarListPat x ps
ConPat { pat_con = L _ con
, pat_args = ps
, pat_con_ext = ConPatTc
{ cpt_arg_tys = arg_tys
, cpt_tvs = ex_tvs
, cpt_dicts = dicts
}
} ->
desugarConPatOut x con arg_tys ex_tvs dicts ps
NPat ty (L _ olit) mb_neg _ -> do
-- See Note [Literal short cut] in "GHC.HsToCore.Match.Literal"
We inline the Literal short cut for @ty@ here , because @ty@ is more
-- precise than the field of OverLitTc, which is all that dsOverLit (which
normally does the literal short cut ) can look at . Also @ty@ matches the
-- type of the scrutinee, so info on both pattern and scrutinee (for which
-- short cutting in dsOverLit works properly) is overloaded iff either is.
dflags <- getDynFlags
let platform = targetPlatform dflags
pm_lit <- case olit of
OverLit{ ol_val = val, ol_ext = OverLitTc { ol_rebindable = rebindable } }
| not rebindable
, Just expr <- shortCutLit platform val ty
-> coreExprAsPmLit <$> dsExpr expr
| not rebindable
, (HsFractional f) <- val
, negates <- if fl_neg f then 1 else 0
-> do
rat_tc <- dsLookupTyCon rationalTyConName
let rat_ty = mkTyConTy rat_tc
return $ Just $ PmLit rat_ty (PmLitOverRat negates f)
| otherwise
-> do
dsLit <- dsOverLit olit
let !pmLit = coreExprAsPmLit dsLit :: Maybe PmLit
-- pprTraceM "desugarPat"
-- (
text " val " < + > ppr val $ $
text " witness " < + > ppr ( ol_witness olit ) $ $
text " dsLit " < + > ppr dsLit $ $
-- text "asPmLit" <+> ppr pmLit
-- )
return pmLit
let lit = case pm_lit of
Just l -> l
Nothing -> pprPanic "failed to detect OverLit" (ppr olit)
let lit' = case mb_neg of
Just _ -> expectJust "failed to negate lit" (negatePmLit lit)
Nothing -> lit
mkPmLitGrds x lit'
LitPat _ lit -> do
core_expr <- dsLit (convertLit lit)
let lit = expectJust "failed to detect Lit" (coreExprAsPmLit core_expr)
mkPmLitGrds x lit
TuplePat _tys pats boxity -> do
(vars, grdss) <- mapAndUnzipM desugarLPatV pats
let tuple_con = tupleDataCon boxity (length vars)
pure $ vanillaConGrd x tuple_con vars : concat grdss
SumPat _ty p alt arity -> do
(y, grds) <- desugarLPatV p
let sum_con = sumDataCon alt arity
See Note [ tuple RuntimeRep vars ] in GHC.Core . TyCon
pure $ vanillaConGrd x sum_con [y] : grds
SplicePat {} -> panic "Check.desugarPat: SplicePat"
-- | 'desugarPat', but also select and return a new match var.
desugarPatV :: Pat GhcTc -> DsM (Id, [PmGrd])
desugarPatV pat = do
x <- selectMatchVar ManyTy pat
grds <- desugarPat x pat
pure (x, grds)
desugarLPat :: Id -> LPat GhcTc -> DsM [PmGrd]
desugarLPat x = desugarPat x . unLoc
-- | 'desugarLPat', but also select and return a new match var.
desugarLPatV :: LPat GhcTc -> DsM (Id, [PmGrd])
desugarLPatV = desugarPatV . unLoc
| @desugarListPat _ x [ p1 , ... , pn]@ is basically
-- @desugarConPatOut _ x $(mkListConPatOuts [p1, ..., pn]>@ without ever
constructing the ' ConPatOut 's .
desugarListPat :: Id -> [LPat GhcTc] -> DsM [PmGrd]
desugarListPat x pats = do
vars_and_grdss <- traverse desugarLPatV pats
mkListGrds x vars_and_grdss
| a constructor pattern
desugarConPatOut :: Id -> ConLike -> [Type] -> [TyVar]
-> [EvVar] -> HsConPatDetails GhcTc -> DsM [PmGrd]
desugarConPatOut x con univ_tys ex_tvs dicts = \case
PrefixCon _ ps -> go_field_pats (zip [0..] ps)
InfixCon p1 p2 -> go_field_pats (zip [0..] [p1,p2])
RecCon (HsRecFields fs _) -> go_field_pats (rec_field_ps fs)
where
-- The actual argument types (instantiated)
arg_tys = map scaledThing $ conLikeInstOrigArgTys con (univ_tys ++ mkTyVarTys ex_tvs)
-- Extract record field patterns tagged by field index from a list of
LHsRecField
rec_field_ps fs = map (tagged_pat . unLoc) fs
where
tagged_pat f = (lbl_to_index (getName (hsRecFieldId f)), hfbRHS f)
Unfortunately the label info is empty when the DataCon was n't defined
-- with record field labels, hence we desugar to field index.
orig_lbls = map flSelector $ conLikeFieldLabels con
lbl_to_index lbl = expectJust "lbl_to_index" $ elemIndex lbl orig_lbls
go_field_pats tagged_pats = do
-- The fields that appear might not be in the correct order. So
-- 1. Do the PmCon match
2 . Then pattern match on the fields in the order given by the first
field of @tagged_pats@.
-- See Note [Field match order for RecCon]
the mentioned field patterns . We 're doing this first to get
the Ids for and bring them in order afterwards .
let trans_pat (n, pat) = do
(var, pvec) <- desugarLPatV pat
pure ((n, var), pvec)
(tagged_vars, arg_grdss) <- mapAndUnzipM trans_pat tagged_pats
let get_pat_id n ty = case lookup n tagged_vars of
Just var -> pure var
Nothing -> mkPmId ty
1 . the constructor pattern match itself
arg_ids <- zipWithM get_pat_id [0..] arg_tys
let con_grd = PmCon x (PmAltConLike con) ex_tvs dicts arg_ids
2 . guards from field selector patterns
let arg_grds = concat arg_grdss
tracePm " ConPatOut " ( ppr x $ $ ppr con $ $ ppr arg_ids )
pure (con_grd : arg_grds)
desugarPatBind :: SrcSpan -> Id -> Pat GhcTc -> DsM (PmPatBind Pre)
See ' GrdPatBind ' for how this simply repurposes .
desugarPatBind loc var pat =
PmPatBind . flip PmGRHS (SrcInfo (L loc (ppr pat))) . GrdVec <$> desugarPat var pat
desugarEmptyCase :: Id -> DsM PmEmptyCase
desugarEmptyCase var = pure PmEmptyCase { pe_var = var }
| the non - empty ' Match'es of a ' MatchGroup ' .
desugarMatches :: [Id] -> NonEmpty (LMatch GhcTc (LHsExpr GhcTc))
-> DsM (PmMatchGroup Pre)
desugarMatches vars matches =
PmMatchGroup <$> traverse (desugarMatch vars) matches
a single match
desugarMatch :: [Id] -> LMatch GhcTc (LHsExpr GhcTc) -> DsM (PmMatch Pre)
desugarMatch vars (L match_loc (Match { m_pats = pats, m_grhss = grhss })) = do
dflags <- getDynFlags
decideBangHood : See Note [ Desugaring -XStrict matches in Pmc ]
let banged_pats = map (decideBangHood dflags) pats
pats' <- concat <$> zipWithM desugarLPat vars banged_pats
grhss' <- desugarGRHSs (locA match_loc) (sep (map ppr pats)) grhss
tracePm " desugarMatch " ( vcat [ ppr pats , ppr pats ' , ppr grhss ' ] )
return PmMatch { pm_pats = GrdVec pats', pm_grhss = grhss' }
desugarGRHSs :: SrcSpan -> SDoc -> GRHSs GhcTc (LHsExpr GhcTc) -> DsM (PmGRHSs Pre)
desugarGRHSs match_loc pp_pats grhss = do
lcls <- desugarLocalBinds (grhssLocalBinds grhss)
grhss' <- traverse (desugarLGRHS match_loc pp_pats)
. expectJust "desugarGRHSs"
. NE.nonEmpty
$ grhssGRHSs grhss
return PmGRHSs { pgs_lcls = GrdVec lcls, pgs_grhss = grhss' }
| a guarded right - hand side to a single ' GrdTree '
desugarLGRHS :: SrcSpan -> SDoc -> LGRHS GhcTc (LHsExpr GhcTc) -> DsM (PmGRHS Pre)
desugarLGRHS match_loc pp_pats (L _loc (GRHS _ gs _)) = do
-- _loc points to the match separator (ie =, ->) that comes after the guards.
-- Hence we have to pass in the match_loc, which we use in case that the RHS
-- is unguarded.
pp_pats is the space - separated pattern of the current Match this
GRHS belongs to , so the @A B part in @A B x | 0 < - x@.
let rhs_info = case gs of
[] -> L match_loc pp_pats
(L grd_loc _):_ -> L (locA grd_loc) (pp_pats <+> vbar <+> interpp'SP gs)
grds <- concatMapM (desugarGuard . unLoc) gs
pure PmGRHS { pg_grds = GrdVec grds, pg_rhs = SrcInfo rhs_info }
| a guard statement to a ' [ PmGrd ] '
desugarGuard :: GuardStmt GhcTc -> DsM [PmGrd]
desugarGuard guard = case guard of
BodyStmt _ e _ _ -> desugarBoolGuard e
LetStmt _ binds -> desugarLocalBinds binds
BindStmt _ p e -> desugarBind p e
LastStmt {} -> panic "desugarGuard LastStmt"
ParStmt {} -> panic "desugarGuard ParStmt"
TransStmt {} -> panic "desugarGuard TransStmt"
RecStmt {} -> panic "desugarGuard RecStmt"
ApplicativeStmt {} -> panic "desugarGuard ApplicativeLastStmt"
| local bindings to a bunch of ' PmLet ' guards .
Deals only with simple or @where@ bindings without any polymorphism ,
-- recursion, pattern bindings etc.
-- See Note [Long-distance information for HsLocalBinds].
desugarLocalBinds :: HsLocalBinds GhcTc -> DsM [PmGrd]
desugarLocalBinds (HsValBinds _ (XValBindsLR (NValBinds binds _))) =
concatMapM (concatMapM go . bagToList) (map snd binds)
where
go :: LHsBind GhcTc -> DsM [PmGrd]
go (L _ FunBind{fun_id = L _ x, fun_matches = mg})
-- See Note [Long-distance information for HsLocalBinds] for why this
-- pattern match is so very specific.
| L _ [L _ Match{m_pats = [], m_grhss = grhss}] <- mg_alts mg
, GRHSs{grhssGRHSs = [L _ (GRHS _ _grds rhs)]} <- grhss = do
core_rhs <- dsLExpr rhs
return [PmLet x core_rhs]
go (L _ (XHsBindsLR (AbsBinds
{ abs_tvs = [], abs_ev_vars = []
, abs_exports=exports, abs_binds = binds }))) = do
Typechecked HsLocalBinds are wrapped in AbsBinds , which carry
-- renamings. See Note [Long-distance information for HsLocalBinds]
-- for the details.
let go_export :: ABExport -> Maybe PmGrd
go_export ABE{abe_poly = x, abe_mono = y, abe_wrap = wrap}
| isIdHsWrapper wrap
= assertPpr (idType x `eqType` idType y)
(ppr x $$ ppr (idType x) $$ ppr y $$ ppr (idType y)) $
Just $ PmLet x (Var y)
| otherwise
= Nothing
let exps = mapMaybe go_export exports
bs <- concatMapM go (bagToList binds)
return (exps ++ bs)
go _ = return []
desugarLocalBinds _binds = return []
| a pattern guard
-- @pat <- e ==> let x = e; <guards for pat <- x>@
desugarBind :: LPat GhcTc -> LHsExpr GhcTc -> DsM [PmGrd]
desugarBind p e = dsLExpr e >>= \case
Var y
| Nothing <- isDataConId_maybe y
RHS is a variable , so that will allow us to omit the let
-> desugarLPat y p
rhs -> do
(x, grds) <- desugarLPatV p
pure (PmLet x rhs : grds)
| a boolean guard
-- @e ==> let x = e; True <- x@
desugarBoolGuard :: LHsExpr GhcTc -> DsM [PmGrd]
desugarBoolGuard e
| isJust (isTrueLHsExpr e) = return []
-- The formal thing to do would be to generate (True <- True)
-- but it is trivial to solve so instead we give back an empty
[ PmGrd ] for efficiency
| otherwise = dsLExpr e >>= \case
Var y
| Nothing <- isDataConId_maybe y
-- Omit the let by matching on y
-> pure [vanillaConGrd y trueDataCon []]
rhs -> do
x <- mkPmId boolTy
pure [PmLet x rhs, vanillaConGrd x trueDataCon []]
Note [ Field match order for RecCon ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The order for RecCon field patterns actually determines evaluation order of
the pattern match . For example :
data T = T { a : : , b : : Int }
f : : T - > ( )
f T { b = 42 , a = ' a ' } = ( )
Then @f ( T ( error " a " ) ( error " b"))@ errors out with " b " because it is mentioned
first in the pattern match .
This means we ca n't just desugar the pattern match to
@[T a b < - x , ' a ' < - a , 42 < - b]@. Instead we have to force them in the
right order : @[T a b < - x , 42 < - b , ' a ' < - a]@.
Note [ Order of guards matters ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Similar to Note [ Field match order for RecCon ] , the order in which the guards
for a pattern match appear matter . Consider a situation similar to T5117 :
f ( 0 : _ ) = ( )
f ( 0 : [ ] ) = ( )
The latter clause is clearly redundant . Yet if we desugar the second clause as
[ x : xs ' < - xs , [ ] < - xs ' , 0 < - x ]
We will say that the second clause only has an inaccessible RHS . That 's because
we force the tail of the list before comparing its head ! So the correct
translation would have been
[ x : xs ' < - xs , 0 < - x , [ ] < - xs ' ]
And we have to take in the guards on list cells into @mkListGrds@.
Note [ ]
~~~~~~~~~~~~~~~~~~~~~~~
The pattern match checker did not know how to handle coerced patterns
` CoPat ` efficiently , which gave rise to # 11276 . The original approach
desugared ` CoPat`s :
pat | > co = = = > x ( pat < - ( x | > co ) )
Why did we do this seemingly unnecessary expansion in the first place ?
The reason is that the type of @pat | > co@ ( which is the type of the value
abstraction we match against ) might be different than that of @pat@. Data
instances such as @Sing ( a : : Bool)@ are a good example of this : If we would
just drop the coercion , we 'd get a type error when matching against its
value abstraction , with the result being that decides that every
possible data constructor fitting is rejected as uninhabited , leading to
a lot of false warnings .
But we can check whether the coercion is a hole or if it is just refl , in
which case we can drop it .
Note [ Long - distance information for HsLocalBinds ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider ( # 18626 )
f : : Int - > ( )
f x | y = ( )
where
y = True
x : : ( )
x | let y = True , y = ( )
Both definitions are exhaustive , but to make the necessary long - distance
connection from @y@ 's binding to its use site in a guard , we have to collect
' PmLet ' guards for the ' HsLocalBinds ' which contain @y@ 's definitions .
In principle , we are only interested in desugaring local binds that are
' FunBind 's , that
* Have no pattern matches . If @y@ above had any patterns , it would be a
function and we ca n't reason about them anyway .
* Have singleton match group with a single GRHS .
Otherwise , what expression to pick in the generated guard @let y = < rhs>@ ?
It turns out that desugaring type - checked local binds in this way is a bit
more complex than expected : Apparently , all bindings are wrapped in ' AbsBinds '
Nfter type - checking . See Note [ AbsBinds ] in " GHC.Hs . Binds " .
We make sure that there is no polymorphism in the way by checking that there
are no ' abs_tvs ' or ' abs_ev_vars ' ( we do n't reason about
@y : : forall a. Eq a = > ... @ ) and that the exports carry no ' HsWrapper 's . In
this case , the exports are a simple renaming substitution that we can capture
with ' PmLet ' . Ultimately we 'll hit those renamed ' FunBind 's , though , which is
the whole point .
The place to store the ' PmLet ' guards for @where@ clauses ( which are per
' GRHSs ' ) is as a field of ' PmGRHSs ' . For plain guards as in the guards of
@x@ , we can simply add them to the ' pg_grds ' field of ' ' .
Note [ Desugaring -XStrict matches in Pmc ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider ( # 21761 )
{ - # LANGUAGE Strict #
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The order for RecCon field patterns actually determines evaluation order of
the pattern match. For example:
data T = T { a :: Char, b :: Int }
f :: T -> ()
f T{ b = 42, a = 'a' } = ()
Then @f (T (error "a") (error "b"))@ errors out with "b" because it is mentioned
first in the pattern match.
This means we can't just desugar the pattern match to
@[T a b <- x, 'a' <- a, 42 <- b]@. Instead we have to force them in the
right order: @[T a b <- x, 42 <- b, 'a' <- a]@.
Note [Order of guards matters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Similar to Note [Field match order for RecCon], the order in which the guards
for a pattern match appear matter. Consider a situation similar to T5117:
f (0:_) = ()
f (0:[]) = ()
The latter clause is clearly redundant. Yet if we desugar the second clause as
[x:xs' <- xs, [] <- xs', 0 <- x]
We will say that the second clause only has an inaccessible RHS. That's because
we force the tail of the list before comparing its head! So the correct
translation would have been
[x:xs' <- xs, 0 <- x, [] <- xs']
And we have to take in the guards on list cells into @mkListGrds@.
Note [Desugar CoPats]
~~~~~~~~~~~~~~~~~~~~~~~
The pattern match checker did not know how to handle coerced patterns
`CoPat` efficiently, which gave rise to #11276. The original approach
desugared `CoPat`s:
pat |> co ===> x (pat <- (x |> co))
Why did we do this seemingly unnecessary expansion in the first place?
The reason is that the type of @pat |> co@ (which is the type of the value
abstraction we match against) might be different than that of @pat@. Data
instances such as @Sing (a :: Bool)@ are a good example of this: If we would
just drop the coercion, we'd get a type error when matching @pat@ against its
value abstraction, with the result being that pmIsSatisfiable decides that every
possible data constructor fitting @pat@ is rejected as uninhabited, leading to
a lot of false warnings.
But we can check whether the coercion is a hole or if it is just refl, in
which case we can drop it.
Note [Long-distance information for HsLocalBinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#18626)
f :: Int -> ()
f x | y = ()
where
y = True
x :: ()
x | let y = True, y = ()
Both definitions are exhaustive, but to make the necessary long-distance
connection from @y@'s binding to its use site in a guard, we have to collect
'PmLet' guards for the 'HsLocalBinds' which contain @y@'s definitions.
In principle, we are only interested in desugaring local binds that are
'FunBind's, that
* Have no pattern matches. If @y@ above had any patterns, it would be a
function and we can't reason about them anyway.
* Have singleton match group with a single GRHS.
Otherwise, what expression to pick in the generated guard @let y = <rhs>@?
It turns out that desugaring type-checked local binds in this way is a bit
more complex than expected: Apparently, all bindings are wrapped in 'AbsBinds'
Nfter type-checking. See Note [AbsBinds] in "GHC.Hs.Binds".
We make sure that there is no polymorphism in the way by checking that there
are no 'abs_tvs' or 'abs_ev_vars' (we don't reason about
@y :: forall a. Eq a => ...@) and that the exports carry no 'HsWrapper's. In
this case, the exports are a simple renaming substitution that we can capture
with 'PmLet'. Ultimately we'll hit those renamed 'FunBind's, though, which is
the whole point.
The place to store the 'PmLet' guards for @where@ clauses (which are per
'GRHSs') is as a field of 'PmGRHSs'. For plain @let@ guards as in the guards of
@x@, we can simply add them to the 'pg_grds' field of 'PmGRHS'.
Note [Desugaring -XStrict matches in Pmc]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#21761)
{-# LANGUAGE Strict #-}
idV :: Void -> Void
idV v = v
Without -XStrict, we would not warn here. But with -XStrict, there is an
implicit bang on `v` and we should give an inaccessible warning for the RHS.
The way we account for that is by calling `decideBangHood` on patterns
in a `Match`, which inserts the implicit bang.
Making the call here actually seems redundant with the call to `decideBangHood`
in `GHC.HsToCore.Match.matchWrapper`, which does it *after* it calls the
pattern-match checker on the Match's patterns. It would be great if we could expect
`matchWrapper` to pass the bang-adorned `Match` to the pattern-match checker,
but sadly then we get worse warning messages which would print `idV` as if the
user *had* written a bang:
Pattern match has inaccessible right hand side
- In an equation for ‘idV’: idV v = ...
+ In an equation for ‘idV’: idV !v = ...
So we live with the duplication.
-}
| null | https://raw.githubusercontent.com/ghc/ghc/d0c7bbedb741e6bf947bcdc0e097070242ab56e1/compiler/GHC/HsToCore/Pmc/Desugar.hs | haskell | # LANGUAGE GADTs #
[Lower Your Guards paper]().
in particular.
# SOURCE #
# SOURCE #
| Smart constructor that eliminates trivial lets
For example:
@mkListGrds "a" "[(x, True <- x),(y, !y)]"@
to
@"[(x:b) <- a, True <- x, (y:c) <- b, !y, [] <- c]"@
variable.
See Note [Order of guards matters] for why we need to intertwine guards
on list elements.
We desugar String literals to list literals for better overlap reasoning.
It's a little unfortunate we do this here rather than in
'GHC.HsToCore.Pmc.Solver.trySolve' and
GHC.HsToCore.Pmc.Solver
like a wildcard
Add the bang in front of the list, because it will happen before any
nested stuff.
mismatch with incoming match var
We add special logic for overloaded list patterns. When:
- RebindableSyntax is off,
- the type of the pattern is the built-in list type,
then we assume that the view function, 'toList', is the identity.
This improves pattern-match overload checks, as this will allow
the pattern match checker to directly inspect the inner pattern.
Generally the translation is
pat |> co ===> let y = x |> co, pat <- y where y is a match var of pat
(n + k) ===> let b = x >= k, True <- b, let n = x-k
list
See Note [Literal short cut] in "GHC.HsToCore.Match.Literal"
precise than the field of OverLitTc, which is all that dsOverLit (which
type of the scrutinee, so info on both pattern and scrutinee (for which
short cutting in dsOverLit works properly) is overloaded iff either is.
pprTraceM "desugarPat"
(
text "asPmLit" <+> ppr pmLit
)
| 'desugarPat', but also select and return a new match var.
| 'desugarLPat', but also select and return a new match var.
@desugarConPatOut _ x $(mkListConPatOuts [p1, ..., pn]>@ without ever
The actual argument types (instantiated)
Extract record field patterns tagged by field index from a list of
with record field labels, hence we desugar to field index.
The fields that appear might not be in the correct order. So
1. Do the PmCon match
See Note [Field match order for RecCon]
_loc points to the match separator (ie =, ->) that comes after the guards.
Hence we have to pass in the match_loc, which we use in case that the RHS
is unguarded.
recursion, pattern bindings etc.
See Note [Long-distance information for HsLocalBinds].
See Note [Long-distance information for HsLocalBinds] for why this
pattern match is so very specific.
renamings. See Note [Long-distance information for HsLocalBinds]
for the details.
@pat <- e ==> let x = e; <guards for pat <- x>@
@e ==> let x = e; True <- x@
The formal thing to do would be to generate (True <- True)
but it is trivial to solve so instead we give back an empty
Omit the let by matching on y
# LANGUAGE Strict # |
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE DisambiguateRecordFields #
| Desugaring step of the
source syntax into guard tree variants Pm * .
In terms of the paper , this module is concerned with Sections 3.1 , Figure 4 ,
module GHC.HsToCore.Pmc.Desugar (
desugarPatBind, desugarGRHSs, desugarMatches, desugarEmptyCase
) where
import GHC.Prelude
import GHC.HsToCore.Pmc.Types
import GHC.HsToCore.Pmc.Utils
import GHC.Core (Expr(Var,App))
import GHC.Data.FastString (unpackFS, lengthFS)
import GHC.Data.Bag (bagToList)
import GHC.Driver.Session
import GHC.Hs
import GHC.Tc.Utils.Zonk (shortCutLit)
import GHC.Types.Id
import GHC.Core.ConLike
import GHC.Types.Name
import GHC.Builtin.Types
import GHC.Builtin.Names (rationalTyConName)
import GHC.Types.SrcLoc
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Core.DataCon
import GHC.Types.Var (EvVar)
import GHC.Core.Coercion
import GHC.Tc.Types.Evidence (HsWrapper(..), isIdHsWrapper)
import GHC.HsToCore.Utils (isTrueLHsExpr, selectMatchVar, decideBangHood)
import GHC.HsToCore.Match.Literal (dsLit, dsOverLit)
import GHC.HsToCore.Monad
import GHC.Core.TyCo.Rep
import GHC.Core.TyCo.Compare( eqType )
import GHC.Core.Type
import GHC.Data.Maybe
import qualified GHC.LanguageExtensions as LangExt
import GHC.Utils.Monad (concatMapM)
import GHC.Types.SourceText (FractionalLit(..))
import Control.Monad (zipWithM, replicateM)
import Data.List (elemIndex)
import Data.List.NonEmpty ( NonEmpty(..) )
import qualified Data.List.NonEmpty as NE
import GHC.Driver . Ppr
mkPmLetVar :: Id -> Id -> [PmGrd]
mkPmLetVar x y | x == y = []
mkPmLetVar x y = [PmLet x (Var y)]
| ADT constructor pattern = > no existentials , no local constraints
vanillaConGrd :: Id -> DataCon -> [Id] -> PmGrd
vanillaConGrd scrut con arg_ids =
PmCon { pm_id = scrut, pm_con_con = PmAltConLike (RealDataCon con)
, pm_con_tvs = [], pm_con_dicts = [], pm_con_args = arg_ids }
| Creates a ' [ PmGrd ] ' refining a match var of list type to a list ,
where list fields are matched against the incoming tagged ' [ PmGrd ] 's .
where @b@ and @c@ are freshly allocated in @mkListGrds@ and @a@ is the match
mkListGrds :: Id -> [(Id, [PmGrd])] -> DsM [PmGrd]
mkListGrds a [] = pure [vanillaConGrd a nilDataCon []]
mkListGrds a ((x, head_grds):xs) = do
b <- mkPmId (idType a)
tail_grds <- mkListGrds b xs
pure $ vanillaConGrd a consDataCon [x, b] : head_grds ++ tail_grds
| Create a ' [ PmGrd ] ' refining a match variable to a ' PmLit ' .
mkPmLitGrds :: Id -> PmLit -> DsM [PmGrd]
mkPmLitGrds x (PmLit _ (PmLitString s)) = do
' GHC.HsToCore . Pmc . ' , but it 's so much simpler
here . See Note [ Representation of Strings in ] in
vars <- replicateM (lengthFS s) (mkPmId charTy)
let mk_char_lit y c = mkPmLitGrds y (PmLit charTy (PmLitChar c))
char_grdss <- zipWithM mk_char_lit vars (unpackFS s)
mkListGrds x (zip vars char_grdss)
mkPmLitGrds x lit = do
let grd = PmCon { pm_id = x
, pm_con_con = PmAltLit lit
, pm_con_tvs = []
, pm_con_dicts = []
, pm_con_args = [] }
pure [grd]
| @desugarPat _ x pat@ transforms into a ' [ PmGrd ] ' , where
the variable representing the match is @x@.
desugarPat :: Id -> Pat GhcTc -> DsM [PmGrd]
desugarPat x pat = case pat of
WildPat _ty -> pure []
VarPat _ y -> pure (mkPmLetVar (unLoc y) x)
ParPat _ _ p _ -> desugarLPat x p
BangPat _ p@(L l p') ->
(PmBang x pm_loc :) <$> desugarLPat x p
where pm_loc = Just (SrcInfo (L (locA l) (ppr p')))
( x@pat ) = = > pat with x as match var and handle impedance
AsPat _ (L _ y) _ p -> (mkPmLetVar y x ++) <$> desugarLPat y p
SigPat _ p _ty -> desugarLPat x p
XPat ext -> case ext of
ExpansionPat orig expansion -> do
dflags <- getDynFlags
case orig of
- a ViewPat is the expansion of a ListPat ,
See # 14547 , and Note [ Desugaring overloaded list patterns ] ( Wrinkle ) .
ListPat {}
| ViewPat arg_ty _lexpr pat <- expansion
, not (xopt LangExt.RebindableSyntax dflags)
, Just tc <- tyConAppTyCon_maybe arg_ty
, tc == listTyCon
-> desugarLPat x pat
_ -> desugarPat x expansion
See Note [ ]
CoPat wrapper p _ty
| isIdHsWrapper wrapper -> desugarPat x p
| WpCast co <- wrapper, isReflexiveCo co -> desugarPat x p
| otherwise -> do
(y, grds) <- desugarPatV p
dsHsWrapper wrapper $ \wrap_rhs_y ->
pure (PmLet y (wrap_rhs_y (Var x)) : grds)
NPlusKPat _pat_ty (L _ n) k1 k2 ge minus -> do
b <- mkPmId boolTy
let grd_b = vanillaConGrd b trueDataCon []
[ke1, ke2] <- traverse dsOverLit [unLoc k1, k2]
rhs_b <- dsSyntaxExpr ge [Var x, ke1]
rhs_n <- dsSyntaxExpr minus [Var x, ke2]
pure [PmLet b rhs_b, grd_b, PmLet n rhs_n]
( fun - > pat ) = = = > let y = fun x , where y is a match var of pat
ViewPat _arg_ty lexpr pat -> do
(y, grds) <- desugarLPatV pat
fun <- dsLExpr lexpr
pure $ PmLet y (App fun (Var x)) : grds
ListPat _ ps ->
desugarListPat x ps
ConPat { pat_con = L _ con
, pat_args = ps
, pat_con_ext = ConPatTc
{ cpt_arg_tys = arg_tys
, cpt_tvs = ex_tvs
, cpt_dicts = dicts
}
} ->
desugarConPatOut x con arg_tys ex_tvs dicts ps
NPat ty (L _ olit) mb_neg _ -> do
We inline the Literal short cut for @ty@ here , because @ty@ is more
normally does the literal short cut ) can look at . Also @ty@ matches the
dflags <- getDynFlags
let platform = targetPlatform dflags
pm_lit <- case olit of
OverLit{ ol_val = val, ol_ext = OverLitTc { ol_rebindable = rebindable } }
| not rebindable
, Just expr <- shortCutLit platform val ty
-> coreExprAsPmLit <$> dsExpr expr
| not rebindable
, (HsFractional f) <- val
, negates <- if fl_neg f then 1 else 0
-> do
rat_tc <- dsLookupTyCon rationalTyConName
let rat_ty = mkTyConTy rat_tc
return $ Just $ PmLit rat_ty (PmLitOverRat negates f)
| otherwise
-> do
dsLit <- dsOverLit olit
let !pmLit = coreExprAsPmLit dsLit :: Maybe PmLit
text " val " < + > ppr val $ $
text " witness " < + > ppr ( ol_witness olit ) $ $
text " dsLit " < + > ppr dsLit $ $
return pmLit
let lit = case pm_lit of
Just l -> l
Nothing -> pprPanic "failed to detect OverLit" (ppr olit)
let lit' = case mb_neg of
Just _ -> expectJust "failed to negate lit" (negatePmLit lit)
Nothing -> lit
mkPmLitGrds x lit'
LitPat _ lit -> do
core_expr <- dsLit (convertLit lit)
let lit = expectJust "failed to detect Lit" (coreExprAsPmLit core_expr)
mkPmLitGrds x lit
TuplePat _tys pats boxity -> do
(vars, grdss) <- mapAndUnzipM desugarLPatV pats
let tuple_con = tupleDataCon boxity (length vars)
pure $ vanillaConGrd x tuple_con vars : concat grdss
SumPat _ty p alt arity -> do
(y, grds) <- desugarLPatV p
let sum_con = sumDataCon alt arity
See Note [ tuple RuntimeRep vars ] in GHC.Core . TyCon
pure $ vanillaConGrd x sum_con [y] : grds
SplicePat {} -> panic "Check.desugarPat: SplicePat"
desugarPatV :: Pat GhcTc -> DsM (Id, [PmGrd])
desugarPatV pat = do
x <- selectMatchVar ManyTy pat
grds <- desugarPat x pat
pure (x, grds)
desugarLPat :: Id -> LPat GhcTc -> DsM [PmGrd]
desugarLPat x = desugarPat x . unLoc
desugarLPatV :: LPat GhcTc -> DsM (Id, [PmGrd])
desugarLPatV = desugarPatV . unLoc
| @desugarListPat _ x [ p1 , ... , pn]@ is basically
constructing the ' ConPatOut 's .
desugarListPat :: Id -> [LPat GhcTc] -> DsM [PmGrd]
desugarListPat x pats = do
vars_and_grdss <- traverse desugarLPatV pats
mkListGrds x vars_and_grdss
| a constructor pattern
desugarConPatOut :: Id -> ConLike -> [Type] -> [TyVar]
-> [EvVar] -> HsConPatDetails GhcTc -> DsM [PmGrd]
desugarConPatOut x con univ_tys ex_tvs dicts = \case
PrefixCon _ ps -> go_field_pats (zip [0..] ps)
InfixCon p1 p2 -> go_field_pats (zip [0..] [p1,p2])
RecCon (HsRecFields fs _) -> go_field_pats (rec_field_ps fs)
where
arg_tys = map scaledThing $ conLikeInstOrigArgTys con (univ_tys ++ mkTyVarTys ex_tvs)
LHsRecField
rec_field_ps fs = map (tagged_pat . unLoc) fs
where
tagged_pat f = (lbl_to_index (getName (hsRecFieldId f)), hfbRHS f)
Unfortunately the label info is empty when the DataCon was n't defined
orig_lbls = map flSelector $ conLikeFieldLabels con
lbl_to_index lbl = expectJust "lbl_to_index" $ elemIndex lbl orig_lbls
go_field_pats tagged_pats = do
2 . Then pattern match on the fields in the order given by the first
field of @tagged_pats@.
the mentioned field patterns . We 're doing this first to get
the Ids for and bring them in order afterwards .
let trans_pat (n, pat) = do
(var, pvec) <- desugarLPatV pat
pure ((n, var), pvec)
(tagged_vars, arg_grdss) <- mapAndUnzipM trans_pat tagged_pats
let get_pat_id n ty = case lookup n tagged_vars of
Just var -> pure var
Nothing -> mkPmId ty
1 . the constructor pattern match itself
arg_ids <- zipWithM get_pat_id [0..] arg_tys
let con_grd = PmCon x (PmAltConLike con) ex_tvs dicts arg_ids
2 . guards from field selector patterns
let arg_grds = concat arg_grdss
tracePm " ConPatOut " ( ppr x $ $ ppr con $ $ ppr arg_ids )
pure (con_grd : arg_grds)
desugarPatBind :: SrcSpan -> Id -> Pat GhcTc -> DsM (PmPatBind Pre)
See ' GrdPatBind ' for how this simply repurposes .
desugarPatBind loc var pat =
PmPatBind . flip PmGRHS (SrcInfo (L loc (ppr pat))) . GrdVec <$> desugarPat var pat
desugarEmptyCase :: Id -> DsM PmEmptyCase
desugarEmptyCase var = pure PmEmptyCase { pe_var = var }
| the non - empty ' Match'es of a ' MatchGroup ' .
desugarMatches :: [Id] -> NonEmpty (LMatch GhcTc (LHsExpr GhcTc))
-> DsM (PmMatchGroup Pre)
desugarMatches vars matches =
PmMatchGroup <$> traverse (desugarMatch vars) matches
a single match
desugarMatch :: [Id] -> LMatch GhcTc (LHsExpr GhcTc) -> DsM (PmMatch Pre)
desugarMatch vars (L match_loc (Match { m_pats = pats, m_grhss = grhss })) = do
dflags <- getDynFlags
decideBangHood : See Note [ Desugaring -XStrict matches in Pmc ]
let banged_pats = map (decideBangHood dflags) pats
pats' <- concat <$> zipWithM desugarLPat vars banged_pats
grhss' <- desugarGRHSs (locA match_loc) (sep (map ppr pats)) grhss
tracePm " desugarMatch " ( vcat [ ppr pats , ppr pats ' , ppr grhss ' ] )
return PmMatch { pm_pats = GrdVec pats', pm_grhss = grhss' }
desugarGRHSs :: SrcSpan -> SDoc -> GRHSs GhcTc (LHsExpr GhcTc) -> DsM (PmGRHSs Pre)
desugarGRHSs match_loc pp_pats grhss = do
lcls <- desugarLocalBinds (grhssLocalBinds grhss)
grhss' <- traverse (desugarLGRHS match_loc pp_pats)
. expectJust "desugarGRHSs"
. NE.nonEmpty
$ grhssGRHSs grhss
return PmGRHSs { pgs_lcls = GrdVec lcls, pgs_grhss = grhss' }
| a guarded right - hand side to a single ' GrdTree '
desugarLGRHS :: SrcSpan -> SDoc -> LGRHS GhcTc (LHsExpr GhcTc) -> DsM (PmGRHS Pre)
desugarLGRHS match_loc pp_pats (L _loc (GRHS _ gs _)) = do
pp_pats is the space - separated pattern of the current Match this
GRHS belongs to , so the @A B part in @A B x | 0 < - x@.
let rhs_info = case gs of
[] -> L match_loc pp_pats
(L grd_loc _):_ -> L (locA grd_loc) (pp_pats <+> vbar <+> interpp'SP gs)
grds <- concatMapM (desugarGuard . unLoc) gs
pure PmGRHS { pg_grds = GrdVec grds, pg_rhs = SrcInfo rhs_info }
| a guard statement to a ' [ PmGrd ] '
desugarGuard :: GuardStmt GhcTc -> DsM [PmGrd]
desugarGuard guard = case guard of
BodyStmt _ e _ _ -> desugarBoolGuard e
LetStmt _ binds -> desugarLocalBinds binds
BindStmt _ p e -> desugarBind p e
LastStmt {} -> panic "desugarGuard LastStmt"
ParStmt {} -> panic "desugarGuard ParStmt"
TransStmt {} -> panic "desugarGuard TransStmt"
RecStmt {} -> panic "desugarGuard RecStmt"
ApplicativeStmt {} -> panic "desugarGuard ApplicativeLastStmt"
| local bindings to a bunch of ' PmLet ' guards .
Deals only with simple or @where@ bindings without any polymorphism ,
desugarLocalBinds :: HsLocalBinds GhcTc -> DsM [PmGrd]
desugarLocalBinds (HsValBinds _ (XValBindsLR (NValBinds binds _))) =
concatMapM (concatMapM go . bagToList) (map snd binds)
where
go :: LHsBind GhcTc -> DsM [PmGrd]
go (L _ FunBind{fun_id = L _ x, fun_matches = mg})
| L _ [L _ Match{m_pats = [], m_grhss = grhss}] <- mg_alts mg
, GRHSs{grhssGRHSs = [L _ (GRHS _ _grds rhs)]} <- grhss = do
core_rhs <- dsLExpr rhs
return [PmLet x core_rhs]
go (L _ (XHsBindsLR (AbsBinds
{ abs_tvs = [], abs_ev_vars = []
, abs_exports=exports, abs_binds = binds }))) = do
Typechecked HsLocalBinds are wrapped in AbsBinds , which carry
let go_export :: ABExport -> Maybe PmGrd
go_export ABE{abe_poly = x, abe_mono = y, abe_wrap = wrap}
| isIdHsWrapper wrap
= assertPpr (idType x `eqType` idType y)
(ppr x $$ ppr (idType x) $$ ppr y $$ ppr (idType y)) $
Just $ PmLet x (Var y)
| otherwise
= Nothing
let exps = mapMaybe go_export exports
bs <- concatMapM go (bagToList binds)
return (exps ++ bs)
go _ = return []
desugarLocalBinds _binds = return []
| a pattern guard
desugarBind :: LPat GhcTc -> LHsExpr GhcTc -> DsM [PmGrd]
desugarBind p e = dsLExpr e >>= \case
Var y
| Nothing <- isDataConId_maybe y
RHS is a variable , so that will allow us to omit the let
-> desugarLPat y p
rhs -> do
(x, grds) <- desugarLPatV p
pure (PmLet x rhs : grds)
| a boolean guard
desugarBoolGuard :: LHsExpr GhcTc -> DsM [PmGrd]
desugarBoolGuard e
| isJust (isTrueLHsExpr e) = return []
[ PmGrd ] for efficiency
| otherwise = dsLExpr e >>= \case
Var y
| Nothing <- isDataConId_maybe y
-> pure [vanillaConGrd y trueDataCon []]
rhs -> do
x <- mkPmId boolTy
pure [PmLet x rhs, vanillaConGrd x trueDataCon []]
Note [ Field match order for RecCon ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The order for RecCon field patterns actually determines evaluation order of
the pattern match . For example :
data T = T { a : : , b : : Int }
f : : T - > ( )
f T { b = 42 , a = ' a ' } = ( )
Then @f ( T ( error " a " ) ( error " b"))@ errors out with " b " because it is mentioned
first in the pattern match .
This means we ca n't just desugar the pattern match to
@[T a b < - x , ' a ' < - a , 42 < - b]@. Instead we have to force them in the
right order : @[T a b < - x , 42 < - b , ' a ' < - a]@.
Note [ Order of guards matters ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Similar to Note [ Field match order for RecCon ] , the order in which the guards
for a pattern match appear matter . Consider a situation similar to T5117 :
f ( 0 : _ ) = ( )
f ( 0 : [ ] ) = ( )
The latter clause is clearly redundant . Yet if we desugar the second clause as
[ x : xs ' < - xs , [ ] < - xs ' , 0 < - x ]
We will say that the second clause only has an inaccessible RHS . That 's because
we force the tail of the list before comparing its head ! So the correct
translation would have been
[ x : xs ' < - xs , 0 < - x , [ ] < - xs ' ]
And we have to take in the guards on list cells into @mkListGrds@.
Note [ ]
~~~~~~~~~~~~~~~~~~~~~~~
The pattern match checker did not know how to handle coerced patterns
` CoPat ` efficiently , which gave rise to # 11276 . The original approach
desugared ` CoPat`s :
pat | > co = = = > x ( pat < - ( x | > co ) )
Why did we do this seemingly unnecessary expansion in the first place ?
The reason is that the type of @pat | > co@ ( which is the type of the value
abstraction we match against ) might be different than that of @pat@. Data
instances such as @Sing ( a : : Bool)@ are a good example of this : If we would
just drop the coercion , we 'd get a type error when matching against its
value abstraction , with the result being that decides that every
possible data constructor fitting is rejected as uninhabited , leading to
a lot of false warnings .
But we can check whether the coercion is a hole or if it is just refl , in
which case we can drop it .
Note [ Long - distance information for HsLocalBinds ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider ( # 18626 )
f : : Int - > ( )
f x | y = ( )
where
y = True
x : : ( )
x | let y = True , y = ( )
Both definitions are exhaustive , but to make the necessary long - distance
connection from @y@ 's binding to its use site in a guard , we have to collect
' PmLet ' guards for the ' HsLocalBinds ' which contain @y@ 's definitions .
In principle , we are only interested in desugaring local binds that are
' FunBind 's , that
* Have no pattern matches . If @y@ above had any patterns , it would be a
function and we ca n't reason about them anyway .
* Have singleton match group with a single GRHS .
Otherwise , what expression to pick in the generated guard @let y = < rhs>@ ?
It turns out that desugaring type - checked local binds in this way is a bit
more complex than expected : Apparently , all bindings are wrapped in ' AbsBinds '
Nfter type - checking . See Note [ AbsBinds ] in " GHC.Hs . Binds " .
We make sure that there is no polymorphism in the way by checking that there
are no ' abs_tvs ' or ' abs_ev_vars ' ( we do n't reason about
@y : : forall a. Eq a = > ... @ ) and that the exports carry no ' HsWrapper 's . In
this case , the exports are a simple renaming substitution that we can capture
with ' PmLet ' . Ultimately we 'll hit those renamed ' FunBind 's , though , which is
the whole point .
The place to store the ' PmLet ' guards for @where@ clauses ( which are per
' GRHSs ' ) is as a field of ' PmGRHSs ' . For plain guards as in the guards of
@x@ , we can simply add them to the ' pg_grds ' field of ' ' .
Note [ Desugaring -XStrict matches in Pmc ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider ( # 21761 )
{ - # LANGUAGE Strict #
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The order for RecCon field patterns actually determines evaluation order of
the pattern match. For example:
data T = T { a :: Char, b :: Int }
f :: T -> ()
f T{ b = 42, a = 'a' } = ()
Then @f (T (error "a") (error "b"))@ errors out with "b" because it is mentioned
first in the pattern match.
This means we can't just desugar the pattern match to
@[T a b <- x, 'a' <- a, 42 <- b]@. Instead we have to force them in the
right order: @[T a b <- x, 42 <- b, 'a' <- a]@.
Note [Order of guards matters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Similar to Note [Field match order for RecCon], the order in which the guards
for a pattern match appear matter. Consider a situation similar to T5117:
f (0:_) = ()
f (0:[]) = ()
The latter clause is clearly redundant. Yet if we desugar the second clause as
[x:xs' <- xs, [] <- xs', 0 <- x]
We will say that the second clause only has an inaccessible RHS. That's because
we force the tail of the list before comparing its head! So the correct
translation would have been
[x:xs' <- xs, 0 <- x, [] <- xs']
And we have to take in the guards on list cells into @mkListGrds@.
Note [Desugar CoPats]
~~~~~~~~~~~~~~~~~~~~~~~
The pattern match checker did not know how to handle coerced patterns
`CoPat` efficiently, which gave rise to #11276. The original approach
desugared `CoPat`s:
pat |> co ===> x (pat <- (x |> co))
Why did we do this seemingly unnecessary expansion in the first place?
The reason is that the type of @pat |> co@ (which is the type of the value
abstraction we match against) might be different than that of @pat@. Data
instances such as @Sing (a :: Bool)@ are a good example of this: If we would
just drop the coercion, we'd get a type error when matching @pat@ against its
value abstraction, with the result being that pmIsSatisfiable decides that every
possible data constructor fitting @pat@ is rejected as uninhabited, leading to
a lot of false warnings.
But we can check whether the coercion is a hole or if it is just refl, in
which case we can drop it.
Note [Long-distance information for HsLocalBinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#18626)
f :: Int -> ()
f x | y = ()
where
y = True
x :: ()
x | let y = True, y = ()
Both definitions are exhaustive, but to make the necessary long-distance
connection from @y@'s binding to its use site in a guard, we have to collect
'PmLet' guards for the 'HsLocalBinds' which contain @y@'s definitions.
In principle, we are only interested in desugaring local binds that are
'FunBind's, that
* Have no pattern matches. If @y@ above had any patterns, it would be a
function and we can't reason about them anyway.
* Have singleton match group with a single GRHS.
Otherwise, what expression to pick in the generated guard @let y = <rhs>@?
It turns out that desugaring type-checked local binds in this way is a bit
more complex than expected: Apparently, all bindings are wrapped in 'AbsBinds'
Nfter type-checking. See Note [AbsBinds] in "GHC.Hs.Binds".
We make sure that there is no polymorphism in the way by checking that there
are no 'abs_tvs' or 'abs_ev_vars' (we don't reason about
@y :: forall a. Eq a => ...@) and that the exports carry no 'HsWrapper's. In
this case, the exports are a simple renaming substitution that we can capture
with 'PmLet'. Ultimately we'll hit those renamed 'FunBind's, though, which is
the whole point.
The place to store the 'PmLet' guards for @where@ clauses (which are per
'GRHSs') is as a field of 'PmGRHSs'. For plain @let@ guards as in the guards of
@x@, we can simply add them to the 'pg_grds' field of 'PmGRHS'.
Note [Desugaring -XStrict matches in Pmc]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#21761)
idV :: Void -> Void
idV v = v
Without -XStrict, we would not warn here. But with -XStrict, there is an
implicit bang on `v` and we should give an inaccessible warning for the RHS.
The way we account for that is by calling `decideBangHood` on patterns
in a `Match`, which inserts the implicit bang.
Making the call here actually seems redundant with the call to `decideBangHood`
in `GHC.HsToCore.Match.matchWrapper`, which does it *after* it calls the
pattern-match checker on the Match's patterns. It would be great if we could expect
`matchWrapper` to pass the bang-adorned `Match` to the pattern-match checker,
but sadly then we get worse warning messages which would print `idV` as if the
user *had* written a bang:
Pattern match has inaccessible right hand side
- In an equation for ‘idV’: idV v = ...
+ In an equation for ‘idV’: idV !v = ...
So we live with the duplication.
-}
|
e163f0f4f2695ae3a34624d644cd2f2f3c146b792eb922a2711471720bec7263 | SquidDev/illuaminate | lint_unknown_global.mli | * Warn when using an unknown global .
Ideally this 'd be merged with { ! } , with some complex description of
" other " modules , but this is a good " first " approximation .
Ideally this'd be merged with {!Lint_unresolved_reference}, with some complex description of
"other" modules, but this is a good "first" approximation. *)
include Linter.S
| null | https://raw.githubusercontent.com/SquidDev/illuaminate/da18b101b4710881b71c42554d70a3a7d17c3cd6/src/lint/lint_unknown_global.mli | ocaml | * Warn when using an unknown global .
Ideally this 'd be merged with { ! } , with some complex description of
" other " modules , but this is a good " first " approximation .
Ideally this'd be merged with {!Lint_unresolved_reference}, with some complex description of
"other" modules, but this is a good "first" approximation. *)
include Linter.S
| |
e3cd818a4cdb3c6f36538491fc2cb37ee11a7b12a275abd8ab453bb29de66b13 | jayunit100/RudolF | web.clj | (ns demo.web
(:use [ring.adapter.jetty]
[BioClojure.seqUtils]
[BioClojure.nmrSampleSchedule]))
(defn demo []
(let [random_motif (apply str (rand-motif-str (rand-int 30)))
random_aa (rand-aa-str (rand-int 40))
translated_aa (aa-to-3-letter random_aa)]
["rand dna = " random_motif "; a rand protein = " random_aa " which is translated to " translated_aa]))
(defn demoPretty []
(interpose "<BR> " (demo)))
(defn app [req]
{:status 200
:headers {"Content-Type" "text/html"}
:body (str
["Welcome Mini-ClotifMiner : The Flagship App of the BioClojure Framework <BR></BR> demo:"
(demo)
"<H1>A Prettier Version : in one line of code, using ' interpose ' demoPretty:</H1>"
(demoPretty)
"<PRE>An NMR sampling schedule:"
(format-schedule example)
"</PRE>"])})
(defn -main []
(let [port (Integer/parseInt (System/getenv "PORT"))]
(run-jetty app {:port port})))
| null | https://raw.githubusercontent.com/jayunit100/RudolF/8936bafbb30c65c78b820062dec550ceeea4b3a4/bioclojure/src/demo/web.clj | clojure | (ns demo.web
(:use [ring.adapter.jetty]
[BioClojure.seqUtils]
[BioClojure.nmrSampleSchedule]))
(defn demo []
(let [random_motif (apply str (rand-motif-str (rand-int 30)))
random_aa (rand-aa-str (rand-int 40))
translated_aa (aa-to-3-letter random_aa)]
["rand dna = " random_motif "; a rand protein = " random_aa " which is translated to " translated_aa]))
(defn demoPretty []
(interpose "<BR> " (demo)))
(defn app [req]
{:status 200
:headers {"Content-Type" "text/html"}
:body (str
["Welcome Mini-ClotifMiner : The Flagship App of the BioClojure Framework <BR></BR> demo:"
(demo)
"<H1>A Prettier Version : in one line of code, using ' interpose ' demoPretty:</H1>"
(demoPretty)
"<PRE>An NMR sampling schedule:"
(format-schedule example)
"</PRE>"])})
(defn -main []
(let [port (Integer/parseInt (System/getenv "PORT"))]
(run-jetty app {:port port})))
| |
b298a74eee4b7d6010ac791503d008f98f160bcb9e60be6da24eb327044088a1 | jackfirth/racket-expect | main.rkt | #lang reprovide
"context.rkt"
"convert-base.rkt"
"convert.rkt"
"data-dict.rkt"
"data-sequence.rkt"
"data-set.rkt"
"data-syntax.rkt"
| null | https://raw.githubusercontent.com/jackfirth/racket-expect/9530df30537ae05400b6a3add9619e5f697dca52/private/data/main.rkt | racket | #lang reprovide
"context.rkt"
"convert-base.rkt"
"convert.rkt"
"data-dict.rkt"
"data-sequence.rkt"
"data-set.rkt"
"data-syntax.rkt"
| |
7dfc12646dc0231b0f1509d20bcebee00e988dc0d0a74f0b6104e30e41899814 | BetterThanTomorrow/joyride | require_extension_test.cljs | (ns integration-test.require-extension-test
(:require [cljs.test :refer [testing is]]
[promesa.core :as p]
["ext" :as ns-required-extension]
[integration-test.macros :refer [deftest-async]]))
#_{:clj-kondo/ignore [:duplicate-require]}
(require '["ext" :as top-level-required-extension])
(deftest-async ns-require-extension
(testing "ns form did require the Joyride extension"
(p/let [answer (ns-required-extension/runCode "42")]
(is (= 42 answer)))))
(deftest-async top-level-require-extension
(testing "Requires the Joyride extension"
(p/let [question (top-level-required-extension/runCode "42")]
(is (= 42 question)))))
| null | https://raw.githubusercontent.com/BetterThanTomorrow/joyride/c67cc35d3ea2c8662380371b11d4a5617d71913f/vscode-test-runner/workspace-1/.joyride/src/integration_test/require_extension_test.cljs | clojure | (ns integration-test.require-extension-test
(:require [cljs.test :refer [testing is]]
[promesa.core :as p]
["ext" :as ns-required-extension]
[integration-test.macros :refer [deftest-async]]))
#_{:clj-kondo/ignore [:duplicate-require]}
(require '["ext" :as top-level-required-extension])
(deftest-async ns-require-extension
(testing "ns form did require the Joyride extension"
(p/let [answer (ns-required-extension/runCode "42")]
(is (= 42 answer)))))
(deftest-async top-level-require-extension
(testing "Requires the Joyride extension"
(p/let [question (top-level-required-extension/runCode "42")]
(is (= 42 question)))))
| |
4b39064739c703e6063d0e470e4e4bfc9649be01da1a17c3f8e46a4730d22293 | o1-labs/snarkette | mnt6_80.ml | open Core_kernel
open Fields
module N = Nat
module Fq =
Make_fp
(N)
(struct
let order =
N.of_string
"475922286169261325753349249653048451545124878552823515553267735739164647307408490559963137"
end)
let non_residue = Fq.of_int 5
module Fq3 = struct
module Params = struct
let non_residue = non_residue
let frobenius_coeffs_c1 =
[| Fq.of_string "1"
; Fq.of_string
"471738898967521029133040851318449165997304108729558973770077319830005517129946578866686956"
; Fq.of_string
"4183387201740296620308398334599285547820769823264541783190415909159130177461911693276180"
|]
let frobenius_coeffs_c2 =
[| Fq.of_string "1"
; Fq.of_string
"4183387201740296620308398334599285547820769823264541783190415909159130177461911693276180"
; Fq.of_string
"471738898967521029133040851318449165997304108729558973770077319830005517129946578866686956"
|]
end
include Make_fp3 (Fq) (Params)
end
module Fq2 =
Make_fp2
(Fq)
(struct
let non_residue = non_residue
end)
module Fq6 = struct
module Params = struct
let non_residue = non_residue
let frobenius_coeffs_c1 =
Array.map ~f:Fq.of_string
[| "1"
; "471738898967521029133040851318449165997304108729558973770077319830005517129946578866686957"
; "471738898967521029133040851318449165997304108729558973770077319830005517129946578866686956"
; "475922286169261325753349249653048451545124878552823515553267735739164647307408490559963136"
; "4183387201740296620308398334599285547820769823264541783190415909159130177461911693276180"
; "4183387201740296620308398334599285547820769823264541783190415909159130177461911693276181"
|]
end
include Make_fp6 (N) (Fq) (Fq2) (Fq3) (Params)
end
module G1 = struct
include Elliptic_curve.Make (N) (Fq)
(struct
let a = Fq.of_string "11"
let b =
Fq.of_string
"106700080510851735677967319632585352256454251201367587890185989362936000262606668469523074"
end)
let one : t =
{ x=
Fq.of_string
"336685752883082228109289846353937104185698209371404178342968838739115829740084426881123453"
; y=
Fq.of_string
"402596290139780989709332707716568920777622032073762749862342374583908837063963736098549800"
; z= Fq.one }
end
module G2 = struct
include Elliptic_curve.Make (N) (Fq3)
(struct
let a : Fq3.t = (Fq.zero, Fq.zero, G1.Coefficients.a)
let b : Fq3.t =
(Fq.(G1.Coefficients.b * Fq3.non_residue), Fq.zero, Fq.zero)
end)
let one : t =
let open Fq in
{ z= Fq3.one
; x=
( of_string
"421456435772811846256826561593908322288509115489119907560382401870203318738334702321297427"
, of_string
"103072927438548502463527009961344915021167584706439945404959058962657261178393635706405114"
, of_string
"143029172143731852627002926324735183809768363301149009204849580478324784395590388826052558"
)
; y=
( of_string
"464673596668689463130099227575639512541218133445388869383893594087634649237515554342751377"
, of_string
"100642907501977375184575075967118071807821117960152743335603284583254620685343989304941678"
, of_string
"123019855502969896026940545715841181300275180157288044663051565390506010149881373807142903"
) }
end
module Pairing_info = struct
let twist : Fq3.t = Fq.(zero, one, zero)
let loop_count = N.of_string "689871209842287392837045615510547309923794944"
let is_loop_count_neg = true
let final_exponent =
N.of_string
"24416320138090509697890595414313438768353977489862543935904010715439066975957855922532159264213056712140358746422742237328406558352706591021642230618060502855451264045397444793186876199015256781648746888625527075466063075011307800862173764236311342105211681121426931616843635215852236649271569251468773714424208521977615548771268520882870120900360322044218806712027729351845307690474985502587527753847200130592058098363641559341826790559426614919168"
let final_exponent_last_chunk_abs_of_w0 =
N.of_string "689871209842287392837045615510547309923794944"
let final_exponent_last_chunk_is_w0_neg = true
let final_exponent_last_chunk_w1 = N.of_string "1"
end
module Pairing = Pairing.Make (N) (Fq) (Fq3) (Fq6) (G1) (G2) (Pairing_info)
module Groth_maller = Groth_maller.Make (struct
module N = N
module G1 = G1
module G2 = G2
module Fq = Fq
module Fqe = Fq3
module Fq_target = Fq6
module Pairing = Pairing
end)
| null | https://raw.githubusercontent.com/o1-labs/snarkette/c4af4a5f654497183871b5f2ee99005020be20d8/src/mnt6_80.ml | ocaml | open Core_kernel
open Fields
module N = Nat
module Fq =
Make_fp
(N)
(struct
let order =
N.of_string
"475922286169261325753349249653048451545124878552823515553267735739164647307408490559963137"
end)
let non_residue = Fq.of_int 5
module Fq3 = struct
module Params = struct
let non_residue = non_residue
let frobenius_coeffs_c1 =
[| Fq.of_string "1"
; Fq.of_string
"471738898967521029133040851318449165997304108729558973770077319830005517129946578866686956"
; Fq.of_string
"4183387201740296620308398334599285547820769823264541783190415909159130177461911693276180"
|]
let frobenius_coeffs_c2 =
[| Fq.of_string "1"
; Fq.of_string
"4183387201740296620308398334599285547820769823264541783190415909159130177461911693276180"
; Fq.of_string
"471738898967521029133040851318449165997304108729558973770077319830005517129946578866686956"
|]
end
include Make_fp3 (Fq) (Params)
end
module Fq2 =
Make_fp2
(Fq)
(struct
let non_residue = non_residue
end)
module Fq6 = struct
module Params = struct
let non_residue = non_residue
let frobenius_coeffs_c1 =
Array.map ~f:Fq.of_string
[| "1"
; "471738898967521029133040851318449165997304108729558973770077319830005517129946578866686957"
; "471738898967521029133040851318449165997304108729558973770077319830005517129946578866686956"
; "475922286169261325753349249653048451545124878552823515553267735739164647307408490559963136"
; "4183387201740296620308398334599285547820769823264541783190415909159130177461911693276180"
; "4183387201740296620308398334599285547820769823264541783190415909159130177461911693276181"
|]
end
include Make_fp6 (N) (Fq) (Fq2) (Fq3) (Params)
end
module G1 = struct
include Elliptic_curve.Make (N) (Fq)
(struct
let a = Fq.of_string "11"
let b =
Fq.of_string
"106700080510851735677967319632585352256454251201367587890185989362936000262606668469523074"
end)
let one : t =
{ x=
Fq.of_string
"336685752883082228109289846353937104185698209371404178342968838739115829740084426881123453"
; y=
Fq.of_string
"402596290139780989709332707716568920777622032073762749862342374583908837063963736098549800"
; z= Fq.one }
end
module G2 = struct
include Elliptic_curve.Make (N) (Fq3)
(struct
let a : Fq3.t = (Fq.zero, Fq.zero, G1.Coefficients.a)
let b : Fq3.t =
(Fq.(G1.Coefficients.b * Fq3.non_residue), Fq.zero, Fq.zero)
end)
let one : t =
let open Fq in
{ z= Fq3.one
; x=
( of_string
"421456435772811846256826561593908322288509115489119907560382401870203318738334702321297427"
, of_string
"103072927438548502463527009961344915021167584706439945404959058962657261178393635706405114"
, of_string
"143029172143731852627002926324735183809768363301149009204849580478324784395590388826052558"
)
; y=
( of_string
"464673596668689463130099227575639512541218133445388869383893594087634649237515554342751377"
, of_string
"100642907501977375184575075967118071807821117960152743335603284583254620685343989304941678"
, of_string
"123019855502969896026940545715841181300275180157288044663051565390506010149881373807142903"
) }
end
module Pairing_info = struct
let twist : Fq3.t = Fq.(zero, one, zero)
let loop_count = N.of_string "689871209842287392837045615510547309923794944"
let is_loop_count_neg = true
let final_exponent =
N.of_string
"24416320138090509697890595414313438768353977489862543935904010715439066975957855922532159264213056712140358746422742237328406558352706591021642230618060502855451264045397444793186876199015256781648746888625527075466063075011307800862173764236311342105211681121426931616843635215852236649271569251468773714424208521977615548771268520882870120900360322044218806712027729351845307690474985502587527753847200130592058098363641559341826790559426614919168"
let final_exponent_last_chunk_abs_of_w0 =
N.of_string "689871209842287392837045615510547309923794944"
let final_exponent_last_chunk_is_w0_neg = true
let final_exponent_last_chunk_w1 = N.of_string "1"
end
module Pairing = Pairing.Make (N) (Fq) (Fq3) (Fq6) (G1) (G2) (Pairing_info)
module Groth_maller = Groth_maller.Make (struct
module N = N
module G1 = G1
module G2 = G2
module Fq = Fq
module Fqe = Fq3
module Fq_target = Fq6
module Pairing = Pairing
end)
| |
1c3e53ceb993c22605749562179fa28489168d4dc5d1dcce325f8561728a1ccd | ovotech/ring-jwt | token.clj | (ns ring.middleware.token
(:require [cheshire.core :as json]
[clojure.walk :refer [postwalk]]
[ring.middleware.jwk :as jwk]
[clojure.spec.alpha :as s])
(:import (com.auth0.jwt.algorithms Algorithm)
(com.auth0.jwt JWT)
(com.auth0.jwt.exceptions JWTDecodeException)
(org.apache.commons.codec Charsets)
(org.apache.commons.codec.binary Base64)
(java.security PublicKey)))
(defn keywordize-non-namespaced-claims
"Walks through the claims keywordizing them unless the key is namespaced. This is detected
by virtue of checking for the presence of a '/' in the key name."
[m]
(let [namespaced? #(clojure.string/includes? % "/")
keywordize-pair (fn [[k v]]
[(if (and (string? k) (not (namespaced? k)))
(keyword k) k)
v])]
(postwalk #(cond-> % (map? %) (->> (map keywordize-pair)
(into {})))
m)))
(defn- base64->map
[base64-str]
(-> base64-str
(Base64/decodeBase64)
(String. Charsets/UTF_8)
(json/parse-string)
(keywordize-non-namespaced-claims)))
(defn- decode-token*
[algorithm token {:keys [leeway-seconds]}]
(-> algorithm
(JWT/require)
(.acceptLeeway (or leeway-seconds 0))
(.build)
(.verify token)
(.getPayload)
(base64->map)))
(defn decode-issuer
[token]
(-> token JWT/decode (.getIssuer)))
(s/def ::alg #{:RS256 :HS256 :ES256})
(s/def ::issuer (s/or :string (s/and string? (complement clojure.string/blank?))
:keyword #{:no-issuer}))
(s/def ::leeway-seconds nat-int?)
(s/def ::secret (s/and string? (complement clojure.string/blank?)))
(s/def ::secret-opts (s/and (s/keys :req-un [::alg ::secret])
#(contains? #{:HS256} (:alg %))))
(s/def ::public-key #(instance? PublicKey %))
(s/def ::jwk-endpoint (s/and string? #(re-matches #"(?i)^https?://.+$" %)))
(s/def ::public-key-opts (s/and #(contains? #{:RS256 :ES256} (:alg %))
(s/or :key (s/keys :req-un [::alg ::public-key])
:url (s/keys :req-un [::alg ::jwk-endpoint]))))
(defmulti decode
"Decodes and verifies the signature of the given JWT token. The decoded claims from the token are returned."
(fn [_ {:keys [alg]}] alg))
(defmethod decode nil
[& _]
(throw (JWTDecodeException. "Could not parse algorithm.")))
(defmethod decode :ES256
[token {:keys [public-key] :as opts}]
{:pre [(s/valid? ::public-key-opts opts)]}
(let [[public-key-type _] (s/conform ::public-key-opts opts)]
(assert (= :key public-key-type))
(-> (Algorithm/ECDSA256 public-key)
(decode-token* token opts))))
(defmethod decode :RS256
[token {:keys [public-key jwk-endpoint] :as opts}]
{:pre [(s/valid? ::public-key-opts opts)]}
(let [[public-key-type _] (s/conform ::public-key-opts opts)]
(-> (Algorithm/RSA256 (case public-key-type
:url (jwk/rsa-key-provider jwk-endpoint)
:key public-key))
(decode-token* token opts))))
(defmethod decode :HS256
[token {:keys [secret] :as opts}]
{:pre [(s/valid? ::secret-opts opts)]}
(-> (Algorithm/HMAC256 secret)
(decode-token* token opts)))
| null | https://raw.githubusercontent.com/ovotech/ring-jwt/6977423b57a16bcf67761531dabea1edfd3b3371/src/ring/middleware/token.clj | clojure | (ns ring.middleware.token
(:require [cheshire.core :as json]
[clojure.walk :refer [postwalk]]
[ring.middleware.jwk :as jwk]
[clojure.spec.alpha :as s])
(:import (com.auth0.jwt.algorithms Algorithm)
(com.auth0.jwt JWT)
(com.auth0.jwt.exceptions JWTDecodeException)
(org.apache.commons.codec Charsets)
(org.apache.commons.codec.binary Base64)
(java.security PublicKey)))
(defn keywordize-non-namespaced-claims
"Walks through the claims keywordizing them unless the key is namespaced. This is detected
by virtue of checking for the presence of a '/' in the key name."
[m]
(let [namespaced? #(clojure.string/includes? % "/")
keywordize-pair (fn [[k v]]
[(if (and (string? k) (not (namespaced? k)))
(keyword k) k)
v])]
(postwalk #(cond-> % (map? %) (->> (map keywordize-pair)
(into {})))
m)))
(defn- base64->map
[base64-str]
(-> base64-str
(Base64/decodeBase64)
(String. Charsets/UTF_8)
(json/parse-string)
(keywordize-non-namespaced-claims)))
(defn- decode-token*
[algorithm token {:keys [leeway-seconds]}]
(-> algorithm
(JWT/require)
(.acceptLeeway (or leeway-seconds 0))
(.build)
(.verify token)
(.getPayload)
(base64->map)))
(defn decode-issuer
[token]
(-> token JWT/decode (.getIssuer)))
(s/def ::alg #{:RS256 :HS256 :ES256})
(s/def ::issuer (s/or :string (s/and string? (complement clojure.string/blank?))
:keyword #{:no-issuer}))
(s/def ::leeway-seconds nat-int?)
(s/def ::secret (s/and string? (complement clojure.string/blank?)))
(s/def ::secret-opts (s/and (s/keys :req-un [::alg ::secret])
#(contains? #{:HS256} (:alg %))))
(s/def ::public-key #(instance? PublicKey %))
(s/def ::jwk-endpoint (s/and string? #(re-matches #"(?i)^https?://.+$" %)))
(s/def ::public-key-opts (s/and #(contains? #{:RS256 :ES256} (:alg %))
(s/or :key (s/keys :req-un [::alg ::public-key])
:url (s/keys :req-un [::alg ::jwk-endpoint]))))
(defmulti decode
"Decodes and verifies the signature of the given JWT token. The decoded claims from the token are returned."
(fn [_ {:keys [alg]}] alg))
(defmethod decode nil
[& _]
(throw (JWTDecodeException. "Could not parse algorithm.")))
(defmethod decode :ES256
[token {:keys [public-key] :as opts}]
{:pre [(s/valid? ::public-key-opts opts)]}
(let [[public-key-type _] (s/conform ::public-key-opts opts)]
(assert (= :key public-key-type))
(-> (Algorithm/ECDSA256 public-key)
(decode-token* token opts))))
(defmethod decode :RS256
[token {:keys [public-key jwk-endpoint] :as opts}]
{:pre [(s/valid? ::public-key-opts opts)]}
(let [[public-key-type _] (s/conform ::public-key-opts opts)]
(-> (Algorithm/RSA256 (case public-key-type
:url (jwk/rsa-key-provider jwk-endpoint)
:key public-key))
(decode-token* token opts))))
(defmethod decode :HS256
[token {:keys [secret] :as opts}]
{:pre [(s/valid? ::secret-opts opts)]}
(-> (Algorithm/HMAC256 secret)
(decode-token* token opts)))
| |
56300aa174a33a35d3c0d78bb52836325f58b836ff033c0fef7de32679d645d7 | penpot/penpot | radius.cljc | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
;; Copyright (c) KALEIDOS INC
(ns app.common.types.shape.radius
(:require
[app.common.pages.common :refer [editable-attrs]]
[app.common.spec :as us]
[clojure.spec.alpha :as s]))
(s/def ::rx ::us/safe-number)
(s/def ::ry ::us/safe-number)
(s/def ::r1 ::us/safe-number)
(s/def ::r2 ::us/safe-number)
(s/def ::r3 ::us/safe-number)
(s/def ::r4 ::us/safe-number)
;; There are some shapes that admit border radius, as rectangles
frames and images . Those shapes may define the radius of the corners in two modes :
- radius-1 all corners have the same radius ( although we store two
;; values :rx and :ry because svg uses it this way).
;; - radius-4 each corner (top-left, top-right, bottom-right, bottom-left)
;; has an independent value. SVG does not allow this directly, so we
;; emulate it with paths.
;; A shape never will have both :rx and :r1 simultaneously
All operations take into account that the shape may not be a one of those
;; shapes that has border radius, and so it hasn't :rx nor :r1.
;; In this case operations must leave shape untouched.
(defn has-radius?
[shape]
(contains? (get editable-attrs (:type shape)) :rx))
(defn radius-mode
[shape]
(if (:r1 shape)
:radius-4
:radius-1))
(defn radius-1?
[shape]
(and (:rx shape) (not= (:rx shape) 0)))
(defn radius-4?
[shape]
(and (:r1 shape)
(or (not= (:r1 shape) 0)
(not= (:r2 shape) 0)
(not= (:r3 shape) 0)
(not= (:r4 shape) 0))))
(defn all-equal?
[shape]
(= (:r1 shape) (:r2 shape) (:r3 shape) (:r4 shape)))
(defn switch-to-radius-1
[shape]
(let [r (if (all-equal? shape) (:r1 shape) 0)]
(cond-> shape
(:r1 shape)
(-> (assoc :rx r :ry r)
(dissoc :r1 :r2 :r3 :r4)))))
(defn switch-to-radius-4
[shape]
(cond-> shape
(:rx shape)
(-> (assoc :r1 (:rx shape)
:r2 (:rx shape)
:r3 (:rx shape)
:r4 (:rx shape))
(dissoc :rx :ry))))
(defn set-radius-1
[shape value]
(cond-> shape
(:r1 shape)
(-> (dissoc :r1 :r2 :r3 :r4)
(assoc :rx 0 :ry 0))
:always
(assoc :rx value :ry value)))
(defn set-radius-4
[shape attr value]
(let [attr (cond->> attr
(:flip-x shape)
(get {:r1 :r2 :r2 :r1 :r3 :r4 :r4 :r3})
(:flip-y shape)
(get {:r1 :r4 :r2 :r3 :r3 :r2 :r4 :r1}))]
(cond-> shape
(:rx shape)
(-> (dissoc :rx :rx)
(assoc :r1 0 :r2 0 :r3 0 :r4 0))
:always
(assoc attr value))))
| null | https://raw.githubusercontent.com/penpot/penpot/5463671db13441ba3f730a34118547d34a5a36f1/common/src/app/common/types/shape/radius.cljc | clojure |
Copyright (c) KALEIDOS INC
There are some shapes that admit border radius, as rectangles
values :rx and :ry because svg uses it this way).
- radius-4 each corner (top-left, top-right, bottom-right, bottom-left)
has an independent value. SVG does not allow this directly, so we
emulate it with paths.
A shape never will have both :rx and :r1 simultaneously
shapes that has border radius, and so it hasn't :rx nor :r1.
In this case operations must leave shape untouched. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns app.common.types.shape.radius
(:require
[app.common.pages.common :refer [editable-attrs]]
[app.common.spec :as us]
[clojure.spec.alpha :as s]))
(s/def ::rx ::us/safe-number)
(s/def ::ry ::us/safe-number)
(s/def ::r1 ::us/safe-number)
(s/def ::r2 ::us/safe-number)
(s/def ::r3 ::us/safe-number)
(s/def ::r4 ::us/safe-number)
frames and images . Those shapes may define the radius of the corners in two modes :
- radius-1 all corners have the same radius ( although we store two
All operations take into account that the shape may not be a one of those
(defn has-radius?
[shape]
(contains? (get editable-attrs (:type shape)) :rx))
(defn radius-mode
[shape]
(if (:r1 shape)
:radius-4
:radius-1))
(defn radius-1?
[shape]
(and (:rx shape) (not= (:rx shape) 0)))
(defn radius-4?
[shape]
(and (:r1 shape)
(or (not= (:r1 shape) 0)
(not= (:r2 shape) 0)
(not= (:r3 shape) 0)
(not= (:r4 shape) 0))))
(defn all-equal?
[shape]
(= (:r1 shape) (:r2 shape) (:r3 shape) (:r4 shape)))
(defn switch-to-radius-1
[shape]
(let [r (if (all-equal? shape) (:r1 shape) 0)]
(cond-> shape
(:r1 shape)
(-> (assoc :rx r :ry r)
(dissoc :r1 :r2 :r3 :r4)))))
(defn switch-to-radius-4
[shape]
(cond-> shape
(:rx shape)
(-> (assoc :r1 (:rx shape)
:r2 (:rx shape)
:r3 (:rx shape)
:r4 (:rx shape))
(dissoc :rx :ry))))
(defn set-radius-1
[shape value]
(cond-> shape
(:r1 shape)
(-> (dissoc :r1 :r2 :r3 :r4)
(assoc :rx 0 :ry 0))
:always
(assoc :rx value :ry value)))
(defn set-radius-4
[shape attr value]
(let [attr (cond->> attr
(:flip-x shape)
(get {:r1 :r2 :r2 :r1 :r3 :r4 :r4 :r3})
(:flip-y shape)
(get {:r1 :r4 :r2 :r3 :r3 :r2 :r4 :r1}))]
(cond-> shape
(:rx shape)
(-> (dissoc :rx :rx)
(assoc :r1 0 :r2 0 :r3 0 :r4 0))
:always
(assoc attr value))))
|
4bd7f868254843203c3e9a5bb77ba368d223a54316ff6760cf42fda0a7c4e982 | dwincort/AdaptiveFuzz | primml.ml | file name : primml.ml
created by :
Last modified : 12/20/2015
Description :
This file contains code for interpreting primitives as if they were direct ocaml functions .
created by: Daniel Winograd-Cort
Last modified: 12/20/2015
Description:
This file contains code for interpreting SFuzz primitives as if they were direct ocaml functions.
*)
type ('a,'b) either = | Left of 'a
| Right of 'b
type any = Any : 'a -> any
type curatorMemory = ((float * float * string * (any option)) option) list
let curatormem = ref ([] : curatorMemory)
let hd lst = match lst with
| x::_ -> x
| [] -> failwith "hd error"
let rec updateNth (lst : 'a list) (index : int) (f : 'a -> 'a) : 'a list =
match lst, index with
| [],_ -> []
| x::xs, 0 -> f x :: xs
| x::xs, n -> x :: updateNth xs (n-1) f
let gen_numnumopt o = match o with
| None -> Printf.printf "%s" "None;"
| Some (d1,d2) -> Printf.printf "Some(%F,%F);" d1 d2
let gen_cmem lst = Printf.printf "%s" "::: "; List.iter gen_numnumopt lst
(* Returns a file as a list of strings in reverse *)
let fileLines (maxLines : int) (filename : string) =
let lines = ref [] in
let chan = open_in filename in
try
for i=1 to maxLines; do
lines := input_line chan :: !lines
done;
close_in chan;
!lines
with End_of_file ->
close_in chan;
!lines
let stringToFloat (s : string) : float =
try
float_of_string s
with Failure _ ->
Printf.eprintf "primml.ml: float_of_string failed to parse: %s. Providing 0 instead.\n" s;
0.
(* &-pair destruction *)
let _fst (x,y) = x
let _snd (x,y) = y
(* Logical Operators *)
let _lor = (||)
let _land = (&&)
let _eq = (=)
Numerical Comparison Operators
let _lt = ( < )
let _gt = ( > )
let _lte = ( <= )
let _gte = ( >= )
Numerical Computation Operators
let _add = ( +. )
let _sub = ( -. )
let _mul = ( *. )
let _div = ( /. )
let div2 = (fun n -> n /. 2.0)
let div3 = (fun n -> n /. 3.0)
let _exp = ( exp )
let _abs = ( abs_float )
let cswp = (fun (x,y) -> if x < y then (x,y) else (y,x))
Integer primitives
let _iadd = ( +. )
let _isub = ( -. )
let _imul = ( *. )
let _idiv = ( /. )
let rec intToPeano n = if n <= 0.0 then Obj.magic (Left ()) else Obj.magic (Right (intToPeano (n -. 1.0)))
let rec peanoToInt x = match Obj.magic x with
| Left () -> 0.
| Right y -> 1. +. peanoToInt y
(* clip creation *)
let clip c = if c > 1.0 then 1.0 else if c < 0.0 then 0.0 else c
let fromClip c = c
(* String operations *)
let string_cc = (^)
(* Show functions *)
let showNum = fun n -> if n = floor n then string_of_int (truncate n) else string_of_float n
let showInt n = string_of_int (truncate n)
let showBag (b : 'a list) (showA : 'a -> string) : string = String.concat "," (List.rev (List.rev_map showA b))
let showVec (v : 'a array) (showA : 'a -> string) : string = "[" ^ (Array.fold_right (fun x -> fun xs -> showA x ^ "," ^ xs) v "]")
(* Read functions *)
let readNum s = try
float_of_string s
with Failure s -> 0.
let readInt s = try
int_of_string s
with Failure s -> 0
Vector and list transform
" List " represents the fuzz list , which is a magic'd tuple
" InternalList " represents ocaml list
" Vector " represents
"List" represents the fuzz list, which is a magic'd tuple
"InternalList" represents ocaml list
"Vector" represents ocaml array *)
let rec listToInternalList lst = match Obj.magic lst with
| Left () -> []
| Right (x,lst') -> x::(listToInternalList lst')
let rec internalListToList v = match v with
| [] -> Obj.magic (Left ())
| x::xs -> Obj.magic (Right (x, internalListToList xs))
let listToVector lst = Array.of_list (listToInternalList lst)
let vectorToList v = internalListToList (Array.to_list v)
(* Testing Utilities *)
let _assert _ = failwith "assert not available in Data Zone"
let assertEq _ = failwith "assertEq not available in Data Zone"
failwith " print not available in Data Zone "
(* Probability monad operations *)
let _return (x : 'a) : unit -> 'a = fun _ -> x
let loadDB _ = failwith "loadDB not available in Data Zone"
(* Data zone activation primitives *)
let tyCheckFuzz _ = failwith "tyCheckFuzz not available in Data Zone"
let runFuzz _ = failwith "runFuzz not available in Data Zone"
let getDelta _ = failwith "getDelta not available in Data Zone"
let getEpsilon _ = failwith "getEpsilon not available in Data Zone"
(* Bag primitives *)
let emptybag = []
let addtobag x b = x::b
let bagjoin = List.append
let bagsize l = float_of_int (List.length l)
let bagmap f b = List.rev (List.rev_map f b)
let bagsum = List.fold_left (+.) 0.0
let bagsumL b =
let rec sumUp xs ys = match xs,ys with
| x::xs,y::ys -> (x +. y)::sumUp xs ys
| xs,[] -> xs
| [],ys -> ys
in List.fold_left sumUp [] (List.rev_map listToInternalList b)
let bagsumV n b =
let res = Array.make (truncate n) 0.0 in
let sumUp = Array.iteri (fun i -> fun x -> Array.set res i (x +. res.(i)))
in List.iter sumUp b; res
let bagsplit f b = List.partition
let bagfoldl = List.fold_left
(* Differential Privacy mechanisms *)
let addNoiseP (eps : float) (n : float) : float = n +. Math.lap (1.0 /. eps)
let addNoise (eps : float) (n : float) : unit -> float = fun () -> addNoiseP eps n
let reportNoisyMaxP (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : 'r =
let problist = List.rev_map (fun r -> (r, quality r db +. Math.lap (k /. eps))) rbag in
Printf.eprintf
" --- reportNoisyMax : Probabilities are : % s " ( String.concat " , ( List.map ( fun x - > " ( " ^string_of_float ( Obj.magic ( fst x))^","^string_of_float ( snd x)^ " ) " ) problist ) ) ;
"--- reportNoisyMax: Probabilities are: %s" (String.concat ",\n" (List.map (fun x -> "("^string_of_float (Obj.magic (fst x))^","^string_of_float (snd x)^")") problist));*)
fst (List.fold_left
(fun best r -> if abs_float (snd r) > abs_float (snd best) then r else best)
(hd rbag, 0.0) problist)
let reportNoisyMax (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : unit -> 'r =
fun () -> reportNoisyMaxP eps k quality rbag db
let expMechP (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : 'r =
let reslist = List.rev_map (fun r -> (r, exp (eps *. (quality r db) /. (2.0 *. k)))) rbag in
let total = List.fold_left (+.) 0.0 (List.map snd reslist) in
let rec sampleLst (p : float) (lst : ('a * float) list) : 'a =
match lst with
| [] -> fst (hd lst) (* Guaranteed to fail! What else can we do? *)
| (a,x)::xs -> if p < x then a else sampleLst (p -. x) xs
in sampleLst (Math.randFloat total) (List.sort (fun a b -> truncate (snd b -. snd a)) reslist)
let expMech (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : unit -> 'r =
fun () -> expMechP eps k quality rbag db
let aboveThresholdP (eps : float) (k : float) (t : float) (db : 'db) : int =
let index = List.length (!curatormem) in
let dbfilename = "database"^string_of_int index^".cmem" in
let oc = open_out dbfilename in
Marshal.to_channel oc db [];
close_out oc;
curatormem := List.append !curatormem [Some (t +. Math.lap (2.0 /. (eps *. k)), eps, dbfilename, Some (Any db))];
index
let aboveThreshold (eps : float) (k : float) (t : float) (db : 'db) : unit -> int =
fun () -> aboveThresholdP eps k t db
let queryAT (token : int) (f : 'db -> float) : (unit, bool) either =
let dbopt = begin match List.nth (!curatormem) token with
| None -> None
| Some (t,e,_, Some (Any db)) -> Some (t,e,Obj.magic db)
| Some (t,e,dbfilename, None) ->
let ic = open_in dbfilename in
let db = Marshal.from_channel ic in
close_in ic;
Some (t,e,db)
end in Option.map_default (fun (t,e,db) ->
if (f db) +. Math.lap (4.0 /. e) >= t then
(curatormem := updateNth !curatormem token (fun _ -> None); Right true)
else Right false) (Left ()) dbopt
let select = Math.sampleList
(* Load data from external file *)
let bagFromFile _ = failwith "bagFromFile not available in Data Zone"
let listFromFile _ = failwith "listFromFile not available in Data Zone"
let listbagFromFile _ = failwith "listbagFromFile not available in Data Zone"
let vectorbagFromFile (maxsize : float) (fn : string) (rexp : string) : (float array) list =
let lines = fileLines (truncate maxsize) fn in
let lineFun line = Array.of_list (List.map stringToFloat (Str.split (Str.regexp rexp) line))
in List.rev_map lineFun lines
let labeledVectorbagFromFile (maxsize : float) (fn : string) (rexp : string) : (float * float array) list =
let lines = fileLines (truncate maxsize) fn in
let lineFun line = (let flst = List.map stringToFloat (Str.split (Str.regexp rexp) line) in (List.hd flst, Array.of_list (List.tl flst)))
in List.rev_map lineFun lines
let readCmemFromFile (maxsize : int) (fn : string) : curatorMemory =
let lines = fileLines maxsize fn in
let lineFun line = match Str.split (Str.regexp_string ",") line with
| t::e::fn::[] -> Some (float_of_string t, float_of_string e, fn, None)
| _ -> None (* FIXME This probably shouldn't be a silent error *)
in List.map lineFun lines
let rec print_cmem oc = function
| [] -> ()
| None::tl -> Printf.fprintf oc "None\n"; print_cmem oc tl
| (Some(t,e,fn,_))::tl -> Printf.fprintf oc "%F,%F,%s\n" t e fn; print_cmem oc tl
let writeCmemToFile (fn : string) (cmem : curatorMemory) : unit =
let oc = open_out fn in
print_cmem oc cmem;
close_out oc
(* Vectors *)
let vsize v = float_of_int (Array.length v)
let vmap = Array.map
let vsmap _ = vmap
let vsum = Array.fold_left ( + . ) 0.0
let vcons (x : 'a) (xs : 'a array) : 'a array = Array.of_list (x::(Array.to_list xs))
let vuncons (v : 'a array) : (unit, 'a * 'a array) either =
match Array.to_list v with
| [] -> Left ()
| x::xs -> Right (x, Array.of_list xs)
let vindex (def : 'a) (i : float) (v : 'a array) : 'a =
try
Array.get v (truncate i)
with Invalid_argument s -> def
let vperformAt (i : float) (f : 'a -> 'b) (v : 'a array) : 'b array =
let res = Array.copy v in
try
let i = truncate i in
Array.set res i (f v.(i)); res
with Invalid_argument s -> res
let vfilter (test : 'a -> bool) (v : 'a array) : 'a array =
let rec lfilter lst = match lst with
| [] -> []
| x::xs -> if test x then x :: lfilter xs else lfilter xs
in Array.of_list (lfilter (Array.to_list v))
let vzipwith (f : 'a -> 'b -> 'c) (v1 : 'a array) (v2 : 'b array) : 'c array =
let l = min (Array.length v1) (Array.length v2)
in Array.init l (fun i -> f v1.(i) v2.(i))
let vszipwith _ _ = vzipwith
let vfuzz (v : (unit -> 'a) array) : unit -> ('a array) =
fun () -> Array.map (fun f -> f ()) v
let vfoldl = Array.fold_left
let vectorIP (v1 : float array) (v2 : float array) : float =
let res = ref 0.0 in
try
Array.iteri (fun i -> fun x -> res := !res +. x +. v2.(i)) v1;
!res
with Invalid_argument s -> !res
| null | https://raw.githubusercontent.com/dwincort/AdaptiveFuzz/ec937e1ea028e17216928dbdd029a5b9b04a0533/src/primml.ml | ocaml | Returns a file as a list of strings in reverse
&-pair destruction
Logical Operators
clip creation
String operations
Show functions
Read functions
Testing Utilities
Probability monad operations
Data zone activation primitives
Bag primitives
Differential Privacy mechanisms
Guaranteed to fail! What else can we do?
Load data from external file
FIXME This probably shouldn't be a silent error
Vectors | file name : primml.ml
created by :
Last modified : 12/20/2015
Description :
This file contains code for interpreting primitives as if they were direct ocaml functions .
created by: Daniel Winograd-Cort
Last modified: 12/20/2015
Description:
This file contains code for interpreting SFuzz primitives as if they were direct ocaml functions.
*)
type ('a,'b) either = | Left of 'a
| Right of 'b
type any = Any : 'a -> any
type curatorMemory = ((float * float * string * (any option)) option) list
let curatormem = ref ([] : curatorMemory)
let hd lst = match lst with
| x::_ -> x
| [] -> failwith "hd error"
let rec updateNth (lst : 'a list) (index : int) (f : 'a -> 'a) : 'a list =
match lst, index with
| [],_ -> []
| x::xs, 0 -> f x :: xs
| x::xs, n -> x :: updateNth xs (n-1) f
let gen_numnumopt o = match o with
| None -> Printf.printf "%s" "None;"
| Some (d1,d2) -> Printf.printf "Some(%F,%F);" d1 d2
let gen_cmem lst = Printf.printf "%s" "::: "; List.iter gen_numnumopt lst
let fileLines (maxLines : int) (filename : string) =
let lines = ref [] in
let chan = open_in filename in
try
for i=1 to maxLines; do
lines := input_line chan :: !lines
done;
close_in chan;
!lines
with End_of_file ->
close_in chan;
!lines
let stringToFloat (s : string) : float =
try
float_of_string s
with Failure _ ->
Printf.eprintf "primml.ml: float_of_string failed to parse: %s. Providing 0 instead.\n" s;
0.
let _fst (x,y) = x
let _snd (x,y) = y
let _lor = (||)
let _land = (&&)
let _eq = (=)
Numerical Comparison Operators
let _lt = ( < )
let _gt = ( > )
let _lte = ( <= )
let _gte = ( >= )
Numerical Computation Operators
let _add = ( +. )
let _sub = ( -. )
let _mul = ( *. )
let _div = ( /. )
let div2 = (fun n -> n /. 2.0)
let div3 = (fun n -> n /. 3.0)
let _exp = ( exp )
let _abs = ( abs_float )
let cswp = (fun (x,y) -> if x < y then (x,y) else (y,x))
Integer primitives
let _iadd = ( +. )
let _isub = ( -. )
let _imul = ( *. )
let _idiv = ( /. )
let rec intToPeano n = if n <= 0.0 then Obj.magic (Left ()) else Obj.magic (Right (intToPeano (n -. 1.0)))
let rec peanoToInt x = match Obj.magic x with
| Left () -> 0.
| Right y -> 1. +. peanoToInt y
let clip c = if c > 1.0 then 1.0 else if c < 0.0 then 0.0 else c
let fromClip c = c
let string_cc = (^)
let showNum = fun n -> if n = floor n then string_of_int (truncate n) else string_of_float n
let showInt n = string_of_int (truncate n)
let showBag (b : 'a list) (showA : 'a -> string) : string = String.concat "," (List.rev (List.rev_map showA b))
let showVec (v : 'a array) (showA : 'a -> string) : string = "[" ^ (Array.fold_right (fun x -> fun xs -> showA x ^ "," ^ xs) v "]")
let readNum s = try
float_of_string s
with Failure s -> 0.
let readInt s = try
int_of_string s
with Failure s -> 0
Vector and list transform
" List " represents the fuzz list , which is a magic'd tuple
" InternalList " represents ocaml list
" Vector " represents
"List" represents the fuzz list, which is a magic'd tuple
"InternalList" represents ocaml list
"Vector" represents ocaml array *)
let rec listToInternalList lst = match Obj.magic lst with
| Left () -> []
| Right (x,lst') -> x::(listToInternalList lst')
let rec internalListToList v = match v with
| [] -> Obj.magic (Left ())
| x::xs -> Obj.magic (Right (x, internalListToList xs))
let listToVector lst = Array.of_list (listToInternalList lst)
let vectorToList v = internalListToList (Array.to_list v)
let _assert _ = failwith "assert not available in Data Zone"
let assertEq _ = failwith "assertEq not available in Data Zone"
failwith " print not available in Data Zone "
let _return (x : 'a) : unit -> 'a = fun _ -> x
let loadDB _ = failwith "loadDB not available in Data Zone"
let tyCheckFuzz _ = failwith "tyCheckFuzz not available in Data Zone"
let runFuzz _ = failwith "runFuzz not available in Data Zone"
let getDelta _ = failwith "getDelta not available in Data Zone"
let getEpsilon _ = failwith "getEpsilon not available in Data Zone"
let emptybag = []
let addtobag x b = x::b
let bagjoin = List.append
let bagsize l = float_of_int (List.length l)
let bagmap f b = List.rev (List.rev_map f b)
let bagsum = List.fold_left (+.) 0.0
let bagsumL b =
let rec sumUp xs ys = match xs,ys with
| x::xs,y::ys -> (x +. y)::sumUp xs ys
| xs,[] -> xs
| [],ys -> ys
in List.fold_left sumUp [] (List.rev_map listToInternalList b)
let bagsumV n b =
let res = Array.make (truncate n) 0.0 in
let sumUp = Array.iteri (fun i -> fun x -> Array.set res i (x +. res.(i)))
in List.iter sumUp b; res
let bagsplit f b = List.partition
let bagfoldl = List.fold_left
let addNoiseP (eps : float) (n : float) : float = n +. Math.lap (1.0 /. eps)
let addNoise (eps : float) (n : float) : unit -> float = fun () -> addNoiseP eps n
let reportNoisyMaxP (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : 'r =
let problist = List.rev_map (fun r -> (r, quality r db +. Math.lap (k /. eps))) rbag in
Printf.eprintf
" --- reportNoisyMax : Probabilities are : % s " ( String.concat " , ( List.map ( fun x - > " ( " ^string_of_float ( Obj.magic ( fst x))^","^string_of_float ( snd x)^ " ) " ) problist ) ) ;
"--- reportNoisyMax: Probabilities are: %s" (String.concat ",\n" (List.map (fun x -> "("^string_of_float (Obj.magic (fst x))^","^string_of_float (snd x)^")") problist));*)
fst (List.fold_left
(fun best r -> if abs_float (snd r) > abs_float (snd best) then r else best)
(hd rbag, 0.0) problist)
let reportNoisyMax (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : unit -> 'r =
fun () -> reportNoisyMaxP eps k quality rbag db
let expMechP (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : 'r =
let reslist = List.rev_map (fun r -> (r, exp (eps *. (quality r db) /. (2.0 *. k)))) rbag in
let total = List.fold_left (+.) 0.0 (List.map snd reslist) in
let rec sampleLst (p : float) (lst : ('a * float) list) : 'a =
match lst with
| (a,x)::xs -> if p < x then a else sampleLst (p -. x) xs
in sampleLst (Math.randFloat total) (List.sort (fun a b -> truncate (snd b -. snd a)) reslist)
let expMech (eps : float) (k : float) (quality : 'r -> 'db -> float) (rbag : 'r list) (db : 'db) : unit -> 'r =
fun () -> expMechP eps k quality rbag db
let aboveThresholdP (eps : float) (k : float) (t : float) (db : 'db) : int =
let index = List.length (!curatormem) in
let dbfilename = "database"^string_of_int index^".cmem" in
let oc = open_out dbfilename in
Marshal.to_channel oc db [];
close_out oc;
curatormem := List.append !curatormem [Some (t +. Math.lap (2.0 /. (eps *. k)), eps, dbfilename, Some (Any db))];
index
let aboveThreshold (eps : float) (k : float) (t : float) (db : 'db) : unit -> int =
fun () -> aboveThresholdP eps k t db
let queryAT (token : int) (f : 'db -> float) : (unit, bool) either =
let dbopt = begin match List.nth (!curatormem) token with
| None -> None
| Some (t,e,_, Some (Any db)) -> Some (t,e,Obj.magic db)
| Some (t,e,dbfilename, None) ->
let ic = open_in dbfilename in
let db = Marshal.from_channel ic in
close_in ic;
Some (t,e,db)
end in Option.map_default (fun (t,e,db) ->
if (f db) +. Math.lap (4.0 /. e) >= t then
(curatormem := updateNth !curatormem token (fun _ -> None); Right true)
else Right false) (Left ()) dbopt
let select = Math.sampleList
let bagFromFile _ = failwith "bagFromFile not available in Data Zone"
let listFromFile _ = failwith "listFromFile not available in Data Zone"
let listbagFromFile _ = failwith "listbagFromFile not available in Data Zone"
let vectorbagFromFile (maxsize : float) (fn : string) (rexp : string) : (float array) list =
let lines = fileLines (truncate maxsize) fn in
let lineFun line = Array.of_list (List.map stringToFloat (Str.split (Str.regexp rexp) line))
in List.rev_map lineFun lines
let labeledVectorbagFromFile (maxsize : float) (fn : string) (rexp : string) : (float * float array) list =
let lines = fileLines (truncate maxsize) fn in
let lineFun line = (let flst = List.map stringToFloat (Str.split (Str.regexp rexp) line) in (List.hd flst, Array.of_list (List.tl flst)))
in List.rev_map lineFun lines
let readCmemFromFile (maxsize : int) (fn : string) : curatorMemory =
let lines = fileLines maxsize fn in
let lineFun line = match Str.split (Str.regexp_string ",") line with
| t::e::fn::[] -> Some (float_of_string t, float_of_string e, fn, None)
in List.map lineFun lines
let rec print_cmem oc = function
| [] -> ()
| None::tl -> Printf.fprintf oc "None\n"; print_cmem oc tl
| (Some(t,e,fn,_))::tl -> Printf.fprintf oc "%F,%F,%s\n" t e fn; print_cmem oc tl
let writeCmemToFile (fn : string) (cmem : curatorMemory) : unit =
let oc = open_out fn in
print_cmem oc cmem;
close_out oc
let vsize v = float_of_int (Array.length v)
let vmap = Array.map
let vsmap _ = vmap
let vsum = Array.fold_left ( + . ) 0.0
let vcons (x : 'a) (xs : 'a array) : 'a array = Array.of_list (x::(Array.to_list xs))
let vuncons (v : 'a array) : (unit, 'a * 'a array) either =
match Array.to_list v with
| [] -> Left ()
| x::xs -> Right (x, Array.of_list xs)
let vindex (def : 'a) (i : float) (v : 'a array) : 'a =
try
Array.get v (truncate i)
with Invalid_argument s -> def
let vperformAt (i : float) (f : 'a -> 'b) (v : 'a array) : 'b array =
let res = Array.copy v in
try
let i = truncate i in
Array.set res i (f v.(i)); res
with Invalid_argument s -> res
let vfilter (test : 'a -> bool) (v : 'a array) : 'a array =
let rec lfilter lst = match lst with
| [] -> []
| x::xs -> if test x then x :: lfilter xs else lfilter xs
in Array.of_list (lfilter (Array.to_list v))
let vzipwith (f : 'a -> 'b -> 'c) (v1 : 'a array) (v2 : 'b array) : 'c array =
let l = min (Array.length v1) (Array.length v2)
in Array.init l (fun i -> f v1.(i) v2.(i))
let vszipwith _ _ = vzipwith
let vfuzz (v : (unit -> 'a) array) : unit -> ('a array) =
fun () -> Array.map (fun f -> f ()) v
let vfoldl = Array.fold_left
let vectorIP (v1 : float array) (v2 : float array) : float =
let res = ref 0.0 in
try
Array.iteri (fun i -> fun x -> res := !res +. x +. v2.(i)) v1;
!res
with Invalid_argument s -> !res
|
0c72583b66f64e81b16e02991e613e6a2cc55e8a1c31e56b44fc2cbeeab54dd9 | gregr/racket-misc | cursor.rkt | #lang racket/base
(provide
(struct-out cursor)
;; cursor notation
::0 ; create a new cursor focusing on the given datum
ascend one level or optionally to the same depth as another cursor
::^. ; ascend as in ::^ then retrieve the focus
::^* ; ascend completely
::^*. ; ascend completely then retrieve the focus
::@ ; descend through a given path
::@? ; like ::@ but return left (unmatchable path) or right (cursor)
::. ; descend as in ::@ then retrieve the focus
::= ; descend as in ::@, refocus with a new value, then ascend to the
; original position
::~ ; like ::= but refocus by applying a transformation to the target
; focus
::~+ ; merge new children into the current path
::@* ; like ::@ but take each path component as an additional argument
::@?* ; like ::@* but return left (unmatchable path) or right (cursor)
::.* ; like ::. but take each path component as an additional argument
::=* ; like ::= but take each path component as an additional argument
::~* ; like ::~ but take each path component as an additional argument
::~+* ; like ::~+ but take each path component as an additional argument
::** ; efficiently perform a sequence of cursor transformations
;; lens operators
merge a list of paths into one path
:. ; follow all paths given as arguments and get the target value
:= ; follow all paths given as arguments and set the target value
:~ ; follow all paths given as arguments and apply a transformation to the
; target value
:.* ; like :. but the arguments taken are segments of a single path
:=* ; like := but the arguments taken are segments of a single path
:~* ; like :~ but the arguments taken are segments of a single path
:~+ ; merge new children into the current path
:~+* ; like :~+ but the arguments taken are segments of a single path
:** ; efficiently perform a sequence of lens transformations and queries
)
(require
"dict.rkt"
"either.rkt"
"function.rkt"
"list.rkt"
"record.rkt"
"sugar.rkt"
racket/dict
racket/function
racket/list
racket/match
)
(module+ test
(require rackunit))
(define (ref+set datum)
(cond
((pair? datum) (values pair-ref-key pair-set-key))
((dict? datum) (values dict-ref dict-set))))
(define (datum-has-key? datum key)
((cond
((pair? datum) pair-has-key?)
((dict? datum) dict-has-key?)
(else (const #f))) datum key))
(record cursor focus trail ancestors)
(define (cursor-new datum) (cursor datum '() '()))
(define (cursor-refocus cur new-focus) (dict-set cur 'focus new-focus))
(define (cursor-ascend cur)
(match cur
((cursor focus (cons key keys) (cons parent ancestors))
(let*-values (((_ p-set) (ref+set parent))
((new-focus) (p-set parent key focus)))
(cursor new-focus keys ancestors)))))
(define (cursor-ascend-to cur-src cur-tgt)
(for/fold ((cur cur-src))
((idx (in-range (- (length (cursor-trail cur-src))
(length (cursor-trail cur-tgt))))))
(cursor-ascend cur)))
(define (cursor-ascend* cur) (cursor-ascend-to cur (cursor-new '())))
(define (cursor-descend cur key)
(match cur
((cursor focus keys ancestors)
(let*-values (((p-ref _) (ref+set focus))
((new-focus) (p-ref focus key)))
(cursor new-focus (cons key keys) (cons focus ancestors))))))
(define (cursor-descend* cur keys)
(foldl (flip cursor-descend) cur keys))
(define (cursor-descend*/either cur keys)
(match keys
('() (right cur))
((cons key keys)
(if (datum-has-key? (cursor-focus cur) key)
(cursor-descend*/either (cursor-descend cur key) keys)
(left (cons key keys))))))
(define :o (curry apply append))
(define ::0 cursor-new)
(define ::^
(case-lambda
((cur) (cursor-ascend cur))
((cur-src cur-tgt) (cursor-ascend-to cur-src cur-tgt))))
(define (::^. cur-src cur-tgt)
(cursor-focus (cursor-ascend-to cur-src cur-tgt)))
(define ::^* cursor-ascend*)
(define ::^*. (compose1 cursor-focus cursor-ascend*))
(define (::@ cur path) (cursor-descend* cur path))
(define (::@? cur path) (cursor-descend*/either cur path))
(define (::. cur path) (cursor-focus (::@ cur path)))
(define (::= cur val path)
(cursor-ascend-to (cursor-refocus (::@ cur path) val)
cur))
(define (::~ cur trans path)
(let ((cur-next (::@ cur path)))
(cursor-ascend-to
(cursor-refocus cur-next (trans (cursor-focus cur-next)))
cur)))
(define (::~+ cur new path) (::~ cur (lambda (sub) (dict-join sub new)) path))
(define (::@* cur . path) (::@ cur path))
(define (::@?* cur . path) (::@? cur path))
(define (::.* cur . path) (::. cur path))
(define (::=* cur val . path) (::= cur val path))
(define (::~* cur trans . path) (::~ cur trans path))
(define (::~+* cur trans . path) (::~+ cur trans path))
(define (:. src path) (::. (::0 src) path))
(define (:= src val path) (::.* (::= (::0 src) val path)))
(define (:~ src trans path) (::.* (::~ (::0 src) trans path)))
(define (:~+ src new path) (::.* (::~+ (::0 src) new path)))
(define (:.* src . path) (:. src path))
(define (:=* src val . path) (:= src val path))
(define (:~* src trans . path) (:~ src trans path))
(define (:~+* src new . path) (:~+ src new path))
(module+ test
(record foo x y)
(record bar a b)
(define foobar (foo (bar 5 1) '(one two three)))
(check-equal? (:.* foobar 'x 'b)
1)
(check-equal? (:.* foobar 'y 1 0)
'two)
(check-equal? (:.* (:~* foobar (curry + 3) 'x 'a) 'x 'a)
8)
(check-equal? (:=* 'src 'tgt) 'tgt)
(check-equal? (:~+* (list 1 2 (hash 'a 1 'b 2 'd 4))
(hash 'c 3 'b 5)
1 1 0)
(list 1 2 (hash 'a 1 'b 5 'c 3 'd 4)))
)
(define (paths->deltas current paths)
(define (compare cur path)
(match* (cur path)
(('() path) (list 0 path))
((cur '()) (list (length cur) '()))
(((cons c0 cs) (cons p0 ps))
(if (equal? c0 p0) (compare cs ps) (list (length cur) path)))))
(match paths
('() '())
((cons path paths)
(list* (compare current path) (paths->deltas path paths)))))
(module+ test
(check-equal?
(paths->deltas '() '((a b c d e f)
(a b c d e f)
(a b c d e f g h)
(a b d e f)
(a b d 1 2)
(a b c 1 2)
(z y x w v)
(z y x 5)
(z y x 5)))
'((0 (a b c d e f))
(0 ())
(0 (g h))
(6 (d e f))
(2 (1 2))
(3 (c 1 2))
(5 (z y x w v))
(2 (5))
(0 ()))
))
(define (paths->transitions initial-path paths)
(forl (list up down) <- (paths->deltas initial-path paths)
up-trans = (if (= 0 up) identity
(lambda (cur) (last (iterate ::^ cur up))))
down-trans = (if (null? down) identity
(lambda (cur) (::@ cur down)))
(match up
(0 down-trans)
(_ (match down
('() up-trans)
(_ (compose1 down-trans up-trans)))))))
(define (::**-process cursor initial-path ops paths)
(forf cursor = cursor
op <- ops
transition <- (paths->transitions initial-path paths)
(op (transition cursor))))
(define (::** cursor initial-path op&path-list)
(apply ::**-process cursor initial-path (zip-default '(() ()) op&path-list)))
(module+ test
(check-equal?
(::** (::0 '(a (b c) d (e f g) h)) '()
`((,(lambda (cur) (::=* cur 3)) (1 1 1 0 1 1 0))
(,(lambda (cur) (::=* cur 4)) (1 1 1 0 1 0))
(,(lambda (cur) (::=* cur 5)) (1 0 1 0))
(,identity ())
(,identity (1 1 0))))
(lets datum = '(a (b c) d (e f g) h)
datum = (:= datum 3 '(1 1 1 0 1 1 0))
datum = (:= datum 4 '(1 1 1 0 1 0))
datum = (:= datum 5 '(1 0 1 0))
(::@ (::0 datum) '(1 1 0)))
))
(define-syntax :**-cont
(syntax-rules (:. := :~ :~+ =)
((_ initial-path (ops ...) (paths ...) cursor (:= value path body ...))
(:**-cont initial-path
(ops ... (lambda (cur) (::=* cur value))) (paths ... path)
cursor (body ...)))
((_ initial-path (ops ...) (paths ...) cursor (:~ update path body ...))
(:**-cont initial-path
(ops ... (lambda (cur) (::~* cur update))) (paths ... path)
cursor (body ...)))
((_ initial-path (ops ...) (paths ...) cursor (:~+ new path body ...))
(:**-cont initial-path
(ops ... (lambda (cur) (::~+* cur new))) (paths ... path)
cursor (body ...)))
((_ initial-path (ops ...) (paths ...) cursor (:. name path body ...))
(:**-cont initial-path (ops ... identity) (paths ... path) cursor
(name = (::.* cursor) body ...)))
((_ initial-path () () cursor (lhs = rhs body ...))
(lets lhs = rhs (:**-cont initial-path () () cursor (body ...))))
((_ initial-path () () cursor (body)) (values (::^*. cursor) body))
((_ initial-path () () cursor ()) (::^*. cursor))
((_ initial-path (ops ...) (paths ... final-path) cursor body)
(let ((cursor (::**-process cursor initial-path
(list ops ...) (list paths ... final-path))))
(:**-cont final-path () () cursor body)))))
(define-syntax :**
(syntax-rules ()
((_ datum body ...) (let ((cursor (::0 datum)))
(:**-cont '() () () cursor (body ...))))))
(module+ test
(check-equal?
(lets (values datum result) =
(:** `(a (b c) d (e f g) ,(hash 'one 1 'two 2) h)
:= 3 '(1 1 1 0 1 1 0)
:~ (lambda (val) (list val 4)) '(1 1 1 0 1 0)
:~+ (hash 'three 3 'two 5) '(1 1 1 1 0)
:= 5 '(1 0 1 0)
:. one '(1 1 1 0 1 0 0)
two = (list one one)
:= two '(1 1 1 0 1 0 0)
:. result '(1 1 0)
result)
(list datum result))
`((a (b 5) d (e ((f f) 4) 3) ,(hash 'one 1 'two 5 'three 3) h) d)
))
| null | https://raw.githubusercontent.com/gregr/racket-misc/0a5c9d4875288795e209d06982b82848c989d08b/cursor.rkt | racket | cursor notation
create a new cursor focusing on the given datum
ascend as in ::^ then retrieve the focus
ascend completely
ascend completely then retrieve the focus
descend through a given path
like ::@ but return left (unmatchable path) or right (cursor)
descend as in ::@ then retrieve the focus
descend as in ::@, refocus with a new value, then ascend to the
original position
like ::= but refocus by applying a transformation to the target
focus
merge new children into the current path
like ::@ but take each path component as an additional argument
like ::@* but return left (unmatchable path) or right (cursor)
like ::. but take each path component as an additional argument
like ::= but take each path component as an additional argument
like ::~ but take each path component as an additional argument
like ::~+ but take each path component as an additional argument
efficiently perform a sequence of cursor transformations
lens operators
follow all paths given as arguments and get the target value
follow all paths given as arguments and set the target value
follow all paths given as arguments and apply a transformation to the
target value
like :. but the arguments taken are segments of a single path
like := but the arguments taken are segments of a single path
like :~ but the arguments taken are segments of a single path
merge new children into the current path
like :~+ but the arguments taken are segments of a single path
efficiently perform a sequence of lens transformations and queries | #lang racket/base
(provide
(struct-out cursor)
ascend one level or optionally to the same depth as another cursor
merge a list of paths into one path
)
(require
"dict.rkt"
"either.rkt"
"function.rkt"
"list.rkt"
"record.rkt"
"sugar.rkt"
racket/dict
racket/function
racket/list
racket/match
)
(module+ test
(require rackunit))
(define (ref+set datum)
(cond
((pair? datum) (values pair-ref-key pair-set-key))
((dict? datum) (values dict-ref dict-set))))
(define (datum-has-key? datum key)
((cond
((pair? datum) pair-has-key?)
((dict? datum) dict-has-key?)
(else (const #f))) datum key))
(record cursor focus trail ancestors)
(define (cursor-new datum) (cursor datum '() '()))
(define (cursor-refocus cur new-focus) (dict-set cur 'focus new-focus))
(define (cursor-ascend cur)
(match cur
((cursor focus (cons key keys) (cons parent ancestors))
(let*-values (((_ p-set) (ref+set parent))
((new-focus) (p-set parent key focus)))
(cursor new-focus keys ancestors)))))
(define (cursor-ascend-to cur-src cur-tgt)
(for/fold ((cur cur-src))
((idx (in-range (- (length (cursor-trail cur-src))
(length (cursor-trail cur-tgt))))))
(cursor-ascend cur)))
(define (cursor-ascend* cur) (cursor-ascend-to cur (cursor-new '())))
(define (cursor-descend cur key)
(match cur
((cursor focus keys ancestors)
(let*-values (((p-ref _) (ref+set focus))
((new-focus) (p-ref focus key)))
(cursor new-focus (cons key keys) (cons focus ancestors))))))
(define (cursor-descend* cur keys)
(foldl (flip cursor-descend) cur keys))
(define (cursor-descend*/either cur keys)
(match keys
('() (right cur))
((cons key keys)
(if (datum-has-key? (cursor-focus cur) key)
(cursor-descend*/either (cursor-descend cur key) keys)
(left (cons key keys))))))
(define :o (curry apply append))
(define ::0 cursor-new)
(define ::^
(case-lambda
((cur) (cursor-ascend cur))
((cur-src cur-tgt) (cursor-ascend-to cur-src cur-tgt))))
(define (::^. cur-src cur-tgt)
(cursor-focus (cursor-ascend-to cur-src cur-tgt)))
(define ::^* cursor-ascend*)
(define ::^*. (compose1 cursor-focus cursor-ascend*))
(define (::@ cur path) (cursor-descend* cur path))
(define (::@? cur path) (cursor-descend*/either cur path))
(define (::. cur path) (cursor-focus (::@ cur path)))
(define (::= cur val path)
(cursor-ascend-to (cursor-refocus (::@ cur path) val)
cur))
(define (::~ cur trans path)
(let ((cur-next (::@ cur path)))
(cursor-ascend-to
(cursor-refocus cur-next (trans (cursor-focus cur-next)))
cur)))
(define (::~+ cur new path) (::~ cur (lambda (sub) (dict-join sub new)) path))
(define (::@* cur . path) (::@ cur path))
(define (::@?* cur . path) (::@? cur path))
(define (::.* cur . path) (::. cur path))
(define (::=* cur val . path) (::= cur val path))
(define (::~* cur trans . path) (::~ cur trans path))
(define (::~+* cur trans . path) (::~+ cur trans path))
(define (:. src path) (::. (::0 src) path))
(define (:= src val path) (::.* (::= (::0 src) val path)))
(define (:~ src trans path) (::.* (::~ (::0 src) trans path)))
(define (:~+ src new path) (::.* (::~+ (::0 src) new path)))
(define (:.* src . path) (:. src path))
(define (:=* src val . path) (:= src val path))
(define (:~* src trans . path) (:~ src trans path))
(define (:~+* src new . path) (:~+ src new path))
(module+ test
(record foo x y)
(record bar a b)
(define foobar (foo (bar 5 1) '(one two three)))
(check-equal? (:.* foobar 'x 'b)
1)
(check-equal? (:.* foobar 'y 1 0)
'two)
(check-equal? (:.* (:~* foobar (curry + 3) 'x 'a) 'x 'a)
8)
(check-equal? (:=* 'src 'tgt) 'tgt)
(check-equal? (:~+* (list 1 2 (hash 'a 1 'b 2 'd 4))
(hash 'c 3 'b 5)
1 1 0)
(list 1 2 (hash 'a 1 'b 5 'c 3 'd 4)))
)
(define (paths->deltas current paths)
(define (compare cur path)
(match* (cur path)
(('() path) (list 0 path))
((cur '()) (list (length cur) '()))
(((cons c0 cs) (cons p0 ps))
(if (equal? c0 p0) (compare cs ps) (list (length cur) path)))))
(match paths
('() '())
((cons path paths)
(list* (compare current path) (paths->deltas path paths)))))
(module+ test
(check-equal?
(paths->deltas '() '((a b c d e f)
(a b c d e f)
(a b c d e f g h)
(a b d e f)
(a b d 1 2)
(a b c 1 2)
(z y x w v)
(z y x 5)
(z y x 5)))
'((0 (a b c d e f))
(0 ())
(0 (g h))
(6 (d e f))
(2 (1 2))
(3 (c 1 2))
(5 (z y x w v))
(2 (5))
(0 ()))
))
(define (paths->transitions initial-path paths)
(forl (list up down) <- (paths->deltas initial-path paths)
up-trans = (if (= 0 up) identity
(lambda (cur) (last (iterate ::^ cur up))))
down-trans = (if (null? down) identity
(lambda (cur) (::@ cur down)))
(match up
(0 down-trans)
(_ (match down
('() up-trans)
(_ (compose1 down-trans up-trans)))))))
(define (::**-process cursor initial-path ops paths)
(forf cursor = cursor
op <- ops
transition <- (paths->transitions initial-path paths)
(op (transition cursor))))
(define (::** cursor initial-path op&path-list)
(apply ::**-process cursor initial-path (zip-default '(() ()) op&path-list)))
(module+ test
(check-equal?
(::** (::0 '(a (b c) d (e f g) h)) '()
`((,(lambda (cur) (::=* cur 3)) (1 1 1 0 1 1 0))
(,(lambda (cur) (::=* cur 4)) (1 1 1 0 1 0))
(,(lambda (cur) (::=* cur 5)) (1 0 1 0))
(,identity ())
(,identity (1 1 0))))
(lets datum = '(a (b c) d (e f g) h)
datum = (:= datum 3 '(1 1 1 0 1 1 0))
datum = (:= datum 4 '(1 1 1 0 1 0))
datum = (:= datum 5 '(1 0 1 0))
(::@ (::0 datum) '(1 1 0)))
))
(define-syntax :**-cont
(syntax-rules (:. := :~ :~+ =)
((_ initial-path (ops ...) (paths ...) cursor (:= value path body ...))
(:**-cont initial-path
(ops ... (lambda (cur) (::=* cur value))) (paths ... path)
cursor (body ...)))
((_ initial-path (ops ...) (paths ...) cursor (:~ update path body ...))
(:**-cont initial-path
(ops ... (lambda (cur) (::~* cur update))) (paths ... path)
cursor (body ...)))
((_ initial-path (ops ...) (paths ...) cursor (:~+ new path body ...))
(:**-cont initial-path
(ops ... (lambda (cur) (::~+* cur new))) (paths ... path)
cursor (body ...)))
((_ initial-path (ops ...) (paths ...) cursor (:. name path body ...))
(:**-cont initial-path (ops ... identity) (paths ... path) cursor
(name = (::.* cursor) body ...)))
((_ initial-path () () cursor (lhs = rhs body ...))
(lets lhs = rhs (:**-cont initial-path () () cursor (body ...))))
((_ initial-path () () cursor (body)) (values (::^*. cursor) body))
((_ initial-path () () cursor ()) (::^*. cursor))
((_ initial-path (ops ...) (paths ... final-path) cursor body)
(let ((cursor (::**-process cursor initial-path
(list ops ...) (list paths ... final-path))))
(:**-cont final-path () () cursor body)))))
(define-syntax :**
(syntax-rules ()
((_ datum body ...) (let ((cursor (::0 datum)))
(:**-cont '() () () cursor (body ...))))))
(module+ test
(check-equal?
(lets (values datum result) =
(:** `(a (b c) d (e f g) ,(hash 'one 1 'two 2) h)
:= 3 '(1 1 1 0 1 1 0)
:~ (lambda (val) (list val 4)) '(1 1 1 0 1 0)
:~+ (hash 'three 3 'two 5) '(1 1 1 1 0)
:= 5 '(1 0 1 0)
:. one '(1 1 1 0 1 0 0)
two = (list one one)
:= two '(1 1 1 0 1 0 0)
:. result '(1 1 0)
result)
(list datum result))
`((a (b 5) d (e ((f f) 4) 3) ,(hash 'one 1 'two 5 'three 3) h) d)
))
|
317bb371921b9b3706f347ebb5112d1c8894b4e4fd98b1374ecfbaa77ef8b85e | wdebeaum/step | valid.lisp | ;;;;
;;;; W::valid
;;;;
(define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(W::valid
(wordfeats (W::morph (:FORMS (-LY))))
(SENSES
((meta-data :origin task-learning :entry-date 20050823 :change-date 20090731 :comments nil)
(EXAMPLE "the return address on spam is usually not valid")
(lf-parent ont::valid-val)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/valid.lisp | lisp |
W::valid
|
(define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(W::valid
(wordfeats (W::morph (:FORMS (-LY))))
(SENSES
((meta-data :origin task-learning :entry-date 20050823 :change-date 20090731 :comments nil)
(EXAMPLE "the return address on spam is usually not valid")
(lf-parent ont::valid-val)
)
)
)
))
|
bace5c0f1b650a17a84c56b039e78479239616e574f365bb1e0a69a062fc2d6a | epiccastle/spire | silent.clj | (ns spire.output.silent
(:require [spire.output.core :as output]))
(set! *warn-on-reflection* true)
(defmethod output/print-thread :silent [driver])
(defmethod output/print-form :silent [driver file form file-meta host-config])
(defmethod output/print-result :silent [driver file form file-meta host-config result])
(defmethod output/debug-result :silent [driver file form file-meta host-config result])
(defmethod output/print-progress :silent [driver file form form-meta host-string {:keys [progress context]}])
(defmethod output/print-streams :silent [driver file form form-meta host-string stdout stderr])
| null | https://raw.githubusercontent.com/epiccastle/spire/f1161ae5ff74124d603c1679507fc0a1b31c26eb/src/clj/spire/output/silent.clj | clojure | (ns spire.output.silent
(:require [spire.output.core :as output]))
(set! *warn-on-reflection* true)
(defmethod output/print-thread :silent [driver])
(defmethod output/print-form :silent [driver file form file-meta host-config])
(defmethod output/print-result :silent [driver file form file-meta host-config result])
(defmethod output/debug-result :silent [driver file form file-meta host-config result])
(defmethod output/print-progress :silent [driver file form form-meta host-string {:keys [progress context]}])
(defmethod output/print-streams :silent [driver file form form-meta host-string stdout stderr])
| |
e2ef0682973a77582d7eace078a6ca17481657e0243562121a4756b79c52812e | synduce/Synduce | count_between.ml | * @synduce -s 2 -NB
type 'a tree =
| Leaf of 'a
| Node of 'a * 'a tree * 'a tree
let rec tree_min = function
| Leaf x -> x
| Node (a, l, r) -> min a (min (tree_min l) (tree_min r))
;;
let rec tree_max = function
| Leaf x -> x
| Node (a, l, r) -> max a (max (tree_max l) (tree_max r))
;;
let repr x = x
let spec lo hi t =
let rec f = function
| Leaf a -> lo < a && a < hi
| Node (a, l, r) -> (lo < a && a < hi) || f l || f r
in
f t
;;
let target lo hi t =
let rec g = function
| Leaf a -> [%synt s0]
| Node (a, l, r) -> if a >= hi then [%synt gt_case] else [%synt le_case]
in
g t
;;
| null | https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/misc/count_between.ml | ocaml | * @synduce -s 2 -NB
type 'a tree =
| Leaf of 'a
| Node of 'a * 'a tree * 'a tree
let rec tree_min = function
| Leaf x -> x
| Node (a, l, r) -> min a (min (tree_min l) (tree_min r))
;;
let rec tree_max = function
| Leaf x -> x
| Node (a, l, r) -> max a (max (tree_max l) (tree_max r))
;;
let repr x = x
let spec lo hi t =
let rec f = function
| Leaf a -> lo < a && a < hi
| Node (a, l, r) -> (lo < a && a < hi) || f l || f r
in
f t
;;
let target lo hi t =
let rec g = function
| Leaf a -> [%synt s0]
| Node (a, l, r) -> if a >= hi then [%synt gt_case] else [%synt le_case]
in
g t
;;
| |
7539737986ebe364e23c5fdfbfc1360aa87ab5edf66338664bffcc8f533b0966 | dharrigan/startrek | generators.clj | (ns startrek.test.generators
{:author "David Harrigan"}
(:require
[startrek.core.domain.starship.model :as starship]))
(defn starship
[& overrides]
(starship/gen-starship overrides))
| null | https://raw.githubusercontent.com/dharrigan/startrek/ee15b048c3a89d28161d77c36cb96db07082e98f/test/startrek/test/generators.clj | clojure | (ns startrek.test.generators
{:author "David Harrigan"}
(:require
[startrek.core.domain.starship.model :as starship]))
(defn starship
[& overrides]
(starship/gen-starship overrides))
| |
57b862a7563cf2155713a2df9e06921b4ab24774bc55056f73dbf39d4747bc82 | jayrbolton/coursework | Conat.hs | {-# LANGUAGE EmptyDataDecls
, ExistentialQuantification
, ScopedTypeVariables
, NoMonomorphismRestriction
#-}
module MAlonzo.Data.Conat where
import qualified Unsafe.Coerce
import qualified MAlonzo.Coinduction
import qualified MAlonzo.Data.Nat
import qualified MAlonzo.Relation.Binary
import qualified MAlonzo.Relation.Binary.Core
name2 = ("Data.Conat.Co\8469")
d2 = (())
data T2 a0 = C3
| C5 a0
name3 = ("Data.Conat.zero")
name5 = ("Data.Conat.suc")
name6 = ("Data.Conat.from\8469")
d6 (MAlonzo.Data.Nat.C3) = ((Unsafe.Coerce.unsafeCoerce) (C3))
d6 v0
= ((Unsafe.Coerce.unsafeCoerce)
((d_1_6) ((Unsafe.Coerce.unsafeCoerce) (v0))))
where d_1_6 (MAlonzo.Data.Nat.C5 v0)
= ((Unsafe.Coerce.unsafeCoerce)
((C5)
((Unsafe.Coerce.unsafeCoerce)
((d37) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
d_1_6 v0
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat.from\8469"))
name8 = ("Data.Conat.\8734\8469")
d8
= ((Unsafe.Coerce.unsafeCoerce)
((C5) ((Unsafe.Coerce.unsafeCoerce) (d51))))
name9 = ("Data.Conat._+_")
d9 (C3) v0 = ((Unsafe.Coerce.unsafeCoerce) (v0))
d9 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_9) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_9 (C5 v0) v1
= ((Unsafe.Coerce.unsafeCoerce)
((C5)
((Unsafe.Coerce.unsafeCoerce)
(((d57) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
d_1_9 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._+_"))
name13 = ("Data.Conat._\8776_")
d13 a0 a1 = (())
data T13 a0 a1 a2 = C14
| C18 a0 a1 a2
name14 = ("Data.Conat.zero")
name18 = ("Data.Conat.suc")
name19 = ("Data.Conat.setoid")
d19
= ((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Relation.Binary.C56)
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (d13)))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Relation.Binary.Core.C250)
((Unsafe.Coerce.unsafeCoerce)
(\ v0 -> ((d22) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
((Unsafe.Coerce.unsafeCoerce)
(\ v0 ->
(\ v1 ->
(((d24) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))))
((Unsafe.Coerce.unsafeCoerce)
(\ v0 ->
(\ v1 ->
(\ v2 ->
((((d26) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2)))))))))))
name22 = ("Data.Conat._.refl")
d22 (C3) = ((Unsafe.Coerce.unsafeCoerce) (C14))
d22 v0
= ((Unsafe.Coerce.unsafeCoerce)
((d_1_22) ((Unsafe.Coerce.unsafeCoerce) (v0))))
where d_1_22 (C5 v0)
= ((Unsafe.Coerce.unsafeCoerce)
((((C18) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce)
((d121) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
d_1_22 v0
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._.refl"))
name24 = ("Data.Conat._.sym")
d24 v0 v1 (C14) = ((Unsafe.Coerce.unsafeCoerce) (C14))
d24 v0 v1 v2
= ((Unsafe.Coerce.unsafeCoerce)
((((d_1_24) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2))))
where d_1_24 v0 v1 (C18 v2 v3 v4)
= ((Unsafe.Coerce.unsafeCoerce)
((((C18) ((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce)
((((d165) ((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v4))))))
d_1_24 v0 v1 v2
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._.sym"))
name26 = ("Data.Conat._.trans")
d26 v0 v1 v2 (C14) (C14) = ((Unsafe.Coerce.unsafeCoerce) (C14))
d26 v0 v1 v2 v3 v4
= ((Unsafe.Coerce.unsafeCoerce)
((((((d_1_26) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v4))))
where d_1_26 v0 v1 v2 (C18 v3 v4 v5) (C18 v6 v7 v8)
= ((Unsafe.Coerce.unsafeCoerce)
((((C18) ((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v7)))
((Unsafe.Coerce.unsafeCoerce)
((((((d301) ((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v4)))
((Unsafe.Coerce.unsafeCoerce) (v5)))
((Unsafe.Coerce.unsafeCoerce) (v7)))
((Unsafe.Coerce.unsafeCoerce) (v8))))))
d_1_26 v0 v1 v2 v3 v4
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._.trans"))
name37 = ("Data.Conat.\9839-0")
d37 v0
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((d6) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
name51 = ("Data.Conat.\9839-1")
d51
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7) ((Unsafe.Coerce.unsafeCoerce) (d8))))
name57 = ("Data.Conat.\9839-2")
d57 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
(((d9)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
name121 = ("Data.Conat._.\9839-3")
d121 v0
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((d22)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0))))))))
name165 = ("Data.Conat._.\9839-4")
d165 v0 v1 v2
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((((d24)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce)
(((d13)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))))
((Unsafe.Coerce.unsafeCoerce) (v2))))))))
name301 = ("Data.Conat._.\9839-5")
d301 v0 v1 v2 v3 v4
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((((((d26)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce)
(((d13)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))))
((Unsafe.Coerce.unsafeCoerce) (v2)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce)
(((d13)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))))))
((Unsafe.Coerce.unsafeCoerce) (v4)))))))) | null | https://raw.githubusercontent.com/jayrbolton/coursework/f0da276527d42a6751fb8d29c76de35ce358fe65/computability_and_formal_languages/project__/agda/MAlonzo/Data/Conat.hs | haskell | # LANGUAGE EmptyDataDecls
, ExistentialQuantification
, ScopedTypeVariables
, NoMonomorphismRestriction
# | module MAlonzo.Data.Conat where
import qualified Unsafe.Coerce
import qualified MAlonzo.Coinduction
import qualified MAlonzo.Data.Nat
import qualified MAlonzo.Relation.Binary
import qualified MAlonzo.Relation.Binary.Core
name2 = ("Data.Conat.Co\8469")
d2 = (())
data T2 a0 = C3
| C5 a0
name3 = ("Data.Conat.zero")
name5 = ("Data.Conat.suc")
name6 = ("Data.Conat.from\8469")
d6 (MAlonzo.Data.Nat.C3) = ((Unsafe.Coerce.unsafeCoerce) (C3))
d6 v0
= ((Unsafe.Coerce.unsafeCoerce)
((d_1_6) ((Unsafe.Coerce.unsafeCoerce) (v0))))
where d_1_6 (MAlonzo.Data.Nat.C5 v0)
= ((Unsafe.Coerce.unsafeCoerce)
((C5)
((Unsafe.Coerce.unsafeCoerce)
((d37) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
d_1_6 v0
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat.from\8469"))
name8 = ("Data.Conat.\8734\8469")
d8
= ((Unsafe.Coerce.unsafeCoerce)
((C5) ((Unsafe.Coerce.unsafeCoerce) (d51))))
name9 = ("Data.Conat._+_")
d9 (C3) v0 = ((Unsafe.Coerce.unsafeCoerce) (v0))
d9 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_9) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_9 (C5 v0) v1
= ((Unsafe.Coerce.unsafeCoerce)
((C5)
((Unsafe.Coerce.unsafeCoerce)
(((d57) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
d_1_9 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._+_"))
name13 = ("Data.Conat._\8776_")
d13 a0 a1 = (())
data T13 a0 a1 a2 = C14
| C18 a0 a1 a2
name14 = ("Data.Conat.zero")
name18 = ("Data.Conat.suc")
name19 = ("Data.Conat.setoid")
d19
= ((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Relation.Binary.C56)
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (d13)))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Relation.Binary.Core.C250)
((Unsafe.Coerce.unsafeCoerce)
(\ v0 -> ((d22) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
((Unsafe.Coerce.unsafeCoerce)
(\ v0 ->
(\ v1 ->
(((d24) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))))
((Unsafe.Coerce.unsafeCoerce)
(\ v0 ->
(\ v1 ->
(\ v2 ->
((((d26) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2)))))))))))
name22 = ("Data.Conat._.refl")
d22 (C3) = ((Unsafe.Coerce.unsafeCoerce) (C14))
d22 v0
= ((Unsafe.Coerce.unsafeCoerce)
((d_1_22) ((Unsafe.Coerce.unsafeCoerce) (v0))))
where d_1_22 (C5 v0)
= ((Unsafe.Coerce.unsafeCoerce)
((((C18) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce)
((d121) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
d_1_22 v0
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._.refl"))
name24 = ("Data.Conat._.sym")
d24 v0 v1 (C14) = ((Unsafe.Coerce.unsafeCoerce) (C14))
d24 v0 v1 v2
= ((Unsafe.Coerce.unsafeCoerce)
((((d_1_24) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2))))
where d_1_24 v0 v1 (C18 v2 v3 v4)
= ((Unsafe.Coerce.unsafeCoerce)
((((C18) ((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce)
((((d165) ((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v4))))))
d_1_24 v0 v1 v2
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._.sym"))
name26 = ("Data.Conat._.trans")
d26 v0 v1 v2 (C14) (C14) = ((Unsafe.Coerce.unsafeCoerce) (C14))
d26 v0 v1 v2 v3 v4
= ((Unsafe.Coerce.unsafeCoerce)
((((((d_1_26) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v4))))
where d_1_26 v0 v1 v2 (C18 v3 v4 v5) (C18 v6 v7 v8)
= ((Unsafe.Coerce.unsafeCoerce)
((((C18) ((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v7)))
((Unsafe.Coerce.unsafeCoerce)
((((((d301) ((Unsafe.Coerce.unsafeCoerce) (v3)))
((Unsafe.Coerce.unsafeCoerce) (v4)))
((Unsafe.Coerce.unsafeCoerce) (v5)))
((Unsafe.Coerce.unsafeCoerce) (v7)))
((Unsafe.Coerce.unsafeCoerce) (v8))))))
d_1_26 v0 v1 v2 v3 v4
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Data.Conat._.trans"))
name37 = ("Data.Conat.\9839-0")
d37 v0
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((d6) ((Unsafe.Coerce.unsafeCoerce) (v0))))))
name51 = ("Data.Conat.\9839-1")
d51
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7) ((Unsafe.Coerce.unsafeCoerce) (d8))))
name57 = ("Data.Conat.\9839-2")
d57 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
(((d9)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
name121 = ("Data.Conat._.\9839-3")
d121 v0
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((d22)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0))))))))
name165 = ("Data.Conat._.\9839-4")
d165 v0 v1 v2
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((((d24)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce)
(((d13)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))))
((Unsafe.Coerce.unsafeCoerce) (v2))))))))
name301 = ("Data.Conat._.\9839-5")
d301 v0 v1 v2 v3 v4
= ((Unsafe.Coerce.unsafeCoerce)
((MAlonzo.Coinduction.C7)
((Unsafe.Coerce.unsafeCoerce)
((((((d26)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce)
(((d13)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v0)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))))
((Unsafe.Coerce.unsafeCoerce) (v2)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce)
(((d13)
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v1)))))
((Unsafe.Coerce.unsafeCoerce)
((((MAlonzo.Coinduction.d10) ((Unsafe.Coerce.unsafeCoerce) (0)))
((Unsafe.Coerce.unsafeCoerce) (d2)))
((Unsafe.Coerce.unsafeCoerce) (v3)))))))
((Unsafe.Coerce.unsafeCoerce) (v4)))))))) |
473e60093d9975d0abf1c65b22e1a3892dc24ee62f45628f224c64b3b6ecba73 | replikativ/datahike | js.cljs | (ns ^:no-doc datahike.js
(:refer-clojure :exclude [filter])
(:require
[goog.object :as go]
[datahike.core :as d]
[clojure.walk :as walk]
[cljs.reader]))
;; Conversions
(defn- keywordize [s]
(if (and (string? s) (= (subs s 0 1) ":"))
(keyword (subs s 1))
s))
(defn- schema->clj [schema]
(->> (js->clj schema)
(reduce-kv
(fn [m k v] (assoc m k (walk/postwalk keywordize v))) {})))
(declare entities->clj)
(defn- entity-map->clj [e]
(walk/postwalk
(fn [form]
(if (and (map? form) (contains? form ":db/id"))
(-> form
(dissoc ":db/id")
(assoc :db/id (get form ":db/id")))
form))
e))
(defn- entity->clj [e]
(cond
(map? e)
(entity-map->clj e)
(= (first e) ":db.fn/call")
(let [[_ f & args] e]
(concat [:db.fn/call (fn [& args] (entities->clj (apply f args)))] args))
(sequential? e)
(let [[op & entity] e]
(concat [(keywordize op)] entity))))
(defn- entities->clj [entities]
(->> (js->clj entities)
(map entity->clj)))
(defn- tempids->js [tempids]
(let [obj (js-obj)]
(doseq [[k v] tempids]
(go/set obj (str k) v))
obj))
(defn- tx-report->js [report]
#js {:db_before (:db-before report)
:db_after (:db-after report)
:tx_data (->> (:tx-data report) into-array)
:tempids (tempids->js (:tempids report))
:tx_meta (:tx-meta report)})
(defn js->Datom [d]
(if (array? d)
(d/datom (aget d 0) (aget d 1) (aget d 2) (or (aget d 3) d/tx0) (or (aget d 4) true))
(d/datom (.-e d) (.-a d) (.-v d) (or (.-tx d) d/tx0) (or (.-added d) true))))
(defn- pull-result->js
[result]
(->> result
(walk/postwalk #(if (keyword? %) (str %) %))
clj->js))
;; Public API
(defn ^:export empty_db [& [schema]]
(d/empty-db (schema->clj schema)))
(defn ^:export init_db [datoms & [schema]]
(d/init-db (map js->Datom datoms) (schema->clj schema)))
(defn ^:export q [query & sources]
(let [query (cljs.reader/read-string query)
results (apply d/q query sources)]
(clj->js results)))
(defn ^:export pull [db pattern eid]
(let [pattern (cljs.reader/read-string pattern)
eid (js->clj eid)
results (d/pull db pattern eid)]
(pull-result->js results)))
(defn ^:export pull_many [db pattern eids]
(let [pattern (cljs.reader/read-string pattern)
eids (js->clj eids)
results (d/pull-many db pattern eids)]
(pull-result->js results)))
(defn ^:export db_with [db entities]
(d/db-with db (entities->clj entities)))
(defn ^:export entity [db eid]
(d/entity db (js->clj eid)))
(def ^:export touch d/touch)
(def ^:export entity_db d/entity-db)
(def ^:export filter d/filter)
(def ^:export is_filtered d/is-filtered)
(defn ^:export create_conn [& [schema]]
(d/create-conn (schema->clj schema)))
(def ^:export conn_from_db d/conn-from-db)
(defn ^:export conn_from_datoms
([datoms] (conn_from_db (init_db datoms)))
([datoms schema] (conn_from_db (init_db datoms schema))))
(defn ^:export db [conn] @conn)
(defn ^:export transact [conn entities & [tx-meta]]
(let [entities (entities->clj entities)
report (-> (d/-transact! conn entities tx-meta)
tx-report->js)]
(doseq [[_ callback] @(:listeners (meta conn))]
(callback report))
report))
(defn ^:export reset_conn [conn db & [tx-meta]]
(let [report #js {:db_before @conn
:db_after db
:tx_data (into-array
(concat
(map #(assoc % :added false) (d/datoms @conn :eavt))
(d/datoms db :eavt)))
:tx_meta tx-meta}]
(reset! conn db)
(doseq [[_ callback] @(:listeners (meta conn))]
(callback report))
db))
(def ^:export listen d/listen!)
(def ^:export unlisten d/unlisten!)
(defn ^:export resolve_tempid [tempids tempid]
(go/get tempids (str tempid)))
(defn ^:export datoms [db index & components]
(->> (apply d/datoms db (keywordize index) components)
into-array))
(defn ^:export seek_datoms [db index & components]
(->> (apply d/seek-datoms db (keywordize index) components)
into-array))
(defn ^:export index_range [db attr start end]
(into-array (d/index-range db attr start end)))
(defn ^:export squuid []
(str (d/squuid)))
(defn ^:export squuid_time_millis [uuid]
(d/squuid-time-millis (cljs.core/uuid uuid)))
| null | https://raw.githubusercontent.com/replikativ/datahike/7e60af807dd4db1d0eb73b75ac2f010e31361a3a/src/datahike/js.cljs | clojure | Conversions
Public API | (ns ^:no-doc datahike.js
(:refer-clojure :exclude [filter])
(:require
[goog.object :as go]
[datahike.core :as d]
[clojure.walk :as walk]
[cljs.reader]))
(defn- keywordize [s]
(if (and (string? s) (= (subs s 0 1) ":"))
(keyword (subs s 1))
s))
(defn- schema->clj [schema]
(->> (js->clj schema)
(reduce-kv
(fn [m k v] (assoc m k (walk/postwalk keywordize v))) {})))
(declare entities->clj)
(defn- entity-map->clj [e]
(walk/postwalk
(fn [form]
(if (and (map? form) (contains? form ":db/id"))
(-> form
(dissoc ":db/id")
(assoc :db/id (get form ":db/id")))
form))
e))
(defn- entity->clj [e]
(cond
(map? e)
(entity-map->clj e)
(= (first e) ":db.fn/call")
(let [[_ f & args] e]
(concat [:db.fn/call (fn [& args] (entities->clj (apply f args)))] args))
(sequential? e)
(let [[op & entity] e]
(concat [(keywordize op)] entity))))
(defn- entities->clj [entities]
(->> (js->clj entities)
(map entity->clj)))
(defn- tempids->js [tempids]
(let [obj (js-obj)]
(doseq [[k v] tempids]
(go/set obj (str k) v))
obj))
(defn- tx-report->js [report]
#js {:db_before (:db-before report)
:db_after (:db-after report)
:tx_data (->> (:tx-data report) into-array)
:tempids (tempids->js (:tempids report))
:tx_meta (:tx-meta report)})
(defn js->Datom [d]
(if (array? d)
(d/datom (aget d 0) (aget d 1) (aget d 2) (or (aget d 3) d/tx0) (or (aget d 4) true))
(d/datom (.-e d) (.-a d) (.-v d) (or (.-tx d) d/tx0) (or (.-added d) true))))
(defn- pull-result->js
[result]
(->> result
(walk/postwalk #(if (keyword? %) (str %) %))
clj->js))
(defn ^:export empty_db [& [schema]]
(d/empty-db (schema->clj schema)))
(defn ^:export init_db [datoms & [schema]]
(d/init-db (map js->Datom datoms) (schema->clj schema)))
(defn ^:export q [query & sources]
(let [query (cljs.reader/read-string query)
results (apply d/q query sources)]
(clj->js results)))
(defn ^:export pull [db pattern eid]
(let [pattern (cljs.reader/read-string pattern)
eid (js->clj eid)
results (d/pull db pattern eid)]
(pull-result->js results)))
(defn ^:export pull_many [db pattern eids]
(let [pattern (cljs.reader/read-string pattern)
eids (js->clj eids)
results (d/pull-many db pattern eids)]
(pull-result->js results)))
(defn ^:export db_with [db entities]
(d/db-with db (entities->clj entities)))
(defn ^:export entity [db eid]
(d/entity db (js->clj eid)))
(def ^:export touch d/touch)
(def ^:export entity_db d/entity-db)
(def ^:export filter d/filter)
(def ^:export is_filtered d/is-filtered)
(defn ^:export create_conn [& [schema]]
(d/create-conn (schema->clj schema)))
(def ^:export conn_from_db d/conn-from-db)
(defn ^:export conn_from_datoms
([datoms] (conn_from_db (init_db datoms)))
([datoms schema] (conn_from_db (init_db datoms schema))))
(defn ^:export db [conn] @conn)
(defn ^:export transact [conn entities & [tx-meta]]
(let [entities (entities->clj entities)
report (-> (d/-transact! conn entities tx-meta)
tx-report->js)]
(doseq [[_ callback] @(:listeners (meta conn))]
(callback report))
report))
(defn ^:export reset_conn [conn db & [tx-meta]]
(let [report #js {:db_before @conn
:db_after db
:tx_data (into-array
(concat
(map #(assoc % :added false) (d/datoms @conn :eavt))
(d/datoms db :eavt)))
:tx_meta tx-meta}]
(reset! conn db)
(doseq [[_ callback] @(:listeners (meta conn))]
(callback report))
db))
(def ^:export listen d/listen!)
(def ^:export unlisten d/unlisten!)
(defn ^:export resolve_tempid [tempids tempid]
(go/get tempids (str tempid)))
(defn ^:export datoms [db index & components]
(->> (apply d/datoms db (keywordize index) components)
into-array))
(defn ^:export seek_datoms [db index & components]
(->> (apply d/seek-datoms db (keywordize index) components)
into-array))
(defn ^:export index_range [db attr start end]
(into-array (d/index-range db attr start end)))
(defn ^:export squuid []
(str (d/squuid)))
(defn ^:export squuid_time_millis [uuid]
(d/squuid-time-millis (cljs.core/uuid uuid)))
|
bfe58732a79095856c1a121cd8ef129d4d77ccab77ea179db199de6a0ddbd82d | screenshotbot/screenshotbot-oss | types.lisp | ;; -*- mode: lisp; syntax: common-lisp -*-
(in-package :libssh2)
(defcenum +DISCONNECT-CODE+
(:HOST-NOT-ALLOWED-TO-CONNECT 1)
(:PROTOCOL-ERROR 2)
(:KEY-EXCHANGE-FAILED 3)
(:RESERVED 4)
(:MAC-ERROR 5)
(:COMPRESSION-ERROR 6)
(:SERVICE-NOT-AVAILABLE 7)
(:PROTOCOL-VERSION-NOT-SUPPORTED 8)
(:HOST-KEY-NOT-VERIFIABLE 9)
(:CONNECTION-LOST 10)
(:BY-APPLICATION 11)
(:TOO-MANY-CONNECTIONS 12)
(:AUTH-CANCELLED-BY-USER 13)
(:NO-MORE-AUTH-METHODS-AVAILABLE 14)
(:ILLEGAL-USER-NAME 15))
(defconstant +eagain+ -37)
(defcenum +ERROR-CODE+
(:ERROR-NONE 0)
(:ERROR-SOCKET-NONE -1)
(:ERROR-BANNER-RECV -2)
(:ERROR-BANNER-SEND -3)
(:ERROR-INVALID-MAC -4)
(:ERROR-KEX-FAILURE -5)
(:ERROR-ALLOC -6)
(:ERROR-SOCKET-SEND -7)
(:ERROR-KEY-EXCHANGE-FAILURE -8)
(:ERROR-TIMEOUT -9)
(:ERROR-HOSTKEY-INIT -10)
(:ERROR-HOSTKEY-SIGN -11)
(:ERROR-DECRYPT -12)
(:ERROR-SOCKET-DISCONNECT -13)
(:ERROR-PROTO -14)
(:ERROR-PASSWORD-EXPIRED -15)
(:ERROR-FILE -16)
(:ERROR-METHOD-NONE -17)
(:ERROR-AUTHENTICATION-FAILED -18)
(:ERROR-PUBLICKEY-UNVERIFIED -19)
(:ERROR-CHANNEL-OUTOFORDER -20)
(:ERROR-CHANNEL-FAILURE -21)
(:ERROR-CHANNEL-REQUEST-DENIED -22)
(:ERROR-CHANNEL-UNKNOWN -23)
(:ERROR-CHANNEL-WINDOW-EXCEEDED -24)
(:ERROR-CHANNEL-PACKET-EXCEEDED -25)
(:ERROR-CHANNEL-CLOSED -26)
(:ERROR-CHANNEL-EOF-SENT -27)
(:ERROR-SCP-PROTOCOL -28)
(:ERROR-ZLIB -29)
(:ERROR-SOCKET-TIMEOUT -30)
(:ERROR-SFTP-PROTOCOL -31)
(:ERROR-REQUEST-DENIED -32)
(:ERROR-METHOD-NOT-SUPPORTED -33)
(:ERROR-INVAL -34)
(:ERROR-INVALID-POLL-TYPE -35)
(:ERROR-PUBLICKEY-PROTOCOL -36)
(:ERROR-EAGAIN -37)
(:ERROR-BUFFER-TOO-SMALL -38)
(:ERROR-BAD-USE -39)
(:ERROR-COMPRESS -40)
(:ERROR-OUT-OF-BOUNDARY -41)
(:ERROR-AGENT-PROTOCOL -42)
(:ERROR-SOCKET-RECV -43)
(:ERROR-ENCRYPT -44)
(:ERROR-BAD-SOCKET -45)
(:ERROR-KNOWN-HOSTS -46))
(defcenum +BLOCKING+
(:BLOCKING 1)
(:NON-BLOCKING 0))
(defcenum +IDENTITY-AMOUNT+
(:MORE 0)
(:END 1))
(defcenum +CHANNEL-EOF+
(:NOT-EOF 0)
(:EOF 1))
(defcenum +STREAM-ID+
(:STDOUT 0)
(:STDERR 1)
(:EXTENDED -1)
(:ALL -2))
(defcenum +HASH-TYPE+
(:MD5 1)
(:SHA1 2))
(defcenum +CHECK-VERDICT+
(:FAILURE 3)
(:NOT-FOUND 2)
(:MISMATCH 1)
(:MATCH 0))
(defctype +session+ :pointer)
(defctype +key+ :pointer)
(defctype +ssh-agent+ :pointer)
(defctype +known-hosts+ :pointer)
(defctype +keyhash+ :pointer)
(defctype +channel+ :pointer)
(defbitfield +TRACE-OPTIONS+
(.TRANS. 2)
(.KEX. 4)
(.AUTH. 8)
(.CONN. 16)
(.SCP. 32)
(.SFTP. 64)
(.ERROR. 128)
(.PUBLICKEY 256)
(.SOCKET 512))
(defbitfield +known-hosts-flags+
(.type-plain. 1)
(.type-sha1. 2)
(.raw. 65536)
(.base64. 131072)
(.rsa1. 262144)
(.ssh. 524288))
(defcstruct +known-host+
(magic :unsigned-int)
(node :pointer)
(name :string)
(key :string)
(type +known-hosts-flags+))
(defcstruct +kbd-prompt+
(text :pointer)
(length :unsigned-int)
(echo :unsigned-char))
(defcstruct +kbd-response+
(text :pointer)
(length :unsigned-int))
(defstruct key
(data 0 :read-only t)
(size 0 :read-only t)
(type 0 :read-only t))
(define-condition ssh-condition (condition)
((message :type string
:initarg :message
:accessor message)
(code :type +ERROR-CODE+
:accessor code
:initarg :code))
(:report (lambda (c stream)
(format stream "An SSH error occurred (code: ~A): ~A." (code c) (message c))))
(:documentation "Parent condition for all situations where a libssh2
call yields a non-zero return value. `CODE' and `MESSAGE' are used
to transport the error code and message from C."))
(define-condition ssh-generic-error (ssh-condition error)
()
(:documentation "Signalled when a non-correctable condition occurs
during a libssh2 call."))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *default-errors-list*
(cons :UNKNOWN
(remove :ERROR-NONE
(foreign-enum-keyword-list '+ERROR-CODE+)))))
(defvar *errors-list* *default-errors-list*)
(define-condition libssh2-invalid-error-code (ssh-generic-error)
()
(:documentation "Signalled when an error code is returned by libssh2
which is unknown (or better: not yet known) to this library; this
situation can arise when libssh2 adds a new error, but the lisp code
is not yet updated to reflect the change. The `MESSAGE' slot is set
to 'Received unknown error code from libssh2; please contact the
cl-libssh2 authors.'"))
(defmethod initialize-instance :after ((e libssh2-invalid-error-code) &key)
(setf (message e) "Received unknown error code from libssh2; please contact the cl-libssh2 authors."))
(define-condition ssh-handshake-error (ssh-generic-error) ())
(define-condition ssh-hostkey-condition (ssh-condition)
((host :type string
:accessor host
:initarg :host)
(hash :type string
:accessor hash
:initarg :hash)))
(define-condition ssh-unknown-hostkey (ssh-hostkey-condition)
()
(:report (lambda (c stream)
(format stream "Unknown key for host ~A (hash: ~A)" (host c) (hash c)))))
(define-condition ssh-bad-hostkey (ssh-hostkey-condition ssh-generic-error)
((reason :type +check-verdict+
:accessor reason
:initarg :reason))
(:report (lambda (c stream)
(format stream "Verification of key for host ~A (hash: ~A) failed with reason ~A" (host c) (hash c) (reason c)))))
;;; SFTP related types
(defcenum (sftp-open-types :int)
(:file 0)
(:dir 1))
(defbitfield (sftp-flags :unsigned-long)
(:none #x0)
(:read #x1)
(:write #x2)
(:append #x4)
(:creat #x8)
(:trunc #x10)
(:excl #x20))
(defbitfield (sftp-modes :long)
(:named-pipe #x10000)
(:character-special #x20000)
(:directory #x40000)
(:block-special #x60000)
(:regular #x100000)
(:symbolic-link #x120000)
(:socket #x140000)
(:user-read #x400)
(:user-write #x200)
(:user-execute #x100)
(:group-read #x40)
(:group-write #x20)
(:group-execute #x10)
(:other-read #x4)
(:other-write #x2)
(:other-execute #x1))
(defcenum (sftp-error-code :unsigned-long)
(:ok 0)
(:error-sftp-eof 1)
(:error-sftp-no_such_file 2)
(:error-sftp-permission_denied 3)
(:error-sftp-failure 4)
(:error-sftp-bad_message 5)
(:error-sftp-no_connection 6)
(:error-sftp-connection_lost 7)
(:error-sftp-op_unsupported 8)
(:error-sftp-invalid_handle 9)
(:error-sftp-no_such_path 10)
(:error-sftp-file_already_exists 11)
(:error-sftp-write_protect 12)
(:error-sftp-no_media 13)
(:error-sftp-no_space_on_filesystem 14)
(:error-sftp-quota_exceeded 15)
(:error-sftp-unknown_principal 16)
(:error-sftp-lock_conflict 17)
(:error-sftp-dir_not_empty 18)
(:error-sftp-not_a_directory 19)
(:error-sftp-invalid_filename 20)
(:error-sftp-link_loop 21))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/66a28bdf73558bd9dfa0b96dde8d46c9abae5182/third-party/cl-libssh2/src/types.lisp | lisp | -*- mode: lisp; syntax: common-lisp -*-
this
please contact the
SFTP related types |
(in-package :libssh2)
(defcenum +DISCONNECT-CODE+
(:HOST-NOT-ALLOWED-TO-CONNECT 1)
(:PROTOCOL-ERROR 2)
(:KEY-EXCHANGE-FAILED 3)
(:RESERVED 4)
(:MAC-ERROR 5)
(:COMPRESSION-ERROR 6)
(:SERVICE-NOT-AVAILABLE 7)
(:PROTOCOL-VERSION-NOT-SUPPORTED 8)
(:HOST-KEY-NOT-VERIFIABLE 9)
(:CONNECTION-LOST 10)
(:BY-APPLICATION 11)
(:TOO-MANY-CONNECTIONS 12)
(:AUTH-CANCELLED-BY-USER 13)
(:NO-MORE-AUTH-METHODS-AVAILABLE 14)
(:ILLEGAL-USER-NAME 15))
(defconstant +eagain+ -37)
(defcenum +ERROR-CODE+
(:ERROR-NONE 0)
(:ERROR-SOCKET-NONE -1)
(:ERROR-BANNER-RECV -2)
(:ERROR-BANNER-SEND -3)
(:ERROR-INVALID-MAC -4)
(:ERROR-KEX-FAILURE -5)
(:ERROR-ALLOC -6)
(:ERROR-SOCKET-SEND -7)
(:ERROR-KEY-EXCHANGE-FAILURE -8)
(:ERROR-TIMEOUT -9)
(:ERROR-HOSTKEY-INIT -10)
(:ERROR-HOSTKEY-SIGN -11)
(:ERROR-DECRYPT -12)
(:ERROR-SOCKET-DISCONNECT -13)
(:ERROR-PROTO -14)
(:ERROR-PASSWORD-EXPIRED -15)
(:ERROR-FILE -16)
(:ERROR-METHOD-NONE -17)
(:ERROR-AUTHENTICATION-FAILED -18)
(:ERROR-PUBLICKEY-UNVERIFIED -19)
(:ERROR-CHANNEL-OUTOFORDER -20)
(:ERROR-CHANNEL-FAILURE -21)
(:ERROR-CHANNEL-REQUEST-DENIED -22)
(:ERROR-CHANNEL-UNKNOWN -23)
(:ERROR-CHANNEL-WINDOW-EXCEEDED -24)
(:ERROR-CHANNEL-PACKET-EXCEEDED -25)
(:ERROR-CHANNEL-CLOSED -26)
(:ERROR-CHANNEL-EOF-SENT -27)
(:ERROR-SCP-PROTOCOL -28)
(:ERROR-ZLIB -29)
(:ERROR-SOCKET-TIMEOUT -30)
(:ERROR-SFTP-PROTOCOL -31)
(:ERROR-REQUEST-DENIED -32)
(:ERROR-METHOD-NOT-SUPPORTED -33)
(:ERROR-INVAL -34)
(:ERROR-INVALID-POLL-TYPE -35)
(:ERROR-PUBLICKEY-PROTOCOL -36)
(:ERROR-EAGAIN -37)
(:ERROR-BUFFER-TOO-SMALL -38)
(:ERROR-BAD-USE -39)
(:ERROR-COMPRESS -40)
(:ERROR-OUT-OF-BOUNDARY -41)
(:ERROR-AGENT-PROTOCOL -42)
(:ERROR-SOCKET-RECV -43)
(:ERROR-ENCRYPT -44)
(:ERROR-BAD-SOCKET -45)
(:ERROR-KNOWN-HOSTS -46))
(defcenum +BLOCKING+
(:BLOCKING 1)
(:NON-BLOCKING 0))
(defcenum +IDENTITY-AMOUNT+
(:MORE 0)
(:END 1))
(defcenum +CHANNEL-EOF+
(:NOT-EOF 0)
(:EOF 1))
(defcenum +STREAM-ID+
(:STDOUT 0)
(:STDERR 1)
(:EXTENDED -1)
(:ALL -2))
(defcenum +HASH-TYPE+
(:MD5 1)
(:SHA1 2))
(defcenum +CHECK-VERDICT+
(:FAILURE 3)
(:NOT-FOUND 2)
(:MISMATCH 1)
(:MATCH 0))
(defctype +session+ :pointer)
(defctype +key+ :pointer)
(defctype +ssh-agent+ :pointer)
(defctype +known-hosts+ :pointer)
(defctype +keyhash+ :pointer)
(defctype +channel+ :pointer)
(defbitfield +TRACE-OPTIONS+
(.TRANS. 2)
(.KEX. 4)
(.AUTH. 8)
(.CONN. 16)
(.SCP. 32)
(.SFTP. 64)
(.ERROR. 128)
(.PUBLICKEY 256)
(.SOCKET 512))
(defbitfield +known-hosts-flags+
(.type-plain. 1)
(.type-sha1. 2)
(.raw. 65536)
(.base64. 131072)
(.rsa1. 262144)
(.ssh. 524288))
(defcstruct +known-host+
(magic :unsigned-int)
(node :pointer)
(name :string)
(key :string)
(type +known-hosts-flags+))
(defcstruct +kbd-prompt+
(text :pointer)
(length :unsigned-int)
(echo :unsigned-char))
(defcstruct +kbd-response+
(text :pointer)
(length :unsigned-int))
(defstruct key
(data 0 :read-only t)
(size 0 :read-only t)
(type 0 :read-only t))
(define-condition ssh-condition (condition)
((message :type string
:initarg :message
:accessor message)
(code :type +ERROR-CODE+
:accessor code
:initarg :code))
(:report (lambda (c stream)
(format stream "An SSH error occurred (code: ~A): ~A." (code c) (message c))))
(:documentation "Parent condition for all situations where a libssh2
call yields a non-zero return value. `CODE' and `MESSAGE' are used
to transport the error code and message from C."))
(define-condition ssh-generic-error (ssh-condition error)
()
(:documentation "Signalled when a non-correctable condition occurs
during a libssh2 call."))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *default-errors-list*
(cons :UNKNOWN
(remove :ERROR-NONE
(foreign-enum-keyword-list '+ERROR-CODE+)))))
(defvar *errors-list* *default-errors-list*)
(define-condition libssh2-invalid-error-code (ssh-generic-error)
()
(:documentation "Signalled when an error code is returned by libssh2
situation can arise when libssh2 adds a new error, but the lisp code
is not yet updated to reflect the change. The `MESSAGE' slot is set
cl-libssh2 authors.'"))
(defmethod initialize-instance :after ((e libssh2-invalid-error-code) &key)
(setf (message e) "Received unknown error code from libssh2; please contact the cl-libssh2 authors."))
(define-condition ssh-handshake-error (ssh-generic-error) ())
(define-condition ssh-hostkey-condition (ssh-condition)
((host :type string
:accessor host
:initarg :host)
(hash :type string
:accessor hash
:initarg :hash)))
(define-condition ssh-unknown-hostkey (ssh-hostkey-condition)
()
(:report (lambda (c stream)
(format stream "Unknown key for host ~A (hash: ~A)" (host c) (hash c)))))
(define-condition ssh-bad-hostkey (ssh-hostkey-condition ssh-generic-error)
((reason :type +check-verdict+
:accessor reason
:initarg :reason))
(:report (lambda (c stream)
(format stream "Verification of key for host ~A (hash: ~A) failed with reason ~A" (host c) (hash c) (reason c)))))
(defcenum (sftp-open-types :int)
(:file 0)
(:dir 1))
(defbitfield (sftp-flags :unsigned-long)
(:none #x0)
(:read #x1)
(:write #x2)
(:append #x4)
(:creat #x8)
(:trunc #x10)
(:excl #x20))
(defbitfield (sftp-modes :long)
(:named-pipe #x10000)
(:character-special #x20000)
(:directory #x40000)
(:block-special #x60000)
(:regular #x100000)
(:symbolic-link #x120000)
(:socket #x140000)
(:user-read #x400)
(:user-write #x200)
(:user-execute #x100)
(:group-read #x40)
(:group-write #x20)
(:group-execute #x10)
(:other-read #x4)
(:other-write #x2)
(:other-execute #x1))
(defcenum (sftp-error-code :unsigned-long)
(:ok 0)
(:error-sftp-eof 1)
(:error-sftp-no_such_file 2)
(:error-sftp-permission_denied 3)
(:error-sftp-failure 4)
(:error-sftp-bad_message 5)
(:error-sftp-no_connection 6)
(:error-sftp-connection_lost 7)
(:error-sftp-op_unsupported 8)
(:error-sftp-invalid_handle 9)
(:error-sftp-no_such_path 10)
(:error-sftp-file_already_exists 11)
(:error-sftp-write_protect 12)
(:error-sftp-no_media 13)
(:error-sftp-no_space_on_filesystem 14)
(:error-sftp-quota_exceeded 15)
(:error-sftp-unknown_principal 16)
(:error-sftp-lock_conflict 17)
(:error-sftp-dir_not_empty 18)
(:error-sftp-not_a_directory 19)
(:error-sftp-invalid_filename 20)
(:error-sftp-link_loop 21))
|
b5662c6a37df2325d7821c7054c7b300bf74d9304af097d89009653e25b041b3 | mrphlip/aoc | 21a.hs | root :: Integer
jntc = tzrz * jmgz
chsl = rbmj + chpp
tmjp = rlbw + prhj
rllz = wrgr * jplq
bttz = hslv + jsph
pbcg = frwf - vzrg
gfhs = 4
sglc = 8
rqmt = 2
fltv = 2
zggp = thct * ddvm
cqdj = 8
mslt = gsnz + blhq
mrqj = vzvz * sdnf
bqfd = jtlf - hmfq
pgsr = 2
bgmj = vhqn + nnrs
qjgh = 2
vbwn = 2
dftr = 2
rphr = tnjt + vwds
wjqp = 3
jqvb = 11
djcv = rtzp + ltmf
pzfg = frcg + gwdc
sbvb = zqvr `div` qbtm
fhwn = tbjd + szcc
wdrt = 3
hplr = gtwd * jbss
svgc = lddn + czqc
cmjg = 5
mmvj = jlbq * zdcv
fpmz = gzjs * lwdn
dvht = 5
cffj = hddd + qjrz
qcvt = rlhd * ljqt
swqg = bvnb * wrsz
sbmb = 7
zmph = 3
vjcd = qplm + fvsm
ggwg = pdfh * pjtb
mvnq = 2
zjgh = hqpr + bbgs
cwzv = wfzn * dwtq
wswt = 17
hslp = 2
msct = chtt * tcvm
frwt = jnts * qpsz
hnvf = pbwq + bhzw
znsz = 2
wfbs = 5
dgwc = 13
gcwt = 3
crhj = pznp * vcvv
pqzd = jjsc * gjnr
qfjf = 5
tbjd = 6
lglj = ghnb * jdzl
cwfj = 9
lvqr = nlgh + nqfp
szfs = dwdn - mcjd
tgjh = 4
vccz = dgcb + pqbm
nmvr = wwvn * rsdv
tblc = 5
bqdv = 9
nsft = 3
qgvr = bpzw * mgvr
jswp = 3
qmbr = 5
zdcv = tlnj + qsff
qbns = tprb `div` qvzt
lftn = fmbw * jzjp
zngc = 4
vqzd = hjmb `div` dspt
bvdt = 3
cpqr = 2
clhj = 5
jnnp = 2
mjhm = 16
zzrp = qcrs + gtbj
tgjj = rcsj * mwmr
rfqb = ncnl + dwgd
zhcb = gsng + gnhq
bbsr = 3
dpfm = 1
mrmp = sgvw * cmdh
gbwd = 18
zhcs = 3
hnrz = 2
wwvn = 3
hbth = dcwg + fjrb
bsqw = bqfd + sncr
qzpl = fqrd * gqlh
chtt = 10
dtqz = 4
sjhh = 17
whhm = 4
plqr = 1
nbmb = bvtc - ngwv
zgcs = 2
jzjp = 2
jbfs = 11
cchn = dpgb + ptjg
wgvf = slhc + gmnw
dvrf = 2
bhjn = 2
vrms = tczg * rhlg
plcs = 4
gjcs = 7
wdfz = slwr + nqlt
djfv = ncjg + dbmw
gfbs = fsrz * cqgh
hfwt = 2
tcpv = jgjb + vwcm
bmjq = cpwb + nmvw
nrwh = 4
fqrd = 6
dwjj = 4
pjwh = lghd `div` cftw
brwh = sbzv * cmjg
vpts = zqnn + hflj
vqds = vgsm + pmnv
znlq = bqgv + dhzl
fcls = bvbj `div` qpfh
rhvf = 19
nqnw = 3
mlfm = 4
gzjq = 2
zfln = pwqd * sbmd
qqst = jfhc * qcvt
zprj = 3
rvmz = ntdt + zhjb
lqdh = cgrj + lfls
lnbf = rtfj * ghlw
mwdb = 9
rclm = 12
qpsz = 14
qthm = rrmz * tfhq
fmbt = twzz * wchd
fvpj = plgp * nmtc
qfjl = 7
vcwg = smsr * dmdl
pttw = 8
hwqm = znmm + mhwn
crnl = tdvz * fqtj
fzwp = 5
swfd = tscb * hdgq
nlgh = cgdh - vdch
dbfp = 12
pzbr = qrzt * shjp
gmbz = chqv * lhwn
dmjp = 2
cjcl = 4
ljbm = 2
tjhg = svdh * svcm
wztf = 5
vpmw = thmn + mtvl
nfqr = 3
cdzs = pntb + ncbg
mhtc = 3
prrj = jvvr `div` mpzh
nbqf = rtvl * lqdh
bnvv = qdgh + tght
nqdj = 4
jmgn = 2
gbpb = dnch * cnjf
rgth = hmdh + vchv
lmvn = 13
lslm = 4
ltzd = sgwp * cmng
fsrz = 2
zvgp = fwhj * pzgj
lvhs = 5
ctvm = lfvt * vmmb
djvv = lzjn * rclm
tgbp = vhgv + hjch
sjwz = 3
qcpj = 4
mmgz = 3
qglw = 3
vlgr = 2
vcgp = hhsq + jhzd
zhzd = 2
tmpn = 2
hdcz = wjhs * bbgl
tshl = jncw - hsdj
chps = 4
thwz = 9
lbzf = nfgg - bmcs
ffmm = zhjp * rbvs
wpql = htrh `div` zggd
mrmf = 19
wnwl = jdph * fwdq
fhfq = pgqt + fbcc
tscb = 3
jnwm = 10
fjhr = nftz * brss
nsgc = 3
dplt = 7
wstd = ltgp + rnrf
hztd = 5
vnjz = brnn * bcwv
spbn = wnjz * wnql
jhvq = 13
zvsq = 5
hjlp = 2
bslw = 1
gzzf = qwzc * wfbs
jqqv = 2
flnz = gpfs + fnnp
rtcg = dbfd `div` pfsm
gsnz = wfts + mbnv
nlnn = 3
jvpc = fcbt + rphr
bdvw = jtzh * tdmd
lzqm = 6
jtzh = 2
tlhl = 3
hlpt = wvfm * ssls
mfbr = tgbp * tdtb
wsjg = qvww + qllf
wsdf = 15
rtgw = 11
fwdq = 2
jdph = mqbs * ctzc
mrtl = 2
hfnd = srzl * fbcb
rgrh = 7
nltl = 11
pgns = zffq * pbbd
mcpb = 9
jmtj = 17
vhfz = 8
jqmf = 7
frbg = 20
qqrz = 2
trmp = 18
rhng = tdmm * phjw
jmll = 12
vqjv = 3
tdmd = zvff + zggr
plvh = 16
lgfr = 3
gncb = 2
gvmf = 3
rlbw = 2
hjch = bwwq * fdsm
nlzl = hfnd * hlrh
tfrj = 20
rnrf = mrgm * vwhf
nvmm = 1
wgmz = rhcp `div` rlmn
hpbq = 3
qjfp = 3
pjqj = 10
dwwh = 2
qpmt = ssjf * bmrj
jmqm = hmlj + tfcl
gzsw = 2
wmgn = 4
dstw = ptbp + qnrd
vznm = qvvs * nsft
pczb = cdfz * ghbn
bzdz = lslm + jsdw
hlhg = jmll + mhrz
fgdw = wtsj * fpbt
jbbg = 3
hfbj = 7
rzqq = wbgw * tzdd
lhwn = 4
pndj = 5
szws = 4
frwf = jcjg + jsnv
pjfc = rtcq `div` zfdr
jrqq = zvsm + qzhz
sdfq = 3
nvmn = znlq * ssql
qzhf = 6
hrrn = 20
fgjt = 11
zhlq = 4
nfgg = dnfh - psls
pnrq = fbzq + lbqm
spqg = 3
blgg = 13
tswl = mvmn * sqbn
qsmp = 2
dtdb = 3
jmjp = 3
sprd = 2
zgmr = 3
mwpb = pqsg + ppsm
sjld = 2
mvhz = nslp `div` wmgn
ddsm = 2
rqnr = rlfb + nrwh
rsnc = spth - hqfs
dwgj = 2
tcdj = bttz * fmnh
vpbh = lhjn `div` gmcq
npqv = dmqt * dstn
qmwm = jsnt + jvzj
pvtq = 9
pvhz = tstp * ltdn
thmn = 9
chpc = mqws * rppc
dwdn = ndgs * nlnn
zzpb = bvqg + pjjh
hpfn = 5
dfqh = fpvz - hgtm
wnbm = 2
czjp = 3
jcsg = 2
dvjh = rzqq + cpvv
wdnd = sbvw * hlrj
lgvh = 4
lpbr = mbww + qsmp
mgvn = ppgd + djvv
jjlt = 20
tzrz = 3
cqct = hbqd `div` dfcj
qzsq = 6
dqvj = rfnc + wqzg
hvfp = hndj + cndw
sgqv = 19
svdh = 2
crhl = cfsr `div` lwhh
pwgm = 9
pgmw = 7
ccvc = qmrn + twjr
svsl = bmws + qjqp
jzqs = 2
rbmj = 13
sgwp = 9
tlbm = fvln * jjbr
vcwc = mrbm + rvgm
npzj = nbmb `div` cmrn
fvzd = mfjt + gtgn
fjbh = 2
htrh = cjlc * gjrf
hlfv = zszm * pzsz
pcvb = 2
hdbc = zwbs - rndg
qjdc = tmjp * pmsh
rtfb = jppl `div` qpft
bdln = 2
qqzj = vrms * nvhp
lbrd = 5
chlh = vsgd + gqgq
rlpp = mnmv + wtwr
zdzr = jnwm + cndn
sgqc = 3
hdgq = 3
dsms = jmtj * svqr
rlcp = gjcs + lnmr
szll = 2
bhjg = 3
nllp = 7
ptjg = mlfm * ptbv
jfhc = 2
qsff = 4
gcsg = 2
jgpp = rgsh + crjw
qghb = rqjn `div` bnnv
glwr = zphr * tnzz
vvmr = 2
dgcb = mpqs + snbz
bsng = sjwz + rzzm
pbcq = wgrl + ccvc
czwl = djjt + wspf
bslv = jlff + nvzz
pznp = 2
dtnv = cpgw - gpvb
sdqw = 5
gcnq = 2
tpnh = 2
zmnq = qglt `div` tgjw
vwnz = 5
cmms = jgpp + rdnh
vzwn = 2
hqpr = 12
qjqp = hqsp * hwrg
dgtj = wdzt * zcnc
nwfw = 5
hghn = 5
qlfm = 3
lgtd = mcgl `div` vdnj
vnct = 2
rqjn = jnjd + hdwc
bpql = wgvf + pmpc
bgrc = cglv - lmmt
ljrp = 1
tvsj = 9
frzb = 2
ngnc = 1
hhsq = 2
qwcb = 6
ljcf = 19
wrgm = 5
zwbs = gvjr * gztn
bhsl = 6
brpr = 2
hfrs = 5
wdmd = 2
vsvn = 2
zhmz = sfld + rhng
ddvm = spnl * mwdg
vmlh = cwzs + wnwl
cwzs = 4
gwfg = 4
snhj = gfjq + jqmf
cwmv = 5
ppvp = rtwl * wqvr
bqdt = bcmg + lpsh
qpft = 3
bcwv = mhfj + mdpd
jplq = wvld * sprd
mwmr = 3
nvsg = slfg + pmbv
tgvp = 3
fpvz = thfp * fdbs
dcgh = 4
bjpc = 1
jtnt = 2
qfdm = 4
tdlw = vbqg * tzsf
qtnh = mrmp + blrg
scft = 16
bqqb = nvgh * npdt
hcwr = 6
czbb = 4
fnld = 3
qvrr = 5
pbpg = 18
qmrh = 2
rrcw = 14
mcjq = 14
pzcm = 3
jlbq = 3
pslb = 3
dqwp = jwjh - drrw
cndg = 5
dnfh = tmdj + wpfl
ddgd = gfbs + tfdn
jvqz = nltz `div` dwgj
szvm = 10
rlfb = 3
llhs = scnp + fssf
brrr = dvgl + szvm
gcct = brbw + hthd
vvqj = tzwh + rzsq
jfgq = 2
mbqg = ctvq `div` gvvm
wrrt = tbnv * gwdn
rvvm = 2
sgpt = mstv + jpsd
qnrd = fwsj + qthm
tzpq = wssc * shsm
cqhn = 13
zjcd = qzvg * wmhn
wqbc = 2
fbcb = 3
vfqs = wdjm + nrvj
bjgz = 3
hrld = lfcm * fqlj
gtsh = qvvc * qpmt
wqrr = nljh * nlgn
sfld = 1
jmmm = bslv `div` plcs
zbgv = 3
bhbs = mqvp + qnhz
bwcr = ghvc `div` bnwn
jhmn = sctd * zhgp
cgbp = hdgc + pzfg
rbvs = 3
rdrc = 3
zqjw = 2
jsvm = 7
dtlr = 3
vwds = cfqw * hcfh
grhw = zdzr + jtbs
pnlt = lvqr * tthc
swph = tzpq - hfjh
qrrg = 3
dcfv = czgw * jbfs
pwdl = pnwr * wfct
fzzh = jgrw + rnbg
wrsz = clsz * zjtg
jnwl = 4
tsfg = 9
cgng = scft + cztp
dhzl = 5
rfnc = lrdn + cpqt
hmtm = 1
frgj = tzrv + grbs
sglr = 17
ndqw = 3
pntb = cgng + gblv
zhgp = mmgz + qgll
wblj = ndfv - crwz
rzrz = hjpb * cfnc
zgct = 8
trll = 4
lbcr = wwrz + szmc
pdvm = bhhj + zjtj
gbcd = 5
wndj = 2
gwcr = 16
rqlc = 2
mrhc = 3
wqzg = tdfl + rwmm
bhgc = zrcb * tfjw
tsws = plfh * dgss
hlsp = 3
rstd = 16
pzsz = nzgp * qjcw
pvlj = tpjf + fjzt
wndn = bszj * znsz
bngj = vrns * zbgv
wsqw = bhsr * tscd
mtvl = svrs + lzss
dpll = 6
qvgj = grwn `div` gzpq
tnrj = lcbc * qrrg
tvjr = 5
bjjz = 16
gmsn = jzcn + cnvt
thtw = frvh - bslw
zjwg = 5
tmhb = mzdb + hmss
ttpb = qwgp `div` vjsr
vsgd = 6
phwp = mglb + chpc
tzmv = 18
zmlh = mwfq `div` nzjl
rjvg = 5
lwdn = 7
tdvz = zgzb * fszw
hddd = 5
jwsw = rdml * chwp
wwrn = 2
hjzz = 7
dfhb = gbpb * qwdp
qvgl = jcsp * rjpn
wtrb = dmrb + pbcg
ncpt = 19
zhjb = 6
nqlt = 5
djrw = pqdm + gqzj
vncc = lnbf + dnqq
dgpg = tgjh * csqr
fstz = vqjs `div` hdff
hrsd = 9
vwzs = qcsr * nnlr
mdbm = zgmc * tshn
rqqj = spnf + ptln
clzt = 2
glzm = 3
twbs = vgsp * dcfv
hhgj = 2
zvsm = 7
zsnz = vjzg + rlrf
ggwz = qfgs * hwdr
wfgq = hlfv + tfst
rfhb = vhcg * zjvg
llhq = dpbg * zhcb
tdnw = qwlz * rtfb
llcq = 3
gtbj = pfbd * thwz
bjcg = lfvh + cqdj
dttv = 12
dsbb = crhl * pgsr
clhw = phtz * cfrb
tfrh = 2
wdjm = tqrg * mrct
dgbs = 5
rgzs = hhzt * bsdf
ldhd = 2
sznh = blbj + tdbt
fgmf = 14
svrs = ndrr - dzdb
zwcl = zqdm + ggcj
chtr = lvdm * thss
hqpj = 8
nglb = ldnq * jfqj
fvjr = nqdm * wcnf
ffls = 6
mfjl = pths * zzpb
rdhb = dvbp + pttw
zpgb = zdzd + swrj
zbfh = btpw * pptr
pgqt = hvrb * pnvz
dggw = jfjv `div` zzzt
dtbh = qjlz + hcnw
nllc = mrdp + wmwg
jsnt = svdf + vnjr
rbzr = 1
lbdp = 3
dwtq = wmpf * gcwt
wgjr = qvnw + hwqm
brnn = 2
jszd = 7
hcgd = tfjd * vqds
pgvl = 17
vbzv = 2
zsvw = 3
jncw = jswp * grqb
qzjd = nwsw * wsgc
bszj = vpcn - npjb
lwcp = ddsm * dlww
ctvq = tswl * jvwq
vdnj = 5
gsng = 6
zsmq = 4
tpjf = 1
zmbf = 3
tfqd = vwll * bhsl
gvpp = zqjw * lrgl
dnpw = 3
bfjc = 5
vshd = 2
rngb = sbbs * hfcw
chpp = rbsw * chsn
vmnp = 11
zwbj = 4
wvvp = zzrp * jsmg
vssm = glsf + tjsp
pvzn = qzjb * gncr
nnrs = grnh + rlcp
jwbl = dtpp + wngb
jsps = 2
qncp = 5
mtpd = 20
vmdq = 4
qbww = 5
rrwf = 4
zrcb = hmwp * tsbc
wdjl = zdzt * rdlb
cpvv = 2
mpdc = pnlt - svvz
psbc = 5
fscs = dgnt + htrt
cmsh = tnrj + gjpg
sjsw = fqlv - hrnj
svdf = 9
ngwv = qtlj + lwqq
svcm = 4
hfng = mrhc * qscw
sdsg = nmft * bvdt
lnld = 3
tshn = 14
fqbm = fgvt + lzvb
wrsc = rtcg * ndqw
hhzt = 5
lmjt = 3
sdcf = lzqw * gzzf
tptf = 9
qllf = hhdr * hgrc
hsll = dzfm + tvcn
jqjq = nmlg * gnhd
zgch = ggwz + dstc
qhtp = gbwc * pdhv
gfjq = nhlc * jhwm
sjdj = cwls * wtwj
thss = qfjf + mnwl
mcvc = fbsn + psgw
qzbv = mnsw + wzgz
bdvl = wswr * tblc
wfmj = tqgq - pwbn
tsgh = cmbj * sdcf
nrll = 9
wdnm = vqzd - hnjz
zcnc = vfdm + mwdb
zjcr = qncp * qlqd
pvzc = chmm + tlbm
cqvh = nrzd * ztcr
wrvt = pzbr * dggw
gtvf = vmsh + tvtn
vdmw = mzjw * tvtl
dbfd = cgdr * vhmz
mrbm = gvzz + vdsf
dzzn = vttd + zdhj
lflz = mvnq * bgqp
rlcd = 1
cmrn = 2
tjgd = mfjl + zjcd
bqsd = phwp * zwfn
nmlg = 6
mhll = 2
qwgm = sgcb * bwtw
vbrn = sjrz `div` wjqp
fsdh = dqvj + lsvv
whdh = 4
gjnr = znrj + dptn
nvgm = lgws * dndp
mstv = fqrf * gsct
ztgm = gpnm - jjrt
stzj = 4
msds = 5
mgnz = 1
ctqv = vbmr * tfzv
ghzz = dtpq `div` mnfq
hflj = ghqg + ctcj
jnts = rgjg + qbww
flgb = qlfm * grcw
slgn = 4
ljrg = 3
dgwq = jrrs + zccc
pplh = 7
tdfl = 3
bmbb = fbsv * srhj
lsvv = bgmj * hcwr
jfqj = 2
tfcl = tptb * bgcs
lwqq = gqlm * vlrd
szww = 2
szzs = 4
fqtj = 19
pfsj = 6
fhfh = vdvv + gzrq
hmrt = smqq + wndn
rnqz = fzvn * mclw
gczf = rnqd + hfbj
bcgd = gnpd + spgd
sgcl = psjc `div` jsps
tdbs = hcgd - fvhw
tpgv = tdjg * gsfd
mmll = dtpf + szll
qzvg = 13
rpjq = 5
zcbc = gwcr + gmsn
lrsg = 3
qvnw = 5
tlrb = tbpl + dgwc
ppsm = 7
ldpv = jrgj + dgfq
tmdj = vbwn + rlgc
dmgd = cbln + rgws
sbbs = 13
hjgm = hjvl * hwbs
lmlz = ddll * zgjv
gwhp = 4
sbdl = 2
cgrj = 2
bwgv = 5
fmjs = 3
czgw = 3
gpms = pshm + cbwl
wlbz = 7
ldhz = 4
rlhm = 5
ncpb = 3
wpgl = gwhp + btsv
nqzc = 2
hjwf = 6
jvvr = tcpq + gvcv
fvsm = 4
dglb = nllp * srqm
ptln = whhm * wztf
hnzv = lrbv + grtv
njvp = 14
ncbg = 9
vzrg = 2
ncfh = 3
wgjm = 2
cgvc = 4
fjnd = bjgz * qljh
jmzj = hsln * dsnc
grtv = 1
fbdz = ffsm - wbwr
lsvw = 2
gcqf = 6
pdjr = lhrt * mjsw
zrjf = 1
jsvj = dqcb * cclg
hlrj = 2
wrwg = hhcl * pfsd
vsgs = 3
svqt = jdfh * wbnc
qqzb = hhqq * zrlt
vfqc = 4
pjtb = 2
mrhj = 7
gtnj = 6
hwrg = 2
fgsv = dvbw `div` pzrc
wwrz = vdmq + mbqg
jrrs = 4
rdvf = jcjv + mgnz
jlzd = 2
mglp = jctm + fvpj
pnpb = 1
wpvw = 3
zqvr = ssnn * dwwh
gtlb = mwcq + qdbb
bvnb = 5
dtjd = 2
mtzm = bhzj * cpbj
hcnw = 5
nrqn = 4
mlgm = llnj + vgwz
rzwn = 2
rzsq = 4
chqv = vwss * lfgr
vgsp = 2
vhls = zsnz + dlnm
clcp = 4
dtpf = 7
fzjv = wssd * zmph
lppg = 10
njjr = sbvb * lpjg
pqlj = 5
mglb = cpqr * gpbv
jdbd = hcgc + trmp
blrg = msrz `div` mlrn
rglm = 5
hstd = 4
pmsp = hgnm * nbpt
wtsj = 4
cfrb = 2
zmrd = pvzc * qncm
dlpj = 2
tqqd = 3
hrns = zpzw * fjnd
pstz = sfcs + pzcm
qglt = sgss * gcjt
jqnr = 7
nnlr = 7
zhbs = njtn + wgvm
ncch = fjrq - bjpc
bfcn = 2
ctcj = 7
rsdv = nrjw * mddj
dclb = rcfh - gfhs
hwgr = tghw + phwc
dbwl = 2
nvzz = 11
ntdt = vwzs + bbtf
rccr = 2
qdgh = 14
ndqc = qzgt + zmlh
bmbq = hhsh * wdff
ccwq = lvrd `div` hnrz
ngls = 8
qhgz = 4
zqnn = 1
phgr = 5
tfhq = wqbc * tpcl
qcmj = jbjg + hqpj
jcdp = mfrs `div` wgjm
swsg = mmrl * qcmj
prhj = 5
bcmg = wwrn * hbvq
dcws = 1
zvzp = 3
thwc = vwnz * cmgz
chbw = cndg + sjbm
lnrf = 2
fnnp = tlrb * tlhl
srdg = 2
spth = smzl * jbtv
hwwc = 7
frnb = 3
ggcj = lcgp - gglg
dbhh = 2
fznq = 5
dmtq = 8
gsps = 8
chtp = 5
tffb = 2
lztp = wqgv * tpnh
pghs = wtrb - fwmj
tcpq = gljb `div` sqcs
zzmz = vlgr * grjn
pvdq = bhqz `div` zpll
hwbs = pqht + hdvs
nzvd = zpbq + dzlz
dstv = 13
chts = dtdl + vpnq
wpwm = 11
mmrl = 9
qqbp = cwzv * dnrj
mslj = djfr + jszd
lbzl = 9
rdlb = 3
fbsv = fpgn + mdbm
jpsd = gpvj * lptn
wzmw = 5
zszm = 7
gtwd = 2
tvtd = jmmm + rfgd
wmpf = 2
tgnb = svqt + wpql
bhzj = cvmv * wgjr
bnlh = qgvr + qrhq
zpbq = 18
qwqr = pvhz + trzt
blgc = 2
jcfh = 2
pvnj = 4
humn = 855
wvld = 19
grgv = qzpl - dbtg
btpw = 10
bwtw = 9
nthg = 2
mddj = 3
gfvj = 3
bpzw = czmp * rqgt
cpwb = 3
nlgn = 2
wntz = bhrv `div` mwvc
tlwj = 3
hlrh = 3
zsdj = qfjl * rrns
lwcm = 3
plfh = 3
nslp = trfg - hghn
vcqq = 5
cqwv = 5
plzr = spwq + tjhg
nqfp = 6
dwqv = 8
tgzm = dcgh * znpr
gtqv = qdps + nltl
rgjg = 2
qqpn = 6
wzct = vfbw + gpzw
gdjm = 2
wgfc = 7
flmd = 5
qrzt = 13
fthr = 4
chlt = jhbp + bnnl
lhdb = 2
qplg = drcm + lrtm
rlhd = 5
rlmn = 2
ptww = vndb + mrqj
qjqb = 11
zjvg = fnlz * zcbc
qrrp = 2
dhtd = 7
zgmc = vgnm + ngvh
jpcs = 3
hbvq = 4
fvct = 13
hhtw = 2
wfct = fjln `div` fjbh
gvjq = 8
bhrv = vgbv * bhcb
rtwl = 2
vhcg = 2
qhsv = rccr * hgvt
rtgj = 16
brpn = jjlt - nfgb
bbgs = 1
ddsq = 3
brhn = whlq + sznh
bjvm = 2
tdtc = 4
zhpz = 2
spwz = rjrt * jqvb
mfgp = 2
mhwn = 3
jhzd = 5
mjvp = 4
gbhw = rfqd * rhhm
cqmn = vfvr + bqfc
rszz = dgvf * ljbm
wgvm = zpgb * bnvv
psps = 5
jjvv = 2
bpdj = 2
jvzj = 6
vmsh = bdht `div` ldhd
zjvz = whgd + gbcd
fpbt = hgmb + djdw
fghp = 2
znpr = 6
nlmw = 2
pnsw = pwbb * qcht
hrnj = 3
gpvj = dcvt * mpvr
fjhf = nnsn * jngw
sltv = 2
dqvw = mjnp + rfnr
llnj = bnwz + lbhv
tptb = 11
ntqg = nqzc * lssg
trfg = zsft * wlbz
swrj = gnzp * qwqr
wvfn = wwcz - mcjn
dwgt = 2
ltmf = 14
tdmn = 13
qscw = 3
fjbm = 5
tdbt = jchd + rtgj
dvbw = rdtf * zccb
tnlb = 11
rcsj = 2
pmpc = fzjf `div` hfrs
fdsm = 12
vghh = lrpj * nglh
pmtd = 3
jchd = cnqq `div` gtvq
wsvf = 2
svsm = zgct * fqgc
cwpt = fbsj * wfgq
hvrb = 5
gzrq = 3
tfgg = rpgm `div` sgvf
plhm = ncgv * dbhh
tbnv = 3
cpgw = wgbc * tmhb
tgpq = 5
shdb = 2
zcsn = 12
lhsn = 3
zgjv = nzdm + ncrp
lcgp = jhgl * rgth
cbwl = zjgh * lbrd
zjbz = 5
trbf = 19
tczs = czqd - twqq
thpm = 17
fbsj = tgjj + fqcm
clpg = 16
czrv = bpvp + fhfh
qnzv = nfpp + jqjp
wrgr = 2
tjqq = vpmw * gbgf
mjfs = tvsn * vfqc
zwfn = 2
wmzb = 10
nltz = gwfg * lcgq
pfrm = 2
qhfv = dzgg * nmhg
cbbf = 3
bvqg = hpws + cqmr
tgzr = swbz * tjbc
hhcl = 13
mftw = 3
zcgn = jfjl * msms
srsj = stds + fvpw
lmdr = msml + mbgw
vdch = 1
brss = sjsw * lbjm
ptbv = 4
zhjp = mtnl + cwcb
hsdj = cwfj * vznm
dfpv = 2
qjlz = 1
gglg = 12
rnwr = mgmh * tgnb
hgpj = tbfn * tgtq
hmdh = 7
qjrz = sptw * dqvl
rjds = 4
qbsd = ddsq * fbvr
jjqv = vpbb * qccg
hmvm = hjtj `div` mdpc
gljb = znqs `div` qgms
vpbb = dzzl + cpbb
lbgs = 2
gwdn = 7
pbsc = fbqr + zhwq
vfvr = rhdz + trrq
tlfn = 2
blbj = tjqq + jmnf
mcgl = zrbs + rlhm
dmqj = qbmq `div` hjwf
bqgv = dvlb * whtz
cpbb = drfw + dmqj
szwg = 10
smhb = 4
jbtv = 15
lzvb = 12
wwwq = bmgw * lzbl
qlqd = wvfn + zbbp
pptr = 2
wnfq = 16
wdff = 17
hcpg = 1
vgvw = 11
rzgg = fvbn * vccz
qzpg = lwfh + lrtr
znrs = 9
jnpc = blgg + gbwd
lnlg = vmnp * vcqd
jcjg = hpdw * qjqb
vdvv = sbmb * srvr
gfcm = 5
rzdv = 2
spzn = gcqf * hnbp
sbgb = ggsq + lfjf
gsfd = 2
zgbg = 4
bhcj = nshq + lmvn
drrw = 4
hcjt = 2
pzrc = 2
jfjl = 2
pctc = 6
gggr = twgp * wpwm
wtpb = 14
gncr = 2
lbnh = mctq + nlsn
hwsh = 4
pmqv = 4
ppbd = jfqr + lzqm
cdvf = twbs `div` hjlp
nlsn = qmgp * plvh
jjlv = fmjs + bvpb
lmmt = qwcb + hbmw
hdwc = 13
mqws = wmzn * sfzc
mjsw = 12
pfjj = 2
hngm = qzhf * jfgm
mdpd = jvdc * nrnb
jswq = 5
bgcs = 3
pjjh = mdbh * ctqq
vncq = 4
jjpq = 5
qbmq = grsz * hplr
dzrj = cwnd + hcct
clbs = dtbh * cbbf
wgml = tcpv * hrpq
mmjj = mnjh * fzqt
ffhb = 12
pwbn = pbsc + rmdr
btsv = 9
gnwj = 2
zmnl = 6
hmwp = 2
rdnh = qbjw + lwcp
vnjv = mspc * sltv
vngt = nglb `div` rbtf
vccc = 2
trrq = ghtz + nqdj
clsz = 2
cwgq = msjt - ddgc
jlff = ffmz * ccfw
rbtf = 2
jvbv = 8
rtpm = sbdl + fvzv
slwr = zzjt * fhwn
pjfb = 3
pqht = 17
gjpg = zcpv * dvjq
jgjb = qrdv - njqt
lfcm = mzmh + hmtm
qcwp = 3
lzwq = 3
gqgq = 1
mclw = vbgd + zvgp
zrht = dtcd * swqt
ffmz = 15
jttv = 3
cmbj = srsj + bqsd
zrlt = 7
rvqv = 3
smzl = 3
znts = 2
tnpc = 15
rsff = 5
sdhh = chlt + jvbv
cglv = qdtw * zwbg
ppgd = tnpc + djfv
ddgr = 4
slhp = wmzb + vshl
tqdh = 18
npjb = 6
gvjr = 7
qwdp = tsvg `div` nlwp
bvpb = 4
qbtm = 2
rgws = 5
vqjs = lnpq * llhq
tdjg = blnq + wfmj
hlwf = ppvp + dqsf
rtvl = mbgp - qqbl
pqzg = 5
wfts = bzdz * dzww
rlpt = 5
rhdz = bmlw + gfvh
drtq = 3
sjcc = stjr - jcwl
tcvm = nbpm * swph
wtwr = 4
hvjz = 2
pcff = rgpp * vgwj
whpl = slgn * mbnm
nnbl = 5
znsw = 4
hmss = fbgc + ltzd
dpbg = 2
fjrb = 16
czqc = nzvd * bpsl
smqm = fcsb `div` hwwc
zrbs = gvmf * bwmq
wbnc = 5
zccc = 3
rgsh = 5
fszm = 3
sptw = 2
mspc = bngj + hsgg
wnjz = 5
dhpc = 4
tpdw = fnld * rvmz
grjb = blpq + ghgs
lddn = mftw * sglc
nftz = 2
gzqc = jvzg * cltm
qrdv = qfdm + rhjj
lpvw = hghh + pvdq
tzqb = 11
zghq = bhjg * ghrv
hnvc = 9
npbf = 15
rtzp = vstr + qrhd
chwp = mlth + pfpp
drfw = vbpc * brpn
wfzn = 2
jmnt = 2
lfls = 5
mppr = dgpg + wrrt
pbwq = 1
ssql = 2
wswr = prrj - pcff
dqzd = 13
jjbt = vlln * mrhj
wdww = nvmn * cqmn
jsnv = mtpd * lsvw
bcbc = ngnc + mpfr
vqfn = 10
jqjp = ptww * vhfz
nrzd = 4
zqgc = 9
sgjc = jzqs * dtlr
phrs = dsbb - jpcs
mhql = wdrt * ljcf
gmrn = whpl * gblj
tppg = tdnw * rjjl
zfdr = 2
jtdq = 5
qplm = dplt + thtw
blpq = brhn * hvjz
lwfh = lgtd * tvsj
wmhv = ppjl * srtg
zssb = tzfp + lztp
cpdc = gtwn * wbdm
srnh = mpdc + cmdp
cmdh = 2
fwnc = 3
vjsr = 2
ngvh = 3
dtpq = cffj * sjld
jvtz = 3
zdbd = ndqc * mfgp
vwcm = zhfb + chtr
sdms = 3
slhc = hmrt * sdqw
dvbp = 11
tmrs = 2
swbz = jttv * hvfp
mbcf = flwn * tpjw
hjpb = 3
vrns = wsdd + mhql
mbgw = hjzz + zcsn
lfjd = bbcm - mrcb
cftw = 5
sgrm = jnpm * wrdw
dtcd = dmmd * zprj
lmjv = swqg + qdgt
gtgn = 1
mbnv = 9
ccfw = pfjj + wzmw
tptj = brwh + stzj
wqgv = mdmr * ltbp
rgfl = rszz + dngf
nbpt = 2
ntpg = 2
gnhq = 1
crmt = zjwg * rgrh
jjhh = rltp * vnjv
bhqw = hztd * crmt
zqcz = 2
jnff = lvdh * dmsb
dspt = 3
nzdm = qndn * ltfs
mqbs = 6
vgbm = 7
jnjd = nvsg + gwwt
vsnt = zdls * hfwt
htqm = 3
qdns = hnvf * qtnh
mtft = 4
gblj = 4
nrjw = plts + snhf
dnpq = sgqc * rdvf
vlrd = pgtf + rvvm
ggrf = 3
ltbp = 5
nrdl = 5
gpzw = gczs + czrv
qwlz = lgvh + zllw
hnqg = fdqj * pghs
sgcb = 3
sncr = zhmz * cbcd
bgqp = 4
tstw = 4
vbgd = 10
mhht = 1
pqzw = vqsq + cfgv
nbgc = 2
hcfb = dpgq * cfjc
shrc = hlpt - swfd
gmhv = mzpd + wdww
qjcw = 2
gmnw = ljnd + fpcd
pths = 9
dqcb = plvd + njsb
qfjc = 5
qhbl = zmbf + qhtp
lshn = 5
bbgl = 3
jcjv = szws * gmqd
zdzd = 2
vctl = wstd * htfw
jctm = mppr * szjv
lzss = 2
qdlt = 9
srlw = hwmv + rlcd
jnmb = mtzm `div` gjsj
qcns = gqqb + lwvr
jlwb = fstz - mgvq
cpqt = gczf * lhfp
grnh = 3
lmgg = 17
sdwp = pmgh * dbfj
vjzg = 16
pphc = 3
grcw = 8
gjsj = 4
gfhp = ncpb + zsmq
fjln = jcdp * hpwf
vcsh = bfdc + fzwp
gpvb = fthr * vvqj
ftjz = rpjq * qmwb
nmhg = 2
sbmd = 4
cvds = pqlj + qbsj
mqvp = pqzg * zhdn
dvjq = vzqc - rnqz
qbhl = 2
fwmj = 5
rqwf = 11
jmgz = rgbj + hcvv
ssjf = htqm * wzjp
nlwp = 2
zgqh = 2
pfsd = 2
nmft = 2
rjpn = 7
tbzv = 5
tjcb = 4
jtcv = 1
thct = lbnh + sgpt
frcf = 4
nbpm = 3
zllw = 3
svqr = 5
gqlm = 4
mhfq = 6
qmgp = 2
hwbl = qbsd * hhgj
qljh = bfjc + qjgh
szfv = 2
tdts = 17
mzdb = vcwc * bsbw
pdfh = 7
qzgt = znts * plzr
szwc = wgml + nhdp
sclh = 2
tvcn = 8
rhcp = mvhz + fdfl
dqnm = 5
cgdh = trll + gggr
wpfl = 18
lzjn = 7
hdff = 2
mgvq = 4
nznz = 2
rzjl = 4
pfpp = 9
hjmb = srcv + wgpz
qfcg = dtnv `div` gzjq
gvvm = 6
dscl = zgll * qmwm
fhth = 4
wmzq = 3
rfgd = 7
cfjc = 3
fpcd = jlgf * sjhh
gzpq = 5
zdzt = 2
tzwh = jbgr * nsgc
tsbc = tsgh + tgzr
jjsc = 2
zpzw = 2
dtdl = dhpc + vsgs
dzzl = zrjc * vnct
rdml = 2
pbbd = zlvd + wndj
vspw = zmrd + wzsf
cmng = 3
tdqs = 1
tfdn = bvsf + wcvs
rltp = gvpp + vcwg
vbfb = zsvw * hbth
lfvt = nbbg * zvzp
hbmw = 12
dgfq = 4
rlnz = 2
jvzg = zcrd `div` wsvf
pqsg = qsrq * hjgm
nrnb = 8
znmm = 4
tthc = 2
bzjc = nrqn + qgrg
rjrt = 2
psls = jmnt * lcms
wzsw = 13
ctzc = 2
cbcd = 2
mctq = 5
brlp = zggp `div` tmrs
zhfb = tscr * dhgc
nvjl = tnls + cvds
rmfd = 8
sbhm = 2
plgp = nlzl + cgbp
spjr = ssnf + clcp
gcjt = 2
cvzw = 11
fqcm = 1
lfzb = tlfn * llhs
lrbv = zhbv + mwpb
qwjw = hdtj - bdln
qdlf = 3
crdh = 2
tsvg = qvgl * wtpb
pnvz = 11
qwzc = bnlh + wrvt
gnhd = hstd * tffb
mjnp = fdzn `div` sttm
ldmb = 2
lcgq = qbhl * sbvt
jrgj = 3
srgd = 13
rsgh = 3
srnb = 3
pgtf = 11
rjfc = 1
hgvt = 3
rzlg = qgcb + mfbs
fzjf = dzrj * rlpt
wgzh = fjhf + mbcf
zdls = twcp + wgzh
cdqj = wwth + hwsh
mbgp = ptgc * hnrp
mpzh = 2
fdzn = ttpb * jcsg
sdnr = jbvw + vrdd
lzqw = 5
cpbj = rhvf * ntpg
nvgh = 3
tjbc = rvpd * brlp
dvjc = 2
cqll = dvjh + zwcl
jwpr = chps * qbns
sblm = vcgp * nnbl
tljq = 2
jtbs = lrvq * nfqr
fnwq = sdhh * bbsr
pzmm = rzlg * sznr
hthd = zcmj * smqm
qpjn = tfgg - sssq
hbqd = vsnt + ffhv
fbvr = 3
ndfv = tfht * bcgd
rpgm = jtnt * qlwm
nglh = 3
lrtr = szfv * ffmm
jngw = rzdv * czwl
hhsh = 3
dbtg = njvg - wrgm
rrns = qmbr + vbzv
tght = 11
ghlw = 7
bqhh = 2
bvzf = frwt - hdcz
vnjr = 16
gqqb = 12
wnsn = ftqz * hsww
gvfh = bcgt * jwff
zhdn = tdtd `div` msds
ltgp = rfhb * dhwf
smgw = 2
zgzb = lwzc + gzsw
sttm = 2
hnrp = rtsg * jsvm
cnbl = 5
zrff = zlgg + fbdz
lwhh = fpmz `div` brpr
vfdm = 14
wsjb = dfwt + nlrt
smdv = lflz + pzmm
cztp = rjds * rbgh
rwgr = 12
tgtq = zbfh - zpmp
nfpp = wpbt + zthq
dsbj = zhcs * pmtd
jrph = rscz * pcvb
njsb = 5
hhdr = 4
wcnf = 7
vhqn = dpnc * dlpj
lwzc = 5
mdpc = 4
qncm = 4
jtrn = zrjf + fgsv
spmd = rnss + ncpt
gsct = 3
gnpd = zwsp `div` jffs
psnq = fqbm + dwtm
glpt = 2
rrbb = rzwn * szwg
dtpp = 4
fmng = fmbt + mwsg
dbfj = 4
jdww = svgc - hjbp
zqdm = crlj * wptm
fffz = wcht + grjw
tnpl = jnnp * qqpn
dztm = pvlj * tdtc
rhlg = hhtw * nvlf
qmwb = 6
npgr = ctpg - jqjq
gwfl = bhbs + qqrz
wmwg = gtnj * qrrp
lrvq = 3
pvpm = wwwm `div` glpt
ghtz = srnb * rgfp
wpcv = 2
lhwl = ttwb * wpvw
tjsp = vqmd + hvqp
tlnp = 2
vfbw = pvzn `div` hnbv
mnfq = 2
nwfd = 20
hmfq = 2
spwq = fpst * sgcl
nshq = 6
tpdt = 2
gqzj = 15
vwss = 6
gwbq = bbzz `div` ttzr
tnzz = 3
sctd = 2
fmrf = 7
qzfd = zhpz * fnwq
vhgv = lfzb `div` bdtl
dnph = 2
gtwn = fsdh + srnh
bvbj = bmbb * jrlv
tzfj = flgb + gtqv
smcr = 3
jrlv = 9
znjt = rnmw + bpql
zmhw = zgmr * dsdl
bhsr = 2
dbsw = 14
jhgl = 2
qsbp = 7
hgrc = 5
ljnd = gpms - lglj
hfth = nqnw * rblm
lrgv = vlmt * dwgt
wdzt = 2
blnq = mjfs * szww
tnjt = mgvn + mjhm
dnqq = 2
ldnq = lbdp + bjcg
ctbh = qlvw + lbzf
ssnf = cwfb * rqwf
ssls = 2
cnvt = gfdw + hrrn
vfjv = wnfq + rdsh
hpwf = 2
dmdl = 3
jbvw = dqvw * wrsc
zvdv = 2
fwsj = hcfm * grjb
tfjw = 2
fgfj = 6
pvrb = 8
qbsj = 6
smrh = bpjc + mcfz
mnmv = 3
wgbc = 2
nlrt = 10
qwgp = dfpv * dsdn
srqm = vqfn + dpfm
lbhv = snrr * zssb
crwz = flnz * fjbm
trct = 19
gtvq = 2
hwgb = wlcr * bhgc
nrvj = 8
qlfp = 3
mnff = vctl `div` dtjd
czqd = cqrb + vwdn
tddg = 10
sssq = 1
stcr = pqzd - fgdw
ghqg = cjrg * tgnh
frzm = pbzz + vghh
tqrg = 3
mcfz = fzzh `div` dtdt
gdlg = 2
rvfj = qcns * ptnt
twzz = 3
bbmm = 4
jgrw = bwcr - jnff
bcgt = 5
vgwj = 3
fvwt = wvvp - psnq
msrz = nbgc * dglb
dmhq = 9
gblv = 6
hcfh = tzqb * pvnj
phtz = bfrr `div` wnbm
drcm = pmsp * bqqb
cbln = 4
ggsq = 5
mvmn = 3
pzgj = 9
qrhq = nbqf * zgch
fggl = 2
cnjm = dclb `div` rhgt
swhn = sdsg * ldhz
rwtr = cwlb * qjfp
tfjd = pbcq * jwbl
sfnm = nmrn + nqdg
gqlh = 18
nzgp = 3
jqnc = mnff * drtq
vbpc = ntqg + tgpq
hdjv = 3
hnbv = 2
zsft = 7
fvhw = fhfq * grgv
dpgq = 4
pzph = hnvc * jpnz
mcjd = 4
fjrq = lhdb * ffmd
tdmm = 3
pfqj = 15
zgtf = 3
pmgh = wrhp + rjfc
zphr = 3
pwqd = ljgh + gmrn
lrtm = fffz + swsg
qrhd = 2
qlvw = mfwr + stbr
sjrz = ggrf * mglp
zzjt = 2
tzmg = zfln * vbrn
zbbp = 6
nhdp = sdwp * jhvq
crcr = glpc * bsrl
mcjn = 5
fbqr = 1
ttzr = 2
jsph = lclz * ppbd
bnwn = 3
ptgc = 2
bgvr = sclh * sblm
wnlf = ffls + jswq
vstr = 5
mrdp = gmzr * ngfj
mzpd = njjr * bhqw
jbss = sjcc + swhn
rtfj = 3
jppl = qdjh * zwcr
sbzv = 5
fjzt = 8
pplj = jwzt * tlwj
mwcq = lmjv + fwll
fmtl = pnjm + rsff
phjw = 3
root = gvfh + njlw
lzpd = 4
wzsf = jnpc * jjpq
zjtg = jwpr `div` znsw
frvh = rjmb - dtqz
jwjh = 12
ttjt = jsvj + vvmt
fmdv = jzqn * srgd
mgpl = jtcv + wsqw
rtcq = qvzb `div` zhlq
mpqs = mhwv * shrc
mmgh = frzm * bzjc
wqvr = fcnm * nthg
wptm = 5
twjr = spjr + tnhq
spnl = 2
jzqn = dppn + wntz
fcnm = dhtd + dttv
wzgz = 4
gmcq = rcqp - zgcs
qnhz = 6
qzhc = jrcc - pmqv
dhwf = gdlg * nddc
cqgh = qfcg - rlwp
dtqc = 2
csqr = 2
bbcm = 10
qjhv = 2
wftn = dpvl + tpwr
hslv = 4
bhhj = 17
ltdn = 4
mwdg = 3
ghnb = 3
lvvz = dpgv + tdlw
grvq = 1
flwn = 5
wzjp = 11
ncgs = 5
tpcl = fmdv + vdhh
cfqw = 5
dsdl = 3
sqbn = 7
bdtl = 2
bmlw = 1
vwll = lsjn + qqst
mhfj = 1
lsph = cqll * lbgs
wbwr = qcpj * zgbg
fvpw = dnpq + bhcj
rhjj = jwsw - cbcz
tvsn = 3
qzdd = 5
wvwb = 12
bmrj = 2
mrct = 5
wprd = 2
lwvr = nhnw - hcpg
dngf = 5
nfgb = 3
qcnr = pslb * plcr
hnnp = gspw - lgsw
wrhp = 6
rnqd = sglr * gnqp
vzqc = pncc `div` bwgv
frbv = 10
nhnb = 3
tzrv = mcvc * mlgm
zfvl = 13
pncc = tmsb + qhfv
snhf = rjcm + rlpp
rrnw = rzgg + jbsd
tbfn = 2
bpjc = wzct + qzjd
gmzr = 4
cvdl = ccwq + dztm
gtvr = 2
zsrl = njzj * bzfw
trzt = 5
rdpz = 4
mthb = 9
mdmr = 4
hgnm = 5
mfbs = 5
fcgs = ljrg * fmrf
ncrp = lpvw * tvjr
jcsp = 3
tzdd = 2
lclz = 7
hqsp = 9
dhgc = 5
smqq = tfrj + pnrq
gnqp = 2
hgmb = wmhv - cqtg
gbht = 2
vpcn = fvct + hlhg
mrcb = 3
jssr = 11
rvpd = 2
fzqd = 7
gfdw = pjfb * zmhw
hdgc = 6
hjvl = 2
bsbw = wnsn + qwgm
zgrr = 2
dpgb = pzwh + lppg
tlnj = pbpg + pnpb
qgll = 4
bfdc = 1
nqdm = 2
gnzp = 2
hwdr = fgjt + pqzw
cqrb = fhth + fzqd
nqdg = 3
lpjg = 3
tgnh = 3
cgdr = 3
ghvc = bdvw - gbhw
bsrl = tbdr * tstw
lcms = 3
jwff = hwgb - hmvm
ghrv = 2
fzqt = 7
swps = pgns + pfqj
ggnl = fpzt + vdnr
btvd = 2
bpvp = pjwr * dtqc
hdvs = nqtj + wjsp
qqbl = zzmz `div` wdmd
shjp = bqdv * hzsv
fnws = nwfd - spqg
lvnf = rdrz + rbzr
zwmq = gbht * qlfp
tnhq = 1
mlrn = 2
hhqq = 3
zzzt = 2
zpmp = 3
zgmn = 13
jcwl = jvqz + qjhv
rcfh = zfvl * pfzw
csjv = 13
jtlf = 13
qlwm = phrs * bhjn
pzlt = llzb * tsnq
qgrg = 2
njqt = 4
qgcb = djcv * jfgq
vlmt = nvgm `div` dnpw
pzwh = 1
nbbg = 3
dbmw = frcf * wmzq
zffq = 7
ntmd = 15
cbcz = mcgc + hwbl
swmf = pvpm * fmtl
zthq = spbn * hzgq
wlrd = 11
szmc = 3
dmsb = 4
cwnd = jvpc * jhww
zwcr = 3
tswr = zgqh * bqdt
qvww = cqhn * gfvq
dfbg = 15
mfwr = 7
cnhc = 2
mrsf = crdh * vqzl
hpws = pvtq * btvd
qnfn = clzt * dfdq
vgsm = pdjr - wgmz
tprb = fltv * vhls
pwbb = mthb * prwh
sdnf = 2
hcgc = cczv - hlqd
fdbs = jdbd * pvdp
ddll = 2
gpfs = 4
rlwp = jntc + qvgj
swqt = 4
grjn = rrwz + pfsj
jpcz = nznz * dgbs
jdfh = qdns + hnqg
qdvq = sdnr `div` jvgj
tlrg = 16
nzjl = 2
fqgc = 3
fqlv = vqjv + wswt
rrct = tslz * lwcm
hcfm = tgvp * lrsg
hzsv = 11
rjjl = 4
gbhl = lsph `div` jqqv
qzjb = vspw * wpcv
tsnq = lvnf * fggl
hjwt = pstg + smdv
jvdc = 2
fbsn = 16
lppt = 3
qsbh = snhj + plhm
vcvv = lshn + tvtd
gmqd = 2
frcg = 6
ctqq = 7
wzdw = 2
ljqt = 5
jjbr = 5
ntwt = 2
hmlj = rvqv * lmdr
cltm = 2
sgvf = 2
tqgq = grhw * bjvm
gjqf = ntzn * wfrp
npdt = 3
mlth = frbg + rlnz
dfwt = sdms * lgfr
fqlj = 4
tvtn = smcr * ncdz
lfgz = fghp * zjbz
npmt = gfhp + szfs
mhrz = 4
lvrd = zjvz * bfcn
pshm = cchn * hcfb
twgp = 2
blln = gwbq * bqhh
cczv = hfng * tqqd
dsdn = hrld - dwbl
zbhj = 5
chmm = vjcd - pjfc
sgvw = lpwb + bjjz
tdtb = 2
dzlz = 5
fzpn = glzm * mcpb
qdjm = dbfp + tcdj
hnbp = 3
qrqw = 9
dntn = sjsr * gcnq
pmnv = fznq * dbsw
bbtf = qmlw * pfrm
nqtj = rmfd + cjcl
bvtc = zhbs `div` lbzl
stds = zdbd - gjvc
nwpz = 6
grqb = qjdc + npgr
nglc = zrht + vmlh
cmdp = ztgm * gbnp
hjbp = zwbj * vshd
plts = rwgr `div` jlzd
qjzb = bmjq * vsvn
jgtn = 7
ntpz = wtfq * vgvw
lrpj = 5
djfr = 16
ddgc = bsng * psbc
mpvr = 2
znrj = lhwl * bgrc
dzww = hlsp + dwjj
dfcj = 4
plvd = 6
qvvs = 7
hfjh = 1
snbz = dsms + tqdh
pnwr = 2
jrcc = 12
dptn = hdjv * wdnm
wvfm = jrph - wnlf
qdtw = 7
fnlz = 2
rtsg = 3
fmnh = 7
fqrf = 2
hcct = zvwv + dzzn
srcv = hrns * vfqs
qcrs = ddgd `div` hsnv
jmpm = tptf * drfs
hltp = 2
bnwz = rngb * dqwp
vgwz = gtsh `div` dwqv
fbbd = 2
phvw = 3
sqcs = mhtc * mlgc
cfqs = npmt + qsbp
chws = 3
bsdf = 5
glpc = 8
lrdn = 18
hbft = 1
qbjw = tlrg + jqhz
vrdd = znjt + fcls
nhlc = 2
tzbc = 3
lptn = ljrp + phgr
lgsw = qdlt + cqvh
bdht = lrgv * wlvs
ngfj = 10
wssc = 2
dppn = zwmq * fsmf
fnbj = rvbs * flmd
whtz = 14
twqq = 2
fgsw = nwpz * nrll
whlq = chbw + lnlg
grsz = 3
hndj = gtvf * nmvr
zcrd = hbqp - cwjb
dzgg = qqbp - vtms
fpst = 2
gwwt = 5
dgnt = 4
tpwr = 3
nmvw = gdjm * vngt
vzvz = 13
fbgc = hdtp * pdvm
vchv = svsl - rdpz
srzl = 3
twcp = ldwb * rstd
mbts = gnwj * smhb
ffhv = wftn * fncq
bnnl = mmll * nhnb
bwmq = fpcg * dqnm
jpnz = 17
wfrp = 4
lbjm = 4
fvbn = 2
bzfw = 2
jhwm = 4
qpfh = 3
nvhp = zcgn - tnpl
ntbc = 4
ntzn = 2
htrt = 4
gvjc = 2
jqhz = jjvv * lmgg
jlgf = jvtz + clpg
shsm = qcwp + srlw
ndgs = tljq + rqlg
lrgl = ltzj `div` frzb
jbjg = rtsn * nrdl
wpbt = tsdv `div` cwmv
dstn = 3
pfbd = qcnr `div` czjp
msms = pngq - npqv
dpfv = 13
pbzz = 1
lbqm = szgc + vncq
vwhf = crcr + qdjm
sjsr = 10
rlrf = wlrd * dftr
grjw = ctvm * qcwb
phwc = hjwt + gmhv
bbzz = slhp * vzwn
svvz = 10
rnbg = tdts * thpm
gbgf = 5
jdhs = gbhl - pstz
lvdh = 15
nljh = 4
hbqp = dbwl * qnzv
nddc = zbhj * rglm
ghbn = 5
hghh = tzfj + vnjz
npvq = 4
fzvn = zmnl + qwjw
ffsm = shdb * tptj
cfgv = 2
lgws = 3
rhzd = vgbm + cnhc
gjvc = pwgm * lvhs
dmmd = 4
dwtm = clbs + qjzb
fsmf = chts + frnb
jdzl = lpbr * gfvj
tvtl = fszm + ngls
tstp = 2
wcht = znrs + rfqb
dlww = 14
sldj = 5
vdhh = ctbh * dmhq
rgbj = hsll + tnlb
wbgw = 6
dndp = dstw + ncwh
wwth = 3
dqvl = 16
dmqt = 3
bqfc = qpjn + dmtq
cwfb = 5
vgnm = srdg * qzsq
rnss = 16
spgd = jcfh * qplg
vdnr = gcct * tpdw
jfgm = 7
vtms = dscl * zqcz
lnmr = 1
tpjw = fjhr + fwnc
pdhv = 2
gfvq = 3
scnp = fgsw + wsjg
czmp = 7
gbnp = 8
nhnw = svsm + dpll
rlhz = dfhb * lmlz
ncnl = 7
rbgh = fvzd + hbft
vdmq = mgpl * bmfg
tfht = 3
wsjm = 2
vcqd = 9
mzjw = 2
tfst = qpvg - wmvz
cwls = jnwl * qvrr
mfrs = jcbq * tmpn
mbww = hpfn + bbmm
hsgg = vccc * sgrm
qmlw = zgmn * gcsg
thfp = 2
gvzz = mmjj * sbgb
bpth = cwlj * dqzd
wwwm = qnfn + jlwb
tghw = clhw * dgtj
gpbv = ddgr * tjcb
gvsb = 11
crlj = 5
wmnn = 2
rdrz = mrsf + wvwb
rjcm = 4
dpvl = 16
ncdz = mtdc * csjv
rscz = 17
qvzt = 4
zjtj = 4
wlvs = 4
fssf = wsjm * zrff
wbdm = ghzz * lnrf
jbgr = 3
tbdr = 3
qcht = nvjl * tzbc
mgmh = 2
mnsw = 3
dwbl = 5
pmsh = crhj `div` rqmt
hqfs = 14
tsnd = 2
nmrn = dtdb * zqgc
dsnc = mwpd + mmgh
dlnm = hgpj * qpqs
tzfp = cbgs + szzs
glsf = cvzw * hssc
cndn = 1
vlcz = hpbq * wprd
lsjn = zsdj + lfgz
hzgq = 7
dpnc = 3
rvgm = ppng `div` lfjd
ptbp = dgwq * cwgq
crjw = fbbd * npbf
nhsq = 14
ftqz = 4
vshl = 3
rzzm = jmgn * btmc
ppjl = 3
sbvt = jqnr * wzdw
mpfr = wgfc * dnph
wfhg = 5
ptgz = 11
jsmg = 2
jjrt = 6
szjv = szwc * twnf
hssc = qzbv + bcbc
bhqz = nglc + jmzj
dwgd = 16
vlln = 2
pnjm = 14
fcsb = hfth + ctqv
cdfz = 2
wspf = pswj * sbhm
rgfp = 3
rmdr = 4
znqs = tpgv * jmqm
bwwq = 9
tfzv = 7
mtdc = hlwf + nghp
jmpz = 5
mwfq = qrqw * zghq
cwcb = 6
tnls = 12
rfqd = vbfb + rvfj
pqbm = tlnp * brrr
gwdc = 2
prwh = 19
dmrb = chsl * rjvg
cclg = 19
zlwg = llcq * pwdl
jcbq = jtrn - dntn
ncgv = vcqq + spzn
bmgw = gwjp * gtlb
brbw = blln + dfbg
nmtc = pzph + lsvn
pfsm = 3
zgjg = gncb * lppt
lghd = fnws * cqwv
jzcn = 10
dcwg = tswr + zvsq
zvff = cmsh `div` hltp
qfgs = tshl + hlpg
qndn = tjgd - ttjt
mlgc = 2
stbr = 4
fpzt = qpwm * bvzf
cnqq = tppg `div` ldmb
drfs = 3
vpnq = 3
tslz = 2
srhj = 2
cqmr = tzmv + nvmm
bmbs = gtvr * sdfq
pqdm = nfnw * pgmw
tzsf = 2
hsnv = 2
cmgz = tfrh * lbcr
lhfp = 2
zccb = glwr + tfql
zlgg = 1
jfqr = 1
ltfs = 2
grwn = tfqd + vcsh
nwsw = lvvz - npvq
jmnf = wdfz + cvdl
vjss = czbb * ggwg
rhhm = 3
qpsf = 3
lpwb = mcjq + dcws
bhcb = 2
lfjf = rrct * tptc
wchd = 8
hsww = qfnz * tpjp
tsdv = cfqs * jmpz
zhbv = 18
rhgt = 5
lcbc = rqqj * lrbm
bmws = 5
rlgc = 5
tvfq = 4
rwmm = cgvc * fcbb
plcr = wqrr + vncc
vhmz = fzpn + bpth
fhrm = qhgd + tgzm
wssd = 15
sjvh = wblj `div` zhzd
bmfg = 3
whgd = mhfq * rzrz
qccg = 2
dnch = 3
lnpq = 4
cqtg = 7
lssg = 3
dpgv = 3
wnql = 2
rblm = qglw * cdqj
qpqs = 2
dtdt = 4
zvwv = lnld + rsgh
zggr = rgzs * pgvl
fwll = rhpw * mfbr
rgpp = hnzv + rtpm
hlqd = mjvp * zgrr
jmqs = jdhs - jjbt
rvbs = 5
gspw = qsbh + cmms
njtn = jjqv - dfqh
qzhz = 4
zlvd = 5
msjt = dvrf * hnnp
zhwq = 6
wgpz = mrmf * smrh
cfsr = ldpv * jgtn
szgc = lzwq * tpdt
gpnm = swps - sldj
fbzq = jmpm + jpcz
ttwb = 3
rfnr = ffhb + rrbb
chsn = 2
tczg = 15
nghp = rllz * mmvj
ctpg = thwc - gmbz
ggmh = lftn + qzpg
rtsn = 3
rqlg = 5
qdps = qhgz * pczb
mrgm = lmjt * zgtf
lsvn = jhmn * vdmw
qvvc = tsnd * nllc
lvdm = 3
bwhl = 5
zdhj = tsfg * lhsn
cjrg = 2
rdtf = rnzf * zvdv
fdfl = rsnc + sfnm
hrpq = 3
ffmd = pjwh * bpdj
sfzc = 5
mbnm = 7
jfjv = ntwt * frgj
ptnt = 2
tfql = 3
dzdb = 1
mfjt = 5
cspw = 5
ldwb = pjqj + ntmd
rrmz = wpgl * qmrh
vttd = blgc * nwfw
dcvt = 3
njlw = wwwq * pzlt
mgvr = 7
hlpg = zlwg + vssm
hjtj = rbbf + rrnw
qtlj = gvsb * qzdd
bvsf = 8
fqwr = ggnl + pnsw
qcwb = 3
cbgs = 3
dfdq = 5
sfcs = 5
zwbg = hrsd + fscs
ztcr = 6
fcbt = tdmn * nlmw
qdbb = gjqf * dpfv
bfrr = dvjc * jdww
fvzv = ncgs + zgjg
ssnn = 13
lfgr = 4
bnnv = 2
zggd = 2
wrdw = 6
mzmh = 6
smsr = 11
spnf = ntpz - djrw
slfg = fvjr * tvfq
lrbm = 2
tcsp = 5
fcbb = 7
cnjf = mslj + bmbs
rndg = 2
qdgt = hdbc + zsrl
pngq = phvw + gwfl
wmhn = vjss + jrqq
djjt = 5
qsrq = 2
qvzb = gvjq * pctc
mdbh = tczs * gvjc
cwlb = 2
dvgl = fhrm + mtft
ndrr = rqlc * rwtr
jwzt = 5
psjc = 14
pvdp = 7
jbsd = chtp * qqzb
gqjf = jmjp * chlh
dstc = hwgr + bgvr
wtfq = 15
ghgs = gzqc + mslt
rqgt = tdbs + jjhh
cndw = tzmg - rlhz
ncwh = cpdc `div` hcjt
zpll = 3
grbs = msct + qqzj
fszw = rrwf + qhbl
blhq = pndj * njvp
zgll = 2
rhpw = 2
sbvw = vlcz + mspq
wjhs = tcsp + whdh
nvlf = 5
dqsf = fzjv - nhsq
tbpl = 6
jsdw = plqr + jssr
sznr = 5
pstg = dmgd * bmbq
tmsb = rrcw * qghb
bhzw = ntbc * bwhl
tscr = 3
mwvc = 2
mnwl = 2
mtnl = 3
cwlj = 4
wlcr = 8
fwhj = 3
ltzj = dmjp * ggmh
qmrn = 6
sgss = jqnc + rnwr
vbqg = jtdq + pvrb
jvwq = 2
dgvf = zngc * qpsf
wtwj = mhll * mbts
fpgn = pplj + qzhc
njvg = 16
szcc = wdnd + ptgz
qcsr = 3
llzb = vpbh * vvmr
gwjp = 5
lhjn = gsps * zmnq
wjsp = 2
rrwz = 5
qfnz = 2
hgtm = hngm - whlg
wgrl = 1
rcqp = 10
zwsp = bdvl - sjdj
tpjp = gqjf + lttg
qpwm = 4
ppng = humn - swmf
dgss = 3
mspq = 1
njzj = qfjc * rqnr
cfnc = 2
hvqp = jmqs + cdzs
vbmr = grvq + sgjc
dnrj = cwpt + npzj
twnf = 2
rjmb = 17
rnzf = 5
wngb = qdlf + fgfj
vdsf = qzfd + rdhb
vvmt = dstv * ftjz
fncq = 10
zrjc = jnmb + sjvh
qgms = 3
pfzw = 3
bmcs = 2
dvlb = 2
wcvs = cdvf * wrwg
fbcc = 4
nfnw = 3
sjbm = wzsw + pplh
mwpd = gfcm * trbf
srvr = 2
fpcg = 2
gfvh = qhsv * pphc
hfcw = 2
lqcc = 5
jnpm = 2
tdtd = psps * jjlv
htfw = 2
gjrf = fqwr - qdvq
bpsl = 5
nnsn = 2
zmwr = 3
rppc = 5
gvcv = fvwt `div` cnbl
qdjh = 7
gbwc = frbv + mhht
fvln = 2
vgbv = 11
zcpv = 2
vndb = dsbj + wmnn
vqsq = 5
jvgj = 2
lttg = 8
whlg = 11
fmbw = rgfl + rhzd
cjlc = 4
wsgc = 5
fgvt = fcgs + spwz
bpss = 7
fdqj = 4
wmzn = 5
mcgc = 1
rnmw = cqct + crnl
rdsh = 9
qhgd = wdjl + tsws
btmc = 4
djdw = clhj * tddg
vmmb = 6
msml = 3
gztn = rzjl + dvht
gczs = mrtl * ncch
hdtp = ncfh * rtgw
jhww = 2
wsdd = 2
cwjb = vfjv + spmd
ljgh = zjcr * fnbj
pmbv = 10
wmvz = vmdq + sgqv
mwsg = 13
rbsw = 5
dzfm = 3
mnjh = 2
jhbp = hslp * lzpd
qpvg = cspw * fgmf
hwmv = 5
hcvv = jbbg * wsdf
stjr = fmng * tbzv
vqmd = wsjb * rdrc
tgjw = 2
ncjg = lqcc + wfhg
lpsh = 5
psgw = 7
hpdw = 3
vqzl = 3
srtg = cnjm + tdqs
pswj = chws * zmwr
snrr = 5
lhrt = 11
tscd = 3
gzjs = 2
tptc = 3
zcmj = 3
cvmv = 8
hsln = 4
pjwr = 3
lfvh = 2
rbbf = stcr `div` smgw
lzbl = bsqw * trct
hdtj = 15
hnjz = vpts + bpss
vwdn = 2
wwcz = 16
mhwv = 2
jffs = 5
main = print root
| null | https://raw.githubusercontent.com/mrphlip/aoc/d7e3717370229ed0a7584bcf657fb3b72c33631c/2022/21a.hs | haskell | root :: Integer
jntc = tzrz * jmgz
chsl = rbmj + chpp
tmjp = rlbw + prhj
rllz = wrgr * jplq
bttz = hslv + jsph
pbcg = frwf - vzrg
gfhs = 4
sglc = 8
rqmt = 2
fltv = 2
zggp = thct * ddvm
cqdj = 8
mslt = gsnz + blhq
mrqj = vzvz * sdnf
bqfd = jtlf - hmfq
pgsr = 2
bgmj = vhqn + nnrs
qjgh = 2
vbwn = 2
dftr = 2
rphr = tnjt + vwds
wjqp = 3
jqvb = 11
djcv = rtzp + ltmf
pzfg = frcg + gwdc
sbvb = zqvr `div` qbtm
fhwn = tbjd + szcc
wdrt = 3
hplr = gtwd * jbss
svgc = lddn + czqc
cmjg = 5
mmvj = jlbq * zdcv
fpmz = gzjs * lwdn
dvht = 5
cffj = hddd + qjrz
qcvt = rlhd * ljqt
swqg = bvnb * wrsz
sbmb = 7
zmph = 3
vjcd = qplm + fvsm
ggwg = pdfh * pjtb
mvnq = 2
zjgh = hqpr + bbgs
cwzv = wfzn * dwtq
wswt = 17
hslp = 2
msct = chtt * tcvm
frwt = jnts * qpsz
hnvf = pbwq + bhzw
znsz = 2
wfbs = 5
dgwc = 13
gcwt = 3
crhj = pznp * vcvv
pqzd = jjsc * gjnr
qfjf = 5
tbjd = 6
lglj = ghnb * jdzl
cwfj = 9
lvqr = nlgh + nqfp
szfs = dwdn - mcjd
tgjh = 4
vccz = dgcb + pqbm
nmvr = wwvn * rsdv
tblc = 5
bqdv = 9
nsft = 3
qgvr = bpzw * mgvr
jswp = 3
qmbr = 5
zdcv = tlnj + qsff
qbns = tprb `div` qvzt
lftn = fmbw * jzjp
zngc = 4
vqzd = hjmb `div` dspt
bvdt = 3
cpqr = 2
clhj = 5
jnnp = 2
mjhm = 16
zzrp = qcrs + gtbj
tgjj = rcsj * mwmr
rfqb = ncnl + dwgd
zhcb = gsng + gnhq
bbsr = 3
dpfm = 1
mrmp = sgvw * cmdh
gbwd = 18
zhcs = 3
hnrz = 2
wwvn = 3
hbth = dcwg + fjrb
bsqw = bqfd + sncr
qzpl = fqrd * gqlh
chtt = 10
dtqz = 4
sjhh = 17
whhm = 4
plqr = 1
nbmb = bvtc - ngwv
zgcs = 2
jzjp = 2
jbfs = 11
cchn = dpgb + ptjg
wgvf = slhc + gmnw
dvrf = 2
bhjn = 2
vrms = tczg * rhlg
plcs = 4
gjcs = 7
wdfz = slwr + nqlt
djfv = ncjg + dbmw
gfbs = fsrz * cqgh
hfwt = 2
tcpv = jgjb + vwcm
bmjq = cpwb + nmvw
nrwh = 4
fqrd = 6
dwjj = 4
pjwh = lghd `div` cftw
brwh = sbzv * cmjg
vpts = zqnn + hflj
vqds = vgsm + pmnv
znlq = bqgv + dhzl
fcls = bvbj `div` qpfh
rhvf = 19
nqnw = 3
mlfm = 4
gzjq = 2
zfln = pwqd * sbmd
qqst = jfhc * qcvt
zprj = 3
rvmz = ntdt + zhjb
lqdh = cgrj + lfls
lnbf = rtfj * ghlw
mwdb = 9
rclm = 12
qpsz = 14
qthm = rrmz * tfhq
fmbt = twzz * wchd
fvpj = plgp * nmtc
qfjl = 7
vcwg = smsr * dmdl
pttw = 8
hwqm = znmm + mhwn
crnl = tdvz * fqtj
fzwp = 5
swfd = tscb * hdgq
nlgh = cgdh - vdch
dbfp = 12
pzbr = qrzt * shjp
gmbz = chqv * lhwn
dmjp = 2
cjcl = 4
ljbm = 2
tjhg = svdh * svcm
wztf = 5
vpmw = thmn + mtvl
nfqr = 3
cdzs = pntb + ncbg
mhtc = 3
prrj = jvvr `div` mpzh
nbqf = rtvl * lqdh
bnvv = qdgh + tght
nqdj = 4
jmgn = 2
gbpb = dnch * cnjf
rgth = hmdh + vchv
lmvn = 13
lslm = 4
ltzd = sgwp * cmng
fsrz = 2
zvgp = fwhj * pzgj
lvhs = 5
ctvm = lfvt * vmmb
djvv = lzjn * rclm
tgbp = vhgv + hjch
sjwz = 3
qcpj = 4
mmgz = 3
qglw = 3
vlgr = 2
vcgp = hhsq + jhzd
zhzd = 2
tmpn = 2
hdcz = wjhs * bbgl
tshl = jncw - hsdj
chps = 4
thwz = 9
lbzf = nfgg - bmcs
ffmm = zhjp * rbvs
wpql = htrh `div` zggd
mrmf = 19
wnwl = jdph * fwdq
fhfq = pgqt + fbcc
tscb = 3
jnwm = 10
fjhr = nftz * brss
nsgc = 3
dplt = 7
wstd = ltgp + rnrf
hztd = 5
vnjz = brnn * bcwv
spbn = wnjz * wnql
jhvq = 13
zvsq = 5
hjlp = 2
bslw = 1
gzzf = qwzc * wfbs
jqqv = 2
flnz = gpfs + fnnp
rtcg = dbfd `div` pfsm
gsnz = wfts + mbnv
nlnn = 3
jvpc = fcbt + rphr
bdvw = jtzh * tdmd
lzqm = 6
jtzh = 2
tlhl = 3
hlpt = wvfm * ssls
mfbr = tgbp * tdtb
wsjg = qvww + qllf
wsdf = 15
rtgw = 11
fwdq = 2
jdph = mqbs * ctzc
mrtl = 2
hfnd = srzl * fbcb
rgrh = 7
nltl = 11
pgns = zffq * pbbd
mcpb = 9
jmtj = 17
vhfz = 8
jqmf = 7
frbg = 20
qqrz = 2
trmp = 18
rhng = tdmm * phjw
jmll = 12
vqjv = 3
tdmd = zvff + zggr
plvh = 16
lgfr = 3
gncb = 2
gvmf = 3
rlbw = 2
hjch = bwwq * fdsm
nlzl = hfnd * hlrh
tfrj = 20
rnrf = mrgm * vwhf
nvmm = 1
wgmz = rhcp `div` rlmn
hpbq = 3
qjfp = 3
pjqj = 10
dwwh = 2
qpmt = ssjf * bmrj
jmqm = hmlj + tfcl
gzsw = 2
wmgn = 4
dstw = ptbp + qnrd
vznm = qvvs * nsft
pczb = cdfz * ghbn
bzdz = lslm + jsdw
hlhg = jmll + mhrz
fgdw = wtsj * fpbt
jbbg = 3
hfbj = 7
rzqq = wbgw * tzdd
lhwn = 4
pndj = 5
szws = 4
frwf = jcjg + jsnv
pjfc = rtcq `div` zfdr
jrqq = zvsm + qzhz
sdfq = 3
nvmn = znlq * ssql
qzhf = 6
hrrn = 20
fgjt = 11
zhlq = 4
nfgg = dnfh - psls
pnrq = fbzq + lbqm
spqg = 3
blgg = 13
tswl = mvmn * sqbn
qsmp = 2
dtdb = 3
jmjp = 3
sprd = 2
zgmr = 3
mwpb = pqsg + ppsm
sjld = 2
mvhz = nslp `div` wmgn
ddsm = 2
rqnr = rlfb + nrwh
rsnc = spth - hqfs
dwgj = 2
tcdj = bttz * fmnh
vpbh = lhjn `div` gmcq
npqv = dmqt * dstn
qmwm = jsnt + jvzj
pvtq = 9
pvhz = tstp * ltdn
thmn = 9
chpc = mqws * rppc
dwdn = ndgs * nlnn
zzpb = bvqg + pjjh
hpfn = 5
dfqh = fpvz - hgtm
wnbm = 2
czjp = 3
jcsg = 2
dvjh = rzqq + cpvv
wdnd = sbvw * hlrj
lgvh = 4
lpbr = mbww + qsmp
mgvn = ppgd + djvv
jjlt = 20
tzrz = 3
cqct = hbqd `div` dfcj
qzsq = 6
dqvj = rfnc + wqzg
hvfp = hndj + cndw
sgqv = 19
svdh = 2
crhl = cfsr `div` lwhh
pwgm = 9
pgmw = 7
ccvc = qmrn + twjr
svsl = bmws + qjqp
jzqs = 2
rbmj = 13
sgwp = 9
tlbm = fvln * jjbr
vcwc = mrbm + rvgm
npzj = nbmb `div` cmrn
fvzd = mfjt + gtgn
fjbh = 2
htrh = cjlc * gjrf
hlfv = zszm * pzsz
pcvb = 2
hdbc = zwbs - rndg
qjdc = tmjp * pmsh
rtfb = jppl `div` qpft
bdln = 2
qqzj = vrms * nvhp
lbrd = 5
chlh = vsgd + gqgq
rlpp = mnmv + wtwr
zdzr = jnwm + cndn
sgqc = 3
hdgq = 3
dsms = jmtj * svqr
rlcp = gjcs + lnmr
szll = 2
bhjg = 3
nllp = 7
ptjg = mlfm * ptbv
jfhc = 2
qsff = 4
gcsg = 2
jgpp = rgsh + crjw
qghb = rqjn `div` bnnv
glwr = zphr * tnzz
vvmr = 2
dgcb = mpqs + snbz
bsng = sjwz + rzzm
pbcq = wgrl + ccvc
czwl = djjt + wspf
bslv = jlff + nvzz
pznp = 2
dtnv = cpgw - gpvb
sdqw = 5
gcnq = 2
tpnh = 2
zmnq = qglt `div` tgjw
vwnz = 5
cmms = jgpp + rdnh
vzwn = 2
hqpr = 12
qjqp = hqsp * hwrg
dgtj = wdzt * zcnc
nwfw = 5
hghn = 5
qlfm = 3
lgtd = mcgl `div` vdnj
vnct = 2
rqjn = jnjd + hdwc
bpql = wgvf + pmpc
bgrc = cglv - lmmt
ljrp = 1
tvsj = 9
frzb = 2
ngnc = 1
hhsq = 2
qwcb = 6
ljcf = 19
wrgm = 5
zwbs = gvjr * gztn
bhsl = 6
brpr = 2
hfrs = 5
wdmd = 2
vsvn = 2
zhmz = sfld + rhng
ddvm = spnl * mwdg
vmlh = cwzs + wnwl
cwzs = 4
gwfg = 4
snhj = gfjq + jqmf
cwmv = 5
ppvp = rtwl * wqvr
bqdt = bcmg + lpsh
qpft = 3
bcwv = mhfj + mdpd
jplq = wvld * sprd
mwmr = 3
nvsg = slfg + pmbv
tgvp = 3
fpvz = thfp * fdbs
dcgh = 4
bjpc = 1
jtnt = 2
qfdm = 4
tdlw = vbqg * tzsf
qtnh = mrmp + blrg
scft = 16
bqqb = nvgh * npdt
hcwr = 6
czbb = 4
fnld = 3
qvrr = 5
pbpg = 18
qmrh = 2
rrcw = 14
mcjq = 14
pzcm = 3
jlbq = 3
pslb = 3
dqwp = jwjh - drrw
cndg = 5
dnfh = tmdj + wpfl
ddgd = gfbs + tfdn
jvqz = nltz `div` dwgj
szvm = 10
rlfb = 3
llhs = scnp + fssf
brrr = dvgl + szvm
gcct = brbw + hthd
vvqj = tzwh + rzsq
jfgq = 2
mbqg = ctvq `div` gvvm
wrrt = tbnv * gwdn
rvvm = 2
sgpt = mstv + jpsd
qnrd = fwsj + qthm
tzpq = wssc * shsm
cqhn = 13
zjcd = qzvg * wmhn
wqbc = 2
fbcb = 3
vfqs = wdjm + nrvj
bjgz = 3
hrld = lfcm * fqlj
gtsh = qvvc * qpmt
wqrr = nljh * nlgn
sfld = 1
jmmm = bslv `div` plcs
zbgv = 3
bhbs = mqvp + qnhz
bwcr = ghvc `div` bnwn
jhmn = sctd * zhgp
cgbp = hdgc + pzfg
rbvs = 3
rdrc = 3
zqjw = 2
jsvm = 7
dtlr = 3
vwds = cfqw * hcfh
grhw = zdzr + jtbs
pnlt = lvqr * tthc
swph = tzpq - hfjh
qrrg = 3
dcfv = czgw * jbfs
pwdl = pnwr * wfct
fzzh = jgrw + rnbg
wrsz = clsz * zjtg
jnwl = 4
tsfg = 9
cgng = scft + cztp
dhzl = 5
rfnc = lrdn + cpqt
hmtm = 1
frgj = tzrv + grbs
sglr = 17
ndqw = 3
pntb = cgng + gblv
zhgp = mmgz + qgll
wblj = ndfv - crwz
rzrz = hjpb * cfnc
zgct = 8
trll = 4
lbcr = wwrz + szmc
pdvm = bhhj + zjtj
gbcd = 5
wndj = 2
gwcr = 16
rqlc = 2
mrhc = 3
wqzg = tdfl + rwmm
bhgc = zrcb * tfjw
tsws = plfh * dgss
hlsp = 3
rstd = 16
pzsz = nzgp * qjcw
pvlj = tpjf + fjzt
wndn = bszj * znsz
bngj = vrns * zbgv
wsqw = bhsr * tscd
mtvl = svrs + lzss
dpll = 6
qvgj = grwn `div` gzpq
tnrj = lcbc * qrrg
tvjr = 5
bjjz = 16
gmsn = jzcn + cnvt
thtw = frvh - bslw
zjwg = 5
tmhb = mzdb + hmss
ttpb = qwgp `div` vjsr
vsgd = 6
phwp = mglb + chpc
tzmv = 18
zmlh = mwfq `div` nzjl
rjvg = 5
lwdn = 7
tdvz = zgzb * fszw
hddd = 5
jwsw = rdml * chwp
wwrn = 2
hjzz = 7
dfhb = gbpb * qwdp
qvgl = jcsp * rjpn
wtrb = dmrb + pbcg
ncpt = 19
zhjb = 6
nqlt = 5
djrw = pqdm + gqzj
vncc = lnbf + dnqq
dgpg = tgjh * csqr
fstz = vqjs `div` hdff
hrsd = 9
vwzs = qcsr * nnlr
mdbm = zgmc * tshn
rqqj = spnf + ptln
clzt = 2
glzm = 3
twbs = vgsp * dcfv
hhgj = 2
zvsm = 7
zsnz = vjzg + rlrf
ggwz = qfgs * hwdr
wfgq = hlfv + tfst
rfhb = vhcg * zjvg
llhq = dpbg * zhcb
tdnw = qwlz * rtfb
llcq = 3
gtbj = pfbd * thwz
bjcg = lfvh + cqdj
dttv = 12
dsbb = crhl * pgsr
clhw = phtz * cfrb
tfrh = 2
wdjm = tqrg * mrct
dgbs = 5
rgzs = hhzt * bsdf
ldhd = 2
sznh = blbj + tdbt
fgmf = 14
svrs = ndrr - dzdb
zwcl = zqdm + ggcj
chtr = lvdm * thss
hqpj = 8
nglb = ldnq * jfqj
fvjr = nqdm * wcnf
ffls = 6
mfjl = pths * zzpb
rdhb = dvbp + pttw
zpgb = zdzd + swrj
zbfh = btpw * pptr
pgqt = hvrb * pnvz
dggw = jfjv `div` zzzt
dtbh = qjlz + hcnw
nllc = mrdp + wmwg
jsnt = svdf + vnjr
rbzr = 1
lbdp = 3
dwtq = wmpf * gcwt
wgjr = qvnw + hwqm
brnn = 2
jszd = 7
hcgd = tfjd * vqds
pgvl = 17
vbzv = 2
zsvw = 3
jncw = jswp * grqb
qzjd = nwsw * wsgc
bszj = vpcn - npjb
lwcp = ddsm * dlww
ctvq = tswl * jvwq
vdnj = 5
gsng = 6
zsmq = 4
tpjf = 1
zmbf = 3
tfqd = vwll * bhsl
gvpp = zqjw * lrgl
dnpw = 3
bfjc = 5
vshd = 2
rngb = sbbs * hfcw
chpp = rbsw * chsn
vmnp = 11
zwbj = 4
wvvp = zzrp * jsmg
vssm = glsf + tjsp
pvzn = qzjb * gncr
nnrs = grnh + rlcp
jwbl = dtpp + wngb
jsps = 2
qncp = 5
mtpd = 20
vmdq = 4
qbww = 5
rrwf = 4
zrcb = hmwp * tsbc
wdjl = zdzt * rdlb
cpvv = 2
mpdc = pnlt - svvz
psbc = 5
fscs = dgnt + htrt
cmsh = tnrj + gjpg
sjsw = fqlv - hrnj
svdf = 9
ngwv = qtlj + lwqq
svcm = 4
hfng = mrhc * qscw
sdsg = nmft * bvdt
lnld = 3
tshn = 14
fqbm = fgvt + lzvb
wrsc = rtcg * ndqw
hhzt = 5
lmjt = 3
sdcf = lzqw * gzzf
tptf = 9
qllf = hhdr * hgrc
hsll = dzfm + tvcn
jqjq = nmlg * gnhd
zgch = ggwz + dstc
qhtp = gbwc * pdhv
gfjq = nhlc * jhwm
sjdj = cwls * wtwj
thss = qfjf + mnwl
mcvc = fbsn + psgw
qzbv = mnsw + wzgz
bdvl = wswr * tblc
wfmj = tqgq - pwbn
tsgh = cmbj * sdcf
nrll = 9
wdnm = vqzd - hnjz
zcnc = vfdm + mwdb
zjcr = qncp * qlqd
pvzc = chmm + tlbm
cqvh = nrzd * ztcr
wrvt = pzbr * dggw
gtvf = vmsh + tvtn
vdmw = mzjw * tvtl
dbfd = cgdr * vhmz
mrbm = gvzz + vdsf
dzzn = vttd + zdhj
lflz = mvnq * bgqp
rlcd = 1
cmrn = 2
tjgd = mfjl + zjcd
bqsd = phwp * zwfn
nmlg = 6
mhll = 2
qwgm = sgcb * bwtw
vbrn = sjrz `div` wjqp
fsdh = dqvj + lsvv
whdh = 4
gjnr = znrj + dptn
nvgm = lgws * dndp
mstv = fqrf * gsct
ztgm = gpnm - jjrt
stzj = 4
msds = 5
mgnz = 1
ctqv = vbmr * tfzv
ghzz = dtpq `div` mnfq
hflj = ghqg + ctcj
jnts = rgjg + qbww
flgb = qlfm * grcw
slgn = 4
ljrg = 3
dgwq = jrrs + zccc
pplh = 7
tdfl = 3
bmbb = fbsv * srhj
lsvv = bgmj * hcwr
jfqj = 2
tfcl = tptb * bgcs
lwqq = gqlm * vlrd
szww = 2
szzs = 4
fqtj = 19
pfsj = 6
fhfh = vdvv + gzrq
hmrt = smqq + wndn
rnqz = fzvn * mclw
gczf = rnqd + hfbj
bcgd = gnpd + spgd
sgcl = psjc `div` jsps
tdbs = hcgd - fvhw
tpgv = tdjg * gsfd
mmll = dtpf + szll
qzvg = 13
rpjq = 5
zcbc = gwcr + gmsn
lrsg = 3
qvnw = 5
tlrb = tbpl + dgwc
ppsm = 7
ldpv = jrgj + dgfq
tmdj = vbwn + rlgc
dmgd = cbln + rgws
sbbs = 13
hjgm = hjvl * hwbs
lmlz = ddll * zgjv
gwhp = 4
sbdl = 2
cgrj = 2
bwgv = 5
fmjs = 3
czgw = 3
gpms = pshm + cbwl
wlbz = 7
ldhz = 4
rlhm = 5
ncpb = 3
wpgl = gwhp + btsv
nqzc = 2
hjwf = 6
jvvr = tcpq + gvcv
fvsm = 4
dglb = nllp * srqm
ptln = whhm * wztf
hnzv = lrbv + grtv
njvp = 14
ncbg = 9
vzrg = 2
ncfh = 3
wgjm = 2
cgvc = 4
fjnd = bjgz * qljh
jmzj = hsln * dsnc
grtv = 1
fbdz = ffsm - wbwr
lsvw = 2
gcqf = 6
pdjr = lhrt * mjsw
zrjf = 1
jsvj = dqcb * cclg
hlrj = 2
wrwg = hhcl * pfsd
vsgs = 3
svqt = jdfh * wbnc
qqzb = hhqq * zrlt
vfqc = 4
pjtb = 2
mrhj = 7
gtnj = 6
hwrg = 2
fgsv = dvbw `div` pzrc
wwrz = vdmq + mbqg
jrrs = 4
rdvf = jcjv + mgnz
jlzd = 2
mglp = jctm + fvpj
pnpb = 1
wpvw = 3
zqvr = ssnn * dwwh
gtlb = mwcq + qdbb
bvnb = 5
dtjd = 2
mtzm = bhzj * cpbj
hcnw = 5
nrqn = 4
mlgm = llnj + vgwz
rzwn = 2
rzsq = 4
chqv = vwss * lfgr
vgsp = 2
vhls = zsnz + dlnm
clcp = 4
dtpf = 7
fzjv = wssd * zmph
lppg = 10
njjr = sbvb * lpjg
pqlj = 5
mglb = cpqr * gpbv
jdbd = hcgc + trmp
blrg = msrz `div` mlrn
rglm = 5
hstd = 4
pmsp = hgnm * nbpt
wtsj = 4
cfrb = 2
zmrd = pvzc * qncm
dlpj = 2
tqqd = 3
hrns = zpzw * fjnd
pstz = sfcs + pzcm
qglt = sgss * gcjt
jqnr = 7
nnlr = 7
zhbs = njtn + wgvm
ncch = fjrq - bjpc
bfcn = 2
ctcj = 7
rsdv = nrjw * mddj
dclb = rcfh - gfhs
hwgr = tghw + phwc
dbwl = 2
nvzz = 11
ntdt = vwzs + bbtf
rccr = 2
qdgh = 14
ndqc = qzgt + zmlh
bmbq = hhsh * wdff
ccwq = lvrd `div` hnrz
ngls = 8
qhgz = 4
zqnn = 1
phgr = 5
tfhq = wqbc * tpcl
qcmj = jbjg + hqpj
jcdp = mfrs `div` wgjm
swsg = mmrl * qcmj
prhj = 5
bcmg = wwrn * hbvq
dcws = 1
zvzp = 3
thwc = vwnz * cmgz
chbw = cndg + sjbm
lnrf = 2
fnnp = tlrb * tlhl
srdg = 2
spth = smzl * jbtv
hwwc = 7
frnb = 3
ggcj = lcgp - gglg
dbhh = 2
fznq = 5
dmtq = 8
gsps = 8
chtp = 5
tffb = 2
lztp = wqgv * tpnh
pghs = wtrb - fwmj
tcpq = gljb `div` sqcs
zzmz = vlgr * grjn
pvdq = bhqz `div` zpll
hwbs = pqht + hdvs
nzvd = zpbq + dzlz
dstv = 13
chts = dtdl + vpnq
wpwm = 11
mmrl = 9
qqbp = cwzv * dnrj
mslj = djfr + jszd
lbzl = 9
rdlb = 3
fbsv = fpgn + mdbm
jpsd = gpvj * lptn
wzmw = 5
zszm = 7
gtwd = 2
tvtd = jmmm + rfgd
wmpf = 2
tgnb = svqt + wpql
bhzj = cvmv * wgjr
bnlh = qgvr + qrhq
zpbq = 18
qwqr = pvhz + trzt
blgc = 2
jcfh = 2
pvnj = 4
humn = 855
wvld = 19
grgv = qzpl - dbtg
btpw = 10
bwtw = 9
nthg = 2
mddj = 3
gfvj = 3
bpzw = czmp * rqgt
cpwb = 3
nlgn = 2
wntz = bhrv `div` mwvc
tlwj = 3
hlrh = 3
zsdj = qfjl * rrns
lwcm = 3
plfh = 3
nslp = trfg - hghn
vcqq = 5
cqwv = 5
plzr = spwq + tjhg
nqfp = 6
dwqv = 8
tgzm = dcgh * znpr
gtqv = qdps + nltl
rgjg = 2
qqpn = 6
wzct = vfbw + gpzw
gdjm = 2
wgfc = 7
flmd = 5
qrzt = 13
fthr = 4
chlt = jhbp + bnnl
lhdb = 2
qplg = drcm + lrtm
rlhd = 5
rlmn = 2
ptww = vndb + mrqj
qjqb = 11
zjvg = fnlz * zcbc
qrrp = 2
dhtd = 7
zgmc = vgnm + ngvh
jpcs = 3
hbvq = 4
fvct = 13
hhtw = 2
wfct = fjln `div` fjbh
gvjq = 8
bhrv = vgbv * bhcb
rtwl = 2
vhcg = 2
qhsv = rccr * hgvt
rtgj = 16
brpn = jjlt - nfgb
bbgs = 1
ddsq = 3
brhn = whlq + sznh
bjvm = 2
tdtc = 4
zhpz = 2
spwz = rjrt * jqvb
mfgp = 2
mhwn = 3
jhzd = 5
mjvp = 4
gbhw = rfqd * rhhm
cqmn = vfvr + bqfc
rszz = dgvf * ljbm
wgvm = zpgb * bnvv
psps = 5
jjvv = 2
bpdj = 2
jvzj = 6
vmsh = bdht `div` ldhd
zjvz = whgd + gbcd
fpbt = hgmb + djdw
fghp = 2
znpr = 6
nlmw = 2
pnsw = pwbb * qcht
hrnj = 3
gpvj = dcvt * mpvr
fjhf = nnsn * jngw
sltv = 2
dqvw = mjnp + rfnr
llnj = bnwz + lbhv
tptb = 11
ntqg = nqzc * lssg
trfg = zsft * wlbz
swrj = gnzp * qwqr
wvfn = wwcz - mcjn
dwgt = 2
ltmf = 14
tdmn = 13
qscw = 3
fjbm = 5
tdbt = jchd + rtgj
dvbw = rdtf * zccb
tnlb = 11
rcsj = 2
pmpc = fzjf `div` hfrs
fdsm = 12
vghh = lrpj * nglh
pmtd = 3
jchd = cnqq `div` gtvq
wsvf = 2
svsm = zgct * fqgc
cwpt = fbsj * wfgq
hvrb = 5
gzrq = 3
tfgg = rpgm `div` sgvf
plhm = ncgv * dbhh
tbnv = 3
cpgw = wgbc * tmhb
tgpq = 5
shdb = 2
zcsn = 12
lhsn = 3
zgjv = nzdm + ncrp
lcgp = jhgl * rgth
cbwl = zjgh * lbrd
zjbz = 5
trbf = 19
tczs = czqd - twqq
thpm = 17
fbsj = tgjj + fqcm
clpg = 16
czrv = bpvp + fhfh
qnzv = nfpp + jqjp
wrgr = 2
tjqq = vpmw * gbgf
mjfs = tvsn * vfqc
zwfn = 2
wmzb = 10
nltz = gwfg * lcgq
pfrm = 2
qhfv = dzgg * nmhg
cbbf = 3
bvqg = hpws + cqmr
tgzr = swbz * tjbc
hhcl = 13
mftw = 3
zcgn = jfjl * msms
srsj = stds + fvpw
lmdr = msml + mbgw
vdch = 1
brss = sjsw * lbjm
ptbv = 4
zhjp = mtnl + cwcb
hsdj = cwfj * vznm
dfpv = 2
qjlz = 1
gglg = 12
rnwr = mgmh * tgnb
hgpj = tbfn * tgtq
hmdh = 7
qjrz = sptw * dqvl
rjds = 4
qbsd = ddsq * fbvr
jjqv = vpbb * qccg
hmvm = hjtj `div` mdpc
gljb = znqs `div` qgms
vpbb = dzzl + cpbb
lbgs = 2
gwdn = 7
pbsc = fbqr + zhwq
vfvr = rhdz + trrq
tlfn = 2
blbj = tjqq + jmnf
mcgl = zrbs + rlhm
dmqj = qbmq `div` hjwf
bqgv = dvlb * whtz
cpbb = drfw + dmqj
szwg = 10
smhb = 4
jbtv = 15
lzvb = 12
wwwq = bmgw * lzbl
qlqd = wvfn + zbbp
pptr = 2
wnfq = 16
wdff = 17
hcpg = 1
vgvw = 11
rzgg = fvbn * vccz
qzpg = lwfh + lrtr
znrs = 9
jnpc = blgg + gbwd
lnlg = vmnp * vcqd
jcjg = hpdw * qjqb
vdvv = sbmb * srvr
gfcm = 5
rzdv = 2
spzn = gcqf * hnbp
sbgb = ggsq + lfjf
gsfd = 2
zgbg = 4
bhcj = nshq + lmvn
drrw = 4
hcjt = 2
pzrc = 2
jfjl = 2
pctc = 6
gggr = twgp * wpwm
wtpb = 14
gncr = 2
lbnh = mctq + nlsn
hwsh = 4
pmqv = 4
ppbd = jfqr + lzqm
cdvf = twbs `div` hjlp
nlsn = qmgp * plvh
jjlv = fmjs + bvpb
lmmt = qwcb + hbmw
hdwc = 13
mqws = wmzn * sfzc
mjsw = 12
pfjj = 2
hngm = qzhf * jfgm
mdpd = jvdc * nrnb
jswq = 5
bgcs = 3
pjjh = mdbh * ctqq
vncq = 4
jjpq = 5
qbmq = grsz * hplr
dzrj = cwnd + hcct
clbs = dtbh * cbbf
wgml = tcpv * hrpq
mmjj = mnjh * fzqt
ffhb = 12
pwbn = pbsc + rmdr
btsv = 9
gnwj = 2
zmnl = 6
hmwp = 2
rdnh = qbjw + lwcp
vnjv = mspc * sltv
vngt = nglb `div` rbtf
vccc = 2
trrq = ghtz + nqdj
clsz = 2
cwgq = msjt - ddgc
jlff = ffmz * ccfw
rbtf = 2
jvbv = 8
rtpm = sbdl + fvzv
slwr = zzjt * fhwn
pjfb = 3
pqht = 17
gjpg = zcpv * dvjq
jgjb = qrdv - njqt
lfcm = mzmh + hmtm
qcwp = 3
lzwq = 3
gqgq = 1
mclw = vbgd + zvgp
zrht = dtcd * swqt
ffmz = 15
jttv = 3
cmbj = srsj + bqsd
zrlt = 7
rvqv = 3
smzl = 3
znts = 2
tnpc = 15
rsff = 5
sdhh = chlt + jvbv
cglv = qdtw * zwbg
ppgd = tnpc + djfv
ddgr = 4
slhp = wmzb + vshl
tqdh = 18
npjb = 6
gvjr = 7
qwdp = tsvg `div` nlwp
bvpb = 4
qbtm = 2
rgws = 5
vqjs = lnpq * llhq
tdjg = blnq + wfmj
hlwf = ppvp + dqsf
rtvl = mbgp - qqbl
pqzg = 5
wfts = bzdz * dzww
rlpt = 5
rhdz = bmlw + gfvh
drtq = 3
sjcc = stjr - jcwl
tcvm = nbpm * swph
wtwr = 4
hvjz = 2
pcff = rgpp * vgwj
whpl = slgn * mbnm
nnbl = 5
znsw = 4
hmss = fbgc + ltzd
dpbg = 2
fjrb = 16
czqc = nzvd * bpsl
smqm = fcsb `div` hwwc
zrbs = gvmf * bwmq
wbnc = 5
zccc = 3
rgsh = 5
fszm = 3
sptw = 2
mspc = bngj + hsgg
wnjz = 5
dhpc = 4
tpdw = fnld * rvmz
grjb = blpq + ghgs
lddn = mftw * sglc
nftz = 2
gzqc = jvzg * cltm
qrdv = qfdm + rhjj
lpvw = hghh + pvdq
tzqb = 11
zghq = bhjg * ghrv
hnvc = 9
npbf = 15
rtzp = vstr + qrhd
chwp = mlth + pfpp
drfw = vbpc * brpn
wfzn = 2
jmnt = 2
lfls = 5
mppr = dgpg + wrrt
pbwq = 1
ssql = 2
wswr = prrj - pcff
dqzd = 13
jjbt = vlln * mrhj
wdww = nvmn * cqmn
jsnv = mtpd * lsvw
bcbc = ngnc + mpfr
vqfn = 10
jqjp = ptww * vhfz
nrzd = 4
zqgc = 9
sgjc = jzqs * dtlr
phrs = dsbb - jpcs
mhql = wdrt * ljcf
gmrn = whpl * gblj
tppg = tdnw * rjjl
zfdr = 2
jtdq = 5
qplm = dplt + thtw
blpq = brhn * hvjz
lwfh = lgtd * tvsj
wmhv = ppjl * srtg
zssb = tzfp + lztp
cpdc = gtwn * wbdm
srnh = mpdc + cmdp
cmdh = 2
fwnc = 3
vjsr = 2
ngvh = 3
dtpq = cffj * sjld
jvtz = 3
zdbd = ndqc * mfgp
vwcm = zhfb + chtr
sdms = 3
slhc = hmrt * sdqw
dvbp = 11
tmrs = 2
swbz = jttv * hvfp
mbcf = flwn * tpjw
hjpb = 3
vrns = wsdd + mhql
mbgw = hjzz + zcsn
lfjd = bbcm - mrcb
cftw = 5
sgrm = jnpm * wrdw
dtcd = dmmd * zprj
lmjv = swqg + qdgt
gtgn = 1
mbnv = 9
ccfw = pfjj + wzmw
tptj = brwh + stzj
wqgv = mdmr * ltbp
rgfl = rszz + dngf
nbpt = 2
ntpg = 2
gnhq = 1
crmt = zjwg * rgrh
jjhh = rltp * vnjv
bhqw = hztd * crmt
zqcz = 2
jnff = lvdh * dmsb
dspt = 3
nzdm = qndn * ltfs
mqbs = 6
vgbm = 7
jnjd = nvsg + gwwt
vsnt = zdls * hfwt
htqm = 3
qdns = hnvf * qtnh
mtft = 4
gblj = 4
nrjw = plts + snhf
dnpq = sgqc * rdvf
vlrd = pgtf + rvvm
ggrf = 3
ltbp = 5
nrdl = 5
gpzw = gczs + czrv
qwlz = lgvh + zllw
hnqg = fdqj * pghs
sgcb = 3
sncr = zhmz * cbcd
bgqp = 4
tstw = 4
vbgd = 10
mhht = 1
pqzw = vqsq + cfgv
nbgc = 2
hcfb = dpgq * cfjc
shrc = hlpt - swfd
gmhv = mzpd + wdww
qjcw = 2
gmnw = ljnd + fpcd
pths = 9
dqcb = plvd + njsb
qfjc = 5
qhbl = zmbf + qhtp
lshn = 5
bbgl = 3
jcjv = szws * gmqd
zdzd = 2
vctl = wstd * htfw
jctm = mppr * szjv
lzss = 2
qdlt = 9
srlw = hwmv + rlcd
jnmb = mtzm `div` gjsj
qcns = gqqb + lwvr
jlwb = fstz - mgvq
cpqt = gczf * lhfp
grnh = 3
lmgg = 17
sdwp = pmgh * dbfj
vjzg = 16
pphc = 3
grcw = 8
gjsj = 4
gfhp = ncpb + zsmq
fjln = jcdp * hpwf
vcsh = bfdc + fzwp
gpvb = fthr * vvqj
ftjz = rpjq * qmwb
nmhg = 2
sbmd = 4
cvds = pqlj + qbsj
mqvp = pqzg * zhdn
dvjq = vzqc - rnqz
qbhl = 2
fwmj = 5
rqwf = 11
jmgz = rgbj + hcvv
ssjf = htqm * wzjp
nlwp = 2
zgqh = 2
pfsd = 2
nmft = 2
rjpn = 7
tbzv = 5
tjcb = 4
jtcv = 1
thct = lbnh + sgpt
frcf = 4
nbpm = 3
zllw = 3
svqr = 5
gqlm = 4
mhfq = 6
qmgp = 2
hwbl = qbsd * hhgj
qljh = bfjc + qjgh
szfv = 2
tdts = 17
mzdb = vcwc * bsbw
pdfh = 7
qzgt = znts * plzr
szwc = wgml + nhdp
sclh = 2
tvcn = 8
rhcp = mvhz + fdfl
dqnm = 5
cgdh = trll + gggr
wpfl = 18
lzjn = 7
hdff = 2
mgvq = 4
nznz = 2
rzjl = 4
pfpp = 9
hjmb = srcv + wgpz
qfcg = dtnv `div` gzjq
gvvm = 6
dscl = zgll * qmwm
fhth = 4
wmzq = 3
rfgd = 7
cfjc = 3
fpcd = jlgf * sjhh
gzpq = 5
zdzt = 2
tzwh = jbgr * nsgc
tsbc = tsgh + tgzr
jjsc = 2
zpzw = 2
dtdl = dhpc + vsgs
dzzl = zrjc * vnct
rdml = 2
pbbd = zlvd + wndj
vspw = zmrd + wzsf
cmng = 3
tdqs = 1
tfdn = bvsf + wcvs
rltp = gvpp + vcwg
vbfb = zsvw * hbth
lfvt = nbbg * zvzp
hbmw = 12
dgfq = 4
rlnz = 2
jvzg = zcrd `div` wsvf
pqsg = qsrq * hjgm
nrnb = 8
znmm = 4
tthc = 2
bzjc = nrqn + qgrg
rjrt = 2
psls = jmnt * lcms
wzsw = 13
ctzc = 2
cbcd = 2
mctq = 5
brlp = zggp `div` tmrs
zhfb = tscr * dhgc
nvjl = tnls + cvds
rmfd = 8
sbhm = 2
plgp = nlzl + cgbp
spjr = ssnf + clcp
gcjt = 2
cvzw = 11
fqcm = 1
lfzb = tlfn * llhs
lrbv = zhbv + mwpb
qwjw = hdtj - bdln
qdlf = 3
crdh = 2
tsvg = qvgl * wtpb
pnvz = 11
qwzc = bnlh + wrvt
gnhd = hstd * tffb
mjnp = fdzn `div` sttm
ldmb = 2
lcgq = qbhl * sbvt
jrgj = 3
srgd = 13
rsgh = 3
srnb = 3
pgtf = 11
rjfc = 1
hgvt = 3
rzlg = qgcb + mfbs
fzjf = dzrj * rlpt
wgzh = fjhf + mbcf
zdls = twcp + wgzh
cdqj = wwth + hwsh
mbgp = ptgc * hnrp
mpzh = 2
fdzn = ttpb * jcsg
sdnr = jbvw + vrdd
lzqw = 5
cpbj = rhvf * ntpg
nvgh = 3
tjbc = rvpd * brlp
dvjc = 2
cqll = dvjh + zwcl
jwpr = chps * qbns
sblm = vcgp * nnbl
tljq = 2
jtbs = lrvq * nfqr
fnwq = sdhh * bbsr
pzmm = rzlg * sznr
hthd = zcmj * smqm
qpjn = tfgg - sssq
hbqd = vsnt + ffhv
fbvr = 3
ndfv = tfht * bcgd
rpgm = jtnt * qlwm
nglh = 3
lrtr = szfv * ffmm
jngw = rzdv * czwl
hhsh = 3
dbtg = njvg - wrgm
rrns = qmbr + vbzv
tght = 11
ghlw = 7
bqhh = 2
bvzf = frwt - hdcz
vnjr = 16
gqqb = 12
wnsn = ftqz * hsww
gvfh = bcgt * jwff
zhdn = tdtd `div` msds
ltgp = rfhb * dhwf
smgw = 2
zgzb = lwzc + gzsw
sttm = 2
hnrp = rtsg * jsvm
cnbl = 5
zrff = zlgg + fbdz
lwhh = fpmz `div` brpr
vfdm = 14
wsjb = dfwt + nlrt
smdv = lflz + pzmm
cztp = rjds * rbgh
rwgr = 12
tgtq = zbfh - zpmp
nfpp = wpbt + zthq
dsbj = zhcs * pmtd
jrph = rscz * pcvb
njsb = 5
hhdr = 4
wcnf = 7
vhqn = dpnc * dlpj
lwzc = 5
mdpc = 4
qncm = 4
jtrn = zrjf + fgsv
spmd = rnss + ncpt
gsct = 3
gnpd = zwsp `div` jffs
psnq = fqbm + dwtm
glpt = 2
rrbb = rzwn * szwg
dtpp = 4
fmng = fmbt + mwsg
dbfj = 4
jdww = svgc - hjbp
zqdm = crlj * wptm
fffz = wcht + grjw
tnpl = jnnp * qqpn
dztm = pvlj * tdtc
rhlg = hhtw * nvlf
qmwb = 6
npgr = ctpg - jqjq
gwfl = bhbs + qqrz
wmwg = gtnj * qrrp
lrvq = 3
pvpm = wwwm `div` glpt
ghtz = srnb * rgfp
wpcv = 2
lhwl = ttwb * wpvw
tjsp = vqmd + hvqp
tlnp = 2
vfbw = pvzn `div` hnbv
mnfq = 2
nwfd = 20
hmfq = 2
spwq = fpst * sgcl
nshq = 6
tpdt = 2
gqzj = 15
vwss = 6
gwbq = bbzz `div` ttzr
tnzz = 3
sctd = 2
fmrf = 7
qzfd = zhpz * fnwq
vhgv = lfzb `div` bdtl
dnph = 2
gtwn = fsdh + srnh
bvbj = bmbb * jrlv
tzfj = flgb + gtqv
smcr = 3
jrlv = 9
znjt = rnmw + bpql
zmhw = zgmr * dsdl
bhsr = 2
dbsw = 14
jhgl = 2
qsbp = 7
hgrc = 5
ljnd = gpms - lglj
hfth = nqnw * rblm
lrgv = vlmt * dwgt
wdzt = 2
blnq = mjfs * szww
tnjt = mgvn + mjhm
dnqq = 2
ldnq = lbdp + bjcg
ctbh = qlvw + lbzf
ssnf = cwfb * rqwf
ssls = 2
cnvt = gfdw + hrrn
vfjv = wnfq + rdsh
hpwf = 2
dmdl = 3
jbvw = dqvw * wrsc
zvdv = 2
fwsj = hcfm * grjb
tfjw = 2
fgfj = 6
pvrb = 8
qbsj = 6
smrh = bpjc + mcfz
mnmv = 3
wgbc = 2
nlrt = 10
qwgp = dfpv * dsdn
srqm = vqfn + dpfm
lbhv = snrr * zssb
crwz = flnz * fjbm
trct = 19
gtvq = 2
hwgb = wlcr * bhgc
nrvj = 8
qlfp = 3
mnff = vctl `div` dtjd
czqd = cqrb + vwdn
tddg = 10
sssq = 1
stcr = pqzd - fgdw
ghqg = cjrg * tgnh
frzm = pbzz + vghh
tqrg = 3
mcfz = fzzh `div` dtdt
gdlg = 2
rvfj = qcns * ptnt
twzz = 3
bbmm = 4
jgrw = bwcr - jnff
bcgt = 5
vgwj = 3
fvwt = wvvp - psnq
msrz = nbgc * dglb
dmhq = 9
gblv = 6
hcfh = tzqb * pvnj
phtz = bfrr `div` wnbm
drcm = pmsp * bqqb
cbln = 4
ggsq = 5
mvmn = 3
pzgj = 9
qrhq = nbqf * zgch
fggl = 2
cnjm = dclb `div` rhgt
swhn = sdsg * ldhz
rwtr = cwlb * qjfp
tfjd = pbcq * jwbl
sfnm = nmrn + nqdg
gqlh = 18
nzgp = 3
jqnc = mnff * drtq
vbpc = ntqg + tgpq
hdjv = 3
hnbv = 2
zsft = 7
fvhw = fhfq * grgv
dpgq = 4
pzph = hnvc * jpnz
mcjd = 4
fjrq = lhdb * ffmd
tdmm = 3
pfqj = 15
zgtf = 3
pmgh = wrhp + rjfc
zphr = 3
pwqd = ljgh + gmrn
lrtm = fffz + swsg
qrhd = 2
qlvw = mfwr + stbr
sjrz = ggrf * mglp
zzjt = 2
tzmg = zfln * vbrn
zbbp = 6
nhdp = sdwp * jhvq
crcr = glpc * bsrl
mcjn = 5
fbqr = 1
ttzr = 2
jsph = lclz * ppbd
bnwn = 3
ptgc = 2
bgvr = sclh * sblm
wnlf = ffls + jswq
vstr = 5
mrdp = gmzr * ngfj
mzpd = njjr * bhqw
jbss = sjcc + swhn
rtfj = 3
jppl = qdjh * zwcr
sbzv = 5
fjzt = 8
pplj = jwzt * tlwj
mwcq = lmjv + fwll
fmtl = pnjm + rsff
phjw = 3
root = gvfh + njlw
lzpd = 4
wzsf = jnpc * jjpq
zjtg = jwpr `div` znsw
frvh = rjmb - dtqz
jwjh = 12
ttjt = jsvj + vvmt
fmdv = jzqn * srgd
mgpl = jtcv + wsqw
rtcq = qvzb `div` zhlq
mpqs = mhwv * shrc
mmgh = frzm * bzjc
wqvr = fcnm * nthg
wptm = 5
twjr = spjr + tnhq
spnl = 2
jzqn = dppn + wntz
fcnm = dhtd + dttv
wzgz = 4
gmcq = rcqp - zgcs
qnhz = 6
qzhc = jrcc - pmqv
dhwf = gdlg * nddc
cqgh = qfcg - rlwp
dtqc = 2
csqr = 2
bbcm = 10
qjhv = 2
wftn = dpvl + tpwr
hslv = 4
bhhj = 17
ltdn = 4
mwdg = 3
ghnb = 3
lvvz = dpgv + tdlw
grvq = 1
flwn = 5
wzjp = 11
ncgs = 5
tpcl = fmdv + vdhh
cfqw = 5
dsdl = 3
sqbn = 7
bdtl = 2
bmlw = 1
vwll = lsjn + qqst
mhfj = 1
lsph = cqll * lbgs
wbwr = qcpj * zgbg
fvpw = dnpq + bhcj
rhjj = jwsw - cbcz
tvsn = 3
qzdd = 5
wvwb = 12
bmrj = 2
mrct = 5
wprd = 2
lwvr = nhnw - hcpg
dngf = 5
nfgb = 3
qcnr = pslb * plcr
hnnp = gspw - lgsw
wrhp = 6
rnqd = sglr * gnqp
vzqc = pncc `div` bwgv
frbv = 10
nhnb = 3
tzrv = mcvc * mlgm
zfvl = 13
pncc = tmsb + qhfv
snhf = rjcm + rlpp
rrnw = rzgg + jbsd
tbfn = 2
bpjc = wzct + qzjd
gmzr = 4
cvdl = ccwq + dztm
gtvr = 2
zsrl = njzj * bzfw
trzt = 5
rdpz = 4
mthb = 9
mdmr = 4
hgnm = 5
mfbs = 5
fcgs = ljrg * fmrf
ncrp = lpvw * tvjr
jcsp = 3
tzdd = 2
lclz = 7
hqsp = 9
dhgc = 5
smqq = tfrj + pnrq
gnqp = 2
hgmb = wmhv - cqtg
gbht = 2
vpcn = fvct + hlhg
mrcb = 3
jssr = 11
rvpd = 2
fzqd = 7
gfdw = pjfb * zmhw
hdgc = 6
hjvl = 2
bsbw = wnsn + qwgm
zgrr = 2
dpgb = pzwh + lppg
tlnj = pbpg + pnpb
qgll = 4
bfdc = 1
nqdm = 2
gnzp = 2
hwdr = fgjt + pqzw
cqrb = fhth + fzqd
nqdg = 3
lpjg = 3
tgnh = 3
cgdr = 3
ghvc = bdvw - gbhw
bsrl = tbdr * tstw
lcms = 3
jwff = hwgb - hmvm
ghrv = 2
fzqt = 7
swps = pgns + pfqj
ggnl = fpzt + vdnr
btvd = 2
bpvp = pjwr * dtqc
hdvs = nqtj + wjsp
qqbl = zzmz `div` wdmd
shjp = bqdv * hzsv
fnws = nwfd - spqg
lvnf = rdrz + rbzr
zwmq = gbht * qlfp
tnhq = 1
mlrn = 2
hhqq = 3
zzzt = 2
zpmp = 3
zgmn = 13
jcwl = jvqz + qjhv
rcfh = zfvl * pfzw
csjv = 13
jtlf = 13
qlwm = phrs * bhjn
pzlt = llzb * tsnq
qgrg = 2
njqt = 4
qgcb = djcv * jfgq
vlmt = nvgm `div` dnpw
pzwh = 1
nbbg = 3
dbmw = frcf * wmzq
zffq = 7
ntmd = 15
cbcz = mcgc + hwbl
swmf = pvpm * fmtl
zthq = spbn * hzgq
wlrd = 11
szmc = 3
dmsb = 4
cwnd = jvpc * jhww
zwcr = 3
tswr = zgqh * bqdt
qvww = cqhn * gfvq
dfbg = 15
mfwr = 7
cnhc = 2
mrsf = crdh * vqzl
hpws = pvtq * btvd
qnfn = clzt * dfdq
vgsm = pdjr - wgmz
tprb = fltv * vhls
pwbb = mthb * prwh
sdnf = 2
hcgc = cczv - hlqd
fdbs = jdbd * pvdp
ddll = 2
gpfs = 4
rlwp = jntc + qvgj
swqt = 4
grjn = rrwz + pfsj
jpcz = nznz * dgbs
jdfh = qdns + hnqg
qdvq = sdnr `div` jvgj
tlrg = 16
nzjl = 2
fqgc = 3
fqlv = vqjv + wswt
rrct = tslz * lwcm
hcfm = tgvp * lrsg
hzsv = 11
rjjl = 4
gbhl = lsph `div` jqqv
qzjb = vspw * wpcv
tsnq = lvnf * fggl
hjwt = pstg + smdv
jvdc = 2
fbsn = 16
lppt = 3
qsbh = snhj + plhm
vcvv = lshn + tvtd
gmqd = 2
frcg = 6
ctqq = 7
wzdw = 2
ljqt = 5
jjbr = 5
ntwt = 2
hmlj = rvqv * lmdr
cltm = 2
sgvf = 2
tqgq = grhw * bjvm
gjqf = ntzn * wfrp
npdt = 3
mlth = frbg + rlnz
dfwt = sdms * lgfr
fqlj = 4
tvtn = smcr * ncdz
lfgz = fghp * zjbz
npmt = gfhp + szfs
mhrz = 4
lvrd = zjvz * bfcn
pshm = cchn * hcfb
twgp = 2
blln = gwbq * bqhh
cczv = hfng * tqqd
dsdn = hrld - dwbl
zbhj = 5
chmm = vjcd - pjfc
sgvw = lpwb + bjjz
tdtb = 2
dzlz = 5
fzpn = glzm * mcpb
qdjm = dbfp + tcdj
hnbp = 3
qrqw = 9
dntn = sjsr * gcnq
pmnv = fznq * dbsw
bbtf = qmlw * pfrm
nqtj = rmfd + cjcl
bvtc = zhbs `div` lbzl
stds = zdbd - gjvc
nwpz = 6
grqb = qjdc + npgr
nglc = zrht + vmlh
cmdp = ztgm * gbnp
hjbp = zwbj * vshd
plts = rwgr `div` jlzd
qjzb = bmjq * vsvn
jgtn = 7
ntpz = wtfq * vgvw
lrpj = 5
djfr = 16
ddgc = bsng * psbc
mpvr = 2
znrj = lhwl * bgrc
dzww = hlsp + dwjj
dfcj = 4
plvd = 6
qvvs = 7
hfjh = 1
snbz = dsms + tqdh
pnwr = 2
jrcc = 12
dptn = hdjv * wdnm
wvfm = jrph - wnlf
qdtw = 7
fnlz = 2
rtsg = 3
fmnh = 7
fqrf = 2
hcct = zvwv + dzzn
srcv = hrns * vfqs
qcrs = ddgd `div` hsnv
jmpm = tptf * drfs
hltp = 2
bnwz = rngb * dqwp
vgwz = gtsh `div` dwqv
fbbd = 2
phvw = 3
sqcs = mhtc * mlgc
cfqs = npmt + qsbp
chws = 3
bsdf = 5
glpc = 8
lrdn = 18
hbft = 1
qbjw = tlrg + jqhz
vrdd = znjt + fcls
nhlc = 2
tzbc = 3
lptn = ljrp + phgr
lgsw = qdlt + cqvh
bdht = lrgv * wlvs
ngfj = 10
wssc = 2
dppn = zwmq * fsmf
fnbj = rvbs * flmd
whtz = 14
twqq = 2
fgsw = nwpz * nrll
whlq = chbw + lnlg
grsz = 3
hndj = gtvf * nmvr
zcrd = hbqp - cwjb
dzgg = qqbp - vtms
fpst = 2
gwwt = 5
dgnt = 4
tpwr = 3
nmvw = gdjm * vngt
vzvz = 13
fbgc = hdtp * pdvm
vchv = svsl - rdpz
srzl = 3
twcp = ldwb * rstd
mbts = gnwj * smhb
ffhv = wftn * fncq
bnnl = mmll * nhnb
bwmq = fpcg * dqnm
jpnz = 17
wfrp = 4
lbjm = 4
fvbn = 2
bzfw = 2
jhwm = 4
qpfh = 3
nvhp = zcgn - tnpl
ntbc = 4
ntzn = 2
htrt = 4
gvjc = 2
jqhz = jjvv * lmgg
jlgf = jvtz + clpg
shsm = qcwp + srlw
ndgs = tljq + rqlg
lrgl = ltzj `div` frzb
jbjg = rtsn * nrdl
wpbt = tsdv `div` cwmv
dstn = 3
pfbd = qcnr `div` czjp
msms = pngq - npqv
dpfv = 13
pbzz = 1
lbqm = szgc + vncq
vwhf = crcr + qdjm
sjsr = 10
rlrf = wlrd * dftr
grjw = ctvm * qcwb
phwc = hjwt + gmhv
bbzz = slhp * vzwn
svvz = 10
rnbg = tdts * thpm
gbgf = 5
jdhs = gbhl - pstz
lvdh = 15
nljh = 4
hbqp = dbwl * qnzv
nddc = zbhj * rglm
ghbn = 5
hghh = tzfj + vnjz
npvq = 4
fzvn = zmnl + qwjw
ffsm = shdb * tptj
cfgv = 2
lgws = 3
rhzd = vgbm + cnhc
gjvc = pwgm * lvhs
dmmd = 4
dwtm = clbs + qjzb
fsmf = chts + frnb
jdzl = lpbr * gfvj
tvtl = fszm + ngls
tstp = 2
wcht = znrs + rfqb
dlww = 14
sldj = 5
vdhh = ctbh * dmhq
rgbj = hsll + tnlb
wbgw = 6
dndp = dstw + ncwh
wwth = 3
dqvl = 16
dmqt = 3
bqfc = qpjn + dmtq
cwfb = 5
vgnm = srdg * qzsq
rnss = 16
spgd = jcfh * qplg
vdnr = gcct * tpdw
jfgm = 7
vtms = dscl * zqcz
lnmr = 1
tpjw = fjhr + fwnc
pdhv = 2
gfvq = 3
scnp = fgsw + wsjg
czmp = 7
gbnp = 8
nhnw = svsm + dpll
rlhz = dfhb * lmlz
ncnl = 7
rbgh = fvzd + hbft
vdmq = mgpl * bmfg
tfht = 3
wsjm = 2
vcqd = 9
mzjw = 2
tfst = qpvg - wmvz
cwls = jnwl * qvrr
mfrs = jcbq * tmpn
mbww = hpfn + bbmm
hsgg = vccc * sgrm
qmlw = zgmn * gcsg
thfp = 2
gvzz = mmjj * sbgb
bpth = cwlj * dqzd
wwwm = qnfn + jlwb
tghw = clhw * dgtj
gpbv = ddgr * tjcb
gvsb = 11
crlj = 5
wmnn = 2
rdrz = mrsf + wvwb
rjcm = 4
dpvl = 16
ncdz = mtdc * csjv
rscz = 17
qvzt = 4
zjtj = 4
wlvs = 4
fssf = wsjm * zrff
wbdm = ghzz * lnrf
jbgr = 3
tbdr = 3
qcht = nvjl * tzbc
mgmh = 2
mnsw = 3
dwbl = 5
pmsh = crhj `div` rqmt
hqfs = 14
tsnd = 2
nmrn = dtdb * zqgc
dsnc = mwpd + mmgh
dlnm = hgpj * qpqs
tzfp = cbgs + szzs
glsf = cvzw * hssc
cndn = 1
vlcz = hpbq * wprd
lsjn = zsdj + lfgz
hzgq = 7
dpnc = 3
rvgm = ppng `div` lfjd
ptbp = dgwq * cwgq
crjw = fbbd * npbf
nhsq = 14
ftqz = 4
vshl = 3
rzzm = jmgn * btmc
ppjl = 3
sbvt = jqnr * wzdw
mpfr = wgfc * dnph
wfhg = 5
ptgz = 11
jsmg = 2
jjrt = 6
szjv = szwc * twnf
hssc = qzbv + bcbc
bhqz = nglc + jmzj
dwgd = 16
vlln = 2
pnjm = 14
fcsb = hfth + ctqv
cdfz = 2
wspf = pswj * sbhm
rgfp = 3
rmdr = 4
znqs = tpgv * jmqm
bwwq = 9
tfzv = 7
mtdc = hlwf + nghp
jmpz = 5
mwfq = qrqw * zghq
cwcb = 6
tnls = 12
rfqd = vbfb + rvfj
pqbm = tlnp * brrr
gwdc = 2
prwh = 19
dmrb = chsl * rjvg
cclg = 19
zlwg = llcq * pwdl
jcbq = jtrn - dntn
ncgv = vcqq + spzn
bmgw = gwjp * gtlb
brbw = blln + dfbg
nmtc = pzph + lsvn
pfsm = 3
zgjg = gncb * lppt
lghd = fnws * cqwv
jzcn = 10
dcwg = tswr + zvsq
zvff = cmsh `div` hltp
qfgs = tshl + hlpg
qndn = tjgd - ttjt
mlgc = 2
stbr = 4
fpzt = qpwm * bvzf
cnqq = tppg `div` ldmb
drfs = 3
vpnq = 3
tslz = 2
srhj = 2
cqmr = tzmv + nvmm
bmbs = gtvr * sdfq
pqdm = nfnw * pgmw
tzsf = 2
hsnv = 2
cmgz = tfrh * lbcr
lhfp = 2
zccb = glwr + tfql
zlgg = 1
jfqr = 1
ltfs = 2
grwn = tfqd + vcsh
nwsw = lvvz - npvq
jmnf = wdfz + cvdl
vjss = czbb * ggwg
rhhm = 3
qpsf = 3
lpwb = mcjq + dcws
bhcb = 2
lfjf = rrct * tptc
wchd = 8
hsww = qfnz * tpjp
tsdv = cfqs * jmpz
zhbv = 18
rhgt = 5
lcbc = rqqj * lrbm
bmws = 5
rlgc = 5
tvfq = 4
rwmm = cgvc * fcbb
plcr = wqrr + vncc
vhmz = fzpn + bpth
fhrm = qhgd + tgzm
wssd = 15
sjvh = wblj `div` zhzd
bmfg = 3
whgd = mhfq * rzrz
qccg = 2
dnch = 3
lnpq = 4
cqtg = 7
lssg = 3
dpgv = 3
wnql = 2
rblm = qglw * cdqj
qpqs = 2
dtdt = 4
zvwv = lnld + rsgh
zggr = rgzs * pgvl
fwll = rhpw * mfbr
rgpp = hnzv + rtpm
hlqd = mjvp * zgrr
jmqs = jdhs - jjbt
rvbs = 5
gspw = qsbh + cmms
njtn = jjqv - dfqh
qzhz = 4
zlvd = 5
msjt = dvrf * hnnp
zhwq = 6
wgpz = mrmf * smrh
cfsr = ldpv * jgtn
szgc = lzwq * tpdt
gpnm = swps - sldj
fbzq = jmpm + jpcz
ttwb = 3
rfnr = ffhb + rrbb
chsn = 2
tczg = 15
nghp = rllz * mmvj
ctpg = thwc - gmbz
ggmh = lftn + qzpg
rtsn = 3
rqlg = 5
qdps = qhgz * pczb
mrgm = lmjt * zgtf
lsvn = jhmn * vdmw
qvvc = tsnd * nllc
lvdm = 3
bwhl = 5
zdhj = tsfg * lhsn
cjrg = 2
rdtf = rnzf * zvdv
fdfl = rsnc + sfnm
hrpq = 3
ffmd = pjwh * bpdj
sfzc = 5
mbnm = 7
jfjv = ntwt * frgj
ptnt = 2
tfql = 3
dzdb = 1
mfjt = 5
cspw = 5
ldwb = pjqj + ntmd
rrmz = wpgl * qmrh
vttd = blgc * nwfw
dcvt = 3
njlw = wwwq * pzlt
mgvr = 7
hlpg = zlwg + vssm
hjtj = rbbf + rrnw
qtlj = gvsb * qzdd
bvsf = 8
fqwr = ggnl + pnsw
qcwb = 3
cbgs = 3
dfdq = 5
sfcs = 5
zwbg = hrsd + fscs
ztcr = 6
fcbt = tdmn * nlmw
qdbb = gjqf * dpfv
bfrr = dvjc * jdww
fvzv = ncgs + zgjg
ssnn = 13
lfgr = 4
bnnv = 2
zggd = 2
wrdw = 6
mzmh = 6
smsr = 11
spnf = ntpz - djrw
slfg = fvjr * tvfq
lrbm = 2
tcsp = 5
fcbb = 7
cnjf = mslj + bmbs
rndg = 2
qdgt = hdbc + zsrl
pngq = phvw + gwfl
wmhn = vjss + jrqq
djjt = 5
qsrq = 2
qvzb = gvjq * pctc
mdbh = tczs * gvjc
cwlb = 2
dvgl = fhrm + mtft
ndrr = rqlc * rwtr
jwzt = 5
psjc = 14
pvdp = 7
jbsd = chtp * qqzb
gqjf = jmjp * chlh
dstc = hwgr + bgvr
wtfq = 15
ghgs = gzqc + mslt
rqgt = tdbs + jjhh
cndw = tzmg - rlhz
ncwh = cpdc `div` hcjt
zpll = 3
grbs = msct + qqzj
fszw = rrwf + qhbl
blhq = pndj * njvp
zgll = 2
rhpw = 2
sbvw = vlcz + mspq
wjhs = tcsp + whdh
nvlf = 5
dqsf = fzjv - nhsq
tbpl = 6
jsdw = plqr + jssr
sznr = 5
pstg = dmgd * bmbq
tmsb = rrcw * qghb
bhzw = ntbc * bwhl
tscr = 3
mwvc = 2
mnwl = 2
mtnl = 3
cwlj = 4
wlcr = 8
fwhj = 3
ltzj = dmjp * ggmh
qmrn = 6
sgss = jqnc + rnwr
vbqg = jtdq + pvrb
jvwq = 2
dgvf = zngc * qpsf
wtwj = mhll * mbts
fpgn = pplj + qzhc
njvg = 16
szcc = wdnd + ptgz
qcsr = 3
llzb = vpbh * vvmr
gwjp = 5
lhjn = gsps * zmnq
wjsp = 2
rrwz = 5
qfnz = 2
hgtm = hngm - whlg
wgrl = 1
rcqp = 10
zwsp = bdvl - sjdj
tpjp = gqjf + lttg
qpwm = 4
ppng = humn - swmf
dgss = 3
mspq = 1
njzj = qfjc * rqnr
cfnc = 2
hvqp = jmqs + cdzs
vbmr = grvq + sgjc
dnrj = cwpt + npzj
twnf = 2
rjmb = 17
rnzf = 5
wngb = qdlf + fgfj
vdsf = qzfd + rdhb
vvmt = dstv * ftjz
fncq = 10
zrjc = jnmb + sjvh
qgms = 3
pfzw = 3
bmcs = 2
dvlb = 2
wcvs = cdvf * wrwg
fbcc = 4
nfnw = 3
sjbm = wzsw + pplh
mwpd = gfcm * trbf
srvr = 2
fpcg = 2
gfvh = qhsv * pphc
hfcw = 2
lqcc = 5
jnpm = 2
tdtd = psps * jjlv
htfw = 2
gjrf = fqwr - qdvq
bpsl = 5
nnsn = 2
zmwr = 3
rppc = 5
gvcv = fvwt `div` cnbl
qdjh = 7
gbwc = frbv + mhht
fvln = 2
vgbv = 11
zcpv = 2
vndb = dsbj + wmnn
vqsq = 5
jvgj = 2
lttg = 8
whlg = 11
fmbw = rgfl + rhzd
cjlc = 4
wsgc = 5
fgvt = fcgs + spwz
bpss = 7
fdqj = 4
wmzn = 5
mcgc = 1
rnmw = cqct + crnl
rdsh = 9
qhgd = wdjl + tsws
btmc = 4
djdw = clhj * tddg
vmmb = 6
msml = 3
gztn = rzjl + dvht
gczs = mrtl * ncch
hdtp = ncfh * rtgw
jhww = 2
wsdd = 2
cwjb = vfjv + spmd
ljgh = zjcr * fnbj
pmbv = 10
wmvz = vmdq + sgqv
mwsg = 13
rbsw = 5
dzfm = 3
mnjh = 2
jhbp = hslp * lzpd
qpvg = cspw * fgmf
hwmv = 5
hcvv = jbbg * wsdf
stjr = fmng * tbzv
vqmd = wsjb * rdrc
tgjw = 2
ncjg = lqcc + wfhg
lpsh = 5
psgw = 7
hpdw = 3
vqzl = 3
srtg = cnjm + tdqs
pswj = chws * zmwr
snrr = 5
lhrt = 11
tscd = 3
gzjs = 2
tptc = 3
zcmj = 3
cvmv = 8
hsln = 4
pjwr = 3
lfvh = 2
rbbf = stcr `div` smgw
lzbl = bsqw * trct
hdtj = 15
hnjz = vpts + bpss
vwdn = 2
wwcz = 16
mhwv = 2
jffs = 5
main = print root
| |
52aba4e0152dcf3af88dfe2db6b00317daa6259c3d8f99a37339d655e8068a56 | ftrain/anxietybox | mail.clj | (ns anxietybox.mail
(:require
[environ.core :as env]
[taoensso.timbre :as timbre]
[anxietybox.bot :as bot]
[clj-http.client :as client]))
(timbre/refer-timbre)
(timbre/set-config! [:appenders :spit :enabled?] true)
TODO put this in env .
(timbre/set-config! [:shared-appender-config :spit-filename] "/Users/ford/Desktop/logs/clojure.log")
(def mailgun-auth ["api" (env/env :mailgun-api-key)])
(def mailgun-site "anxietybox.com")
(def mailgun-uri (str "/" mailgun-site "/messages"))
(def from-email "Your Anxiety <>")
(def closing "\n\nSincerely,\n\nYour Anxiety\n\n // ")
(defn mailgun-send
"Post an email to the mailgun gateway."
[form]
(info form)
(client/post mailgun-uri
{:basic-auth mailgun-auth
:throw-entire-message? true
:form-params (merge {:from from-email} form)}))
(defn send-confirmation
""
[box]
(info box)
(mailgun-send { :to (:email box)
:subject "Confirmation requested"
:text (str "Dear " (:name box) ",
\nYou just signed up for Anxietybox.com. Click here to confirm your email:
\n\t/" (:confirm box) "
\nIf you didn't sign up, ignore this email." closing)}))
(defn send-reminder [box]
(mailgun-send { :to (:email box)
:subject "Account information"
:text (str "Dear " (:name box) ",
\nClick here to delete your account:
\n\t/" (:confirm box) "
\nYou can start a new account any time." closing)}))
(defn anxiety-text [box]
(str "Dear " (:name box) ",\n\n"
(bot/compose
(if (:anxieties box) (:description (rand-nth (:anxieties box))))
(if (:reply box) (:description (rand-nth (:replies box)))))
closing
"\n\nP.S. Click here to delete your account:"
"\n\t/"
(:confirm box)
"\nYou can start a new account any time."
))
(defn send-anxiety [box]
(mailgun-send { :to (:email box)
:subject (bot/ps)
:text (anxiety-text box)}))
;(send-anxiety (data/box-select ""))
| null | https://raw.githubusercontent.com/ftrain/anxietybox/cee9286931465f345e22aec162fb8610a00b6977/anxietybox/src/anxietybox/mail.clj | clojure | (send-anxiety (data/box-select "")) | (ns anxietybox.mail
(:require
[environ.core :as env]
[taoensso.timbre :as timbre]
[anxietybox.bot :as bot]
[clj-http.client :as client]))
(timbre/refer-timbre)
(timbre/set-config! [:appenders :spit :enabled?] true)
TODO put this in env .
(timbre/set-config! [:shared-appender-config :spit-filename] "/Users/ford/Desktop/logs/clojure.log")
(def mailgun-auth ["api" (env/env :mailgun-api-key)])
(def mailgun-site "anxietybox.com")
(def mailgun-uri (str "/" mailgun-site "/messages"))
(def from-email "Your Anxiety <>")
(def closing "\n\nSincerely,\n\nYour Anxiety\n\n // ")
(defn mailgun-send
"Post an email to the mailgun gateway."
[form]
(info form)
(client/post mailgun-uri
{:basic-auth mailgun-auth
:throw-entire-message? true
:form-params (merge {:from from-email} form)}))
(defn send-confirmation
""
[box]
(info box)
(mailgun-send { :to (:email box)
:subject "Confirmation requested"
:text (str "Dear " (:name box) ",
\nYou just signed up for Anxietybox.com. Click here to confirm your email:
\n\t/" (:confirm box) "
\nIf you didn't sign up, ignore this email." closing)}))
(defn send-reminder [box]
(mailgun-send { :to (:email box)
:subject "Account information"
:text (str "Dear " (:name box) ",
\nClick here to delete your account:
\n\t/" (:confirm box) "
\nYou can start a new account any time." closing)}))
(defn anxiety-text [box]
(str "Dear " (:name box) ",\n\n"
(bot/compose
(if (:anxieties box) (:description (rand-nth (:anxieties box))))
(if (:reply box) (:description (rand-nth (:replies box)))))
closing
"\n\nP.S. Click here to delete your account:"
"\n\t/"
(:confirm box)
"\nYou can start a new account any time."
))
(defn send-anxiety [box]
(mailgun-send { :to (:email box)
:subject (bot/ps)
:text (anxiety-text box)}))
|
01b49868d9e112a37ea3bf6e7e01b41cc42cff8a9b16e6c89d3d459a813e0b07 | dyoo/whalesong | runtime.rkt | #lang s-exp "../lang/js/js.rkt"
(require "structs.rkt")
(declare-implementation
#:racket "racket-impl.rkt"
#:javascript ("js-impl.js")
#:provided-values (resource->url))
| null | https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/resource/runtime.rkt | racket | #lang s-exp "../lang/js/js.rkt"
(require "structs.rkt")
(declare-implementation
#:racket "racket-impl.rkt"
#:javascript ("js-impl.js")
#:provided-values (resource->url))
| |
01bfd5ee4c528f2e73e77df04995f523ae6c7a99009a544d225c1bb4dc3d1d67 | elaforge/karya | TrackTree.hs | Copyright 2013
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
module Ui.TrackTree where
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Traversable as Traversable
import qualified Data.Tree as Tree
import qualified Util.Pretty as Pretty
import qualified Util.Trees as Trees
import qualified Derive.ParseTitle as ParseTitle
import qualified Derive.ScoreT as ScoreT
import qualified Ui.Block as Block
import qualified Ui.Event as Event
import qualified Ui.Events as Events
import qualified Ui.Skeleton as Skeleton
import qualified Ui.Track as Track
import qualified Ui.Types as Types
import qualified Ui.Ui as Ui
import Global
import Types
| A TrackTree is the Skeleton resolved to the tracks it references .
type TrackTree = [Tree.Tree Ui.TrackInfo]
tracks_of :: Ui.M m => BlockId -> m [Ui.TrackInfo]
tracks_of block_id = do
block <- Ui.get_block block_id
state <- Ui.get
return $ track_info block (Ui.state_tracks state)
where
track_info block tracks = do
(i, btrack@(Block.Track { Block.tracklike_id = Block.TId tid _}))
<- zip [0..] (Block.block_tracks block)
track <- maybe [] (:[]) (Map.lookup tid tracks)
return $ Ui.TrackInfo
{ track_title = Track.track_title track
, track_id = tid
, track_tracknum = i
, track_block = btrack
}
| Return @(parents , self :
parents_children_of :: Ui.M m => BlockId -> TrackId
-> m (Maybe ([Ui.TrackInfo], [Ui.TrackInfo]))
parents_children_of block_id track_id = do
tree <- track_tree_of block_id
case List.find (\(t, _, _) -> Ui.track_id t == track_id)
(Trees.flatPaths tree) of
Nothing -> return Nothing
Just (track, parents, children) ->
return $ Just (parents, track : children)
-- | This is like 'parents_children_of', but only the children, and it doesn't
-- include the given TrackId.
get_children_of :: Ui.M m => BlockId -> TrackId -> m [Ui.TrackInfo]
get_children_of block_id track_id =
parents_children_of block_id track_id >>= \case
Just (_, _ : children) -> return children
_ -> Ui.throw $ "no children of " <> pretty (block_id, track_id)
is_child_of :: Ui.M m => BlockId -> TrackNum -> TrackNum -> m Bool
is_child_of block_id parent child = do
children <- get_children_of block_id
=<< Ui.get_event_track_at block_id parent
return $ child `elem` map Ui.track_tracknum children
-- | Combine the skeleton with the tracks to create a TrackTree.
--
TODO this is pretty complicated . If I stored the tracks as a tree in the
first place and generated the skeleton from that then this would all go
-- away. But that would mean redoing all the "Ui.Skeleton" operations for
trees . And the reason I did n't do it in the first place was the hassle of
-- graph operations on a Data.Tree.
track_tree_of :: Ui.M m => BlockId -> m TrackTree
track_tree_of block_id = do
skel <- Ui.get_skeleton block_id
tracks <- tracks_of block_id
ntracks <- fmap (length . Block.block_tracklike_ids) (Ui.get_block block_id)
let by_tracknum = Map.fromList $
zip (map Ui.track_tracknum tracks) tracks
let (resolved, missing) = resolve_track_tree by_tracknum
(Skeleton.to_forest ntracks skel)
-- Rulers and dividers should show up as missing. They're ok as long as
-- they have no edges.
let really_missing = filter (not . Skeleton.lonely_vertex skel) missing
unless (null really_missing) $
Ui.throw $ "skeleton of " <> showt block_id
<> " names missing tracknums: " <> showt really_missing
return resolved
| Resolve the indices in a tree into whatever values as given by
-- a map.
resolve_track_tree :: Map TrackNum a -> [Tree.Tree TrackNum]
-> ([Tree.Tree a], [TrackNum]) -- ^ resolved tree, and missing TrackNums
resolve_track_tree tracknums = foldr (cat_tree . go) ([], [])
where
go (Tree.Node tracknum subs) = case Map.lookup tracknum tracknums of
Nothing -> (Nothing, [tracknum])
Just track_info ->
let (subforest, missing) = resolve_track_tree tracknums subs
in (Just (Tree.Node track_info subforest), missing)
cat_tree (maybe_tree, missing) (forest, all_missing) = case maybe_tree of
Nothing -> (forest, missing ++ all_missing)
Just tree -> (tree : forest, missing ++ all_missing)
strip_disabled_tracks :: Ui.M m => BlockId -> TrackTree -> m TrackTree
strip_disabled_tracks block_id = concatMapM strip
where
strip (Tree.Node track subs) = ifM (disabled track)
(concatMapM strip subs)
((:[]) . Tree.Node track <$> concatMapM strip subs)
disabled = fmap (Block.Disable `Set.member`)
. Ui.track_flags block_id . Ui.track_tracknum
type EventsTree = [EventsNode]
type EventsNode = Tree.Tree Track
data Track = Track {
track_title :: !Text
-- | Events on this track. These are shifted by
' Derive . Slice.slice_notes ' , so they are in ScoreTime , not TrackTime .
, track_events :: !Events.Events
-- | This goes into the stack when the track is evaluated. Inverted tracks
-- will carry the TrackId of the track they were inverted from, so they'll
-- show up in the stack twice. This means they can record their environ
-- as it actually is when the notes are evaluated, rather than its
-- pre-invert value, which is likely to not have the right scale.
, track_id :: !(Maybe TrackId)
-- | The block these events came from. A track can appear in multiple
-- blocks, but can only appear once in each block.
, track_block_id :: !(Maybe BlockId)
-- | The relative start and end of this slice of track. Like
' track_events ' , this is in ScoreTime , not TrackTime .
, track_start :: !ScoreTime
, track_end :: !ScoreTime
-- | True if this is a sliced track. That means it's a fragment of
-- a track and certain track-level things should be skipped.
, track_sliced :: !Sliced
-- | These events are not evaluated, but go in
' Derive . Derive.ctx_prev_events ' and . This is so that
-- sliced calls (such as inverting calls) can see previous and following
-- events. Shifted along with 'track_events'.
, track_around :: !([Event.Event], [Event.Event])
-- | If the events have been shifted from their original positions on the
-- track, add this to them to put them back in TrackTime.
, track_shifted :: !TrackTime
-- | This is the track's track voice, as defined in 'Environ.track_voices'.
Originally I tried to keep it all within " Derive . Call . BlockUtil " , but
-- it gets complicated with child tracks and slicing. Putting it in
-- 'Track' ensures it can't get lost.
, track_voice :: !(Maybe Int)
} deriving (Show)
track_range :: Track -> (TrackTime, TrackTime)
track_range track = (track_shifted track, track_shifted track + track_end track)
instance Pretty Track where
format (Track title events track_id block_id start end sliced
around shifted voice) =
Pretty.record "Track"
[ ("title", Pretty.format title)
, ("events", Pretty.format events)
, ("track_id", Pretty.format track_id)
, ("block_id", Pretty.format block_id)
, ("start", Pretty.format start)
, ("end", Pretty.format end)
, ("sliced", Pretty.format sliced)
, ("around", Pretty.format around)
, ("shifted", Pretty.format shifted)
, ("voice", Pretty.format voice)
]
make_track :: Text -> Events.Events -> ScoreTime -> Track
make_track title events end = Track
{ track_title = title
, track_events = events
, track_id = Nothing
, track_block_id = Nothing
, track_start = 0
, track_end = end
, track_sliced = NotSliced
, track_around = ([], [])
, track_shifted = 0
, track_voice = Nothing
}
data Sliced =
-- | An intact track, unchanged from the score.
--
-- It's confusing to say track_sliced track == NotSliced, and I could pick
-- something like Intact, but there's no precedent for that terminology.
NotSliced
-- | A "Derive.Slice"d fragment, and certain track-level things should be
-- skipped.
| Sliced !Types.Orientation
-- | Set on the fake track created by inversion.
| Inversion
deriving (Eq, Show)
instance Pretty Sliced where pretty = showt
block_track_id :: Track -> Maybe (BlockId, TrackId)
block_track_id track = do
bid <- track_block_id track
tid <- track_id track
return (bid, tid)
events_tree_of :: Ui.M m => BlockId -> m EventsTree
events_tree_of block_id = do
info_tree <- track_tree_of block_id
end <- Ui.block_ruler_end block_id
events_tree block_id end info_tree
events_tree :: Ui.M m => BlockId -> ScoreTime -> [Tree.Tree Ui.TrackInfo]
-> m EventsTree
events_tree block_id end = mapM resolve . track_voices
where
resolve (Tree.Node (Ui.TrackInfo title track_id _ _, voice) subs) =
Tree.Node <$> make title track_id voice <*> mapM resolve subs
make title track_id voice = do
events <- Ui.get_events track_id
return $ (make_track title events end)
{ track_id = Just track_id
, track_block_id = Just block_id
, track_voice = voice
}
| Get the EventsTree of a block . Strip disabled tracks .
block_events_tree :: Ui.M m => BlockId -> m EventsTree
block_events_tree block_id = do
info_tree <- strip_disabled_tracks block_id =<< track_tree_of block_id
This is the end of the last event or ruler , not
-- Ui.block_logical_range. The reason is that functions that look at
-- track_end are expecting the physical end, e.g.
Control.derive_control uses it to put the last sample on the tempo
-- track.
end <- Ui.block_end block_id
events_tree block_id end info_tree
| All the children of this EventsNode with TrackIds .
track_children :: EventsNode -> Set TrackId
track_children = foldl' (flip Set.insert) Set.empty
. mapMaybe track_id . Tree.flatten
-- | Each note track with an instrument gets a count and maximum count, so they
-- can go in 'Environ.track_voice' and 'Environ.track_voices'.
track_voices :: [Tree.Tree Ui.TrackInfo]
-> [Tree.Tree (Ui.TrackInfo, Maybe Int)]
track_voices tracks = map (fmap only_inst) $ count_occurrences inst_of tracks
where
inst_of = not_empty <=< ParseTitle.title_to_instrument . Ui.track_title
where
not_empty inst = if inst == ScoreT.empty_instrument
then Nothing else Just inst
only_inst (track, voice)
| Just _ <- inst_of track = (track, Just voice)
| otherwise = (track, Nothing)
-- | For each element, give its index amount its equals, and the total number
-- of elements equal to it.
count_occurrences :: (Traversable f, Traversable g, Ord k) =>
(a -> k) -> f (g a) -> f (g (a, Int))
count_occurrences key =
snd . (Traversable.mapAccumL . Traversable.mapAccumL) go mempty
where
go counts x = (Map.insert (key x) (n+1) counts, (x, n))
where n = Map.findWithDefault 0 (key x) counts
| null | https://raw.githubusercontent.com/elaforge/karya/de1b6e8cb0a17870801cc4dd49de8de62eb6c5fe/Ui/TrackTree.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt
| This is like 'parents_children_of', but only the children, and it doesn't
include the given TrackId.
| Combine the skeleton with the tracks to create a TrackTree.
away. But that would mean redoing all the "Ui.Skeleton" operations for
graph operations on a Data.Tree.
Rulers and dividers should show up as missing. They're ok as long as
they have no edges.
a map.
^ resolved tree, and missing TrackNums
| Events on this track. These are shifted by
| This goes into the stack when the track is evaluated. Inverted tracks
will carry the TrackId of the track they were inverted from, so they'll
show up in the stack twice. This means they can record their environ
as it actually is when the notes are evaluated, rather than its
pre-invert value, which is likely to not have the right scale.
| The block these events came from. A track can appear in multiple
blocks, but can only appear once in each block.
| The relative start and end of this slice of track. Like
| True if this is a sliced track. That means it's a fragment of
a track and certain track-level things should be skipped.
| These events are not evaluated, but go in
sliced calls (such as inverting calls) can see previous and following
events. Shifted along with 'track_events'.
| If the events have been shifted from their original positions on the
track, add this to them to put them back in TrackTime.
| This is the track's track voice, as defined in 'Environ.track_voices'.
it gets complicated with child tracks and slicing. Putting it in
'Track' ensures it can't get lost.
| An intact track, unchanged from the score.
It's confusing to say track_sliced track == NotSliced, and I could pick
something like Intact, but there's no precedent for that terminology.
| A "Derive.Slice"d fragment, and certain track-level things should be
skipped.
| Set on the fake track created by inversion.
Ui.block_logical_range. The reason is that functions that look at
track_end are expecting the physical end, e.g.
track.
| Each note track with an instrument gets a count and maximum count, so they
can go in 'Environ.track_voice' and 'Environ.track_voices'.
| For each element, give its index amount its equals, and the total number
of elements equal to it. | Copyright 2013
module Ui.TrackTree where
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Traversable as Traversable
import qualified Data.Tree as Tree
import qualified Util.Pretty as Pretty
import qualified Util.Trees as Trees
import qualified Derive.ParseTitle as ParseTitle
import qualified Derive.ScoreT as ScoreT
import qualified Ui.Block as Block
import qualified Ui.Event as Event
import qualified Ui.Events as Events
import qualified Ui.Skeleton as Skeleton
import qualified Ui.Track as Track
import qualified Ui.Types as Types
import qualified Ui.Ui as Ui
import Global
import Types
| A TrackTree is the Skeleton resolved to the tracks it references .
type TrackTree = [Tree.Tree Ui.TrackInfo]
tracks_of :: Ui.M m => BlockId -> m [Ui.TrackInfo]
tracks_of block_id = do
block <- Ui.get_block block_id
state <- Ui.get
return $ track_info block (Ui.state_tracks state)
where
track_info block tracks = do
(i, btrack@(Block.Track { Block.tracklike_id = Block.TId tid _}))
<- zip [0..] (Block.block_tracks block)
track <- maybe [] (:[]) (Map.lookup tid tracks)
return $ Ui.TrackInfo
{ track_title = Track.track_title track
, track_id = tid
, track_tracknum = i
, track_block = btrack
}
| Return @(parents , self :
parents_children_of :: Ui.M m => BlockId -> TrackId
-> m (Maybe ([Ui.TrackInfo], [Ui.TrackInfo]))
parents_children_of block_id track_id = do
tree <- track_tree_of block_id
case List.find (\(t, _, _) -> Ui.track_id t == track_id)
(Trees.flatPaths tree) of
Nothing -> return Nothing
Just (track, parents, children) ->
return $ Just (parents, track : children)
get_children_of :: Ui.M m => BlockId -> TrackId -> m [Ui.TrackInfo]
get_children_of block_id track_id =
parents_children_of block_id track_id >>= \case
Just (_, _ : children) -> return children
_ -> Ui.throw $ "no children of " <> pretty (block_id, track_id)
is_child_of :: Ui.M m => BlockId -> TrackNum -> TrackNum -> m Bool
is_child_of block_id parent child = do
children <- get_children_of block_id
=<< Ui.get_event_track_at block_id parent
return $ child `elem` map Ui.track_tracknum children
TODO this is pretty complicated . If I stored the tracks as a tree in the
first place and generated the skeleton from that then this would all go
trees . And the reason I did n't do it in the first place was the hassle of
track_tree_of :: Ui.M m => BlockId -> m TrackTree
track_tree_of block_id = do
skel <- Ui.get_skeleton block_id
tracks <- tracks_of block_id
ntracks <- fmap (length . Block.block_tracklike_ids) (Ui.get_block block_id)
let by_tracknum = Map.fromList $
zip (map Ui.track_tracknum tracks) tracks
let (resolved, missing) = resolve_track_tree by_tracknum
(Skeleton.to_forest ntracks skel)
let really_missing = filter (not . Skeleton.lonely_vertex skel) missing
unless (null really_missing) $
Ui.throw $ "skeleton of " <> showt block_id
<> " names missing tracknums: " <> showt really_missing
return resolved
| Resolve the indices in a tree into whatever values as given by
resolve_track_tree :: Map TrackNum a -> [Tree.Tree TrackNum]
resolve_track_tree tracknums = foldr (cat_tree . go) ([], [])
where
go (Tree.Node tracknum subs) = case Map.lookup tracknum tracknums of
Nothing -> (Nothing, [tracknum])
Just track_info ->
let (subforest, missing) = resolve_track_tree tracknums subs
in (Just (Tree.Node track_info subforest), missing)
cat_tree (maybe_tree, missing) (forest, all_missing) = case maybe_tree of
Nothing -> (forest, missing ++ all_missing)
Just tree -> (tree : forest, missing ++ all_missing)
strip_disabled_tracks :: Ui.M m => BlockId -> TrackTree -> m TrackTree
strip_disabled_tracks block_id = concatMapM strip
where
strip (Tree.Node track subs) = ifM (disabled track)
(concatMapM strip subs)
((:[]) . Tree.Node track <$> concatMapM strip subs)
disabled = fmap (Block.Disable `Set.member`)
. Ui.track_flags block_id . Ui.track_tracknum
type EventsTree = [EventsNode]
type EventsNode = Tree.Tree Track
data Track = Track {
track_title :: !Text
' Derive . Slice.slice_notes ' , so they are in ScoreTime , not TrackTime .
, track_events :: !Events.Events
, track_id :: !(Maybe TrackId)
, track_block_id :: !(Maybe BlockId)
' track_events ' , this is in ScoreTime , not TrackTime .
, track_start :: !ScoreTime
, track_end :: !ScoreTime
, track_sliced :: !Sliced
' Derive . Derive.ctx_prev_events ' and . This is so that
, track_around :: !([Event.Event], [Event.Event])
, track_shifted :: !TrackTime
Originally I tried to keep it all within " Derive . Call . BlockUtil " , but
, track_voice :: !(Maybe Int)
} deriving (Show)
track_range :: Track -> (TrackTime, TrackTime)
track_range track = (track_shifted track, track_shifted track + track_end track)
instance Pretty Track where
format (Track title events track_id block_id start end sliced
around shifted voice) =
Pretty.record "Track"
[ ("title", Pretty.format title)
, ("events", Pretty.format events)
, ("track_id", Pretty.format track_id)
, ("block_id", Pretty.format block_id)
, ("start", Pretty.format start)
, ("end", Pretty.format end)
, ("sliced", Pretty.format sliced)
, ("around", Pretty.format around)
, ("shifted", Pretty.format shifted)
, ("voice", Pretty.format voice)
]
make_track :: Text -> Events.Events -> ScoreTime -> Track
make_track title events end = Track
{ track_title = title
, track_events = events
, track_id = Nothing
, track_block_id = Nothing
, track_start = 0
, track_end = end
, track_sliced = NotSliced
, track_around = ([], [])
, track_shifted = 0
, track_voice = Nothing
}
data Sliced =
NotSliced
| Sliced !Types.Orientation
| Inversion
deriving (Eq, Show)
instance Pretty Sliced where pretty = showt
block_track_id :: Track -> Maybe (BlockId, TrackId)
block_track_id track = do
bid <- track_block_id track
tid <- track_id track
return (bid, tid)
events_tree_of :: Ui.M m => BlockId -> m EventsTree
events_tree_of block_id = do
info_tree <- track_tree_of block_id
end <- Ui.block_ruler_end block_id
events_tree block_id end info_tree
events_tree :: Ui.M m => BlockId -> ScoreTime -> [Tree.Tree Ui.TrackInfo]
-> m EventsTree
events_tree block_id end = mapM resolve . track_voices
where
resolve (Tree.Node (Ui.TrackInfo title track_id _ _, voice) subs) =
Tree.Node <$> make title track_id voice <*> mapM resolve subs
make title track_id voice = do
events <- Ui.get_events track_id
return $ (make_track title events end)
{ track_id = Just track_id
, track_block_id = Just block_id
, track_voice = voice
}
| Get the EventsTree of a block . Strip disabled tracks .
block_events_tree :: Ui.M m => BlockId -> m EventsTree
block_events_tree block_id = do
info_tree <- strip_disabled_tracks block_id =<< track_tree_of block_id
This is the end of the last event or ruler , not
Control.derive_control uses it to put the last sample on the tempo
end <- Ui.block_end block_id
events_tree block_id end info_tree
| All the children of this EventsNode with TrackIds .
track_children :: EventsNode -> Set TrackId
track_children = foldl' (flip Set.insert) Set.empty
. mapMaybe track_id . Tree.flatten
track_voices :: [Tree.Tree Ui.TrackInfo]
-> [Tree.Tree (Ui.TrackInfo, Maybe Int)]
track_voices tracks = map (fmap only_inst) $ count_occurrences inst_of tracks
where
inst_of = not_empty <=< ParseTitle.title_to_instrument . Ui.track_title
where
not_empty inst = if inst == ScoreT.empty_instrument
then Nothing else Just inst
only_inst (track, voice)
| Just _ <- inst_of track = (track, Just voice)
| otherwise = (track, Nothing)
count_occurrences :: (Traversable f, Traversable g, Ord k) =>
(a -> k) -> f (g a) -> f (g (a, Int))
count_occurrences key =
snd . (Traversable.mapAccumL . Traversable.mapAccumL) go mempty
where
go counts x = (Map.insert (key x) (n+1) counts, (x, n))
where n = Map.findWithDefault 0 (key x) counts
|
a1f15a037b6818c00ab2703e2a56c325e88bfb9c493dd3728fe577f8a257ec7e | vbmithr/ocaml-text | regexp.ml |
* regexp.ml
* ---------
* Copyright : ( c ) 2010 , < >
* Licence : BSD3
*
* This file is a part of ocaml - text .
* regexp.ml
* ---------
* Copyright : (c) 2010, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of ocaml-text.
*)
let digit3 = <:re< ["0".."9"]{1-3} >>
let () =
match Sys.argv with
| [|program_name; <:re< (digit3 as d1 : int)
"." (digit3 as d2 : int)
"." (digit3 as d3 : int)
"." (digit3 as d4 : int) >>|] ->
Printf.printf "d1 = %d, d2 = %d, d3 = %d, d4 = %d\n" d1 d2 d3 d4
| _ ->
Printf.printf "usage: %s <ipv4 address>\n" Sys.argv.(0)
| null | https://raw.githubusercontent.com/vbmithr/ocaml-text/631d2dadbe73477e085490c70c8c4a3116ddc2ab/examples/regexp.ml | ocaml |
* regexp.ml
* ---------
* Copyright : ( c ) 2010 , < >
* Licence : BSD3
*
* This file is a part of ocaml - text .
* regexp.ml
* ---------
* Copyright : (c) 2010, Jeremie Dimino <>
* Licence : BSD3
*
* This file is a part of ocaml-text.
*)
let digit3 = <:re< ["0".."9"]{1-3} >>
let () =
match Sys.argv with
| [|program_name; <:re< (digit3 as d1 : int)
"." (digit3 as d2 : int)
"." (digit3 as d3 : int)
"." (digit3 as d4 : int) >>|] ->
Printf.printf "d1 = %d, d2 = %d, d3 = %d, d4 = %d\n" d1 d2 d3 d4
| _ ->
Printf.printf "usage: %s <ipv4 address>\n" Sys.argv.(0)
| |
02399f5b823617b4858bbbd37b711855283973c8e81d9242b051fea4018775e8 | racket/gui | editor-autoload.rkt | #lang racket/unit
(require "sig.rkt"
"editor-sig.rkt"
"../preferences.rkt"
"focus-table.rkt"
string-constants
mred/mred-sig
racket/class
racket/match
file/sha1)
(import mred^
[prefix frame: framework:frame^]
[prefix editor: editor-misc^])
(export editor-autoload^)
(init-depend mred^)
(define autoload<%>
(interface (editor:basic<%>)))
(define-local-member-name autoload-file-changed autoload-do-revert)
;; open-dialogs : hash[tlw -o> (cons/c dialog boolean)]
;; the dialogs that are currently being shown, paired with
;; a boolean that indicates if the initial dialog has a checkbox
(define open-dialogs (make-hash))
pending - editors : hash[tlw -o > ( listof editor<% > ) ]
;; editors where we are waiting for a reply from the user
(define pending-editors (make-hash))
;; invariant:
;; (hash-ref pending-editors tlw '()) = (cons ed eds)
;; ⟺
;; (hash-ref open-dialogs tlw #f) ≠ #f
;; only called if we have to ask the user about what to do,
;; so we know that the `ask preference is set or window was dirty
(define (handle-autoload-file-changed&need-dialog editor)
(define tlw (send editor get-top-level-window))
when tlw=#f , this will be ' ( )
(unless (member editor already-pending-editors)
(define all-pending-editors (cons editor already-pending-editors))
(when tlw (hash-set! pending-editors tlw all-pending-editors))
(cond
[(and (null? (cdr all-pending-editors))
(send (car all-pending-editors) is-modified?))
;; first one => need to open the dialog, and it is dirty
(define dlg
(message-box/custom
(string-constant warning)
(get-autoload-warning-message all-pending-editors)
(string-constant revert)
(string-constant ignore)
#f
tlw
'(caution no-default)
2
#:return-the-dialog? #t
#:dialog-mixin frame:focus-table-mixin))
(when tlw
(hash-set! open-dialogs tlw (cons dlg #f))
(hash-set! pending-editors tlw (list editor)))
(define revert? (case (send dlg show-and-return-results)
[(1) #t]
[(2) #f]))
(handle-dialog-closed tlw editor revert?)]
[(null? (cdr all-pending-editors))
;; first one => need to open the dialog, but it isn't dirty
(define dlg
(message+check-box/custom
(string-constant warning)
(get-autoload-warning-message all-pending-editors)
(string-constant dont-ask-again-always-current)
(string-constant revert)
(string-constant ignore)
#f
tlw
'(caution no-default)
2
#:return-the-dialog? #t
#:dialog-mixin frame:focus-table-mixin))
(when tlw
(hash-set! open-dialogs tlw (cons dlg #t))
(hash-set! pending-editors tlw (list editor)))
(define-values (button checked?) (send dlg show-and-return-results))
(define revert? (case button
[(1) #t]
[(2) #f]))
(when checked?
;; setting the preference will start the monitor
;; if `answer` is #t
(preferences:set 'framework:autoload revert?))
(handle-dialog-closed tlw editor revert?)]
[else
;; dialog is already open, see if we need to tweak the text
;; here we know that tlw ≠ #f
(match-define (cons dlg has-check?) (hash-ref open-dialogs tlw))
(hash-set! pending-editors tlw all-pending-editors)
(define any-existing-modified?
(for/or ([ed (in-list already-pending-editors)])
(send ed is-modified?)))
(define this-one-modified? (send editor is-modified?))
here we know that at least one is clean
(when this-one-modified? ;; here we know that we are dirty
here we know we are the first dirty one
;; which means we need to update the label of the checkbox
(send dlg set-check-label
(string-constant
dont-ask-again-always-current/clean-buffer)))))
(define new-dialog-message
(get-autoload-warning-message all-pending-editors))
(send dlg set-message new-dialog-message)])))
(define (get-autoload-warning-message currently-pending-editors)
(define number-of-pending-editors (length currently-pending-editors))
(define all-dirty?
(for/and ([ed (in-list currently-pending-editors)])
(send ed is-modified?)))
(define any-dirty?
(for/or ([ed (in-list currently-pending-editors)])
(send ed is-modified?)))
(cond
[(not any-dirty?)
;; none are dirty
(cond
[(= 1 number-of-pending-editors)
(format
(string-constant autoload-file-changed-on-disk/with-name)
(send (car currently-pending-editors) get-filename))]
[else
(apply
string-append
(string-constant autoload-files-changed-on-disk/with-name)
(for/list ([f (in-list currently-pending-editors)])
(format "\n ~a" (send f get-filename))))])]
[all-dirty?
(cond
[(= 1 number-of-pending-editors)
(format
(string-constant autoload-file-changed-on-disk-editor-dirty/with-name)
(send (car currently-pending-editors) get-filename))]
[else
(apply
string-append
(string-constant autoload-files-changed-on-disk-editor-dirty/with-name)
(for/list ([f (in-list currently-pending-editors)])
(format "\n ~a" (send f get-filename))))])]
[else
mixture of clean and dirty .. in this case we know there is n't just one file
(apply
string-append
(string-constant autoload-files-changed-on-disk-editor-dirty&clean/with-name)
(for/list ([f (in-list currently-pending-editors)])
(format "\n ~a~a"
(send f get-filename)
(if (send f is-modified?)
" ◇"
""))))]))
(define (handle-dialog-closed tlw editor revert?)
(cond
[tlw
(define all-pending-editors (hash-ref pending-editors tlw))
(hash-remove! open-dialogs tlw)
(hash-remove! pending-editors tlw)
(when revert?
(for ([ed (in-list all-pending-editors)])
(send ed autoload-do-revert)))]
[else
(when revert?
(send editor autoload-do-revert))]))
(define autoload-mixin
(mixin (editor:basic<%>) (autoload<%>)
(inherit get-filename load-file
begin-edit-sequence end-edit-sequence
is-modified?)
(define/augment (on-load-file path format)
(on-load/save-file path)
(inner (void) on-load-file path format))
(define/augment (after-load-file success?)
(after-load/save-file)
(inner (void) after-load-file success?))
(define/augment (on-save-file path format)
(on-load/save-file path)
(inner (void) on-load-file path format))
(define/augment (after-save-file success?)
(after-load/save-file)
(inner (void) after-load-file success?))
(define on/after-communication-channel #f)
(define/private (on-load/save-file path)
(unless (editor:doing-autosave?)
(define evt
(and (preferences:get 'framework:autoload)
(filesystem-change-evt path (λ () #f))))
(when evt (monitored-file-sha1-will-change this))
(set! on/after-communication-channel
(vector path evt))))
(define/private (after-load/save-file)
(unless (editor:doing-autosave?)
(match on/after-communication-channel
[(vector path (? filesystem-change-evt? evt))
(monitor-a-file this path evt (current-eventspace))]
[(vector path #f)
;; event creation failed or the preference is turned off
(void)])
(set! on/after-communication-channel #f)))
(define/override (set-filename filename [temporary? #f])
(unless on/after-communication-channel
;; if the filename changes but we aren't doing a
;; save or a load, then, well, just give up
;; if the file is saved, later on, we'll start
;; the monitoring process again
(un-monitor-a-file this))
(super set-filename filename temporary?))
(define/override (update-sha1? path)
(cond
[(editor:doing-autosave?) #f]
[else (super update-sha1? path)]))
(define/augment (on-close)
(un-monitor-a-file this)
(inner (void) on-close))
;; intentionally not a method; ensures
;; the callback stays registered with the
;; preferences system as as long as `this`
;; is held onto
(define pref-callback
(λ (p v)
(case v
[(#f) (un-monitor-a-file this)]
[(#t ask)
(define path (get-filename))
(when path
(monitor-a-file this
path
(filesystem-change-evt path (λ () #f))
(current-eventspace)))])))
(preferences:add-callback 'framework:autoload pref-callback #t)
(define/public (autoload-file-changed)
(define pref (preferences:get 'framework:autoload))
(cond
[(or (is-modified?) (equal? 'ask pref))
(handle-autoload-file-changed&need-dialog this)]
[pref
(autoload-do-revert)]
[else
(un-monitor-a-file this)]))
(define/public (autoload-do-revert)
(define b (box #f))
(define filename (get-filename b))
(when (and filename
(not (unbox b)))
(define start
(if (is-a? this text%)
(send this get-start-position)
#f))
(begin-edit-sequence)
(define failed?
(with-handlers ([exn:fail? (λ (x) #t)])
(load-file filename 'guess #f)
#f))
(unless failed?
(when (is-a? this text%)
(send this set-position start start)))
(end-edit-sequence)))
(super-new)
(inherit enable-sha1)
(enable-sha1)))
(define (monitor-a-file txt path evt eventspace)
(define the-sha1 (send txt get-file-sha1))
(channel-put monitor-a-file-chan (vector txt path the-sha1 evt eventspace)))
(define monitor-a-file-chan (make-channel))
(define (monitored-file-sha1-will-change txt)
(channel-put sha1-will-change-chan txt))
(define sha1-will-change-chan (make-channel))
(define (un-monitor-a-file txt)
(channel-put unmonitor-a-file-chan txt))
(define unmonitor-a-file-chan (make-channel))
(void
(thread
(λ ()
;; path: path-string?
;; evt: filesystem-change-evt?
the - sha1 : ( or / c ' unknown - check ' unknown - no - check bytes ? )
-- the two symbols mean we do n't know the sha1 should be
;; 'unknown-check means the evt has woken up and so when
we get the sha1 we should check the file and
;; 'unknown-no-check means that the evt hasn't yet woken up
bytes ? is the sha1
;; eventspace: eventspace?
(struct monitored (path evt the-sha1 eventspace) #:transparent)
state : hash[txt -o > monitored ? ]
(let loop ([state (hash)])
(apply
sync
(handle-evt
unmonitor-a-file-chan
(λ (txt)
(define old (hash-ref state txt #f))
(when old (filesystem-change-evt-cancel (monitored-evt old)))
(loop (hash-remove state txt))))
(handle-evt
monitor-a-file-chan
(λ (txt+path+eventspace)
(match-define (vector txt path the-sha1 evt eventspace)
txt+path+eventspace)
(define old (hash-ref state txt #f))
(when old (filesystem-change-evt-cancel (monitored-evt old)))
(loop (hash-set state
txt
(monitored path evt
the-sha1
eventspace)))))
(handle-evt
sha1-will-change-chan
(λ (txt)
(match (hash-ref state txt #f)
[(? monitored? old)
(loop (hash-set state txt
(struct-copy monitored old
[the-sha1 'unknown-no-check])))]
[#f (loop state)])))
(for/list ([(txt a-monitored) (in-hash state)])
(match-define (monitored path evt the-sha1 eventspace)
a-monitored)
(handle-evt
evt
(λ (_)
;; create the new evt before we look at the file's
;; sha1 to avoid any moment where the file might
;; be unmonitored.
(define new-evt (filesystem-change-evt path (λ () #f)))
(define state-of-file
(with-handlers ([exn:fail:filesystem? (λ (x) 'failed)])
(cond
[(symbol? the-sha1) 'need-to-wait]
[(equal? the-sha1 (call-with-input-file path sha1-bytes))
'unchanged]
[else 'changed])))
(match state-of-file
['need-to-wait
(cond
[new-evt
(loop (hash-set state txt
(struct-copy monitored a-monitored
[the-sha1 'unknown-check]
[evt new-evt])))]
[else
;; we failed to create an evt; give up on
;; monitoring this file (can we do better?)
(loop (hash-remove state txt))])]
['unchanged
;; this appears to be a spurious wakeup
;; use the new evt to wait again
(cond
[new-evt
(loop (hash-set state txt
(struct-copy monitored a-monitored
[evt new-evt])))]
[else
(loop (hash-remove state txt))])]
['failed
;; an exception was raised above so we don't notify,
;; but also stop monitoring the file
(when new-evt (filesystem-change-evt-cancel new-evt))
(loop (hash-remove state txt))]
['changed
;; here we know that the content has a new hash
;; so it seems safe to safe to reload the buffer.
(parameterize ([current-eventspace eventspace])
(queue-callback
(λ ()
(send txt autoload-file-changed))))
;; we also reenable the monitor here
(loop (hash-set state txt
(struct-copy monitored a-monitored
[evt new-evt])))])))))))))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/framework/private/editor-autoload.rkt | racket | open-dialogs : hash[tlw -o> (cons/c dialog boolean)]
the dialogs that are currently being shown, paired with
a boolean that indicates if the initial dialog has a checkbox
editors where we are waiting for a reply from the user
invariant:
(hash-ref pending-editors tlw '()) = (cons ed eds)
⟺
(hash-ref open-dialogs tlw #f) ≠ #f
only called if we have to ask the user about what to do,
so we know that the `ask preference is set or window was dirty
first one => need to open the dialog, and it is dirty
first one => need to open the dialog, but it isn't dirty
setting the preference will start the monitor
if `answer` is #t
dialog is already open, see if we need to tweak the text
here we know that tlw ≠ #f
here we know that we are dirty
which means we need to update the label of the checkbox
none are dirty
event creation failed or the preference is turned off
if the filename changes but we aren't doing a
save or a load, then, well, just give up
if the file is saved, later on, we'll start
the monitoring process again
intentionally not a method; ensures
the callback stays registered with the
preferences system as as long as `this`
is held onto
path: path-string?
evt: filesystem-change-evt?
'unknown-check means the evt has woken up and so when
'unknown-no-check means that the evt hasn't yet woken up
eventspace: eventspace?
create the new evt before we look at the file's
sha1 to avoid any moment where the file might
be unmonitored.
we failed to create an evt; give up on
monitoring this file (can we do better?)
this appears to be a spurious wakeup
use the new evt to wait again
an exception was raised above so we don't notify,
but also stop monitoring the file
here we know that the content has a new hash
so it seems safe to safe to reload the buffer.
we also reenable the monitor here | #lang racket/unit
(require "sig.rkt"
"editor-sig.rkt"
"../preferences.rkt"
"focus-table.rkt"
string-constants
mred/mred-sig
racket/class
racket/match
file/sha1)
(import mred^
[prefix frame: framework:frame^]
[prefix editor: editor-misc^])
(export editor-autoload^)
(init-depend mred^)
(define autoload<%>
(interface (editor:basic<%>)))
(define-local-member-name autoload-file-changed autoload-do-revert)
(define open-dialogs (make-hash))
pending - editors : hash[tlw -o > ( listof editor<% > ) ]
(define pending-editors (make-hash))
(define (handle-autoload-file-changed&need-dialog editor)
(define tlw (send editor get-top-level-window))
when tlw=#f , this will be ' ( )
(unless (member editor already-pending-editors)
(define all-pending-editors (cons editor already-pending-editors))
(when tlw (hash-set! pending-editors tlw all-pending-editors))
(cond
[(and (null? (cdr all-pending-editors))
(send (car all-pending-editors) is-modified?))
(define dlg
(message-box/custom
(string-constant warning)
(get-autoload-warning-message all-pending-editors)
(string-constant revert)
(string-constant ignore)
#f
tlw
'(caution no-default)
2
#:return-the-dialog? #t
#:dialog-mixin frame:focus-table-mixin))
(when tlw
(hash-set! open-dialogs tlw (cons dlg #f))
(hash-set! pending-editors tlw (list editor)))
(define revert? (case (send dlg show-and-return-results)
[(1) #t]
[(2) #f]))
(handle-dialog-closed tlw editor revert?)]
[(null? (cdr all-pending-editors))
(define dlg
(message+check-box/custom
(string-constant warning)
(get-autoload-warning-message all-pending-editors)
(string-constant dont-ask-again-always-current)
(string-constant revert)
(string-constant ignore)
#f
tlw
'(caution no-default)
2
#:return-the-dialog? #t
#:dialog-mixin frame:focus-table-mixin))
(when tlw
(hash-set! open-dialogs tlw (cons dlg #t))
(hash-set! pending-editors tlw (list editor)))
(define-values (button checked?) (send dlg show-and-return-results))
(define revert? (case button
[(1) #t]
[(2) #f]))
(when checked?
(preferences:set 'framework:autoload revert?))
(handle-dialog-closed tlw editor revert?)]
[else
(match-define (cons dlg has-check?) (hash-ref open-dialogs tlw))
(hash-set! pending-editors tlw all-pending-editors)
(define any-existing-modified?
(for/or ([ed (in-list already-pending-editors)])
(send ed is-modified?)))
(define this-one-modified? (send editor is-modified?))
here we know that at least one is clean
here we know we are the first dirty one
(send dlg set-check-label
(string-constant
dont-ask-again-always-current/clean-buffer)))))
(define new-dialog-message
(get-autoload-warning-message all-pending-editors))
(send dlg set-message new-dialog-message)])))
(define (get-autoload-warning-message currently-pending-editors)
(define number-of-pending-editors (length currently-pending-editors))
(define all-dirty?
(for/and ([ed (in-list currently-pending-editors)])
(send ed is-modified?)))
(define any-dirty?
(for/or ([ed (in-list currently-pending-editors)])
(send ed is-modified?)))
(cond
[(not any-dirty?)
(cond
[(= 1 number-of-pending-editors)
(format
(string-constant autoload-file-changed-on-disk/with-name)
(send (car currently-pending-editors) get-filename))]
[else
(apply
string-append
(string-constant autoload-files-changed-on-disk/with-name)
(for/list ([f (in-list currently-pending-editors)])
(format "\n ~a" (send f get-filename))))])]
[all-dirty?
(cond
[(= 1 number-of-pending-editors)
(format
(string-constant autoload-file-changed-on-disk-editor-dirty/with-name)
(send (car currently-pending-editors) get-filename))]
[else
(apply
string-append
(string-constant autoload-files-changed-on-disk-editor-dirty/with-name)
(for/list ([f (in-list currently-pending-editors)])
(format "\n ~a" (send f get-filename))))])]
[else
mixture of clean and dirty .. in this case we know there is n't just one file
(apply
string-append
(string-constant autoload-files-changed-on-disk-editor-dirty&clean/with-name)
(for/list ([f (in-list currently-pending-editors)])
(format "\n ~a~a"
(send f get-filename)
(if (send f is-modified?)
" ◇"
""))))]))
(define (handle-dialog-closed tlw editor revert?)
(cond
[tlw
(define all-pending-editors (hash-ref pending-editors tlw))
(hash-remove! open-dialogs tlw)
(hash-remove! pending-editors tlw)
(when revert?
(for ([ed (in-list all-pending-editors)])
(send ed autoload-do-revert)))]
[else
(when revert?
(send editor autoload-do-revert))]))
(define autoload-mixin
(mixin (editor:basic<%>) (autoload<%>)
(inherit get-filename load-file
begin-edit-sequence end-edit-sequence
is-modified?)
(define/augment (on-load-file path format)
(on-load/save-file path)
(inner (void) on-load-file path format))
(define/augment (after-load-file success?)
(after-load/save-file)
(inner (void) after-load-file success?))
(define/augment (on-save-file path format)
(on-load/save-file path)
(inner (void) on-load-file path format))
(define/augment (after-save-file success?)
(after-load/save-file)
(inner (void) after-load-file success?))
(define on/after-communication-channel #f)
(define/private (on-load/save-file path)
(unless (editor:doing-autosave?)
(define evt
(and (preferences:get 'framework:autoload)
(filesystem-change-evt path (λ () #f))))
(when evt (monitored-file-sha1-will-change this))
(set! on/after-communication-channel
(vector path evt))))
(define/private (after-load/save-file)
(unless (editor:doing-autosave?)
(match on/after-communication-channel
[(vector path (? filesystem-change-evt? evt))
(monitor-a-file this path evt (current-eventspace))]
[(vector path #f)
(void)])
(set! on/after-communication-channel #f)))
(define/override (set-filename filename [temporary? #f])
(unless on/after-communication-channel
(un-monitor-a-file this))
(super set-filename filename temporary?))
(define/override (update-sha1? path)
(cond
[(editor:doing-autosave?) #f]
[else (super update-sha1? path)]))
(define/augment (on-close)
(un-monitor-a-file this)
(inner (void) on-close))
(define pref-callback
(λ (p v)
(case v
[(#f) (un-monitor-a-file this)]
[(#t ask)
(define path (get-filename))
(when path
(monitor-a-file this
path
(filesystem-change-evt path (λ () #f))
(current-eventspace)))])))
(preferences:add-callback 'framework:autoload pref-callback #t)
(define/public (autoload-file-changed)
(define pref (preferences:get 'framework:autoload))
(cond
[(or (is-modified?) (equal? 'ask pref))
(handle-autoload-file-changed&need-dialog this)]
[pref
(autoload-do-revert)]
[else
(un-monitor-a-file this)]))
(define/public (autoload-do-revert)
(define b (box #f))
(define filename (get-filename b))
(when (and filename
(not (unbox b)))
(define start
(if (is-a? this text%)
(send this get-start-position)
#f))
(begin-edit-sequence)
(define failed?
(with-handlers ([exn:fail? (λ (x) #t)])
(load-file filename 'guess #f)
#f))
(unless failed?
(when (is-a? this text%)
(send this set-position start start)))
(end-edit-sequence)))
(super-new)
(inherit enable-sha1)
(enable-sha1)))
(define (monitor-a-file txt path evt eventspace)
(define the-sha1 (send txt get-file-sha1))
(channel-put monitor-a-file-chan (vector txt path the-sha1 evt eventspace)))
(define monitor-a-file-chan (make-channel))
(define (monitored-file-sha1-will-change txt)
(channel-put sha1-will-change-chan txt))
(define sha1-will-change-chan (make-channel))
(define (un-monitor-a-file txt)
(channel-put unmonitor-a-file-chan txt))
(define unmonitor-a-file-chan (make-channel))
(void
(thread
(λ ()
the - sha1 : ( or / c ' unknown - check ' unknown - no - check bytes ? )
-- the two symbols mean we do n't know the sha1 should be
we get the sha1 we should check the file and
bytes ? is the sha1
(struct monitored (path evt the-sha1 eventspace) #:transparent)
state : hash[txt -o > monitored ? ]
(let loop ([state (hash)])
(apply
sync
(handle-evt
unmonitor-a-file-chan
(λ (txt)
(define old (hash-ref state txt #f))
(when old (filesystem-change-evt-cancel (monitored-evt old)))
(loop (hash-remove state txt))))
(handle-evt
monitor-a-file-chan
(λ (txt+path+eventspace)
(match-define (vector txt path the-sha1 evt eventspace)
txt+path+eventspace)
(define old (hash-ref state txt #f))
(when old (filesystem-change-evt-cancel (monitored-evt old)))
(loop (hash-set state
txt
(monitored path evt
the-sha1
eventspace)))))
(handle-evt
sha1-will-change-chan
(λ (txt)
(match (hash-ref state txt #f)
[(? monitored? old)
(loop (hash-set state txt
(struct-copy monitored old
[the-sha1 'unknown-no-check])))]
[#f (loop state)])))
(for/list ([(txt a-monitored) (in-hash state)])
(match-define (monitored path evt the-sha1 eventspace)
a-monitored)
(handle-evt
evt
(λ (_)
(define new-evt (filesystem-change-evt path (λ () #f)))
(define state-of-file
(with-handlers ([exn:fail:filesystem? (λ (x) 'failed)])
(cond
[(symbol? the-sha1) 'need-to-wait]
[(equal? the-sha1 (call-with-input-file path sha1-bytes))
'unchanged]
[else 'changed])))
(match state-of-file
['need-to-wait
(cond
[new-evt
(loop (hash-set state txt
(struct-copy monitored a-monitored
[the-sha1 'unknown-check]
[evt new-evt])))]
[else
(loop (hash-remove state txt))])]
['unchanged
(cond
[new-evt
(loop (hash-set state txt
(struct-copy monitored a-monitored
[evt new-evt])))]
[else
(loop (hash-remove state txt))])]
['failed
(when new-evt (filesystem-change-evt-cancel new-evt))
(loop (hash-remove state txt))]
['changed
(parameterize ([current-eventspace eventspace])
(queue-callback
(λ ()
(send txt autoload-file-changed))))
(loop (hash-set state txt
(struct-copy monitored a-monitored
[evt new-evt])))])))))))))
|
2a06c9cf73198fb11b1b953c15b4b30aac0a45efeae53ba26fe4a699d86d1660 | yuce/teacup | teacup_utils.erl | Copyright ( c ) 2016 , < > .
% All rights reserved.
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
% * The names of its contributors may not be used to endorse or promote
% products derived from this software without specific prior written
% permission.
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-module(teacup_utils).
-export([exported_functions/1]).
%% == API
exported_functions(Module) ->
Exported = Module:module_info(exports),
sets:from_list(Exported).
| null | https://raw.githubusercontent.com/yuce/teacup/2ab8a3c09b0dc44190c09ff7681bfe7fa8c88506/src/teacup_utils.erl | erlang | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
== API | Copyright ( c ) 2016 , < > .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-module(teacup_utils).
-export([exported_functions/1]).
exported_functions(Module) ->
Exported = Module:module_info(exports),
sets:from_list(Exported).
|
ef88f330a7c274ca32c3a112a5ec84ea0b644c14ca93527dfc7a599367605bb8 | erkin/gophwr | main.rkt | #lang racket/base
(require racket/cmdline)
(require (only-in openssl
ssl-available? ssl-load-fail-reason))
(require "const.rkt"
"config.rkt"
"window.rkt")
(define addresses
(command-line
#:program project-name
#:once-each
(("--ssl" "--tls")
"Start with TLS mode enabled"
(tls-enabled? #t))
(("--debug")
"Enable debug menu"
(debug-mode? #t))
(("--version" "-v")
"Show version and licence information"
(displayln version-message)
(exit))
;; List of arguments to navigate to at startup.
;; The reason we do it with a list is to be able to handle multiple
;; addresses as separate tabs in the future.
#:args addresses
addresses))
(module+ main
(when (tls-enabled?)
(unless ssl-available?
(raise-user-error "TLS not available:"
ssl-load-fail-reason
"Aborting.")
(exit 1)))
(initialise-window)
(if (null? addresses)
;; Go to homepage if no argument is given.
(if homepage
(go-to homepage #:history #t)
Blank page if homepage is # f.
(clear-page page-text))
Go to first address given at commandline .
(go-to (car addresses) #:history #t)))
| null | https://raw.githubusercontent.com/erkin/gophwr/b4001202fa001fe0b486cb756bc9681f1880dc8f/src/main.rkt | racket | List of arguments to navigate to at startup.
The reason we do it with a list is to be able to handle multiple
addresses as separate tabs in the future.
Go to homepage if no argument is given. | #lang racket/base
(require racket/cmdline)
(require (only-in openssl
ssl-available? ssl-load-fail-reason))
(require "const.rkt"
"config.rkt"
"window.rkt")
(define addresses
(command-line
#:program project-name
#:once-each
(("--ssl" "--tls")
"Start with TLS mode enabled"
(tls-enabled? #t))
(("--debug")
"Enable debug menu"
(debug-mode? #t))
(("--version" "-v")
"Show version and licence information"
(displayln version-message)
(exit))
#:args addresses
addresses))
(module+ main
(when (tls-enabled?)
(unless ssl-available?
(raise-user-error "TLS not available:"
ssl-load-fail-reason
"Aborting.")
(exit 1)))
(initialise-window)
(if (null? addresses)
(if homepage
(go-to homepage #:history #t)
Blank page if homepage is # f.
(clear-page page-text))
Go to first address given at commandline .
(go-to (car addresses) #:history #t)))
|
fb3e176d867842ea2c230e8dab7be4cab4cc8185934c75b51df0f5af774f2a71 | mstksg/backprop-learn | State.hs | # LANGUAGE ApplicativeDo #
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
module Backprop.Learn.Model.State (
-- * To and from statelessness
trainState, deState, deStateD, zeroState, dummyState
-- * Manipulate model states
, unroll, unrollFinal, recurrent
) where
import Backprop.Learn.Model.Types
import Control.Monad.Primitive
import Control.Monad.Trans.State
import Data.Bifunctor
import Data.Foldable
import Data.Type.Functor.Product
import Data.Type.Tuple
import Numeric.Backprop
import qualified System.Random.MWC as MWC
-- | Make a model stateless by converting the state to a trained parameter,
-- and dropping the modified state from the result.
--
One of the ways to make a model stateless for training purposes . Useful
when used after ' Unroll ' . See ' DeState ' , as well .
--
-- Its parameters are:
--
-- * If the input has no parameters, just the initial state.
-- * If the input has a parameter, a ':#' of that parameter and initial state.
trainState
:: forall p s a b.
( PureProd Maybe p
, PureProd Maybe s
, AllConstrainedProd Backprop p
, AllConstrainedProd Backprop s
)
=> Model p s a b
-> Model (p :#? s) 'Nothing a b
trainState = withModelFunc $ \f (p :#? s) x n_ ->
(second . const) n_ <$> f p x s
-- | Make a model stateless by pre-applying a fixed state (or a stochastic
-- one with fixed stribution) and dropping the modified state from the
-- result.
--
One of the ways to make a model stateless for training purposes . Useful
when used after ' Unroll ' . See ' TrainState ' , as well .
deState
:: s
-> (forall m. PrimMonad m => MWC.Gen (PrimState m) -> m s)
-> Model p ('Just s) a b
-> Model p 'Nothing a b
deState s sStoch f = Model
{ runLearn = \p x n_ ->
(second . const) n_ $ runLearn f p x (PJust (auto s))
, runLearnStoch = \g p x n_ -> do
s' <- sStoch g
(second . const) n_ <$> runLearnStoch f g p x (PJust (auto s'))
}
-- | 'deState', except the state is always the same even in stochastic
-- mode.
deStateD
:: s
-> Model p ('Just s) a b
-> Model p 'Nothing a b
deStateD s = deState s (const (pure s))
| ' deState ' with a constant state of 0 .
zeroState
:: Num s
=> Model p ('Just s) a b
-> Model p 'Nothing a b
zeroState = deStateD 0
| Unroll a ( usually ) stateful model into one taking a vector of
-- sequential inputs.
--
-- Basically applies the model to every item of input and returns all of
-- the results, but propagating the state between every step.
--
-- Useful when used before 'trainState' or 'deState'. See
' unrollTrainState ' and ' unrollDeState ' .
--
-- Compare to 'feedbackTrace', which, instead of receiving a vector of
-- sequential inputs, receives a single input and uses its output as the
-- next input.
unroll
:: (Traversable t, Backprop a, Backprop b)
=> Model p s a b
-> Model p s (t a) (t b)
unroll = withModelFunc $ \f p xs s ->
(fmap . first) collectVar
. flip runStateT s
. traverse (StateT . f p)
. sequenceVar
$ xs
-- | Version of 'unroll' that only keeps the "final" result, dropping all
-- of the intermediate results.
--
-- Turns a stateful model into one that runs the model repeatedly on
-- multiple inputs sequentially and outputs the final result after seeing
-- all items.
--
-- Note will be partial if given an empty sequence.
unrollFinal
:: (Traversable t, Backprop a)
=> Model p s a b
-> Model p s (t a) b
unrollFinal = withModelFunc $ \f p xs s0 ->
foldlM (\(_, s) x -> f p x s)
(undefined, s0)
(sequenceVar xs)
-- | Fix a part of a parameter of a model to be (a function of) the
-- /previous/ ouput of the model itself.
--
-- Essentially, takes a \( X \times Y \rightarrow Z \) into a /stateful/
-- \( X \rightarrow Z \), where the Y is given by a function of the
-- /previous output/ of the model.
--
-- Essentially makes a model "recurrent": it receives its previous output
-- as input.
--
-- See 'fcr' for an application.
recurrent
:: forall p s ab a b c.
( KnownMayb s
( AllConstrainedProd Backprop s
, PureProd Maybe s
, Backprop a
, Backprop b
)
=> (ab -> (a, b)) -- ^ split
-> (a -> b -> ab) -- ^ join
-> BFunc c b -- ^ store state
-> Model p s ab c
-> Model p (s :#? 'Just b) a c
recurrent spl joi sto = withModelFunc $ \f p x (s :#? y) -> do
(z, s') <- f p (isoVar2 joi spl x (fromPJust y)) s
pure (z, s' :#? PJust (sto z))
-- | Give a stateless model a "dummy" state. For now, useful for using
-- with combinators like 'deState' that require state. However, 'deState'
-- could also be made more lenient (to accept non stateful models) in the
-- future.
--
-- Also useful for usage with combinators like 'Control.Category..' from
-- "Control.Category" that requires all input models to share common state.
dummyState
:: forall s p a b. ()
=> Model p 'Nothing a b
-> Model p s a b
dummyState = withModelFunc $ \f p x s ->
(second . const) s <$> f p x PNothing
| null | https://raw.githubusercontent.com/mstksg/backprop-learn/59aea530a0fad45de6d18b9a723914d1d66dc222/src/Backprop/Learn/Model/State.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE PatternSynonyms #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeInType #
# LANGUAGE TypeOperators #
* To and from statelessness
* Manipulate model states
| Make a model stateless by converting the state to a trained parameter,
and dropping the modified state from the result.
Its parameters are:
* If the input has no parameters, just the initial state.
* If the input has a parameter, a ':#' of that parameter and initial state.
| Make a model stateless by pre-applying a fixed state (or a stochastic
one with fixed stribution) and dropping the modified state from the
result.
| 'deState', except the state is always the same even in stochastic
mode.
sequential inputs.
Basically applies the model to every item of input and returns all of
the results, but propagating the state between every step.
Useful when used before 'trainState' or 'deState'. See
Compare to 'feedbackTrace', which, instead of receiving a vector of
sequential inputs, receives a single input and uses its output as the
next input.
| Version of 'unroll' that only keeps the "final" result, dropping all
of the intermediate results.
Turns a stateful model into one that runs the model repeatedly on
multiple inputs sequentially and outputs the final result after seeing
all items.
Note will be partial if given an empty sequence.
| Fix a part of a parameter of a model to be (a function of) the
/previous/ ouput of the model itself.
Essentially, takes a \( X \times Y \rightarrow Z \) into a /stateful/
\( X \rightarrow Z \), where the Y is given by a function of the
/previous output/ of the model.
Essentially makes a model "recurrent": it receives its previous output
as input.
See 'fcr' for an application.
^ split
^ join
^ store state
| Give a stateless model a "dummy" state. For now, useful for using
with combinators like 'deState' that require state. However, 'deState'
could also be made more lenient (to accept non stateful models) in the
future.
Also useful for usage with combinators like 'Control.Category..' from
"Control.Category" that requires all input models to share common state. | # LANGUAGE ApplicativeDo #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Backprop.Learn.Model.State (
trainState, deState, deStateD, zeroState, dummyState
, unroll, unrollFinal, recurrent
) where
import Backprop.Learn.Model.Types
import Control.Monad.Primitive
import Control.Monad.Trans.State
import Data.Bifunctor
import Data.Foldable
import Data.Type.Functor.Product
import Data.Type.Tuple
import Numeric.Backprop
import qualified System.Random.MWC as MWC
One of the ways to make a model stateless for training purposes . Useful
when used after ' Unroll ' . See ' DeState ' , as well .
trainState
:: forall p s a b.
( PureProd Maybe p
, PureProd Maybe s
, AllConstrainedProd Backprop p
, AllConstrainedProd Backprop s
)
=> Model p s a b
-> Model (p :#? s) 'Nothing a b
trainState = withModelFunc $ \f (p :#? s) x n_ ->
(second . const) n_ <$> f p x s
One of the ways to make a model stateless for training purposes . Useful
when used after ' Unroll ' . See ' TrainState ' , as well .
deState
:: s
-> (forall m. PrimMonad m => MWC.Gen (PrimState m) -> m s)
-> Model p ('Just s) a b
-> Model p 'Nothing a b
deState s sStoch f = Model
{ runLearn = \p x n_ ->
(second . const) n_ $ runLearn f p x (PJust (auto s))
, runLearnStoch = \g p x n_ -> do
s' <- sStoch g
(second . const) n_ <$> runLearnStoch f g p x (PJust (auto s'))
}
deStateD
:: s
-> Model p ('Just s) a b
-> Model p 'Nothing a b
deStateD s = deState s (const (pure s))
| ' deState ' with a constant state of 0 .
zeroState
:: Num s
=> Model p ('Just s) a b
-> Model p 'Nothing a b
zeroState = deStateD 0
| Unroll a ( usually ) stateful model into one taking a vector of
' unrollTrainState ' and ' unrollDeState ' .
unroll
:: (Traversable t, Backprop a, Backprop b)
=> Model p s a b
-> Model p s (t a) (t b)
unroll = withModelFunc $ \f p xs s ->
(fmap . first) collectVar
. flip runStateT s
. traverse (StateT . f p)
. sequenceVar
$ xs
unrollFinal
:: (Traversable t, Backprop a)
=> Model p s a b
-> Model p s (t a) b
unrollFinal = withModelFunc $ \f p xs s0 ->
foldlM (\(_, s) x -> f p x s)
(undefined, s0)
(sequenceVar xs)
recurrent
:: forall p s ab a b c.
( KnownMayb s
( AllConstrainedProd Backprop s
, PureProd Maybe s
, Backprop a
, Backprop b
)
-> Model p s ab c
-> Model p (s :#? 'Just b) a c
recurrent spl joi sto = withModelFunc $ \f p x (s :#? y) -> do
(z, s') <- f p (isoVar2 joi spl x (fromPJust y)) s
pure (z, s' :#? PJust (sto z))
dummyState
:: forall s p a b. ()
=> Model p 'Nothing a b
-> Model p s a b
dummyState = withModelFunc $ \f p x s ->
(second . const) s <$> f p x PNothing
|
9f95ec956f9391243a21f770bbcbbd9bd2b28aab2f27ac138f67a5bd52c5552b | ruricolist/serapeum | hooks.lisp | (in-package #:serapeum)
(defvar *hook* nil
"The hook currently being run.")
(defgeneric add-hook (hook fn &key append)
(:documentation "Add FN to the value of HOOK.")
(:method ((hook symbol) fn &key append)
(declare (type (or function symbol) fn))
(synchronized (hook)
(if (not append)
(pushnew fn (symbol-value hook))
(unless (member fn (symbol-value hook))
(appendf (symbol-value hook) (list fn)))))))
(defgeneric remove-hook (hook fn)
(:documentation "Remove FN from the symbol value of HOOK.")
(:method ((hook symbol) fn)
(synchronized (hook)
(removef (symbol-value hook) fn))))
(defmacro with-hook-restart (&body body)
`(with-simple-restart (continue "Call next function in hook ~s" *hook*)
,@body))
(defun run-hooks (&rest hooks)
"Run all the hooks in HOOKS, without arguments.
The variable `*hook*' is bound to the name of each hook as it is being
run."
(dolist (*hook* hooks)
(run-hook *hook*)))
(defgeneric run-hook (hook &rest args)
(:documentation "Apply each function in HOOK to ARGS.")
(:method ((*hook* symbol) &rest args)
(dolist (fn (symbol-value *hook*))
(with-hook-restart
(apply fn args)))))
(defgeneric run-hook-until-failure (hook &rest args)
(:documentation "Like `run-hook-with-args', but quit once a function returns nil.")
(:method ((*hook* symbol) &rest args)
(loop for fn in (symbol-value *hook*)
always (apply fn args))))
(defgeneric run-hook-until-success (hook &rest args)
(:documentation "Like `run-hook-with-args', but quit once a function returns
non-nil.")
(:method ((*hook* symbol) &rest args)
(loop for fn in (symbol-value *hook*)
thereis (apply fn args))))
| null | https://raw.githubusercontent.com/ruricolist/serapeum/d98b4863d7cdcb8a1ed8478cc44ab41bdad5635b/hooks.lisp | lisp | (in-package #:serapeum)
(defvar *hook* nil
"The hook currently being run.")
(defgeneric add-hook (hook fn &key append)
(:documentation "Add FN to the value of HOOK.")
(:method ((hook symbol) fn &key append)
(declare (type (or function symbol) fn))
(synchronized (hook)
(if (not append)
(pushnew fn (symbol-value hook))
(unless (member fn (symbol-value hook))
(appendf (symbol-value hook) (list fn)))))))
(defgeneric remove-hook (hook fn)
(:documentation "Remove FN from the symbol value of HOOK.")
(:method ((hook symbol) fn)
(synchronized (hook)
(removef (symbol-value hook) fn))))
(defmacro with-hook-restart (&body body)
`(with-simple-restart (continue "Call next function in hook ~s" *hook*)
,@body))
(defun run-hooks (&rest hooks)
"Run all the hooks in HOOKS, without arguments.
The variable `*hook*' is bound to the name of each hook as it is being
run."
(dolist (*hook* hooks)
(run-hook *hook*)))
(defgeneric run-hook (hook &rest args)
(:documentation "Apply each function in HOOK to ARGS.")
(:method ((*hook* symbol) &rest args)
(dolist (fn (symbol-value *hook*))
(with-hook-restart
(apply fn args)))))
(defgeneric run-hook-until-failure (hook &rest args)
(:documentation "Like `run-hook-with-args', but quit once a function returns nil.")
(:method ((*hook* symbol) &rest args)
(loop for fn in (symbol-value *hook*)
always (apply fn args))))
(defgeneric run-hook-until-success (hook &rest args)
(:documentation "Like `run-hook-with-args', but quit once a function returns
non-nil.")
(:method ((*hook* symbol) &rest args)
(loop for fn in (symbol-value *hook*)
thereis (apply fn args))))
| |
a1ec9b6e0d8c4f76e90d1d043959cbfdbacdd5d36cdbd36fbb0f9469ce4e9bb8 | mirage/mirage | config_dash_in_name.ml | open Mirage
let main = main "App" job
let key =
let doc = Key.Arg.info ~doc:"How to say hello." [ "hello" ] in
Key.(create "hello" Arg.(opt string "Hello World!" doc))
let () = register ~keys:[ Key.v key ] ~src:`None "noop-functor.v0" [ main ]
| null | https://raw.githubusercontent.com/mirage/mirage/662bdef6e0cf3ded5ced597f0fa517542873c6db/test/mirage/query/config_dash_in_name.ml | ocaml | open Mirage
let main = main "App" job
let key =
let doc = Key.Arg.info ~doc:"How to say hello." [ "hello" ] in
Key.(create "hello" Arg.(opt string "Hello World!" doc))
let () = register ~keys:[ Key.v key ] ~src:`None "noop-functor.v0" [ main ]
| |
dd6c3a7f68fb9df54f6a5a60aae5368a98aa0acce43a7506cfb8ae9945eb0096 | robertmeta/cowboy-examples | hello_world_chunked_handler.erl | -module(hello_world_chunked_handler).
-export([init/3, handle/2, terminate/2]).
init({tcp, http}, Req, _Opts) ->
{ok, Req, undefined_state}.
handle(Req, State) ->
{ok, Reply} = cowboy_http_req:chunked_reply(200, Req),
cowboy_http_req:chunk("Hello\r\n", Reply),
timer:sleep(1000),
cowboy_http_req:chunk("World, ", Reply),
timer:sleep(1000),
cowboy_http_req:chunk("Chunked!", Reply),
{ok, Reply, State}.
terminate(_Req, _State) ->
ok.
| null | https://raw.githubusercontent.com/robertmeta/cowboy-examples/d03c289c9fb0d750eca11e3f1671e74d1841bd09/apps/hello_world_chunked/src/hello_world_chunked_handler.erl | erlang | -module(hello_world_chunked_handler).
-export([init/3, handle/2, terminate/2]).
init({tcp, http}, Req, _Opts) ->
{ok, Req, undefined_state}.
handle(Req, State) ->
{ok, Reply} = cowboy_http_req:chunked_reply(200, Req),
cowboy_http_req:chunk("Hello\r\n", Reply),
timer:sleep(1000),
cowboy_http_req:chunk("World, ", Reply),
timer:sleep(1000),
cowboy_http_req:chunk("Chunked!", Reply),
{ok, Reply, State}.
terminate(_Req, _State) ->
ok.
| |
1a99a9869a6df9ea11d9458c0deca0dc734104d0d09d9ef6c081340244a0e234 | rabbitmq/rabbitmq-mochiweb | rabbit_web_dispatch_util.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2010 - 2013 VMware , Inc. All rights reserved .
%%
-module(rabbit_web_dispatch_util).
-export([parse_auth_header/1]).
-export([relativise/2]).
parse_auth_header(Header) ->
case Header of
"Basic " ++ Base64 ->
Str = base64:mime_decode_to_string(Base64),
case string:chr(Str, $:) of
0 -> invalid;
N -> [list_to_binary(string:sub_string(Str, 1, N - 1)),
list_to_binary(string:sub_string(Str, N + 1))]
end;
_ ->
invalid
end.
relativise("/" ++ F, "/" ++ T) ->
From = string:tokens(F, "/"),
To = string:tokens(T, "/"),
string:join(relativise0(From, To), "/").
relativise0([H], [H|_] = To) ->
To;
relativise0([H|From], [H|To]) ->
relativise0(From, To);
relativise0(From, []) ->
lists:duplicate(length(From), "..");
relativise0([_|From], To) ->
lists:duplicate(length(From), "..") ++ To;
relativise0([], To) ->
To.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-mochiweb/4dfbdd9b39e5c7fef64c230562305eead0c61973/src/rabbit_web_dispatch_util.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
| The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2010 - 2013 VMware , Inc. All rights reserved .
-module(rabbit_web_dispatch_util).
-export([parse_auth_header/1]).
-export([relativise/2]).
parse_auth_header(Header) ->
case Header of
"Basic " ++ Base64 ->
Str = base64:mime_decode_to_string(Base64),
case string:chr(Str, $:) of
0 -> invalid;
N -> [list_to_binary(string:sub_string(Str, 1, N - 1)),
list_to_binary(string:sub_string(Str, N + 1))]
end;
_ ->
invalid
end.
relativise("/" ++ F, "/" ++ T) ->
From = string:tokens(F, "/"),
To = string:tokens(T, "/"),
string:join(relativise0(From, To), "/").
relativise0([H], [H|_] = To) ->
To;
relativise0([H|From], [H|To]) ->
relativise0(From, To);
relativise0(From, []) ->
lists:duplicate(length(From), "..");
relativise0([_|From], To) ->
lists:duplicate(length(From), "..") ++ To;
relativise0([], To) ->
To.
|
426851378fa9d54c5d6788a7583538cd4a38e7b35f0b874200a38fab68d938cb | tatut/ripley | main.clj | (ns filetree.main
(:require [org.httpkit.server :as server]
[compojure.core :refer [routes GET]]
[ripley.html :as h]
[ripley.live.context :as context]
[ripley.live.source :as source]
[ripley.live.protocols :as p]
[ripley.js :as js]
[clojure.string :as str])
(:import (java.io File)))
(defonce server (atom nil))
;; Some file utilities
(defn- matching-files [path name-filter]
(mapcat
(fn [file]
(if (.isDirectory file)
(matching-files file name-filter)
(when (str/includes? (.getName file) name-filter)
[file])))
(.listFiles path)))
(defn- paths-leading-to-matching-files [path matching-files]
(let [->absolute #(.getAbsolutePath %)
top-path (->absolute path)]
(if (empty? matching-files)
#{}
(into #{top-path}
(comp
(mapcat (fn [matching-file]
(take-while #(not= top-path (->absolute %))
(drop 1 (iterate #(.getParentFile %) matching-file)))))
(map ->absolute))
matching-files))))
;; UI components
(declare folder)
(defn files [{:keys [name-filter] :as ctx} path]
(h/html
[:div {:style "padding-left: 1rem;"}
[:div
[::h/for [file (.listFiles path)
:let [name (.getName file)]]
[::h/if (.isDirectory file)
(folder ctx file)
[:div {:style [::h/live (source/computed
#(or (str/blank? %)
(str/includes? name %)) name-filter)
#(if %
"padding-left: 1.5rem;"
"display: none;")]} name]]]]]))
(defn folder [{:keys [expanded toggle-expanded!] :as ctx} path]
(let [name (-> path .getCanonicalFile .getName)
id (.getAbsolutePath path)
expanded? (source/computed #(contains? % id) expanded)]
(h/html
[::h/live expanded?
(fn [expanded?]
(h/html
[:div
[:div {:style "display: flex;"}
[:button {:on-click (partial toggle-expanded! id)}
[::h/if expanded? "-" "+"]]
[:span name]]
(when expanded?
(files ctx path))]))])))
(defn search! [set-name-filter! set-expanded! path new-name-filter]
;; Expand all paths and parents that contain matching files
(let [paths (if (str/blank? new-name-filter)
#{}
(paths-leading-to-matching-files
path (matching-files path new-name-filter)))]
(set-name-filter! new-name-filter)
(set-expanded! paths)))
(defn filetree-app [path]
(let [[expanded set-expanded!] (source/use-state #{})
[name-filter set-name-filter!] (source/use-state "")]
(h/html
[:div
[:h3 "Filetree"]
[:input#name-filter {:type "text"
:on-input (js/js-debounced 500
#(search! set-name-filter! set-expanded! path %)
(js/input-value :name-filter))}]
(folder {:name-filter name-filter
:expanded expanded
:toggle-expanded! (fn [path]
(let [cur (p/current-value expanded)]
(set-expanded!
((if (cur path)
disj conj) cur path))))}
path)])))
(defn filetree-page [path]
(h/html
[:html
[:head
[:title "Ripley filetree"]]
[:body
(h/live-client-script "/__ripley-live")
(filetree-app path)]]))
(defn filetree-routes [path]
(routes
(GET "/" _req
(h/render-response (partial filetree-page path)))
(context/connection-handler "/__ripley-live")))
(defn- restart
([] (restart 3000 "."))
([port path]
(swap! server
(fn [old-server]
(when old-server
(old-server))
(println "Starting counter server")
(server/run-server (filetree-routes (File. path)) {:port port})))))
(defn -main [& _args]
(restart))
| null | https://raw.githubusercontent.com/tatut/ripley/a934cb13f4ddac22e39b71c0bab79bbdaeef952d/examples/filetree/src/filetree/main.clj | clojure | Some file utilities
UI components
Expand all paths and parents that contain matching files | (ns filetree.main
(:require [org.httpkit.server :as server]
[compojure.core :refer [routes GET]]
[ripley.html :as h]
[ripley.live.context :as context]
[ripley.live.source :as source]
[ripley.live.protocols :as p]
[ripley.js :as js]
[clojure.string :as str])
(:import (java.io File)))
(defonce server (atom nil))
(defn- matching-files [path name-filter]
(mapcat
(fn [file]
(if (.isDirectory file)
(matching-files file name-filter)
(when (str/includes? (.getName file) name-filter)
[file])))
(.listFiles path)))
(defn- paths-leading-to-matching-files [path matching-files]
(let [->absolute #(.getAbsolutePath %)
top-path (->absolute path)]
(if (empty? matching-files)
#{}
(into #{top-path}
(comp
(mapcat (fn [matching-file]
(take-while #(not= top-path (->absolute %))
(drop 1 (iterate #(.getParentFile %) matching-file)))))
(map ->absolute))
matching-files))))
(declare folder)
(defn files [{:keys [name-filter] :as ctx} path]
(h/html
[:div {:style "padding-left: 1rem;"}
[:div
[::h/for [file (.listFiles path)
:let [name (.getName file)]]
[::h/if (.isDirectory file)
(folder ctx file)
[:div {:style [::h/live (source/computed
#(or (str/blank? %)
(str/includes? name %)) name-filter)
#(if %
"padding-left: 1.5rem;"
"display: none;")]} name]]]]]))
(defn folder [{:keys [expanded toggle-expanded!] :as ctx} path]
(let [name (-> path .getCanonicalFile .getName)
id (.getAbsolutePath path)
expanded? (source/computed #(contains? % id) expanded)]
(h/html
[::h/live expanded?
(fn [expanded?]
(h/html
[:div
[:div {:style "display: flex;"}
[:button {:on-click (partial toggle-expanded! id)}
[::h/if expanded? "-" "+"]]
[:span name]]
(when expanded?
(files ctx path))]))])))
(defn search! [set-name-filter! set-expanded! path new-name-filter]
(let [paths (if (str/blank? new-name-filter)
#{}
(paths-leading-to-matching-files
path (matching-files path new-name-filter)))]
(set-name-filter! new-name-filter)
(set-expanded! paths)))
(defn filetree-app [path]
(let [[expanded set-expanded!] (source/use-state #{})
[name-filter set-name-filter!] (source/use-state "")]
(h/html
[:div
[:h3 "Filetree"]
[:input#name-filter {:type "text"
:on-input (js/js-debounced 500
#(search! set-name-filter! set-expanded! path %)
(js/input-value :name-filter))}]
(folder {:name-filter name-filter
:expanded expanded
:toggle-expanded! (fn [path]
(let [cur (p/current-value expanded)]
(set-expanded!
((if (cur path)
disj conj) cur path))))}
path)])))
(defn filetree-page [path]
(h/html
[:html
[:head
[:title "Ripley filetree"]]
[:body
(h/live-client-script "/__ripley-live")
(filetree-app path)]]))
(defn filetree-routes [path]
(routes
(GET "/" _req
(h/render-response (partial filetree-page path)))
(context/connection-handler "/__ripley-live")))
(defn- restart
([] (restart 3000 "."))
([port path]
(swap! server
(fn [old-server]
(when old-server
(old-server))
(println "Starting counter server")
(server/run-server (filetree-routes (File. path)) {:port port})))))
(defn -main [& _args]
(restart))
|
6d97ead2cf4a0fd350b038b6bc6f65cc2f3ac924723473329d5a2b7543ae5d12 | clojure/tools.analyzer | add_binding_atom.clj | Copyright ( c ) , Rich Hickey & contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns clojure.tools.analyzer.passes.add-binding-atom
(:require [clojure.tools.analyzer.ast :refer [prewalk]]
[clojure.tools.analyzer.passes.uniquify :refer [uniquify-locals]]))
(defn add-binding-atom
"Adds an atom-backed-map to every local binding,the same
atom will be shared between all occurences of that local.
The atom is put in the :atom field of the node."
{:pass-info {:walk :pre :depends #{#'uniquify-locals} :state (fn [] (atom {}))}}
([ast] (prewalk ast (partial add-binding-atom (atom {}))))
([state ast]
(case (:op ast)
:binding
(let [a (atom {})]
(swap! state assoc (:name ast) a)
(assoc ast :atom a))
:local
(if-let [a (@state (:name ast))]
(assoc ast :atom a)
;; handle injected locals
(let [a (get-in ast [:env :locals (:name ast) :atom] (atom {}))]
(swap! state assoc (:name ast) a)
(assoc ast :atom a)))
ast)))
| null | https://raw.githubusercontent.com/clojure/tools.analyzer/5d1d0dcf3dfe693e71ef36a44f50d4aa944dc65f/src/main/clojure/clojure/tools/analyzer/passes/add_binding_atom.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.
handle injected locals | Copyright ( c ) , Rich Hickey & contributors .
(ns clojure.tools.analyzer.passes.add-binding-atom
(:require [clojure.tools.analyzer.ast :refer [prewalk]]
[clojure.tools.analyzer.passes.uniquify :refer [uniquify-locals]]))
(defn add-binding-atom
"Adds an atom-backed-map to every local binding,the same
atom will be shared between all occurences of that local.
The atom is put in the :atom field of the node."
{:pass-info {:walk :pre :depends #{#'uniquify-locals} :state (fn [] (atom {}))}}
([ast] (prewalk ast (partial add-binding-atom (atom {}))))
([state ast]
(case (:op ast)
:binding
(let [a (atom {})]
(swap! state assoc (:name ast) a)
(assoc ast :atom a))
:local
(if-let [a (@state (:name ast))]
(assoc ast :atom a)
(let [a (get-in ast [:env :locals (:name ast) :atom] (atom {}))]
(swap! state assoc (:name ast) a)
(assoc ast :atom a)))
ast)))
|
13cd956b25472768c4b60926c758dea1411332e22a1eb406a653caa92b17273b | racket/redex | binding-forms-test.rkt | #lang racket
(module+ test)
(require rackunit)
(require redex/reduction-semantics)
(check-equal? (term (asdf«5000» a«1» b«1a1» c«1☺» c«1☹»))
'( asdf«5000☺» a«1☺» b«1a1» c«1☹» c«1☹☺»))
(define (all-distinct? . lst)
(equal? lst (remove-duplicates lst)))
(define-language lc-without-binding
(x variable-not-otherwise-mentioned)
(expr x
(expr expr)
(lambda (x) expr)
(let ([x expr] ...) expr)))
(define-language lc
(x variable-not-otherwise-mentioned)
(expr x
(expr expr)
(lambda (x) expr)
(let ([x expr] ...) expr))
#:binding-forms
(lambda (x) expr #:refers-to x)
(let ([x expr_x] ...) expr_body #:refers-to (shadow x ...)))
(parameterize
([default-language lc-without-binding])
;; put the wrong behavior in the cache...
(check-equal? (term (substitute (x (lambda (x) x)) x y))
(term (y (lambda (y) y))))
(check-equal? (term (substitute (x (let ([x x] [y y] [z z]) ((x y) z))) [x x1] [y y1] [z z1]))
(term (x1 (let ([x1 x1] [y1 y1] [z1 z1]) ((x1 y1) z1))))))
(parameterize
([default-language lc])
;; make sure cache doesn't leak between languages
(check-match (term (substitute (x (lambda (x) x)) x y))
`(y (lambda (,xx) ,xx))
(all-distinct? 'x 'y xx))
(check-match (term (substitute (x (let ([x y] [y z] [z x]) ((x y) z))) [x y] [y z] [z x]))
`(y (let ([,xx z] [,yy x] [,zz y]) ((,xx ,yy) ,zz)))
(all-distinct? 'x 'x1 xx
'y 'y1 yy
'z 'z1 zz)))
(check-match
(redex-let* lc
([(lambda (x) expr) (term (lambda (x) (y (lambda (y) (y (y x))))))])
(term (lambda (x) expr)))
`(lambda (,x) (y (lambda (y) (y (y ,x)))))
(all-distinct? x 'x 'y))
;; test that it's not just the top-level binding form that gets freshened, when we're opening
more than one .
(check-match
(redex-let* lc
([(lambda (x_1) (lambda (x_2) expr)) (term (lambda (a) (lambda (b) (a b))))])
(term (x_1 x_2 expr)))
`(,aa ,bb (,aa ,bb))
(all-distinct? 'a 'b aa bb))
(check-match
(redex-let* lc
([((lambda (x_1) expr_1) (lambda (x_2) expr_2)) (term ((lambda (a) a) (lambda (b) b)))])
(term (x_1 expr_1 x_2 expr_2)))
`(,aa ,aa ,bb ,bb)
(all-distinct? 'a 'b aa bb))
;; naively-written substitution
;;(should be capture-avoiding, thanks to #:binding-forms)
(define-metafunction lc
subst : any x any -> any
[(subst x x any_new) any_new]
[(subst x x_old any_new) x]
[(subst (any ...) x_old any_new)
((subst any x_old any_new) ...)]
[(subst any x_old any_new) any])
(check-match
(term (subst (lambda (x) (y (lambda (y) (y y)))) y (lambda (z) (z x))))
`(lambda (,x) ((lambda (z) (z x)) (lambda (,y) (,y ,y))))
(all-distinct? x y `x `y))
(parameterize ([default-language lc])
(check-match
(term (substitute (lambda (x) (y (lambda (y) (y y)))) y (lambda (z) (z x))))
`(lambda (,x) ((lambda (z) (z x)) (lambda (,y) (,y ,y))))
(all-distinct? x y `x `y)))
(let ()
(define-language stlc
(M N ::= (M N) x cons nil)
(x variable-not-otherwise-mentioned))
(define red
(reduction-relation
stlc
(--> (any_1 any_2 any_3) (substitute any_1 any_2 any_3))))
(check-equal? (apply-reduction-relation
red
(term ((cons x) x nil)))
(list (term (cons nil)))))
;; == more complex stuff ==
(define-language big-language
(expr (expr expr)
(lambda (x) expr)
(va-lambda (x ...) expr)
(va-vb-lambda (x ...) expr ...)
(ieie x x x expr expr)
(let* clauses expr)
(let3* ((x_a expr_a) (x_b expr_b) (x_c expr_c)) expr_body)
(conjoined-lambda ((x ...) expr) ...)
(embedded-lambda (x) (((x) expr) expr))
(pile-o-binders x ...)
(boring-...-bind (x x ... x))
(natural-let* ((x expr) ...) expr)
x
number
(+ expr ...))
(clauses (cl x expr clauses)
no-cl)
(x variable-not-otherwise-mentioned)
#:binding-forms
(lambda (x) expr #:refers-to x)
(va-lambda (x ...) expr #:refers-to (shadow x ...))
(va-vb-lambda (x ...) expr #:refers-to (shadow x ...) ...)
(ieie x_i x_e x_ie expr_1 #:refers-to (shadow x_ie x_i)
expr_2 #:refers-to (shadow x_i x_ie)) #:exports (shadow x_e x_ie)
(let* clauses expr #:refers-to clauses)
(cl x expr clauses #:refers-to x) #:exports (shadow clauses x)
(let3* ((x_a expr_a) (x_b expr_b #:refers-to x_a)
(x_c expr_c #:refers-to (shadow x_b x_a)))
expr_body #:refers-to (shadow x_c x_b x_a))
(conjoined-lambda ((x ...) expr #:refers-to (shadow x ...)) ...)
(embedded-lambda (x_0) (((any_1) expr_1 #:refers-to any_1) expr_0) #:refers-to x_0)
(pile-o-binders x ...) #:exports (shadow x ...)
(boring-...-bind (x_1 x_2 #:...bind (whatever nothing nothing) x_3))
(natural-let* ((x expr) #:...bind (clauses x (shadow clauses x))) expr_body #:refers-to clauses)
;; it would be nice if this gave an error message about `x_out` or `x_in` on definition (or worked)
#;
(wacky-...-bind x_out ((x_in x_side x_exp expr #:refers-to x_out )
#:...bind (clauses x_side (shadow x_exp clauses)))
expr_body #:refers-to (shadow x_in ...))
)
;; a no-op, except that it triggers freshening
(define-metafunction big-language
freshen-all-the-way-down : any -> any
[(freshen-all-the-way-down (any ...))
((freshen-all-the-way-down any) ...)]
[(freshen-all-the-way-down any) any])
(define-metafunction big-language
[(bl-subst x x any_new) any_new]
[(bl-subst (any ...) x_old any_new)
((bl-subst any x_old any_new) ...)]
[(bl-subst any x_old any_new) any])
(define-syntax-rule (destr-test orig pat (distinct-name ...))
(check-match (term (freshen-all-the-way-down orig))
`pat
(all-distinct? distinct-name ...)))
(define-syntax-rule (subst-test orig old-var new-val expected (distinct-name ...))
(parameterize [(default-language big-language)]
(check-match (term (substitute orig old-var new-val))
`expected
(all-distinct? distinct-name ...))
(check-match (term (bl-subst orig old-var new-val))
`expected
(all-distinct? distinct-name ...))))
(define-syntax-rule (destr-test-lang lang orig pat (distinct-name ...))
(begin
(define-metafunction lang
fatwd : any -> any
[(fatwd (any (... ...)))
((fatwd any) (... ...))]
[(fatwd any) any])
(check-match (term (fatwd orig))
`pat
(all-distinct? distinct-name ...))))
;; capture-avoiding substitution
(subst-test (lambda (x) (a (b (lambda (a) (a b)))))
a (lambda (y) (x y))
(lambda (,xx) ((lambda (y) (x y)) (b (lambda (,aa) (,aa b)))))
('a 'b 'x 'y xx aa))
(define-syntax-rule (aeq lhs rhs)
(alpha-equivalent? (term lhs) (term rhs)))
(check-true (alpha-equivalent? big-language
(term (lambda (xxxxx) xxxxx))
(term (lambda (y) y))))
;; alpha-equivalence tests
(parameterize
[(default-language big-language)]
(check-equal? (aeq (lambda (x) x) (lambda (x) x)) #t)
(check-equal? (aeq (lambda (xxxxx) xxxxx) (lambda (y) y)) #t)
(check-equal? (aeq (lambda (x) x) (lambda (x) y)) #f)
(check-equal? (aeq
(lambda (x) (lambda (y) (x y)))
(lambda (y) (lambda (x) (y x))))
#t)
(check-equal? (aeq
(lambda (y) (lambda (x) (x y)))
(lambda (y) (lambda (x) (y x))))
#f)
(check-equal? (aeq
(lambda (y) (lambda (a) a))
(lambda (y) (lambda (b) b)))
#t)
(check-equal? (aeq
(x (lambda (x) x))
(y (lambda (y) y)))
#f)
(check-equal? (aeq
(a (lambda (x) x))
(a (lambda (y) y)))
#t)
(check-equal? (aeq
(va-vb-lambda (a b c) a b c d)
(va-vb-lambda (x y z) x y z d))
#t)
(check-equal? (aeq
(va-vb-lambda (a b c) a b c d)
(va-vb-lambda (x y z) x y c d))
#f)
(check-equal? (aeq a (a)) #f)
(check-equal? (aeq (b) (a)) #f)
(check-equal? (aeq (((a) a) a) (((b) a) a)) #f)
(check-equal? (aeq (((a) a) a) (((a) a) a)) #t)
(check-equal? (aeq
(let* (cl a x (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl aa x (cl bb (aa 5) (cl cc (bb (aa 6)) no-cl))) (aa (bb cc))))
#t)
(check-equal? (aeq
(let* (cl a x (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl aa x (cl bb (aa 5) (cl cc (bb (a 6)) no-cl))) (aa (bb cc))))
#f)
(check-equal? (aeq
(let* (cl a x (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl aa x (cl bb (aa 5) (cl cc (bb (aa 6)) no-cl))) (aa (bb c))))
#f)
(check-equal? (aeq
((lambda (x) x) 8)
((lambda (y) y) 8))
#t)
(check-equal? (aeq
((lambda (x) (lambda (y) (x y))) 8)
((lambda (y) (lambda (x) (x y))) 8))
#f)
;; tests for
(check-equal? (aeq
(1 2 3 (cl f (lambda (x) x) no-cl))
(1 2 3 (cl f (lambda (y) y) no-cl)))
#t)
(check-equal? (aeq
(1 2 3 (cl f (lambda (x) x) no-cl))
(1 2 3 (cl g (lambda (x) x) no-cl)))
#f)
(check-equal? (aeq
(pile-o-binders a b c)
(pile-o-binders x y z))
#f)
(check-equal? (aeq
((pile-o-binders a b c))
((pile-o-binders x y z)))
#f)
(check-equal? (aeq
((natural-let* ((a (+ a b c)) (b (+ a b c)) (c (+ a b c))) (+ a b c)))
((natural-let* ((aa (+ a b c)) (bb (+ aa b c)) (cc (+ aa bb c))) (+ aa bb cc))))
#t)
(check-equal? (aeq
((natural-let* ((a (+ a b c)) (b (+ a b c)) (c (+ a b c))) (+ a b c)))
((natural-let* ((aa (+ a b c)) (bb (+ aa b c)) (cc (+ aa bb cc))) (+ aa bb cc))))
#f)
;; the old way of generating canonical names had a flaw
(check-equal? (aeq
(lambda (a) (|1| a))
(lambda (a) (a a)))
#f)
)
(destr-test
(1 2 3 (cl f (lambda (x) x) no-cl))
(1 2 3 (cl f (lambda (,xx) ,xx) ,no-cl))
('f 'x xx))
;; TODO: the `no-cl` shouldn't be freshened. Doing proper pattern compilation
;; should get rid of that problem
(destr-test
(lambda (x) (let* (cl x 5 no-cl) x))
(lambda (,x-outer) (let* (cl ,x-inner 5 ,no-cl) ,x-inner))
(x-outer x-inner 'x))
(destr-test
(let* (cl a 4 (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl ,aa 4 (cl ,bb (,aa 5) (cl ,cc (,bb (,aa 6)) ,no-cl))) (,aa (,bb ,cc)))
('a aa 'b bb 'c cc))
(destr-test
(let* (cl a 1 (cl a a no-cl)) a)
(let* (cl ,a 1 (cl ,b ,a ,no-cl)) ,b)
(a b 'a))
;; test that nested structure doesn't get lost
(destr-test
(embedded-lambda (a) (((b) (a b)) (a b)))
(embedded-lambda (,aa) (((,bb) (,aa ,bb)) (,aa b)))
(aa bb 'a 'b))
(destr-test
(embedded-lambda (a) (((a) a) a))
(embedded-lambda (,aa) (((,bb) ,bb) ,aa))
(aa bb 'a))
(destr-test
(embedded-lambda (a) ((((cl a x no-cl)) a) a))
(embedded-lambda (,aa) ((((cl ,bb x ,no-cl)) ,bb) ,aa))
(aa bb 'a))
(destr-test
(let3* ((a 1) (b a) (c (a b)))
(a (b c)))
(let3* ((,aa 1) (,bb ,aa) (,cc (,aa ,bb)))
(,aa (,bb ,cc)))
(aa bb cc 'a 'b 'c))
(destr-test
(conjoined-lambda ((a b c) (a (b (c d)))) ((a b) (b a)))
(conjoined-lambda ((,a ,b ,c) (,a (,b (,c d))))
((,a2 ,b2) (,b2 ,a2)))
(a b c a2 b2 'a 'b 'c))
(destr-test
(let* (cl a ((lambda (a) a) a)
(cl x ((lambda (a) a) a) no-cl)) a)
(let* (cl ,a1 ((lambda (,a2) ,a2) a)
(cl ,x ((lambda (,a3) ,a3) ,a1) ,no-cl)) ,a1)
(a1 a2 a3 'a))
(destr-test
(va-lambda (a b c) (+ c b a))
(va-lambda (,a1 ,b1 ,c1) (+ ,c1 ,b1 ,a1))
(a1 b1 c1 'a 'b 'c))
(destr-test
(va-lambda (a b c) (va-lambda (a b c) (+ a b c)))
(va-lambda (,a2 ,b2 ,c2) (va-lambda (,a1 ,b1 ,c1) (+ ,a1 ,b1 ,c1)))
(a1 b1 c1 a2 b2 c2 'a 'b 'c))
(destr-test
(va-vb-lambda (a b c) (+ c b a) a b c)
(va-vb-lambda (,a1 ,b1 ,c1) (+ ,c1 ,b1 ,a1) ,a1 ,b1 ,c1)
(a1 b1 c1 'a 'b 'c))
;; #:...bind tests
(destr-test
(boring-...-bind (a b c d e f))
(boring-...-bind (a b c d e f))
())
(destr-test
(natural-let* ((a (+ a b c d))
(b (+ a b c d))
(c (+ a b c d))
(d (+ a b c d)))
(+ a b c d))
(natural-let* ((,a (+ a b c d))
(,b (+ ,a b c d))
(,c (+ ,a ,b c d))
(,d (+ ,a ,b ,c d)))
(+ ,a ,b ,c ,d))
(a b c d 'a 'b 'c 'd))
(destr-test
(natural-let* ((a
(natural-let* ((a (+ a b c))
(b (+ a b c)))
(+ a b)))
(b (+ a b c))
(c (+ a b c)))
(natural-let* ((a a)
(b (+ a b)))
(+ a b c)))
(natural-let* ((,a
(natural-let* ((,aa (+ a b c))
(,bb (+ ,aa b c)))
(+ ,aa ,bb)))
(,b (+ ,a b c))
(,c (+ ,a ,b c)))
(natural-let* ((,aaa ,a)
(,bbb (+ ,aaa ,b)))
(+ ,aaa ,bbb ,c)))
(a b c aa bb aaa bbb 'a 'b 'c))
;; nested ...bind test
(define-language lc-nested
(x ::= variable-not-otherwise-mentioned)
(e ::= (λ x ... e) () (e e ...))
#:binding-forms
(λ x #:...bind (clauses x (shadow clauses x)) any_body #:refers-to clauses))
(define-metafunction lc-nested
subst-all : e (x ...) (e ...) -> e
[(subst-all e () ()) e]
[(subst-all e (x x_r ...) (e_x e_r ...))
(subst-all (substitute e x e_x) (x_r ...) (e_r ...))])
(define lc-->
(reduction-relation lc-nested
(--> ((λ x ..._0 e) e_a ..._0)
(subst-all e (x ...) (e_a ...)))))
(check-equal?
(list (term (λ ())))
(apply-reduction-relation* lc--> (term (λ ()))))
(check-equal?
(list (term (λ x (λ x ()))))
(apply-reduction-relation* lc--> (term (λ x (λ x ())))))
(check-equal?
(list (term (λ (λ ()))))
(apply-reduction-relation* lc--> (term (λ (λ ())))))
(check-equal?
(list (term (λ x (λ ()))))
(apply-reduction-relation* lc--> (term (λ x (λ ())))))
(check-true
(redex-match?
lc-nested
;; Indentation not vital. but helpful
(λ x_0 ... (λ x_2 ... ((λ x_1 ... e) ...)))
(term (λ x (λ ((λ ())
(λ y ())))))))
(define-judgment-form lc
#:mode (j-subst I I I O)
#:contract (j-subst expr x expr expr)
[(j-subst expr_l x expr_new expr_l-res)
(j-subst expr_r x expr_new expr_r-res)
----------
(j-subst (expr_l expr_r) x expr_new (expr_l-res expr_r-res))]
[(j-subst expr_body x expr_new expr_res) ;; note the naive-ness!
----------
(j-subst (lambda (x_param) expr_body) x expr_new
(lambda (x_param) expr_res))]
[----------
(j-subst x x expr_new expr_new)]
[(side-condition
,(or (not (symbol=? (term x_other) (term x)))))
----------
(j-subst x_other x expr_new x_other)])
(check-match
(judgment-holds (j-subst (x y) x z expr_out) expr_out)
`((z y)))
(check-match
(judgment-holds (j-subst (lambda (x) (y (x (lambda (y) (x (y (lambda (z) (z (y x)))))))))
y (lambda (i) (x i)) expr_out)
expr_out)
`((lambda (,x) ((lambda (,i) (x ,i)) (,x (lambda (,y) (,x (,y (lambda (,z) (,z (,y ,x))))))))))
(all-distinct? x i y z 'x))
;; Testing for these errors kinda belongs in "syn-err-tests/language-definition.rktd",
;; but these errors are returned in terms of `(binding-form #:exports beta)`, which is
;; not quite a subterm of the `define-language`
#;
(define-language bad-binders
(e (e e)
(hi-im-a-binding-form x x e x x)
x)
(x variable-not-otherwise-mentioned)
#:binding-forms
(hi-im-a-binding-form x_0 x_1 e_1 #:refers-to (shadow x_4 x_0 x_1 x_2 x_3 x_5) x_2 x_3)
#:exports (shadow x_6 x_0 x_1 x_2 x_7))
#;
(define-language lang
(e (thing e* ([x e] ...))
integer)
(e* integer)
(x variable-not-otherwise-mentioned)
#:binding-forms
(thing e* #:refers-to x ([x e] ...)))
;; == interactions with `extend-language` and `union-language` ==
(define-language va-lc
(x variable-not-otherwise-mentioned)
(expr x
(expr ...)
(lambda (x ...) expr))
#:binding-forms
(lambda (x ...) expr #:refers-to (shadow x ...)))
(define-extended-language lc-with-extra-lambda va-lc
(expr ....
(extra-lambda (x) expr))
#:binding-forms
(extra-lambda (x) expr #:refers-to x))
(define (all-distinct-vars? . lst)
(and (equal? lst (remove-duplicates lst))
(andmap symbol? lst)))
(define-syntax-rule (define-subst subst-name lang)
(define-metafunction lang
subst-name : any x any -> any
[(subst-name x x any_new) any_new]
[(subst-name x x_old any_new) x]
[(subst-name (any (... ...)) x_old any_new)
((subst-name any x_old any_new) (... ...))]
[(subst-name any x_old any_new) any]))
(define-subst subst-lwel lc-with-extra-lambda)
(check-match
(term (subst-lwel (lambda (x) (extra-lambda (y) (x y z
(lambda (z) z)
(extra-lambda (z) z))))
z (w x y z)))
`(lambda (,x) (extra-lambda (,y) (,x ,y (w x y z)
(lambda (,z0) ,z0)
(extra-lambda (,z1) ,z1))))
(all-distinct-vars? x y z0 z1 `w `x `y `z))
(define-language definition-lang
(x variable-not-otherwise-mentioned)
(block (blk stmt block)
())
(stmt expr
(def x expr))
(expr (+ expr expr)
number
(x)) ;; this is to define plain variable references from being interpreted as binders
#:binding-forms
(def x expr) #:exports x
(blk stmt block #:refers-to stmt))
(destr-test-lang
definition-lang
(blk (def a 1) (blk (+ (a) (a)) ()))
(blk (def ,aa 1) (blk (+ (,aa) (,aa)) ()))
(aa 'a))
(define-union-language union-def-lc definition-lang lc)
(destr-test-lang
union-def-lc
(blk (def a 1) (blk (+ (a) (a)) ()))
(blk (def ,aa 1) (blk (+ (,aa) (,aa)) ()))
(aa 'a))
(define-subst subst-udl union-def-lc)
(check-match
(term (subst-udl
(blk (x)
(blk (z)
(blk (def x (+ (lambda (z) z) (lambda (x) z)))
(blk (def z x)
(blk (z) ())))))
z (w x y)))
`(blk (x)
(blk ((w x y))
(blk (def ,x0 (+ (lambda (,z0) ,z0) (lambda (,x1) (w x y))))
(blk (def ,z1 ,x)
(blk (,z1) ())))))
(all-distinct-vars? `w `x `y `z x0 x1 z0 z1))
(define-union-language four-lcs (a. lc) (b. lc) lc (c. lc))
(destr-test-lang
four-lcs
(lambda (a) a)
(lambda (,aa) ,aa)
(aa 'a))
(define-union-language pfx-def-and-lc (def. definition-lang) (lc. lc))
(destr-test-lang
pfx-def-and-lc
(lambda (a) a)
(lambda (,aa) ,aa)
(aa 'a))
(destr-test-lang
pfx-def-and-lc
(blk (def a 1) (blk (+ (a) (a)) ()))
(blk (def ,aa 1) (blk (+ (,aa) (,aa)) ()))
(aa 'a))
(define-language lc-no-binding
(expr x
(expr expr)
(lambda (x) expr))
(x variable-not-otherwise-mentioned))
(define-extended-language lc-extended-with-binding lc-no-binding
(expr ....)
(x ....)
#:binding-forms
(lambda (x) expr #:refers-to x))
(destr-test-lang
lc-extended-with-binding
(lambda (x) (lambda (y) (x y)))
(lambda (,x) (lambda (,y) (,x ,y)))
(x y 'x 'y))
;; test that judgment forms set `default-language`
(define-judgment-form lc-extended-with-binding
#:mode (dl-param-test-jf I O)
[(where any_out ,(equal? (default-language) lc-extended-with-binding))
----------
(dl-param-test-jf any_in any_out)])
(check-equal? (judgment-holds (dl-param-test-jf 0 any) any) `(#t))
(check-equal? (apply-reduction-relation dl-param-test-jf
(term 0))
`(#t))
;; ... and metafunctions
(define-metafunction lc-extended-with-binding
[(dl-param-test-mf)
,(equal? (default-language) lc-extended-with-binding)])
(check-equal? (term (dl-param-test-mf)) #t)
;; ... and test--> and test-->>
(let ()
(define ans '())
(define-language L)
(define red (reduction-relation L (--> 0 1)))
(test--> red
(begin (set! ans
(cons (eq? (default-language) L)
ans))
0)
(begin (set! ans
(cons (eq? (default-language) L)
ans))
1))
(test-->> red
(begin (set! ans
(cons (eq? (default-language) L)
ans))
0)
(begin (set! ans
(cons (eq? (default-language) L)
ans))
1))
(check-equal? ans '(#t #t #t #t)))
issue # 23 , keywords in grammar
(define-language kw-lang
[e (Λ (x #:kw x) e)
x
number]
[x variable-not-otherwise-mentioned]
#:binding-forms
(Λ (x_1 #:kw x_2) e #:refers-to x_1))
(parameterize ([default-language kw-lang])
(check-not-exn (λ () (term (substitute (Λ (x_1 #:kw x_2) 0) x_1 1)))))
(check-equal?
(with-handlers ([exn:fail:syntax?
(λ (x)
(regexp-match? #rx"unknown name imported or exported"
(exn-message x)))])
(expand #'(define-language L
(x ::= variable)
(e ::= (e e) (lambda (x) e) x)
#:binding-forms
(lambda (x) e #:refers-to q))))
#t)
(check-regexp-match
#rx"found the same binder, var, at different depths"
(with-handlers ([exn:fail:syntax? exn-message])
(expand (quote-syntax
(define-language L
(var ::= variable)
(e ::= (e e) (lambda (var) e) var)
#:binding-forms
(lambda (var) e #:refers-to (shadow var ...)))))))
(let ()
(define-language L
(e ::= (e e) (λ (x) e) x)
(x ::= variable-not-otherwise-mentioned)
#:binding-forms
(λ (x_1) e #:refers-to x_1))
(check-equal? (term (substitute (x y) x y) #:lang L)
(term (y y))))
(let ()
(define-language L
(e ::= (ζ (hide-hole E)))
(x ::= variable-not-otherwise-mentioned)
(E ::= hole (in-hole (natural E) E))
#:binding-forms
(ξ x e_1 #:refers-to x))
(check-true (pair?
(redex-match
L
(ξ x e)
(term (ξ x (ζ (1 (2 hole)))))))))
(let ()
(define-language L
[x y z ::= variable-not-otherwise-mentioned]
[e ::= x (case-lambda [pat e] ...) (e e)]
[pat ::= (cons pat pat) x]
#:binding-forms
(case-lambda
[(cons x_1 x_2) e_1 #:refers-to (shadow x_1 x_2)]
[(cons y z) e_2 #:refers-to (shadow y z)] ...))
(define m
(redex-match
L
(case-lambda
[(cons x_1 x_2) e_1]
[(cons y_1 y_2) e_2]
[(cons z_1 z_2) e_3])
(term
(case-lambda
[(cons a b) a]
[(cons c d) c]
[(cons e f) e]))))
(check-true (and (list? m) (= (length m) 1)))
(for ([b (in-list (match-bindings (list-ref m 0)))])
(check-true (regexp-match? #rx"«[0-9]+»$" (~a (bind-exp b))))))
| null | https://raw.githubusercontent.com/racket/redex/51df9c14a820a3eaa111b330ec612d8eb63e5ea9/redex-test/redex/tests/binding-forms-test.rkt | racket | put the wrong behavior in the cache...
make sure cache doesn't leak between languages
test that it's not just the top-level binding form that gets freshened, when we're opening
naively-written substitution
(should be capture-avoiding, thanks to #:binding-forms)
== more complex stuff ==
it would be nice if this gave an error message about `x_out` or `x_in` on definition (or worked)
a no-op, except that it triggers freshening
capture-avoiding substitution
alpha-equivalence tests
tests for
the old way of generating canonical names had a flaw
TODO: the `no-cl` shouldn't be freshened. Doing proper pattern compilation
should get rid of that problem
test that nested structure doesn't get lost
#:...bind tests
nested ...bind test
Indentation not vital. but helpful
note the naive-ness!
Testing for these errors kinda belongs in "syn-err-tests/language-definition.rktd",
but these errors are returned in terms of `(binding-form #:exports beta)`, which is
not quite a subterm of the `define-language`
== interactions with `extend-language` and `union-language` ==
this is to define plain variable references from being interpreted as binders
test that judgment forms set `default-language`
... and metafunctions
... and test--> and test-->> | #lang racket
(module+ test)
(require rackunit)
(require redex/reduction-semantics)
(check-equal? (term (asdf«5000» a«1» b«1a1» c«1☺» c«1☹»))
'( asdf«5000☺» a«1☺» b«1a1» c«1☹» c«1☹☺»))
(define (all-distinct? . lst)
(equal? lst (remove-duplicates lst)))
(define-language lc-without-binding
(x variable-not-otherwise-mentioned)
(expr x
(expr expr)
(lambda (x) expr)
(let ([x expr] ...) expr)))
(define-language lc
(x variable-not-otherwise-mentioned)
(expr x
(expr expr)
(lambda (x) expr)
(let ([x expr] ...) expr))
#:binding-forms
(lambda (x) expr #:refers-to x)
(let ([x expr_x] ...) expr_body #:refers-to (shadow x ...)))
(parameterize
([default-language lc-without-binding])
(check-equal? (term (substitute (x (lambda (x) x)) x y))
(term (y (lambda (y) y))))
(check-equal? (term (substitute (x (let ([x x] [y y] [z z]) ((x y) z))) [x x1] [y y1] [z z1]))
(term (x1 (let ([x1 x1] [y1 y1] [z1 z1]) ((x1 y1) z1))))))
(parameterize
([default-language lc])
(check-match (term (substitute (x (lambda (x) x)) x y))
`(y (lambda (,xx) ,xx))
(all-distinct? 'x 'y xx))
(check-match (term (substitute (x (let ([x y] [y z] [z x]) ((x y) z))) [x y] [y z] [z x]))
`(y (let ([,xx z] [,yy x] [,zz y]) ((,xx ,yy) ,zz)))
(all-distinct? 'x 'x1 xx
'y 'y1 yy
'z 'z1 zz)))
(check-match
(redex-let* lc
([(lambda (x) expr) (term (lambda (x) (y (lambda (y) (y (y x))))))])
(term (lambda (x) expr)))
`(lambda (,x) (y (lambda (y) (y (y ,x)))))
(all-distinct? x 'x 'y))
more than one .
(check-match
(redex-let* lc
([(lambda (x_1) (lambda (x_2) expr)) (term (lambda (a) (lambda (b) (a b))))])
(term (x_1 x_2 expr)))
`(,aa ,bb (,aa ,bb))
(all-distinct? 'a 'b aa bb))
(check-match
(redex-let* lc
([((lambda (x_1) expr_1) (lambda (x_2) expr_2)) (term ((lambda (a) a) (lambda (b) b)))])
(term (x_1 expr_1 x_2 expr_2)))
`(,aa ,aa ,bb ,bb)
(all-distinct? 'a 'b aa bb))
(define-metafunction lc
subst : any x any -> any
[(subst x x any_new) any_new]
[(subst x x_old any_new) x]
[(subst (any ...) x_old any_new)
((subst any x_old any_new) ...)]
[(subst any x_old any_new) any])
(check-match
(term (subst (lambda (x) (y (lambda (y) (y y)))) y (lambda (z) (z x))))
`(lambda (,x) ((lambda (z) (z x)) (lambda (,y) (,y ,y))))
(all-distinct? x y `x `y))
(parameterize ([default-language lc])
(check-match
(term (substitute (lambda (x) (y (lambda (y) (y y)))) y (lambda (z) (z x))))
`(lambda (,x) ((lambda (z) (z x)) (lambda (,y) (,y ,y))))
(all-distinct? x y `x `y)))
(let ()
(define-language stlc
(M N ::= (M N) x cons nil)
(x variable-not-otherwise-mentioned))
(define red
(reduction-relation
stlc
(--> (any_1 any_2 any_3) (substitute any_1 any_2 any_3))))
(check-equal? (apply-reduction-relation
red
(term ((cons x) x nil)))
(list (term (cons nil)))))
(define-language big-language
(expr (expr expr)
(lambda (x) expr)
(va-lambda (x ...) expr)
(va-vb-lambda (x ...) expr ...)
(ieie x x x expr expr)
(let* clauses expr)
(let3* ((x_a expr_a) (x_b expr_b) (x_c expr_c)) expr_body)
(conjoined-lambda ((x ...) expr) ...)
(embedded-lambda (x) (((x) expr) expr))
(pile-o-binders x ...)
(boring-...-bind (x x ... x))
(natural-let* ((x expr) ...) expr)
x
number
(+ expr ...))
(clauses (cl x expr clauses)
no-cl)
(x variable-not-otherwise-mentioned)
#:binding-forms
(lambda (x) expr #:refers-to x)
(va-lambda (x ...) expr #:refers-to (shadow x ...))
(va-vb-lambda (x ...) expr #:refers-to (shadow x ...) ...)
(ieie x_i x_e x_ie expr_1 #:refers-to (shadow x_ie x_i)
expr_2 #:refers-to (shadow x_i x_ie)) #:exports (shadow x_e x_ie)
(let* clauses expr #:refers-to clauses)
(cl x expr clauses #:refers-to x) #:exports (shadow clauses x)
(let3* ((x_a expr_a) (x_b expr_b #:refers-to x_a)
(x_c expr_c #:refers-to (shadow x_b x_a)))
expr_body #:refers-to (shadow x_c x_b x_a))
(conjoined-lambda ((x ...) expr #:refers-to (shadow x ...)) ...)
(embedded-lambda (x_0) (((any_1) expr_1 #:refers-to any_1) expr_0) #:refers-to x_0)
(pile-o-binders x ...) #:exports (shadow x ...)
(boring-...-bind (x_1 x_2 #:...bind (whatever nothing nothing) x_3))
(natural-let* ((x expr) #:...bind (clauses x (shadow clauses x))) expr_body #:refers-to clauses)
(wacky-...-bind x_out ((x_in x_side x_exp expr #:refers-to x_out )
#:...bind (clauses x_side (shadow x_exp clauses)))
expr_body #:refers-to (shadow x_in ...))
)
(define-metafunction big-language
freshen-all-the-way-down : any -> any
[(freshen-all-the-way-down (any ...))
((freshen-all-the-way-down any) ...)]
[(freshen-all-the-way-down any) any])
(define-metafunction big-language
[(bl-subst x x any_new) any_new]
[(bl-subst (any ...) x_old any_new)
((bl-subst any x_old any_new) ...)]
[(bl-subst any x_old any_new) any])
(define-syntax-rule (destr-test orig pat (distinct-name ...))
(check-match (term (freshen-all-the-way-down orig))
`pat
(all-distinct? distinct-name ...)))
(define-syntax-rule (subst-test orig old-var new-val expected (distinct-name ...))
(parameterize [(default-language big-language)]
(check-match (term (substitute orig old-var new-val))
`expected
(all-distinct? distinct-name ...))
(check-match (term (bl-subst orig old-var new-val))
`expected
(all-distinct? distinct-name ...))))
(define-syntax-rule (destr-test-lang lang orig pat (distinct-name ...))
(begin
(define-metafunction lang
fatwd : any -> any
[(fatwd (any (... ...)))
((fatwd any) (... ...))]
[(fatwd any) any])
(check-match (term (fatwd orig))
`pat
(all-distinct? distinct-name ...))))
(subst-test (lambda (x) (a (b (lambda (a) (a b)))))
a (lambda (y) (x y))
(lambda (,xx) ((lambda (y) (x y)) (b (lambda (,aa) (,aa b)))))
('a 'b 'x 'y xx aa))
(define-syntax-rule (aeq lhs rhs)
(alpha-equivalent? (term lhs) (term rhs)))
(check-true (alpha-equivalent? big-language
(term (lambda (xxxxx) xxxxx))
(term (lambda (y) y))))
(parameterize
[(default-language big-language)]
(check-equal? (aeq (lambda (x) x) (lambda (x) x)) #t)
(check-equal? (aeq (lambda (xxxxx) xxxxx) (lambda (y) y)) #t)
(check-equal? (aeq (lambda (x) x) (lambda (x) y)) #f)
(check-equal? (aeq
(lambda (x) (lambda (y) (x y)))
(lambda (y) (lambda (x) (y x))))
#t)
(check-equal? (aeq
(lambda (y) (lambda (x) (x y)))
(lambda (y) (lambda (x) (y x))))
#f)
(check-equal? (aeq
(lambda (y) (lambda (a) a))
(lambda (y) (lambda (b) b)))
#t)
(check-equal? (aeq
(x (lambda (x) x))
(y (lambda (y) y)))
#f)
(check-equal? (aeq
(a (lambda (x) x))
(a (lambda (y) y)))
#t)
(check-equal? (aeq
(va-vb-lambda (a b c) a b c d)
(va-vb-lambda (x y z) x y z d))
#t)
(check-equal? (aeq
(va-vb-lambda (a b c) a b c d)
(va-vb-lambda (x y z) x y c d))
#f)
(check-equal? (aeq a (a)) #f)
(check-equal? (aeq (b) (a)) #f)
(check-equal? (aeq (((a) a) a) (((b) a) a)) #f)
(check-equal? (aeq (((a) a) a) (((a) a) a)) #t)
(check-equal? (aeq
(let* (cl a x (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl aa x (cl bb (aa 5) (cl cc (bb (aa 6)) no-cl))) (aa (bb cc))))
#t)
(check-equal? (aeq
(let* (cl a x (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl aa x (cl bb (aa 5) (cl cc (bb (a 6)) no-cl))) (aa (bb cc))))
#f)
(check-equal? (aeq
(let* (cl a x (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl aa x (cl bb (aa 5) (cl cc (bb (aa 6)) no-cl))) (aa (bb c))))
#f)
(check-equal? (aeq
((lambda (x) x) 8)
((lambda (y) y) 8))
#t)
(check-equal? (aeq
((lambda (x) (lambda (y) (x y))) 8)
((lambda (y) (lambda (x) (x y))) 8))
#f)
(check-equal? (aeq
(1 2 3 (cl f (lambda (x) x) no-cl))
(1 2 3 (cl f (lambda (y) y) no-cl)))
#t)
(check-equal? (aeq
(1 2 3 (cl f (lambda (x) x) no-cl))
(1 2 3 (cl g (lambda (x) x) no-cl)))
#f)
(check-equal? (aeq
(pile-o-binders a b c)
(pile-o-binders x y z))
#f)
(check-equal? (aeq
((pile-o-binders a b c))
((pile-o-binders x y z)))
#f)
(check-equal? (aeq
((natural-let* ((a (+ a b c)) (b (+ a b c)) (c (+ a b c))) (+ a b c)))
((natural-let* ((aa (+ a b c)) (bb (+ aa b c)) (cc (+ aa bb c))) (+ aa bb cc))))
#t)
(check-equal? (aeq
((natural-let* ((a (+ a b c)) (b (+ a b c)) (c (+ a b c))) (+ a b c)))
((natural-let* ((aa (+ a b c)) (bb (+ aa b c)) (cc (+ aa bb cc))) (+ aa bb cc))))
#f)
(check-equal? (aeq
(lambda (a) (|1| a))
(lambda (a) (a a)))
#f)
)
(destr-test
(1 2 3 (cl f (lambda (x) x) no-cl))
(1 2 3 (cl f (lambda (,xx) ,xx) ,no-cl))
('f 'x xx))
(destr-test
(lambda (x) (let* (cl x 5 no-cl) x))
(lambda (,x-outer) (let* (cl ,x-inner 5 ,no-cl) ,x-inner))
(x-outer x-inner 'x))
(destr-test
(let* (cl a 4 (cl b (a 5) (cl c (b (a 6)) no-cl))) (a (b c)))
(let* (cl ,aa 4 (cl ,bb (,aa 5) (cl ,cc (,bb (,aa 6)) ,no-cl))) (,aa (,bb ,cc)))
('a aa 'b bb 'c cc))
(destr-test
(let* (cl a 1 (cl a a no-cl)) a)
(let* (cl ,a 1 (cl ,b ,a ,no-cl)) ,b)
(a b 'a))
(destr-test
(embedded-lambda (a) (((b) (a b)) (a b)))
(embedded-lambda (,aa) (((,bb) (,aa ,bb)) (,aa b)))
(aa bb 'a 'b))
(destr-test
(embedded-lambda (a) (((a) a) a))
(embedded-lambda (,aa) (((,bb) ,bb) ,aa))
(aa bb 'a))
(destr-test
(embedded-lambda (a) ((((cl a x no-cl)) a) a))
(embedded-lambda (,aa) ((((cl ,bb x ,no-cl)) ,bb) ,aa))
(aa bb 'a))
(destr-test
(let3* ((a 1) (b a) (c (a b)))
(a (b c)))
(let3* ((,aa 1) (,bb ,aa) (,cc (,aa ,bb)))
(,aa (,bb ,cc)))
(aa bb cc 'a 'b 'c))
(destr-test
(conjoined-lambda ((a b c) (a (b (c d)))) ((a b) (b a)))
(conjoined-lambda ((,a ,b ,c) (,a (,b (,c d))))
((,a2 ,b2) (,b2 ,a2)))
(a b c a2 b2 'a 'b 'c))
(destr-test
(let* (cl a ((lambda (a) a) a)
(cl x ((lambda (a) a) a) no-cl)) a)
(let* (cl ,a1 ((lambda (,a2) ,a2) a)
(cl ,x ((lambda (,a3) ,a3) ,a1) ,no-cl)) ,a1)
(a1 a2 a3 'a))
(destr-test
(va-lambda (a b c) (+ c b a))
(va-lambda (,a1 ,b1 ,c1) (+ ,c1 ,b1 ,a1))
(a1 b1 c1 'a 'b 'c))
(destr-test
(va-lambda (a b c) (va-lambda (a b c) (+ a b c)))
(va-lambda (,a2 ,b2 ,c2) (va-lambda (,a1 ,b1 ,c1) (+ ,a1 ,b1 ,c1)))
(a1 b1 c1 a2 b2 c2 'a 'b 'c))
(destr-test
(va-vb-lambda (a b c) (+ c b a) a b c)
(va-vb-lambda (,a1 ,b1 ,c1) (+ ,c1 ,b1 ,a1) ,a1 ,b1 ,c1)
(a1 b1 c1 'a 'b 'c))
(destr-test
(boring-...-bind (a b c d e f))
(boring-...-bind (a b c d e f))
())
(destr-test
(natural-let* ((a (+ a b c d))
(b (+ a b c d))
(c (+ a b c d))
(d (+ a b c d)))
(+ a b c d))
(natural-let* ((,a (+ a b c d))
(,b (+ ,a b c d))
(,c (+ ,a ,b c d))
(,d (+ ,a ,b ,c d)))
(+ ,a ,b ,c ,d))
(a b c d 'a 'b 'c 'd))
(destr-test
(natural-let* ((a
(natural-let* ((a (+ a b c))
(b (+ a b c)))
(+ a b)))
(b (+ a b c))
(c (+ a b c)))
(natural-let* ((a a)
(b (+ a b)))
(+ a b c)))
(natural-let* ((,a
(natural-let* ((,aa (+ a b c))
(,bb (+ ,aa b c)))
(+ ,aa ,bb)))
(,b (+ ,a b c))
(,c (+ ,a ,b c)))
(natural-let* ((,aaa ,a)
(,bbb (+ ,aaa ,b)))
(+ ,aaa ,bbb ,c)))
(a b c aa bb aaa bbb 'a 'b 'c))
(define-language lc-nested
(x ::= variable-not-otherwise-mentioned)
(e ::= (λ x ... e) () (e e ...))
#:binding-forms
(λ x #:...bind (clauses x (shadow clauses x)) any_body #:refers-to clauses))
(define-metafunction lc-nested
subst-all : e (x ...) (e ...) -> e
[(subst-all e () ()) e]
[(subst-all e (x x_r ...) (e_x e_r ...))
(subst-all (substitute e x e_x) (x_r ...) (e_r ...))])
(define lc-->
(reduction-relation lc-nested
(--> ((λ x ..._0 e) e_a ..._0)
(subst-all e (x ...) (e_a ...)))))
(check-equal?
(list (term (λ ())))
(apply-reduction-relation* lc--> (term (λ ()))))
(check-equal?
(list (term (λ x (λ x ()))))
(apply-reduction-relation* lc--> (term (λ x (λ x ())))))
(check-equal?
(list (term (λ (λ ()))))
(apply-reduction-relation* lc--> (term (λ (λ ())))))
(check-equal?
(list (term (λ x (λ ()))))
(apply-reduction-relation* lc--> (term (λ x (λ ())))))
(check-true
(redex-match?
lc-nested
(λ x_0 ... (λ x_2 ... ((λ x_1 ... e) ...)))
(term (λ x (λ ((λ ())
(λ y ())))))))
(define-judgment-form lc
#:mode (j-subst I I I O)
#:contract (j-subst expr x expr expr)
[(j-subst expr_l x expr_new expr_l-res)
(j-subst expr_r x expr_new expr_r-res)
----------
(j-subst (expr_l expr_r) x expr_new (expr_l-res expr_r-res))]
----------
(j-subst (lambda (x_param) expr_body) x expr_new
(lambda (x_param) expr_res))]
[----------
(j-subst x x expr_new expr_new)]
[(side-condition
,(or (not (symbol=? (term x_other) (term x)))))
----------
(j-subst x_other x expr_new x_other)])
(check-match
(judgment-holds (j-subst (x y) x z expr_out) expr_out)
`((z y)))
(check-match
(judgment-holds (j-subst (lambda (x) (y (x (lambda (y) (x (y (lambda (z) (z (y x)))))))))
y (lambda (i) (x i)) expr_out)
expr_out)
`((lambda (,x) ((lambda (,i) (x ,i)) (,x (lambda (,y) (,x (,y (lambda (,z) (,z (,y ,x))))))))))
(all-distinct? x i y z 'x))
(define-language bad-binders
(e (e e)
(hi-im-a-binding-form x x e x x)
x)
(x variable-not-otherwise-mentioned)
#:binding-forms
(hi-im-a-binding-form x_0 x_1 e_1 #:refers-to (shadow x_4 x_0 x_1 x_2 x_3 x_5) x_2 x_3)
#:exports (shadow x_6 x_0 x_1 x_2 x_7))
(define-language lang
(e (thing e* ([x e] ...))
integer)
(e* integer)
(x variable-not-otherwise-mentioned)
#:binding-forms
(thing e* #:refers-to x ([x e] ...)))
(define-language va-lc
(x variable-not-otherwise-mentioned)
(expr x
(expr ...)
(lambda (x ...) expr))
#:binding-forms
(lambda (x ...) expr #:refers-to (shadow x ...)))
(define-extended-language lc-with-extra-lambda va-lc
(expr ....
(extra-lambda (x) expr))
#:binding-forms
(extra-lambda (x) expr #:refers-to x))
(define (all-distinct-vars? . lst)
(and (equal? lst (remove-duplicates lst))
(andmap symbol? lst)))
(define-syntax-rule (define-subst subst-name lang)
(define-metafunction lang
subst-name : any x any -> any
[(subst-name x x any_new) any_new]
[(subst-name x x_old any_new) x]
[(subst-name (any (... ...)) x_old any_new)
((subst-name any x_old any_new) (... ...))]
[(subst-name any x_old any_new) any]))
(define-subst subst-lwel lc-with-extra-lambda)
(check-match
(term (subst-lwel (lambda (x) (extra-lambda (y) (x y z
(lambda (z) z)
(extra-lambda (z) z))))
z (w x y z)))
`(lambda (,x) (extra-lambda (,y) (,x ,y (w x y z)
(lambda (,z0) ,z0)
(extra-lambda (,z1) ,z1))))
(all-distinct-vars? x y z0 z1 `w `x `y `z))
(define-language definition-lang
(x variable-not-otherwise-mentioned)
(block (blk stmt block)
())
(stmt expr
(def x expr))
(expr (+ expr expr)
number
#:binding-forms
(def x expr) #:exports x
(blk stmt block #:refers-to stmt))
(destr-test-lang
definition-lang
(blk (def a 1) (blk (+ (a) (a)) ()))
(blk (def ,aa 1) (blk (+ (,aa) (,aa)) ()))
(aa 'a))
(define-union-language union-def-lc definition-lang lc)
(destr-test-lang
union-def-lc
(blk (def a 1) (blk (+ (a) (a)) ()))
(blk (def ,aa 1) (blk (+ (,aa) (,aa)) ()))
(aa 'a))
(define-subst subst-udl union-def-lc)
(check-match
(term (subst-udl
(blk (x)
(blk (z)
(blk (def x (+ (lambda (z) z) (lambda (x) z)))
(blk (def z x)
(blk (z) ())))))
z (w x y)))
`(blk (x)
(blk ((w x y))
(blk (def ,x0 (+ (lambda (,z0) ,z0) (lambda (,x1) (w x y))))
(blk (def ,z1 ,x)
(blk (,z1) ())))))
(all-distinct-vars? `w `x `y `z x0 x1 z0 z1))
(define-union-language four-lcs (a. lc) (b. lc) lc (c. lc))
(destr-test-lang
four-lcs
(lambda (a) a)
(lambda (,aa) ,aa)
(aa 'a))
(define-union-language pfx-def-and-lc (def. definition-lang) (lc. lc))
(destr-test-lang
pfx-def-and-lc
(lambda (a) a)
(lambda (,aa) ,aa)
(aa 'a))
(destr-test-lang
pfx-def-and-lc
(blk (def a 1) (blk (+ (a) (a)) ()))
(blk (def ,aa 1) (blk (+ (,aa) (,aa)) ()))
(aa 'a))
(define-language lc-no-binding
(expr x
(expr expr)
(lambda (x) expr))
(x variable-not-otherwise-mentioned))
(define-extended-language lc-extended-with-binding lc-no-binding
(expr ....)
(x ....)
#:binding-forms
(lambda (x) expr #:refers-to x))
(destr-test-lang
lc-extended-with-binding
(lambda (x) (lambda (y) (x y)))
(lambda (,x) (lambda (,y) (,x ,y)))
(x y 'x 'y))
(define-judgment-form lc-extended-with-binding
#:mode (dl-param-test-jf I O)
[(where any_out ,(equal? (default-language) lc-extended-with-binding))
----------
(dl-param-test-jf any_in any_out)])
(check-equal? (judgment-holds (dl-param-test-jf 0 any) any) `(#t))
(check-equal? (apply-reduction-relation dl-param-test-jf
(term 0))
`(#t))
(define-metafunction lc-extended-with-binding
[(dl-param-test-mf)
,(equal? (default-language) lc-extended-with-binding)])
(check-equal? (term (dl-param-test-mf)) #t)
(let ()
(define ans '())
(define-language L)
(define red (reduction-relation L (--> 0 1)))
(test--> red
(begin (set! ans
(cons (eq? (default-language) L)
ans))
0)
(begin (set! ans
(cons (eq? (default-language) L)
ans))
1))
(test-->> red
(begin (set! ans
(cons (eq? (default-language) L)
ans))
0)
(begin (set! ans
(cons (eq? (default-language) L)
ans))
1))
(check-equal? ans '(#t #t #t #t)))
issue # 23 , keywords in grammar
(define-language kw-lang
[e (Λ (x #:kw x) e)
x
number]
[x variable-not-otherwise-mentioned]
#:binding-forms
(Λ (x_1 #:kw x_2) e #:refers-to x_1))
(parameterize ([default-language kw-lang])
(check-not-exn (λ () (term (substitute (Λ (x_1 #:kw x_2) 0) x_1 1)))))
(check-equal?
(with-handlers ([exn:fail:syntax?
(λ (x)
(regexp-match? #rx"unknown name imported or exported"
(exn-message x)))])
(expand #'(define-language L
(x ::= variable)
(e ::= (e e) (lambda (x) e) x)
#:binding-forms
(lambda (x) e #:refers-to q))))
#t)
(check-regexp-match
#rx"found the same binder, var, at different depths"
(with-handlers ([exn:fail:syntax? exn-message])
(expand (quote-syntax
(define-language L
(var ::= variable)
(e ::= (e e) (lambda (var) e) var)
#:binding-forms
(lambda (var) e #:refers-to (shadow var ...)))))))
(let ()
(define-language L
(e ::= (e e) (λ (x) e) x)
(x ::= variable-not-otherwise-mentioned)
#:binding-forms
(λ (x_1) e #:refers-to x_1))
(check-equal? (term (substitute (x y) x y) #:lang L)
(term (y y))))
(let ()
(define-language L
(e ::= (ζ (hide-hole E)))
(x ::= variable-not-otherwise-mentioned)
(E ::= hole (in-hole (natural E) E))
#:binding-forms
(ξ x e_1 #:refers-to x))
(check-true (pair?
(redex-match
L
(ξ x e)
(term (ξ x (ζ (1 (2 hole)))))))))
(let ()
(define-language L
[x y z ::= variable-not-otherwise-mentioned]
[e ::= x (case-lambda [pat e] ...) (e e)]
[pat ::= (cons pat pat) x]
#:binding-forms
(case-lambda
[(cons x_1 x_2) e_1 #:refers-to (shadow x_1 x_2)]
[(cons y z) e_2 #:refers-to (shadow y z)] ...))
(define m
(redex-match
L
(case-lambda
[(cons x_1 x_2) e_1]
[(cons y_1 y_2) e_2]
[(cons z_1 z_2) e_3])
(term
(case-lambda
[(cons a b) a]
[(cons c d) c]
[(cons e f) e]))))
(check-true (and (list? m) (= (length m) 1)))
(for ([b (in-list (match-bindings (list-ref m 0)))])
(check-true (regexp-match? #rx"«[0-9]+»$" (~a (bind-exp b))))))
|
d84eb8748700058801e0f262cb2cc22c4065cc72a3bebaa3858a2fed59e2ad98 | winterland1989/magic-haskell | Calculator.hs | # LANGUAGE FlexibleContexts #
import Control.Monad.State.Strict
import Control.Monad.Writer.Strict
import Control.Monad.Trans
import Control.Monad
import Text.Read (readMaybe)
calculator :: WriterT String (StateT Double IO) ()
calculator = do
result <- get
liftIO $ print result
(op:input) <- liftIO getLine
let opFn = case op of
'+' -> sAdd
'-' -> sMinus
'*' -> sTime
'/' -> sDivide
_ -> const $ return ()
case readMaybe input of
Just x -> opFn x >> calculator
Nothing -> tell "Illegal input.\n"
where
sAdd x = do
tell $ "Add: " ++ (show x) ++ "\n"
modify (+ x)
sMinus x = do
tell $ "Minus: " ++ (show x) ++ "\n"
modify (\y -> y - x)
sTime x = do
tell $ "Time: " ++ (show x) ++ "\n"
modify (* x)
sDivide x = do
tell $ "Divide: " ++ (show x) ++ "\n"
modify (/ x)
main :: IO ()
main = (flip evalStateT) 0 $ do
log <- execWriterT calculator
liftIO $ do
putStr "Calculator log:\n"
putStr log
| null | https://raw.githubusercontent.com/winterland1989/magic-haskell/027362d7feb175b10eafa6f12873009ae7e0fb57/code/Calculator.hs | haskell | # LANGUAGE FlexibleContexts #
import Control.Monad.State.Strict
import Control.Monad.Writer.Strict
import Control.Monad.Trans
import Control.Monad
import Text.Read (readMaybe)
calculator :: WriterT String (StateT Double IO) ()
calculator = do
result <- get
liftIO $ print result
(op:input) <- liftIO getLine
let opFn = case op of
'+' -> sAdd
'-' -> sMinus
'*' -> sTime
'/' -> sDivide
_ -> const $ return ()
case readMaybe input of
Just x -> opFn x >> calculator
Nothing -> tell "Illegal input.\n"
where
sAdd x = do
tell $ "Add: " ++ (show x) ++ "\n"
modify (+ x)
sMinus x = do
tell $ "Minus: " ++ (show x) ++ "\n"
modify (\y -> y - x)
sTime x = do
tell $ "Time: " ++ (show x) ++ "\n"
modify (* x)
sDivide x = do
tell $ "Divide: " ++ (show x) ++ "\n"
modify (/ x)
main :: IO ()
main = (flip evalStateT) 0 $ do
log <- execWriterT calculator
liftIO $ do
putStr "Calculator log:\n"
putStr log
| |
81ceb9022243cf53275cdcaf117b69eac1096cf2e9fcb6441f3ceb0cf97e5c24 | symbiont-io/detsys-testkit | Random.hs | module StuntDouble.Random
( Seed
, RandomInterval
, makeSeed
, interval
, exponential
, add
, detRandomInterval
, isLessThan
)
where
import Data.Fixed (mod')
import System.Random
------------------------------------------------------------------------
newtype Seed = Seed StdGen
instance RandomGen Seed where
split (Seed g) = let (g', g'') = split g in (Seed g', Seed g'')
next (Seed g) = fmap Seed (next g)
makeSeed :: Int -> Seed
makeSeed = Seed . mkStdGen
newtype RandomInterval = RandomInterval Double
deriving Show
detRandomInterval :: Double -> RandomInterval
detRandomInterval d = RandomInterval $ mod' d 1
add :: RandomInterval -> RandomInterval -> RandomInterval
add (RandomInterval d) (RandomInterval d') = detRandomInterval $ d + d'
isLessThan :: RandomInterval -> Double -> Bool
isLessThan (RandomInterval d) d' = d < d'
interval :: Seed -> (RandomInterval, Seed)
interval seed =
let
(d, seed') = randomR (0, 1) seed
in
(RandomInterval d, seed')
exponential :: Double -> RandomInterval -> Double
exponential mean (RandomInterval u) = (- mean) * log u
| null | https://raw.githubusercontent.com/symbiont-io/detsys-testkit/930edda1ac10feaa7054c25f9d28326a236f2be5/src/runtime-prototype/src/StuntDouble/Random.hs | haskell | ---------------------------------------------------------------------- | module StuntDouble.Random
( Seed
, RandomInterval
, makeSeed
, interval
, exponential
, add
, detRandomInterval
, isLessThan
)
where
import Data.Fixed (mod')
import System.Random
newtype Seed = Seed StdGen
instance RandomGen Seed where
split (Seed g) = let (g', g'') = split g in (Seed g', Seed g'')
next (Seed g) = fmap Seed (next g)
makeSeed :: Int -> Seed
makeSeed = Seed . mkStdGen
newtype RandomInterval = RandomInterval Double
deriving Show
detRandomInterval :: Double -> RandomInterval
detRandomInterval d = RandomInterval $ mod' d 1
add :: RandomInterval -> RandomInterval -> RandomInterval
add (RandomInterval d) (RandomInterval d') = detRandomInterval $ d + d'
isLessThan :: RandomInterval -> Double -> Bool
isLessThan (RandomInterval d) d' = d < d'
interval :: Seed -> (RandomInterval, Seed)
interval seed =
let
(d, seed') = randomR (0, 1) seed
in
(RandomInterval d, seed')
exponential :: Double -> RandomInterval -> Double
exponential mean (RandomInterval u) = (- mean) * log u
|
7cd654afbf426a3891216eeb876afedf33add7b2d5a8138d35ff306d66c40f40 | 97jaz/gregor | clock.rkt | #lang racket/base
(require racket/contract/base
"generics.rkt"
"moment.rkt"
"datetime.rkt"
"date.rkt"
"time.rkt")
(define (now/moment #:tz [tz (current-timezone)])
(posix->moment ((current-clock)) tz))
(define (now/moment/utc)
(now/moment #:tz "Etc/UTC"))
(define (now #:tz [tz (current-timezone)])
(moment->datetime/local (now/moment #:tz tz)))
(define (now/utc)
(now #:tz "Etc/UTC"))
(define (today #:tz [tz (current-timezone)])
(datetime->date (now #:tz tz)))
(define (today/utc)
(today #:tz "Etc/UTC"))
(define (current-time #:tz [tz (current-timezone)])
(datetime->time (now #:tz tz)))
(define (current-time/utc)
(current-time #:tz "Etc/UTC"))
(define (current-posix-seconds)
(/ (inexact->exact (current-inexact-milliseconds)) 1000))
(define current-clock (make-parameter current-posix-seconds))
(provide/contract
[current-clock any/c]
[current-posix-seconds any/c]
[now/moment (->i () (#:tz [tz tz/c]) [res moment?])]
[now (->i () (#:tz [tz tz/c]) [res datetime?])]
[today (->i () (#:tz [tz tz/c]) [res date?])]
[current-time (->i () (#:tz [tz tz/c]) [res time?])]
[now/moment/utc (-> moment?)]
[now/utc (-> datetime?)]
[today/utc (-> date?)]
[current-time/utc (-> time?)])
| null | https://raw.githubusercontent.com/97jaz/gregor/91d71c6082fec4197aaf9ade57aceb148116c11c/gregor-lib/gregor/private/clock.rkt | racket | #lang racket/base
(require racket/contract/base
"generics.rkt"
"moment.rkt"
"datetime.rkt"
"date.rkt"
"time.rkt")
(define (now/moment #:tz [tz (current-timezone)])
(posix->moment ((current-clock)) tz))
(define (now/moment/utc)
(now/moment #:tz "Etc/UTC"))
(define (now #:tz [tz (current-timezone)])
(moment->datetime/local (now/moment #:tz tz)))
(define (now/utc)
(now #:tz "Etc/UTC"))
(define (today #:tz [tz (current-timezone)])
(datetime->date (now #:tz tz)))
(define (today/utc)
(today #:tz "Etc/UTC"))
(define (current-time #:tz [tz (current-timezone)])
(datetime->time (now #:tz tz)))
(define (current-time/utc)
(current-time #:tz "Etc/UTC"))
(define (current-posix-seconds)
(/ (inexact->exact (current-inexact-milliseconds)) 1000))
(define current-clock (make-parameter current-posix-seconds))
(provide/contract
[current-clock any/c]
[current-posix-seconds any/c]
[now/moment (->i () (#:tz [tz tz/c]) [res moment?])]
[now (->i () (#:tz [tz tz/c]) [res datetime?])]
[today (->i () (#:tz [tz tz/c]) [res date?])]
[current-time (->i () (#:tz [tz tz/c]) [res time?])]
[now/moment/utc (-> moment?)]
[now/utc (-> datetime?)]
[today/utc (-> date?)]
[current-time/utc (-> time?)])
| |
278ccdb7d89ab6fcc982a2820baee182bb74928d2696eb08e5675dd8e991c53e | project-oak/hafnium-verification | QualifiedCppName.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
exception ParseError of string
type t [@@deriving compare]
val empty : t
(** empty qualified name *)
val of_qual_string : string -> t
(** attempts to parse the argument into a list::of::possibly::templated<T>::qualifiers *)
val to_qual_string : t -> string
(** returns qualified name as a string with "::" as a separator between qualifiers *)
val append_qualifier : t -> qual:string -> t
(** append qualifier to the end (innermost scope) of the qualified name *)
val extract_last : t -> (string * t) option
(** returns last (innermost scope) qualifier and qualified name without last qualifier *)
val strip_template_args : t -> t
* returns qualified name without template arguments . For example :
- input : std::shared_ptr < int>::shared_ptr < long >
- output : std::shared_ptr::shared_ptr
- input: std::shared_ptr<int>::shared_ptr<long>
- output: std::shared_ptr::shared_ptr *)
val append_template_args_to_last : t -> args:string -> t
(** append template arguments to the last qualifier. Fails if qualified name is empty or it already
has template args *)
val to_list : t -> string list
(** returns list of qualifiers *)
val to_rev_list : t -> string list
* returns reversed list of qualifiers , ie innermost scope is the first element
val of_list : string list -> t
(** given list of qualifiers in normal order produce qualified name ["std", "move"] *)
val of_rev_list : string list -> t
(** given reversed list of qualifiers, produce qualified name (ie. ["move", "std"] for std::move )*)
val from_field_qualified_name : t -> t
val pp : Format.formatter -> t -> unit
* Module to match qualified C++ procnames " fuzzily " , that is up to namescapes and templating . In
particular , this deals with the following issues :
+ ' std : : ' namespace may have inline namespace afterwards : std::move becomes std::__1::move . This
happens on libc++ and to some extent on libstdc++ . To work around this problem , make matching
against ' std : : ' more fuzzier : std::X::Y::Z will match std::.*::X::Y::Z ( but only for the ' std '
namespace ) .
+ The names are allowed not to commit to a template specialization : we want std::move to match
std::__1::move < const X & > and std::__1::move < int > . To do so , comparison function for qualifiers
will ignore template specializations .
For example :
[ " std " , " move " ] :
- matches : [ " std " , " blah " , " move " ]
- matches : [ " std " , " blah < int > " , " move " ]
- does not match : [ " std","blah " , " move " , " BAD " ] - we do n't want std::.*::X : : . * to pass
- does not match : [ " " , " move " ] , - it 's not std namespace anymore
[ " folly " , " someFunction " ]
- matches : [ " folly","someFunction " ]
- matches : [ " folly","someFunction < int > " ]
- matches : [ " folly < int>","someFunction " ]
- does not match : [ " folly " , " BAD " , " someFunction " ] - unlike ' std ' any other namespace needs all
qualifiers to match
- does not match : [ " folly","someFunction < int > " , " BAD " ] - same as previous example
particular, this deals with the following issues:
+ 'std::' namespace may have inline namespace afterwards: std::move becomes std::__1::move. This
happens on libc++ and to some extent on libstdc++. To work around this problem, make matching
against 'std::' more fuzzier: std::X::Y::Z will match std::.*::X::Y::Z (but only for the 'std'
namespace).
+ The names are allowed not to commit to a template specialization: we want std::move to match
std::__1::move<const X&> and std::__1::move<int>. To do so, comparison function for qualifiers
will ignore template specializations.
For example:
["std", "move"]:
- matches: ["std", "blah", "move"]
- matches: ["std", "blah<int>", "move"]
- does not match: ["std","blah", "move", "BAD"] - we don't want std::.*::X::.* to pass
- does not match: ["stdBAD", "move"], - it's not std namespace anymore
["folly", "someFunction"]
- matches: ["folly","someFunction"]
- matches: ["folly","someFunction<int>"]
- matches: ["folly<int>","someFunction"]
- does not match: ["folly", "BAD", "someFunction"] - unlike 'std' any other namespace needs all
qualifiers to match
- does not match: ["folly","someFunction<int>", "BAD"] - same as previous example *)
module Match : sig
type quals_matcher
val of_fuzzy_qual_names : ?prefix:bool -> string list -> quals_matcher
val match_qualifiers : quals_matcher -> t -> bool
end
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/IR/QualifiedCppName.mli | ocaml | * empty qualified name
* attempts to parse the argument into a list::of::possibly::templated<T>::qualifiers
* returns qualified name as a string with "::" as a separator between qualifiers
* append qualifier to the end (innermost scope) of the qualified name
* returns last (innermost scope) qualifier and qualified name without last qualifier
* append template arguments to the last qualifier. Fails if qualified name is empty or it already
has template args
* returns list of qualifiers
* given list of qualifiers in normal order produce qualified name ["std", "move"]
* given reversed list of qualifiers, produce qualified name (ie. ["move", "std"] for std::move ) |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
exception ParseError of string
type t [@@deriving compare]
val empty : t
val of_qual_string : string -> t
val to_qual_string : t -> string
val append_qualifier : t -> qual:string -> t
val extract_last : t -> (string * t) option
val strip_template_args : t -> t
* returns qualified name without template arguments . For example :
- input : std::shared_ptr < int>::shared_ptr < long >
- output : std::shared_ptr::shared_ptr
- input: std::shared_ptr<int>::shared_ptr<long>
- output: std::shared_ptr::shared_ptr *)
val append_template_args_to_last : t -> args:string -> t
val to_list : t -> string list
val to_rev_list : t -> string list
* returns reversed list of qualifiers , ie innermost scope is the first element
val of_list : string list -> t
val of_rev_list : string list -> t
val from_field_qualified_name : t -> t
val pp : Format.formatter -> t -> unit
* Module to match qualified C++ procnames " fuzzily " , that is up to namescapes and templating . In
particular , this deals with the following issues :
+ ' std : : ' namespace may have inline namespace afterwards : std::move becomes std::__1::move . This
happens on libc++ and to some extent on libstdc++ . To work around this problem , make matching
against ' std : : ' more fuzzier : std::X::Y::Z will match std::.*::X::Y::Z ( but only for the ' std '
namespace ) .
+ The names are allowed not to commit to a template specialization : we want std::move to match
std::__1::move < const X & > and std::__1::move < int > . To do so , comparison function for qualifiers
will ignore template specializations .
For example :
[ " std " , " move " ] :
- matches : [ " std " , " blah " , " move " ]
- matches : [ " std " , " blah < int > " , " move " ]
- does not match : [ " std","blah " , " move " , " BAD " ] - we do n't want std::.*::X : : . * to pass
- does not match : [ " " , " move " ] , - it 's not std namespace anymore
[ " folly " , " someFunction " ]
- matches : [ " folly","someFunction " ]
- matches : [ " folly","someFunction < int > " ]
- matches : [ " folly < int>","someFunction " ]
- does not match : [ " folly " , " BAD " , " someFunction " ] - unlike ' std ' any other namespace needs all
qualifiers to match
- does not match : [ " folly","someFunction < int > " , " BAD " ] - same as previous example
particular, this deals with the following issues:
+ 'std::' namespace may have inline namespace afterwards: std::move becomes std::__1::move. This
happens on libc++ and to some extent on libstdc++. To work around this problem, make matching
against 'std::' more fuzzier: std::X::Y::Z will match std::.*::X::Y::Z (but only for the 'std'
namespace).
+ The names are allowed not to commit to a template specialization: we want std::move to match
std::__1::move<const X&> and std::__1::move<int>. To do so, comparison function for qualifiers
will ignore template specializations.
For example:
["std", "move"]:
- matches: ["std", "blah", "move"]
- matches: ["std", "blah<int>", "move"]
- does not match: ["std","blah", "move", "BAD"] - we don't want std::.*::X::.* to pass
- does not match: ["stdBAD", "move"], - it's not std namespace anymore
["folly", "someFunction"]
- matches: ["folly","someFunction"]
- matches: ["folly","someFunction<int>"]
- matches: ["folly<int>","someFunction"]
- does not match: ["folly", "BAD", "someFunction"] - unlike 'std' any other namespace needs all
qualifiers to match
- does not match: ["folly","someFunction<int>", "BAD"] - same as previous example *)
module Match : sig
type quals_matcher
val of_fuzzy_qual_names : ?prefix:bool -> string list -> quals_matcher
val match_qualifiers : quals_matcher -> t -> bool
end
|
02d64304786f99ab3ec442bb9320240e2cb7506fce6cce046acea21b802948fe | CSCfi/rems | organization.cljs | (ns rems.administration.organization
(:require [clojure.string :as str]
[re-frame.core :as rf]
[rems.administration.administration :as administration]
[rems.administration.components :refer [inline-info-field]]
[rems.administration.status-flags :as status-flags]
[rems.atoms :as atoms :refer [document-title enrich-user readonly-checkbox]]
[rems.collapsible :as collapsible]
[rems.common.roles :as roles]
[rems.flash-message :as flash-message]
[rems.spinner :as spinner]
[rems.text :refer [text]]
[rems.util :refer [fetch]]))
(rf/reg-event-fx
::enter-page
(fn [{:keys [db]} [_ organization-id]]
{:db (assoc db ::loading? true)
::fetch-organization [organization-id]}))
(defn- fetch-organization [organization-id]
(fetch (str "/api/organizations/" organization-id)
{:handler #(rf/dispatch [::fetch-organization-result %])
:error-handler (flash-message/default-error-handler :top "Fetch organization")}))
(rf/reg-fx ::fetch-organization (fn [[organization-id]] (fetch-organization organization-id)))
(rf/reg-event-db
::fetch-organization-result
(fn [db [_ organization]]
(-> db
(assoc ::organization organization)
(dissoc ::loading?))))
(rf/reg-sub ::organization (fn [db _] (::organization db)))
(rf/reg-sub ::loading? (fn [db _] (::loading? db)))
(defn edit-button [id]
[atoms/link {:id "edit-organization"
:class "btn btn-primary"}
(str "/administration/organizations/edit/" id)
(text :t.administration/edit)])
(defn- display-localized-review-email [review-email]
[:div
(doall (for [[langcode localization] (:name review-email)]
^{:key (str "review-email-" (name langcode))}
[inline-info-field (str (text :t.administration/name)
" (" (str/upper-case (name langcode)) ")")
localization]))
[inline-info-field (text :t.administration/email) (:email review-email)]])
(defn- review-emails-field [review-emails]
(if (empty? review-emails)
[inline-info-field (text :t.administration/review-emails)] ; looks good when empty
[:div.mb-2
[:label (text :t.administration/review-emails)]
[:div.solid-group
(->> review-emails
(map display-localized-review-email)
(interpose [:br]))]]))
(defn organization-view [organization language]
[:div.spaced-vertically-3
[collapsible/component
{:id "organization"
:title (get-in organization [:organization/name language])
:always [:div
[inline-info-field (text :t.administration/id) (:organization/id organization)]
(doall (for [[langcode localization] (:organization/short-name organization)]
^{:key (str "short-name-" (name langcode))}
[inline-info-field (str (text :t.administration/short-name)
" (" (str/upper-case (name langcode)) ")")
localization]))
(doall (for [[langcode localization] (:organization/name organization)]
^{:key (str "name-" (name langcode))}
[inline-info-field (str (text :t.administration/title)
" (" (str/upper-case (name langcode)) ")")
localization]))
[inline-info-field
(text :t.administration/owners)
(->> (:organization/owners organization)
(map enrich-user)
(map :display))
{:multiline? true}]
[review-emails-field (:organization/review-emails organization)]
[inline-info-field (text :t.administration/active) [readonly-checkbox {:value (status-flags/active? organization)}]]]}]
(let [id (:organization/id organization)
org-owner? (->> @(rf/subscribe [:owned-organizations])
(some (comp #{id} :organization/id)))
set-org-enabled #(rf/dispatch [:rems.administration.organizations/set-organization-enabled %1 %2 [::enter-page id]])
set-org-archived #(rf/dispatch [:rems.administration.organizations/set-organization-archived %1 %2 [::enter-page id]])]
[:div.col.commands
[administration/back-button "/administration/organizations"]
(when org-owner?
[edit-button id])
[roles/show-when #{:owner}
[status-flags/enabled-toggle {:id :enable-toggle} organization set-org-enabled]
[status-flags/archived-toggle {:id :archive-toggle} organization set-org-archived]]])])
(defn organization-page []
(let [organization (rf/subscribe [::organization])
language (rf/subscribe [:language])
loading? (rf/subscribe [::loading?])]
[:div
[administration/navigator]
[document-title (text :t.administration/organization)]
[flash-message/component :top]
(if @loading?
[spinner/big]
[organization-view @organization @language])]))
| null | https://raw.githubusercontent.com/CSCfi/rems/2865219d752be85c3d5073e4e311ecec2e81ac25/src/cljs/rems/administration/organization.cljs | clojure | looks good when empty | (ns rems.administration.organization
(:require [clojure.string :as str]
[re-frame.core :as rf]
[rems.administration.administration :as administration]
[rems.administration.components :refer [inline-info-field]]
[rems.administration.status-flags :as status-flags]
[rems.atoms :as atoms :refer [document-title enrich-user readonly-checkbox]]
[rems.collapsible :as collapsible]
[rems.common.roles :as roles]
[rems.flash-message :as flash-message]
[rems.spinner :as spinner]
[rems.text :refer [text]]
[rems.util :refer [fetch]]))
(rf/reg-event-fx
::enter-page
(fn [{:keys [db]} [_ organization-id]]
{:db (assoc db ::loading? true)
::fetch-organization [organization-id]}))
(defn- fetch-organization [organization-id]
(fetch (str "/api/organizations/" organization-id)
{:handler #(rf/dispatch [::fetch-organization-result %])
:error-handler (flash-message/default-error-handler :top "Fetch organization")}))
(rf/reg-fx ::fetch-organization (fn [[organization-id]] (fetch-organization organization-id)))
(rf/reg-event-db
::fetch-organization-result
(fn [db [_ organization]]
(-> db
(assoc ::organization organization)
(dissoc ::loading?))))
(rf/reg-sub ::organization (fn [db _] (::organization db)))
(rf/reg-sub ::loading? (fn [db _] (::loading? db)))
(defn edit-button [id]
[atoms/link {:id "edit-organization"
:class "btn btn-primary"}
(str "/administration/organizations/edit/" id)
(text :t.administration/edit)])
(defn- display-localized-review-email [review-email]
[:div
(doall (for [[langcode localization] (:name review-email)]
^{:key (str "review-email-" (name langcode))}
[inline-info-field (str (text :t.administration/name)
" (" (str/upper-case (name langcode)) ")")
localization]))
[inline-info-field (text :t.administration/email) (:email review-email)]])
(defn- review-emails-field [review-emails]
(if (empty? review-emails)
[:div.mb-2
[:label (text :t.administration/review-emails)]
[:div.solid-group
(->> review-emails
(map display-localized-review-email)
(interpose [:br]))]]))
(defn organization-view [organization language]
[:div.spaced-vertically-3
[collapsible/component
{:id "organization"
:title (get-in organization [:organization/name language])
:always [:div
[inline-info-field (text :t.administration/id) (:organization/id organization)]
(doall (for [[langcode localization] (:organization/short-name organization)]
^{:key (str "short-name-" (name langcode))}
[inline-info-field (str (text :t.administration/short-name)
" (" (str/upper-case (name langcode)) ")")
localization]))
(doall (for [[langcode localization] (:organization/name organization)]
^{:key (str "name-" (name langcode))}
[inline-info-field (str (text :t.administration/title)
" (" (str/upper-case (name langcode)) ")")
localization]))
[inline-info-field
(text :t.administration/owners)
(->> (:organization/owners organization)
(map enrich-user)
(map :display))
{:multiline? true}]
[review-emails-field (:organization/review-emails organization)]
[inline-info-field (text :t.administration/active) [readonly-checkbox {:value (status-flags/active? organization)}]]]}]
(let [id (:organization/id organization)
org-owner? (->> @(rf/subscribe [:owned-organizations])
(some (comp #{id} :organization/id)))
set-org-enabled #(rf/dispatch [:rems.administration.organizations/set-organization-enabled %1 %2 [::enter-page id]])
set-org-archived #(rf/dispatch [:rems.administration.organizations/set-organization-archived %1 %2 [::enter-page id]])]
[:div.col.commands
[administration/back-button "/administration/organizations"]
(when org-owner?
[edit-button id])
[roles/show-when #{:owner}
[status-flags/enabled-toggle {:id :enable-toggle} organization set-org-enabled]
[status-flags/archived-toggle {:id :archive-toggle} organization set-org-archived]]])])
(defn organization-page []
(let [organization (rf/subscribe [::organization])
language (rf/subscribe [:language])
loading? (rf/subscribe [::loading?])]
[:div
[administration/navigator]
[document-title (text :t.administration/organization)]
[flash-message/component :top]
(if @loading?
[spinner/big]
[organization-view @organization @language])]))
|
ebbb95d235929d8fdfdadf393b57029eda881694bd5464eb7b2af4d0918dcf0d | rabbitmq/rabbitmq-common | mirrored_supervisor.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2011 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(mirrored_supervisor).
pg2 is deprecated in OTP 23 .
-compile(nowarn_deprecated_function).
%% Mirrored Supervisor
%% ===================
%%
%% This module implements a new type of supervisor. It acts like a
%% normal supervisor, but at creation time you also provide the name
%% of a process group to join. All the supervisors within the
%% process group act like a single large distributed supervisor:
%%
* A process with a given child_id will only exist on one
%% supervisor within the group.
%%
* If one supervisor fails , children may migrate to surviving
%% supervisors within the group.
%%
%% In almost all cases you will want to use the module name for the
%% process group. Using multiple process groups with the same module
%% name is supported. Having multiple module names for the same
%% process group will lead to undefined behaviour.
%%
Motivation
%% ----------
%%
%% Sometimes you have processes which:
%%
%% * Only need to exist once per cluster.
%%
%% * Does not contain much state (or can reconstruct its state easily).
%%
%% * Needs to be restarted elsewhere should it be running on a node
%% which fails.
%%
By creating a mirrored supervisor group with one supervisor on
%% each node, that's what you get.
%%
%%
%% API use
%% -------
%%
%% This is basically the same as for supervisor, except that:
%%
1 ) start_link(Module , ) becomes
start_link(Group , TxFun , Module , ) .
%%
2 ) start_link({local , Name } , Module , ) becomes
start_link({local , Name } , Group , TxFun , Module , ) .
%%
3 ) start_link({global , Name } , Module , ) is not available .
%%
4 ) The restart strategy simple_one_for_one is not available .
%%
5 ) is used to hold global state . At some point your
%% application should invoke create_tables() (or table_definitions()
%% if it wants to manage table creation itself).
%%
The TxFun parameter to start_link/{4,5 } is a function which the
mirrored supervisor can use to execute transactions . In the
%% RabbitMQ server this goes via a worker pool; in other cases a
%% function like:
%%
%% tx_fun(Fun) ->
case : sync_transaction(Fun ) of
%% {atomic, Result} -> Result;
%% {aborted, Reason} -> throw({error, Reason})
%% end.
%%
%% could be used.
%%
%% Internals
%% ---------
%%
Each mirrored_supervisor consists of three processes - the overall
%% supervisor, the delegate supervisor and the mirroring server. The
overall supervisor supervises the other two processes . Its pid is
the one returned from start_link ; the pids of the other two
%% processes are effectively hidden in the API.
%%
%% The delegate supervisor is in charge of supervising all the child
%% processes that are added to the supervisor as usual.
%%
%% The mirroring server intercepts calls to the supervisor API
%% (directed at the overall supervisor), does any special handling,
%% and forwards everything to the delegate supervisor.
%%
This module implements all three , hence init/1 is somewhat overloaded .
%%
%% The mirroring server creates and joins a process group on
%% startup. It monitors all the existing members of this group, and
%% broadcasts a "hello" message to them so that they can monitor it in
%% turn. When it receives a 'DOWN' message, it checks to see if it's
the " first " server in the group and restarts all the child
%% processes from the dead supervisor if so.
%%
%% In the future we might load balance this.
%%
%% Startup is slightly fiddly. The mirroring server needs to know the
Pid of the overall supervisor , but we do n't have that until it has
%% started. Therefore we set this after the fact. We also start any
%% children we found in Module:init() at this point, since starting
%% children requires knowing the overall supervisor pid.
-define(SUPERVISOR, supervisor2).
-define(GEN_SERVER, gen_server2).
-define(SUP_MODULE, mirrored_supervisor_sups).
-define(TABLE, mirrored_sup_childspec).
-define(TABLE_DEF,
{?TABLE,
[{record_name, mirrored_sup_childspec},
{type, ordered_set},
{attributes, record_info(fields, mirrored_sup_childspec)}]}).
-define(TABLE_MATCH, {match, #mirrored_sup_childspec{ _ = '_' }}).
-export([start_link/4, start_link/5,
start_child/2, restart_child/2,
delete_child/2, terminate_child/2,
which_children/1, count_children/1, check_childspecs/1]).
-behaviour(?GEN_SERVER).
-export([init/1, handle_call/3, handle_info/2, terminate/2, code_change/3,
handle_cast/2]).
-export([start_internal/3]).
-export([create_tables/0, table_definitions/0]).
-record(mirrored_sup_childspec, {key, mirroring_pid, childspec}).
-record(state, {overall,
delegate,
group,
tx_fun,
initial_childspecs,
child_order}).
%%--------------------------------------------------------------------------
%% Callback behaviour
%%--------------------------------------------------------------------------
-callback init(Args :: term()) ->
{ok, {{RestartStrategy :: ?SUPERVISOR:strategy(),
MaxR :: non_neg_integer(),
MaxT :: non_neg_integer()},
[ChildSpec :: ?SUPERVISOR:child_spec()]}}
| ignore.
%%--------------------------------------------------------------------------
Specs
%%--------------------------------------------------------------------------
-type startlink_err() :: {'already_started', pid()} | 'shutdown' | term().
-type startlink_ret() :: {'ok', pid()} | 'ignore' | {'error', startlink_err()}.
-type group_name() :: any().
-type(tx_fun() :: fun((fun(() -> A)) -> A)).
-spec start_link(GroupName, TxFun, Module, Args) -> startlink_ret() when
GroupName :: group_name(),
TxFun :: tx_fun(),
Module :: module(),
Args :: term().
-spec start_link(SupName, GroupName, TxFun, Module, Args) ->
startlink_ret() when
SupName :: ?SUPERVISOR:sup_name(),
GroupName :: group_name(),
TxFun :: tx_fun(),
Module :: module(),
Args :: term().
-spec start_internal(Group, TxFun, ChildSpecs) -> Result when
Group :: group_name(),
TxFun :: tx_fun(),
ChildSpecs :: [?SUPERVISOR:child_spec()],
Result :: {'ok', pid()} | {'error', term()}.
-spec create_tables() -> Result when
Result :: 'ok'.
%%----------------------------------------------------------------------------
start_link(Group, TxFun, Mod, Args) ->
start_link0([], Group, TxFun, init(Mod, Args)).
start_link({local, SupName}, Group, TxFun, Mod, Args) ->
start_link0([{local, SupName}], Group, TxFun, init(Mod, Args));
start_link({global, _SupName}, _Group, _TxFun, _Mod, _Args) ->
erlang:error(badarg).
start_link0(Prefix, Group, TxFun, Init) ->
case apply(?SUPERVISOR, start_link,
Prefix ++ [?SUP_MODULE, {overall, Group, TxFun, Init}]) of
{ok, Pid} -> case catch call(Pid, {init, Pid}) of
ok -> {ok, Pid};
E -> E
end;
Other -> Other
end.
init(Mod, Args) ->
case Mod:init(Args) of
{ok, {{Bad, _, _}, _ChildSpecs}} when
Bad =:= simple_one_for_one -> erlang:error(badarg);
Init -> Init
end.
start_child(Sup, ChildSpec) -> call(Sup, {start_child, ChildSpec}).
delete_child(Sup, Id) -> find_call(Sup, Id, {delete_child, Id}).
restart_child(Sup, Id) -> find_call(Sup, Id, {msg, restart_child, [Id]}).
terminate_child(Sup, Id) -> find_call(Sup, Id, {msg, terminate_child, [Id]}).
which_children(Sup) -> fold(which_children, Sup, fun lists:append/2).
count_children(Sup) -> fold(count_children, Sup, fun add_proplists/2).
check_childspecs(Specs) -> ?SUPERVISOR:check_childspecs(Specs).
call(Sup, Msg) -> ?GEN_SERVER:call(mirroring(Sup), Msg, infinity).
cast(Sup, Msg) -> with_exit_handler(
fun() -> ok end,
fun() -> ?GEN_SERVER:cast(mirroring(Sup), Msg) end).
find_call(Sup, Id, Msg) ->
Group = call(Sup, group),
MatchHead = #mirrored_sup_childspec{mirroring_pid = '$1',
key = {Group, Id},
_ = '_'},
If we did this inside a tx we could still have failover
immediately after the tx - we ca n't be 100 % here . So we may as
%% well dirty_select.
case mnesia:dirty_select(?TABLE, [{MatchHead, [], ['$1']}]) of
[Mirror] -> call(Mirror, Msg);
[] -> {error, not_found}
end.
fold(FunAtom, Sup, AggFun) ->
Group = call(Sup, group),
lists:foldl(AggFun, [],
[apply(?SUPERVISOR, FunAtom, [D]) ||
M <- pg2:get_members(Group),
D <- [delegate(M)]]).
child(Sup, Id) ->
[Pid] = [Pid || {Id1, Pid, _, _} <- ?SUPERVISOR:which_children(Sup),
Id1 =:= Id],
Pid.
delegate(Sup) -> child(Sup, delegate).
mirroring(Sup) -> child(Sup, mirroring).
%%----------------------------------------------------------------------------
start_internal(Group, TxFun, ChildSpecs) ->
?GEN_SERVER:start_link(?MODULE, {Group, TxFun, ChildSpecs},
[{timeout, infinity}]).
%%----------------------------------------------------------------------------
init({Group, TxFun, ChildSpecs}) ->
{ok, #state{group = Group,
tx_fun = TxFun,
initial_childspecs = ChildSpecs,
child_order = child_order_from(ChildSpecs)}}.
handle_call({init, Overall}, _From,
State = #state{overall = undefined,
delegate = undefined,
group = Group,
tx_fun = TxFun,
initial_childspecs = ChildSpecs}) ->
process_flag(trap_exit, true),
pg2:create(Group),
ok = pg2:join(Group, Overall),
Rest = pg2:get_members(Group) -- [Overall],
case Rest of
[] -> TxFun(fun() -> delete_all(Group) end);
_ -> ok
end,
[begin
?GEN_SERVER:cast(mirroring(Pid), {ensure_monitoring, Overall}),
erlang:monitor(process, Pid)
end || Pid <- Rest],
Delegate = delegate(Overall),
erlang:monitor(process, Delegate),
State1 = State#state{overall = Overall, delegate = Delegate},
case errors([maybe_start(Group, TxFun, Overall, Delegate, S)
|| S <- ChildSpecs]) of
[] -> {reply, ok, State1};
Errors -> {stop, {shutdown, Errors}, State1}
end;
handle_call({start_child, ChildSpec}, _From,
State = #state{overall = Overall,
delegate = Delegate,
group = Group,
tx_fun = TxFun}) ->
{reply, case maybe_start(Group, TxFun, Overall, Delegate, ChildSpec) of
already_in_mnesia -> {error, already_present};
{already_in_mnesia, Pid} -> {error, {already_started, Pid}};
Else -> Else
end, State};
handle_call({delete_child, Id}, _From, State = #state{delegate = Delegate,
group = Group,
tx_fun = TxFun}) ->
{reply, stop(Group, TxFun, Delegate, Id), State};
handle_call({msg, F, A}, _From, State = #state{delegate = Delegate}) ->
{reply, apply(?SUPERVISOR, F, [Delegate | A]), State};
handle_call(group, _From, State = #state{group = Group}) ->
{reply, Group, State};
handle_call(Msg, _From, State) ->
{stop, {unexpected_call, Msg}, State}.
handle_cast({ensure_monitoring, Pid}, State) ->
erlang:monitor(process, Pid),
{noreply, State};
handle_cast({die, Reason}, State = #state{group = Group}) ->
_ = tell_all_peers_to_die(Group, Reason),
{stop, Reason, State};
handle_cast(Msg, State) ->
{stop, {unexpected_cast, Msg}, State}.
handle_info({'DOWN', _Ref, process, Pid, Reason},
State = #state{delegate = Pid, group = Group}) ->
%% Since the delegate is temporary, its death won't cause us to
%% die. Since the overall supervisor kills processes in reverse
%% order when shutting down "from above" and we started after the
%% delegate, if we see the delegate die then that means it died
%% "from below" i.e. due to the behaviour of its children, not
%% because the whole app was being torn down.
%%
%% Therefore if we get here we know we need to cause the entire
%% mirrored sup to shut down, not just fail over.
_ = tell_all_peers_to_die(Group, Reason),
{stop, Reason, State};
handle_info({'DOWN', _Ref, process, Pid, _Reason},
State = #state{delegate = Delegate,
group = Group,
tx_fun = TxFun,
overall = O,
child_order = ChildOrder}) ->
TODO load balance this
%% No guarantee pg2 will have received the DOWN before us.
R = case lists:sort(pg2:get_members(Group)) -- [Pid] of
[O | _] -> ChildSpecs =
TxFun(fun() -> update_all(O, Pid) end),
[start(Delegate, ChildSpec)
|| ChildSpec <- restore_child_order(ChildSpecs,
ChildOrder)];
_ -> []
end,
case errors(R) of
[] -> {noreply, State};
Errors -> {stop, {shutdown, Errors}, State}
end;
handle_info(Info, State) ->
{stop, {unexpected_info, Info}, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%----------------------------------------------------------------------------
tell_all_peers_to_die(Group, Reason) ->
[cast(P, {die, Reason}) || P <- pg2:get_members(Group) -- [self()]].
maybe_start(Group, TxFun, Overall, Delegate, ChildSpec) ->
try TxFun(fun() -> check_start(Group, Overall, Delegate, ChildSpec) end) of
start -> start(Delegate, ChildSpec);
undefined -> already_in_mnesia;
Pid -> {already_in_mnesia, Pid}
catch
%% If we are torn down while in the transaction...
{error, E} -> {error, E}
end.
check_start(Group, Overall, Delegate, ChildSpec) ->
case mnesia:wread({?TABLE, {Group, id(ChildSpec)}}) of
[] -> _ = write(Group, Overall, ChildSpec),
start;
[S] -> #mirrored_sup_childspec{key = {Group, Id},
mirroring_pid = Pid} = S,
case Overall of
Pid -> child(Delegate, Id);
_ -> case supervisor(Pid) of
dead -> _ = write(Group, Overall, ChildSpec),
start;
Delegate0 -> child(Delegate0, Id)
end
end
end.
supervisor(Pid) -> with_exit_handler(fun() -> dead end,
fun() -> delegate(Pid) end).
write(Group, Overall, ChildSpec) ->
S = #mirrored_sup_childspec{key = {Group, id(ChildSpec)},
mirroring_pid = Overall,
childspec = ChildSpec},
ok = mnesia:write(?TABLE, S, write),
ChildSpec.
delete(Group, Id) ->
ok = mnesia:delete({?TABLE, {Group, Id}}).
start(Delegate, ChildSpec) ->
apply(?SUPERVISOR, start_child, [Delegate, ChildSpec]).
stop(Group, TxFun, Delegate, Id) ->
try TxFun(fun() -> check_stop(Group, Delegate, Id) end) of
deleted -> apply(?SUPERVISOR, delete_child, [Delegate, Id]);
running -> {error, running}
catch
{error, E} -> {error, E}
end.
check_stop(Group, Delegate, Id) ->
case child(Delegate, Id) of
undefined -> delete(Group, Id),
deleted;
_ -> running
end.
id({Id, _, _, _, _, _}) -> Id.
update_all(Overall, OldOverall) ->
MatchHead = #mirrored_sup_childspec{mirroring_pid = OldOverall,
key = '$1',
childspec = '$2',
_ = '_'},
[write(Group, Overall, C) ||
[{Group, _Id}, C] <- mnesia:select(?TABLE, [{MatchHead, [], ['$$']}])].
delete_all(Group) ->
MatchHead = #mirrored_sup_childspec{key = {Group, '_'},
childspec = '$1',
_ = '_'},
[delete(Group, id(C)) ||
C <- mnesia:select(?TABLE, [{MatchHead, [], ['$1']}])].
errors(Results) -> [E || {error, E} <- Results].
%%----------------------------------------------------------------------------
create_tables() -> create_tables([?TABLE_DEF]).
create_tables([]) ->
ok;
create_tables([{Table, Attributes} | Ts]) ->
case mnesia:create_table(Table, Attributes) of
{atomic, ok} -> create_tables(Ts);
{aborted, {already_exists, ?TABLE}} -> create_tables(Ts);
Err -> Err
end.
table_definitions() ->
{Name, Attributes} = ?TABLE_DEF,
[{Name, [?TABLE_MATCH | Attributes]}].
%%----------------------------------------------------------------------------
with_exit_handler(Handler, Thunk) ->
try
Thunk()
catch
exit:{R, _} when R =:= noproc; R =:= nodedown;
R =:= normal; R =:= shutdown ->
Handler();
exit:{{R, _}, _} when R =:= nodedown; R =:= shutdown ->
Handler()
end.
add_proplists(P1, P2) ->
add_proplists(lists:keysort(1, P1), lists:keysort(1, P2), []).
add_proplists([], P2, Acc) -> P2 ++ Acc;
add_proplists(P1, [], Acc) -> P1 ++ Acc;
add_proplists([{K, V1} | P1], [{K, V2} | P2], Acc) ->
add_proplists(P1, P2, [{K, V1 + V2} | Acc]);
add_proplists([{K1, _} = KV | P1], [{K2, _} | _] = P2, Acc) when K1 < K2 ->
add_proplists(P1, P2, [KV | Acc]);
add_proplists(P1, [KV | P2], Acc) ->
add_proplists(P1, P2, [KV | Acc]).
child_order_from(ChildSpecs) ->
lists:zipwith(fun(C, N) ->
{id(C), N}
end, ChildSpecs, lists:seq(1, length(ChildSpecs))).
restore_child_order(ChildSpecs, ChildOrder) ->
lists:sort(fun(A, B) ->
proplists:get_value(id(A), ChildOrder)
< proplists:get_value(id(B), ChildOrder)
end, ChildSpecs).
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-common/67c4397ffa9f51d87f994aa4db4a68e8e95326ab/src/mirrored_supervisor.erl | erlang |
Mirrored Supervisor
===================
This module implements a new type of supervisor. It acts like a
normal supervisor, but at creation time you also provide the name
of a process group to join. All the supervisors within the
process group act like a single large distributed supervisor:
supervisor within the group.
supervisors within the group.
In almost all cases you will want to use the module name for the
process group. Using multiple process groups with the same module
name is supported. Having multiple module names for the same
process group will lead to undefined behaviour.
----------
Sometimes you have processes which:
* Only need to exist once per cluster.
* Does not contain much state (or can reconstruct its state easily).
* Needs to be restarted elsewhere should it be running on a node
which fails.
each node, that's what you get.
API use
-------
This is basically the same as for supervisor, except that:
application should invoke create_tables() (or table_definitions()
if it wants to manage table creation itself).
RabbitMQ server this goes via a worker pool; in other cases a
function like:
tx_fun(Fun) ->
{atomic, Result} -> Result;
{aborted, Reason} -> throw({error, Reason})
end.
could be used.
Internals
---------
supervisor, the delegate supervisor and the mirroring server. The
processes are effectively hidden in the API.
The delegate supervisor is in charge of supervising all the child
processes that are added to the supervisor as usual.
The mirroring server intercepts calls to the supervisor API
(directed at the overall supervisor), does any special handling,
and forwards everything to the delegate supervisor.
The mirroring server creates and joins a process group on
startup. It monitors all the existing members of this group, and
broadcasts a "hello" message to them so that they can monitor it in
turn. When it receives a 'DOWN' message, it checks to see if it's
processes from the dead supervisor if so.
In the future we might load balance this.
Startup is slightly fiddly. The mirroring server needs to know the
started. Therefore we set this after the fact. We also start any
children we found in Module:init() at this point, since starting
children requires knowing the overall supervisor pid.
--------------------------------------------------------------------------
Callback behaviour
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
----------------------------------------------------------------------------
here . So we may as
well dirty_select.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Since the delegate is temporary, its death won't cause us to
die. Since the overall supervisor kills processes in reverse
order when shutting down "from above" and we started after the
delegate, if we see the delegate die then that means it died
"from below" i.e. due to the behaviour of its children, not
because the whole app was being torn down.
Therefore if we get here we know we need to cause the entire
mirrored sup to shut down, not just fail over.
No guarantee pg2 will have received the DOWN before us.
----------------------------------------------------------------------------
If we are torn down while in the transaction...
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2011 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(mirrored_supervisor).
pg2 is deprecated in OTP 23 .
-compile(nowarn_deprecated_function).
* A process with a given child_id will only exist on one
* If one supervisor fails , children may migrate to surviving
Motivation
By creating a mirrored supervisor group with one supervisor on
1 ) start_link(Module , ) becomes
start_link(Group , TxFun , Module , ) .
2 ) start_link({local , Name } , Module , ) becomes
start_link({local , Name } , Group , TxFun , Module , ) .
3 ) start_link({global , Name } , Module , ) is not available .
4 ) The restart strategy simple_one_for_one is not available .
5 ) is used to hold global state . At some point your
The TxFun parameter to start_link/{4,5 } is a function which the
mirrored supervisor can use to execute transactions . In the
case : sync_transaction(Fun ) of
Each mirrored_supervisor consists of three processes - the overall
overall supervisor supervises the other two processes . Its pid is
the one returned from start_link ; the pids of the other two
This module implements all three , hence init/1 is somewhat overloaded .
the " first " server in the group and restarts all the child
Pid of the overall supervisor , but we do n't have that until it has
-define(SUPERVISOR, supervisor2).
-define(GEN_SERVER, gen_server2).
-define(SUP_MODULE, mirrored_supervisor_sups).
-define(TABLE, mirrored_sup_childspec).
-define(TABLE_DEF,
{?TABLE,
[{record_name, mirrored_sup_childspec},
{type, ordered_set},
{attributes, record_info(fields, mirrored_sup_childspec)}]}).
-define(TABLE_MATCH, {match, #mirrored_sup_childspec{ _ = '_' }}).
-export([start_link/4, start_link/5,
start_child/2, restart_child/2,
delete_child/2, terminate_child/2,
which_children/1, count_children/1, check_childspecs/1]).
-behaviour(?GEN_SERVER).
-export([init/1, handle_call/3, handle_info/2, terminate/2, code_change/3,
handle_cast/2]).
-export([start_internal/3]).
-export([create_tables/0, table_definitions/0]).
-record(mirrored_sup_childspec, {key, mirroring_pid, childspec}).
-record(state, {overall,
delegate,
group,
tx_fun,
initial_childspecs,
child_order}).
-callback init(Args :: term()) ->
{ok, {{RestartStrategy :: ?SUPERVISOR:strategy(),
MaxR :: non_neg_integer(),
MaxT :: non_neg_integer()},
[ChildSpec :: ?SUPERVISOR:child_spec()]}}
| ignore.
Specs
-type startlink_err() :: {'already_started', pid()} | 'shutdown' | term().
-type startlink_ret() :: {'ok', pid()} | 'ignore' | {'error', startlink_err()}.
-type group_name() :: any().
-type(tx_fun() :: fun((fun(() -> A)) -> A)).
-spec start_link(GroupName, TxFun, Module, Args) -> startlink_ret() when
GroupName :: group_name(),
TxFun :: tx_fun(),
Module :: module(),
Args :: term().
-spec start_link(SupName, GroupName, TxFun, Module, Args) ->
startlink_ret() when
SupName :: ?SUPERVISOR:sup_name(),
GroupName :: group_name(),
TxFun :: tx_fun(),
Module :: module(),
Args :: term().
-spec start_internal(Group, TxFun, ChildSpecs) -> Result when
Group :: group_name(),
TxFun :: tx_fun(),
ChildSpecs :: [?SUPERVISOR:child_spec()],
Result :: {'ok', pid()} | {'error', term()}.
-spec create_tables() -> Result when
Result :: 'ok'.
start_link(Group, TxFun, Mod, Args) ->
start_link0([], Group, TxFun, init(Mod, Args)).
start_link({local, SupName}, Group, TxFun, Mod, Args) ->
start_link0([{local, SupName}], Group, TxFun, init(Mod, Args));
start_link({global, _SupName}, _Group, _TxFun, _Mod, _Args) ->
erlang:error(badarg).
start_link0(Prefix, Group, TxFun, Init) ->
case apply(?SUPERVISOR, start_link,
Prefix ++ [?SUP_MODULE, {overall, Group, TxFun, Init}]) of
{ok, Pid} -> case catch call(Pid, {init, Pid}) of
ok -> {ok, Pid};
E -> E
end;
Other -> Other
end.
init(Mod, Args) ->
case Mod:init(Args) of
{ok, {{Bad, _, _}, _ChildSpecs}} when
Bad =:= simple_one_for_one -> erlang:error(badarg);
Init -> Init
end.
start_child(Sup, ChildSpec) -> call(Sup, {start_child, ChildSpec}).
delete_child(Sup, Id) -> find_call(Sup, Id, {delete_child, Id}).
restart_child(Sup, Id) -> find_call(Sup, Id, {msg, restart_child, [Id]}).
terminate_child(Sup, Id) -> find_call(Sup, Id, {msg, terminate_child, [Id]}).
which_children(Sup) -> fold(which_children, Sup, fun lists:append/2).
count_children(Sup) -> fold(count_children, Sup, fun add_proplists/2).
check_childspecs(Specs) -> ?SUPERVISOR:check_childspecs(Specs).
call(Sup, Msg) -> ?GEN_SERVER:call(mirroring(Sup), Msg, infinity).
cast(Sup, Msg) -> with_exit_handler(
fun() -> ok end,
fun() -> ?GEN_SERVER:cast(mirroring(Sup), Msg) end).
find_call(Sup, Id, Msg) ->
Group = call(Sup, group),
MatchHead = #mirrored_sup_childspec{mirroring_pid = '$1',
key = {Group, Id},
_ = '_'},
If we did this inside a tx we could still have failover
case mnesia:dirty_select(?TABLE, [{MatchHead, [], ['$1']}]) of
[Mirror] -> call(Mirror, Msg);
[] -> {error, not_found}
end.
fold(FunAtom, Sup, AggFun) ->
Group = call(Sup, group),
lists:foldl(AggFun, [],
[apply(?SUPERVISOR, FunAtom, [D]) ||
M <- pg2:get_members(Group),
D <- [delegate(M)]]).
child(Sup, Id) ->
[Pid] = [Pid || {Id1, Pid, _, _} <- ?SUPERVISOR:which_children(Sup),
Id1 =:= Id],
Pid.
delegate(Sup) -> child(Sup, delegate).
mirroring(Sup) -> child(Sup, mirroring).
start_internal(Group, TxFun, ChildSpecs) ->
?GEN_SERVER:start_link(?MODULE, {Group, TxFun, ChildSpecs},
[{timeout, infinity}]).
init({Group, TxFun, ChildSpecs}) ->
{ok, #state{group = Group,
tx_fun = TxFun,
initial_childspecs = ChildSpecs,
child_order = child_order_from(ChildSpecs)}}.
handle_call({init, Overall}, _From,
State = #state{overall = undefined,
delegate = undefined,
group = Group,
tx_fun = TxFun,
initial_childspecs = ChildSpecs}) ->
process_flag(trap_exit, true),
pg2:create(Group),
ok = pg2:join(Group, Overall),
Rest = pg2:get_members(Group) -- [Overall],
case Rest of
[] -> TxFun(fun() -> delete_all(Group) end);
_ -> ok
end,
[begin
?GEN_SERVER:cast(mirroring(Pid), {ensure_monitoring, Overall}),
erlang:monitor(process, Pid)
end || Pid <- Rest],
Delegate = delegate(Overall),
erlang:monitor(process, Delegate),
State1 = State#state{overall = Overall, delegate = Delegate},
case errors([maybe_start(Group, TxFun, Overall, Delegate, S)
|| S <- ChildSpecs]) of
[] -> {reply, ok, State1};
Errors -> {stop, {shutdown, Errors}, State1}
end;
handle_call({start_child, ChildSpec}, _From,
State = #state{overall = Overall,
delegate = Delegate,
group = Group,
tx_fun = TxFun}) ->
{reply, case maybe_start(Group, TxFun, Overall, Delegate, ChildSpec) of
already_in_mnesia -> {error, already_present};
{already_in_mnesia, Pid} -> {error, {already_started, Pid}};
Else -> Else
end, State};
handle_call({delete_child, Id}, _From, State = #state{delegate = Delegate,
group = Group,
tx_fun = TxFun}) ->
{reply, stop(Group, TxFun, Delegate, Id), State};
handle_call({msg, F, A}, _From, State = #state{delegate = Delegate}) ->
{reply, apply(?SUPERVISOR, F, [Delegate | A]), State};
handle_call(group, _From, State = #state{group = Group}) ->
{reply, Group, State};
handle_call(Msg, _From, State) ->
{stop, {unexpected_call, Msg}, State}.
handle_cast({ensure_monitoring, Pid}, State) ->
erlang:monitor(process, Pid),
{noreply, State};
handle_cast({die, Reason}, State = #state{group = Group}) ->
_ = tell_all_peers_to_die(Group, Reason),
{stop, Reason, State};
handle_cast(Msg, State) ->
{stop, {unexpected_cast, Msg}, State}.
handle_info({'DOWN', _Ref, process, Pid, Reason},
State = #state{delegate = Pid, group = Group}) ->
_ = tell_all_peers_to_die(Group, Reason),
{stop, Reason, State};
handle_info({'DOWN', _Ref, process, Pid, _Reason},
State = #state{delegate = Delegate,
group = Group,
tx_fun = TxFun,
overall = O,
child_order = ChildOrder}) ->
TODO load balance this
R = case lists:sort(pg2:get_members(Group)) -- [Pid] of
[O | _] -> ChildSpecs =
TxFun(fun() -> update_all(O, Pid) end),
[start(Delegate, ChildSpec)
|| ChildSpec <- restore_child_order(ChildSpecs,
ChildOrder)];
_ -> []
end,
case errors(R) of
[] -> {noreply, State};
Errors -> {stop, {shutdown, Errors}, State}
end;
handle_info(Info, State) ->
{stop, {unexpected_info, Info}, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
tell_all_peers_to_die(Group, Reason) ->
[cast(P, {die, Reason}) || P <- pg2:get_members(Group) -- [self()]].
maybe_start(Group, TxFun, Overall, Delegate, ChildSpec) ->
try TxFun(fun() -> check_start(Group, Overall, Delegate, ChildSpec) end) of
start -> start(Delegate, ChildSpec);
undefined -> already_in_mnesia;
Pid -> {already_in_mnesia, Pid}
catch
{error, E} -> {error, E}
end.
check_start(Group, Overall, Delegate, ChildSpec) ->
case mnesia:wread({?TABLE, {Group, id(ChildSpec)}}) of
[] -> _ = write(Group, Overall, ChildSpec),
start;
[S] -> #mirrored_sup_childspec{key = {Group, Id},
mirroring_pid = Pid} = S,
case Overall of
Pid -> child(Delegate, Id);
_ -> case supervisor(Pid) of
dead -> _ = write(Group, Overall, ChildSpec),
start;
Delegate0 -> child(Delegate0, Id)
end
end
end.
supervisor(Pid) -> with_exit_handler(fun() -> dead end,
fun() -> delegate(Pid) end).
write(Group, Overall, ChildSpec) ->
S = #mirrored_sup_childspec{key = {Group, id(ChildSpec)},
mirroring_pid = Overall,
childspec = ChildSpec},
ok = mnesia:write(?TABLE, S, write),
ChildSpec.
delete(Group, Id) ->
ok = mnesia:delete({?TABLE, {Group, Id}}).
start(Delegate, ChildSpec) ->
apply(?SUPERVISOR, start_child, [Delegate, ChildSpec]).
stop(Group, TxFun, Delegate, Id) ->
try TxFun(fun() -> check_stop(Group, Delegate, Id) end) of
deleted -> apply(?SUPERVISOR, delete_child, [Delegate, Id]);
running -> {error, running}
catch
{error, E} -> {error, E}
end.
check_stop(Group, Delegate, Id) ->
case child(Delegate, Id) of
undefined -> delete(Group, Id),
deleted;
_ -> running
end.
id({Id, _, _, _, _, _}) -> Id.
update_all(Overall, OldOverall) ->
MatchHead = #mirrored_sup_childspec{mirroring_pid = OldOverall,
key = '$1',
childspec = '$2',
_ = '_'},
[write(Group, Overall, C) ||
[{Group, _Id}, C] <- mnesia:select(?TABLE, [{MatchHead, [], ['$$']}])].
delete_all(Group) ->
MatchHead = #mirrored_sup_childspec{key = {Group, '_'},
childspec = '$1',
_ = '_'},
[delete(Group, id(C)) ||
C <- mnesia:select(?TABLE, [{MatchHead, [], ['$1']}])].
errors(Results) -> [E || {error, E} <- Results].
create_tables() -> create_tables([?TABLE_DEF]).
create_tables([]) ->
ok;
create_tables([{Table, Attributes} | Ts]) ->
case mnesia:create_table(Table, Attributes) of
{atomic, ok} -> create_tables(Ts);
{aborted, {already_exists, ?TABLE}} -> create_tables(Ts);
Err -> Err
end.
table_definitions() ->
{Name, Attributes} = ?TABLE_DEF,
[{Name, [?TABLE_MATCH | Attributes]}].
with_exit_handler(Handler, Thunk) ->
try
Thunk()
catch
exit:{R, _} when R =:= noproc; R =:= nodedown;
R =:= normal; R =:= shutdown ->
Handler();
exit:{{R, _}, _} when R =:= nodedown; R =:= shutdown ->
Handler()
end.
add_proplists(P1, P2) ->
add_proplists(lists:keysort(1, P1), lists:keysort(1, P2), []).
add_proplists([], P2, Acc) -> P2 ++ Acc;
add_proplists(P1, [], Acc) -> P1 ++ Acc;
add_proplists([{K, V1} | P1], [{K, V2} | P2], Acc) ->
add_proplists(P1, P2, [{K, V1 + V2} | Acc]);
add_proplists([{K1, _} = KV | P1], [{K2, _} | _] = P2, Acc) when K1 < K2 ->
add_proplists(P1, P2, [KV | Acc]);
add_proplists(P1, [KV | P2], Acc) ->
add_proplists(P1, P2, [KV | Acc]).
child_order_from(ChildSpecs) ->
lists:zipwith(fun(C, N) ->
{id(C), N}
end, ChildSpecs, lists:seq(1, length(ChildSpecs))).
restore_child_order(ChildSpecs, ChildOrder) ->
lists:sort(fun(A, B) ->
proplists:get_value(id(A), ChildOrder)
< proplists:get_value(id(B), ChildOrder)
end, ChildSpecs).
|
95ebbc1c256c67a1514496f92139b0a7143f4d9e9a14eee3e14c5a6fe9e8cf2f | qiao/sicp-solutions | 2.58.scm | (define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
(else
(error "unknown expression type -- DERIV" exp))))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list a1 '+ a2))))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list m1 '* m2))))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (sum? x)
(and (pair? x) (eq? (cadr x) '+)))
(define (addend s) (car s))
(define (augend s) (caddr s))
(define (product? x)
(and (pair? x) (eq? (cadr x) '*)))
(define (multiplier p) (car p))
(define (multiplicand p) (caddr p))
| null | https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter2/2.58.scm | scheme | (define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
(else
(error "unknown expression type -- DERIV" exp))))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list a1 '+ a2))))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list m1 '* m2))))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (sum? x)
(and (pair? x) (eq? (cadr x) '+)))
(define (addend s) (car s))
(define (augend s) (caddr s))
(define (product? x)
(and (pair? x) (eq? (cadr x) '*)))
(define (multiplier p) (car p))
(define (multiplicand p) (caddr p))
| |
99635f788601a0838b219c5f6547f2b8f1b8e02e1a3ba2820d84e28ec4348547 | maximedenes/native-coq | goptions.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(* This module manages customization parameters at the vernacular level *)
open Pp
open Errors
open Util
open Libobject
open Names
open Libnames
open Term
open Nametab
open Mod_subst
open Interface
type option_name = Interface.option_name
(****************************************************************************)
(* 0- Common things *)
let nickname table = String.concat " " table
let error_undeclared_key key =
error ((nickname key)^": no table or option of this type")
(****************************************************************************)
(* 1- Tables *)
class type ['a] table_of_A =
object
method add : 'a -> unit
method remove : 'a -> unit
method mem : 'a -> unit
method print : unit
end
module MakeTable =
functor
(A : sig
type t
type key
val table : (string * key table_of_A) list ref
val encode : key -> t
val subst : substitution -> t -> t
val printer : t -> std_ppcmds
val key : option_name
val title : string
val member_message : t -> bool -> std_ppcmds
val synchronous : bool
end) ->
struct
type option_mark =
| GOadd
| GOrmv
let nick = nickname A.key
let _ =
if List.mem_assoc nick !A.table then
error "Sorry, this table name is already used."
module MySet = Set.Make (struct type t = A.t let compare = compare end)
let t = ref (MySet.empty : MySet.t)
let _ =
if A.synchronous then
let freeze () = !t in
let unfreeze c = t := c in
let init () = t := MySet.empty in
Summary.declare_summary nick
{ Summary.freeze_function = freeze;
Summary.unfreeze_function = unfreeze;
Summary.init_function = init }
let (add_option,remove_option) =
if A.synchronous then
let cache_options (_,(f,p)) = match f with
| GOadd -> t := MySet.add p !t
| GOrmv -> t := MySet.remove p !t in
let load_options i o = if i=1 then cache_options o in
let subst_options (subst,(f,p as obj)) =
let p' = A.subst subst p in
if p' == p then obj else
(f,p')
in
let inGo : option_mark * A.t -> obj =
Libobject.declare_object {(Libobject.default_object nick) with
Libobject.load_function = load_options;
Libobject.open_function = load_options;
Libobject.cache_function = cache_options;
Libobject.subst_function = subst_options;
Libobject.classify_function = (fun x -> Substitute x)}
in
((fun c -> Lib.add_anonymous_leaf (inGo (GOadd, c))),
(fun c -> Lib.add_anonymous_leaf (inGo (GOrmv, c))))
else
((fun c -> t := MySet.add c !t),
(fun c -> t := MySet.remove c !t))
let print_table table_name printer table =
msg (str table_name ++
(hov 0
(if MySet.is_empty table then str "None" ++ fnl ()
else MySet.fold
(fun a b -> printer a ++ spc () ++ b)
table (mt ()) ++ fnl ())))
class table_of_A () =
object
method add x = add_option (A.encode x)
method remove x = remove_option (A.encode x)
method mem x =
let y = A.encode x in
let answer = MySet.mem y !t in
msg (A.member_message y answer ++ fnl ())
method print = print_table A.title A.printer !t
end
let _ = A.table := (nick,new table_of_A ())::!A.table
let active c = MySet.mem c !t
let elements () = MySet.elements !t
end
let string_table = ref []
let get_string_table k = List.assoc (nickname k) !string_table
module type StringConvertArg =
sig
val key : option_name
val title : string
val member_message : string -> bool -> std_ppcmds
val synchronous : bool
end
module StringConvert = functor (A : StringConvertArg) ->
struct
type t = string
type key = string
let table = string_table
let encode x = x
let subst _ x = x
let printer = str
let key = A.key
let title = A.title
let member_message = A.member_message
let synchronous = A.synchronous
end
module MakeStringTable =
functor (A : StringConvertArg) -> MakeTable (StringConvert(A))
let ref_table = ref []
let get_ref_table k = List.assoc (nickname k) !ref_table
module type RefConvertArg =
sig
type t
val encode : reference -> t
val subst : substitution -> t -> t
val printer : t -> std_ppcmds
val key : option_name
val title : string
val member_message : t -> bool -> std_ppcmds
val synchronous : bool
end
module RefConvert = functor (A : RefConvertArg) ->
struct
type t = A.t
type key = reference
let table = ref_table
let encode = A.encode
let subst = A.subst
let printer = A.printer
let key = A.key
let title = A.title
let member_message = A.member_message
let synchronous = A.synchronous
end
module MakeRefTable =
functor (A : RefConvertArg) -> MakeTable (RefConvert(A))
(****************************************************************************)
(* 2- Flags. *)
type 'a option_sig = {
optsync : bool;
optdepr : bool;
optname : string;
optkey : option_name;
optread : unit -> 'a;
optwrite : 'a -> unit }
type option_type = bool * (unit -> option_value) -> (option_value -> unit)
module OptionMap =
Map.Make (struct type t = option_name let compare = compare end)
let value_tab = ref OptionMap.empty
(* This raises Not_found if option of key [key] is unknown *)
let get_option key = OptionMap.find key !value_tab
let check_key key = try
let _ = get_option key in
error "Sorry, this option name is already used."
with Not_found ->
if List.mem_assoc (nickname key) !string_table
or List.mem_assoc (nickname key) !ref_table
then error "Sorry, this option name is already used."
open Summary
open Libobject
open Lib
let declare_option cast uncast
{ optsync=sync; optdepr=depr; optname=name; optkey=key; optread=read; optwrite=write } =
check_key key;
let default = read() in
spiwack : I use two spaces in the nicknames of " local " and " global " objects .
That way I should n't collide with [ nickname key ] for any [ key ] . As [ key]-s are
lists of strings * without * spaces .
That way I shouldn't collide with [nickname key] for any [key]. As [key]-s are
lists of strings *without* spaces. *)
let (write,lwrite,gwrite) = if sync then
let ldecl_obj = (* "Local": doesn't survive section or modules. *)
declare_object {(default_object ("L "^nickname key)) with
cache_function = (fun (_,v) -> write v);
classify_function = (fun _ -> Dispose)}
in
let decl_obj = (* default locality: survives sections but not modules. *)
declare_object {(default_object (nickname key)) with
cache_function = (fun (_,v) -> write v);
classify_function = (fun _ -> Dispose);
discharge_function = (fun (_,v) -> Some v)}
in
let gdecl_obj = (* "Global": survives section and modules. *)
declare_object {(default_object ("G "^nickname key)) with
cache_function = (fun (_,v) -> write v);
classify_function = (fun v -> Substitute v);
subst_function = (fun (_,v) -> v);
discharge_function = (fun (_,v) -> Some v);
load_function = (fun _ (_,v) -> write v)}
in
let _ = declare_summary (nickname key)
{ freeze_function = read;
unfreeze_function = write;
init_function = (fun () -> write default) }
in
begin fun v -> add_anonymous_leaf (decl_obj v) end ,
begin fun v -> add_anonymous_leaf (ldecl_obj v) end ,
begin fun v -> add_anonymous_leaf (gdecl_obj v) end
else write,write,write
in
let cread () = cast (read ()) in
let cwrite v = write (uncast v) in
let clwrite v = lwrite (uncast v) in
let cgwrite v = gwrite (uncast v) in
value_tab := OptionMap.add key (name, depr, (sync,cread,cwrite,clwrite,cgwrite)) !value_tab;
write
type 'a write_function = 'a -> unit
let declare_int_option =
declare_option
(fun v -> IntValue v)
(function IntValue v -> v | _ -> anomaly "async_option")
let declare_bool_option =
declare_option
(fun v -> BoolValue v)
(function BoolValue v -> v | _ -> anomaly "async_option")
let declare_string_option =
declare_option
(fun v -> StringValue v)
(function StringValue v -> v | _ -> anomaly "async_option")
(* 3- User accessible commands *)
(* Setting values of options *)
let set_option_value locality check_and_cast key v =
let (name, depr, (_,read,write,lwrite,gwrite)) =
try get_option key
with Not_found -> error ("There is no option "^(nickname key)^".")
in
let write = match locality with
| None -> write
| Some true -> lwrite
| Some false -> gwrite
in
write (check_and_cast v (read ()))
let bad_type_error () = error "Bad type of value for this option."
let check_int_value v = function
| IntValue _ -> IntValue v
| _ -> bad_type_error ()
let check_bool_value v = function
| BoolValue _ -> BoolValue v
| _ -> bad_type_error ()
let check_string_value v = function
| StringValue _ -> StringValue v
| _ -> bad_type_error ()
let check_unset_value v = function
| BoolValue _ -> BoolValue false
| IntValue _ -> IntValue None
| _ -> bad_type_error ()
(* Nota: For compatibility reasons, some errors are treated as
warning. This allows a script to refer to an option that doesn't
exist anymore *)
let set_int_option_value_gen locality =
set_option_value locality check_int_value
let set_bool_option_value_gen locality key v =
try set_option_value locality check_bool_value key v
with UserError (_,s) -> Flags.if_warn msg_warning s
let set_string_option_value_gen locality =
set_option_value locality check_string_value
let unset_option_value_gen locality key =
try set_option_value locality check_unset_value key ()
with UserError (_,s) -> Flags.if_warn msg_warning s
let set_int_option_value = set_int_option_value_gen None
let set_bool_option_value = set_bool_option_value_gen None
let set_string_option_value = set_string_option_value_gen None
(* Printing options/tables *)
let msg_option_value (name,v) =
match v with
| BoolValue true -> str "true"
| BoolValue false -> str "false"
| IntValue (Some n) -> int n
| IntValue None -> str "undefined"
| StringValue s -> str s
(* | IdentValue r -> pr_global_env Idset.empty r *)
let print_option_value key =
let (name, depr, (_,read,_,_,_)) = get_option key in
let s = read () in
match s with
| BoolValue b ->
msg (str ("The "^name^" mode is "^(if b then "on" else "off")) ++
fnl ())
| _ ->
msg (str ("Current value of "^name^" is ") ++
msg_option_value (name,s) ++ fnl ())
let get_tables () =
let tables = !value_tab in
let fold key (name, depr, (sync,read,_,_,_)) accu =
let state = {
opt_sync = sync;
opt_name = name;
opt_depr = depr;
opt_value = read ();
} in
OptionMap.add key state accu
in
OptionMap.fold fold tables OptionMap.empty
let print_tables () =
let print_option key name value depr =
let msg = str (" "^(nickname key)^": ") ++ msg_option_value (name, value) in
if depr then msg ++ str " [DEPRECATED]" ++ fnl ()
else msg ++ fnl ()
in
msg
(str "Synchronous options:" ++ fnl () ++
OptionMap.fold
(fun key (name, depr, (sync,read,_,_,_)) p ->
if sync then p ++ print_option key name (read ()) depr
else p)
!value_tab (mt ()) ++
str "Asynchronous options:" ++ fnl () ++
OptionMap.fold
(fun key (name, depr, (sync,read,_,_,_)) p ->
if sync then p
else p ++ print_option key name (read ()) depr)
!value_tab (mt ()) ++
str "Tables:" ++ fnl () ++
List.fold_right
(fun (nickkey,_) p -> p ++ str (" "^nickkey) ++ fnl ())
!string_table (mt ()) ++
List.fold_right
(fun (nickkey,_) p -> p ++ str (" "^nickkey) ++ fnl ())
!ref_table (mt ()) ++
fnl ()
)
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/library/goptions.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
This module manages customization parameters at the vernacular level
**************************************************************************
0- Common things
**************************************************************************
1- Tables
**************************************************************************
2- Flags.
This raises Not_found if option of key [key] is unknown
"Local": doesn't survive section or modules.
default locality: survives sections but not modules.
"Global": survives section and modules.
3- User accessible commands
Setting values of options
Nota: For compatibility reasons, some errors are treated as
warning. This allows a script to refer to an option that doesn't
exist anymore
Printing options/tables
| IdentValue r -> pr_global_env Idset.empty r | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Errors
open Util
open Libobject
open Names
open Libnames
open Term
open Nametab
open Mod_subst
open Interface
type option_name = Interface.option_name
let nickname table = String.concat " " table
let error_undeclared_key key =
error ((nickname key)^": no table or option of this type")
class type ['a] table_of_A =
object
method add : 'a -> unit
method remove : 'a -> unit
method mem : 'a -> unit
method print : unit
end
module MakeTable =
functor
(A : sig
type t
type key
val table : (string * key table_of_A) list ref
val encode : key -> t
val subst : substitution -> t -> t
val printer : t -> std_ppcmds
val key : option_name
val title : string
val member_message : t -> bool -> std_ppcmds
val synchronous : bool
end) ->
struct
type option_mark =
| GOadd
| GOrmv
let nick = nickname A.key
let _ =
if List.mem_assoc nick !A.table then
error "Sorry, this table name is already used."
module MySet = Set.Make (struct type t = A.t let compare = compare end)
let t = ref (MySet.empty : MySet.t)
let _ =
if A.synchronous then
let freeze () = !t in
let unfreeze c = t := c in
let init () = t := MySet.empty in
Summary.declare_summary nick
{ Summary.freeze_function = freeze;
Summary.unfreeze_function = unfreeze;
Summary.init_function = init }
let (add_option,remove_option) =
if A.synchronous then
let cache_options (_,(f,p)) = match f with
| GOadd -> t := MySet.add p !t
| GOrmv -> t := MySet.remove p !t in
let load_options i o = if i=1 then cache_options o in
let subst_options (subst,(f,p as obj)) =
let p' = A.subst subst p in
if p' == p then obj else
(f,p')
in
let inGo : option_mark * A.t -> obj =
Libobject.declare_object {(Libobject.default_object nick) with
Libobject.load_function = load_options;
Libobject.open_function = load_options;
Libobject.cache_function = cache_options;
Libobject.subst_function = subst_options;
Libobject.classify_function = (fun x -> Substitute x)}
in
((fun c -> Lib.add_anonymous_leaf (inGo (GOadd, c))),
(fun c -> Lib.add_anonymous_leaf (inGo (GOrmv, c))))
else
((fun c -> t := MySet.add c !t),
(fun c -> t := MySet.remove c !t))
let print_table table_name printer table =
msg (str table_name ++
(hov 0
(if MySet.is_empty table then str "None" ++ fnl ()
else MySet.fold
(fun a b -> printer a ++ spc () ++ b)
table (mt ()) ++ fnl ())))
class table_of_A () =
object
method add x = add_option (A.encode x)
method remove x = remove_option (A.encode x)
method mem x =
let y = A.encode x in
let answer = MySet.mem y !t in
msg (A.member_message y answer ++ fnl ())
method print = print_table A.title A.printer !t
end
let _ = A.table := (nick,new table_of_A ())::!A.table
let active c = MySet.mem c !t
let elements () = MySet.elements !t
end
let string_table = ref []
let get_string_table k = List.assoc (nickname k) !string_table
module type StringConvertArg =
sig
val key : option_name
val title : string
val member_message : string -> bool -> std_ppcmds
val synchronous : bool
end
module StringConvert = functor (A : StringConvertArg) ->
struct
type t = string
type key = string
let table = string_table
let encode x = x
let subst _ x = x
let printer = str
let key = A.key
let title = A.title
let member_message = A.member_message
let synchronous = A.synchronous
end
module MakeStringTable =
functor (A : StringConvertArg) -> MakeTable (StringConvert(A))
let ref_table = ref []
let get_ref_table k = List.assoc (nickname k) !ref_table
module type RefConvertArg =
sig
type t
val encode : reference -> t
val subst : substitution -> t -> t
val printer : t -> std_ppcmds
val key : option_name
val title : string
val member_message : t -> bool -> std_ppcmds
val synchronous : bool
end
module RefConvert = functor (A : RefConvertArg) ->
struct
type t = A.t
type key = reference
let table = ref_table
let encode = A.encode
let subst = A.subst
let printer = A.printer
let key = A.key
let title = A.title
let member_message = A.member_message
let synchronous = A.synchronous
end
module MakeRefTable =
functor (A : RefConvertArg) -> MakeTable (RefConvert(A))
type 'a option_sig = {
optsync : bool;
optdepr : bool;
optname : string;
optkey : option_name;
optread : unit -> 'a;
optwrite : 'a -> unit }
type option_type = bool * (unit -> option_value) -> (option_value -> unit)
module OptionMap =
Map.Make (struct type t = option_name let compare = compare end)
let value_tab = ref OptionMap.empty
let get_option key = OptionMap.find key !value_tab
let check_key key = try
let _ = get_option key in
error "Sorry, this option name is already used."
with Not_found ->
if List.mem_assoc (nickname key) !string_table
or List.mem_assoc (nickname key) !ref_table
then error "Sorry, this option name is already used."
open Summary
open Libobject
open Lib
let declare_option cast uncast
{ optsync=sync; optdepr=depr; optname=name; optkey=key; optread=read; optwrite=write } =
check_key key;
let default = read() in
spiwack : I use two spaces in the nicknames of " local " and " global " objects .
That way I should n't collide with [ nickname key ] for any [ key ] . As [ key]-s are
lists of strings * without * spaces .
That way I shouldn't collide with [nickname key] for any [key]. As [key]-s are
lists of strings *without* spaces. *)
let (write,lwrite,gwrite) = if sync then
declare_object {(default_object ("L "^nickname key)) with
cache_function = (fun (_,v) -> write v);
classify_function = (fun _ -> Dispose)}
in
declare_object {(default_object (nickname key)) with
cache_function = (fun (_,v) -> write v);
classify_function = (fun _ -> Dispose);
discharge_function = (fun (_,v) -> Some v)}
in
declare_object {(default_object ("G "^nickname key)) with
cache_function = (fun (_,v) -> write v);
classify_function = (fun v -> Substitute v);
subst_function = (fun (_,v) -> v);
discharge_function = (fun (_,v) -> Some v);
load_function = (fun _ (_,v) -> write v)}
in
let _ = declare_summary (nickname key)
{ freeze_function = read;
unfreeze_function = write;
init_function = (fun () -> write default) }
in
begin fun v -> add_anonymous_leaf (decl_obj v) end ,
begin fun v -> add_anonymous_leaf (ldecl_obj v) end ,
begin fun v -> add_anonymous_leaf (gdecl_obj v) end
else write,write,write
in
let cread () = cast (read ()) in
let cwrite v = write (uncast v) in
let clwrite v = lwrite (uncast v) in
let cgwrite v = gwrite (uncast v) in
value_tab := OptionMap.add key (name, depr, (sync,cread,cwrite,clwrite,cgwrite)) !value_tab;
write
type 'a write_function = 'a -> unit
let declare_int_option =
declare_option
(fun v -> IntValue v)
(function IntValue v -> v | _ -> anomaly "async_option")
let declare_bool_option =
declare_option
(fun v -> BoolValue v)
(function BoolValue v -> v | _ -> anomaly "async_option")
let declare_string_option =
declare_option
(fun v -> StringValue v)
(function StringValue v -> v | _ -> anomaly "async_option")
let set_option_value locality check_and_cast key v =
let (name, depr, (_,read,write,lwrite,gwrite)) =
try get_option key
with Not_found -> error ("There is no option "^(nickname key)^".")
in
let write = match locality with
| None -> write
| Some true -> lwrite
| Some false -> gwrite
in
write (check_and_cast v (read ()))
let bad_type_error () = error "Bad type of value for this option."
let check_int_value v = function
| IntValue _ -> IntValue v
| _ -> bad_type_error ()
let check_bool_value v = function
| BoolValue _ -> BoolValue v
| _ -> bad_type_error ()
let check_string_value v = function
| StringValue _ -> StringValue v
| _ -> bad_type_error ()
let check_unset_value v = function
| BoolValue _ -> BoolValue false
| IntValue _ -> IntValue None
| _ -> bad_type_error ()
let set_int_option_value_gen locality =
set_option_value locality check_int_value
let set_bool_option_value_gen locality key v =
try set_option_value locality check_bool_value key v
with UserError (_,s) -> Flags.if_warn msg_warning s
let set_string_option_value_gen locality =
set_option_value locality check_string_value
let unset_option_value_gen locality key =
try set_option_value locality check_unset_value key ()
with UserError (_,s) -> Flags.if_warn msg_warning s
let set_int_option_value = set_int_option_value_gen None
let set_bool_option_value = set_bool_option_value_gen None
let set_string_option_value = set_string_option_value_gen None
let msg_option_value (name,v) =
match v with
| BoolValue true -> str "true"
| BoolValue false -> str "false"
| IntValue (Some n) -> int n
| IntValue None -> str "undefined"
| StringValue s -> str s
let print_option_value key =
let (name, depr, (_,read,_,_,_)) = get_option key in
let s = read () in
match s with
| BoolValue b ->
msg (str ("The "^name^" mode is "^(if b then "on" else "off")) ++
fnl ())
| _ ->
msg (str ("Current value of "^name^" is ") ++
msg_option_value (name,s) ++ fnl ())
let get_tables () =
let tables = !value_tab in
let fold key (name, depr, (sync,read,_,_,_)) accu =
let state = {
opt_sync = sync;
opt_name = name;
opt_depr = depr;
opt_value = read ();
} in
OptionMap.add key state accu
in
OptionMap.fold fold tables OptionMap.empty
let print_tables () =
let print_option key name value depr =
let msg = str (" "^(nickname key)^": ") ++ msg_option_value (name, value) in
if depr then msg ++ str " [DEPRECATED]" ++ fnl ()
else msg ++ fnl ()
in
msg
(str "Synchronous options:" ++ fnl () ++
OptionMap.fold
(fun key (name, depr, (sync,read,_,_,_)) p ->
if sync then p ++ print_option key name (read ()) depr
else p)
!value_tab (mt ()) ++
str "Asynchronous options:" ++ fnl () ++
OptionMap.fold
(fun key (name, depr, (sync,read,_,_,_)) p ->
if sync then p
else p ++ print_option key name (read ()) depr)
!value_tab (mt ()) ++
str "Tables:" ++ fnl () ++
List.fold_right
(fun (nickkey,_) p -> p ++ str (" "^nickkey) ++ fnl ())
!string_table (mt ()) ++
List.fold_right
(fun (nickkey,_) p -> p ++ str (" "^nickkey) ++ fnl ())
!ref_table (mt ()) ++
fnl ()
)
|
888891732b40245a50b8abc19b1eba788628e25f7ed32148f0ec9d78a19aeaa7 | LeiWangHoward/Common-Lisp-Playground | trie_lw.lisp | (defpackage "trie"
(:use "common-lisp")
(:export "trie" "add-word" "mapc-trie" "read-words" "subtrie" "trie-count" "trie-word")
(in-package trie)
(defclass trie ()
((value :initform nil
:accessor trie-value)
(branches :initform (make-hash-table)
:accessor trie-branches)))
(defun add-word (word trie)
(cond ((equal (subseq word 1) "")
(if (gethash (elt word 0) (trie-branches trie))
(setf (trie-value (gethash (elt word 0) (trie-branches trie))) #\.)
(setf (gethash (elt word 0) (trie-branches trie)) (make-trie)
(trie-value (gethash (elt word 0) (trie-branches trie)))#\.)))
(t (unless (gethash (elt word 0) (trie-branches trie))
(setf (gethash (elt word 0) (trie-branches trie))
(make-trie)))
(add-word (subseq word 1) (gethash (elt word 0) (trie-branches trie))))))
( setf trie ( make - hash - table ) )
;(defstruct trie
; (b(make-hash-table)))
(defun subtrie(trie &rest args)
(s2 trie args))
(defun s2(trie lst)
(cond((null lst)trie)
((and(null(cdr lst))
(gethash(car lst)(trie-b trie)))
(gethash(car lst)(trie-b trie)))
((gethash(car lst)(trie-b trie))
(s2(gethash(car lst)(trie-b trie))(cdr lst)))
(t nil)))
(defun trie-word(trie)
(trie-wd trie))
(defun trie-count(trie)
(let((total 0))
(when(trie-wd trie)
(incf total))
(loop for key being the hash-keys of (trie-b trie) using (hash-value value)
do(incf total (trie-count value)))
total))
(defun mapc-trie(fn trie)
(loop for key being the hash-keys of (trie-b trie) using (hash-value value)
do(funcall fn key value)))
(defun read-words(path trie)
(with-open-file (str path :direction :input)
(do ((line (read-line str nil nil)
(read-line str nil nil)))
((null line) trie)
(add-word line trie))))
| null | https://raw.githubusercontent.com/LeiWangHoward/Common-Lisp-Playground/4130232954f1bbf8aa003d856ccb2ab382da0534/croosword-boggles/trie_lw.lisp | lisp | (defstruct trie
(b(make-hash-table)))
| (defpackage "trie"
(:use "common-lisp")
(:export "trie" "add-word" "mapc-trie" "read-words" "subtrie" "trie-count" "trie-word")
(in-package trie)
(defclass trie ()
((value :initform nil
:accessor trie-value)
(branches :initform (make-hash-table)
:accessor trie-branches)))
(defun add-word (word trie)
(cond ((equal (subseq word 1) "")
(if (gethash (elt word 0) (trie-branches trie))
(setf (trie-value (gethash (elt word 0) (trie-branches trie))) #\.)
(setf (gethash (elt word 0) (trie-branches trie)) (make-trie)
(trie-value (gethash (elt word 0) (trie-branches trie)))#\.)))
(t (unless (gethash (elt word 0) (trie-branches trie))
(setf (gethash (elt word 0) (trie-branches trie))
(make-trie)))
(add-word (subseq word 1) (gethash (elt word 0) (trie-branches trie))))))
( setf trie ( make - hash - table ) )
(defun subtrie(trie &rest args)
(s2 trie args))
(defun s2(trie lst)
(cond((null lst)trie)
((and(null(cdr lst))
(gethash(car lst)(trie-b trie)))
(gethash(car lst)(trie-b trie)))
((gethash(car lst)(trie-b trie))
(s2(gethash(car lst)(trie-b trie))(cdr lst)))
(t nil)))
(defun trie-word(trie)
(trie-wd trie))
(defun trie-count(trie)
(let((total 0))
(when(trie-wd trie)
(incf total))
(loop for key being the hash-keys of (trie-b trie) using (hash-value value)
do(incf total (trie-count value)))
total))
(defun mapc-trie(fn trie)
(loop for key being the hash-keys of (trie-b trie) using (hash-value value)
do(funcall fn key value)))
(defun read-words(path trie)
(with-open-file (str path :direction :input)
(do ((line (read-line str nil nil)
(read-line str nil nil)))
((null line) trie)
(add-word line trie))))
|
e3b74564336eaea6dd2235a6c8ec04061226af0e377063a57c1735dbb158fdd8 | ribelo/danzig | danzig_test.cljc | (ns ribelo.danzig-test
(:require [ribelo.danzig :as dz :refer [=>>]]
#?(:clj [clojure.test :as t]
:cljs [cljs.test :as t :include-macros true])))
(comment
(def data [0 1 2]))
(t/deftest comp-some
(let [data [0 1 2]]
(t/is
(= [1 2 3]
(into [] (dz/comp-some (map inc) (when false (map dec))) data)))))
(t/deftest fat-thread-last
(let [data [0 1 2]]
(t/is
(= [1 2 3]
(=>> data (map inc))))
(t/is
(= [1 2 3]
(=>> data (map inc) (when false (map dec)))))
(t/is
(= 1
(=>> data (map inc) first)))
(t/is
(= 3
(=>> data (map inc) last)))
(t/is
(= #{1 2 3}
(=>> data (map inc) (into #{}))))
(t/is
(= #{1 2 3}
(=>> data (map inc) (into #{}))))))
(t/deftest vecs->maps
(t/is
(= [{:a 0, :b 0} {:a 1, :b 2} {:a 3, :b 4}]
(=>> [[0 0] [1 2] [3 4]] (dz/vecs->maps {0 :a 1 :b}))
(=>> [[0 0] [1 2] [3 4]] (dz/vecs->maps [:a :b])))))
(t/deftest row
(t/is
(= {:a 0, :b 0}
(dz/row [:a :b] [0 0]))))
(comment
(def data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]))
(t/deftest where
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/testing "?f"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where (fn [{:keys [a]}] (= a -1)))))))
(t/testing "?k ?v"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where :a -1)))))
(t/testing "{?k ?v}"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where {:a -1})))))
(t/testing "?k ?f"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where :a neg?)))))
(t/testing "[?f1 [[?f2 & ?xs] | ?k/?v] ...]"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where [= :a :c]))))
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where [= :a -1]))))
(t/is
(= [{:a :some/key}]
(=>> [{:a :some/key} {:a :another/key}] (dz/where [= :a ':some/key]))))
(t/is
(= [{:a -1, :b 0, :c -1} {:a 0, :b 1, :c 1} {:a 1, :b 2, :c 3}]
(=>> data (dz/where [= [+ :a :b] :c]))))
(t/is
(= [{:a 0, :b 1, :c 1}]
(=>> data (dz/where [= [+ :a :b] [+ :a :c]]))))
(t/is
(= [{:a 0, :b 1, :c 1}]
(=>> data (dz/where [= [+ :a :b] [+ [+ :a :c] [- :b 1]]])))))))
(t/deftest column-names
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/is [:a :b :c]
(=>> data (dz/column-names ::dz/all)))
(t/is [:a :b :c]
(=>> data (dz/column-names :a)))))
(t/deftest select-column
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/is [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]
(=>> data (dz/select-columns :all)))
(t/is [{:a -1, :b 0} {:a 0, :b 1} {:a 1, :b 2}]
(=>> data (dz/select-columns :a :b)))
(t/is [{:a -1, :b 0} {:a 0, :b 1} {:a 1, :b 2}]
(=>> data (dz/select-columns #"a|b")))))
(t/deftest with
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/testing "?i ?k ?v"
(t/is
(= [{:a 999 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]
(=>> data (dz/with 0 :a 999)))))
(t/testing "?i ?m"
(t/is
(= [{:a 999 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]
(=>> data (dz/with 0 {:a 999})))))
(t/testing "?k ?f"
(t/is
(= [{:a -1, :b 0, :c -1, :d 9} {:a 0, :b 1, :c 1, :d 11} {:a 1, :b 2, :c 3, :d 13}]
(=>> data (dz/with :d (fn [{:keys [a b]}] (+ a b 10)))))))
(t/testing "?k ?v"
(t/is
(= [{:a -1, :b 0, :c -1, :d 5} {:a 0, :b 1, :c 1, :d 5} {:a 1, :b 2, :c 3, :d 5}]
(=>> data (dz/with :d 5)))))
(t/testing "?k [?f . !ks]"
(t/is
(= [{:a -1, :b 0, :c -1, :d 9} {:a 0, :b 1, :c 1, :d 11} {:a 1, :b 2, :c 3, :d 13}]
(=>> data (dz/with :d [+ :a :b 10])))))
(t/testing "?k [?f1 [[?f2 & ?xs] | ?k/?v] ...]}"
(t/is
(= [{:a 0, :b 0, :c -1} {:a 1, :b 1, :c 1} {:a 2, :b 2, :c 3}]
(=>> data (dz/with :a [+ :a 1]))))
(t/is
(= [{:a -1, :b 0, :c -1} {:a 1, :b 1, :c 1} {:a 3, :b 2, :c 3}]
(=>> data (dz/with :a [+ :a :b])))))
(t/testing "{?k [?f1 [[?f2 & ?xs] | ?k/?v] ...]}"
(t/is
(= [{:a 0, :b 5, :c -1} {:a 1, :b 6, :c 1} {:a 2, :b 7, :c 3}]
(=>> data (dz/with {:a [+ :a 1] :b [+ :b 5]}))))
(t/is
(= [{:a 0, :b 1, :c -1} {:a 1, :b 0, :c 1} {:a 2, :b -1, :c 3}]
(=>> data (dz/with {:a [+ :a 1] :b [- :b :c]})))))
(t/testing "{?k ?v}"
(t/is
(= [{:a 5, :b 10, :c -1} {:a 5, :b 10, :c 1} {:a 5, :b 10, :c 3}]
(=>> data (dz/with {:a 5 :b 10})))))
(t/testing "{?k ?f}"
(t/is
(= [{:a 0, :b 5, :c -1} {:a 1, :b 6, :c 1} {:a 2, :b 7, :c 3}]
(=>> data (dz/with {:a (fn [{:keys [a]}] (+ a 1))
:b (fn [{:keys [b]}] (+ b 5))})))))
(t/testing ":when ?pred & ?rest"
(t/is
(= [{:a 0, :b 5, :c -1} {:a 1, :b 6, :c 1} {:a 2, :b 7, :c 3}]
(=>> data (dz/with :when [= :a 0] :a 999)))))))
(comment
(require '[ribelo.danzig.aggregate :as agg])
(def data [{:a -1 :b [0 1 2] :c 0} {:a -1 :b [1 2 3] :c 0} {:a 1 :b [2 3 4] :c 1}]))
(t/deftest aggregate
(let [data [{:a -1 :b [0 1 2] :c 0} {:a -1 :b [1 2 3] :c 0} {:a 1 :b [2 3 4] :c 1}]]
(t/testing "?k/?f"
(t/is
(= [{:a -1, :b 18, :c 1}]
(=>> data (dz/aggregate {:a :sum
:b (comp (mapcat :b) (x/reduce +))
:c :sum})))))
))
(t/deftest group-by
(let [data [{:a -1 :b [0 1 2] :c 0} {:a -1 :b [1 2 3] :c 0} {:a 1 :b [2 3 4] :c 1}]]
(t/testing "?k/?f"
(t/is
(= [[-1 [{:a -1, :b [0 1 2], :c 0} {:a -1, :b [1 2 3], :c 0}]] [1 [{:a 1, :b [2 3 4], :c 1}]]]
(=>> data (dz/group-by :a)))))
(t/testing "?k/?f ?xf"
(t/is
(= [[-1 [{:a -1, :b [0 1 2], :c 0} {:a -1, :b [1 2 3], :c 0}]] [1 [{:a 1, :b [2 3 4], :c 1}]]]
(=>> data (dz/group-by :a (x/into [])))))
(t/is
(= [[-1 -2] [1 1]]
(=>> data (dz/group-by :a (comp (map :a) (x/reduce +))))))
(t/is
(= [[-1 -2] [1 1]]
(=>> data (dz/group-by :a (agg/sum :a)))))
(t/is
(= [[-1 -2] [1 1]]
(=>> data (dz/group-by :a :sum)))))
(t/testing "[!ks/!fs] ?xf"
(t/is
(= [[[-1 0] [{:a -1, :b [0 1 2], :c 0} {:a -1, :b [1 2 3], :c 0}]] [[1 1] [{:a 1, :b [2 3 4], :c 1}]]]
(=>> data (dz/group-by [:a :c] (x/into [])))))
)))
| null | https://raw.githubusercontent.com/ribelo/danzig/7936688d033b4d09f5fa6dfebda2f402e458592c/test/ribelo/danzig_test.cljc | clojure | (ns ribelo.danzig-test
(:require [ribelo.danzig :as dz :refer [=>>]]
#?(:clj [clojure.test :as t]
:cljs [cljs.test :as t :include-macros true])))
(comment
(def data [0 1 2]))
(t/deftest comp-some
(let [data [0 1 2]]
(t/is
(= [1 2 3]
(into [] (dz/comp-some (map inc) (when false (map dec))) data)))))
(t/deftest fat-thread-last
(let [data [0 1 2]]
(t/is
(= [1 2 3]
(=>> data (map inc))))
(t/is
(= [1 2 3]
(=>> data (map inc) (when false (map dec)))))
(t/is
(= 1
(=>> data (map inc) first)))
(t/is
(= 3
(=>> data (map inc) last)))
(t/is
(= #{1 2 3}
(=>> data (map inc) (into #{}))))
(t/is
(= #{1 2 3}
(=>> data (map inc) (into #{}))))))
(t/deftest vecs->maps
(t/is
(= [{:a 0, :b 0} {:a 1, :b 2} {:a 3, :b 4}]
(=>> [[0 0] [1 2] [3 4]] (dz/vecs->maps {0 :a 1 :b}))
(=>> [[0 0] [1 2] [3 4]] (dz/vecs->maps [:a :b])))))
(t/deftest row
(t/is
(= {:a 0, :b 0}
(dz/row [:a :b] [0 0]))))
(comment
(def data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]))
(t/deftest where
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/testing "?f"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where (fn [{:keys [a]}] (= a -1)))))))
(t/testing "?k ?v"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where :a -1)))))
(t/testing "{?k ?v}"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where {:a -1})))))
(t/testing "?k ?f"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where :a neg?)))))
(t/testing "[?f1 [[?f2 & ?xs] | ?k/?v] ...]"
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where [= :a :c]))))
(t/is
(= [{:a -1, :b 0 :c -1}]
(=>> data (dz/where [= :a -1]))))
(t/is
(= [{:a :some/key}]
(=>> [{:a :some/key} {:a :another/key}] (dz/where [= :a ':some/key]))))
(t/is
(= [{:a -1, :b 0, :c -1} {:a 0, :b 1, :c 1} {:a 1, :b 2, :c 3}]
(=>> data (dz/where [= [+ :a :b] :c]))))
(t/is
(= [{:a 0, :b 1, :c 1}]
(=>> data (dz/where [= [+ :a :b] [+ :a :c]]))))
(t/is
(= [{:a 0, :b 1, :c 1}]
(=>> data (dz/where [= [+ :a :b] [+ [+ :a :c] [- :b 1]]])))))))
(t/deftest column-names
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/is [:a :b :c]
(=>> data (dz/column-names ::dz/all)))
(t/is [:a :b :c]
(=>> data (dz/column-names :a)))))
(t/deftest select-column
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/is [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]
(=>> data (dz/select-columns :all)))
(t/is [{:a -1, :b 0} {:a 0, :b 1} {:a 1, :b 2}]
(=>> data (dz/select-columns :a :b)))
(t/is [{:a -1, :b 0} {:a 0, :b 1} {:a 1, :b 2}]
(=>> data (dz/select-columns #"a|b")))))
(t/deftest with
(let [data [{:a -1 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]]
(t/testing "?i ?k ?v"
(t/is
(= [{:a 999 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]
(=>> data (dz/with 0 :a 999)))))
(t/testing "?i ?m"
(t/is
(= [{:a 999 :b 0 :c -1} {:a 0 :b 1 :c 1} {:a 1 :b 2 :c 3}]
(=>> data (dz/with 0 {:a 999})))))
(t/testing "?k ?f"
(t/is
(= [{:a -1, :b 0, :c -1, :d 9} {:a 0, :b 1, :c 1, :d 11} {:a 1, :b 2, :c 3, :d 13}]
(=>> data (dz/with :d (fn [{:keys [a b]}] (+ a b 10)))))))
(t/testing "?k ?v"
(t/is
(= [{:a -1, :b 0, :c -1, :d 5} {:a 0, :b 1, :c 1, :d 5} {:a 1, :b 2, :c 3, :d 5}]
(=>> data (dz/with :d 5)))))
(t/testing "?k [?f . !ks]"
(t/is
(= [{:a -1, :b 0, :c -1, :d 9} {:a 0, :b 1, :c 1, :d 11} {:a 1, :b 2, :c 3, :d 13}]
(=>> data (dz/with :d [+ :a :b 10])))))
(t/testing "?k [?f1 [[?f2 & ?xs] | ?k/?v] ...]}"
(t/is
(= [{:a 0, :b 0, :c -1} {:a 1, :b 1, :c 1} {:a 2, :b 2, :c 3}]
(=>> data (dz/with :a [+ :a 1]))))
(t/is
(= [{:a -1, :b 0, :c -1} {:a 1, :b 1, :c 1} {:a 3, :b 2, :c 3}]
(=>> data (dz/with :a [+ :a :b])))))
(t/testing "{?k [?f1 [[?f2 & ?xs] | ?k/?v] ...]}"
(t/is
(= [{:a 0, :b 5, :c -1} {:a 1, :b 6, :c 1} {:a 2, :b 7, :c 3}]
(=>> data (dz/with {:a [+ :a 1] :b [+ :b 5]}))))
(t/is
(= [{:a 0, :b 1, :c -1} {:a 1, :b 0, :c 1} {:a 2, :b -1, :c 3}]
(=>> data (dz/with {:a [+ :a 1] :b [- :b :c]})))))
(t/testing "{?k ?v}"
(t/is
(= [{:a 5, :b 10, :c -1} {:a 5, :b 10, :c 1} {:a 5, :b 10, :c 3}]
(=>> data (dz/with {:a 5 :b 10})))))
(t/testing "{?k ?f}"
(t/is
(= [{:a 0, :b 5, :c -1} {:a 1, :b 6, :c 1} {:a 2, :b 7, :c 3}]
(=>> data (dz/with {:a (fn [{:keys [a]}] (+ a 1))
:b (fn [{:keys [b]}] (+ b 5))})))))
(t/testing ":when ?pred & ?rest"
(t/is
(= [{:a 0, :b 5, :c -1} {:a 1, :b 6, :c 1} {:a 2, :b 7, :c 3}]
(=>> data (dz/with :when [= :a 0] :a 999)))))))
(comment
(require '[ribelo.danzig.aggregate :as agg])
(def data [{:a -1 :b [0 1 2] :c 0} {:a -1 :b [1 2 3] :c 0} {:a 1 :b [2 3 4] :c 1}]))
(t/deftest aggregate
(let [data [{:a -1 :b [0 1 2] :c 0} {:a -1 :b [1 2 3] :c 0} {:a 1 :b [2 3 4] :c 1}]]
(t/testing "?k/?f"
(t/is
(= [{:a -1, :b 18, :c 1}]
(=>> data (dz/aggregate {:a :sum
:b (comp (mapcat :b) (x/reduce +))
:c :sum})))))
))
(t/deftest group-by
(let [data [{:a -1 :b [0 1 2] :c 0} {:a -1 :b [1 2 3] :c 0} {:a 1 :b [2 3 4] :c 1}]]
(t/testing "?k/?f"
(t/is
(= [[-1 [{:a -1, :b [0 1 2], :c 0} {:a -1, :b [1 2 3], :c 0}]] [1 [{:a 1, :b [2 3 4], :c 1}]]]
(=>> data (dz/group-by :a)))))
(t/testing "?k/?f ?xf"
(t/is
(= [[-1 [{:a -1, :b [0 1 2], :c 0} {:a -1, :b [1 2 3], :c 0}]] [1 [{:a 1, :b [2 3 4], :c 1}]]]
(=>> data (dz/group-by :a (x/into [])))))
(t/is
(= [[-1 -2] [1 1]]
(=>> data (dz/group-by :a (comp (map :a) (x/reduce +))))))
(t/is
(= [[-1 -2] [1 1]]
(=>> data (dz/group-by :a (agg/sum :a)))))
(t/is
(= [[-1 -2] [1 1]]
(=>> data (dz/group-by :a :sum)))))
(t/testing "[!ks/!fs] ?xf"
(t/is
(= [[[-1 0] [{:a -1, :b [0 1 2], :c 0} {:a -1, :b [1 2 3], :c 0}]] [[1 1] [{:a 1, :b [2 3 4], :c 1}]]]
(=>> data (dz/group-by [:a :c] (x/into [])))))
)))
| |
8986a3bfdb06865da8f48cecd7ef08570be66a613a7f26a6cadcf2a983b74989 | exercism/haskell | Binary.hs | {-# LANGUAGE BangPatterns #-}
module Binary (toDecimal) where
import Control.Monad (foldM)
import Data.Maybe (fromMaybe)
toDecimal :: String -> Int
toDecimal = fromMaybe 0 . foldM go 0
where
go !n c = (n * 2 +) `fmap` toDigit c
toDigit '0' = Just 0
toDigit '1' = Just 1
toDigit _ = Nothing
| null | https://raw.githubusercontent.com/exercism/haskell/ae17e9fc5ca736a228db6dda5e3f3b057fa6f3d0/exercises/practice/binary/.meta/examples/success-standard/src/Binary.hs | haskell | # LANGUAGE BangPatterns # | module Binary (toDecimal) where
import Control.Monad (foldM)
import Data.Maybe (fromMaybe)
toDecimal :: String -> Int
toDecimal = fromMaybe 0 . foldM go 0
where
go !n c = (n * 2 +) `fmap` toDigit c
toDigit '0' = Just 0
toDigit '1' = Just 1
toDigit _ = Nothing
|
2e41e62492f43c01e8d59ded6b189022199064d9f31f65a830dd00d2092e26f4 | oklm-wsh/MrMime | msgID.ml | type local = Rfc822.local
type word = Rfc822.word
type domain = Rfc822.domain
type msg_id = Rfc822.msg_id
let pp = Format.fprintf
let pp_lst ~sep pp_data fmt lst =
let rec aux = function
| [] -> ()
| [ x ] -> pp_data fmt x
| x :: r -> pp fmt "%a%a" pp_data x sep (); aux r
in aux lst
let pp_local = Address.pp_local
let pp_domain fmt (x : domain) = match x with
| `Domain lst ->
pp fmt "@[<hov>%a@]"
(pp_lst ~sep:(fun fmt () -> pp fmt ".") Format.pp_print_string) lst
| `Literal s -> pp fmt "[@[<hov>%s@]]" s
let pp fmt (local, domain) =
pp fmt "{@[<hov>local = %a;@ domain = %a@]}"
pp_local local
pp_domain domain
module Encoder =
struct
open Encoder
open Wrap
let w_left = Address.Encoder.w_local
let w_right = function
| `Domain lst ->
let rec aux = function
| [] -> noop
| [ x ] -> string x
| x :: r -> string x $ hovbox 0 $ string "." $ aux r $ close_box
in hovbox 0 $ aux lst $ close_box
| `Literal lit ->
hovbox 0
$ string "["
$ string lit
$ string "]"
$ close_box
let w_msg_id (local, domain) =
hovbox 0
$ char '<'
$ hovbox 1
$ w_left local
$ close_box
$ char '@'
$ hovbox 1
$ w_right domain
$ close_box
$ char '>'
$ close_box
end
module Decoder =
struct
let p_msg_id = Rfc822.msg_id
end
let of_string ?(chunk = 1024) s =
let s' = s ^ "\r\n" in
let l = String.length s' in
let i = Input.create_bytes chunk in
let rec aux consumed = function
| Parser.Fail _ -> None
| Parser.Read { buffer; k; } ->
let n = min chunk (l - consumed) in
Input.write_string buffer s' consumed n;
aux (consumed + n) @@ k n (if n = 0 then Parser.Complete else Parser.Incomplete)
| Parser.Done v -> Some v
in
aux 0 @@ Parser.run i Parser.(Rfc822.msg_id <* Rfc822.crlf)
let of_string_raw ?(chunk = 1024) s off len =
let i = Input.create_bytes chunk in
let rec aux consumed = function
| Parser.Fail _ -> None
| Parser.Read { buffer; k; } ->
let n = min chunk (len - (consumed - off)) in
Input.write_string buffer s consumed n;
aux (consumed + n) @@ k n (if n = 0 then Parser.Complete else Parser.Incomplete)
| Parser.Done v -> Some (v, consumed - off)
in
aux off @@ Parser.run i Rfc822.msg_id
| null | https://raw.githubusercontent.com/oklm-wsh/MrMime/4d2a9dc75905927a092c0424cff7462e2b26bb96/lib/msgID.ml | ocaml | type local = Rfc822.local
type word = Rfc822.word
type domain = Rfc822.domain
type msg_id = Rfc822.msg_id
let pp = Format.fprintf
let pp_lst ~sep pp_data fmt lst =
let rec aux = function
| [] -> ()
| [ x ] -> pp_data fmt x
| x :: r -> pp fmt "%a%a" pp_data x sep (); aux r
in aux lst
let pp_local = Address.pp_local
let pp_domain fmt (x : domain) = match x with
| `Domain lst ->
pp fmt "@[<hov>%a@]"
(pp_lst ~sep:(fun fmt () -> pp fmt ".") Format.pp_print_string) lst
| `Literal s -> pp fmt "[@[<hov>%s@]]" s
let pp fmt (local, domain) =
pp fmt "{@[<hov>local = %a;@ domain = %a@]}"
pp_local local
pp_domain domain
module Encoder =
struct
open Encoder
open Wrap
let w_left = Address.Encoder.w_local
let w_right = function
| `Domain lst ->
let rec aux = function
| [] -> noop
| [ x ] -> string x
| x :: r -> string x $ hovbox 0 $ string "." $ aux r $ close_box
in hovbox 0 $ aux lst $ close_box
| `Literal lit ->
hovbox 0
$ string "["
$ string lit
$ string "]"
$ close_box
let w_msg_id (local, domain) =
hovbox 0
$ char '<'
$ hovbox 1
$ w_left local
$ close_box
$ char '@'
$ hovbox 1
$ w_right domain
$ close_box
$ char '>'
$ close_box
end
module Decoder =
struct
let p_msg_id = Rfc822.msg_id
end
let of_string ?(chunk = 1024) s =
let s' = s ^ "\r\n" in
let l = String.length s' in
let i = Input.create_bytes chunk in
let rec aux consumed = function
| Parser.Fail _ -> None
| Parser.Read { buffer; k; } ->
let n = min chunk (l - consumed) in
Input.write_string buffer s' consumed n;
aux (consumed + n) @@ k n (if n = 0 then Parser.Complete else Parser.Incomplete)
| Parser.Done v -> Some v
in
aux 0 @@ Parser.run i Parser.(Rfc822.msg_id <* Rfc822.crlf)
let of_string_raw ?(chunk = 1024) s off len =
let i = Input.create_bytes chunk in
let rec aux consumed = function
| Parser.Fail _ -> None
| Parser.Read { buffer; k; } ->
let n = min chunk (len - (consumed - off)) in
Input.write_string buffer s consumed n;
aux (consumed + n) @@ k n (if n = 0 then Parser.Complete else Parser.Incomplete)
| Parser.Done v -> Some (v, consumed - off)
in
aux off @@ Parser.run i Rfc822.msg_id
| |
35d8955548393ad7fe70280a949de221eef9b3bb2e95de345ddfffeadc908fe0 | dmitryvk/sbcl-win32-threads | life.lisp | ;;;; This file contains the lifetime analysis phase in the compiler.
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB!C")
;;;; utilities
Link in a GLOBAL - CONFLICTS structure for TN in BLOCK with NUMBER
as the LTN number . The conflict is inserted in the per - TN
GLOBAL - CONFLICTS thread after the TN 's CURRENT - CONFLICT . We change
;;; the CURRENT-CONFLICT to point to the new conflict. Since we scan
the blocks in reverse DFO , this list is automatically built in
;;; order. We have to actually scan the current GLOBAL-TNs for the
;;; block in order to keep that thread sorted.
(defun add-global-conflict (kind tn block number)
(declare (type (member :read :write :read-only :live) kind)
(type tn tn) (type ir2-block block)
(type (or local-tn-number null) number))
(let ((new (make-global-conflicts kind tn block number)))
(let ((last (tn-current-conflict tn)))
(if last
(shiftf (global-conflicts-next-tnwise new)
(global-conflicts-next-tnwise last)
new)
(shiftf (global-conflicts-next-tnwise new)
(tn-global-conflicts tn)
new)))
(setf (tn-current-conflict tn) new)
(insert-block-global-conflict new block))
(values))
;;; Do the actual insertion of the conflict NEW into BLOCK's global
;;; conflicts.
(defun insert-block-global-conflict (new block)
(let ((global-num (tn-number (global-conflicts-tn new))))
(do ((prev nil conf)
(conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((or (null conf)
(> (tn-number (global-conflicts-tn conf)) global-num))
(if prev
(setf (global-conflicts-next-blockwise prev) new)
(setf (ir2-block-global-tns block) new))
(setf (global-conflicts-next-blockwise new) conf))))
(values))
;;; Reset the CURRENT-CONFLICT slot in all packed TNs to point to the
;;; head of the GLOBAL-CONFLICTS thread.
(defun reset-current-conflict (component)
(do-packed-tns (tn component)
(setf (tn-current-conflict tn) (tn-global-conflicts tn))))
;;; Cache the results of BLOCK-PHYSENV during lifetime analysis.
;;;
;;; Fetching the home-lambda of a block (needed in block-physenv) can
;;; be an expensive operation under some circumstances, and it needs
;;; to be done a lot during lifetime analysis when compiling with high
DEBUG ( e.g. 30 % of the total compilation time for CL - PPCRE with
DEBUG 3 just for that ) .
(defun cached-block-physenv (block)
(let ((physenv (block-physenv-cache block)))
(if (eq physenv :none)
(setf (block-physenv-cache block)
(block-physenv block))
physenv)))
;;;; pre-pass
Convert TN ( currently local ) to be a global TN , since we
discovered that it is referenced in more than one block . We just
add a global - conflicts structure with a kind derived from the KILL
;;; and LIVE sets.
(defun convert-to-global (tn)
(declare (type tn tn))
(let ((block (tn-local tn))
(num (tn-local-number tn)))
(add-global-conflict
(if (zerop (sbit (ir2-block-written block) num))
:read-only
(if (zerop (sbit (ir2-block-live-out block) num))
:write
:read))
tn block num))
(values))
;;; Scan all references to packed TNs in block. We assign LTN numbers
to each referenced TN , and also build the Kill and Live sets that
summarize the references to each TN for purposes of lifetime
;;; analysis.
;;;
;;; It is possible that we will run out of LTN numbers. If this
happens , then we return the VOP that we were processing at the
time we ran out , otherwise we return NIL .
;;;
If a TN is referenced in more than one block , then we must
;;; represent references using GLOBAL-CONFLICTS structures. When we
first see a TN , we assume it will be local . If we see a reference
later on in a different block , then we go back and fix the TN to
;;; global.
;;;
We must globalize TNs that have a block other than the current one
;;; in their LOCAL slot and have no GLOBAL-CONFLICTS. The latter
;;; condition is necessary because we always set Local and
LOCAL - NUMBER when we process a reference to a TN , even when the TN
;;; is already known to be global.
;;;
;;; When we see reference to global TNs during the scan, we add the
;;; global-conflict as :READ-ONLY, since we don't know the correct
;;; kind until we are done scanning the block.
(defun find-local-references (block)
(declare (type ir2-block block))
(let ((kill (ir2-block-written block))
(live (ir2-block-live-out block))
(tns (ir2-block-local-tns block)))
(let ((ltn-num (ir2-block-local-tn-count block)))
(do ((vop (ir2-block-last-vop block)
(vop-prev vop)))
((null vop))
(do ((ref (vop-refs vop) (tn-ref-next-ref ref)))
((null ref))
(let* ((tn (tn-ref-tn ref))
(local (tn-local tn))
(kind (tn-kind tn)))
(unless (member kind '(:component :environment :constant))
(unless (eq local block)
(when (= ltn-num local-tn-limit)
(return-from find-local-references vop))
(when local
(unless (tn-global-conflicts tn)
(convert-to-global tn))
(add-global-conflict :read-only tn block ltn-num))
(setf (tn-local tn) block)
(setf (tn-local-number tn) ltn-num)
(setf (svref tns ltn-num) tn)
(incf ltn-num))
(let ((num (tn-local-number tn)))
(if (tn-ref-write-p ref)
(setf (sbit kill num) 1 (sbit live num) 0)
(setf (sbit live num) 1)))))))
(setf (ir2-block-local-tn-count block) ltn-num)))
nil)
;;; Finish up the global conflicts for TNs referenced in BLOCK
;;; according to the local Kill and Live sets.
;;;
;;; We set the kind for TNs already in the global-TNs. If not written
;;; at all, then is :READ-ONLY, the default. Must have been referenced
;;; somehow, or we wouldn't have conflicts for it.
;;;
;;; We also iterate over all the local TNs, looking for TNs local to
;;; this block that are still live at the block beginning, and thus
must be global . This case is only important when a TN is read in a
;;; block but not written in any other, since otherwise the write
would promote the TN to global . But this does happen with various
;;; passing-location TNs that are magically written. This also serves
;;; to propagate the lives of erroneously uninitialized TNs so that
;;; consistency checks can detect them.
(defun init-global-conflict-kind (block)
(declare (type ir2-block block))
(let ((live (ir2-block-live-out block)))
(let ((kill (ir2-block-written block)))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf))
(let ((num (global-conflicts-number conf)))
(unless (zerop (sbit kill num))
(setf (global-conflicts-kind conf)
(if (zerop (sbit live num))
:write
:read))))))
(let ((ltns (ir2-block-local-tns block)))
(dotimes (i (ir2-block-local-tn-count block))
(let ((tn (svref ltns i)))
(unless (or (eq tn :more)
(tn-global-conflicts tn)
(zerop (sbit live i)))
(convert-to-global tn))))))
(values))
(defevent split-ir2-block "Split an IR2 block to meet LOCAL-TN-LIMIT.")
Move the code after the VOP LOSE in 2BLOCK into its own block . The
block is linked into the emit order following 2BLOCK . NUMBER is
;;; the block number assigned to the new block. We return the new
;;; block.
(defun split-ir2-blocks (2block lose number)
(declare (type ir2-block 2block) (type vop lose)
(type unsigned-byte number))
(event split-ir2-block (vop-node lose))
(let ((new (make-ir2-block (ir2-block-block 2block)))
(new-start (vop-next lose)))
(setf (ir2-block-number new) number)
(add-to-emit-order new 2block)
(do ((vop new-start (vop-next vop)))
((null vop))
(setf (vop-block vop) new))
(setf (ir2-block-start-vop new) new-start)
(shiftf (ir2-block-last-vop new) (ir2-block-last-vop 2block) lose)
(setf (vop-next lose) nil)
(setf (vop-prev new-start) nil)
new))
;;; Clear the global and local conflict info in BLOCK so that we can
;;; recompute it without any old cruft being retained. It is assumed
;;; that all LTN numbers are in use.
;;;
;;; First we delete all the global conflicts. The conflict we are
deleting must be the last in the TN 's GLOBAL - CONFLICTS , but we
;;; must scan for it in order to find the previous conflict.
;;;
Next , we scan the local TNs , nulling out the LOCAL slot in all TNs
;;; with no global conflicts. This allows these TNs to be treated as
;;; local when we scan the block again.
;;;
If there are conflicts , then we set LOCAL to one of the
;;; conflicting blocks. This ensures that LOCAL doesn't hold over
;;; BLOCK as its value, causing the subsequent reanalysis to think
that the TN has already been seen in that block .
;;;
This function must not be called on blocks that have : MORE TNs .
(defun clear-lifetime-info (block)
(declare (type ir2-block block))
(setf (ir2-block-local-tn-count block) 0)
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf)
(setf (ir2-block-global-tns block) nil))
(let ((tn (global-conflicts-tn conf)))
(aver (eq (tn-current-conflict tn) conf))
(aver (null (global-conflicts-next-tnwise conf)))
(do ((current (tn-global-conflicts tn)
(global-conflicts-next-tnwise current))
(prev nil current))
((eq current conf)
(if prev
(setf (global-conflicts-next-tnwise prev) nil)
(setf (tn-global-conflicts tn) nil))
(setf (tn-current-conflict tn) prev)))))
(fill (ir2-block-written block) 0)
(let ((ltns (ir2-block-local-tns block)))
(dotimes (i local-tn-limit)
(let ((tn (svref ltns i)))
(aver (not (eq tn :more)))
(let ((conf (tn-global-conflicts tn)))
(setf (tn-local tn)
(if conf
(global-conflicts-block conf)
nil))))))
(values))
;;; This provides a panic mode for assigning LTN numbers when there is
a VOP with so many more operands that they ca n't all be assigned
;;; distinct numbers. When this happens, we recover by assigning all
the & MORE operands the same LTN number . We can get away with this ,
;;; since all &MORE args (and results) are referenced simultaneously
;;; as far as conflict analysis is concerned.
;;;
BLOCK is the IR2 - BLOCK that the MORE VOP is at the end of . OPS is
the full argument or result TN - REF list . Fixed is the types of the
;;; fixed operands (used only to skip those operands.)
;;;
What we do is grab a LTN number , then make a : READ - ONLY global
conflict for each more operand TN . We require that there be no
;;; existing global conflict in BLOCK for any of the operands. Since
conflicts must be cleared before the first call , this only
prohibits the same TN being used both as a more operand and as any
other operand to the same VOP .
;;;
;;; We don't have to worry about getting the correct conflict kind,
since INIT - GLOBAL - CONFLICT - KIND will fix things up . Similarly ,
;;; FIND-LOCAL-REFERENCES will set the local conflict bit
;;; corresponding to this call.
;;;
We also set the LOCAL and LOCAL - NUMBER slots in each TN . It is
;;; possible that there are no operands in any given call to this
;;; function, but there had better be either some more args or more
;;; results.
(defun coalesce-more-ltn-numbers (block ops fixed)
(declare (type ir2-block block) (type (or tn-ref null) ops) (list fixed))
(let ((num (ir2-block-local-tn-count block)))
(aver (< num local-tn-limit))
(incf (ir2-block-local-tn-count block))
(setf (svref (ir2-block-local-tns block) num) :more)
(do ((op (do ((op ops (tn-ref-across op))
(i 0 (1+ i)))
((= i (length fixed)) op)
(declare (type index i)))
(tn-ref-across op)))
((null op))
(let ((tn (tn-ref-tn op)))
(assert
(flet ((frob (refs)
(do ((ref refs (tn-ref-next ref)))
((null ref) t)
(when (and (eq (vop-block (tn-ref-vop ref)) block)
(not (eq ref op)))
(return nil)))))
(and (frob (tn-reads tn)) (frob (tn-writes tn))))
() "More operand ~S used more than once in its VOP." op)
(aver (not (find-in #'global-conflicts-next-blockwise tn
(ir2-block-global-tns block)
:key #'global-conflicts-tn)))
(add-global-conflict :read-only tn block num)
(setf (tn-local tn) block)
(setf (tn-local-number tn) num))))
(values))
(defevent coalesce-more-ltn-numbers
"Coalesced LTN numbers for a more operand to meet LOCAL-TN-LIMIT.")
;;; Loop over the blocks in COMPONENT, assigning LTN numbers and
recording TN birth and death . The only interesting action is when
we run out of local TN numbers while finding local references .
;;;
If we run out of LTN numbers while processing a VOP within the
;;; block, then we just split off the VOPs we have successfully
;;; processed into their own block.
;;;
If we run out of LTN numbers while processing the our first VOP
( the last in the block ) , then it must be the case that this VOP
has large more operands . We split the VOP into its own block , and
then call COALESCE - MORE - LTN - NUMBERS to assign all the more
args / results the same LTN number(s ) .
;;;
;;; In either case, we clear the lifetime information that we computed
;;; so far, recomputing it after taking corrective action.
;;;
;;; Whenever we split a block, we finish the pre-pass on the split-off
;;; block by doing FIND-LOCAL-REFERENCES and
INIT - GLOBAL - CONFLICT - KIND . This ca n't run out of LTN numbers .
(defun lifetime-pre-pass (component)
(declare (type component component))
(let ((counter -1))
(declare (type fixnum counter))
(do-blocks-backwards (block component)
(let ((2block (block-info block)))
(do ((lose (find-local-references 2block)
(find-local-references 2block))
(last-lose nil lose)
(coalesced nil))
((not lose)
(init-global-conflict-kind 2block)
(setf (ir2-block-number 2block) (incf counter)))
(clear-lifetime-info 2block)
(cond
((vop-next lose)
(aver (not (eq last-lose lose)))
(let ((new (split-ir2-blocks 2block lose (incf counter))))
(aver (not (find-local-references new)))
(init-global-conflict-kind new)))
(t
(aver (not (eq lose coalesced)))
(setq coalesced lose)
(event coalesce-more-ltn-numbers (vop-node lose))
(let ((info (vop-info lose))
(new (if (vop-prev lose)
(split-ir2-blocks 2block (vop-prev lose)
(incf counter))
2block)))
(coalesce-more-ltn-numbers new (vop-args lose)
(vop-info-arg-types info))
(coalesce-more-ltn-numbers new (vop-results lose)
(vop-info-result-types info))
(let ((lose (find-local-references new)))
(aver (not lose)))
(init-global-conflict-kind new))))))))
(values))
environment TN stuff
Add a : LIVE global conflict for TN in 2BLOCK if there is none
present . If DEBUG - P is false ( a : ENVIRONMENT TN ) , then modify any
;;; existing conflict to be :LIVE.
(defun setup-environment-tn-conflict (tn 2block debug-p)
(declare (type tn tn) (type ir2-block 2block))
(let ((block-num (ir2-block-number 2block)))
(do ((conf (tn-current-conflict tn) (global-conflicts-next-tnwise conf))
(prev nil conf))
((or (null conf)
(> (ir2-block-number (global-conflicts-block conf)) block-num))
(setf (tn-current-conflict tn) prev)
(add-global-conflict :live tn 2block nil))
(when (eq (global-conflicts-block conf) 2block)
(unless (or debug-p
(eq (global-conflicts-kind conf) :live))
(setf (global-conflicts-kind conf) :live)
(setf (svref (ir2-block-local-tns 2block)
(global-conflicts-number conf))
nil)
(setf (global-conflicts-number conf) nil))
(setf (tn-current-conflict tn) conf)
(return))))
(values))
;;; Iterate over all the blocks in ENV, setting up :LIVE conflicts for
TN . We make the TN global if it is n't already . The TN must have at
;;; least one reference.
(defun setup-environment-tn-conflicts (component tn env debug-p)
(declare (type component component) (type tn tn) (type physenv env))
(when (and debug-p
(not (tn-global-conflicts tn))
(tn-local tn))
(convert-to-global tn))
(setf (tn-current-conflict tn) (tn-global-conflicts tn))
(do-blocks-backwards (block component)
(when (eq (cached-block-physenv block) env)
(let* ((2block (block-info block))
(last (do ((b (ir2-block-next 2block) (ir2-block-next b))
(prev 2block b))
((not (eq (ir2-block-block b) block))
prev))))
(do ((b last (ir2-block-prev b)))
((not (eq (ir2-block-block b) block)))
(setup-environment-tn-conflict tn b debug-p)))))
(values))
;;; Iterate over all the environment TNs, adding always-live conflicts
;;; as appropriate.
(defun setup-environment-live-conflicts (component)
(declare (type component component))
(dolist (fun (component-lambdas component))
(let* ((env (lambda-physenv fun))
(2env (physenv-info env)))
(dolist (tn (ir2-physenv-live-tns 2env))
(setup-environment-tn-conflicts component tn env nil))
(dolist (tn (ir2-physenv-debug-live-tns 2env))
(setup-environment-tn-conflicts component tn env t))))
(values))
Convert a : NORMAL or : DEBUG - ENVIRONMENT TN to an : ENVIRONMENT TN .
;;; This requires adding :LIVE conflicts to all blocks in TN-PHYSENV.
(defun convert-to-environment-tn (tn tn-physenv)
(declare (type tn tn) (type physenv tn-physenv))
(aver (member (tn-kind tn) '(:normal :debug-environment)))
(ecase (tn-kind tn)
(:debug-environment
(setq tn-physenv (tn-physenv tn))
(let* ((2env (physenv-info tn-physenv)))
(setf (ir2-physenv-debug-live-tns 2env)
(delete tn (ir2-physenv-debug-live-tns 2env)))))
(:normal
(setf (tn-local tn) nil)
(setf (tn-local-number tn) nil)))
(setup-environment-tn-conflicts *component-being-compiled* tn tn-physenv nil)
(setf (tn-kind tn) :environment)
(setf (tn-physenv tn) tn-physenv)
(push tn (ir2-physenv-live-tns (physenv-info tn-physenv)))
(values))
;;;; flow analysis
;;; For each GLOBAL-TN in BLOCK2 that is :LIVE, :READ or :READ-ONLY,
;;; ensure that there is a corresponding GLOBAL-CONFLICT in BLOCK1. If
;;; there is none, make a :LIVE GLOBAL-CONFLICT. If there is a
;;; :READ-ONLY conflict, promote it to :LIVE.
;;;
;;; If we did add a new conflict, return true, otherwise false. We
;;; don't need to return true when we promote a :READ-ONLY conflict,
;;; since it doesn't reveal any new information to predecessors of
;;; BLOCK1.
;;;
;;; We use the TN-CURRENT-CONFLICT to walk through the global
conflicts . Since the global conflicts for a TN are ordered by
;;; block, we can be sure that the CURRENT-CONFLICT always points at
;;; or before the block that we are looking at. This allows us to
quickly determine if there is a global conflict for a given TN in
;;; BLOCK1.
;;;
;;; When we scan down the conflicts, we know that there must be at
least one conflict for TN , since we got our hands on TN by picking
;;; it out of a conflict in BLOCK2.
;;;
;;; We leave the CURRENT-CONFLICT pointing to the conflict for BLOCK1.
;;; The CURRENT-CONFLICT must be initialized to the head of the
GLOBAL - CONFLICTS for the TN between each flow analysis iteration .
(defun propagate-live-tns (block1 block2)
(declare (type ir2-block block1 block2))
(let ((live-in (ir2-block-live-in block1))
(did-something nil))
(do ((conf2 (ir2-block-global-tns block2)
(global-conflicts-next-blockwise conf2)))
((null conf2))
(ecase (global-conflicts-kind conf2)
((:live :read :read-only)
(let* ((tn (global-conflicts-tn conf2))
(tn-conflicts (tn-current-conflict tn))
(number1 (ir2-block-number block1)))
(aver tn-conflicts)
(do ((current tn-conflicts (global-conflicts-next-tnwise current))
(prev nil current))
((or (null current)
(> (ir2-block-number (global-conflicts-block current))
number1))
(setf (tn-current-conflict tn) prev)
(add-global-conflict :live tn block1 nil)
(setq did-something t))
(when (eq (global-conflicts-block current) block1)
(case (global-conflicts-kind current)
(:live)
(:read-only
(setf (global-conflicts-kind current) :live)
(setf (svref (ir2-block-local-tns block1)
(global-conflicts-number current))
nil)
(setf (global-conflicts-number current) nil))
(t
(setf (sbit live-in (global-conflicts-number current)) 1)))
(setf (tn-current-conflict tn) current)
(return)))))
(:write)))
did-something))
;;; Do backward global flow analysis to find all TNs live at each
;;; block boundary.
(defun lifetime-flow-analysis (component)
(loop
(reset-current-conflict component)
(let ((did-something nil))
(do-blocks-backwards (block component)
(let* ((2block (block-info block))
(last (do ((b (ir2-block-next 2block) (ir2-block-next b))
(prev 2block b))
((not (eq (ir2-block-block b) block))
prev))))
(dolist (b (block-succ block))
(when (and (block-start b)
(propagate-live-tns last (block-info b)))
(setq did-something t)))
(do ((b (ir2-block-prev last) (ir2-block-prev b))
(prev last b))
((not (eq (ir2-block-block b) block)))
(when (propagate-live-tns b prev)
(setq did-something t)))))
(unless did-something (return))))
(values))
;;;; post-pass
Note that TN conflicts with all current live TNs . NUM is TN 's LTN
number . We bit - ior LIVE - BITS with TN 's LOCAL - CONFLICTS , and set TN 's
;;; number in the conflicts of all TNs in LIVE-LIST.
(defun note-conflicts (live-bits live-list tn num)
(declare (type tn tn) (type (or tn null) live-list)
(type local-tn-bit-vector live-bits)
(type local-tn-number num))
(let ((lconf (tn-local-conflicts tn)))
(bit-ior live-bits lconf lconf))
(do ((live live-list (tn-next* live)))
((null live))
(setf (sbit (tn-local-conflicts live) num) 1))
(values))
Compute a bit vector of the TNs live after VOP that are n't results .
(defun compute-save-set (vop live-bits)
(declare (type vop vop) (type local-tn-bit-vector live-bits))
(let ((live (bit-vector-copy live-bits)))
(do ((r (vop-results vop) (tn-ref-across r)))
((null r))
(let ((tn (tn-ref-tn r)))
(ecase (tn-kind tn)
((:normal :debug-environment)
(setf (sbit live (tn-local-number tn)) 0))
(:environment :component))))
live))
;;; This is used to determine whether a :DEBUG-ENVIRONMENT TN should
be considered live at block end . We return true if a VOP with
non - null SAVE - P appears before the first read of TN ( hence is seen
first in our backward scan . )
(defun saved-after-read (tn block)
(do ((vop (ir2-block-last-vop block) (vop-prev vop)))
((null vop) t)
(when (vop-info-save-p (vop-info vop)) (return t))
(when (find-in #'tn-ref-across tn (vop-args vop) :key #'tn-ref-tn)
(return nil))))
;;; If the block has no successors, or its successor is the component
;;; tail, then all :DEBUG-ENVIRONMENT TNs are always added, regardless
;;; of whether they appeared to be live. This ensures that these TNs
;;; are considered to be live throughout blocks that read them, but
;;; don't have any interesting successors (such as a return or tail
;;; call.) In this case, we set the corresponding bit in LIVE-IN as
;;; well.
(defun make-debug-environment-tns-live (block live-bits live-list)
(let* ((1block (ir2-block-block block))
(live-in (ir2-block-live-in block))
(succ (block-succ 1block))
(next (ir2-block-next block)))
(when (and next
(not (eq (ir2-block-block next) 1block))
(or (null succ)
(eq (first succ)
(component-tail (block-component 1block)))))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf))
(let* ((tn (global-conflicts-tn conf))
(num (global-conflicts-number conf)))
(when (and num (zerop (sbit live-bits num))
(eq (tn-kind tn) :debug-environment)
(eq (tn-physenv tn) (cached-block-physenv 1block))
(saved-after-read tn block))
(note-conflicts live-bits live-list tn num)
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list)
(setf (sbit live-in num) 1))))))
(values live-bits live-list))
;;; Return as values, a LTN bit-vector and a list (threaded by
;;; TN-NEXT*) representing the TNs live at the end of BLOCK (exclusive
;;; of :LIVE TNs).
;;;
;;; We iterate over the TNs in the global conflicts that are live at
;;; the block end, setting up the TN-LOCAL-CONFLICTS and
TN - LOCAL - NUMBER , and adding the TN to the live list .
;;;
;;; If a :MORE result is not live, we effectively fake a read to it.
;;; This is part of the action described in ENSURE-RESULTS-LIVE.
;;;
;;; At the end, we call MAKE-DEBUG-ENVIRONEMNT-TNS-LIVE to make debug
;;; environment TNs appear live when appropriate, even when they
;;; aren't.
;;;
# # # Note : we alias the global - conflicts - conflicts here as the
;;; tn-local-conflicts.
(defun compute-initial-conflicts (block)
(declare (type ir2-block block))
(let* ((live-in (ir2-block-live-in block))
(ltns (ir2-block-local-tns block))
(live-bits (bit-vector-copy live-in))
(live-list nil))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf))
(let ((bits (global-conflicts-conflicts conf))
(tn (global-conflicts-tn conf))
(num (global-conflicts-number conf))
(kind (global-conflicts-kind conf)))
(setf (tn-local-number tn) num)
(unless (eq kind :live)
(cond ((not (zerop (sbit live-bits num)))
(bit-vector-replace bits live-bits)
(setf (sbit bits num) 0)
(push-in tn-next* tn live-list))
((and (eq (svref ltns num) :more)
(eq kind :write))
(note-conflicts live-bits live-list tn num)
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list)
(setf (sbit live-in num) 1)))
(setf (tn-local-conflicts tn) bits))))
(make-debug-environment-tns-live block live-bits live-list)))
A function called in CONFLICT - ANALYZE-1 - BLOCK when we have a VOP
with SAVE - P true . We compute the save - set , and if : FORCE - TO - STACK ,
;;; force all the live TNs to be stack environment TNs.
(defun conflictize-save-p-vop (vop block live-bits)
(declare (type vop vop) (type ir2-block block)
(type local-tn-bit-vector live-bits))
(let ((ss (compute-save-set vop live-bits)))
(setf (vop-save-set vop) ss)
(when (eq (vop-info-save-p (vop-info vop)) :force-to-stack)
(do-live-tns (tn ss block)
(unless (eq (tn-kind tn) :component)
(force-tn-to-stack tn)
(unless (eq (tn-kind tn) :environment)
(convert-to-environment-tn
tn
(cached-block-physenv (ir2-block-block block))))))))
(values))
FIXME : The next 3 macros are n't needed in the target runtime .
;;; Figure out some way to make them only at build time. (Just
( EVAL - WHEN (: - TOPLEVEL : EXECUTE ) ( DEFMACRO .. ) ) is n't good enough ,
since we need CL : DEFMACRO at build - the - cross - compiler time and
;;; SB!XC:DEFMACRO at run-the-cross-compiler time.)
;;; This is used in SCAN-VOP-REFS to simultaneously do something to
;;; all of the TNs referenced by a big more arg. We have to treat
;;; these TNs specially, since when we set or clear the bit in the
;;; live TNs, the represents a change in the liveness of all the more
;;; TNs. If we iterated as normal, the next more ref would be thought
to be not live when it was , etc . We update to be the last
;;; :more ref we scanned, so that the main loop will step to the next
;;; non-more ref.
(defmacro frob-more-tns (action)
`(when (eq (svref ltns num) :more)
(let ((prev ref))
(do ((mref (tn-ref-next-ref ref) (tn-ref-next-ref mref)))
((null mref))
(let ((mtn (tn-ref-tn mref)))
(unless (eql (tn-local-number mtn) num)
(return))
,action)
(setq prev mref))
(setq ref prev))))
Handle the part of CONFLICT - ANALYZE-1 - BLOCK that scans the REFs
for the current VOP . This macro shamelessly references free
;;; variables in C-A-1-B.
(defmacro scan-vop-refs ()
'(do ((ref (vop-refs vop) (tn-ref-next-ref ref)))
((null ref))
(let* ((tn (tn-ref-tn ref))
(num (tn-local-number tn)))
(cond
((not num))
((not (zerop (sbit live-bits num)))
(when (tn-ref-write-p ref)
(setf (sbit live-bits num) 0)
(deletef-in tn-next* live-list tn)
(frob-more-tns (deletef-in tn-next* live-list mtn))))
(t
(aver (not (tn-ref-write-p ref)))
(note-conflicts live-bits live-list tn num)
(frob-more-tns (note-conflicts live-bits live-list mtn num))
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list)
(frob-more-tns (push-in tn-next* mtn live-list)))))))
;;; This macro is called by CONFLICT-ANALYZE-1-BLOCK to scan the
current VOP 's results , and make any dead ones live . This is
necessary , since even though a result is dead after the VOP , it
may be in use for an extended period within the VOP ( especially if
;;; it has :FROM specified.) During this interval, temporaries must be
;;; noted to conflict with the result. More results are finessed in
;;; COMPUTE-INITIAL-CONFLICTS, so we ignore them here.
(defmacro ensure-results-live ()
'(do ((res (vop-results vop) (tn-ref-across res)))
((null res))
(let* ((tn (tn-ref-tn res))
(num (tn-local-number tn)))
(when (and num (zerop (sbit live-bits num)))
(unless (eq (svref ltns num) :more)
(note-conflicts live-bits live-list tn num)
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list))))))
;;; Compute the block-local conflict information for BLOCK. We iterate
over all the TN - REFs in a block in reference order , maintaining
;;; the set of live TNs in both a list and a bit-vector
;;; representation.
(defun conflict-analyze-1-block (block)
(declare (type ir2-block block))
(multiple-value-bind (live-bits live-list)
(compute-initial-conflicts block)
(let ((ltns (ir2-block-local-tns block)))
(do ((vop (ir2-block-last-vop block)
(vop-prev vop)))
((null vop))
(when (vop-info-save-p (vop-info vop))
(conflictize-save-p-vop vop block live-bits))
(ensure-results-live)
(scan-vop-refs)))))
;;; Conflict analyze each block, and also add it.
(defun lifetime-post-pass (component)
(declare (type component component))
(do-ir2-blocks (block component)
(conflict-analyze-1-block block)))
alias TN stuff
Destructively modify OCONF to include the conflict information in CONF .
(defun merge-alias-block-conflicts (conf oconf)
(declare (type global-conflicts conf oconf))
(let* ((kind (global-conflicts-kind conf))
(num (global-conflicts-number conf))
(okind (global-conflicts-kind oconf))
(onum (global-conflicts-number oconf))
(block (global-conflicts-block oconf))
(ltns (ir2-block-local-tns block)))
(cond
((eq okind :live))
((eq kind :live)
(setf (global-conflicts-kind oconf) :live)
(setf (svref ltns onum) nil)
(setf (global-conflicts-number oconf) nil))
(t
(unless (eq kind okind)
(setf (global-conflicts-kind oconf) :read))
;; Make original conflict with all the local TNs the alias
;; conflicted with.
(bit-ior (global-conflicts-conflicts oconf)
(global-conflicts-conflicts conf)
t)
(flet ((frob (x)
(unless (zerop (sbit x num))
(setf (sbit x onum) 1))))
;; Make all the local TNs that conflicted with the alias
;; conflict with the original.
(dotimes (i (ir2-block-local-tn-count block))
(let ((tn (svref ltns i)))
(when (and tn (not (eq tn :more))
(null (tn-global-conflicts tn)))
(frob (tn-local-conflicts tn)))))
;; Same for global TNs...
(do ((current (ir2-block-global-tns block)
(global-conflicts-next-blockwise current)))
((null current))
(unless (eq (global-conflicts-kind current) :live)
(frob (global-conflicts-conflicts current))))
Make the original TN live everywhere that the alias was live .
(frob (ir2-block-written block))
(frob (ir2-block-live-in block))
(frob (ir2-block-live-out block))
(do ((vop (ir2-block-start-vop block)
(vop-next vop)))
((null vop))
(let ((sset (vop-save-set vop)))
(when sset (frob sset)))))))
;; Delete the alias's conflict info.
(when num
(setf (svref ltns num) nil))
(deletef-in global-conflicts-next-blockwise
(ir2-block-global-tns block)
conf))
(values))
Co - opt CONF to be a conflict for TN .
(defun change-global-conflicts-tn (conf new)
(declare (type global-conflicts conf) (type tn new))
(setf (global-conflicts-tn conf) new)
(let ((ltn-num (global-conflicts-number conf))
(block (global-conflicts-block conf)))
(deletef-in global-conflicts-next-blockwise
(ir2-block-global-tns block)
conf)
(setf (global-conflicts-next-blockwise conf) nil)
(insert-block-global-conflict conf block)
(when ltn-num
(setf (svref (ir2-block-local-tns block) ltn-num) new)))
(values))
Do CONVERT - TO - GLOBAL on TN if it has no global conflicts . Copy the
;;; local conflicts into the global bit vector.
(defun ensure-global-tn (tn)
(declare (type tn tn))
(cond ((tn-global-conflicts tn))
((tn-local tn)
(convert-to-global tn)
(bit-ior (global-conflicts-conflicts (tn-global-conflicts tn))
(tn-local-conflicts tn)
t))
(t
(aver (and (null (tn-reads tn)) (null (tn-writes tn))))))
(values))
;;; For each :ALIAS TN, destructively merge the conflict info into the
original TN and replace the uses of the alias .
;;;
For any block that uses only the alias TN , just insert that
conflict into the conflicts for the original TN , changing the LTN
map to refer to the original TN . This gives a result
;;; indistinguishable from the what there would have been if the
original TN had always been referenced . This leaves no sign that
an alias TN was ever involved .
;;;
If a block has references to both the alias and the original TN ,
;;; then we call MERGE-ALIAS-BLOCK-CONFLICTS to combine the conflicts
;;; into the original conflict.
(defun merge-alias-conflicts (component)
(declare (type component component))
(do ((tn (ir2-component-alias-tns (component-info component))
(tn-next tn)))
((null tn))
(let ((original (tn-save-tn tn)))
(ensure-global-tn tn)
(ensure-global-tn original)
(let ((conf (tn-global-conflicts tn))
(oconf (tn-global-conflicts original))
(oprev nil))
(loop
(unless oconf
(if oprev
(setf (global-conflicts-next-tnwise oprev) conf)
(setf (tn-global-conflicts original) conf))
(do ((current conf (global-conflicts-next-tnwise current)))
((null current))
(change-global-conflicts-tn current original))
(return))
(let* ((block (global-conflicts-block conf))
(num (ir2-block-number block))
(onum (ir2-block-number (global-conflicts-block oconf))))
(cond ((< onum num)
(shiftf oprev oconf (global-conflicts-next-tnwise oconf)))
((> onum num)
(if oprev
(setf (global-conflicts-next-tnwise oprev) conf)
(setf (tn-global-conflicts original) conf))
(change-global-conflicts-tn conf original)
(shiftf oprev
conf
(global-conflicts-next-tnwise conf)
oconf))
(t
(merge-alias-block-conflicts conf oconf)
(shiftf oprev oconf (global-conflicts-next-tnwise oconf))
(setf conf (global-conflicts-next-tnwise conf)))))
(unless conf (return))))
(flet ((frob (refs)
(let ((ref refs)
(next nil))
(loop
(unless ref (return))
(setq next (tn-ref-next ref))
(change-tn-ref-tn ref original)
(setq ref next)))))
(frob (tn-reads tn))
(frob (tn-writes tn)))
(setf (tn-global-conflicts tn) nil)))
(values))
;;; On high debug levels, for all variables that a lambda closes over
;;; convert the TNs to :ENVIRONMENT TNs (in the physical environment
;;; of that lambda). This way the debugger can display the variables.
(defun maybe-environmentalize-closure-tns (component)
(dolist (lambda (component-lambdas component))
(when (policy lambda (>= debug 2))
(let ((physenv (lambda-physenv lambda)))
(dolist (closure-var (physenv-closure physenv))
(let ((tn (find-in-physenv closure-var physenv)))
(when (member (tn-kind tn) '(:normal :debug-environment))
(convert-to-environment-tn tn physenv))))))))
(defun lifetime-analyze (component)
(lifetime-pre-pass component)
(maybe-environmentalize-closure-tns component)
(setup-environment-live-conflicts component)
(lifetime-flow-analysis component)
(lifetime-post-pass component)
(merge-alias-conflicts component))
;;;; conflict testing
Test for a conflict between the local TN X and the global TN Y. We
just look for a global conflict of Y in X 's block , and then test
;;; for conflict in that block.
;;;
;;; [### Might be more efficient to scan Y's global conflicts. This
;;; depends on whether there are more global TNs than blocks.]
(defun tns-conflict-local-global (x y)
(let ((block (tn-local x)))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf) nil)
(when (eq (global-conflicts-tn conf) y)
(let ((num (global-conflicts-number conf)))
(return (or (not num)
(not (zerop (sbit (tn-local-conflicts x)
num))))))))))
Test for conflict between two global TNs X and Y.
(defun tns-conflict-global-global (x y)
(declare (type tn x y))
(let* ((x-conf (tn-global-conflicts x))
(x-num (ir2-block-number (global-conflicts-block x-conf)))
(y-conf (tn-global-conflicts y))
(y-num (ir2-block-number (global-conflicts-block y-conf))))
(macrolet ((advance (n c)
`(progn
(setq ,c (global-conflicts-next-tnwise ,c))
(unless ,c (return-from tns-conflict-global-global nil))
(setq ,n (ir2-block-number (global-conflicts-block ,c)))))
(scan (g l lc)
`(do ()
((>= ,g ,l))
(advance ,l ,lc))))
(loop
;; x-conf, y-conf true, x-num, y-num corresponding block numbers.
(scan x-num y-num y-conf)
(scan y-num x-num x-conf)
(when (= x-num y-num)
(let ((ltn-num-x (global-conflicts-number x-conf)))
(unless (and ltn-num-x
(global-conflicts-number y-conf)
(zerop (sbit (global-conflicts-conflicts y-conf)
ltn-num-x)))
(return t))
(advance x-num x-conf)
(advance y-num y-conf)))))))
;;; Return true if X and Y are distinct and the lifetimes of X and Y
;;; overlap at any point.
(defun tns-conflict (x y)
(declare (type tn x y))
(let ((x-kind (tn-kind x))
(y-kind (tn-kind y)))
(cond ((eq x y) nil)
((or (eq x-kind :component) (eq y-kind :component)) t)
((tn-global-conflicts x)
(if (tn-global-conflicts y)
(tns-conflict-global-global x y)
(tns-conflict-local-global y x)))
((tn-global-conflicts y)
(tns-conflict-local-global x y))
(t
(and (eq (tn-local x) (tn-local y))
(not (zerop (sbit (tn-local-conflicts x)
(tn-local-number y)))))))))
| null | https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/life.lisp | lisp | This file contains the lifetime analysis phase in the compiler.
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
utilities
the CURRENT-CONFLICT to point to the new conflict. Since we scan
order. We have to actually scan the current GLOBAL-TNs for the
block in order to keep that thread sorted.
Do the actual insertion of the conflict NEW into BLOCK's global
conflicts.
Reset the CURRENT-CONFLICT slot in all packed TNs to point to the
head of the GLOBAL-CONFLICTS thread.
Cache the results of BLOCK-PHYSENV during lifetime analysis.
Fetching the home-lambda of a block (needed in block-physenv) can
be an expensive operation under some circumstances, and it needs
to be done a lot during lifetime analysis when compiling with high
pre-pass
and LIVE sets.
Scan all references to packed TNs in block. We assign LTN numbers
analysis.
It is possible that we will run out of LTN numbers. If this
represent references using GLOBAL-CONFLICTS structures. When we
global.
in their LOCAL slot and have no GLOBAL-CONFLICTS. The latter
condition is necessary because we always set Local and
is already known to be global.
When we see reference to global TNs during the scan, we add the
global-conflict as :READ-ONLY, since we don't know the correct
kind until we are done scanning the block.
Finish up the global conflicts for TNs referenced in BLOCK
according to the local Kill and Live sets.
We set the kind for TNs already in the global-TNs. If not written
at all, then is :READ-ONLY, the default. Must have been referenced
somehow, or we wouldn't have conflicts for it.
We also iterate over all the local TNs, looking for TNs local to
this block that are still live at the block beginning, and thus
block but not written in any other, since otherwise the write
passing-location TNs that are magically written. This also serves
to propagate the lives of erroneously uninitialized TNs so that
consistency checks can detect them.
the block number assigned to the new block. We return the new
block.
Clear the global and local conflict info in BLOCK so that we can
recompute it without any old cruft being retained. It is assumed
that all LTN numbers are in use.
First we delete all the global conflicts. The conflict we are
must scan for it in order to find the previous conflict.
with no global conflicts. This allows these TNs to be treated as
local when we scan the block again.
conflicting blocks. This ensures that LOCAL doesn't hold over
BLOCK as its value, causing the subsequent reanalysis to think
This provides a panic mode for assigning LTN numbers when there is
distinct numbers. When this happens, we recover by assigning all
since all &MORE args (and results) are referenced simultaneously
as far as conflict analysis is concerned.
fixed operands (used only to skip those operands.)
existing global conflict in BLOCK for any of the operands. Since
We don't have to worry about getting the correct conflict kind,
FIND-LOCAL-REFERENCES will set the local conflict bit
corresponding to this call.
possible that there are no operands in any given call to this
function, but there had better be either some more args or more
results.
Loop over the blocks in COMPONENT, assigning LTN numbers and
block, then we just split off the VOPs we have successfully
processed into their own block.
In either case, we clear the lifetime information that we computed
so far, recomputing it after taking corrective action.
Whenever we split a block, we finish the pre-pass on the split-off
block by doing FIND-LOCAL-REFERENCES and
existing conflict to be :LIVE.
Iterate over all the blocks in ENV, setting up :LIVE conflicts for
least one reference.
Iterate over all the environment TNs, adding always-live conflicts
as appropriate.
This requires adding :LIVE conflicts to all blocks in TN-PHYSENV.
flow analysis
For each GLOBAL-TN in BLOCK2 that is :LIVE, :READ or :READ-ONLY,
ensure that there is a corresponding GLOBAL-CONFLICT in BLOCK1. If
there is none, make a :LIVE GLOBAL-CONFLICT. If there is a
:READ-ONLY conflict, promote it to :LIVE.
If we did add a new conflict, return true, otherwise false. We
don't need to return true when we promote a :READ-ONLY conflict,
since it doesn't reveal any new information to predecessors of
BLOCK1.
We use the TN-CURRENT-CONFLICT to walk through the global
block, we can be sure that the CURRENT-CONFLICT always points at
or before the block that we are looking at. This allows us to
BLOCK1.
When we scan down the conflicts, we know that there must be at
it out of a conflict in BLOCK2.
We leave the CURRENT-CONFLICT pointing to the conflict for BLOCK1.
The CURRENT-CONFLICT must be initialized to the head of the
Do backward global flow analysis to find all TNs live at each
block boundary.
post-pass
number in the conflicts of all TNs in LIVE-LIST.
This is used to determine whether a :DEBUG-ENVIRONMENT TN should
If the block has no successors, or its successor is the component
tail, then all :DEBUG-ENVIRONMENT TNs are always added, regardless
of whether they appeared to be live. This ensures that these TNs
are considered to be live throughout blocks that read them, but
don't have any interesting successors (such as a return or tail
call.) In this case, we set the corresponding bit in LIVE-IN as
well.
Return as values, a LTN bit-vector and a list (threaded by
TN-NEXT*) representing the TNs live at the end of BLOCK (exclusive
of :LIVE TNs).
We iterate over the TNs in the global conflicts that are live at
the block end, setting up the TN-LOCAL-CONFLICTS and
If a :MORE result is not live, we effectively fake a read to it.
This is part of the action described in ENSURE-RESULTS-LIVE.
At the end, we call MAKE-DEBUG-ENVIRONEMNT-TNS-LIVE to make debug
environment TNs appear live when appropriate, even when they
aren't.
tn-local-conflicts.
force all the live TNs to be stack environment TNs.
Figure out some way to make them only at build time. (Just
SB!XC:DEFMACRO at run-the-cross-compiler time.)
This is used in SCAN-VOP-REFS to simultaneously do something to
all of the TNs referenced by a big more arg. We have to treat
these TNs specially, since when we set or clear the bit in the
live TNs, the represents a change in the liveness of all the more
TNs. If we iterated as normal, the next more ref would be thought
:more ref we scanned, so that the main loop will step to the next
non-more ref.
variables in C-A-1-B.
This macro is called by CONFLICT-ANALYZE-1-BLOCK to scan the
it has :FROM specified.) During this interval, temporaries must be
noted to conflict with the result. More results are finessed in
COMPUTE-INITIAL-CONFLICTS, so we ignore them here.
Compute the block-local conflict information for BLOCK. We iterate
the set of live TNs in both a list and a bit-vector
representation.
Conflict analyze each block, and also add it.
Make original conflict with all the local TNs the alias
conflicted with.
Make all the local TNs that conflicted with the alias
conflict with the original.
Same for global TNs...
Delete the alias's conflict info.
local conflicts into the global bit vector.
For each :ALIAS TN, destructively merge the conflict info into the
indistinguishable from the what there would have been if the
then we call MERGE-ALIAS-BLOCK-CONFLICTS to combine the conflicts
into the original conflict.
On high debug levels, for all variables that a lambda closes over
convert the TNs to :ENVIRONMENT TNs (in the physical environment
of that lambda). This way the debugger can display the variables.
conflict testing
for conflict in that block.
[### Might be more efficient to scan Y's global conflicts. This
depends on whether there are more global TNs than blocks.]
x-conf, y-conf true, x-num, y-num corresponding block numbers.
Return true if X and Y are distinct and the lifetimes of X and Y
overlap at any point. |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB!C")
Link in a GLOBAL - CONFLICTS structure for TN in BLOCK with NUMBER
as the LTN number . The conflict is inserted in the per - TN
GLOBAL - CONFLICTS thread after the TN 's CURRENT - CONFLICT . We change
the blocks in reverse DFO , this list is automatically built in
(defun add-global-conflict (kind tn block number)
(declare (type (member :read :write :read-only :live) kind)
(type tn tn) (type ir2-block block)
(type (or local-tn-number null) number))
(let ((new (make-global-conflicts kind tn block number)))
(let ((last (tn-current-conflict tn)))
(if last
(shiftf (global-conflicts-next-tnwise new)
(global-conflicts-next-tnwise last)
new)
(shiftf (global-conflicts-next-tnwise new)
(tn-global-conflicts tn)
new)))
(setf (tn-current-conflict tn) new)
(insert-block-global-conflict new block))
(values))
(defun insert-block-global-conflict (new block)
(let ((global-num (tn-number (global-conflicts-tn new))))
(do ((prev nil conf)
(conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((or (null conf)
(> (tn-number (global-conflicts-tn conf)) global-num))
(if prev
(setf (global-conflicts-next-blockwise prev) new)
(setf (ir2-block-global-tns block) new))
(setf (global-conflicts-next-blockwise new) conf))))
(values))
(defun reset-current-conflict (component)
(do-packed-tns (tn component)
(setf (tn-current-conflict tn) (tn-global-conflicts tn))))
DEBUG ( e.g. 30 % of the total compilation time for CL - PPCRE with
DEBUG 3 just for that ) .
(defun cached-block-physenv (block)
(let ((physenv (block-physenv-cache block)))
(if (eq physenv :none)
(setf (block-physenv-cache block)
(block-physenv block))
physenv)))
Convert TN ( currently local ) to be a global TN , since we
discovered that it is referenced in more than one block . We just
add a global - conflicts structure with a kind derived from the KILL
(defun convert-to-global (tn)
(declare (type tn tn))
(let ((block (tn-local tn))
(num (tn-local-number tn)))
(add-global-conflict
(if (zerop (sbit (ir2-block-written block) num))
:read-only
(if (zerop (sbit (ir2-block-live-out block) num))
:write
:read))
tn block num))
(values))
to each referenced TN , and also build the Kill and Live sets that
summarize the references to each TN for purposes of lifetime
happens , then we return the VOP that we were processing at the
time we ran out , otherwise we return NIL .
If a TN is referenced in more than one block , then we must
first see a TN , we assume it will be local . If we see a reference
later on in a different block , then we go back and fix the TN to
We must globalize TNs that have a block other than the current one
LOCAL - NUMBER when we process a reference to a TN , even when the TN
(defun find-local-references (block)
(declare (type ir2-block block))
(let ((kill (ir2-block-written block))
(live (ir2-block-live-out block))
(tns (ir2-block-local-tns block)))
(let ((ltn-num (ir2-block-local-tn-count block)))
(do ((vop (ir2-block-last-vop block)
(vop-prev vop)))
((null vop))
(do ((ref (vop-refs vop) (tn-ref-next-ref ref)))
((null ref))
(let* ((tn (tn-ref-tn ref))
(local (tn-local tn))
(kind (tn-kind tn)))
(unless (member kind '(:component :environment :constant))
(unless (eq local block)
(when (= ltn-num local-tn-limit)
(return-from find-local-references vop))
(when local
(unless (tn-global-conflicts tn)
(convert-to-global tn))
(add-global-conflict :read-only tn block ltn-num))
(setf (tn-local tn) block)
(setf (tn-local-number tn) ltn-num)
(setf (svref tns ltn-num) tn)
(incf ltn-num))
(let ((num (tn-local-number tn)))
(if (tn-ref-write-p ref)
(setf (sbit kill num) 1 (sbit live num) 0)
(setf (sbit live num) 1)))))))
(setf (ir2-block-local-tn-count block) ltn-num)))
nil)
must be global . This case is only important when a TN is read in a
would promote the TN to global . But this does happen with various
(defun init-global-conflict-kind (block)
(declare (type ir2-block block))
(let ((live (ir2-block-live-out block)))
(let ((kill (ir2-block-written block)))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf))
(let ((num (global-conflicts-number conf)))
(unless (zerop (sbit kill num))
(setf (global-conflicts-kind conf)
(if (zerop (sbit live num))
:write
:read))))))
(let ((ltns (ir2-block-local-tns block)))
(dotimes (i (ir2-block-local-tn-count block))
(let ((tn (svref ltns i)))
(unless (or (eq tn :more)
(tn-global-conflicts tn)
(zerop (sbit live i)))
(convert-to-global tn))))))
(values))
(defevent split-ir2-block "Split an IR2 block to meet LOCAL-TN-LIMIT.")
Move the code after the VOP LOSE in 2BLOCK into its own block . The
block is linked into the emit order following 2BLOCK . NUMBER is
(defun split-ir2-blocks (2block lose number)
(declare (type ir2-block 2block) (type vop lose)
(type unsigned-byte number))
(event split-ir2-block (vop-node lose))
(let ((new (make-ir2-block (ir2-block-block 2block)))
(new-start (vop-next lose)))
(setf (ir2-block-number new) number)
(add-to-emit-order new 2block)
(do ((vop new-start (vop-next vop)))
((null vop))
(setf (vop-block vop) new))
(setf (ir2-block-start-vop new) new-start)
(shiftf (ir2-block-last-vop new) (ir2-block-last-vop 2block) lose)
(setf (vop-next lose) nil)
(setf (vop-prev new-start) nil)
new))
deleting must be the last in the TN 's GLOBAL - CONFLICTS , but we
Next , we scan the local TNs , nulling out the LOCAL slot in all TNs
If there are conflicts , then we set LOCAL to one of the
that the TN has already been seen in that block .
This function must not be called on blocks that have : MORE TNs .
(defun clear-lifetime-info (block)
(declare (type ir2-block block))
(setf (ir2-block-local-tn-count block) 0)
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf)
(setf (ir2-block-global-tns block) nil))
(let ((tn (global-conflicts-tn conf)))
(aver (eq (tn-current-conflict tn) conf))
(aver (null (global-conflicts-next-tnwise conf)))
(do ((current (tn-global-conflicts tn)
(global-conflicts-next-tnwise current))
(prev nil current))
((eq current conf)
(if prev
(setf (global-conflicts-next-tnwise prev) nil)
(setf (tn-global-conflicts tn) nil))
(setf (tn-current-conflict tn) prev)))))
(fill (ir2-block-written block) 0)
(let ((ltns (ir2-block-local-tns block)))
(dotimes (i local-tn-limit)
(let ((tn (svref ltns i)))
(aver (not (eq tn :more)))
(let ((conf (tn-global-conflicts tn)))
(setf (tn-local tn)
(if conf
(global-conflicts-block conf)
nil))))))
(values))
a VOP with so many more operands that they ca n't all be assigned
the & MORE operands the same LTN number . We can get away with this ,
BLOCK is the IR2 - BLOCK that the MORE VOP is at the end of . OPS is
the full argument or result TN - REF list . Fixed is the types of the
What we do is grab a LTN number , then make a : READ - ONLY global
conflict for each more operand TN . We require that there be no
conflicts must be cleared before the first call , this only
prohibits the same TN being used both as a more operand and as any
other operand to the same VOP .
since INIT - GLOBAL - CONFLICT - KIND will fix things up . Similarly ,
We also set the LOCAL and LOCAL - NUMBER slots in each TN . It is
(defun coalesce-more-ltn-numbers (block ops fixed)
(declare (type ir2-block block) (type (or tn-ref null) ops) (list fixed))
(let ((num (ir2-block-local-tn-count block)))
(aver (< num local-tn-limit))
(incf (ir2-block-local-tn-count block))
(setf (svref (ir2-block-local-tns block) num) :more)
(do ((op (do ((op ops (tn-ref-across op))
(i 0 (1+ i)))
((= i (length fixed)) op)
(declare (type index i)))
(tn-ref-across op)))
((null op))
(let ((tn (tn-ref-tn op)))
(assert
(flet ((frob (refs)
(do ((ref refs (tn-ref-next ref)))
((null ref) t)
(when (and (eq (vop-block (tn-ref-vop ref)) block)
(not (eq ref op)))
(return nil)))))
(and (frob (tn-reads tn)) (frob (tn-writes tn))))
() "More operand ~S used more than once in its VOP." op)
(aver (not (find-in #'global-conflicts-next-blockwise tn
(ir2-block-global-tns block)
:key #'global-conflicts-tn)))
(add-global-conflict :read-only tn block num)
(setf (tn-local tn) block)
(setf (tn-local-number tn) num))))
(values))
(defevent coalesce-more-ltn-numbers
"Coalesced LTN numbers for a more operand to meet LOCAL-TN-LIMIT.")
recording TN birth and death . The only interesting action is when
we run out of local TN numbers while finding local references .
If we run out of LTN numbers while processing a VOP within the
If we run out of LTN numbers while processing the our first VOP
( the last in the block ) , then it must be the case that this VOP
has large more operands . We split the VOP into its own block , and
then call COALESCE - MORE - LTN - NUMBERS to assign all the more
args / results the same LTN number(s ) .
INIT - GLOBAL - CONFLICT - KIND . This ca n't run out of LTN numbers .
(defun lifetime-pre-pass (component)
(declare (type component component))
(let ((counter -1))
(declare (type fixnum counter))
(do-blocks-backwards (block component)
(let ((2block (block-info block)))
(do ((lose (find-local-references 2block)
(find-local-references 2block))
(last-lose nil lose)
(coalesced nil))
((not lose)
(init-global-conflict-kind 2block)
(setf (ir2-block-number 2block) (incf counter)))
(clear-lifetime-info 2block)
(cond
((vop-next lose)
(aver (not (eq last-lose lose)))
(let ((new (split-ir2-blocks 2block lose (incf counter))))
(aver (not (find-local-references new)))
(init-global-conflict-kind new)))
(t
(aver (not (eq lose coalesced)))
(setq coalesced lose)
(event coalesce-more-ltn-numbers (vop-node lose))
(let ((info (vop-info lose))
(new (if (vop-prev lose)
(split-ir2-blocks 2block (vop-prev lose)
(incf counter))
2block)))
(coalesce-more-ltn-numbers new (vop-args lose)
(vop-info-arg-types info))
(coalesce-more-ltn-numbers new (vop-results lose)
(vop-info-result-types info))
(let ((lose (find-local-references new)))
(aver (not lose)))
(init-global-conflict-kind new))))))))
(values))
environment TN stuff
Add a : LIVE global conflict for TN in 2BLOCK if there is none
present . If DEBUG - P is false ( a : ENVIRONMENT TN ) , then modify any
(defun setup-environment-tn-conflict (tn 2block debug-p)
(declare (type tn tn) (type ir2-block 2block))
(let ((block-num (ir2-block-number 2block)))
(do ((conf (tn-current-conflict tn) (global-conflicts-next-tnwise conf))
(prev nil conf))
((or (null conf)
(> (ir2-block-number (global-conflicts-block conf)) block-num))
(setf (tn-current-conflict tn) prev)
(add-global-conflict :live tn 2block nil))
(when (eq (global-conflicts-block conf) 2block)
(unless (or debug-p
(eq (global-conflicts-kind conf) :live))
(setf (global-conflicts-kind conf) :live)
(setf (svref (ir2-block-local-tns 2block)
(global-conflicts-number conf))
nil)
(setf (global-conflicts-number conf) nil))
(setf (tn-current-conflict tn) conf)
(return))))
(values))
TN . We make the TN global if it is n't already . The TN must have at
(defun setup-environment-tn-conflicts (component tn env debug-p)
(declare (type component component) (type tn tn) (type physenv env))
(when (and debug-p
(not (tn-global-conflicts tn))
(tn-local tn))
(convert-to-global tn))
(setf (tn-current-conflict tn) (tn-global-conflicts tn))
(do-blocks-backwards (block component)
(when (eq (cached-block-physenv block) env)
(let* ((2block (block-info block))
(last (do ((b (ir2-block-next 2block) (ir2-block-next b))
(prev 2block b))
((not (eq (ir2-block-block b) block))
prev))))
(do ((b last (ir2-block-prev b)))
((not (eq (ir2-block-block b) block)))
(setup-environment-tn-conflict tn b debug-p)))))
(values))
(defun setup-environment-live-conflicts (component)
(declare (type component component))
(dolist (fun (component-lambdas component))
(let* ((env (lambda-physenv fun))
(2env (physenv-info env)))
(dolist (tn (ir2-physenv-live-tns 2env))
(setup-environment-tn-conflicts component tn env nil))
(dolist (tn (ir2-physenv-debug-live-tns 2env))
(setup-environment-tn-conflicts component tn env t))))
(values))
Convert a : NORMAL or : DEBUG - ENVIRONMENT TN to an : ENVIRONMENT TN .
(defun convert-to-environment-tn (tn tn-physenv)
(declare (type tn tn) (type physenv tn-physenv))
(aver (member (tn-kind tn) '(:normal :debug-environment)))
(ecase (tn-kind tn)
(:debug-environment
(setq tn-physenv (tn-physenv tn))
(let* ((2env (physenv-info tn-physenv)))
(setf (ir2-physenv-debug-live-tns 2env)
(delete tn (ir2-physenv-debug-live-tns 2env)))))
(:normal
(setf (tn-local tn) nil)
(setf (tn-local-number tn) nil)))
(setup-environment-tn-conflicts *component-being-compiled* tn tn-physenv nil)
(setf (tn-kind tn) :environment)
(setf (tn-physenv tn) tn-physenv)
(push tn (ir2-physenv-live-tns (physenv-info tn-physenv)))
(values))
conflicts . Since the global conflicts for a TN are ordered by
quickly determine if there is a global conflict for a given TN in
least one conflict for TN , since we got our hands on TN by picking
GLOBAL - CONFLICTS for the TN between each flow analysis iteration .
(defun propagate-live-tns (block1 block2)
(declare (type ir2-block block1 block2))
(let ((live-in (ir2-block-live-in block1))
(did-something nil))
(do ((conf2 (ir2-block-global-tns block2)
(global-conflicts-next-blockwise conf2)))
((null conf2))
(ecase (global-conflicts-kind conf2)
((:live :read :read-only)
(let* ((tn (global-conflicts-tn conf2))
(tn-conflicts (tn-current-conflict tn))
(number1 (ir2-block-number block1)))
(aver tn-conflicts)
(do ((current tn-conflicts (global-conflicts-next-tnwise current))
(prev nil current))
((or (null current)
(> (ir2-block-number (global-conflicts-block current))
number1))
(setf (tn-current-conflict tn) prev)
(add-global-conflict :live tn block1 nil)
(setq did-something t))
(when (eq (global-conflicts-block current) block1)
(case (global-conflicts-kind current)
(:live)
(:read-only
(setf (global-conflicts-kind current) :live)
(setf (svref (ir2-block-local-tns block1)
(global-conflicts-number current))
nil)
(setf (global-conflicts-number current) nil))
(t
(setf (sbit live-in (global-conflicts-number current)) 1)))
(setf (tn-current-conflict tn) current)
(return)))))
(:write)))
did-something))
(defun lifetime-flow-analysis (component)
(loop
(reset-current-conflict component)
(let ((did-something nil))
(do-blocks-backwards (block component)
(let* ((2block (block-info block))
(last (do ((b (ir2-block-next 2block) (ir2-block-next b))
(prev 2block b))
((not (eq (ir2-block-block b) block))
prev))))
(dolist (b (block-succ block))
(when (and (block-start b)
(propagate-live-tns last (block-info b)))
(setq did-something t)))
(do ((b (ir2-block-prev last) (ir2-block-prev b))
(prev last b))
((not (eq (ir2-block-block b) block)))
(when (propagate-live-tns b prev)
(setq did-something t)))))
(unless did-something (return))))
(values))
Note that TN conflicts with all current live TNs . NUM is TN 's LTN
number . We bit - ior LIVE - BITS with TN 's LOCAL - CONFLICTS , and set TN 's
(defun note-conflicts (live-bits live-list tn num)
(declare (type tn tn) (type (or tn null) live-list)
(type local-tn-bit-vector live-bits)
(type local-tn-number num))
(let ((lconf (tn-local-conflicts tn)))
(bit-ior live-bits lconf lconf))
(do ((live live-list (tn-next* live)))
((null live))
(setf (sbit (tn-local-conflicts live) num) 1))
(values))
Compute a bit vector of the TNs live after VOP that are n't results .
(defun compute-save-set (vop live-bits)
(declare (type vop vop) (type local-tn-bit-vector live-bits))
(let ((live (bit-vector-copy live-bits)))
(do ((r (vop-results vop) (tn-ref-across r)))
((null r))
(let ((tn (tn-ref-tn r)))
(ecase (tn-kind tn)
((:normal :debug-environment)
(setf (sbit live (tn-local-number tn)) 0))
(:environment :component))))
live))
be considered live at block end . We return true if a VOP with
non - null SAVE - P appears before the first read of TN ( hence is seen
first in our backward scan . )
(defun saved-after-read (tn block)
(do ((vop (ir2-block-last-vop block) (vop-prev vop)))
((null vop) t)
(when (vop-info-save-p (vop-info vop)) (return t))
(when (find-in #'tn-ref-across tn (vop-args vop) :key #'tn-ref-tn)
(return nil))))
(defun make-debug-environment-tns-live (block live-bits live-list)
(let* ((1block (ir2-block-block block))
(live-in (ir2-block-live-in block))
(succ (block-succ 1block))
(next (ir2-block-next block)))
(when (and next
(not (eq (ir2-block-block next) 1block))
(or (null succ)
(eq (first succ)
(component-tail (block-component 1block)))))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf))
(let* ((tn (global-conflicts-tn conf))
(num (global-conflicts-number conf)))
(when (and num (zerop (sbit live-bits num))
(eq (tn-kind tn) :debug-environment)
(eq (tn-physenv tn) (cached-block-physenv 1block))
(saved-after-read tn block))
(note-conflicts live-bits live-list tn num)
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list)
(setf (sbit live-in num) 1))))))
(values live-bits live-list))
TN - LOCAL - NUMBER , and adding the TN to the live list .
# # # Note : we alias the global - conflicts - conflicts here as the
(defun compute-initial-conflicts (block)
(declare (type ir2-block block))
(let* ((live-in (ir2-block-live-in block))
(ltns (ir2-block-local-tns block))
(live-bits (bit-vector-copy live-in))
(live-list nil))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf))
(let ((bits (global-conflicts-conflicts conf))
(tn (global-conflicts-tn conf))
(num (global-conflicts-number conf))
(kind (global-conflicts-kind conf)))
(setf (tn-local-number tn) num)
(unless (eq kind :live)
(cond ((not (zerop (sbit live-bits num)))
(bit-vector-replace bits live-bits)
(setf (sbit bits num) 0)
(push-in tn-next* tn live-list))
((and (eq (svref ltns num) :more)
(eq kind :write))
(note-conflicts live-bits live-list tn num)
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list)
(setf (sbit live-in num) 1)))
(setf (tn-local-conflicts tn) bits))))
(make-debug-environment-tns-live block live-bits live-list)))
A function called in CONFLICT - ANALYZE-1 - BLOCK when we have a VOP
with SAVE - P true . We compute the save - set , and if : FORCE - TO - STACK ,
(defun conflictize-save-p-vop (vop block live-bits)
(declare (type vop vop) (type ir2-block block)
(type local-tn-bit-vector live-bits))
(let ((ss (compute-save-set vop live-bits)))
(setf (vop-save-set vop) ss)
(when (eq (vop-info-save-p (vop-info vop)) :force-to-stack)
(do-live-tns (tn ss block)
(unless (eq (tn-kind tn) :component)
(force-tn-to-stack tn)
(unless (eq (tn-kind tn) :environment)
(convert-to-environment-tn
tn
(cached-block-physenv (ir2-block-block block))))))))
(values))
FIXME : The next 3 macros are n't needed in the target runtime .
( EVAL - WHEN (: - TOPLEVEL : EXECUTE ) ( DEFMACRO .. ) ) is n't good enough ,
since we need CL : DEFMACRO at build - the - cross - compiler time and
to be not live when it was , etc . We update to be the last
(defmacro frob-more-tns (action)
`(when (eq (svref ltns num) :more)
(let ((prev ref))
(do ((mref (tn-ref-next-ref ref) (tn-ref-next-ref mref)))
((null mref))
(let ((mtn (tn-ref-tn mref)))
(unless (eql (tn-local-number mtn) num)
(return))
,action)
(setq prev mref))
(setq ref prev))))
Handle the part of CONFLICT - ANALYZE-1 - BLOCK that scans the REFs
for the current VOP . This macro shamelessly references free
(defmacro scan-vop-refs ()
'(do ((ref (vop-refs vop) (tn-ref-next-ref ref)))
((null ref))
(let* ((tn (tn-ref-tn ref))
(num (tn-local-number tn)))
(cond
((not num))
((not (zerop (sbit live-bits num)))
(when (tn-ref-write-p ref)
(setf (sbit live-bits num) 0)
(deletef-in tn-next* live-list tn)
(frob-more-tns (deletef-in tn-next* live-list mtn))))
(t
(aver (not (tn-ref-write-p ref)))
(note-conflicts live-bits live-list tn num)
(frob-more-tns (note-conflicts live-bits live-list mtn num))
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list)
(frob-more-tns (push-in tn-next* mtn live-list)))))))
current VOP 's results , and make any dead ones live . This is
necessary , since even though a result is dead after the VOP , it
may be in use for an extended period within the VOP ( especially if
(defmacro ensure-results-live ()
'(do ((res (vop-results vop) (tn-ref-across res)))
((null res))
(let* ((tn (tn-ref-tn res))
(num (tn-local-number tn)))
(when (and num (zerop (sbit live-bits num)))
(unless (eq (svref ltns num) :more)
(note-conflicts live-bits live-list tn num)
(setf (sbit live-bits num) 1)
(push-in tn-next* tn live-list))))))
over all the TN - REFs in a block in reference order , maintaining
(defun conflict-analyze-1-block (block)
(declare (type ir2-block block))
(multiple-value-bind (live-bits live-list)
(compute-initial-conflicts block)
(let ((ltns (ir2-block-local-tns block)))
(do ((vop (ir2-block-last-vop block)
(vop-prev vop)))
((null vop))
(when (vop-info-save-p (vop-info vop))
(conflictize-save-p-vop vop block live-bits))
(ensure-results-live)
(scan-vop-refs)))))
(defun lifetime-post-pass (component)
(declare (type component component))
(do-ir2-blocks (block component)
(conflict-analyze-1-block block)))
alias TN stuff
Destructively modify OCONF to include the conflict information in CONF .
(defun merge-alias-block-conflicts (conf oconf)
(declare (type global-conflicts conf oconf))
(let* ((kind (global-conflicts-kind conf))
(num (global-conflicts-number conf))
(okind (global-conflicts-kind oconf))
(onum (global-conflicts-number oconf))
(block (global-conflicts-block oconf))
(ltns (ir2-block-local-tns block)))
(cond
((eq okind :live))
((eq kind :live)
(setf (global-conflicts-kind oconf) :live)
(setf (svref ltns onum) nil)
(setf (global-conflicts-number oconf) nil))
(t
(unless (eq kind okind)
(setf (global-conflicts-kind oconf) :read))
(bit-ior (global-conflicts-conflicts oconf)
(global-conflicts-conflicts conf)
t)
(flet ((frob (x)
(unless (zerop (sbit x num))
(setf (sbit x onum) 1))))
(dotimes (i (ir2-block-local-tn-count block))
(let ((tn (svref ltns i)))
(when (and tn (not (eq tn :more))
(null (tn-global-conflicts tn)))
(frob (tn-local-conflicts tn)))))
(do ((current (ir2-block-global-tns block)
(global-conflicts-next-blockwise current)))
((null current))
(unless (eq (global-conflicts-kind current) :live)
(frob (global-conflicts-conflicts current))))
Make the original TN live everywhere that the alias was live .
(frob (ir2-block-written block))
(frob (ir2-block-live-in block))
(frob (ir2-block-live-out block))
(do ((vop (ir2-block-start-vop block)
(vop-next vop)))
((null vop))
(let ((sset (vop-save-set vop)))
(when sset (frob sset)))))))
(when num
(setf (svref ltns num) nil))
(deletef-in global-conflicts-next-blockwise
(ir2-block-global-tns block)
conf))
(values))
Co - opt CONF to be a conflict for TN .
(defun change-global-conflicts-tn (conf new)
(declare (type global-conflicts conf) (type tn new))
(setf (global-conflicts-tn conf) new)
(let ((ltn-num (global-conflicts-number conf))
(block (global-conflicts-block conf)))
(deletef-in global-conflicts-next-blockwise
(ir2-block-global-tns block)
conf)
(setf (global-conflicts-next-blockwise conf) nil)
(insert-block-global-conflict conf block)
(when ltn-num
(setf (svref (ir2-block-local-tns block) ltn-num) new)))
(values))
Do CONVERT - TO - GLOBAL on TN if it has no global conflicts . Copy the
(defun ensure-global-tn (tn)
(declare (type tn tn))
(cond ((tn-global-conflicts tn))
((tn-local tn)
(convert-to-global tn)
(bit-ior (global-conflicts-conflicts (tn-global-conflicts tn))
(tn-local-conflicts tn)
t))
(t
(aver (and (null (tn-reads tn)) (null (tn-writes tn))))))
(values))
original TN and replace the uses of the alias .
For any block that uses only the alias TN , just insert that
conflict into the conflicts for the original TN , changing the LTN
map to refer to the original TN . This gives a result
original TN had always been referenced . This leaves no sign that
an alias TN was ever involved .
If a block has references to both the alias and the original TN ,
(defun merge-alias-conflicts (component)
(declare (type component component))
(do ((tn (ir2-component-alias-tns (component-info component))
(tn-next tn)))
((null tn))
(let ((original (tn-save-tn tn)))
(ensure-global-tn tn)
(ensure-global-tn original)
(let ((conf (tn-global-conflicts tn))
(oconf (tn-global-conflicts original))
(oprev nil))
(loop
(unless oconf
(if oprev
(setf (global-conflicts-next-tnwise oprev) conf)
(setf (tn-global-conflicts original) conf))
(do ((current conf (global-conflicts-next-tnwise current)))
((null current))
(change-global-conflicts-tn current original))
(return))
(let* ((block (global-conflicts-block conf))
(num (ir2-block-number block))
(onum (ir2-block-number (global-conflicts-block oconf))))
(cond ((< onum num)
(shiftf oprev oconf (global-conflicts-next-tnwise oconf)))
((> onum num)
(if oprev
(setf (global-conflicts-next-tnwise oprev) conf)
(setf (tn-global-conflicts original) conf))
(change-global-conflicts-tn conf original)
(shiftf oprev
conf
(global-conflicts-next-tnwise conf)
oconf))
(t
(merge-alias-block-conflicts conf oconf)
(shiftf oprev oconf (global-conflicts-next-tnwise oconf))
(setf conf (global-conflicts-next-tnwise conf)))))
(unless conf (return))))
(flet ((frob (refs)
(let ((ref refs)
(next nil))
(loop
(unless ref (return))
(setq next (tn-ref-next ref))
(change-tn-ref-tn ref original)
(setq ref next)))))
(frob (tn-reads tn))
(frob (tn-writes tn)))
(setf (tn-global-conflicts tn) nil)))
(values))
(defun maybe-environmentalize-closure-tns (component)
(dolist (lambda (component-lambdas component))
(when (policy lambda (>= debug 2))
(let ((physenv (lambda-physenv lambda)))
(dolist (closure-var (physenv-closure physenv))
(let ((tn (find-in-physenv closure-var physenv)))
(when (member (tn-kind tn) '(:normal :debug-environment))
(convert-to-environment-tn tn physenv))))))))
(defun lifetime-analyze (component)
(lifetime-pre-pass component)
(maybe-environmentalize-closure-tns component)
(setup-environment-live-conflicts component)
(lifetime-flow-analysis component)
(lifetime-post-pass component)
(merge-alias-conflicts component))
Test for a conflict between the local TN X and the global TN Y. We
just look for a global conflict of Y in X 's block , and then test
(defun tns-conflict-local-global (x y)
(let ((block (tn-local x)))
(do ((conf (ir2-block-global-tns block)
(global-conflicts-next-blockwise conf)))
((null conf) nil)
(when (eq (global-conflicts-tn conf) y)
(let ((num (global-conflicts-number conf)))
(return (or (not num)
(not (zerop (sbit (tn-local-conflicts x)
num))))))))))
Test for conflict between two global TNs X and Y.
(defun tns-conflict-global-global (x y)
(declare (type tn x y))
(let* ((x-conf (tn-global-conflicts x))
(x-num (ir2-block-number (global-conflicts-block x-conf)))
(y-conf (tn-global-conflicts y))
(y-num (ir2-block-number (global-conflicts-block y-conf))))
(macrolet ((advance (n c)
`(progn
(setq ,c (global-conflicts-next-tnwise ,c))
(unless ,c (return-from tns-conflict-global-global nil))
(setq ,n (ir2-block-number (global-conflicts-block ,c)))))
(scan (g l lc)
`(do ()
((>= ,g ,l))
(advance ,l ,lc))))
(loop
(scan x-num y-num y-conf)
(scan y-num x-num x-conf)
(when (= x-num y-num)
(let ((ltn-num-x (global-conflicts-number x-conf)))
(unless (and ltn-num-x
(global-conflicts-number y-conf)
(zerop (sbit (global-conflicts-conflicts y-conf)
ltn-num-x)))
(return t))
(advance x-num x-conf)
(advance y-num y-conf)))))))
(defun tns-conflict (x y)
(declare (type tn x y))
(let ((x-kind (tn-kind x))
(y-kind (tn-kind y)))
(cond ((eq x y) nil)
((or (eq x-kind :component) (eq y-kind :component)) t)
((tn-global-conflicts x)
(if (tn-global-conflicts y)
(tns-conflict-global-global x y)
(tns-conflict-local-global y x)))
((tn-global-conflicts y)
(tns-conflict-local-global x y))
(t
(and (eq (tn-local x) (tn-local y))
(not (zerop (sbit (tn-local-conflicts x)
(tn-local-number y)))))))))
|
83c92cb0f8b7b5935cdd64749894881edd3d71e0d4928ef64dd56d1f717e884f | REMath/mit_16.399 | baexp.mli | (* baexp.mli *)
open Abstract_Syntax
open Avalues
open Aenv
(* backward evaluation of arithmetic operations *)
val b_aexp : aexp -> Aenv.t -> Avalues.t -> Aenv.t
| null | https://raw.githubusercontent.com/REMath/mit_16.399/3f395d6a9dfa1ed232d307c3c542df3dbd5b614a/project/Initialization-Simple-Sign-FB-LDI-BA/baexp.mli | ocaml | baexp.mli
backward evaluation of arithmetic operations | open Abstract_Syntax
open Avalues
open Aenv
val b_aexp : aexp -> Aenv.t -> Avalues.t -> Aenv.t
|
2259864b8b65a8c26b2eba70fd53f58d51fee60e49c12452f2563f3caeb954da | jcclinton/wow-emulator | spell_callbacks.erl | This is a World of Warcraft emulator written in erlang , supporting
client 1.12.x
%%
Copyright ( C ) 2014 < jamieclinton.com >
%%
%% This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
%% (at your option) any later version.
%%
%% This program is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%% GNU General Public License for more details.
%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%
%% World of Warcraft, and all World of Warcraft or Warcraft art, images,
and lore ande copyrighted by Blizzard Entertainment , Inc.
-module(spell_callbacks).
-export([cast/1, cancel_cast/1]).
-include("include/binary.hrl").
-include("include/spell.hrl").
-include("include/database_records.hrl").
-include("include/data_types.hrl").
-spec cast(recv_data()) -> handler_response().
cast(Data) ->
Guid = recv_data:get(guid, Data),
Payload = recv_data:get(payload, Data),
<<SpellId?L, TargetMask?W, TargetsIn/binary>> = Payload,
io : format("cast i d ~p with mask ~p and targets ~p ~ n " , [ , TargetMask , TargetsIn ] ) ,
TargetInfo = spell_target_info:read(TargetMask, TargetsIn, Guid),
io : info : ~p ~ n " , [ TargetInfo ] ) ,
unit_spell:cast(Guid, SpellId, TargetInfo),
ok.
-spec cancel_cast(recv_data()) -> handler_response().
cancel_cast(Data) ->
<<SpellId?L>> = recv_data:get(payload, Data),
io:format("cancel spell id: ~p~n", [SpellId]),
Error = ?spell_failed_immune,
{smsg_cast_failed, <<SpellId?L, Error?B>>}.
| null | https://raw.githubusercontent.com/jcclinton/wow-emulator/21bc67bfc9eea131c447c67f7f889ba040dcdd79/src/handlers/spell_callbacks.erl | erlang |
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
World of Warcraft, and all World of Warcraft or Warcraft art, images, | This is a World of Warcraft emulator written in erlang , supporting
client 1.12.x
Copyright ( C ) 2014 < jamieclinton.com >
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
and lore ande copyrighted by Blizzard Entertainment , Inc.
-module(spell_callbacks).
-export([cast/1, cancel_cast/1]).
-include("include/binary.hrl").
-include("include/spell.hrl").
-include("include/database_records.hrl").
-include("include/data_types.hrl").
-spec cast(recv_data()) -> handler_response().
cast(Data) ->
Guid = recv_data:get(guid, Data),
Payload = recv_data:get(payload, Data),
<<SpellId?L, TargetMask?W, TargetsIn/binary>> = Payload,
io : format("cast i d ~p with mask ~p and targets ~p ~ n " , [ , TargetMask , TargetsIn ] ) ,
TargetInfo = spell_target_info:read(TargetMask, TargetsIn, Guid),
io : info : ~p ~ n " , [ TargetInfo ] ) ,
unit_spell:cast(Guid, SpellId, TargetInfo),
ok.
-spec cancel_cast(recv_data()) -> handler_response().
cancel_cast(Data) ->
<<SpellId?L>> = recv_data:get(payload, Data),
io:format("cancel spell id: ~p~n", [SpellId]),
Error = ?spell_failed_immune,
{smsg_cast_failed, <<SpellId?L, Error?B>>}.
|
861c9a5c9cfebcd6702758d471035dbaa985e712cf53841a38c501be453d0f33 | NetComposer/nksip | uas_test_server2.erl |
%% -------------------------------------------------------------------
%%
%% uas_test: Basic Test Suite
%%
Copyright ( c ) 2013 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(uas_test_server2).
-export([sip_route/5]).
-include_lib("nkserver/include/nkserver_module.hrl").
sip_route(_Scheme, _User, _Domain, _Req, _Call) ->
timer:sleep(500),
process.
| null | https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/test/callbacks/uas_test_server2.erl | erlang | -------------------------------------------------------------------
uas_test: Basic Test Suite
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
------------------------------------------------------------------- |
Copyright ( c ) 2013 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(uas_test_server2).
-export([sip_route/5]).
-include_lib("nkserver/include/nkserver_module.hrl").
sip_route(_Scheme, _User, _Domain, _Req, _Call) ->
timer:sleep(500),
process.
|
b2efa6232c63b83bc43f46cd5f4bfc212161aed7d70ad2cbdb59dd080bc1ebb2 | kadena-io/pact | Bench.hs | module Main where
import qualified Pact.Bench as Bench
main :: IO ()
main = Bench.main
| null | https://raw.githubusercontent.com/kadena-io/pact/e2f3dd1fd1952bb4f736042083769b52dbb2a819/executables/Bench.hs | haskell | module Main where
import qualified Pact.Bench as Bench
main :: IO ()
main = Bench.main
| |
b4108de5353029fb5ad4db06ccf2384ea2caf10ed16f5cb550c66d2190ff06cc | fredfeng/CS162 | eval.ml | open Ast
(** Variable set. Based on OCaml standard library Set. *)
module VarSet = Set.Make (String)
(* Helper function for parsing an expression. Useful for testing. *)
let parse (s: string) : Ast.expr =
Parser.main Scanner.token (Lexing.from_string s)
(*******************************************************************|
|********************** Interpreter ****************************|
|*******************************************************************|
|*******************************************************************)
(* Exception indicating that evaluation is stuck *)
exception Stuck of string
(* Raises an exception indicating that evaluation got stuck. *)
let im_stuck msg = raise (Stuck msg)
(* Raises an exception for things that need to be implemented
* in this assignment *)
let todo () = failwith "TODO"
(* Helper function to check that an expression is a value, otherwise raises a
Stuck exception. *)
let assert_value e =
if is_value e then () else im_stuck (string_of_expr e ^ " is not a value")
(** Computes the set of free variables in the given expression *)
let rec free_vars (e : expr) : VarSet.t =
failwith "TODO: homework" ;;
(** Performs the substitution [x -> e1]e2 *)
let rec subst (x : string) (e1 : expr) (e2 : expr) : expr =
failwith "TODO: homework" ;;
* Evaluates e. You need to copy over your
implementation of homework 3 .
implementation of homework 3. *)
let rec eval (e : expr) : expr =
try
match e with
| _ -> todo ()
with
| Stuck msg -> im_stuck (msg ^ "\nin expression " ^ string_of_expr e)
;;
| null | https://raw.githubusercontent.com/fredfeng/CS162/3e868a98e2b2b1ffc749a46a98b62df75ca4d46c/homework/hw4/eval.ml | ocaml | * Variable set. Based on OCaml standard library Set.
Helper function for parsing an expression. Useful for testing.
******************************************************************|
|********************** Interpreter ****************************|
|*******************************************************************|
|******************************************************************
Exception indicating that evaluation is stuck
Raises an exception indicating that evaluation got stuck.
Raises an exception for things that need to be implemented
* in this assignment
Helper function to check that an expression is a value, otherwise raises a
Stuck exception.
* Computes the set of free variables in the given expression
* Performs the substitution [x -> e1]e2 | open Ast
module VarSet = Set.Make (String)
let parse (s: string) : Ast.expr =
Parser.main Scanner.token (Lexing.from_string s)
exception Stuck of string
let im_stuck msg = raise (Stuck msg)
let todo () = failwith "TODO"
let assert_value e =
if is_value e then () else im_stuck (string_of_expr e ^ " is not a value")
let rec free_vars (e : expr) : VarSet.t =
failwith "TODO: homework" ;;
let rec subst (x : string) (e1 : expr) (e2 : expr) : expr =
failwith "TODO: homework" ;;
* Evaluates e. You need to copy over your
implementation of homework 3 .
implementation of homework 3. *)
let rec eval (e : expr) : expr =
try
match e with
| _ -> todo ()
with
| Stuck msg -> im_stuck (msg ^ "\nin expression " ^ string_of_expr e)
;;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.