_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 |
|---|---|---|---|---|---|---|---|---|
408a0a3b1dba2d241f99f363cbca90bda0356a864c88813e2767723225825b5b | TrustInSoft/tis-kernel | plugin.mli | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* 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 , version 2.1 .
(* *)
(* It 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. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(** Provided plug-general services for plug-ins.
@since Beryllium-20090601-beta1
@plugin development guide *)
module type S = sig
include Log.Messages
val add_group: ?memo:bool -> string -> Cmdline.Group.t
(** Create a new group inside the plug-in.
The given string must be different of all the other group names of this
plug-in if [memo] is [false].
If [memo] is [true] the function will either create a fresh group or
return an existing group of the same name in the same plugin.
[memo] defaults to [false]
@since Beryllium-20090901 *)
module Help: Parameter_sig.Bool
(** @deprecated since Oxygen-20120901 *)
module Verbose: Parameter_sig.Int
module Debug: Parameter_sig.Int
module Debug_category: Parameter_sig.String_set
(** prints debug messages having the corresponding key.
@since Oxygen-20120901
@modify Fluorine-20130401 Set instead of list
*)
(** Handle the specific `share' directory of the plug-in.
@since Oxygen-20120901 *)
module Share: Parameter_sig.Specific_dir
(** Handle the specific `session' directory of the plug-in.
@since Neon-20140301 *)
module Session: Parameter_sig.Specific_dir
(** Handle the specific `config' directory of the plug-in.
@since Neon-20140301 *)
module Config: Parameter_sig.Specific_dir
val help: Cmdline.Group.t
* The group containing option -*-help .
@since
@since Boron-20100401 *)
val messages: Cmdline.Group.t
* The group containing options -*-debug and -*-verbose .
@since
@since Boron-20100401 *)
end
type plugin = private
{ p_name: string;
p_shortname: string;
p_help: string;
p_parameters: (string, Typed_parameter.t list) Hashtbl.t }
(** Only iterable parameters (see {!do_iterate} and {!do_not_iterate}) are
registered in the field [p_parameters].
@since Beryllium-20090901 *)
module type General_services = sig
include S
include Parameter_sig.Builder
end
(**/**)
val register_kernel: unit -> unit
* Begin to register parameters of the kernel . Not for casual users .
@since Beryllium-20090601 - beta1
@since Beryllium-20090601-beta1 *)
(**/**)
(** Functors for registering a new plug-in. It provides access to several
services.
@plugin development guide *)
module Register
(P: sig
val name: string (** Name of the module. Arbitrary non-empty string. *)
val shortname: string (** Prefix for plugin options. No space allowed. *)
val help: string (** description of the module. Free-form text. *)
end) :
General_services
val is_share_visible: unit -> unit
(** Make visible to the end-user the -<plug-in>-share option.
To be called just before applying {!Register} to create plug-in services.
@since Oxygen-20120901 *)
val is_session_visible: unit -> unit
(** Make visible to the end-user the -<plug-in>-session option.
To be called just before applying {!Register} to create plug-in services.
@since Neon-20140301 *)
val is_config_visible: unit -> unit
(** Make visible to the end-user the -<plug-in>-config option.
To be called just before applying {!Register} to create plug-in services.
@since Neon-20140301 *)
val plugin_subpath: string -> unit
(** Use the given string as the sub-directory in which the plugin files will
be installed (ie. [share/tis-kernel/plugin_subpath]...). Relevant for
directories [Share], [Session] and [Config] above.
@since Neon-20140301 *)
(* ************************************************************************* *)
* { 2 Handling plugins }
(* ************************************************************************* *)
val get_from_shortname: string -> plugin
(** Get a plug-in from its shortname.
@since Oxygen-20120901 *)
val get_from_name: string -> plugin
(** Get a plug-in from its name.
@since Oxygen-20120901 *)
val is_present: string -> bool
(** Whether a plug-in already exists.
Plugins are identified by their short name.
@since Magnesium-20151001 *)
val get: string -> plugin
(** Get a plug-in from its name.
@deprecated since Oxygen-20120901 *)
val iter_on_plugins: (plugin -> unit) -> unit
(** Iterate on each registered plug-ins.
@since Beryllium-20090901 *)
(**/**)
(* ************************************************************************* *)
* { 2 Internal kernel stuff }
(* ************************************************************************* *)
val positive_debug_ref: int ref
(** @since Boron-20100401 *)
val session_is_set_ref: (unit -> bool) ref
val session_ref: (unit -> string) ref
val config_is_set_ref: (unit -> bool) ref
val config_ref: (unit -> string) ref
(**/**)
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_services/plugin_entry_points/plugin.mli | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
************************************************************************
* Provided plug-general services for plug-ins.
@since Beryllium-20090601-beta1
@plugin development guide
* Create a new group inside the plug-in.
The given string must be different of all the other group names of this
plug-in if [memo] is [false].
If [memo] is [true] the function will either create a fresh group or
return an existing group of the same name in the same plugin.
[memo] defaults to [false]
@since Beryllium-20090901
* @deprecated since Oxygen-20120901
* prints debug messages having the corresponding key.
@since Oxygen-20120901
@modify Fluorine-20130401 Set instead of list
* Handle the specific `share' directory of the plug-in.
@since Oxygen-20120901
* Handle the specific `session' directory of the plug-in.
@since Neon-20140301
* Handle the specific `config' directory of the plug-in.
@since Neon-20140301
* Only iterable parameters (see {!do_iterate} and {!do_not_iterate}) are
registered in the field [p_parameters].
@since Beryllium-20090901
*/*
*/*
* Functors for registering a new plug-in. It provides access to several
services.
@plugin development guide
* Name of the module. Arbitrary non-empty string.
* Prefix for plugin options. No space allowed.
* description of the module. Free-form text.
* Make visible to the end-user the -<plug-in>-share option.
To be called just before applying {!Register} to create plug-in services.
@since Oxygen-20120901
* Make visible to the end-user the -<plug-in>-session option.
To be called just before applying {!Register} to create plug-in services.
@since Neon-20140301
* Make visible to the end-user the -<plug-in>-config option.
To be called just before applying {!Register} to create plug-in services.
@since Neon-20140301
* Use the given string as the sub-directory in which the plugin files will
be installed (ie. [share/tis-kernel/plugin_subpath]...). Relevant for
directories [Share], [Session] and [Config] above.
@since Neon-20140301
*************************************************************************
*************************************************************************
* Get a plug-in from its shortname.
@since Oxygen-20120901
* Get a plug-in from its name.
@since Oxygen-20120901
* Whether a plug-in already exists.
Plugins are identified by their short name.
@since Magnesium-20151001
* Get a plug-in from its name.
@deprecated since Oxygen-20120901
* Iterate on each registered plug-ins.
@since Beryllium-20090901
*/*
*************************************************************************
*************************************************************************
* @since Boron-20100401
*/*
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
module type S = sig
include Log.Messages
val add_group: ?memo:bool -> string -> Cmdline.Group.t
module Help: Parameter_sig.Bool
module Verbose: Parameter_sig.Int
module Debug: Parameter_sig.Int
module Debug_category: Parameter_sig.String_set
module Share: Parameter_sig.Specific_dir
module Session: Parameter_sig.Specific_dir
module Config: Parameter_sig.Specific_dir
val help: Cmdline.Group.t
* The group containing option -*-help .
@since
@since Boron-20100401 *)
val messages: Cmdline.Group.t
* The group containing options -*-debug and -*-verbose .
@since
@since Boron-20100401 *)
end
type plugin = private
{ p_name: string;
p_shortname: string;
p_help: string;
p_parameters: (string, Typed_parameter.t list) Hashtbl.t }
module type General_services = sig
include S
include Parameter_sig.Builder
end
val register_kernel: unit -> unit
* Begin to register parameters of the kernel . Not for casual users .
@since Beryllium-20090601 - beta1
@since Beryllium-20090601-beta1 *)
module Register
(P: sig
end) :
General_services
val is_share_visible: unit -> unit
val is_session_visible: unit -> unit
val is_config_visible: unit -> unit
val plugin_subpath: string -> unit
* { 2 Handling plugins }
val get_from_shortname: string -> plugin
val get_from_name: string -> plugin
val is_present: string -> bool
val get: string -> plugin
val iter_on_plugins: (plugin -> unit) -> unit
* { 2 Internal kernel stuff }
val positive_debug_ref: int ref
val session_is_set_ref: (unit -> bool) ref
val session_ref: (unit -> string) ref
val config_is_set_ref: (unit -> bool) ref
val config_ref: (unit -> string) ref
|
9c0f08ea0506c4f96ac78d67eda0904a1e551f806b835f99af987b3abac905d4 | dktr0/estuary | Router.hs | # LANGUAGE RecursiveDo , ScopedTypeVariables , FlexibleContexts #
module Estuary.Widgets.Router(
router,
router',
getInitialState
) where
import Control.Monad.IO.Class
import Control.Monad.Fix (MonadFix)
import Data.Maybe
import GHCJS.DOM.EventM(on, event)
import GHCJS.DOM.Types(ToJSString(..), FromJSString(..))
import GHCJS.DOM(currentWindow,)
import GHCJS.DOM.History
import qualified GHCJS.DOM.PopStateEvent as PopStateEvent
import qualified GHCJS.DOM.Window as Window(getHistory)
import qualified GHCJS.DOM.WindowEventHandlers as Window (popState)
import GHCJS.Marshal
import GHCJS.Marshal.Pure
import GHCJS.Nullable
import Reflex
import Reflex.Dom
router ::
(Monad m, Functor m, TriggerEvent t m, MonadFix m, Reflex t, PerformEvent t m, MonadIO (Performable m), Adjustable t m, MonadIO m, MonadHold t m, FromJSVal state, ToJSVal state)
=> state -> Event t state -> (state -> m (Event t state, a)) -> m (Dynamic t (Event t state, a))
router def inStatChangeEv renderPage = mdo
let initialPage = renderPage def
-- Triggered ambiently (back button or otherwise). If the state is null or can't
-- be decoded, fall back into the initial state.
popStateEv :: Event t state <- fmap (fromMaybe def) <$> getPopStateEv
-- Triggered via a page widget (dynPage is the recursive value from further below).
-- When a change is explicitly triggered, we notify the history via pushPageState.
let dynStateChangeEv = fmap fst dynPage
let triggeredStateChangeEv = leftmost [
inStatChangeEv,
switchPromptlyDyn dynStateChangeEv
]
performEvent_ $ ffor triggeredStateChangeEv $ \state -> liftIO $ do
pushPageState state ""
-- The router state is changed when either the browser buttons are pressed or
-- a child page triggers a change.
let stateChangeEv = leftmost [popStateEv, triggeredStateChangeEv]
dynPage :: Dynamic t (Event t state, a) <- widgetHold initialPage (renderPage <$> stateChangeEv)
return dynPage
router' ::
(TriggerEvent t m, MonadFix m, MonadHold t m, PerformEvent t m, Reflex t, MonadIO m, Adjustable t m, MonadIO (Performable m), FromJSVal state, ToJSVal state)
=> state -> Event t state -> (state -> m (Event t state)) -> m (Dynamic t (Event t state))
router' def inStatChangeEv renderPage = mdo
let initialPage = renderPage def
popStateEv :: Event t state <- fmap (fromMaybe def) <$> getPopStateEv
let triggeredStateChangeEv = leftmost [
inStatChangeEv,
switchPromptlyDyn dynPage
]
performEvent_ $ ffor triggeredStateChangeEv $ \state -> liftIO $ do
pushPageState state ""
let stateChangeEv = leftmost [popStateEv, triggeredStateChangeEv]
dynPage :: Dynamic t (Event t state) <- widgetHold initialPage (renderPage <$> stateChangeEv)
return dynPage
getInitialState :: (FromJSVal state) => state -> IO (state)
getInitialState def =
maybeIO def currentWindow $ \window ->
maybeIO def (Just <$> Window.getHistory window) $ \history -> do
maybeIO def (pFromJSVal <$> pToJSVal <$> getState history) $ \state ->
maybeIO def (liftIO $ fromJSVal state) return
pushPageState :: (ToJSVal state, ToJSString url) => state -> url -> IO ()
pushPageState state url = do
maybeIO () currentWindow $ \window ->
maybeIO () (Just <$> Window.getHistory window) $ \history -> do
jsState <- liftIO $ toJSVal state
Mozilla reccomends to pass " " as title to keep things future proof
pushState history jsState "" (Just url)
getPopStateEv ::
(Monad m, MonadIO m, Reflex t, TriggerEvent t m, FromJSVal state)
=> m (Event t (Maybe state))
getPopStateEv = do
mWindow <- liftIO $ currentWindow
case mWindow of
Nothing -> return never
Just window ->
wrapDomEvent window (\e -> on e Window.popState) $ do
in ( EventM t PopState ) which is ( ReaderT PopState IO )
eventData <- event -- ask
nullableJsState <- liftIO $ pFromJSVal <$> pToJSVal <$> PopStateEvent.getState eventData
case nullableJsState of
Nothing -> return Nothing
Just jsState -> liftIO $ fromJSVal jsState
maybeIO :: b -> IO (Maybe a) -> (a -> IO b) -> IO b
maybeIO def computeA computeBFromA = do
val <- computeA
case val of
Nothing -> return def
Just a -> computeBFromA a
| null | https://raw.githubusercontent.com/dktr0/estuary/c08a4790533c983ba236468e0ae197df50f2109f/client/src/Estuary/Widgets/Router.hs | haskell | Triggered ambiently (back button or otherwise). If the state is null or can't
be decoded, fall back into the initial state.
Triggered via a page widget (dynPage is the recursive value from further below).
When a change is explicitly triggered, we notify the history via pushPageState.
The router state is changed when either the browser buttons are pressed or
a child page triggers a change.
ask | # LANGUAGE RecursiveDo , ScopedTypeVariables , FlexibleContexts #
module Estuary.Widgets.Router(
router,
router',
getInitialState
) where
import Control.Monad.IO.Class
import Control.Monad.Fix (MonadFix)
import Data.Maybe
import GHCJS.DOM.EventM(on, event)
import GHCJS.DOM.Types(ToJSString(..), FromJSString(..))
import GHCJS.DOM(currentWindow,)
import GHCJS.DOM.History
import qualified GHCJS.DOM.PopStateEvent as PopStateEvent
import qualified GHCJS.DOM.Window as Window(getHistory)
import qualified GHCJS.DOM.WindowEventHandlers as Window (popState)
import GHCJS.Marshal
import GHCJS.Marshal.Pure
import GHCJS.Nullable
import Reflex
import Reflex.Dom
router ::
(Monad m, Functor m, TriggerEvent t m, MonadFix m, Reflex t, PerformEvent t m, MonadIO (Performable m), Adjustable t m, MonadIO m, MonadHold t m, FromJSVal state, ToJSVal state)
=> state -> Event t state -> (state -> m (Event t state, a)) -> m (Dynamic t (Event t state, a))
router def inStatChangeEv renderPage = mdo
let initialPage = renderPage def
popStateEv :: Event t state <- fmap (fromMaybe def) <$> getPopStateEv
let dynStateChangeEv = fmap fst dynPage
let triggeredStateChangeEv = leftmost [
inStatChangeEv,
switchPromptlyDyn dynStateChangeEv
]
performEvent_ $ ffor triggeredStateChangeEv $ \state -> liftIO $ do
pushPageState state ""
let stateChangeEv = leftmost [popStateEv, triggeredStateChangeEv]
dynPage :: Dynamic t (Event t state, a) <- widgetHold initialPage (renderPage <$> stateChangeEv)
return dynPage
router' ::
(TriggerEvent t m, MonadFix m, MonadHold t m, PerformEvent t m, Reflex t, MonadIO m, Adjustable t m, MonadIO (Performable m), FromJSVal state, ToJSVal state)
=> state -> Event t state -> (state -> m (Event t state)) -> m (Dynamic t (Event t state))
router' def inStatChangeEv renderPage = mdo
let initialPage = renderPage def
popStateEv :: Event t state <- fmap (fromMaybe def) <$> getPopStateEv
let triggeredStateChangeEv = leftmost [
inStatChangeEv,
switchPromptlyDyn dynPage
]
performEvent_ $ ffor triggeredStateChangeEv $ \state -> liftIO $ do
pushPageState state ""
let stateChangeEv = leftmost [popStateEv, triggeredStateChangeEv]
dynPage :: Dynamic t (Event t state) <- widgetHold initialPage (renderPage <$> stateChangeEv)
return dynPage
getInitialState :: (FromJSVal state) => state -> IO (state)
getInitialState def =
maybeIO def currentWindow $ \window ->
maybeIO def (Just <$> Window.getHistory window) $ \history -> do
maybeIO def (pFromJSVal <$> pToJSVal <$> getState history) $ \state ->
maybeIO def (liftIO $ fromJSVal state) return
pushPageState :: (ToJSVal state, ToJSString url) => state -> url -> IO ()
pushPageState state url = do
maybeIO () currentWindow $ \window ->
maybeIO () (Just <$> Window.getHistory window) $ \history -> do
jsState <- liftIO $ toJSVal state
Mozilla reccomends to pass " " as title to keep things future proof
pushState history jsState "" (Just url)
getPopStateEv ::
(Monad m, MonadIO m, Reflex t, TriggerEvent t m, FromJSVal state)
=> m (Event t (Maybe state))
getPopStateEv = do
mWindow <- liftIO $ currentWindow
case mWindow of
Nothing -> return never
Just window ->
wrapDomEvent window (\e -> on e Window.popState) $ do
in ( EventM t PopState ) which is ( ReaderT PopState IO )
nullableJsState <- liftIO $ pFromJSVal <$> pToJSVal <$> PopStateEvent.getState eventData
case nullableJsState of
Nothing -> return Nothing
Just jsState -> liftIO $ fromJSVal jsState
maybeIO :: b -> IO (Maybe a) -> (a -> IO b) -> IO b
maybeIO def computeA computeBFromA = do
val <- computeA
case val of
Nothing -> return def
Just a -> computeBFromA a
|
067df133a4b7967dd81743a981c27d049bc3794b650a533230cf8c21f4ec7c10 | tfausak/strive | Enums.hs | {-# LANGUAGE OverloadedStrings #-}
-- | Types for choosing an option from a limited set.
module Strive.Enums
( ActivityType (..),
ActivityZoneType (..),
AgeGroup (..),
ClubType (..),
FrameType (..),
Gender (..),
MeasurementPreference (..),
PhotoType (..),
Resolution (..),
ResourceState (..),
SegmentActivityType (..),
SeriesType (..),
SportType (..),
StreamType (..),
WeightClass (..),
)
where
import Control.Applicative (empty)
import Data.Aeson (FromJSON, Value (Number, String), parseJSON)
-- | An activity's type.
data ActivityType
= AlpineSki
| BackcountrySki
| Canoeing
| CrossCountrySkiing
| Crossfit
| Elliptical
| Hike
| IceSkate
| InlineSkate
| Kayaking
| KiteSurf
| NordicSki
| Ride
| RockClimbing
| RollerSki
| Rowing
| Run
| Snowboard
| Snowshoe
| StairStepper
| StandUpPaddling
| Surfing
| Swim
| VirtualRide
| Walk
| WeightTraining
| Windsurf
| Workout
| Yoga
deriving (Eq, Show)
instance FromJSON ActivityType where
parseJSON (String "AlpineSki") = pure AlpineSki
parseJSON (String "BackcountrySki") = pure BackcountrySki
parseJSON (String "Canoeing") = pure Canoeing
parseJSON (String "CrossCountrySkiing") = pure CrossCountrySkiing
parseJSON (String "Crossfit") = pure Crossfit
parseJSON (String "Elliptical") = pure Elliptical
parseJSON (String "Hike") = pure Hike
parseJSON (String "IceSkate") = pure IceSkate
parseJSON (String "InlineSkate") = pure InlineSkate
parseJSON (String "Kayaking") = pure Kayaking
parseJSON (String "KiteSurf") = pure KiteSurf
parseJSON (String "NordicSki") = pure NordicSki
parseJSON (String "Ride") = pure Ride
parseJSON (String "RockClimbing") = pure RockClimbing
parseJSON (String "RollerSki") = pure RollerSki
parseJSON (String "Rowing") = pure Rowing
parseJSON (String "Run") = pure Run
parseJSON (String "Snowboard") = pure Snowboard
parseJSON (String "Snowshoe") = pure Snowshoe
parseJSON (String "StairStepper") = pure StairStepper
parseJSON (String "StandUpPaddling") = pure StandUpPaddling
parseJSON (String "Surfing") = pure Surfing
parseJSON (String "Swim") = pure Swim
parseJSON (String "VirtualRide") = pure VirtualRide
parseJSON (String "Walk") = pure Walk
parseJSON (String "WeightTraining") = pure WeightTraining
parseJSON (String "Windsurf") = pure Windsurf
parseJSON (String "Workout") = pure Workout
parseJSON (String "Yoga") = pure Yoga
parseJSON _ = empty
-- | An activity zone's type.
data ActivityZoneType
= HeartrateZone
| PowerZone
deriving (Eq, Show)
instance FromJSON ActivityZoneType where
parseJSON (String "heartrate") = pure HeartrateZone
parseJSON (String "power") = pure PowerZone
parseJSON _ = empty
-- | An athlete's age group.
data AgeGroup
= Ages0To24
| Ages25To34
| Ages35To44
| Ages45To54
| Ages55To64
| Ages65Plus
deriving (Eq)
instance Show AgeGroup where
show Ages0To24 = "0_24"
show Ages25To34 = "25_34"
show Ages35To44 = "35_44"
show Ages45To54 = "45_54"
show Ages55To64 = "55_64"
show Ages65Plus = "65_plus"
-- | A club's type.
data ClubType
= CasualClub
| Company
| Other
| RacingTeam
| Shop
deriving (Eq, Show)
instance FromJSON ClubType where
parseJSON (String "casual_club") = pure CasualClub
parseJSON (String "company") = pure Company
parseJSON (String "other") = pure Other
parseJSON (String "racing_team") = pure RacingTeam
parseJSON (String "shop") = pure Shop
parseJSON _ = empty
-- | A bike's frame type.
data FrameType
= CrossFrame
| MountainFrame
| RoadFrame
| TimeTrialFrame
deriving (Eq, Show)
instance FromJSON FrameType where
parseJSON (Number 2) = pure CrossFrame
parseJSON (Number 1) = pure MountainFrame
parseJSON (Number 3) = pure RoadFrame
parseJSON (Number 4) = pure TimeTrialFrame
parseJSON _ = empty
-- | An athlete's gender.
data Gender
= Female
| Male
deriving (Eq)
instance Show Gender where
show Female = "F"
show Male = "M"
instance FromJSON Gender where
parseJSON (String "F") = pure Female
parseJSON (String "M") = pure Male
parseJSON _ = empty
-- | An athlete's measurement preference.
data MeasurementPreference
= Feet
| Meters
deriving (Eq, Show)
instance FromJSON MeasurementPreference where
parseJSON (String "feet") = pure Feet
parseJSON (String "meters") = pure Meters
parseJSON _ = empty
-- | A photo's type.
data PhotoType = InstagramPhoto
deriving (Eq, Show)
instance FromJSON PhotoType where
parseJSON (String "InstagramPhoto") = pure InstagramPhoto
parseJSON _ = empty
-- | A stream's resolution.
data Resolution
= Low
| Medium
| High
deriving (Eq)
instance Show Resolution where
show Low = "low"
show Medium = "medium"
show High = "high"
instance FromJSON Resolution where
parseJSON (String "low") = pure Low
parseJSON (String "medium") = pure Medium
parseJSON (String "high") = pure High
parseJSON _ = empty
-- | A resource's state.
data ResourceState
= Meta
| Summary
| Detailed
deriving (Eq, Show)
instance FromJSON ResourceState where
parseJSON (Number 1) = pure Meta
parseJSON (Number 2) = pure Summary
parseJSON (Number 3) = pure Detailed
parseJSON _ = empty
-- | A segment's activity type.
data SegmentActivityType
= Riding
| Running
deriving (Eq)
instance Show SegmentActivityType where
show Riding = "riding"
show Running = "running"
-- | A series' type in a stream.
data SeriesType
= Distance
| Time
deriving (Eq)
instance Show SeriesType where
show Distance = "distance"
show Time = "time"
instance FromJSON SeriesType where
parseJSON (String "distance") = pure Distance
parseJSON (String "time") = pure Time
parseJSON _ = empty
-- | A club's sport type.
data SportType
= SportCycling
| SportOther
| SportRunning
| SportTriathalon
deriving (Eq, Show)
instance FromJSON SportType where
parseJSON (String "cycling") = pure SportCycling
parseJSON (String "other") = pure SportOther
parseJSON (String "running") = pure SportRunning
parseJSON (String "triathalon") = pure SportTriathalon
parseJSON _ = empty
-- | A stream's type.
data StreamType
= AltitudeStream
| CadenceStream
| DistanceStream
| GradeSmoothStream
| HeartrateStream
| LatlngStream
| MovingStream
| TempStream
| TimeStream
| VelocitySmoothStream
| WattsStream
deriving (Eq)
instance Show StreamType where
show AltitudeStream = "altitude"
show CadenceStream = "cadence"
show DistanceStream = "distance"
show GradeSmoothStream = "grade_smooth"
show HeartrateStream = "heartrate"
show LatlngStream = "latlng"
show MovingStream = "moving"
show TempStream = "temp"
show TimeStream = "time"
show VelocitySmoothStream = "velocity_smooth"
show WattsStream = "watts"
-- | An athlete's weight class.
data WeightClass
= Kilograms0To54
| Kilograms55To64
| Kilograms65To74
| Kilograms75To84
| Kilograms85To94
| Kilograms95Plus
| Pounds0To124
| Pounds125To149
| Pounds150To164
| Pounds165To179
| Pounds180To199
| Pounds200Plus
deriving (Eq)
instance Show WeightClass where
show Kilograms0To54 = "0_54"
show Kilograms55To64 = "55_64"
show Kilograms65To74 = "65_74"
show Kilograms75To84 = "75_84"
show Kilograms85To94 = "85_94"
show Kilograms95Plus = "95_plus"
show Pounds0To124 = "0_124"
show Pounds125To149 = "125_149"
show Pounds150To164 = "150_164"
show Pounds165To179 = "165_179"
show Pounds180To199 = "180_199"
show Pounds200Plus = "200_plus"
| null | https://raw.githubusercontent.com/tfausak/strive/82294daca85ca624ca1e746d7aa4c01d57233356/source/library/Strive/Enums.hs | haskell | # LANGUAGE OverloadedStrings #
| Types for choosing an option from a limited set.
| An activity's type.
| An activity zone's type.
| An athlete's age group.
| A club's type.
| A bike's frame type.
| An athlete's gender.
| An athlete's measurement preference.
| A photo's type.
| A stream's resolution.
| A resource's state.
| A segment's activity type.
| A series' type in a stream.
| A club's sport type.
| A stream's type.
| An athlete's weight class. |
module Strive.Enums
( ActivityType (..),
ActivityZoneType (..),
AgeGroup (..),
ClubType (..),
FrameType (..),
Gender (..),
MeasurementPreference (..),
PhotoType (..),
Resolution (..),
ResourceState (..),
SegmentActivityType (..),
SeriesType (..),
SportType (..),
StreamType (..),
WeightClass (..),
)
where
import Control.Applicative (empty)
import Data.Aeson (FromJSON, Value (Number, String), parseJSON)
data ActivityType
= AlpineSki
| BackcountrySki
| Canoeing
| CrossCountrySkiing
| Crossfit
| Elliptical
| Hike
| IceSkate
| InlineSkate
| Kayaking
| KiteSurf
| NordicSki
| Ride
| RockClimbing
| RollerSki
| Rowing
| Run
| Snowboard
| Snowshoe
| StairStepper
| StandUpPaddling
| Surfing
| Swim
| VirtualRide
| Walk
| WeightTraining
| Windsurf
| Workout
| Yoga
deriving (Eq, Show)
instance FromJSON ActivityType where
parseJSON (String "AlpineSki") = pure AlpineSki
parseJSON (String "BackcountrySki") = pure BackcountrySki
parseJSON (String "Canoeing") = pure Canoeing
parseJSON (String "CrossCountrySkiing") = pure CrossCountrySkiing
parseJSON (String "Crossfit") = pure Crossfit
parseJSON (String "Elliptical") = pure Elliptical
parseJSON (String "Hike") = pure Hike
parseJSON (String "IceSkate") = pure IceSkate
parseJSON (String "InlineSkate") = pure InlineSkate
parseJSON (String "Kayaking") = pure Kayaking
parseJSON (String "KiteSurf") = pure KiteSurf
parseJSON (String "NordicSki") = pure NordicSki
parseJSON (String "Ride") = pure Ride
parseJSON (String "RockClimbing") = pure RockClimbing
parseJSON (String "RollerSki") = pure RollerSki
parseJSON (String "Rowing") = pure Rowing
parseJSON (String "Run") = pure Run
parseJSON (String "Snowboard") = pure Snowboard
parseJSON (String "Snowshoe") = pure Snowshoe
parseJSON (String "StairStepper") = pure StairStepper
parseJSON (String "StandUpPaddling") = pure StandUpPaddling
parseJSON (String "Surfing") = pure Surfing
parseJSON (String "Swim") = pure Swim
parseJSON (String "VirtualRide") = pure VirtualRide
parseJSON (String "Walk") = pure Walk
parseJSON (String "WeightTraining") = pure WeightTraining
parseJSON (String "Windsurf") = pure Windsurf
parseJSON (String "Workout") = pure Workout
parseJSON (String "Yoga") = pure Yoga
parseJSON _ = empty
data ActivityZoneType
= HeartrateZone
| PowerZone
deriving (Eq, Show)
instance FromJSON ActivityZoneType where
parseJSON (String "heartrate") = pure HeartrateZone
parseJSON (String "power") = pure PowerZone
parseJSON _ = empty
data AgeGroup
= Ages0To24
| Ages25To34
| Ages35To44
| Ages45To54
| Ages55To64
| Ages65Plus
deriving (Eq)
instance Show AgeGroup where
show Ages0To24 = "0_24"
show Ages25To34 = "25_34"
show Ages35To44 = "35_44"
show Ages45To54 = "45_54"
show Ages55To64 = "55_64"
show Ages65Plus = "65_plus"
data ClubType
= CasualClub
| Company
| Other
| RacingTeam
| Shop
deriving (Eq, Show)
instance FromJSON ClubType where
parseJSON (String "casual_club") = pure CasualClub
parseJSON (String "company") = pure Company
parseJSON (String "other") = pure Other
parseJSON (String "racing_team") = pure RacingTeam
parseJSON (String "shop") = pure Shop
parseJSON _ = empty
data FrameType
= CrossFrame
| MountainFrame
| RoadFrame
| TimeTrialFrame
deriving (Eq, Show)
instance FromJSON FrameType where
parseJSON (Number 2) = pure CrossFrame
parseJSON (Number 1) = pure MountainFrame
parseJSON (Number 3) = pure RoadFrame
parseJSON (Number 4) = pure TimeTrialFrame
parseJSON _ = empty
data Gender
= Female
| Male
deriving (Eq)
instance Show Gender where
show Female = "F"
show Male = "M"
instance FromJSON Gender where
parseJSON (String "F") = pure Female
parseJSON (String "M") = pure Male
parseJSON _ = empty
data MeasurementPreference
= Feet
| Meters
deriving (Eq, Show)
instance FromJSON MeasurementPreference where
parseJSON (String "feet") = pure Feet
parseJSON (String "meters") = pure Meters
parseJSON _ = empty
data PhotoType = InstagramPhoto
deriving (Eq, Show)
instance FromJSON PhotoType where
parseJSON (String "InstagramPhoto") = pure InstagramPhoto
parseJSON _ = empty
data Resolution
= Low
| Medium
| High
deriving (Eq)
instance Show Resolution where
show Low = "low"
show Medium = "medium"
show High = "high"
instance FromJSON Resolution where
parseJSON (String "low") = pure Low
parseJSON (String "medium") = pure Medium
parseJSON (String "high") = pure High
parseJSON _ = empty
data ResourceState
= Meta
| Summary
| Detailed
deriving (Eq, Show)
instance FromJSON ResourceState where
parseJSON (Number 1) = pure Meta
parseJSON (Number 2) = pure Summary
parseJSON (Number 3) = pure Detailed
parseJSON _ = empty
data SegmentActivityType
= Riding
| Running
deriving (Eq)
instance Show SegmentActivityType where
show Riding = "riding"
show Running = "running"
data SeriesType
= Distance
| Time
deriving (Eq)
instance Show SeriesType where
show Distance = "distance"
show Time = "time"
instance FromJSON SeriesType where
parseJSON (String "distance") = pure Distance
parseJSON (String "time") = pure Time
parseJSON _ = empty
data SportType
= SportCycling
| SportOther
| SportRunning
| SportTriathalon
deriving (Eq, Show)
instance FromJSON SportType where
parseJSON (String "cycling") = pure SportCycling
parseJSON (String "other") = pure SportOther
parseJSON (String "running") = pure SportRunning
parseJSON (String "triathalon") = pure SportTriathalon
parseJSON _ = empty
data StreamType
= AltitudeStream
| CadenceStream
| DistanceStream
| GradeSmoothStream
| HeartrateStream
| LatlngStream
| MovingStream
| TempStream
| TimeStream
| VelocitySmoothStream
| WattsStream
deriving (Eq)
instance Show StreamType where
show AltitudeStream = "altitude"
show CadenceStream = "cadence"
show DistanceStream = "distance"
show GradeSmoothStream = "grade_smooth"
show HeartrateStream = "heartrate"
show LatlngStream = "latlng"
show MovingStream = "moving"
show TempStream = "temp"
show TimeStream = "time"
show VelocitySmoothStream = "velocity_smooth"
show WattsStream = "watts"
data WeightClass
= Kilograms0To54
| Kilograms55To64
| Kilograms65To74
| Kilograms75To84
| Kilograms85To94
| Kilograms95Plus
| Pounds0To124
| Pounds125To149
| Pounds150To164
| Pounds165To179
| Pounds180To199
| Pounds200Plus
deriving (Eq)
instance Show WeightClass where
show Kilograms0To54 = "0_54"
show Kilograms55To64 = "55_64"
show Kilograms65To74 = "65_74"
show Kilograms75To84 = "75_84"
show Kilograms85To94 = "85_94"
show Kilograms95Plus = "95_plus"
show Pounds0To124 = "0_124"
show Pounds125To149 = "125_149"
show Pounds150To164 = "150_164"
show Pounds165To179 = "165_179"
show Pounds180To199 = "180_199"
show Pounds200Plus = "200_plus"
|
4f5f80ee320140b678f7e780e638428612bc107b74e893b432fdd478fc88ad7e | ghc/testsuite | SafeLang09_A.hs | # LANGUAGE FlexibleInstances #
-- | Trusted library that unsafe plugins can use
module SafeLang09_A where
class Pos a where
res :: a -> Bool
-- Any call to res with a list in out TCB
-- should use this method and never a more
-- specific one provided by an untrusted module
instance Pos [a] where
res _ = True
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/safeHaskell/safeLanguage/SafeLang09_A.hs | haskell | | Trusted library that unsafe plugins can use
Any call to res with a list in out TCB
should use this method and never a more
specific one provided by an untrusted module | # LANGUAGE FlexibleInstances #
module SafeLang09_A where
class Pos a where
res :: a -> Bool
instance Pos [a] where
res _ = True
|
db67f56958019f20818d7fbc93095ce1fa0501752fe42f8f79a0a2c2bf6372a5 | tsloughter/kuberl | kuberl_v1_cluster_role_binding_list.erl | -module(kuberl_v1_cluster_role_binding_list).
-export([encode/1]).
-export_type([kuberl_v1_cluster_role_binding_list/0]).
-type kuberl_v1_cluster_role_binding_list() ::
#{ 'apiVersion' => binary(),
'items' := list(),
'kind' => binary(),
'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta()
}.
encode(#{ 'apiVersion' := ApiVersion,
'items' := Items,
'kind' := Kind,
'metadata' := Metadata
}) ->
#{ 'apiVersion' => ApiVersion,
'items' => Items,
'kind' => Kind,
'metadata' => Metadata
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_cluster_role_binding_list.erl | erlang | -module(kuberl_v1_cluster_role_binding_list).
-export([encode/1]).
-export_type([kuberl_v1_cluster_role_binding_list/0]).
-type kuberl_v1_cluster_role_binding_list() ::
#{ 'apiVersion' => binary(),
'items' := list(),
'kind' => binary(),
'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta()
}.
encode(#{ 'apiVersion' := ApiVersion,
'items' := Items,
'kind' := Kind,
'metadata' := Metadata
}) ->
#{ 'apiVersion' => ApiVersion,
'items' => Items,
'kind' => Kind,
'metadata' => Metadata
}.
| |
649b6d87941a0619c2967ead18d710838c30a669e799f6bbcb5cb5d6f9f43990 | Twinside/Rasterific | QuadraticFormula.hs | module Graphics.Rasterific.QuadraticFormula( QuadraticFormula( .. )
, discriminant
, formulaRoots
) where
-- | Represent an equation `a * x^2 + b * x + c = 0`
data QuadraticFormula a = QuadraticFormula
{ _coeffA :: !a -- ^ Coefficient for the square part (x^2)
, _coeffB :: !a -- ^ Coefficient the linear part (x)
, _coeffC :: !a -- ^ Constant
}
instance Functor QuadraticFormula where
# INLINE fmap #
fmap f (QuadraticFormula a b c) =
QuadraticFormula (f a) (f b) (f c)
instance Applicative QuadraticFormula where
pure a = QuadraticFormula a a a
# INLINE pure #
QuadraticFormula a b c <*> QuadraticFormula d e f =
QuadraticFormula (a d) (b e) (c f)
{-# INLINE (<*>) #-}
-- | Discriminant equation, if the result is:
--
-- * Below 0, then the formula doesn't have any solution
--
-- * Equal to 0, then the formula has an unique root.
--
* Above 0 , the formula has two solutions
--
discriminant :: Num a => QuadraticFormula a -> a
discriminant (QuadraticFormula a b c) = b * b - 4 * a *c
-- | Extract all the roots of the formula ie. where the
unknown gives a result of 0
formulaRoots :: (Ord a, Floating a) => QuadraticFormula a -> [a]
formulaRoots formula@(QuadraticFormula a b _)
| disc < 0 = []
| disc == 0 = [positiveResult]
| otherwise = [positiveResult, negativeResult]
where
disc = discriminant formula
squarePart = sqrt disc
positiveResult = (negate b + squarePart) / (2 * a)
negativeResult = (negate b - squarePart) / (2 * a)
| null | https://raw.githubusercontent.com/Twinside/Rasterific/709e2828d6378aa82f133a881665f2fa951e0204/src/Graphics/Rasterific/QuadraticFormula.hs | haskell | | Represent an equation `a * x^2 + b * x + c = 0`
^ Coefficient for the square part (x^2)
^ Coefficient the linear part (x)
^ Constant
# INLINE (<*>) #
| Discriminant equation, if the result is:
* Below 0, then the formula doesn't have any solution
* Equal to 0, then the formula has an unique root.
| Extract all the roots of the formula ie. where the | module Graphics.Rasterific.QuadraticFormula( QuadraticFormula( .. )
, discriminant
, formulaRoots
) where
data QuadraticFormula a = QuadraticFormula
}
instance Functor QuadraticFormula where
# INLINE fmap #
fmap f (QuadraticFormula a b c) =
QuadraticFormula (f a) (f b) (f c)
instance Applicative QuadraticFormula where
pure a = QuadraticFormula a a a
# INLINE pure #
QuadraticFormula a b c <*> QuadraticFormula d e f =
QuadraticFormula (a d) (b e) (c f)
* Above 0 , the formula has two solutions
discriminant :: Num a => QuadraticFormula a -> a
discriminant (QuadraticFormula a b c) = b * b - 4 * a *c
unknown gives a result of 0
formulaRoots :: (Ord a, Floating a) => QuadraticFormula a -> [a]
formulaRoots formula@(QuadraticFormula a b _)
| disc < 0 = []
| disc == 0 = [positiveResult]
| otherwise = [positiveResult, negativeResult]
where
disc = discriminant formula
squarePart = sqrt disc
positiveResult = (negate b + squarePart) / (2 * a)
negativeResult = (negate b - squarePart) / (2 * a)
|
d8996ec7fdf91c1e99278ff82e4f0120a3eab739e241b988ec56edd608fddf99 | Enecuum/Node | Model.hs | module Enecuum.Samples.Blockchain.DB.Model where
import qualified Enecuum.Core.Types as D
data KBlocksDB
instance D.DB KBlocksDB where
getDbName = "kblocks"
data KBlocksMetaDB
instance D.DB KBlocksMetaDB where
getDbName = "kblocks_meta"
data MBlocksDB
instance D.DB MBlocksDB where
getDbName = "mblocks"
data MBlocksMetaDB
instance D.DB MBlocksMetaDB where
getDbName = "mblocks_meta"
data TransactionsDB
instance D.DB TransactionsDB where
getDbName = "txs"
data TransactionsMetaDB
instance D.DB TransactionsMetaDB where
getDbName = "txs_meta"
data DBModel = DBModel
{ _kBlocksDB :: D.Storage KBlocksDB
, _kBlocksMetaDB :: D.Storage KBlocksMetaDB
, _mBlocksDB :: D.Storage MBlocksDB
, _mBlocksMetaDB :: D.Storage MBlocksMetaDB
, _transactionsDB :: D.Storage TransactionsDB
, _transactionsMetaDB :: D.Storage TransactionsMetaDB
}
| null | https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/src/Enecuum/Samples/Blockchain/DB/Model.hs | haskell | module Enecuum.Samples.Blockchain.DB.Model where
import qualified Enecuum.Core.Types as D
data KBlocksDB
instance D.DB KBlocksDB where
getDbName = "kblocks"
data KBlocksMetaDB
instance D.DB KBlocksMetaDB where
getDbName = "kblocks_meta"
data MBlocksDB
instance D.DB MBlocksDB where
getDbName = "mblocks"
data MBlocksMetaDB
instance D.DB MBlocksMetaDB where
getDbName = "mblocks_meta"
data TransactionsDB
instance D.DB TransactionsDB where
getDbName = "txs"
data TransactionsMetaDB
instance D.DB TransactionsMetaDB where
getDbName = "txs_meta"
data DBModel = DBModel
{ _kBlocksDB :: D.Storage KBlocksDB
, _kBlocksMetaDB :: D.Storage KBlocksMetaDB
, _mBlocksDB :: D.Storage MBlocksDB
, _mBlocksMetaDB :: D.Storage MBlocksMetaDB
, _transactionsDB :: D.Storage TransactionsDB
, _transactionsMetaDB :: D.Storage TransactionsMetaDB
}
| |
3504ac73d7ca92e34b708eefc8a45aade35207404f59fd7bf1e79b71a1f5fd3a | melange-re/melange | pq_test.ml | module PrioQueue =
struct
type priority = int
type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue
let empty = Empty
let rec insert queue prio elt =
match queue with
Empty -> Node(prio, elt, Empty, Empty)
| Node(p, e, left, right) ->
if prio <= p
then Node(prio, elt, insert right p e, left)
else Node(p, e, insert right prio elt, left)
exception Queue_is_empty
let rec remove_top = function
Empty -> raise Queue_is_empty
| Node(prio, elt, left, Empty) -> left
| Node(prio, elt, Empty, right) -> right
| Node(prio, elt, (Node(lprio, lelt, _, _) as left),
(Node(rprio, relt, _, _) as right)) ->
if lprio <= rprio
then Node(lprio, lelt, remove_top left, right)
else Node(rprio, relt, left, remove_top right)
let extract = function
Empty -> raise Queue_is_empty
| Node(prio, elt, _, _) as queue -> (prio, elt, remove_top queue)
end;;
| null | https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/test/pq_test.ml | ocaml | module PrioQueue =
struct
type priority = int
type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue
let empty = Empty
let rec insert queue prio elt =
match queue with
Empty -> Node(prio, elt, Empty, Empty)
| Node(p, e, left, right) ->
if prio <= p
then Node(prio, elt, insert right p e, left)
else Node(p, e, insert right prio elt, left)
exception Queue_is_empty
let rec remove_top = function
Empty -> raise Queue_is_empty
| Node(prio, elt, left, Empty) -> left
| Node(prio, elt, Empty, right) -> right
| Node(prio, elt, (Node(lprio, lelt, _, _) as left),
(Node(rprio, relt, _, _) as right)) ->
if lprio <= rprio
then Node(lprio, lelt, remove_top left, right)
else Node(rprio, relt, left, remove_top right)
let extract = function
Empty -> raise Queue_is_empty
| Node(prio, elt, _, _) as queue -> (prio, elt, remove_top queue)
end;;
| |
c1baf6a9afa8cf92c143bcb0d7311d44eec85b918f4705fce3edac54a11e765b | jebberjeb/clojure-socketrepl.nvim | parser.clj | (ns socket-repl.parser
(:require
[clojure.string :as string]
[clojure.tools.reader.reader-types :as reader-types]
[clojure.tools.reader :as reader]))
(defn position
"Returns the zero-indexed position in a code string given line and column."
[code-str row col]
(->> code-str
string/split-lines
(take (dec row))
(string/join)
count
` ( dec row ) ` to include for newlines
dec
(max 0)))
(defn search-start
"Find the place to start reading from. Search backwards from the starting
point, looking for a '[', '{', or '('. If none can be found, search from
the beginning of `code-str`."
[code-str start-row start-col]
(let [openers #{\[ \( \{}
start-position (position code-str start-row start-col)]
(if (contains? openers (nth code-str start-position))
start-position
(let [code-str-prefix (subs code-str 0 start-position)]
(->> openers
(map #(string/last-index-of code-str-prefix %))
(remove nil?)
(apply max 0))))))
(defn read-next
"Reads the next expression from some code. Uses an `indexing-pushback-reader`
to determine how much was read, and return that substring of the original
`code-str`, rather than what was actually read by the reader."
[code-str start-row start-col]
(let [code-str (subs code-str (search-start code-str start-row start-col))
rdr (reader-types/indexing-push-back-reader code-str)]
;; Read a form, but discard it, as we want the original string.
(reader/read rdr)
(subs code-str
0
;; Even though this returns the position *after* the read, this works
;; because subs is end point exclusive.
(position code-str
(reader-types/get-line-number rdr)
(reader-types/get-column-number rdr)))))
| null | https://raw.githubusercontent.com/jebberjeb/clojure-socketrepl.nvim/4161837da0578114438a99bbd317a1e77a108b0f/src/socket_repl/parser.clj | clojure | Read a form, but discard it, as we want the original string.
Even though this returns the position *after* the read, this works
because subs is end point exclusive. | (ns socket-repl.parser
(:require
[clojure.string :as string]
[clojure.tools.reader.reader-types :as reader-types]
[clojure.tools.reader :as reader]))
(defn position
"Returns the zero-indexed position in a code string given line and column."
[code-str row col]
(->> code-str
string/split-lines
(take (dec row))
(string/join)
count
` ( dec row ) ` to include for newlines
dec
(max 0)))
(defn search-start
"Find the place to start reading from. Search backwards from the starting
point, looking for a '[', '{', or '('. If none can be found, search from
the beginning of `code-str`."
[code-str start-row start-col]
(let [openers #{\[ \( \{}
start-position (position code-str start-row start-col)]
(if (contains? openers (nth code-str start-position))
start-position
(let [code-str-prefix (subs code-str 0 start-position)]
(->> openers
(map #(string/last-index-of code-str-prefix %))
(remove nil?)
(apply max 0))))))
(defn read-next
"Reads the next expression from some code. Uses an `indexing-pushback-reader`
to determine how much was read, and return that substring of the original
`code-str`, rather than what was actually read by the reader."
[code-str start-row start-col]
(let [code-str (subs code-str (search-start code-str start-row start-col))
rdr (reader-types/indexing-push-back-reader code-str)]
(reader/read rdr)
(subs code-str
0
(position code-str
(reader-types/get-line-number rdr)
(reader-types/get-column-number rdr)))))
|
7f4f02dc9e72a343eadf18b064a4483f3a37109f1357689a74a85b7f45b52ddd | xclerc/ocamljava | bytecodegen_prim.mli |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
(** Compilation of OCaml primitives. *)
val compile_primitive : int -> Lambda.primitive -> Macroinstr.expression list ->
(int -> Macroinstr.expression list -> Instrtree.t) ->
(bool -> int -> Macroinstr.expression -> Instrtree.t) ->
Instrtree.t
* [ compile_primitive ofs prim args cl ce ] compiles the primitive [ prim ]
at offset [ ofs ] with arguments [ args ] ; the functions [ cl ] and [ ce ]
are used to compile respectively expression lists and simple
expressions . The first function takes the following parameters :
- offset ;
- expression list to compile .
The second function takes the following parameters :
- whether the expression is in a tail position ;
- offest ;
- expression to compile .
at offset [ofs] with arguments [args]; the functions [cl] and [ce]
are used to compile respectively expression lists and simple
expressions. The first function takes the following parameters:
- offset;
- expression list to compile.
The second function takes the following parameters:
- whether the expression is in a tail position;
- offest;
- expression to compile. *)
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/compiler/javacomp/bytecodegen_prim.mli | ocaml | * Compilation of OCaml primitives. |
* This file is part of compiler .
* Copyright ( C ) 2007 - 2015 .
*
* compiler is free software ; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* ( with a change to choice of law ) .
*
* compiler 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
* Q Public License for more details .
*
* You should have received a copy of the Q Public License
* along with this program . If not , see
* < -1.0 > .
* This file is part of OCaml-Java compiler.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java compiler is free software; you can redistribute it and/or modify
* it under the terms of the Q Public License as published by
* Trolltech (with a change to choice of law).
*
* OCaml-Java compiler 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
* Q Public License for more details.
*
* You should have received a copy of the Q Public License
* along with this program. If not, see
* <-1.0>.
*)
val compile_primitive : int -> Lambda.primitive -> Macroinstr.expression list ->
(int -> Macroinstr.expression list -> Instrtree.t) ->
(bool -> int -> Macroinstr.expression -> Instrtree.t) ->
Instrtree.t
* [ compile_primitive ofs prim args cl ce ] compiles the primitive [ prim ]
at offset [ ofs ] with arguments [ args ] ; the functions [ cl ] and [ ce ]
are used to compile respectively expression lists and simple
expressions . The first function takes the following parameters :
- offset ;
- expression list to compile .
The second function takes the following parameters :
- whether the expression is in a tail position ;
- offest ;
- expression to compile .
at offset [ofs] with arguments [args]; the functions [cl] and [ce]
are used to compile respectively expression lists and simple
expressions. The first function takes the following parameters:
- offset;
- expression list to compile.
The second function takes the following parameters:
- whether the expression is in a tail position;
- offest;
- expression to compile. *)
|
9a7b52a1488203f7f95d2c1ae02e909683667c0ec774761e749117b476c9d546 | ocaml-flambda/ocaml-jst | tast_mapper.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, LexiFi
(* *)
Copyright 2015 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Asttypes
open Typedtree
(* TODO: add 'methods' for location, attribute, extension,
include_declaration, include_description *)
type mapper =
{
binding_op: mapper -> binding_op -> binding_op;
case: 'k . mapper -> 'k case -> 'k case;
class_declaration: mapper -> class_declaration -> class_declaration;
class_description: mapper -> class_description -> class_description;
class_expr: mapper -> class_expr -> class_expr;
class_field: mapper -> class_field -> class_field;
class_signature: mapper -> class_signature -> class_signature;
class_structure: mapper -> class_structure -> class_structure;
class_type: mapper -> class_type -> class_type;
class_type_declaration: mapper -> class_type_declaration ->
class_type_declaration;
class_type_field: mapper -> class_type_field -> class_type_field;
env: mapper -> Env.t -> Env.t;
expr: mapper -> expression -> expression;
extension_constructor: mapper -> extension_constructor ->
extension_constructor;
module_binding: mapper -> module_binding -> module_binding;
module_coercion: mapper -> module_coercion -> module_coercion;
module_declaration: mapper -> module_declaration -> module_declaration;
module_substitution: mapper -> module_substitution -> module_substitution;
module_expr: mapper -> module_expr -> module_expr;
module_type: mapper -> module_type -> module_type;
module_type_declaration:
mapper -> module_type_declaration -> module_type_declaration;
package_type: mapper -> package_type -> package_type;
pat: 'k . mapper -> 'k general_pattern -> 'k general_pattern;
row_field: mapper -> row_field -> row_field;
object_field: mapper -> object_field -> object_field;
open_declaration: mapper -> open_declaration -> open_declaration;
open_description: mapper -> open_description -> open_description;
signature: mapper -> signature -> signature;
signature_item: mapper -> signature_item -> signature_item;
structure: mapper -> structure -> structure;
structure_item: mapper -> structure_item -> structure_item;
typ: mapper -> core_type -> core_type;
type_declaration: mapper -> type_declaration -> type_declaration;
type_declarations: mapper -> (rec_flag * type_declaration list)
-> (rec_flag * type_declaration list);
type_extension: mapper -> type_extension -> type_extension;
type_exception: mapper -> type_exception -> type_exception;
type_kind: mapper -> type_kind -> type_kind;
value_binding: mapper -> value_binding -> value_binding;
value_bindings: mapper -> (rec_flag * value_binding list) ->
(rec_flag * value_binding list);
value_description: mapper -> value_description -> value_description;
with_constraint: mapper -> with_constraint -> with_constraint;
}
let id x = x
let tuple2 f1 f2 (x, y) = (f1 x, f2 y)
let tuple3 f1 f2 f3 (x, y, z) = (f1 x, f2 y, f3 z)
let structure sub {str_items; str_type; str_final_env} =
{
str_items = List.map (sub.structure_item sub) str_items;
str_final_env = sub.env sub str_final_env;
str_type;
}
let class_infos sub f x =
{x with
ci_params = List.map (tuple2 (sub.typ sub) id) x.ci_params;
ci_expr = f x.ci_expr;
}
let module_type_declaration sub x =
let mtd_type = Option.map (sub.module_type sub) x.mtd_type in
{x with mtd_type}
let module_declaration sub x =
let md_type = sub.module_type sub x.md_type in
{x with md_type}
let module_substitution _ x = x
let include_kind sub = function
| Tincl_structure -> Tincl_structure
| Tincl_functor ccs ->
Tincl_functor
(List.map (fun (nm, cc) -> (nm, sub.module_coercion sub cc)) ccs)
| Tincl_gen_functor ccs ->
Tincl_gen_functor
(List.map (fun (nm, cc) -> (nm, sub.module_coercion sub cc)) ccs)
let str_include_infos sub x =
{ x with incl_mod = sub.module_expr sub x.incl_mod;
incl_kind = include_kind sub x.incl_kind }
let class_type_declaration sub x =
class_infos sub (sub.class_type sub) x
let class_declaration sub x =
class_infos sub (sub.class_expr sub) x
let structure_item sub {str_desc; str_loc; str_env} =
let str_env = sub.env sub str_env in
let str_desc =
match str_desc with
| Tstr_eval (exp, attrs) -> Tstr_eval (sub.expr sub exp, attrs)
| Tstr_value (rec_flag, list) ->
let (rec_flag, list) = sub.value_bindings sub (rec_flag, list) in
Tstr_value (rec_flag, list)
| Tstr_primitive v -> Tstr_primitive (sub.value_description sub v)
| Tstr_type (rec_flag, list) ->
let (rec_flag, list) = sub.type_declarations sub (rec_flag, list) in
Tstr_type (rec_flag, list)
| Tstr_typext te -> Tstr_typext (sub.type_extension sub te)
| Tstr_exception ext -> Tstr_exception (sub.type_exception sub ext)
| Tstr_module mb -> Tstr_module (sub.module_binding sub mb)
| Tstr_recmodule list ->
Tstr_recmodule (List.map (sub.module_binding sub) list)
| Tstr_modtype x -> Tstr_modtype (sub.module_type_declaration sub x)
| Tstr_class list ->
Tstr_class
(List.map (tuple2 (sub.class_declaration sub) id) list)
| Tstr_class_type list ->
Tstr_class_type
(List.map (tuple3 id id (sub.class_type_declaration sub)) list)
| Tstr_include incl ->
Tstr_include (str_include_infos sub incl)
| Tstr_open od -> Tstr_open (sub.open_declaration sub od)
| Tstr_attribute _ as d -> d
in
{str_desc; str_env; str_loc}
let value_description sub x =
let val_desc = sub.typ sub x.val_desc in
{x with val_desc}
let label_decl sub x =
let ld_type = sub.typ sub x.ld_type in
{x with ld_type}
let field_decl sub (ty, gf) =
let ty = sub.typ sub ty in
(ty, gf)
let constructor_args sub = function
| Cstr_tuple l -> Cstr_tuple (List.map (field_decl sub) l)
| Cstr_record l -> Cstr_record (List.map (label_decl sub) l)
let constructor_decl sub cd =
let cd_args = constructor_args sub cd.cd_args in
let cd_res = Option.map (sub.typ sub) cd.cd_res in
{cd with cd_args; cd_res}
let type_kind sub = function
| Ttype_abstract -> Ttype_abstract
| Ttype_variant list -> Ttype_variant (List.map (constructor_decl sub) list)
| Ttype_record list -> Ttype_record (List.map (label_decl sub) list)
| Ttype_open -> Ttype_open
let type_declaration sub x =
let typ_cstrs =
List.map
(tuple3 (sub.typ sub) (sub.typ sub) id)
x.typ_cstrs
in
let typ_kind = sub.type_kind sub x.typ_kind in
let typ_manifest = Option.map (sub.typ sub) x.typ_manifest in
let typ_params = List.map (tuple2 (sub.typ sub) id) x.typ_params in
{x with typ_cstrs; typ_kind; typ_manifest; typ_params}
let type_declarations sub (rec_flag, list) =
(rec_flag, List.map (sub.type_declaration sub) list)
let type_extension sub x =
let tyext_params = List.map (tuple2 (sub.typ sub) id) x.tyext_params in
let tyext_constructors =
List.map (sub.extension_constructor sub) x.tyext_constructors
in
{x with tyext_constructors; tyext_params}
let type_exception sub x =
let tyexn_constructor =
sub.extension_constructor sub x.tyexn_constructor
in
{x with tyexn_constructor}
let extension_constructor sub x =
let ext_kind =
match x.ext_kind with
Text_decl(v, ctl, cto) ->
Text_decl(v, constructor_args sub ctl, Option.map (sub.typ sub) cto)
| Text_rebind _ as d -> d
in
{x with ext_kind}
let pat_extra sub = function
| Tpat_type _
| Tpat_unpack as d -> d
| Tpat_open (path,loc,env) -> Tpat_open (path, loc, sub.env sub env)
| Tpat_constraint ct -> Tpat_constraint (sub.typ sub ct)
let pat
: type k . mapper -> k general_pattern -> k general_pattern
= fun sub x ->
let pat_env = sub.env sub x.pat_env in
let pat_extra = List.map (tuple3 (pat_extra sub) id id) x.pat_extra in
let pat_desc : k pattern_desc =
match x.pat_desc with
| Tpat_any
| Tpat_var _
| Tpat_constant _ -> x.pat_desc
| Tpat_tuple l -> Tpat_tuple (List.map (sub.pat sub) l)
| Tpat_construct (loc, cd, l, vto) ->
let vto = Option.map (fun (vl,cty) -> vl, sub.typ sub cty) vto in
Tpat_construct (loc, cd, List.map (sub.pat sub) l, vto)
| Tpat_variant (l, po, rd) ->
Tpat_variant (l, Option.map (sub.pat sub) po, rd)
| Tpat_record (l, closed) ->
Tpat_record (List.map (tuple3 id id (sub.pat sub)) l, closed)
| Tpat_array (am, l) -> Tpat_array (am, List.map (sub.pat sub) l)
| Tpat_alias (p, id, s, m) -> Tpat_alias (sub.pat sub p, id, s, m)
| Tpat_lazy p -> Tpat_lazy (sub.pat sub p)
| Tpat_value p ->
(as_computation_pattern (sub.pat sub (p :> pattern))).pat_desc
| Tpat_exception p ->
Tpat_exception (sub.pat sub p)
| Tpat_or (p1, p2, rd) ->
Tpat_or (sub.pat sub p1, sub.pat sub p2, rd)
in
{x with pat_extra; pat_desc; pat_env}
let expr sub x =
let extra = function
| Texp_constraint cty ->
Texp_constraint (sub.typ sub cty)
| Texp_coerce (cty1, cty2) ->
Texp_coerce (Option.map (sub.typ sub) cty1, sub.typ sub cty2)
| Texp_newtype _ as d -> d
| Texp_poly cto -> Texp_poly (Option.map (sub.typ sub) cto)
in
let exp_extra = List.map (tuple3 extra id id) x.exp_extra in
let exp_env = sub.env sub x.exp_env in
let map_comprehension {comp_body; comp_clauses} =
{ comp_body =
sub.expr sub comp_body
; comp_clauses =
List.map
(function
| Texp_comp_for bindings ->
Texp_comp_for
(List.map
(fun {comp_cb_iterator; comp_cb_attributes} ->
let comp_cb_iterator = match comp_cb_iterator with
| Texp_comp_range
{ ident; pattern; start; stop; direction }
->
Texp_comp_range
{ ident
; pattern
(* Just mirroring [ident], ignored (see
[Texp_for] *)
; start = sub.expr sub start
; stop = sub.expr sub stop
; direction }
| Texp_comp_in { pattern; sequence } ->
Texp_comp_in
{ pattern = sub.pat sub pattern
; sequence = sub.expr sub sequence }
in
{comp_cb_iterator; comp_cb_attributes})
bindings)
| Texp_comp_when exp ->
Texp_comp_when (sub.expr sub exp))
comp_clauses
}
in
let exp_desc =
match x.exp_desc with
| Texp_ident _
| Texp_constant _ as d -> d
| Texp_let (rec_flag, list, exp) ->
let (rec_flag, list) = sub.value_bindings sub (rec_flag, list) in
Texp_let (rec_flag, list, sub.expr sub exp)
| Texp_function { arg_label; param; cases;
partial; region; curry; warnings; arg_mode; alloc_mode } ->
let cases = List.map (sub.case sub) cases in
Texp_function { arg_label; param; cases;
partial; region; curry; warnings; arg_mode; alloc_mode }
| Texp_apply (exp, list, pos, am) ->
Texp_apply (
sub.expr sub exp,
List.map (function
| (lbl, Arg exp) -> (lbl, Arg (sub.expr sub exp))
| (lbl, Omitted o) -> (lbl, Omitted o))
list,
pos, am
)
| Texp_match (exp, cases, p) ->
Texp_match (
sub.expr sub exp,
List.map (sub.case sub) cases,
p
)
| Texp_try (exp, cases) ->
Texp_try (
sub.expr sub exp,
List.map (sub.case sub) cases
)
| Texp_tuple (list, am) ->
Texp_tuple (List.map (sub.expr sub) list, am)
| Texp_construct (lid, cd, args, am) ->
Texp_construct (lid, cd, List.map (sub.expr sub) args, am)
| Texp_variant (l, expo) ->
Texp_variant (l, Option.map (fun (e, am) -> (sub.expr sub e, am)) expo)
| Texp_record { fields; representation; extended_expression; alloc_mode } ->
let fields = Array.map (function
| label, Kept t -> label, Kept t
| label, Overridden (lid, exp) ->
label, Overridden (lid, sub.expr sub exp))
fields
in
Texp_record {
fields; representation;
extended_expression = Option.map (sub.expr sub) extended_expression;
alloc_mode
}
| Texp_field (exp, lid, ld, am) ->
Texp_field (sub.expr sub exp, lid, ld, am)
| Texp_setfield (exp1, am, lid, ld, exp2) ->
Texp_setfield (
sub.expr sub exp1,
am,
lid,
ld,
sub.expr sub exp2
)
| Texp_array (amut, list, alloc_mode) ->
Texp_array (amut, List.map (sub.expr sub) list, alloc_mode)
| Texp_list_comprehension comp ->
Texp_list_comprehension (map_comprehension comp)
| Texp_array_comprehension (amut, comp) ->
Texp_array_comprehension (amut, map_comprehension comp)
| Texp_ifthenelse (exp1, exp2, expo) ->
Texp_ifthenelse (
sub.expr sub exp1,
sub.expr sub exp2,
Option.map (sub.expr sub) expo
)
| Texp_sequence (exp1, exp2) ->
Texp_sequence (
sub.expr sub exp1,
sub.expr sub exp2
)
| Texp_while wh ->
Texp_while { wh with wh_cond = sub.expr sub wh.wh_cond;
wh_body = sub.expr sub wh.wh_body
}
| Texp_for tf ->
Texp_for {tf with for_from = sub.expr sub tf.for_from;
for_to = sub.expr sub tf.for_to;
for_body = sub.expr sub tf.for_body}
| Texp_send (exp, meth, ap, am) ->
Texp_send
(
sub.expr sub exp,
meth,
ap,
am
)
| Texp_new _
| Texp_instvar _ as d -> d
| Texp_setinstvar (path1, path2, id, exp) ->
Texp_setinstvar (
path1,
path2,
id,
sub.expr sub exp
)
| Texp_override (path, list) ->
Texp_override (
path,
List.map (tuple3 id id (sub.expr sub)) list
)
| Texp_letmodule (id, s, pres, mexpr, exp) ->
Texp_letmodule (
id,
s,
pres,
sub.module_expr sub mexpr,
sub.expr sub exp
)
| Texp_letexception (cd, exp) ->
Texp_letexception (
sub.extension_constructor sub cd,
sub.expr sub exp
)
| Texp_assert exp ->
Texp_assert (sub.expr sub exp)
| Texp_lazy exp ->
Texp_lazy (sub.expr sub exp)
| Texp_object (cl, sl) ->
Texp_object (sub.class_structure sub cl, sl)
| Texp_pack mexpr ->
Texp_pack (sub.module_expr sub mexpr)
| Texp_letop {let_; ands; param; body; partial; warnings} ->
Texp_letop{
let_ = sub.binding_op sub let_;
ands = List.map (sub.binding_op sub) ands;
param;
body = sub.case sub body;
partial;
warnings
}
| Texp_unreachable ->
Texp_unreachable
| Texp_extension_constructor _ as e ->
e
| Texp_open (od, e) ->
Texp_open (sub.open_declaration sub od, sub.expr sub e)
| Texp_probe {name; handler} ->
Texp_probe {name; handler = sub.expr sub handler }
| Texp_probe_is_enabled _ as e -> e
in
{x with exp_extra; exp_desc; exp_env}
let package_type sub x =
let pack_fields = List.map (tuple2 id (sub.typ sub)) x.pack_fields in
{x with pack_fields}
let binding_op sub x =
{ x with bop_exp = sub.expr sub x.bop_exp }
let signature sub x =
let sig_final_env = sub.env sub x.sig_final_env in
let sig_items = List.map (sub.signature_item sub) x.sig_items in
{x with sig_items; sig_final_env}
let sig_include_infos sub x =
{ x with incl_mod = sub.module_type sub x.incl_mod;
incl_kind = include_kind sub x.incl_kind }
let signature_item sub x =
let sig_env = sub.env sub x.sig_env in
let sig_desc =
match x.sig_desc with
| Tsig_value v ->
Tsig_value (sub.value_description sub v)
| Tsig_type (rec_flag, list) ->
let (rec_flag, list) = sub.type_declarations sub (rec_flag, list) in
Tsig_type (rec_flag, list)
| Tsig_typesubst list ->
let (_, list) = sub.type_declarations sub (Nonrecursive, list) in
Tsig_typesubst list
| Tsig_typext te ->
Tsig_typext (sub.type_extension sub te)
| Tsig_exception ext ->
Tsig_exception (sub.type_exception sub ext)
| Tsig_module x ->
Tsig_module (sub.module_declaration sub x)
| Tsig_modsubst x ->
Tsig_modsubst (sub.module_substitution sub x)
| Tsig_recmodule list ->
Tsig_recmodule (List.map (sub.module_declaration sub) list)
| Tsig_modtype x ->
Tsig_modtype (sub.module_type_declaration sub x)
| Tsig_modtypesubst x ->
Tsig_modtypesubst (sub.module_type_declaration sub x)
| Tsig_include incl ->
Tsig_include (sig_include_infos sub incl)
| Tsig_class list ->
Tsig_class (List.map (sub.class_description sub) list)
| Tsig_class_type list ->
Tsig_class_type
(List.map (sub.class_type_declaration sub) list)
| Tsig_open od -> Tsig_open (sub.open_description sub od)
| Tsig_attribute _ as d -> d
in
{x with sig_desc; sig_env}
let class_description sub x =
class_infos sub (sub.class_type sub) x
let functor_parameter sub = function
| Unit -> Unit
| Named (id, s, mtype) -> Named (id, s, sub.module_type sub mtype)
let module_type sub x =
let mty_env = sub.env sub x.mty_env in
let mty_desc =
match x.mty_desc with
| Tmty_ident _
| Tmty_alias _ as d -> d
| Tmty_signature sg -> Tmty_signature (sub.signature sub sg)
| Tmty_functor (arg, mtype2) ->
Tmty_functor (functor_parameter sub arg, sub.module_type sub mtype2)
| Tmty_with (mtype, list) ->
Tmty_with (
sub.module_type sub mtype,
List.map (tuple3 id id (sub.with_constraint sub)) list
)
| Tmty_typeof mexpr ->
Tmty_typeof (sub.module_expr sub mexpr)
in
{x with mty_desc; mty_env}
let with_constraint sub = function
| Twith_type decl -> Twith_type (sub.type_declaration sub decl)
| Twith_typesubst decl -> Twith_typesubst (sub.type_declaration sub decl)
| Twith_modtype mty -> Twith_modtype (sub.module_type sub mty)
| Twith_modtypesubst mty -> Twith_modtypesubst (sub.module_type sub mty)
| Twith_module _
| Twith_modsubst _ as d -> d
let open_description sub od =
{od with open_env = sub.env sub od.open_env}
let open_declaration sub od =
{od with open_expr = sub.module_expr sub od.open_expr;
open_env = sub.env sub od.open_env}
let module_coercion sub = function
| Tcoerce_none -> Tcoerce_none
| Tcoerce_functor (c1,c2) ->
Tcoerce_functor (sub.module_coercion sub c1, sub.module_coercion sub c2)
| Tcoerce_alias (env, p, c1) ->
Tcoerce_alias (sub.env sub env, p, sub.module_coercion sub c1)
| Tcoerce_structure (l1, l2) ->
let l1' = List.map (fun (i,c) -> i, sub.module_coercion sub c) l1 in
let l2' =
List.map (fun (id,i,c) -> id, i, sub.module_coercion sub c) l2
in
Tcoerce_structure (l1', l2')
| Tcoerce_primitive pc ->
Tcoerce_primitive {pc with pc_env = sub.env sub pc.pc_env}
let module_expr sub x =
let mod_env = sub.env sub x.mod_env in
let mod_desc =
match x.mod_desc with
| Tmod_ident _ as d -> d
| Tmod_structure st -> Tmod_structure (sub.structure sub st)
| Tmod_functor (arg, mexpr) ->
Tmod_functor (functor_parameter sub arg, sub.module_expr sub mexpr)
| Tmod_apply (mexp1, mexp2, c) ->
Tmod_apply (
sub.module_expr sub mexp1,
sub.module_expr sub mexp2,
sub.module_coercion sub c
)
| Tmod_constraint (mexpr, mt, Tmodtype_implicit, c) ->
Tmod_constraint (sub.module_expr sub mexpr, mt, Tmodtype_implicit,
sub.module_coercion sub c)
| Tmod_constraint (mexpr, mt, Tmodtype_explicit mtype, c) ->
Tmod_constraint (
sub.module_expr sub mexpr,
mt,
Tmodtype_explicit (sub.module_type sub mtype),
sub.module_coercion sub c
)
| Tmod_unpack (exp, mty) ->
Tmod_unpack
(
sub.expr sub exp,
mty
)
in
{x with mod_desc; mod_env}
let module_binding sub x =
let mb_expr = sub.module_expr sub x.mb_expr in
{x with mb_expr}
let class_expr sub x =
let cl_env = sub.env sub x.cl_env in
let cl_desc =
match x.cl_desc with
| Tcl_constraint (cl, clty, vals, meths, concrs) ->
Tcl_constraint (
sub.class_expr sub cl,
Option.map (sub.class_type sub) clty,
vals,
meths,
concrs
)
| Tcl_structure clstr ->
Tcl_structure (sub.class_structure sub clstr)
| Tcl_fun (label, pat, priv, cl, partial) ->
Tcl_fun (
label,
sub.pat sub pat,
List.map (tuple2 id (sub.expr sub)) priv,
sub.class_expr sub cl,
partial
)
| Tcl_apply (cl, args) ->
Tcl_apply (
sub.class_expr sub cl,
List.map (function
| (lbl, Arg exp) -> (lbl, Arg (sub.expr sub exp))
| (lbl, Omitted o) -> (lbl, Omitted o))
args
)
| Tcl_let (rec_flag, value_bindings, ivars, cl) ->
let (rec_flag, value_bindings) =
sub.value_bindings sub (rec_flag, value_bindings)
in
Tcl_let (
rec_flag,
value_bindings,
List.map (tuple2 id (sub.expr sub)) ivars,
sub.class_expr sub cl
)
| Tcl_ident (path, lid, tyl) ->
Tcl_ident (path, lid, List.map (sub.typ sub) tyl)
| Tcl_open (od, e) ->
Tcl_open (sub.open_description sub od, sub.class_expr sub e)
in
{x with cl_desc; cl_env}
let class_type sub x =
let cltyp_env = sub.env sub x.cltyp_env in
let cltyp_desc =
match x.cltyp_desc with
| Tcty_signature csg -> Tcty_signature (sub.class_signature sub csg)
| Tcty_constr (path, lid, list) ->
Tcty_constr (
path,
lid,
List.map (sub.typ sub) list
)
| Tcty_arrow (label, ct, cl) ->
Tcty_arrow
(label,
sub.typ sub ct,
sub.class_type sub cl
)
| Tcty_open (od, e) ->
Tcty_open (sub.open_description sub od, sub.class_type sub e)
in
{x with cltyp_desc; cltyp_env}
let class_signature sub x =
let csig_self = sub.typ sub x.csig_self in
let csig_fields = List.map (sub.class_type_field sub) x.csig_fields in
{x with csig_self; csig_fields}
let class_type_field sub x =
let ctf_desc =
match x.ctf_desc with
| Tctf_inherit ct ->
Tctf_inherit (sub.class_type sub ct)
| Tctf_val (s, mut, virt, ct) ->
Tctf_val (s, mut, virt, sub.typ sub ct)
| Tctf_method (s, priv, virt, ct) ->
Tctf_method (s, priv, virt, sub.typ sub ct)
| Tctf_constraint (ct1, ct2) ->
Tctf_constraint (sub.typ sub ct1, sub.typ sub ct2)
| Tctf_attribute _ as d -> d
in
{x with ctf_desc}
let typ sub x =
let ctyp_env = sub.env sub x.ctyp_env in
let ctyp_desc =
match x.ctyp_desc with
| Ttyp_any
| Ttyp_var _ as d -> d
| Ttyp_arrow (label, ct1, ct2) ->
Ttyp_arrow (label, sub.typ sub ct1, sub.typ sub ct2)
| Ttyp_tuple list -> Ttyp_tuple (List.map (sub.typ sub) list)
| Ttyp_constr (path, lid, list) ->
Ttyp_constr (path, lid, List.map (sub.typ sub) list)
| Ttyp_object (list, closed) ->
Ttyp_object ((List.map (sub.object_field sub) list), closed)
| Ttyp_class (path, lid, list) ->
Ttyp_class
(path,
lid,
List.map (sub.typ sub) list
)
| Ttyp_alias (ct, s) ->
Ttyp_alias (sub.typ sub ct, s)
| Ttyp_variant (list, closed, labels) ->
Ttyp_variant (List.map (sub.row_field sub) list, closed, labels)
| Ttyp_poly (sl, ct) ->
Ttyp_poly (sl, sub.typ sub ct)
| Ttyp_package pack ->
Ttyp_package (sub.package_type sub pack)
in
{x with ctyp_desc; ctyp_env}
let class_structure sub x =
let cstr_self = sub.pat sub x.cstr_self in
let cstr_fields = List.map (sub.class_field sub) x.cstr_fields in
{x with cstr_self; cstr_fields}
let row_field sub x =
let rf_desc = match x.rf_desc with
| Ttag (label, b, list) ->
Ttag (label, b, List.map (sub.typ sub) list)
| Tinherit ct -> Tinherit (sub.typ sub ct)
in
{ x with rf_desc; }
let object_field sub x =
let of_desc = match x.of_desc with
| OTtag (label, ct) ->
OTtag (label, (sub.typ sub ct))
| OTinherit ct -> OTinherit (sub.typ sub ct)
in
{ x with of_desc; }
let class_field_kind sub = function
| Tcfk_virtual ct -> Tcfk_virtual (sub.typ sub ct)
| Tcfk_concrete (ovf, e) -> Tcfk_concrete (ovf, sub.expr sub e)
let class_field sub x =
let cf_desc =
match x.cf_desc with
| Tcf_inherit (ovf, cl, super, vals, meths) ->
Tcf_inherit (ovf, sub.class_expr sub cl, super, vals, meths)
| Tcf_constraint (cty, cty') ->
Tcf_constraint (
sub.typ sub cty,
sub.typ sub cty'
)
| Tcf_val (s, mf, id, k, b) ->
Tcf_val (s, mf, id, class_field_kind sub k, b)
| Tcf_method (s, priv, k) ->
Tcf_method (s, priv, class_field_kind sub k)
| Tcf_initializer exp ->
Tcf_initializer (sub.expr sub exp)
| Tcf_attribute _ as d -> d
in
{x with cf_desc}
let value_bindings sub (rec_flag, list) =
(rec_flag, List.map (sub.value_binding sub) list)
let case
: type k . mapper -> k case -> k case
= fun sub {c_lhs; c_guard; c_rhs} ->
{
c_lhs = sub.pat sub c_lhs;
c_guard = Option.map (sub.expr sub) c_guard;
c_rhs = sub.expr sub c_rhs;
}
let value_binding sub x =
let vb_pat = sub.pat sub x.vb_pat in
let vb_expr = sub.expr sub x.vb_expr in
{x with vb_pat; vb_expr}
let env _sub x = x
let default =
{
binding_op;
case;
class_declaration;
class_description;
class_expr;
class_field;
class_signature;
class_structure;
class_type;
class_type_declaration;
class_type_field;
env;
expr;
extension_constructor;
module_binding;
module_coercion;
module_declaration;
module_substitution;
module_expr;
module_type;
module_type_declaration;
package_type;
pat;
row_field;
object_field;
open_declaration;
open_description;
signature;
signature_item;
structure;
structure_item;
typ;
type_declaration;
type_declarations;
type_extension;
type_exception;
type_kind;
value_binding;
value_bindings;
value_description;
with_constraint;
}
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/4fd53a1f6fa8e93d60e808bc82ee79f622709f09/typing/tast_mapper.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
TODO: add 'methods' for location, attribute, extension,
include_declaration, include_description
Just mirroring [ident], ignored (see
[Texp_for] | , LexiFi
Copyright 2015 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Asttypes
open Typedtree
type mapper =
{
binding_op: mapper -> binding_op -> binding_op;
case: 'k . mapper -> 'k case -> 'k case;
class_declaration: mapper -> class_declaration -> class_declaration;
class_description: mapper -> class_description -> class_description;
class_expr: mapper -> class_expr -> class_expr;
class_field: mapper -> class_field -> class_field;
class_signature: mapper -> class_signature -> class_signature;
class_structure: mapper -> class_structure -> class_structure;
class_type: mapper -> class_type -> class_type;
class_type_declaration: mapper -> class_type_declaration ->
class_type_declaration;
class_type_field: mapper -> class_type_field -> class_type_field;
env: mapper -> Env.t -> Env.t;
expr: mapper -> expression -> expression;
extension_constructor: mapper -> extension_constructor ->
extension_constructor;
module_binding: mapper -> module_binding -> module_binding;
module_coercion: mapper -> module_coercion -> module_coercion;
module_declaration: mapper -> module_declaration -> module_declaration;
module_substitution: mapper -> module_substitution -> module_substitution;
module_expr: mapper -> module_expr -> module_expr;
module_type: mapper -> module_type -> module_type;
module_type_declaration:
mapper -> module_type_declaration -> module_type_declaration;
package_type: mapper -> package_type -> package_type;
pat: 'k . mapper -> 'k general_pattern -> 'k general_pattern;
row_field: mapper -> row_field -> row_field;
object_field: mapper -> object_field -> object_field;
open_declaration: mapper -> open_declaration -> open_declaration;
open_description: mapper -> open_description -> open_description;
signature: mapper -> signature -> signature;
signature_item: mapper -> signature_item -> signature_item;
structure: mapper -> structure -> structure;
structure_item: mapper -> structure_item -> structure_item;
typ: mapper -> core_type -> core_type;
type_declaration: mapper -> type_declaration -> type_declaration;
type_declarations: mapper -> (rec_flag * type_declaration list)
-> (rec_flag * type_declaration list);
type_extension: mapper -> type_extension -> type_extension;
type_exception: mapper -> type_exception -> type_exception;
type_kind: mapper -> type_kind -> type_kind;
value_binding: mapper -> value_binding -> value_binding;
value_bindings: mapper -> (rec_flag * value_binding list) ->
(rec_flag * value_binding list);
value_description: mapper -> value_description -> value_description;
with_constraint: mapper -> with_constraint -> with_constraint;
}
let id x = x
let tuple2 f1 f2 (x, y) = (f1 x, f2 y)
let tuple3 f1 f2 f3 (x, y, z) = (f1 x, f2 y, f3 z)
let structure sub {str_items; str_type; str_final_env} =
{
str_items = List.map (sub.structure_item sub) str_items;
str_final_env = sub.env sub str_final_env;
str_type;
}
let class_infos sub f x =
{x with
ci_params = List.map (tuple2 (sub.typ sub) id) x.ci_params;
ci_expr = f x.ci_expr;
}
let module_type_declaration sub x =
let mtd_type = Option.map (sub.module_type sub) x.mtd_type in
{x with mtd_type}
let module_declaration sub x =
let md_type = sub.module_type sub x.md_type in
{x with md_type}
let module_substitution _ x = x
let include_kind sub = function
| Tincl_structure -> Tincl_structure
| Tincl_functor ccs ->
Tincl_functor
(List.map (fun (nm, cc) -> (nm, sub.module_coercion sub cc)) ccs)
| Tincl_gen_functor ccs ->
Tincl_gen_functor
(List.map (fun (nm, cc) -> (nm, sub.module_coercion sub cc)) ccs)
let str_include_infos sub x =
{ x with incl_mod = sub.module_expr sub x.incl_mod;
incl_kind = include_kind sub x.incl_kind }
let class_type_declaration sub x =
class_infos sub (sub.class_type sub) x
let class_declaration sub x =
class_infos sub (sub.class_expr sub) x
let structure_item sub {str_desc; str_loc; str_env} =
let str_env = sub.env sub str_env in
let str_desc =
match str_desc with
| Tstr_eval (exp, attrs) -> Tstr_eval (sub.expr sub exp, attrs)
| Tstr_value (rec_flag, list) ->
let (rec_flag, list) = sub.value_bindings sub (rec_flag, list) in
Tstr_value (rec_flag, list)
| Tstr_primitive v -> Tstr_primitive (sub.value_description sub v)
| Tstr_type (rec_flag, list) ->
let (rec_flag, list) = sub.type_declarations sub (rec_flag, list) in
Tstr_type (rec_flag, list)
| Tstr_typext te -> Tstr_typext (sub.type_extension sub te)
| Tstr_exception ext -> Tstr_exception (sub.type_exception sub ext)
| Tstr_module mb -> Tstr_module (sub.module_binding sub mb)
| Tstr_recmodule list ->
Tstr_recmodule (List.map (sub.module_binding sub) list)
| Tstr_modtype x -> Tstr_modtype (sub.module_type_declaration sub x)
| Tstr_class list ->
Tstr_class
(List.map (tuple2 (sub.class_declaration sub) id) list)
| Tstr_class_type list ->
Tstr_class_type
(List.map (tuple3 id id (sub.class_type_declaration sub)) list)
| Tstr_include incl ->
Tstr_include (str_include_infos sub incl)
| Tstr_open od -> Tstr_open (sub.open_declaration sub od)
| Tstr_attribute _ as d -> d
in
{str_desc; str_env; str_loc}
let value_description sub x =
let val_desc = sub.typ sub x.val_desc in
{x with val_desc}
let label_decl sub x =
let ld_type = sub.typ sub x.ld_type in
{x with ld_type}
let field_decl sub (ty, gf) =
let ty = sub.typ sub ty in
(ty, gf)
let constructor_args sub = function
| Cstr_tuple l -> Cstr_tuple (List.map (field_decl sub) l)
| Cstr_record l -> Cstr_record (List.map (label_decl sub) l)
let constructor_decl sub cd =
let cd_args = constructor_args sub cd.cd_args in
let cd_res = Option.map (sub.typ sub) cd.cd_res in
{cd with cd_args; cd_res}
let type_kind sub = function
| Ttype_abstract -> Ttype_abstract
| Ttype_variant list -> Ttype_variant (List.map (constructor_decl sub) list)
| Ttype_record list -> Ttype_record (List.map (label_decl sub) list)
| Ttype_open -> Ttype_open
let type_declaration sub x =
let typ_cstrs =
List.map
(tuple3 (sub.typ sub) (sub.typ sub) id)
x.typ_cstrs
in
let typ_kind = sub.type_kind sub x.typ_kind in
let typ_manifest = Option.map (sub.typ sub) x.typ_manifest in
let typ_params = List.map (tuple2 (sub.typ sub) id) x.typ_params in
{x with typ_cstrs; typ_kind; typ_manifest; typ_params}
let type_declarations sub (rec_flag, list) =
(rec_flag, List.map (sub.type_declaration sub) list)
let type_extension sub x =
let tyext_params = List.map (tuple2 (sub.typ sub) id) x.tyext_params in
let tyext_constructors =
List.map (sub.extension_constructor sub) x.tyext_constructors
in
{x with tyext_constructors; tyext_params}
let type_exception sub x =
let tyexn_constructor =
sub.extension_constructor sub x.tyexn_constructor
in
{x with tyexn_constructor}
let extension_constructor sub x =
let ext_kind =
match x.ext_kind with
Text_decl(v, ctl, cto) ->
Text_decl(v, constructor_args sub ctl, Option.map (sub.typ sub) cto)
| Text_rebind _ as d -> d
in
{x with ext_kind}
let pat_extra sub = function
| Tpat_type _
| Tpat_unpack as d -> d
| Tpat_open (path,loc,env) -> Tpat_open (path, loc, sub.env sub env)
| Tpat_constraint ct -> Tpat_constraint (sub.typ sub ct)
let pat
: type k . mapper -> k general_pattern -> k general_pattern
= fun sub x ->
let pat_env = sub.env sub x.pat_env in
let pat_extra = List.map (tuple3 (pat_extra sub) id id) x.pat_extra in
let pat_desc : k pattern_desc =
match x.pat_desc with
| Tpat_any
| Tpat_var _
| Tpat_constant _ -> x.pat_desc
| Tpat_tuple l -> Tpat_tuple (List.map (sub.pat sub) l)
| Tpat_construct (loc, cd, l, vto) ->
let vto = Option.map (fun (vl,cty) -> vl, sub.typ sub cty) vto in
Tpat_construct (loc, cd, List.map (sub.pat sub) l, vto)
| Tpat_variant (l, po, rd) ->
Tpat_variant (l, Option.map (sub.pat sub) po, rd)
| Tpat_record (l, closed) ->
Tpat_record (List.map (tuple3 id id (sub.pat sub)) l, closed)
| Tpat_array (am, l) -> Tpat_array (am, List.map (sub.pat sub) l)
| Tpat_alias (p, id, s, m) -> Tpat_alias (sub.pat sub p, id, s, m)
| Tpat_lazy p -> Tpat_lazy (sub.pat sub p)
| Tpat_value p ->
(as_computation_pattern (sub.pat sub (p :> pattern))).pat_desc
| Tpat_exception p ->
Tpat_exception (sub.pat sub p)
| Tpat_or (p1, p2, rd) ->
Tpat_or (sub.pat sub p1, sub.pat sub p2, rd)
in
{x with pat_extra; pat_desc; pat_env}
let expr sub x =
let extra = function
| Texp_constraint cty ->
Texp_constraint (sub.typ sub cty)
| Texp_coerce (cty1, cty2) ->
Texp_coerce (Option.map (sub.typ sub) cty1, sub.typ sub cty2)
| Texp_newtype _ as d -> d
| Texp_poly cto -> Texp_poly (Option.map (sub.typ sub) cto)
in
let exp_extra = List.map (tuple3 extra id id) x.exp_extra in
let exp_env = sub.env sub x.exp_env in
let map_comprehension {comp_body; comp_clauses} =
{ comp_body =
sub.expr sub comp_body
; comp_clauses =
List.map
(function
| Texp_comp_for bindings ->
Texp_comp_for
(List.map
(fun {comp_cb_iterator; comp_cb_attributes} ->
let comp_cb_iterator = match comp_cb_iterator with
| Texp_comp_range
{ ident; pattern; start; stop; direction }
->
Texp_comp_range
{ ident
; pattern
; start = sub.expr sub start
; stop = sub.expr sub stop
; direction }
| Texp_comp_in { pattern; sequence } ->
Texp_comp_in
{ pattern = sub.pat sub pattern
; sequence = sub.expr sub sequence }
in
{comp_cb_iterator; comp_cb_attributes})
bindings)
| Texp_comp_when exp ->
Texp_comp_when (sub.expr sub exp))
comp_clauses
}
in
let exp_desc =
match x.exp_desc with
| Texp_ident _
| Texp_constant _ as d -> d
| Texp_let (rec_flag, list, exp) ->
let (rec_flag, list) = sub.value_bindings sub (rec_flag, list) in
Texp_let (rec_flag, list, sub.expr sub exp)
| Texp_function { arg_label; param; cases;
partial; region; curry; warnings; arg_mode; alloc_mode } ->
let cases = List.map (sub.case sub) cases in
Texp_function { arg_label; param; cases;
partial; region; curry; warnings; arg_mode; alloc_mode }
| Texp_apply (exp, list, pos, am) ->
Texp_apply (
sub.expr sub exp,
List.map (function
| (lbl, Arg exp) -> (lbl, Arg (sub.expr sub exp))
| (lbl, Omitted o) -> (lbl, Omitted o))
list,
pos, am
)
| Texp_match (exp, cases, p) ->
Texp_match (
sub.expr sub exp,
List.map (sub.case sub) cases,
p
)
| Texp_try (exp, cases) ->
Texp_try (
sub.expr sub exp,
List.map (sub.case sub) cases
)
| Texp_tuple (list, am) ->
Texp_tuple (List.map (sub.expr sub) list, am)
| Texp_construct (lid, cd, args, am) ->
Texp_construct (lid, cd, List.map (sub.expr sub) args, am)
| Texp_variant (l, expo) ->
Texp_variant (l, Option.map (fun (e, am) -> (sub.expr sub e, am)) expo)
| Texp_record { fields; representation; extended_expression; alloc_mode } ->
let fields = Array.map (function
| label, Kept t -> label, Kept t
| label, Overridden (lid, exp) ->
label, Overridden (lid, sub.expr sub exp))
fields
in
Texp_record {
fields; representation;
extended_expression = Option.map (sub.expr sub) extended_expression;
alloc_mode
}
| Texp_field (exp, lid, ld, am) ->
Texp_field (sub.expr sub exp, lid, ld, am)
| Texp_setfield (exp1, am, lid, ld, exp2) ->
Texp_setfield (
sub.expr sub exp1,
am,
lid,
ld,
sub.expr sub exp2
)
| Texp_array (amut, list, alloc_mode) ->
Texp_array (amut, List.map (sub.expr sub) list, alloc_mode)
| Texp_list_comprehension comp ->
Texp_list_comprehension (map_comprehension comp)
| Texp_array_comprehension (amut, comp) ->
Texp_array_comprehension (amut, map_comprehension comp)
| Texp_ifthenelse (exp1, exp2, expo) ->
Texp_ifthenelse (
sub.expr sub exp1,
sub.expr sub exp2,
Option.map (sub.expr sub) expo
)
| Texp_sequence (exp1, exp2) ->
Texp_sequence (
sub.expr sub exp1,
sub.expr sub exp2
)
| Texp_while wh ->
Texp_while { wh with wh_cond = sub.expr sub wh.wh_cond;
wh_body = sub.expr sub wh.wh_body
}
| Texp_for tf ->
Texp_for {tf with for_from = sub.expr sub tf.for_from;
for_to = sub.expr sub tf.for_to;
for_body = sub.expr sub tf.for_body}
| Texp_send (exp, meth, ap, am) ->
Texp_send
(
sub.expr sub exp,
meth,
ap,
am
)
| Texp_new _
| Texp_instvar _ as d -> d
| Texp_setinstvar (path1, path2, id, exp) ->
Texp_setinstvar (
path1,
path2,
id,
sub.expr sub exp
)
| Texp_override (path, list) ->
Texp_override (
path,
List.map (tuple3 id id (sub.expr sub)) list
)
| Texp_letmodule (id, s, pres, mexpr, exp) ->
Texp_letmodule (
id,
s,
pres,
sub.module_expr sub mexpr,
sub.expr sub exp
)
| Texp_letexception (cd, exp) ->
Texp_letexception (
sub.extension_constructor sub cd,
sub.expr sub exp
)
| Texp_assert exp ->
Texp_assert (sub.expr sub exp)
| Texp_lazy exp ->
Texp_lazy (sub.expr sub exp)
| Texp_object (cl, sl) ->
Texp_object (sub.class_structure sub cl, sl)
| Texp_pack mexpr ->
Texp_pack (sub.module_expr sub mexpr)
| Texp_letop {let_; ands; param; body; partial; warnings} ->
Texp_letop{
let_ = sub.binding_op sub let_;
ands = List.map (sub.binding_op sub) ands;
param;
body = sub.case sub body;
partial;
warnings
}
| Texp_unreachable ->
Texp_unreachable
| Texp_extension_constructor _ as e ->
e
| Texp_open (od, e) ->
Texp_open (sub.open_declaration sub od, sub.expr sub e)
| Texp_probe {name; handler} ->
Texp_probe {name; handler = sub.expr sub handler }
| Texp_probe_is_enabled _ as e -> e
in
{x with exp_extra; exp_desc; exp_env}
let package_type sub x =
let pack_fields = List.map (tuple2 id (sub.typ sub)) x.pack_fields in
{x with pack_fields}
let binding_op sub x =
{ x with bop_exp = sub.expr sub x.bop_exp }
let signature sub x =
let sig_final_env = sub.env sub x.sig_final_env in
let sig_items = List.map (sub.signature_item sub) x.sig_items in
{x with sig_items; sig_final_env}
let sig_include_infos sub x =
{ x with incl_mod = sub.module_type sub x.incl_mod;
incl_kind = include_kind sub x.incl_kind }
let signature_item sub x =
let sig_env = sub.env sub x.sig_env in
let sig_desc =
match x.sig_desc with
| Tsig_value v ->
Tsig_value (sub.value_description sub v)
| Tsig_type (rec_flag, list) ->
let (rec_flag, list) = sub.type_declarations sub (rec_flag, list) in
Tsig_type (rec_flag, list)
| Tsig_typesubst list ->
let (_, list) = sub.type_declarations sub (Nonrecursive, list) in
Tsig_typesubst list
| Tsig_typext te ->
Tsig_typext (sub.type_extension sub te)
| Tsig_exception ext ->
Tsig_exception (sub.type_exception sub ext)
| Tsig_module x ->
Tsig_module (sub.module_declaration sub x)
| Tsig_modsubst x ->
Tsig_modsubst (sub.module_substitution sub x)
| Tsig_recmodule list ->
Tsig_recmodule (List.map (sub.module_declaration sub) list)
| Tsig_modtype x ->
Tsig_modtype (sub.module_type_declaration sub x)
| Tsig_modtypesubst x ->
Tsig_modtypesubst (sub.module_type_declaration sub x)
| Tsig_include incl ->
Tsig_include (sig_include_infos sub incl)
| Tsig_class list ->
Tsig_class (List.map (sub.class_description sub) list)
| Tsig_class_type list ->
Tsig_class_type
(List.map (sub.class_type_declaration sub) list)
| Tsig_open od -> Tsig_open (sub.open_description sub od)
| Tsig_attribute _ as d -> d
in
{x with sig_desc; sig_env}
let class_description sub x =
class_infos sub (sub.class_type sub) x
let functor_parameter sub = function
| Unit -> Unit
| Named (id, s, mtype) -> Named (id, s, sub.module_type sub mtype)
let module_type sub x =
let mty_env = sub.env sub x.mty_env in
let mty_desc =
match x.mty_desc with
| Tmty_ident _
| Tmty_alias _ as d -> d
| Tmty_signature sg -> Tmty_signature (sub.signature sub sg)
| Tmty_functor (arg, mtype2) ->
Tmty_functor (functor_parameter sub arg, sub.module_type sub mtype2)
| Tmty_with (mtype, list) ->
Tmty_with (
sub.module_type sub mtype,
List.map (tuple3 id id (sub.with_constraint sub)) list
)
| Tmty_typeof mexpr ->
Tmty_typeof (sub.module_expr sub mexpr)
in
{x with mty_desc; mty_env}
let with_constraint sub = function
| Twith_type decl -> Twith_type (sub.type_declaration sub decl)
| Twith_typesubst decl -> Twith_typesubst (sub.type_declaration sub decl)
| Twith_modtype mty -> Twith_modtype (sub.module_type sub mty)
| Twith_modtypesubst mty -> Twith_modtypesubst (sub.module_type sub mty)
| Twith_module _
| Twith_modsubst _ as d -> d
let open_description sub od =
{od with open_env = sub.env sub od.open_env}
let open_declaration sub od =
{od with open_expr = sub.module_expr sub od.open_expr;
open_env = sub.env sub od.open_env}
let module_coercion sub = function
| Tcoerce_none -> Tcoerce_none
| Tcoerce_functor (c1,c2) ->
Tcoerce_functor (sub.module_coercion sub c1, sub.module_coercion sub c2)
| Tcoerce_alias (env, p, c1) ->
Tcoerce_alias (sub.env sub env, p, sub.module_coercion sub c1)
| Tcoerce_structure (l1, l2) ->
let l1' = List.map (fun (i,c) -> i, sub.module_coercion sub c) l1 in
let l2' =
List.map (fun (id,i,c) -> id, i, sub.module_coercion sub c) l2
in
Tcoerce_structure (l1', l2')
| Tcoerce_primitive pc ->
Tcoerce_primitive {pc with pc_env = sub.env sub pc.pc_env}
let module_expr sub x =
let mod_env = sub.env sub x.mod_env in
let mod_desc =
match x.mod_desc with
| Tmod_ident _ as d -> d
| Tmod_structure st -> Tmod_structure (sub.structure sub st)
| Tmod_functor (arg, mexpr) ->
Tmod_functor (functor_parameter sub arg, sub.module_expr sub mexpr)
| Tmod_apply (mexp1, mexp2, c) ->
Tmod_apply (
sub.module_expr sub mexp1,
sub.module_expr sub mexp2,
sub.module_coercion sub c
)
| Tmod_constraint (mexpr, mt, Tmodtype_implicit, c) ->
Tmod_constraint (sub.module_expr sub mexpr, mt, Tmodtype_implicit,
sub.module_coercion sub c)
| Tmod_constraint (mexpr, mt, Tmodtype_explicit mtype, c) ->
Tmod_constraint (
sub.module_expr sub mexpr,
mt,
Tmodtype_explicit (sub.module_type sub mtype),
sub.module_coercion sub c
)
| Tmod_unpack (exp, mty) ->
Tmod_unpack
(
sub.expr sub exp,
mty
)
in
{x with mod_desc; mod_env}
let module_binding sub x =
let mb_expr = sub.module_expr sub x.mb_expr in
{x with mb_expr}
let class_expr sub x =
let cl_env = sub.env sub x.cl_env in
let cl_desc =
match x.cl_desc with
| Tcl_constraint (cl, clty, vals, meths, concrs) ->
Tcl_constraint (
sub.class_expr sub cl,
Option.map (sub.class_type sub) clty,
vals,
meths,
concrs
)
| Tcl_structure clstr ->
Tcl_structure (sub.class_structure sub clstr)
| Tcl_fun (label, pat, priv, cl, partial) ->
Tcl_fun (
label,
sub.pat sub pat,
List.map (tuple2 id (sub.expr sub)) priv,
sub.class_expr sub cl,
partial
)
| Tcl_apply (cl, args) ->
Tcl_apply (
sub.class_expr sub cl,
List.map (function
| (lbl, Arg exp) -> (lbl, Arg (sub.expr sub exp))
| (lbl, Omitted o) -> (lbl, Omitted o))
args
)
| Tcl_let (rec_flag, value_bindings, ivars, cl) ->
let (rec_flag, value_bindings) =
sub.value_bindings sub (rec_flag, value_bindings)
in
Tcl_let (
rec_flag,
value_bindings,
List.map (tuple2 id (sub.expr sub)) ivars,
sub.class_expr sub cl
)
| Tcl_ident (path, lid, tyl) ->
Tcl_ident (path, lid, List.map (sub.typ sub) tyl)
| Tcl_open (od, e) ->
Tcl_open (sub.open_description sub od, sub.class_expr sub e)
in
{x with cl_desc; cl_env}
let class_type sub x =
let cltyp_env = sub.env sub x.cltyp_env in
let cltyp_desc =
match x.cltyp_desc with
| Tcty_signature csg -> Tcty_signature (sub.class_signature sub csg)
| Tcty_constr (path, lid, list) ->
Tcty_constr (
path,
lid,
List.map (sub.typ sub) list
)
| Tcty_arrow (label, ct, cl) ->
Tcty_arrow
(label,
sub.typ sub ct,
sub.class_type sub cl
)
| Tcty_open (od, e) ->
Tcty_open (sub.open_description sub od, sub.class_type sub e)
in
{x with cltyp_desc; cltyp_env}
let class_signature sub x =
let csig_self = sub.typ sub x.csig_self in
let csig_fields = List.map (sub.class_type_field sub) x.csig_fields in
{x with csig_self; csig_fields}
let class_type_field sub x =
let ctf_desc =
match x.ctf_desc with
| Tctf_inherit ct ->
Tctf_inherit (sub.class_type sub ct)
| Tctf_val (s, mut, virt, ct) ->
Tctf_val (s, mut, virt, sub.typ sub ct)
| Tctf_method (s, priv, virt, ct) ->
Tctf_method (s, priv, virt, sub.typ sub ct)
| Tctf_constraint (ct1, ct2) ->
Tctf_constraint (sub.typ sub ct1, sub.typ sub ct2)
| Tctf_attribute _ as d -> d
in
{x with ctf_desc}
let typ sub x =
let ctyp_env = sub.env sub x.ctyp_env in
let ctyp_desc =
match x.ctyp_desc with
| Ttyp_any
| Ttyp_var _ as d -> d
| Ttyp_arrow (label, ct1, ct2) ->
Ttyp_arrow (label, sub.typ sub ct1, sub.typ sub ct2)
| Ttyp_tuple list -> Ttyp_tuple (List.map (sub.typ sub) list)
| Ttyp_constr (path, lid, list) ->
Ttyp_constr (path, lid, List.map (sub.typ sub) list)
| Ttyp_object (list, closed) ->
Ttyp_object ((List.map (sub.object_field sub) list), closed)
| Ttyp_class (path, lid, list) ->
Ttyp_class
(path,
lid,
List.map (sub.typ sub) list
)
| Ttyp_alias (ct, s) ->
Ttyp_alias (sub.typ sub ct, s)
| Ttyp_variant (list, closed, labels) ->
Ttyp_variant (List.map (sub.row_field sub) list, closed, labels)
| Ttyp_poly (sl, ct) ->
Ttyp_poly (sl, sub.typ sub ct)
| Ttyp_package pack ->
Ttyp_package (sub.package_type sub pack)
in
{x with ctyp_desc; ctyp_env}
let class_structure sub x =
let cstr_self = sub.pat sub x.cstr_self in
let cstr_fields = List.map (sub.class_field sub) x.cstr_fields in
{x with cstr_self; cstr_fields}
let row_field sub x =
let rf_desc = match x.rf_desc with
| Ttag (label, b, list) ->
Ttag (label, b, List.map (sub.typ sub) list)
| Tinherit ct -> Tinherit (sub.typ sub ct)
in
{ x with rf_desc; }
let object_field sub x =
let of_desc = match x.of_desc with
| OTtag (label, ct) ->
OTtag (label, (sub.typ sub ct))
| OTinherit ct -> OTinherit (sub.typ sub ct)
in
{ x with of_desc; }
let class_field_kind sub = function
| Tcfk_virtual ct -> Tcfk_virtual (sub.typ sub ct)
| Tcfk_concrete (ovf, e) -> Tcfk_concrete (ovf, sub.expr sub e)
let class_field sub x =
let cf_desc =
match x.cf_desc with
| Tcf_inherit (ovf, cl, super, vals, meths) ->
Tcf_inherit (ovf, sub.class_expr sub cl, super, vals, meths)
| Tcf_constraint (cty, cty') ->
Tcf_constraint (
sub.typ sub cty,
sub.typ sub cty'
)
| Tcf_val (s, mf, id, k, b) ->
Tcf_val (s, mf, id, class_field_kind sub k, b)
| Tcf_method (s, priv, k) ->
Tcf_method (s, priv, class_field_kind sub k)
| Tcf_initializer exp ->
Tcf_initializer (sub.expr sub exp)
| Tcf_attribute _ as d -> d
in
{x with cf_desc}
let value_bindings sub (rec_flag, list) =
(rec_flag, List.map (sub.value_binding sub) list)
let case
: type k . mapper -> k case -> k case
= fun sub {c_lhs; c_guard; c_rhs} ->
{
c_lhs = sub.pat sub c_lhs;
c_guard = Option.map (sub.expr sub) c_guard;
c_rhs = sub.expr sub c_rhs;
}
let value_binding sub x =
let vb_pat = sub.pat sub x.vb_pat in
let vb_expr = sub.expr sub x.vb_expr in
{x with vb_pat; vb_expr}
let env _sub x = x
let default =
{
binding_op;
case;
class_declaration;
class_description;
class_expr;
class_field;
class_signature;
class_structure;
class_type;
class_type_declaration;
class_type_field;
env;
expr;
extension_constructor;
module_binding;
module_coercion;
module_declaration;
module_substitution;
module_expr;
module_type;
module_type_declaration;
package_type;
pat;
row_field;
object_field;
open_declaration;
open_description;
signature;
signature_item;
structure;
structure_item;
typ;
type_declaration;
type_declarations;
type_extension;
type_exception;
type_kind;
value_binding;
value_bindings;
value_description;
with_constraint;
}
|
7707ecb44c5f89f7896acb6c912ba9525070614bfec918685b951f13d0594a4d | evilmartians/foundry | local_inference.ml | open Unicode.Std
open Big_int
open ExtList
open Ssa
let name = "Local Inference"
let stvar () = Rt.Tvar (Rt.static_tvar ())
let int_binop_ty = (* val int_binop : 'a -> 'a -> 'a *)
let tv = stvar () in Rt.FunctionTy ([tv; tv], tv)
let int_cmpop_ty = (* val int_cmpop : 'a -> 'a -> bool *)
let tv = stvar () in Rt.FunctionTy ([tv; tv], Rt.BooleanTy)
let run_on_function passmgr capsule funcn =
let specialize ?reason env =
if env <> [] && Ssa.specialize funcn env then
Pass_manager.mark ?reason passmgr funcn
in
let local_var_ty frame name =
let rec lookup ty =
match Table.get ty.Rt.e_ty_bindings name with
| Some binding -> binding.Rt.b_ty
| None ->
match ty.Rt.e_ty_parent with
| Some ty -> lookup ty
| None -> assert false
in
match frame.ty with
| Rt.EnvironmentTy ty -> lookup ty
| _ -> assert false
in
let ty_before_inference = funcn.ty in
iter_instrs funcn ~f:(fun instr ->
let unify ty ty' =
try
specialize ~reason:("unified " ^ (Rt.inspect_type ty) ^
" and " ^ (Rt.inspect_type ty') ^
" for " ^ instr.id)
(Typing.unify ty ty');
with exn ->
Pass_manager.print_exn exn ("inferring on %" ^ instr.id)
in
match instr.opcode with
(* Make sure that call and return instruction types match the
signatures of their associated functions. *)
| ReturnInstr value
-> (let _, return_ty = func_ty funcn in
if not (Rt.equal value.ty return_ty) then
unify return_ty value.ty)
| CallInstr (callee, args)
-> (match callee.ty with
(* Call instruction does not necessarily point directly to
the function; it can be a function pointer. *)
| Rt.FunctionTy (args_ty', _)
-> (* Unify call site signature with callee signature. *)
(let args_ty = List.map (fun x -> x.ty) args in
let sig_ty = Rt.FunctionTy (args_ty, instr.ty) in
unify callee.ty sig_ty)
| _
-> ())
| ClosureInstr (callee, frame)
-> (match callee.ty, instr.ty with
| Rt.FunctionTy _, Rt.LambdaTy (arg_ty_elems, ret_ty)
-> (let arg_tys = Rt.tys_of_lambda_ty_elems arg_ty_elems in
let sig_ty = Rt.FunctionTy (frame.ty :: arg_tys, ret_ty) in
unify callee.ty sig_ty)
| _
-> ())
(* Local variable access. *)
| LVarLoadInstr (frame, name)
-> unify instr.ty (local_var_ty frame name)
| LVarStoreInstr (frame, name, value)
-> unify value.ty (local_var_ty frame name)
(* Instance variable access. *)
| IVarLoadInstr ({ ty = Rt.Class cls }, name)
-> unify instr.ty (Typing.slot_ty cls name)
| IVarStoreInstr ({ ty = Rt.Class cls }, name, value)
-> unify value.ty (Typing.slot_ty cls name)
(* Phi. *)
| PhiInstr incoming
-> (let tys = List.map (fun (_,value) -> value.ty) incoming in
let env = Typing.unify_list (instr.ty :: tys) in
specialize env)
(* Select. *)
| SelectInstr (cond, if_true, if_false)
-> (let env = Typing.unify_list ([instr.ty; if_true.ty; if_false.ty]) in
specialize env)
Tuples .
| TupleExtendInstr ({ ty = Rt.TupleTy xs }, operands)
-> (let operand_tys = List.map (fun x -> x.ty) operands in
let ty = Rt.TupleTy (xs @ operand_tys) in
unify instr.ty ty)
| TupleConcatInstr ({ ty = Rt.TupleTy xs }, { ty = Rt.TupleTy ys })
-> (let ty = Rt.TupleTy (xs @ ys) in
unify instr.ty ty)
Records .
| RecordExtendInstr ({ ty = Rt.RecordTy xs }, operands)
-> (try
let operands = Assoc.sorted (List.map (fun (key, value) ->
match key.opcode with
| Const (Rt.Symbol name) -> name, value.ty
| _ -> raise Exit)
operands)
in
let ty = Rt.RecordTy operands in
unify instr.ty ty
with Exit ->
())
| RecordConcatInstr ({ ty = Rt.RecordTy xs }, { ty = Rt.RecordTy ys })
-> (let ty = Rt.RecordTy (Assoc.merge xs ys) in
unify instr.ty ty)
(* Primitives obey simple, primitive-specific typing rules. *)
| PrimitiveInstr (prim, operands)
-> (let unify_int_op int_op_ty =
(* Unify actual type of this primitive invocation with
its polymorphic signature. *)
let ty =
match operands with
| [a; b] -> Rt.FunctionTy ([a.Ssa.ty; b.Ssa.ty], instr.Ssa.ty)
| _ -> assert false
in
let env = Typing.unify int_op_ty ty in
let ty' = Typing.subst env ty in
(* Verify that the substitution yields a valid primitive
signature, i.e. it is indeed an integer operation. *)
match ty' with
| Rt.FunctionTy([Rt.IntegerTy; _], _)
| Rt.FunctionTy([Rt.UnsignedTy(_); _], _)
| Rt.FunctionTy([Rt.SignedTy(_); _], _)
-> (* Only specialize if the unification produced substitutions
for the original function. As intop signatures are
polymorphic, they will always produce non-empty env's. *)
(if not (Rt.equal ty ty') then
specialize env)
| Rt.FunctionTy([Rt.Class(klass, _); _], _)
when klass == (!Rt.roots).Rt.kFixed
-> (if not (Rt.equal ty ty') then
specialize env)
| _
-> ()
in
match (prim :> latin1s) with
(* Debug primitive is polymorphic; it accepts any amount of
values of any kind. *)
| "debug"
-> unify instr.ty Rt.NilTy
(* Operands to integer primitives must have the
same integral type. *)
| "int_add" | "int_sub" | "int_mul" | "int_div" | "int_mod" | "int_exp"
| "int_and" | "int_or" | "int_xor" | "int_shl" | "int_shr"
-> unify_int_op int_binop_ty
| "int_eq" | "int_ne" | "int_le" | "int_lt" | "int_ge" | "int_gt"
-> unify_int_op int_cmpop_ty
(* Option primitives. *)
| "opt_alloc"
-> (match operands with
| [ { ty } ]
-> (let ty = Rt.OptionTy (ty) in
unify instr.ty ty)
| _
-> ())
| "opt_any"
-> unify instr.ty Rt.BooleanTy
| "opt_get"
-> (match operands with
| [ { ty = Rt.OptionTy (ty) } ]
-> unify instr.ty ty
| _
-> ())
(* Tuple and record primitives. *)
| "tup_lookup"
-> (match operands with
| [ { ty = Rt.TupleTy xs };
{ opcode = Const (Rt.Integer idx) } ]
-> (try
let ty = List.nth xs (int_of_big_int idx) in
unify instr.ty ty
with List.Invalid_index _ ->
())
| _
-> ())
| "tup_slice"
-> (match operands with
| [ { ty = Rt.TupleTy xs };
{ opcode = Const (Rt.Integer lft) };
{ opcode = Const (Rt.Integer rgt) } ]
-> (let lft = int_of_big_int lft
and rgt = int_of_big_int rgt in
let _, lft_slice = List.split_nth lft xs in
let rgt_slice, _ = List.split_nth (rgt - lft) lft_slice in
unify instr.ty (Rt.TupleTy rgt_slice))
| _
-> ())
| "rec_lookup"
-> (match operands with
| [ { ty = Rt.RecordTy xs };
{ opcode = Const (Rt.Symbol sym) } ]
-> (try
let ty = Assoc.find xs sym in
unify instr.ty ty
with Not_found ->
())
| _
-> ())
(* Object primitives. *)
| "obj_alloc"
-> (match operands with
| [klass]
-> (* The klass is not generally constant here; however, its type
is always known, and we can figure out the objectclass based
on metaclass. *)
(match klass.ty with
| Rt.Class ({ Rt.k_objectclass = None }, _)
-> (* Someone is trying to allocate a value, or a Class instance. *)
(failwith "obj_alloc: objectclass=None")
| Rt.Class ({ Rt.k_objectclass = Some klass }, specz')
-> unify instr.ty (Rt.Class (klass, specz'))
| _
-> ())
| _
-> ())
(* Memory access primitives. *)
| "mem_load" | "mem_loadv" | "mem_store" | "mem_storev"
-> (match operands with
| { ty = align_ty } :: { ty = addr_ty } :: _
-> (unify align_ty (Rt.UnsignedTy 32);
unify addr_ty (Rt.UnsignedTy 32);
if prim = "mem_store" || prim = "mem_storev" then
unify instr.ty Rt.NilTy
else
unify instr.ty (Rt.Class (!Rt.roots.Rt.kFixed, Assoc.sorted [
"width", Rt.tvar_as_ty ();
"signed", Rt.tvar_as_ty ();
])))
| _
-> assert false)
| _
-> ())
| _
-> ());
(* If the function never returns, change its signature to return nil. *)
let does_return = ref false in
iter_instrs funcn ~f:(fun instr ->
match instr.opcode with
| ReturnInstr _ -> does_return := true
| _ -> ());
if not !does_return then begin
let args_ty, _ = func_ty funcn in
set_ty funcn (Rt.FunctionTy (args_ty, Rt.NilTy))
end;
(* If function signature has changed, revisit all uses of this
function. *)
if not (Rt.equal funcn.ty ty_before_inference) then
iter_uses funcn ~f:(fun user ->
let funcn = block_parent (instr_parent user) in
Pass_manager.mark ~reason:"signature changed" passmgr funcn);
If operand types of any call instructions have changed , revisit
the callee . Here , a weaker version of the check is implemented :
if operand types are more specific than signature of any call
instruction , revisit the callee .
Note that this check is different from the one above : the former
aims to substitute type variables in caller ( this function ) function
with type information from callee , and the latter ( the check below )
aims to let the specialization pass decide if it wants to duplucate
the body .
the callee. Here, a weaker version of the check is implemented:
if operand types are more specific than signature of any call
instruction, revisit the callee.
Note that this check is different from the one above: the former
aims to substitute type variables in caller (this function) function
with type information from callee, and the latter (the check below)
aims to let the specialization pass decide if it wants to duplucate
the body.
*)
iter_instrs funcn ~f:(fun instr ->
match instr.opcode with
| CallInstr (callee, operands)
-> (match callee.opcode with
| Function _
-> (let args_ty = List.map (fun x -> x.ty) operands in
let sig_ty = Rt.FunctionTy (args_ty, instr.ty) in
let env = Typing.unify callee.ty sig_ty in
let sig_ty' = Typing.subst env callee.ty in
if not (Rt.equal sig_ty' callee.ty) then
Pass_manager.mark ~reason:"signature mismatch" passmgr callee)
| _
-> ())
| ClosureInstr (callee, frame)
-> (match callee.opcode, instr.ty with
| Function _, Rt.LambdaTy (arg_ty_elems, ret_ty)
-> (let arg_tys = Rt.tys_of_lambda_ty_elems arg_ty_elems in
let sig_ty = Rt.FunctionTy (frame.ty :: arg_tys, ret_ty) in
let env = Typing.unify callee.ty sig_ty in
let sig_ty' = Typing.subst env callee.ty in
if not (Rt.equal sig_ty' callee.ty) then
Pass_manager.mark ~reason:"signature mismatch" passmgr callee)
| _
-> ())
| _
-> ())
| null | https://raw.githubusercontent.com/evilmartians/foundry/ce947c7dcca79ab7a7ce25870e9fc0eb15e9c2bd/src/transforms/local_inference.ml | ocaml | val int_binop : 'a -> 'a -> 'a
val int_cmpop : 'a -> 'a -> bool
Make sure that call and return instruction types match the
signatures of their associated functions.
Call instruction does not necessarily point directly to
the function; it can be a function pointer.
Unify call site signature with callee signature.
Local variable access.
Instance variable access.
Phi.
Select.
Primitives obey simple, primitive-specific typing rules.
Unify actual type of this primitive invocation with
its polymorphic signature.
Verify that the substitution yields a valid primitive
signature, i.e. it is indeed an integer operation.
Only specialize if the unification produced substitutions
for the original function. As intop signatures are
polymorphic, they will always produce non-empty env's.
Debug primitive is polymorphic; it accepts any amount of
values of any kind.
Operands to integer primitives must have the
same integral type.
Option primitives.
Tuple and record primitives.
Object primitives.
The klass is not generally constant here; however, its type
is always known, and we can figure out the objectclass based
on metaclass.
Someone is trying to allocate a value, or a Class instance.
Memory access primitives.
If the function never returns, change its signature to return nil.
If function signature has changed, revisit all uses of this
function. | open Unicode.Std
open Big_int
open ExtList
open Ssa
let name = "Local Inference"
let stvar () = Rt.Tvar (Rt.static_tvar ())
let tv = stvar () in Rt.FunctionTy ([tv; tv], tv)
let tv = stvar () in Rt.FunctionTy ([tv; tv], Rt.BooleanTy)
let run_on_function passmgr capsule funcn =
let specialize ?reason env =
if env <> [] && Ssa.specialize funcn env then
Pass_manager.mark ?reason passmgr funcn
in
let local_var_ty frame name =
let rec lookup ty =
match Table.get ty.Rt.e_ty_bindings name with
| Some binding -> binding.Rt.b_ty
| None ->
match ty.Rt.e_ty_parent with
| Some ty -> lookup ty
| None -> assert false
in
match frame.ty with
| Rt.EnvironmentTy ty -> lookup ty
| _ -> assert false
in
let ty_before_inference = funcn.ty in
iter_instrs funcn ~f:(fun instr ->
let unify ty ty' =
try
specialize ~reason:("unified " ^ (Rt.inspect_type ty) ^
" and " ^ (Rt.inspect_type ty') ^
" for " ^ instr.id)
(Typing.unify ty ty');
with exn ->
Pass_manager.print_exn exn ("inferring on %" ^ instr.id)
in
match instr.opcode with
| ReturnInstr value
-> (let _, return_ty = func_ty funcn in
if not (Rt.equal value.ty return_ty) then
unify return_ty value.ty)
| CallInstr (callee, args)
-> (match callee.ty with
| Rt.FunctionTy (args_ty', _)
(let args_ty = List.map (fun x -> x.ty) args in
let sig_ty = Rt.FunctionTy (args_ty, instr.ty) in
unify callee.ty sig_ty)
| _
-> ())
| ClosureInstr (callee, frame)
-> (match callee.ty, instr.ty with
| Rt.FunctionTy _, Rt.LambdaTy (arg_ty_elems, ret_ty)
-> (let arg_tys = Rt.tys_of_lambda_ty_elems arg_ty_elems in
let sig_ty = Rt.FunctionTy (frame.ty :: arg_tys, ret_ty) in
unify callee.ty sig_ty)
| _
-> ())
| LVarLoadInstr (frame, name)
-> unify instr.ty (local_var_ty frame name)
| LVarStoreInstr (frame, name, value)
-> unify value.ty (local_var_ty frame name)
| IVarLoadInstr ({ ty = Rt.Class cls }, name)
-> unify instr.ty (Typing.slot_ty cls name)
| IVarStoreInstr ({ ty = Rt.Class cls }, name, value)
-> unify value.ty (Typing.slot_ty cls name)
| PhiInstr incoming
-> (let tys = List.map (fun (_,value) -> value.ty) incoming in
let env = Typing.unify_list (instr.ty :: tys) in
specialize env)
| SelectInstr (cond, if_true, if_false)
-> (let env = Typing.unify_list ([instr.ty; if_true.ty; if_false.ty]) in
specialize env)
Tuples .
| TupleExtendInstr ({ ty = Rt.TupleTy xs }, operands)
-> (let operand_tys = List.map (fun x -> x.ty) operands in
let ty = Rt.TupleTy (xs @ operand_tys) in
unify instr.ty ty)
| TupleConcatInstr ({ ty = Rt.TupleTy xs }, { ty = Rt.TupleTy ys })
-> (let ty = Rt.TupleTy (xs @ ys) in
unify instr.ty ty)
Records .
| RecordExtendInstr ({ ty = Rt.RecordTy xs }, operands)
-> (try
let operands = Assoc.sorted (List.map (fun (key, value) ->
match key.opcode with
| Const (Rt.Symbol name) -> name, value.ty
| _ -> raise Exit)
operands)
in
let ty = Rt.RecordTy operands in
unify instr.ty ty
with Exit ->
())
| RecordConcatInstr ({ ty = Rt.RecordTy xs }, { ty = Rt.RecordTy ys })
-> (let ty = Rt.RecordTy (Assoc.merge xs ys) in
unify instr.ty ty)
| PrimitiveInstr (prim, operands)
-> (let unify_int_op int_op_ty =
let ty =
match operands with
| [a; b] -> Rt.FunctionTy ([a.Ssa.ty; b.Ssa.ty], instr.Ssa.ty)
| _ -> assert false
in
let env = Typing.unify int_op_ty ty in
let ty' = Typing.subst env ty in
match ty' with
| Rt.FunctionTy([Rt.IntegerTy; _], _)
| Rt.FunctionTy([Rt.UnsignedTy(_); _], _)
| Rt.FunctionTy([Rt.SignedTy(_); _], _)
(if not (Rt.equal ty ty') then
specialize env)
| Rt.FunctionTy([Rt.Class(klass, _); _], _)
when klass == (!Rt.roots).Rt.kFixed
-> (if not (Rt.equal ty ty') then
specialize env)
| _
-> ()
in
match (prim :> latin1s) with
| "debug"
-> unify instr.ty Rt.NilTy
| "int_add" | "int_sub" | "int_mul" | "int_div" | "int_mod" | "int_exp"
| "int_and" | "int_or" | "int_xor" | "int_shl" | "int_shr"
-> unify_int_op int_binop_ty
| "int_eq" | "int_ne" | "int_le" | "int_lt" | "int_ge" | "int_gt"
-> unify_int_op int_cmpop_ty
| "opt_alloc"
-> (match operands with
| [ { ty } ]
-> (let ty = Rt.OptionTy (ty) in
unify instr.ty ty)
| _
-> ())
| "opt_any"
-> unify instr.ty Rt.BooleanTy
| "opt_get"
-> (match operands with
| [ { ty = Rt.OptionTy (ty) } ]
-> unify instr.ty ty
| _
-> ())
| "tup_lookup"
-> (match operands with
| [ { ty = Rt.TupleTy xs };
{ opcode = Const (Rt.Integer idx) } ]
-> (try
let ty = List.nth xs (int_of_big_int idx) in
unify instr.ty ty
with List.Invalid_index _ ->
())
| _
-> ())
| "tup_slice"
-> (match operands with
| [ { ty = Rt.TupleTy xs };
{ opcode = Const (Rt.Integer lft) };
{ opcode = Const (Rt.Integer rgt) } ]
-> (let lft = int_of_big_int lft
and rgt = int_of_big_int rgt in
let _, lft_slice = List.split_nth lft xs in
let rgt_slice, _ = List.split_nth (rgt - lft) lft_slice in
unify instr.ty (Rt.TupleTy rgt_slice))
| _
-> ())
| "rec_lookup"
-> (match operands with
| [ { ty = Rt.RecordTy xs };
{ opcode = Const (Rt.Symbol sym) } ]
-> (try
let ty = Assoc.find xs sym in
unify instr.ty ty
with Not_found ->
())
| _
-> ())
| "obj_alloc"
-> (match operands with
| [klass]
(match klass.ty with
| Rt.Class ({ Rt.k_objectclass = None }, _)
(failwith "obj_alloc: objectclass=None")
| Rt.Class ({ Rt.k_objectclass = Some klass }, specz')
-> unify instr.ty (Rt.Class (klass, specz'))
| _
-> ())
| _
-> ())
| "mem_load" | "mem_loadv" | "mem_store" | "mem_storev"
-> (match operands with
| { ty = align_ty } :: { ty = addr_ty } :: _
-> (unify align_ty (Rt.UnsignedTy 32);
unify addr_ty (Rt.UnsignedTy 32);
if prim = "mem_store" || prim = "mem_storev" then
unify instr.ty Rt.NilTy
else
unify instr.ty (Rt.Class (!Rt.roots.Rt.kFixed, Assoc.sorted [
"width", Rt.tvar_as_ty ();
"signed", Rt.tvar_as_ty ();
])))
| _
-> assert false)
| _
-> ())
| _
-> ());
let does_return = ref false in
iter_instrs funcn ~f:(fun instr ->
match instr.opcode with
| ReturnInstr _ -> does_return := true
| _ -> ());
if not !does_return then begin
let args_ty, _ = func_ty funcn in
set_ty funcn (Rt.FunctionTy (args_ty, Rt.NilTy))
end;
if not (Rt.equal funcn.ty ty_before_inference) then
iter_uses funcn ~f:(fun user ->
let funcn = block_parent (instr_parent user) in
Pass_manager.mark ~reason:"signature changed" passmgr funcn);
If operand types of any call instructions have changed , revisit
the callee . Here , a weaker version of the check is implemented :
if operand types are more specific than signature of any call
instruction , revisit the callee .
Note that this check is different from the one above : the former
aims to substitute type variables in caller ( this function ) function
with type information from callee , and the latter ( the check below )
aims to let the specialization pass decide if it wants to duplucate
the body .
the callee. Here, a weaker version of the check is implemented:
if operand types are more specific than signature of any call
instruction, revisit the callee.
Note that this check is different from the one above: the former
aims to substitute type variables in caller (this function) function
with type information from callee, and the latter (the check below)
aims to let the specialization pass decide if it wants to duplucate
the body.
*)
iter_instrs funcn ~f:(fun instr ->
match instr.opcode with
| CallInstr (callee, operands)
-> (match callee.opcode with
| Function _
-> (let args_ty = List.map (fun x -> x.ty) operands in
let sig_ty = Rt.FunctionTy (args_ty, instr.ty) in
let env = Typing.unify callee.ty sig_ty in
let sig_ty' = Typing.subst env callee.ty in
if not (Rt.equal sig_ty' callee.ty) then
Pass_manager.mark ~reason:"signature mismatch" passmgr callee)
| _
-> ())
| ClosureInstr (callee, frame)
-> (match callee.opcode, instr.ty with
| Function _, Rt.LambdaTy (arg_ty_elems, ret_ty)
-> (let arg_tys = Rt.tys_of_lambda_ty_elems arg_ty_elems in
let sig_ty = Rt.FunctionTy (frame.ty :: arg_tys, ret_ty) in
let env = Typing.unify callee.ty sig_ty in
let sig_ty' = Typing.subst env callee.ty in
if not (Rt.equal sig_ty' callee.ty) then
Pass_manager.mark ~reason:"signature mismatch" passmgr callee)
| _
-> ())
| _
-> ())
|
1bd907ae2039511b328ea18dd0388060183b249e2437cea1e9ecd1229a9fa3de | paurkedal/batyr | listener.ml | Copyright ( C ) 2022 < >
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
*)
include Batyr_core.Listener.Make (Batyr_on_xmpp.Listener)
| null | https://raw.githubusercontent.com/paurkedal/batyr/13aa15970a60286afbd887685a816fcd5fc4976e/batyr-on-xmpp/bin/listener.ml | ocaml | Copyright ( C ) 2022 < >
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
*)
include Batyr_core.Listener.Make (Batyr_on_xmpp.Listener)
| |
1e6b3474a8b41a343185d4805e0d05b882fae94c063d0a843b882180d03ccd39 | billstclair/trubanc-lisp | rfc2388.lisp | ;;;; -*- mode: LISP; package: RFC2388 -*-
Copyright ( c ) 2003
Modifications for TBNL Copyright ( c ) 2004 and Dr.
;;;;
;;;; Redistribution and use in source and binary forms, with or without
;;;; modification, are permitted provided that the following conditions
;;;; are met:
1 . Redistributions of source code must retain the above copyright
;;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;;; notice, this list of conditions and the following disclaimer in the
;;;; documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
;;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;;;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :rfc2388)
;;; Utility functions
(defun lwsp-char-p (char)
"Returns true if CHAR is a linear-whitespace-char (LWSP-char). Either
space or tab, in short."
(or (char= char #\space)
(char= char #\tab)))
;;; *** This actually belongs to RFC2046
;;;
(defun read-until-next-boundary (stream boundary &optional discard out-stream)
"Reads from STREAM up to the next boundary. Returns two values: read
data (nil if DISCARD is true), and true if the boundary is not last
(i.e., there's more data)."
;; Read until [CRLF]--boundary[--][transport-padding]CRLF
States : 1 2 345 67 8 9 10
;;
;; *** This will WARN like crazy on some bad input -- should only do each
;; warning once.
(let ((length (length boundary)))
(unless (<= 1 length 70)
(warn "Boundary has invalid length -- must be between 1 and 70, but is: ~S" length))
(when (lwsp-char-p (schar boundary (1- length)))
(warn "Boundary has trailing whitespace: ~S" boundary)))
(flet ((run (result)
"This one writes everything up to a boundary to RESULT stream,
and returns false if the closing delimiter has been read, and
true otherwise."
(let ((state 1)
(boundary-index 0)
(boundary-length (length boundary))
(closed nil)
(queued-chars (make-string 4))
(queue-index 0)
char
(leave-char nil))
(flet ((write-queued-chars ()
(dotimes (i queue-index)
(write-char (schar queued-chars i) result))
(setf queue-index 0))
(enqueue-char ()
(setf (schar queued-chars queue-index) char)
(incf queue-index)))
(loop
(if leave-char
(setq leave-char nil)
(setq char (read-char stream nil nil)))
(unless char
(setq closed t)
(return))
#-(and)
(format t "~&S:~D QI:~D BI:~2,'0D CH:~:[~;*~]~S~%"
state queue-index boundary-index leave-char char)
(case state
(1 ;; optional starting CR
(cond ((char= char #\return)
(enqueue-char)
(setq state 2))
((char= char #\-)
(setq leave-char t
state 3))
(t
(write-char char result))))
optional starting LF
(cond ((char= char #\linefeed)
(enqueue-char)
(setq state 3))
(t
(write-queued-chars)
(setq leave-char t
state 1))))
(3 ;; first dash in dash-boundary
(cond ((char= char #\-)
(enqueue-char)
(setq state 4))
(t
(write-queued-chars)
(setq leave-char t
state 1))))
second dash in dash - boundary
(cond ((char= char #\-)
(enqueue-char)
(setq state 5))
(t
(write-queued-chars)
(setq leave-char t
state 1))))
(5 ;; boundary
(cond ((char= char (schar boundary boundary-index))
(incf boundary-index)
(when (= boundary-index boundary-length)
(setq state 6)))
(t
(write-queued-chars)
(write-sequence boundary result :end boundary-index)
(setq boundary-index 0
leave-char t
state 1))))
(6 ;; first dash in close-delimiter
(cond ((char= char #\-)
(setq state 7))
(t
(setq leave-char t)
(setq state 8))))
second dash in close - delimiter
(cond ((char= char #\-)
(setq closed t
state 8))
(t
this is a strange situation -- only two dashes , linear
whitespace or CR is allowed after boundary , but there was
a single dash ... One thing is clear -- this is not a
;; close-delimiter. Hence this is garbage what we're looking
;; at!
(warn "Garbage where expecting close-delimiter!")
(setq leave-char t)
(setq state 8))))
transport - padding ( LWSP * = = [ # \space # \tab ] * )
(cond ((lwsp-char-p char)
;; ignore these
)
(t
(setq leave-char t)
(setq state 9))))
(9 ;; CR
(cond ((char= char #\return)
(setq state 10))
(t
(warn "Garbage where expecting CR!"))))
LF
(cond ((char= char #\linefeed)
;; the end
(return))
(t
(warn "Garbage where expecting LF!")))))))
(not closed))))
(if discard
(let ((stream (make-broadcast-stream)))
(values nil (run stream)))
(let* ((stream (or out-stream (make-string-output-stream)))
(closed (run stream)))
(values (or out-stream (get-output-stream-string stream))
closed)))))
(defun make-tmp-file-name ()
(if (find-package :tbnl)
(funcall (find-symbol "MAKE-TMP-FILE-NAME" :tbnl))
(error "WRITE-CONTENT-TO-FILE keyword argument to PARSE-MIME is supported in TBNL only at the moment.")))
;;; Header parsing
(defstruct (header (:type list)
(:constructor make-header (name value parameters)))
name
value
parameters)
(defun skip-linear-whitespace (string &key (start 0) end)
"Returns the position of first non-linear-whitespace character in STRING
bound by START and END."
(position-if-not #'lwsp-char-p string :start start :end end))
(defgeneric parse-header (source &optional start-state)
(:documentation "Parses SOURCE and returs a single MIME header.
Header is a list of the form (NAME VALUE PARAMETERS), PARAMETERS
is a list of (NAME . VALUE)"))
(defmethod parse-header ((source string) &optional (start-state :name))
(with-input-from-string (in source)
(parse-header in start-state)))
;;; *** I don't like this parser -- it will have to be rewritten when I
;;; make my state-machine parser-generator macro!
;;;
(defmethod parse-header ((stream stream) &optional (start-state :name))
"Returns a MIME part header, or NIL, if there is no header. Header is
terminated by CRLF."
(let ((state (ecase start-state
(:name 1)
(:value 2)
(:parameters 3)))
(result (make-string-output-stream))
char
(leave-char nil)
name
value
parameter-name
parameters)
(labels ((skip-lwsp (next-state)
(loop
do (setq char (read-char stream nil nil))
while (and char (lwsp-char-p char)))
(setq leave-char t
state next-state))
(collect-parameter ()
(push (cons parameter-name
(get-output-stream-string result))
parameters)
(setq parameter-name nil)
(skip-lwsp 3))
(token-end-char-p (char)
(or (char= char #\;)
(lwsp-char-p char))))
(loop
(if leave-char
(setq leave-char nil)
(setq char (read-char stream nil nil)))
;; end of stream
(unless char
(return))
(when (char= #\return char)
(setq char (read-char stream nil nil))
(cond ((or (null char)
(char= #\linefeed char))
;; CRLF ends the input
(return))
(t
(warn "LINEFEED without RETURN in header.")
(write-char #\return result)
(setq leave-char t))))
#-(and)
(format t "~&S:~,'0D CH:~:[~;*~]~S~%"
state leave-char char)
(ecase state
(1 ;; NAME
(cond ((char= char #\:)
;; end of name
(setq name (get-output-stream-string result))
(skip-lwsp 2))
(t
(write-char char result))))
(2 ;; VALUE
(cond ((token-end-char-p char)
(setq value (get-output-stream-string result))
(skip-lwsp 3))
(t
(write-char char result))))
PARAMETER name
(cond ((char= #\= char)
(setq parameter-name (get-output-stream-string result)
state 4))
(t
(write-char char result))))
PARAMETER value start
(cond ((char= #\" char)
(setq state 5))
(t
(setq leave-char t
state 7))))
(5 ;; Quoted PARAMETER value
(cond ((char= #\" char)
(setq state 6))
(t
(write-char char result))))
End of quoted PARAMETER value
(cond ((token-end-char-p char)
(collect-parameter))
(t
;; no space or semicolon after quoted parameter value
(setq leave-char t
state 3))))
Unquoted PARAMETER value
(cond ((token-end-char-p char)
(collect-parameter))
(t
(write-char char result))))))
(case state
(1
(setq name (get-output-stream-string result)))
(2
(setq value (get-output-stream-string result)))
((3 4)
(let ((name (get-output-stream-string result)))
(unless (zerop (length name))
(warn "Parameter without value in header.")
(push (cons name nil) parameters))))
((5 6 7)
(push (cons parameter-name (get-output-stream-string result)) parameters))))
(if (and (or (null name)
(zerop (length name)))
(null value)
(null parameters))
nil
(make-header name value parameters))))
;;; _The_ MIME parsing
(defgeneric parse-mime (source boundary &key recursive-p write-content-to-file)
(:documentation
"Parses MIME entities, returning them as a list. Each element in the
list is of form: (body headers), where BODY is the contents of MIME
part, and HEADERS are all headers for that part. BOUNDARY is a string
used to separate MIME entities."))
(defstruct (content-type (:type list)
(:constructor make-content-type (super sub)))
super
sub)
(defun parse-content-type (string)
"Returns content-type which is parsed from STRING."
(let ((sep-offset (position #\/ string))
(type (array-element-type string)))
(if (numberp sep-offset)
(make-content-type (make-array sep-offset
:element-type type
:displaced-to string)
(make-array (- (length string) (incf sep-offset))
:element-type type
:displaced-to string
:displaced-index-offset sep-offset))
(make-content-type string nil))))
(defun unparse-content-type (ct)
"Returns content-type CT in string representation."
(let ((super (content-type-super ct))
(sub (content-type-sub ct)))
(cond ((and super sub)
(concatenate 'string super "/" sub))
(t (or super "")))))
(defstruct (mime-part (:type list)
(:constructor make-mime-part (contents headers)))
contents
headers)
(defmethod parse-mime ((input string) separator &key (recursive-p t) (write-content-to-file t))
(with-input-from-string (stream input)
(parse-mime stream separator :recursive-p recursive-p :write-content-to-file write-content-to-file)))
(defmethod parse-mime ((input stream) boundary &key (recursive-p t) (write-content-to-file t))
Find the first boundary . Return immediately if it is also the last
;; one.
(unless (nth-value 1 (read-until-next-boundary input boundary t))
(return-from parse-mime nil))
(let ((result ())
content-type-header)
(loop
(let ((headers (loop
for header = (parse-header input)
while header
when (string-equal "CONTENT-TYPE" (header-name header))
do (setf content-type-header header
(header-value header) (parse-content-type (header-value header)))
collect header)))
(if (and recursive-p
(string-equal "MULTIPART" (content-type-super (header-value content-type-header))))
(let ((boundary (cdr (find-parameter "BOUNDARY" (header-parameters content-type-header)))))
(push (make-mime-part (parse-mime input boundary) headers) result))
(let ((file-name (get-file-name headers)))
(cond ((and write-content-to-file
file-name)
(let ((temp-file (make-tmp-file-name)))
(multiple-value-bind (text more)
(with-open-file (out-file (ensure-directories-exist temp-file)
:direction :output
;; external format for faithful I/O
;; see <-cookbook.sourceforge.net/io.html#faith>
#+(or :sbcl :lispworks :allegro)
:external-format
#+sbcl :latin-1
#+:lispworks '(:latin-1 :eol-style :lf)
#+:allegro (excl:crlf-base-ef :latin1))
(read-until-next-boundary input boundary nil out-file))
(declare (ignore text))
(when (and (stringp file-name)
(plusp (length file-name)))
(push (make-mime-part temp-file headers) result))
(when (not more)
(return)))))
(t
(multiple-value-bind (text more)
(read-until-next-boundary input boundary)
(push (make-mime-part text headers) result)
(when (not more)
(return)))))))))
(nreverse result)))
(defun find-header (label headers)
"Find header by label from set of headers."
(find label headers :key #'rfc2388:header-name :test #'string-equal))
(defun find-parameter (name params)
"Find header parameter by name from set of parameters."
(assoc name params :test #'string-equal))
(defun content-type (part &key as-string)
"Returns the Content-Type header of mime-part PART."
(let ((header (find-header "CONTENT-TYPE" (mime-part-headers part))))
(if header
(if as-string
(or (unparse-content-type (header-value header)) "")
(header-value header))
(when as-string ""))))
(defun find-content-disposition-header (headers)
(find-if (lambda (header)
(and (string-equal "CONTENT-DISPOSITION"
(rfc2388:header-name header))
(string-equal "FORM-DATA"
(rfc2388:header-value header))))
headers))
(defun get-file-name (headers)
(cdr (find-parameter "FILENAME"
(header-parameters (find-content-disposition-header headers)))))
| null | https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/rfc2388/rfc2388.lisp | lisp | -*- mode: LISP; package: RFC2388 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Utility functions
*** This actually belongs to RFC2046
Read until [CRLF]--boundary[--][transport-padding]CRLF
*** This will WARN like crazy on some bad input -- should only do each
warning once.
optional starting CR
first dash in dash-boundary
boundary
first dash in close-delimiter
close-delimiter. Hence this is garbage what we're looking
at!
ignore these
CR
the end
Header parsing
*** I don't like this parser -- it will have to be rewritten when I
make my state-machine parser-generator macro!
)
end of stream
CRLF ends the input
NAME
end of name
VALUE
Quoted PARAMETER value
no space or semicolon after quoted parameter value
_The_ MIME parsing
one.
external format for faithful I/O
see <-cookbook.sourceforge.net/io.html#faith> | Copyright ( c ) 2003
Modifications for TBNL Copyright ( c ) 2004 and Dr.
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(in-package :rfc2388)
(defun lwsp-char-p (char)
"Returns true if CHAR is a linear-whitespace-char (LWSP-char). Either
space or tab, in short."
(or (char= char #\space)
(char= char #\tab)))
(defun read-until-next-boundary (stream boundary &optional discard out-stream)
"Reads from STREAM up to the next boundary. Returns two values: read
data (nil if DISCARD is true), and true if the boundary is not last
(i.e., there's more data)."
States : 1 2 345 67 8 9 10
(let ((length (length boundary)))
(unless (<= 1 length 70)
(warn "Boundary has invalid length -- must be between 1 and 70, but is: ~S" length))
(when (lwsp-char-p (schar boundary (1- length)))
(warn "Boundary has trailing whitespace: ~S" boundary)))
(flet ((run (result)
"This one writes everything up to a boundary to RESULT stream,
and returns false if the closing delimiter has been read, and
true otherwise."
(let ((state 1)
(boundary-index 0)
(boundary-length (length boundary))
(closed nil)
(queued-chars (make-string 4))
(queue-index 0)
char
(leave-char nil))
(flet ((write-queued-chars ()
(dotimes (i queue-index)
(write-char (schar queued-chars i) result))
(setf queue-index 0))
(enqueue-char ()
(setf (schar queued-chars queue-index) char)
(incf queue-index)))
(loop
(if leave-char
(setq leave-char nil)
(setq char (read-char stream nil nil)))
(unless char
(setq closed t)
(return))
#-(and)
(format t "~&S:~D QI:~D BI:~2,'0D CH:~:[~;*~]~S~%"
state queue-index boundary-index leave-char char)
(case state
(cond ((char= char #\return)
(enqueue-char)
(setq state 2))
((char= char #\-)
(setq leave-char t
state 3))
(t
(write-char char result))))
optional starting LF
(cond ((char= char #\linefeed)
(enqueue-char)
(setq state 3))
(t
(write-queued-chars)
(setq leave-char t
state 1))))
(cond ((char= char #\-)
(enqueue-char)
(setq state 4))
(t
(write-queued-chars)
(setq leave-char t
state 1))))
second dash in dash - boundary
(cond ((char= char #\-)
(enqueue-char)
(setq state 5))
(t
(write-queued-chars)
(setq leave-char t
state 1))))
(cond ((char= char (schar boundary boundary-index))
(incf boundary-index)
(when (= boundary-index boundary-length)
(setq state 6)))
(t
(write-queued-chars)
(write-sequence boundary result :end boundary-index)
(setq boundary-index 0
leave-char t
state 1))))
(cond ((char= char #\-)
(setq state 7))
(t
(setq leave-char t)
(setq state 8))))
second dash in close - delimiter
(cond ((char= char #\-)
(setq closed t
state 8))
(t
this is a strange situation -- only two dashes , linear
whitespace or CR is allowed after boundary , but there was
a single dash ... One thing is clear -- this is not a
(warn "Garbage where expecting close-delimiter!")
(setq leave-char t)
(setq state 8))))
transport - padding ( LWSP * = = [ # \space # \tab ] * )
(cond ((lwsp-char-p char)
)
(t
(setq leave-char t)
(setq state 9))))
(cond ((char= char #\return)
(setq state 10))
(t
(warn "Garbage where expecting CR!"))))
LF
(cond ((char= char #\linefeed)
(return))
(t
(warn "Garbage where expecting LF!")))))))
(not closed))))
(if discard
(let ((stream (make-broadcast-stream)))
(values nil (run stream)))
(let* ((stream (or out-stream (make-string-output-stream)))
(closed (run stream)))
(values (or out-stream (get-output-stream-string stream))
closed)))))
(defun make-tmp-file-name ()
(if (find-package :tbnl)
(funcall (find-symbol "MAKE-TMP-FILE-NAME" :tbnl))
(error "WRITE-CONTENT-TO-FILE keyword argument to PARSE-MIME is supported in TBNL only at the moment.")))
(defstruct (header (:type list)
(:constructor make-header (name value parameters)))
name
value
parameters)
(defun skip-linear-whitespace (string &key (start 0) end)
"Returns the position of first non-linear-whitespace character in STRING
bound by START and END."
(position-if-not #'lwsp-char-p string :start start :end end))
(defgeneric parse-header (source &optional start-state)
(:documentation "Parses SOURCE and returs a single MIME header.
Header is a list of the form (NAME VALUE PARAMETERS), PARAMETERS
is a list of (NAME . VALUE)"))
(defmethod parse-header ((source string) &optional (start-state :name))
(with-input-from-string (in source)
(parse-header in start-state)))
(defmethod parse-header ((stream stream) &optional (start-state :name))
"Returns a MIME part header, or NIL, if there is no header. Header is
terminated by CRLF."
(let ((state (ecase start-state
(:name 1)
(:value 2)
(:parameters 3)))
(result (make-string-output-stream))
char
(leave-char nil)
name
value
parameter-name
parameters)
(labels ((skip-lwsp (next-state)
(loop
do (setq char (read-char stream nil nil))
while (and char (lwsp-char-p char)))
(setq leave-char t
state next-state))
(collect-parameter ()
(push (cons parameter-name
(get-output-stream-string result))
parameters)
(setq parameter-name nil)
(skip-lwsp 3))
(token-end-char-p (char)
(lwsp-char-p char))))
(loop
(if leave-char
(setq leave-char nil)
(setq char (read-char stream nil nil)))
(unless char
(return))
(when (char= #\return char)
(setq char (read-char stream nil nil))
(cond ((or (null char)
(char= #\linefeed char))
(return))
(t
(warn "LINEFEED without RETURN in header.")
(write-char #\return result)
(setq leave-char t))))
#-(and)
(format t "~&S:~,'0D CH:~:[~;*~]~S~%"
state leave-char char)
(ecase state
(cond ((char= char #\:)
(setq name (get-output-stream-string result))
(skip-lwsp 2))
(t
(write-char char result))))
(cond ((token-end-char-p char)
(setq value (get-output-stream-string result))
(skip-lwsp 3))
(t
(write-char char result))))
PARAMETER name
(cond ((char= #\= char)
(setq parameter-name (get-output-stream-string result)
state 4))
(t
(write-char char result))))
PARAMETER value start
(cond ((char= #\" char)
(setq state 5))
(t
(setq leave-char t
state 7))))
(cond ((char= #\" char)
(setq state 6))
(t
(write-char char result))))
End of quoted PARAMETER value
(cond ((token-end-char-p char)
(collect-parameter))
(t
(setq leave-char t
state 3))))
Unquoted PARAMETER value
(cond ((token-end-char-p char)
(collect-parameter))
(t
(write-char char result))))))
(case state
(1
(setq name (get-output-stream-string result)))
(2
(setq value (get-output-stream-string result)))
((3 4)
(let ((name (get-output-stream-string result)))
(unless (zerop (length name))
(warn "Parameter without value in header.")
(push (cons name nil) parameters))))
((5 6 7)
(push (cons parameter-name (get-output-stream-string result)) parameters))))
(if (and (or (null name)
(zerop (length name)))
(null value)
(null parameters))
nil
(make-header name value parameters))))
(defgeneric parse-mime (source boundary &key recursive-p write-content-to-file)
(:documentation
"Parses MIME entities, returning them as a list. Each element in the
list is of form: (body headers), where BODY is the contents of MIME
part, and HEADERS are all headers for that part. BOUNDARY is a string
used to separate MIME entities."))
(defstruct (content-type (:type list)
(:constructor make-content-type (super sub)))
super
sub)
(defun parse-content-type (string)
"Returns content-type which is parsed from STRING."
(let ((sep-offset (position #\/ string))
(type (array-element-type string)))
(if (numberp sep-offset)
(make-content-type (make-array sep-offset
:element-type type
:displaced-to string)
(make-array (- (length string) (incf sep-offset))
:element-type type
:displaced-to string
:displaced-index-offset sep-offset))
(make-content-type string nil))))
(defun unparse-content-type (ct)
"Returns content-type CT in string representation."
(let ((super (content-type-super ct))
(sub (content-type-sub ct)))
(cond ((and super sub)
(concatenate 'string super "/" sub))
(t (or super "")))))
(defstruct (mime-part (:type list)
(:constructor make-mime-part (contents headers)))
contents
headers)
(defmethod parse-mime ((input string) separator &key (recursive-p t) (write-content-to-file t))
(with-input-from-string (stream input)
(parse-mime stream separator :recursive-p recursive-p :write-content-to-file write-content-to-file)))
(defmethod parse-mime ((input stream) boundary &key (recursive-p t) (write-content-to-file t))
Find the first boundary . Return immediately if it is also the last
(unless (nth-value 1 (read-until-next-boundary input boundary t))
(return-from parse-mime nil))
(let ((result ())
content-type-header)
(loop
(let ((headers (loop
for header = (parse-header input)
while header
when (string-equal "CONTENT-TYPE" (header-name header))
do (setf content-type-header header
(header-value header) (parse-content-type (header-value header)))
collect header)))
(if (and recursive-p
(string-equal "MULTIPART" (content-type-super (header-value content-type-header))))
(let ((boundary (cdr (find-parameter "BOUNDARY" (header-parameters content-type-header)))))
(push (make-mime-part (parse-mime input boundary) headers) result))
(let ((file-name (get-file-name headers)))
(cond ((and write-content-to-file
file-name)
(let ((temp-file (make-tmp-file-name)))
(multiple-value-bind (text more)
(with-open-file (out-file (ensure-directories-exist temp-file)
:direction :output
#+(or :sbcl :lispworks :allegro)
:external-format
#+sbcl :latin-1
#+:lispworks '(:latin-1 :eol-style :lf)
#+:allegro (excl:crlf-base-ef :latin1))
(read-until-next-boundary input boundary nil out-file))
(declare (ignore text))
(when (and (stringp file-name)
(plusp (length file-name)))
(push (make-mime-part temp-file headers) result))
(when (not more)
(return)))))
(t
(multiple-value-bind (text more)
(read-until-next-boundary input boundary)
(push (make-mime-part text headers) result)
(when (not more)
(return)))))))))
(nreverse result)))
(defun find-header (label headers)
"Find header by label from set of headers."
(find label headers :key #'rfc2388:header-name :test #'string-equal))
(defun find-parameter (name params)
"Find header parameter by name from set of parameters."
(assoc name params :test #'string-equal))
(defun content-type (part &key as-string)
"Returns the Content-Type header of mime-part PART."
(let ((header (find-header "CONTENT-TYPE" (mime-part-headers part))))
(if header
(if as-string
(or (unparse-content-type (header-value header)) "")
(header-value header))
(when as-string ""))))
(defun find-content-disposition-header (headers)
(find-if (lambda (header)
(and (string-equal "CONTENT-DISPOSITION"
(rfc2388:header-name header))
(string-equal "FORM-DATA"
(rfc2388:header-value header))))
headers))
(defun get-file-name (headers)
(cdr (find-parameter "FILENAME"
(header-parameters (find-content-disposition-header headers)))))
|
31b69db8b5b35865d82cbaa55403cf6e614c4692045b34b739349c00c3581a49 | korya/efuns | utils.ml | (***********************************************************************)
(* *)
xlib for
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
(*
Useful functions.
*)
let count_char_sub str pos len char =
let pos_end = pos + len in
let rec occur pos n =
if pos = pos_end then (n, 0) else
let next_pos =
try
String.index_from str pos char
with
Not_found -> -1
in
if next_pos = -1 || next_pos >= pos_end then (n,pos_end - pos) else
occur (next_pos + 1) (n + 1)
in
occur pos 0
let count_char str char =
let len = String.length str in
count_char_sub str 0 len char
let rec list_nth n list =
match n, list with
0, (ele :: _) -> ele
| _, [] -> raise Not_found
| _, (_:: tail) -> list_nth (n-1) tail
let rec mem_assq x = function
| [] -> false
| (a, b) :: l -> a == x || mem_assq x l
let rec removeq x = function
| [] -> []
| (a, b as pair) :: l -> if a == x then l else pair :: removeq x l
let rec list_removeq list ele =
match list with
e :: tail when e == ele -> list_removeq tail ele
| e :: tail -> e :: (list_removeq tail ele)
| _ -> []
let remove_assocq ele list =
List.fold_left (fun list ((e,_) as head) ->
if e == ele then list
else head :: list) [] list
let list_remove list ele =
List.fold_left (fun list e ->
if e = ele then list
else e :: list) [] list
let remove_assoc ele list =
List.fold_left (fun list ((e,_) as head) ->
if e = ele then list
else head :: list) [] list
let rec name =
if is_relative name then
longname " " ( name )
else
let tokens = decomp name in
let rec iter longname tokens =
match tokens with
[ ] - > " "
| [
let len = String.length name in
let rec iter i n =
if i+n+1 > = len || name.[i+n ] = ' / ' then
if i+n+1 > = len then
String.sub name i n
else
( String.sub name i ( n-1 )
in
iter 0 0
let curdirname name =
let rec
let rec longname dirname name =
if is_relative name then
longname "" (Filename.concat dirname name)
else
let tokens = decomp name in
let rec iter longname tokens =
match tokens with
[] -> ""
| [
let len = String.length name in
let rec iter i n =
if i+n+1 >= len || name.[i+n] = '/' then
if i+n+1 >= len then
String.sub name i n
else
(String.sub name i (n-1)
in
iter 0 0
let longname curdirname name =
let rec
*)
let file_list dirname =
try
let dir = Unix.opendir dirname in
let rec iter list =
try
let file = Unix.readdir dir in
iter (file :: list)
with
_ -> list
in
let list = iter [] in
Unix.closedir dir;
list
with
_ -> []
let string_ncmp s1 s2 n =
let sz1 = String.length s1 in
let sz2 = String.length s2 in
if sz1 < n || sz2 < n then s1 = s2
else
let s1' = String.sub s1 0 n in
let s2' = String.sub s2 0 n in
s1' = s2'
let completion list start =
let n = String.length start in
if n = 0 then list else
List.fold_left (fun list s ->
if string_ncmp start s n then
s :: list
else
list
) [] list
let common_suffix list start =
let newlist = completion list start in
let lenl = List.length newlist in
let len = String.length start in
match newlist with
[] -> "",0
| ele :: tail ->
let lenele = String.length ele in
if tail = [] then
String.sub ele len (lenele - len),1
else
let maxlen = List.fold_left (fun len e -> min len (String.length e))
lenele tail in
let suffix = ref "" in
try
for i = len to maxlen - 1 do
let c = ele.[i] in
List.iter (fun e -> if not (e.[i] == c) then raise Exit) tail;
suffix := !suffix ^ (String.make 1 c)
done;
raise Exit
with
_ -> !suffix, lenl
let read_string inc =
let len = in_channel_length inc in
let str = String.create len in
let curs = ref 0 in
let left = ref len in
try
while !left > 0 do
let read = input inc str !curs !left in
if read = 0 then raise End_of_file;
left := !left - read;
curs := !curs + read;
done;
str
with
End_of_file ->
String.sub str 0 !curs
let list_of_hash t =
let l = ref [] in
Hashtbl.iter (fun key ele -> l := (key,ele) :: !l) t;
!l
let find_in_path path name =
if not (Filename.is_implicit name) then
if Sys.file_exists name then name else raise Not_found
else begin
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
end
let string_to_path str =
let len = String.length str in
let rec iter start pos =
if pos >= len then
[String.sub str start (len - start)]
else
if str.[pos] = ' ' || str.[pos] = ':' then
(String.sub str start (pos - start)) :: (iter (pos+1) (pos+1))
else
iter start (pos+1)
in
iter 0 0
let path_to_string path =
let s = List.fold_left (fun str dir -> str ^ ":" ^ dir) "" path in
if String.length s > 0 then
let len = String.length s in
String.sub s 1 (len-1)
else ""
let hash_add_assoc hash list =
List.iter (fun (abbrev, repl) -> Hashtbl.add hash abbrev repl) list
(* Simplify a filename before printing it *)
let user =
try
Sys.getenv "USER"
with
Not_found -> ""
let homedir =
try
Sys.getenv "HOME"
with
Not_found -> ""
let known_dirs = ref [ homedir,"~"]
let check_prefix filename prefix =
let len = String.length prefix in
let n = String.length filename - len in
if n < 0 then raise Not_found;
for i = 0 to len-1 do
if filename.[i] <> prefix.[i] then raise Not_found
done;
String.sub filename len n
let replace_prefix filename prefixes =
List.fold_left (fun filename (dir,repl) ->
try
let fin = check_prefix filename dir in
repl ^ fin
with
Not_found -> filename) filename prefixes
let filename_to_string filename =
(* replace known dirs by ~ *)
replace_prefix filename !known_dirs
let string_to_filename filename =
replace known ~ by
replace_prefix filename (List.map (fun (a,b) -> b,a) !known_dirs)
let exns = ref []
let register_exn f = exns := f :: !exns
let printexn exn =
let rec iter exns =
match exns with
[] -> Printexc.to_string exn
| f :: tail ->
try f exn with
_ -> iter tail
in
iter !exns
let catchexn s f =
try f () with
e ->
Printf.printf "Uncaught exception in %s: %s" s (printexn e);
print_newline ()
let vcatchexn s f =
try Some (f ()) with
e ->
Printf.printf "Uncaught exception in %s: %s" s (printexn e);
print_newline ();
None
let set_signal sig_num sig_beh =
let _ = Sys.signal sig_num sig_beh in ()
let format_to_string action arg =
let string = ref "" in
let (p,f) = Format.get_formatter_output_functions () in
Format.set_formatter_output_functions
(fun str pos len ->
let s = String.sub str pos len in
string := !string ^ s)
(fun () -> ());
try
action arg;
Format.print_flush ();
Format.set_formatter_output_functions p f;
!string
with
e ->
Format.print_flush ();
Format.set_formatter_output_functions p f;
raise e
let do_and_format action arg =
let string = ref "" in
let (p,f) = Format.get_formatter_output_functions () in
Format.set_formatter_output_functions
(fun str pos len ->
let s = String.sub str pos len in
string := !string ^ s)
(fun () -> ());
try
let v = action arg in
Format.print_flush ();
Format.set_formatter_output_functions p f;
!string, v
with
e ->
Format.print_flush ();
Format.set_formatter_output_functions p f;
raise e
let format_to_string action arg =
fst (do_and_format action arg)
open Unix
let is_directory filename =
try let s = Unix.stat filename in s.st_kind = S_DIR with _ -> false
let is_link filename =
try let s = Unix.lstat filename in s.st_kind = S_LNK with _ -> false
let list_dir filename =
let dir = opendir filename in
let list = ref [] in
try
while true do
list := (readdir dir) :: !list
done;
assert false
with _ ->
closedir dir;
!list
let load_directory filename =
let today = localtime (time ()) in
let s = Printf.sprintf "Directory %s :\n" filename in
let list = list_dir filename in
List.fold_left (fun s entry ->
let fullname = Filename.concat filename entry in
let stats = lstat fullname in
let perm = stats.st_perm in
let rights = String.create 10 in
rights.[9] <- (if perm land 1 = 0 then '-' else
if perm land 2048 = 0 then 'x' else 's');
rights.[8] <- (if perm land 2 = 0 then '-' else 'w');
rights.[7] <- (if perm land 4 = 0 then '-' else 'r');
rights.[6] <- (if perm land 8 = 0 then '-' else
if perm land 1024 = 0 then 'x' else 's');
rights.[5] <- (if perm land 16 = 0 then '-' else 'w');
rights.[4] <- (if perm land 32 = 0 then '-' else 'r');
rights.[3] <- (if perm land 64 = 0 then '-' else
if perm land 512 = 0 then 'x' else 's');
rights.[2] <- (if perm land 128 = 0 then '-' else 'w');
rights.[1] <- (if perm land 256 = 0 then '-' else 'r');
rights.[0] <- (match stats.st_kind with
S_DIR -> 'd'
| S_CHR -> 'c'
| S_BLK -> 'b'
| S_REG -> '-'
| S_LNK -> 'l'
| S_FIFO -> 'f'
| S_SOCK -> 's'
);
let time = stats.st_mtime in
let time = localtime time in
let date =
Printf.sprintf "%3s %2d %5s"
(match time.tm_mon with
0 -> "Jan"
| 1 -> "Feb"
| 2 -> "Mar"
| 3 -> "Apr"
| 4 -> "May"
| 5 -> "Jun"
| 6 -> "Jul"
| 7 -> "Aug"
| 8 -> "Sep"
| 9 -> "Oct"
| 10 -> "Nov"
| 11 -> "Dec"
| _ -> "???")
time.tm_mday
(if today.tm_year = time.tm_year then
Printf.sprintf "%02d:%02d"
time.tm_hour time.tm_min
else
Printf.sprintf " %4d" (time.tm_year + 1900)
)
in
let owner = stats.st_uid in
let owner = try (getpwuid owner).pw_name
with _ -> string_of_int owner in
let group = stats.st_gid in
let group = try (getgrgid group).gr_name
with _ -> string_of_int group in
let size = stats.st_size in
Printf.sprintf "%s %s %8s %8s %8d %s %s%s\n"
s rights owner group size date entry
(if is_link fullname then
Printf.sprintf " -> %s"
(try Unix.readlink fullname with _ -> "???") else "")
) s (Sort.list (<) list)
(* This function format filenames so that directory names end with / *)
let normal_name curdir filename =
let fullname =
if Filename.is_relative filename then
Filename.concat curdir filename
else
filename
in
let rec iter name list level =
let b = Filename.basename name in
let d = Filename.dirname name in
if b = "." || b = "" then
if d = "/" || d = "." then list else
iter d list level else
if b = ".." then iter d list (level+1) else
if b = "/" then list else
if level > 0 then iter d list (level-1) else
iter d (b :: list) 0
in
let list = iter fullname [] 0 in
match list with
[] -> "/"
| _ ->
let name = List.fold_left (fun s name -> s ^ "/" ^ name ) "" list in
if is_directory name then name ^ "/" else name
[ to_regexp_string ] replace a string with * and ? ( shell regexps ) to
a string for Emacs regexp library
a string for Emacs regexp library *)
let to_regexp_string s =
let plus = ref 0 in
let len = String.length s in
for i = 0 to len - 1 do
let c = s.[i] in
match c with
'.' | '*' | '[' | ']' -> incr plus
| _ -> ()
done;
let ss = String.create (len + !plus) in
let plus = ref 0 in
let rec iter i j =
if i < len then
let c = s.[i] in
match c with
'*' -> ss.[j] <- '.'; ss.[j+1] <- '*'; iter (i+1) (j+2)
| '?' -> ss.[j] <- '.'; iter (i+1) (j+1)
| '.'
| '['
| ']' -> ss.[j] <- '\\'; ss.[j+1] <- c; iter (i+1) (j+2)
| _ -> ss.[j] <- c; iter (i+1) (j+1)
in
iter 0 0;
ss
let ignore _ = ()
let hashtbl_mem h key =
try let _ = Hashtbl.find h key in true with _ -> false
let glob_to_regexp glob =
let lexbuf = Lexing.from_string glob in
let rec iter s =
let token = Lexers.lexer_glob lexbuf in
if token = "" then s else
iter (s^token)
in
"^"^(iter "")^"$"
let list_dir_normal dir =
try
let rec remove_dot list =
match list with
[] -> []
| file :: tail ->
if String.length file > 0 && file.[0] = '.' then remove_dot tail else
begin
file :: (remove_dot tail)
end
in
remove_dot (list_dir dir)
with _ -> []
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/common/utils.ml | ocaml | *********************************************************************
*********************************************************************
Useful functions.
Simplify a filename before printing it
replace known dirs by ~
This function format filenames so that directory names end with / | xlib for
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
let count_char_sub str pos len char =
let pos_end = pos + len in
let rec occur pos n =
if pos = pos_end then (n, 0) else
let next_pos =
try
String.index_from str pos char
with
Not_found -> -1
in
if next_pos = -1 || next_pos >= pos_end then (n,pos_end - pos) else
occur (next_pos + 1) (n + 1)
in
occur pos 0
let count_char str char =
let len = String.length str in
count_char_sub str 0 len char
let rec list_nth n list =
match n, list with
0, (ele :: _) -> ele
| _, [] -> raise Not_found
| _, (_:: tail) -> list_nth (n-1) tail
let rec mem_assq x = function
| [] -> false
| (a, b) :: l -> a == x || mem_assq x l
let rec removeq x = function
| [] -> []
| (a, b as pair) :: l -> if a == x then l else pair :: removeq x l
let rec list_removeq list ele =
match list with
e :: tail when e == ele -> list_removeq tail ele
| e :: tail -> e :: (list_removeq tail ele)
| _ -> []
let remove_assocq ele list =
List.fold_left (fun list ((e,_) as head) ->
if e == ele then list
else head :: list) [] list
let list_remove list ele =
List.fold_left (fun list e ->
if e = ele then list
else e :: list) [] list
let remove_assoc ele list =
List.fold_left (fun list ((e,_) as head) ->
if e = ele then list
else head :: list) [] list
let rec name =
if is_relative name then
longname " " ( name )
else
let tokens = decomp name in
let rec iter longname tokens =
match tokens with
[ ] - > " "
| [
let len = String.length name in
let rec iter i n =
if i+n+1 > = len || name.[i+n ] = ' / ' then
if i+n+1 > = len then
String.sub name i n
else
( String.sub name i ( n-1 )
in
iter 0 0
let curdirname name =
let rec
let rec longname dirname name =
if is_relative name then
longname "" (Filename.concat dirname name)
else
let tokens = decomp name in
let rec iter longname tokens =
match tokens with
[] -> ""
| [
let len = String.length name in
let rec iter i n =
if i+n+1 >= len || name.[i+n] = '/' then
if i+n+1 >= len then
String.sub name i n
else
(String.sub name i (n-1)
in
iter 0 0
let longname curdirname name =
let rec
*)
let file_list dirname =
try
let dir = Unix.opendir dirname in
let rec iter list =
try
let file = Unix.readdir dir in
iter (file :: list)
with
_ -> list
in
let list = iter [] in
Unix.closedir dir;
list
with
_ -> []
let string_ncmp s1 s2 n =
let sz1 = String.length s1 in
let sz2 = String.length s2 in
if sz1 < n || sz2 < n then s1 = s2
else
let s1' = String.sub s1 0 n in
let s2' = String.sub s2 0 n in
s1' = s2'
let completion list start =
let n = String.length start in
if n = 0 then list else
List.fold_left (fun list s ->
if string_ncmp start s n then
s :: list
else
list
) [] list
let common_suffix list start =
let newlist = completion list start in
let lenl = List.length newlist in
let len = String.length start in
match newlist with
[] -> "",0
| ele :: tail ->
let lenele = String.length ele in
if tail = [] then
String.sub ele len (lenele - len),1
else
let maxlen = List.fold_left (fun len e -> min len (String.length e))
lenele tail in
let suffix = ref "" in
try
for i = len to maxlen - 1 do
let c = ele.[i] in
List.iter (fun e -> if not (e.[i] == c) then raise Exit) tail;
suffix := !suffix ^ (String.make 1 c)
done;
raise Exit
with
_ -> !suffix, lenl
let read_string inc =
let len = in_channel_length inc in
let str = String.create len in
let curs = ref 0 in
let left = ref len in
try
while !left > 0 do
let read = input inc str !curs !left in
if read = 0 then raise End_of_file;
left := !left - read;
curs := !curs + read;
done;
str
with
End_of_file ->
String.sub str 0 !curs
let list_of_hash t =
let l = ref [] in
Hashtbl.iter (fun key ele -> l := (key,ele) :: !l) t;
!l
let find_in_path path name =
if not (Filename.is_implicit name) then
if Sys.file_exists name then name else raise Not_found
else begin
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
end
let string_to_path str =
let len = String.length str in
let rec iter start pos =
if pos >= len then
[String.sub str start (len - start)]
else
if str.[pos] = ' ' || str.[pos] = ':' then
(String.sub str start (pos - start)) :: (iter (pos+1) (pos+1))
else
iter start (pos+1)
in
iter 0 0
let path_to_string path =
let s = List.fold_left (fun str dir -> str ^ ":" ^ dir) "" path in
if String.length s > 0 then
let len = String.length s in
String.sub s 1 (len-1)
else ""
let hash_add_assoc hash list =
List.iter (fun (abbrev, repl) -> Hashtbl.add hash abbrev repl) list
let user =
try
Sys.getenv "USER"
with
Not_found -> ""
let homedir =
try
Sys.getenv "HOME"
with
Not_found -> ""
let known_dirs = ref [ homedir,"~"]
let check_prefix filename prefix =
let len = String.length prefix in
let n = String.length filename - len in
if n < 0 then raise Not_found;
for i = 0 to len-1 do
if filename.[i] <> prefix.[i] then raise Not_found
done;
String.sub filename len n
let replace_prefix filename prefixes =
List.fold_left (fun filename (dir,repl) ->
try
let fin = check_prefix filename dir in
repl ^ fin
with
Not_found -> filename) filename prefixes
let filename_to_string filename =
replace_prefix filename !known_dirs
let string_to_filename filename =
replace known ~ by
replace_prefix filename (List.map (fun (a,b) -> b,a) !known_dirs)
let exns = ref []
let register_exn f = exns := f :: !exns
let printexn exn =
let rec iter exns =
match exns with
[] -> Printexc.to_string exn
| f :: tail ->
try f exn with
_ -> iter tail
in
iter !exns
let catchexn s f =
try f () with
e ->
Printf.printf "Uncaught exception in %s: %s" s (printexn e);
print_newline ()
let vcatchexn s f =
try Some (f ()) with
e ->
Printf.printf "Uncaught exception in %s: %s" s (printexn e);
print_newline ();
None
let set_signal sig_num sig_beh =
let _ = Sys.signal sig_num sig_beh in ()
let format_to_string action arg =
let string = ref "" in
let (p,f) = Format.get_formatter_output_functions () in
Format.set_formatter_output_functions
(fun str pos len ->
let s = String.sub str pos len in
string := !string ^ s)
(fun () -> ());
try
action arg;
Format.print_flush ();
Format.set_formatter_output_functions p f;
!string
with
e ->
Format.print_flush ();
Format.set_formatter_output_functions p f;
raise e
let do_and_format action arg =
let string = ref "" in
let (p,f) = Format.get_formatter_output_functions () in
Format.set_formatter_output_functions
(fun str pos len ->
let s = String.sub str pos len in
string := !string ^ s)
(fun () -> ());
try
let v = action arg in
Format.print_flush ();
Format.set_formatter_output_functions p f;
!string, v
with
e ->
Format.print_flush ();
Format.set_formatter_output_functions p f;
raise e
let format_to_string action arg =
fst (do_and_format action arg)
open Unix
let is_directory filename =
try let s = Unix.stat filename in s.st_kind = S_DIR with _ -> false
let is_link filename =
try let s = Unix.lstat filename in s.st_kind = S_LNK with _ -> false
let list_dir filename =
let dir = opendir filename in
let list = ref [] in
try
while true do
list := (readdir dir) :: !list
done;
assert false
with _ ->
closedir dir;
!list
let load_directory filename =
let today = localtime (time ()) in
let s = Printf.sprintf "Directory %s :\n" filename in
let list = list_dir filename in
List.fold_left (fun s entry ->
let fullname = Filename.concat filename entry in
let stats = lstat fullname in
let perm = stats.st_perm in
let rights = String.create 10 in
rights.[9] <- (if perm land 1 = 0 then '-' else
if perm land 2048 = 0 then 'x' else 's');
rights.[8] <- (if perm land 2 = 0 then '-' else 'w');
rights.[7] <- (if perm land 4 = 0 then '-' else 'r');
rights.[6] <- (if perm land 8 = 0 then '-' else
if perm land 1024 = 0 then 'x' else 's');
rights.[5] <- (if perm land 16 = 0 then '-' else 'w');
rights.[4] <- (if perm land 32 = 0 then '-' else 'r');
rights.[3] <- (if perm land 64 = 0 then '-' else
if perm land 512 = 0 then 'x' else 's');
rights.[2] <- (if perm land 128 = 0 then '-' else 'w');
rights.[1] <- (if perm land 256 = 0 then '-' else 'r');
rights.[0] <- (match stats.st_kind with
S_DIR -> 'd'
| S_CHR -> 'c'
| S_BLK -> 'b'
| S_REG -> '-'
| S_LNK -> 'l'
| S_FIFO -> 'f'
| S_SOCK -> 's'
);
let time = stats.st_mtime in
let time = localtime time in
let date =
Printf.sprintf "%3s %2d %5s"
(match time.tm_mon with
0 -> "Jan"
| 1 -> "Feb"
| 2 -> "Mar"
| 3 -> "Apr"
| 4 -> "May"
| 5 -> "Jun"
| 6 -> "Jul"
| 7 -> "Aug"
| 8 -> "Sep"
| 9 -> "Oct"
| 10 -> "Nov"
| 11 -> "Dec"
| _ -> "???")
time.tm_mday
(if today.tm_year = time.tm_year then
Printf.sprintf "%02d:%02d"
time.tm_hour time.tm_min
else
Printf.sprintf " %4d" (time.tm_year + 1900)
)
in
let owner = stats.st_uid in
let owner = try (getpwuid owner).pw_name
with _ -> string_of_int owner in
let group = stats.st_gid in
let group = try (getgrgid group).gr_name
with _ -> string_of_int group in
let size = stats.st_size in
Printf.sprintf "%s %s %8s %8s %8d %s %s%s\n"
s rights owner group size date entry
(if is_link fullname then
Printf.sprintf " -> %s"
(try Unix.readlink fullname with _ -> "???") else "")
) s (Sort.list (<) list)
let normal_name curdir filename =
let fullname =
if Filename.is_relative filename then
Filename.concat curdir filename
else
filename
in
let rec iter name list level =
let b = Filename.basename name in
let d = Filename.dirname name in
if b = "." || b = "" then
if d = "/" || d = "." then list else
iter d list level else
if b = ".." then iter d list (level+1) else
if b = "/" then list else
if level > 0 then iter d list (level-1) else
iter d (b :: list) 0
in
let list = iter fullname [] 0 in
match list with
[] -> "/"
| _ ->
let name = List.fold_left (fun s name -> s ^ "/" ^ name ) "" list in
if is_directory name then name ^ "/" else name
[ to_regexp_string ] replace a string with * and ? ( shell regexps ) to
a string for Emacs regexp library
a string for Emacs regexp library *)
let to_regexp_string s =
let plus = ref 0 in
let len = String.length s in
for i = 0 to len - 1 do
let c = s.[i] in
match c with
'.' | '*' | '[' | ']' -> incr plus
| _ -> ()
done;
let ss = String.create (len + !plus) in
let plus = ref 0 in
let rec iter i j =
if i < len then
let c = s.[i] in
match c with
'*' -> ss.[j] <- '.'; ss.[j+1] <- '*'; iter (i+1) (j+2)
| '?' -> ss.[j] <- '.'; iter (i+1) (j+1)
| '.'
| '['
| ']' -> ss.[j] <- '\\'; ss.[j+1] <- c; iter (i+1) (j+2)
| _ -> ss.[j] <- c; iter (i+1) (j+1)
in
iter 0 0;
ss
let ignore _ = ()
let hashtbl_mem h key =
try let _ = Hashtbl.find h key in true with _ -> false
let glob_to_regexp glob =
let lexbuf = Lexing.from_string glob in
let rec iter s =
let token = Lexers.lexer_glob lexbuf in
if token = "" then s else
iter (s^token)
in
"^"^(iter "")^"$"
let list_dir_normal dir =
try
let rec remove_dot list =
match list with
[] -> []
| file :: tail ->
if String.length file > 0 && file.[0] = '.' then remove_dot tail else
begin
file :: (remove_dot tail)
end
in
remove_dot (list_dir dir)
with _ -> []
|
1b78b20f2edea2cb1adef518818437fdfe0a3fa06f85eefc369d589eadb85741 | sky-big/RabbitMQ | rabbit_mgmt_wm_user.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 Management Plugin .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2010 - 2014 GoPivotal , Inc. All rights reserved .
%%
-module(rabbit_mgmt_wm_user).
-export([init/1, resource_exists/2, to_json/2,
content_types_provided/2, content_types_accepted/2,
is_authorized/2, allowed_methods/2, accept_content/2,
delete_resource/2, user/1, put_user/1]).
-import(rabbit_misc, [pget/2]).
-include("rabbit_mgmt.hrl").
-include("webmachine.hrl").
-include("rabbit.hrl").
%%--------------------------------------------------------------------
init(_Config) -> {ok, #context{}}.
content_types_provided(ReqData, Context) ->
{[{"application/json", to_json}], ReqData, Context}.
content_types_accepted(ReqData, Context) ->
{[{"application/json", accept_content}], ReqData, Context}.
allowed_methods(ReqData, Context) ->
{['HEAD', 'GET', 'PUT', 'DELETE'], ReqData, Context}.
resource_exists(ReqData, Context) ->
{case user(ReqData) of
{ok, _} -> true;
{error, _} -> false
end, ReqData, Context}.
to_json(ReqData, Context) ->
{ok, User} = user(ReqData),
rabbit_mgmt_util:reply(rabbit_mgmt_format:internal_user(User),
ReqData, Context).
accept_content(ReqData, Context) ->
Username = rabbit_mgmt_util:id(user, ReqData),
rabbit_mgmt_util:with_decode(
[], ReqData, Context,
fun(_, User) ->
put_user([{name, Username} | User]),
{true, ReqData, Context}
end).
delete_resource(ReqData, Context) ->
User = rabbit_mgmt_util:id(user, ReqData),
rabbit_auth_backend_internal:delete_user(User),
{true, ReqData, Context}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_admin(ReqData, Context).
%%--------------------------------------------------------------------
user(ReqData) ->
rabbit_auth_backend_internal:lookup_user(rabbit_mgmt_util:id(user, ReqData)).
put_user(User) ->
CP = fun rabbit_auth_backend_internal:change_password/2,
CPH = fun rabbit_auth_backend_internal:change_password_hash/2,
case {proplists:is_defined(password, User),
proplists:is_defined(password_hash, User)} of
{true, _} -> put_user(User, pget(password, User), CP);
{_, true} -> Hash = rabbit_mgmt_util:b64decode_or_throw(
pget(password_hash, User)),
put_user(User, Hash, CPH);
_ -> put_user(User, <<>>, CPH)
end.
put_user(User, PWArg, PWFun) ->
Username = pget(name, User),
Tags = case {pget(tags, User), pget(administrator, User)} of
{undefined, undefined} ->
throw({error, tags_not_present});
{undefined, AdminS} ->
case rabbit_mgmt_util:parse_bool(AdminS) of
true -> [administrator];
false -> []
end;
{TagsS, _} ->
[list_to_atom(string:strip(T)) ||
T <- string:tokens(binary_to_list(TagsS), ",")]
end,
case rabbit_auth_backend_internal:lookup_user(Username) of
{error, not_found} ->
rabbit_auth_backend_internal:add_user(
Username, rabbit_guid:binary(rabbit_guid:gen_secure(), "tmp"));
_ ->
ok
end,
PWFun(Username, PWArg),
ok = rabbit_auth_backend_internal:set_tags(Username, Tags).
| null | https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-management/src/rabbit_mgmt_wm_user.erl | erlang | 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
Version 1.1 ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ Management Plugin .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2010 - 2014 GoPivotal , Inc. All rights reserved .
-module(rabbit_mgmt_wm_user).
-export([init/1, resource_exists/2, to_json/2,
content_types_provided/2, content_types_accepted/2,
is_authorized/2, allowed_methods/2, accept_content/2,
delete_resource/2, user/1, put_user/1]).
-import(rabbit_misc, [pget/2]).
-include("rabbit_mgmt.hrl").
-include("webmachine.hrl").
-include("rabbit.hrl").
init(_Config) -> {ok, #context{}}.
content_types_provided(ReqData, Context) ->
{[{"application/json", to_json}], ReqData, Context}.
content_types_accepted(ReqData, Context) ->
{[{"application/json", accept_content}], ReqData, Context}.
allowed_methods(ReqData, Context) ->
{['HEAD', 'GET', 'PUT', 'DELETE'], ReqData, Context}.
resource_exists(ReqData, Context) ->
{case user(ReqData) of
{ok, _} -> true;
{error, _} -> false
end, ReqData, Context}.
to_json(ReqData, Context) ->
{ok, User} = user(ReqData),
rabbit_mgmt_util:reply(rabbit_mgmt_format:internal_user(User),
ReqData, Context).
accept_content(ReqData, Context) ->
Username = rabbit_mgmt_util:id(user, ReqData),
rabbit_mgmt_util:with_decode(
[], ReqData, Context,
fun(_, User) ->
put_user([{name, Username} | User]),
{true, ReqData, Context}
end).
delete_resource(ReqData, Context) ->
User = rabbit_mgmt_util:id(user, ReqData),
rabbit_auth_backend_internal:delete_user(User),
{true, ReqData, Context}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_admin(ReqData, Context).
user(ReqData) ->
rabbit_auth_backend_internal:lookup_user(rabbit_mgmt_util:id(user, ReqData)).
put_user(User) ->
CP = fun rabbit_auth_backend_internal:change_password/2,
CPH = fun rabbit_auth_backend_internal:change_password_hash/2,
case {proplists:is_defined(password, User),
proplists:is_defined(password_hash, User)} of
{true, _} -> put_user(User, pget(password, User), CP);
{_, true} -> Hash = rabbit_mgmt_util:b64decode_or_throw(
pget(password_hash, User)),
put_user(User, Hash, CPH);
_ -> put_user(User, <<>>, CPH)
end.
put_user(User, PWArg, PWFun) ->
Username = pget(name, User),
Tags = case {pget(tags, User), pget(administrator, User)} of
{undefined, undefined} ->
throw({error, tags_not_present});
{undefined, AdminS} ->
case rabbit_mgmt_util:parse_bool(AdminS) of
true -> [administrator];
false -> []
end;
{TagsS, _} ->
[list_to_atom(string:strip(T)) ||
T <- string:tokens(binary_to_list(TagsS), ",")]
end,
case rabbit_auth_backend_internal:lookup_user(Username) of
{error, not_found} ->
rabbit_auth_backend_internal:add_user(
Username, rabbit_guid:binary(rabbit_guid:gen_secure(), "tmp"));
_ ->
ok
end,
PWFun(Username, PWArg),
ok = rabbit_auth_backend_internal:set_tags(Username, Tags).
|
cd861d2c0467bfeeff2f9855cc80568fbba27bb36ef03e13b9d0f52a13cc6186 | hemmi/coq2scala | indschemes.ml | (************************************************************************)
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 *)
(************************************************************************)
Created by from contents related to inductive schemes
initially developed by ( induction schemes ) , Siles ( decidable equality and boolean equality ) and
( combined scheme ) in file command.ml , Sep 2009
initially developed by Christine Paulin (induction schemes), Vincent
Siles (decidable equality and boolean equality) and Matthieu Sozeau
(combined scheme) in file command.ml, Sep 2009 *)
(* This file provides entry points for manually or automatically
declaring new schemes *)
open Pp
open Flags
open Util
open Names
open Declarations
open Entries
open Term
open Inductive
open Decl_kinds
open Indrec
open Declare
open Libnames
open Goptions
open Nameops
open Termops
open Typeops
open Inductiveops
open Pretyping
open Topconstr
open Nametab
open Smartlocate
open Vernacexpr
open Ind_tables
open Auto_ind_decl
open Eqschemes
open Elimschemes
(* Flags governing automatic synthesis of schemes *)
let elim_flag = ref true
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of induction schemes";
optkey = ["Elimination";"Schemes"];
optread = (fun () -> !elim_flag) ;
optwrite = (fun b -> elim_flag := b) }
let case_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of case analysis schemes";
optkey = ["Case";"Analysis";"Schemes"];
optread = (fun () -> !case_flag) ;
optwrite = (fun b -> case_flag := b) }
let eq_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of boolean equality";
optkey = ["Boolean";"Equality";"Schemes"];
optread = (fun () -> !eq_flag) ;
optwrite = (fun b -> eq_flag := b) }
let _ = (* compatibility *)
declare_bool_option
{ optsync = true;
optdepr = true;
optname = "automatic declaration of boolean equality";
optkey = ["Equality";"Scheme"];
optread = (fun () -> !eq_flag) ;
optwrite = (fun b -> eq_flag := b) }
let is_eq_flag () = !eq_flag && Flags.version_strictly_greater Flags.V8_2
let eq_dec_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of decidable equality";
optkey = ["Decidable";"Equality";"Schemes"];
optread = (fun () -> !eq_dec_flag) ;
optwrite = (fun b -> eq_dec_flag := b) }
let rewriting_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname ="automatic declaration of rewriting schemes for equality types";
optkey = ["Rewriting";"Schemes"];
optread = (fun () -> !rewriting_flag) ;
optwrite = (fun b -> rewriting_flag := b) }
(* Util *)
let define id internal c t =
let f = declare_constant ~internal in
let kn = f id
(DefinitionEntry
{ const_entry_body = c;
const_entry_secctx = None;
const_entry_type = t;
const_entry_opaque = false },
Decl_kinds.IsDefinition Scheme) in
definition_message id;
kn
Boolean equality
let declare_beq_scheme_gen internal names kn =
ignore (define_mutual_scheme beq_scheme_kind internal names kn)
let alarm what internal msg =
let debug = false in
match internal with
| KernelVerbose
| KernelSilent ->
(if debug then
Flags.if_warn Pp.msg_warning
(hov 0 msg ++ fnl () ++ what ++ str " not defined."))
| _ -> errorlabstrm "" msg
let try_declare_scheme what f internal names kn =
try f internal names kn
with
| ParameterWithoutEquality cst ->
alarm what internal
(str "Boolean equality not found for parameter " ++ pr_con cst ++
str".")
| InductiveWithProduct ->
alarm what internal
(str "Unable to decide equality of functional arguments.")
| InductiveWithSort ->
alarm what internal
(str "Unable to decide equality of type arguments.")
| NonSingletonProp ind ->
alarm what internal
(str "Cannot extract computational content from proposition " ++
quote (Printer.pr_inductive (Global.env()) ind) ++ str ".")
| EqNotFound (ind',ind) ->
alarm what internal
(str "Boolean equality on " ++
quote (Printer.pr_inductive (Global.env()) ind') ++
strbrk " is missing.")
| UndefinedCst s ->
alarm what internal
(strbrk "Required constant " ++ str s ++ str " undefined.")
| AlreadyDeclared msg ->
alarm what internal (msg ++ str ".")
| e when Errors.noncritical e ->
alarm what internal
(str "Unknown exception during scheme creation.")
let beq_scheme_msg mind =
let mib = Global.lookup_mind mind in
(* TODO: mutual inductive case *)
str "Boolean equality on " ++
pr_enum (fun ind -> quote (Printer.pr_inductive (Global.env()) ind))
(list_tabulate (fun i -> (mind,i)) (Array.length mib.mind_packets))
let declare_beq_scheme_with l kn =
try_declare_scheme (beq_scheme_msg kn) declare_beq_scheme_gen UserVerbose l kn
let try_declare_beq_scheme kn =
TODO : handle Fix , eventually handle
proof - irrelevance ; improve decidability by depending on decidability
for the parameters rather than on the bl and properties
proof-irrelevance; improve decidability by depending on decidability
for the parameters rather than on the bl and lb properties *)
try_declare_scheme (beq_scheme_msg kn) declare_beq_scheme_gen KernelVerbose [] kn
let declare_beq_scheme = declare_beq_scheme_with []
(* Case analysis schemes *)
let declare_one_case_analysis_scheme ind =
let (mib,mip) = Global.lookup_inductive ind in
let kind = inductive_sort_family mip in
let dep = if kind = InProp then case_scheme_kind_from_prop else case_dep_scheme_kind_from_type in
let kelim = elim_sorts (mib,mip) in
in case the inductive has a type elimination , generates only one
induction scheme , the other ones share the same code with the
apropriate type
induction scheme, the other ones share the same code with the
apropriate type *)
if List.mem InType kelim then
ignore (define_individual_scheme dep KernelVerbose None ind)
Induction / recursion schemes
let kinds_from_prop =
[InType,rect_scheme_kind_from_prop;
InProp,ind_scheme_kind_from_prop;
InSet,rec_scheme_kind_from_prop]
let kinds_from_type =
[InType,rect_dep_scheme_kind_from_type;
InProp,ind_dep_scheme_kind_from_type;
InSet,rec_dep_scheme_kind_from_type]
let declare_one_induction_scheme ind =
let (mib,mip) = Global.lookup_inductive ind in
let kind = inductive_sort_family mip in
let from_prop = kind = InProp in
let kelim = elim_sorts (mib,mip) in
let elims =
list_map_filter (fun (sort,kind) ->
if List.mem sort kelim then Some kind else None)
(if from_prop then kinds_from_prop else kinds_from_type) in
List.iter (fun kind -> ignore (define_individual_scheme kind KernelVerbose None ind))
elims
let declare_induction_schemes kn =
let mib = Global.lookup_mind kn in
if mib.mind_finite then begin
for i = 0 to Array.length mib.mind_packets - 1 do
declare_one_induction_scheme (kn,i);
done;
end
equality
let declare_eq_decidability_gen internal names kn =
let mib = Global.lookup_mind kn in
if mib.mind_finite then
ignore (define_mutual_scheme eq_dec_scheme_kind internal names kn)
let eq_dec_scheme_msg ind = (* TODO: mutual inductive case *)
str "Decidable equality on " ++ quote (Printer.pr_inductive (Global.env()) ind)
let declare_eq_decidability_scheme_with l kn =
try_declare_scheme (eq_dec_scheme_msg (kn,0))
declare_eq_decidability_gen UserVerbose l kn
let try_declare_eq_decidability kn =
try_declare_scheme (eq_dec_scheme_msg (kn,0))
declare_eq_decidability_gen KernelVerbose [] kn
let declare_eq_decidability = declare_eq_decidability_scheme_with []
let ignore_error f x =
try ignore (f x) with e when Errors.noncritical e -> ()
let declare_rewriting_schemes ind =
if Hipattern.is_inductive_equality ind then begin
ignore (define_individual_scheme rew_r2l_scheme_kind KernelVerbose None ind);
ignore (define_individual_scheme rew_r2l_dep_scheme_kind KernelVerbose None ind);
ignore (define_individual_scheme rew_r2l_forward_dep_scheme_kind
KernelVerbose None ind);
These ones expect the equality to be symmetric ; the first one also
(* needs eq *)
ignore_error (define_individual_scheme rew_l2r_scheme_kind KernelVerbose None) ind;
ignore_error
(define_individual_scheme rew_l2r_dep_scheme_kind KernelVerbose None) ind;
ignore_error
(define_individual_scheme rew_l2r_forward_dep_scheme_kind KernelVerbose None) ind
end
let declare_congr_scheme ind =
if Hipattern.is_equality_type (mkInd ind) then begin
if
try Coqlib.check_required_library Coqlib.logic_module_name; true
with e when Errors.noncritical e -> false
then
ignore (define_individual_scheme congr_scheme_kind KernelVerbose None ind)
else
warning "Cannot build congruence scheme because eq is not found"
end
let declare_sym_scheme ind =
if Hipattern.is_inductive_equality ind then
(* Expect the equality to be symmetric *)
ignore_error (define_individual_scheme sym_scheme_kind KernelVerbose None) ind
(* Scheme command *)
let rec split_scheme l =
let env = Global.env() in
match l with
| [] -> [],[]
| (Some id,t)::q -> let l1,l2 = split_scheme q in
( match t with
| InductionScheme (x,y,z) -> ((id,x,smart_global_inductive y,z)::l1),l2
| CaseScheme (x,y,z) -> ((id,x,smart_global_inductive y,z)::l1),l2
| EqualityScheme x -> l1,((Some id,smart_global_inductive x)::l2)
)
if no name has been provided , we build one from the types of the ind
requested
if no name has been provided, we build one from the types of the ind
requested
*)
| (None,t)::q ->
let l1,l2 = split_scheme q in
let names inds recs isdep y z =
let ind = smart_global_inductive y in
let sort_of_ind = inductive_sort_family (snd (lookup_mind_specif env ind)) in
let z' = family_of_sort (interp_sort z) in
let suffix = (
match sort_of_ind with
| InProp ->
if isdep then (match z' with
| InProp -> inds ^ "_dep"
| InSet -> recs ^ "_dep"
| InType -> recs ^ "t_dep")
else ( match z' with
| InProp -> inds
| InSet -> recs
| InType -> recs ^ "t" )
| _ ->
if isdep then (match z' with
| InProp -> inds
| InSet -> recs
| InType -> recs ^ "t" )
else (match z' with
| InProp -> inds ^ "_nodep"
| InSet -> recs ^ "_nodep"
| InType -> recs ^ "t_nodep")
) in
let newid = add_suffix (basename_of_global (IndRef ind)) suffix in
let newref = (dummy_loc,newid) in
((newref,isdep,ind,z)::l1),l2
in
match t with
| CaseScheme (x,y,z) -> names "_case" "_case" x y z
| InductionScheme (x,y,z) -> names "_ind" "_rec" x y z
| EqualityScheme x -> l1,((None,smart_global_inductive x)::l2)
let do_mutual_induction_scheme lnamedepindsort =
let lrecnames = List.map (fun ((_,f),_,_,_) -> f) lnamedepindsort
and sigma = Evd.empty
and env0 = Global.env() in
let lrecspec =
List.map
(fun (_,dep,ind,sort) -> (ind,dep,interp_elimination_sort sort))
lnamedepindsort
in
let listdecl = Indrec.build_mutual_induction_scheme env0 sigma lrecspec in
let rec declare decl fi lrecref =
let decltype = Retyping.get_type_of env0 Evd.empty decl in
let decltype = refresh_universes decltype in
let cst = define fi UserVerbose decl (Some decltype) in
ConstRef cst :: lrecref
in
let _ = List.fold_right2 declare listdecl lrecnames [] in
fixpoint_message None lrecnames
let get_common_underlying_mutual_inductive = function
| [] -> assert false
| (id,(mind,i as ind))::l as all ->
match List.filter (fun (_,(mind',_)) -> mind <> mind') l with
| (_,ind')::_ ->
raise (RecursionSchemeError (NotMutualInScheme (ind,ind')))
| [] ->
if not (list_distinct (List.map snd (List.map snd all))) then
error "A type occurs twice";
mind,
list_map_filter
(function (Some id,(_,i)) -> Some (i,snd id) | (None,_) -> None) all
let do_scheme l =
let ischeme,escheme = split_scheme l in
we want 1 kind of scheme at a time so we check if the user
tried to declare different schemes at once
tried to declare different schemes at once *)
if (ischeme <> []) && (escheme <> [])
then
error "Do not declare equality and induction scheme at the same time."
else (
if ischeme <> [] then do_mutual_induction_scheme ischeme
else
let mind,l = get_common_underlying_mutual_inductive escheme in
declare_beq_scheme_with l mind;
declare_eq_decidability_scheme_with l mind
)
(**********************************************************************)
(* Combined scheme *)
, Dec 2006
let list_split_rev_at index l =
let rec aux i acc = function
hd :: tl when i = index -> acc, tl
| hd :: tl -> aux (succ i) (hd :: acc) tl
| [] -> failwith "list_split_when: Invalid argument"
in aux 0 [] l
let fold_left' f = function
[] -> raise (Invalid_argument "fold_left'")
| hd :: tl -> List.fold_left f hd tl
let build_combined_scheme env schemes =
let defs = List.map (fun cst -> (cst, Typeops.type_of_constant env cst)) schemes in
let nschemes = schemes in
let find_inductive ty =
let (ctx, arity) = decompose_prod ty in
let (_, last) = List.hd ctx in
match kind_of_term last with
| App (ind, args) ->
let ind = destInd ind in
let (_,spec) = Inductive.lookup_mind_specif env ind in
ctx, ind, spec.mind_nrealargs
| _ -> ctx, destInd last, 0
in
let (c, t) = List.hd defs in
let ctx, ind, nargs = find_inductive t in
(* Number of clauses, including the predicates quantification *)
let prods = nb_prod t - (nargs + 1) in
let coqand = Coqlib.build_coq_and () and coqconj = Coqlib.build_coq_conj () in
let relargs = rel_vect 0 prods in
let concls = List.rev_map
(fun (cst, t) ->
mkApp(mkConst cst, relargs),
snd (decompose_prod_n prods t)) defs in
let concl_bod, concl_typ =
fold_left'
(fun (accb, acct) (cst, x) ->
mkApp (coqconj, [| x; acct; cst; accb |]),
mkApp (coqand, [| x; acct |])) concls
in
let ctx, _ =
list_split_rev_at prods
(List.rev_map (fun (x, y) -> x, None, y) ctx) in
let typ = it_mkProd_wo_LetIn concl_typ ctx in
let body = it_mkLambda_or_LetIn concl_bod ctx in
(body, typ)
let do_combined_scheme name schemes =
let csts =
List.map (fun x ->
let refe = Ident x in
let qualid = qualid_of_reference refe in
try Nametab.locate_constant (snd qualid)
with Not_found -> error ((string_of_qualid (snd qualid))^" is not declared."))
schemes
in
let body,typ = build_combined_scheme (Global.env ()) csts in
ignore (define (snd name) UserVerbose body (Some typ));
fixpoint_message None [snd name]
(**********************************************************************)
let map_inductive_block f kn n = for i=0 to n-1 do f (kn,i) done
let mutual_inductive_size kn = Array.length (Global.lookup_mind kn).mind_packets
let declare_default_schemes kn =
let n = mutual_inductive_size kn in
if !elim_flag then declare_induction_schemes kn;
if !case_flag then map_inductive_block declare_one_case_analysis_scheme kn n;
if is_eq_flag() then try_declare_beq_scheme kn;
if !eq_dec_flag then try_declare_eq_decidability kn;
if !rewriting_flag then map_inductive_block declare_congr_scheme kn n;
if !rewriting_flag then map_inductive_block declare_sym_scheme kn n;
if !rewriting_flag then map_inductive_block declare_rewriting_schemes kn n
| null | https://raw.githubusercontent.com/hemmi/coq2scala/d10f441c18146933a99bf2088116bd213ac3648d/coq-8.4pl2/toplevel/indschemes.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
This file provides entry points for manually or automatically
declaring new schemes
Flags governing automatic synthesis of schemes
compatibility
Util
TODO: mutual inductive case
Case analysis schemes
TODO: mutual inductive case
needs eq
Expect the equality to be symmetric
Scheme command
********************************************************************
Combined scheme
Number of clauses, including the predicates quantification
******************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Created by from contents related to inductive schemes
initially developed by ( induction schemes ) , Siles ( decidable equality and boolean equality ) and
( combined scheme ) in file command.ml , Sep 2009
initially developed by Christine Paulin (induction schemes), Vincent
Siles (decidable equality and boolean equality) and Matthieu Sozeau
(combined scheme) in file command.ml, Sep 2009 *)
open Pp
open Flags
open Util
open Names
open Declarations
open Entries
open Term
open Inductive
open Decl_kinds
open Indrec
open Declare
open Libnames
open Goptions
open Nameops
open Termops
open Typeops
open Inductiveops
open Pretyping
open Topconstr
open Nametab
open Smartlocate
open Vernacexpr
open Ind_tables
open Auto_ind_decl
open Eqschemes
open Elimschemes
let elim_flag = ref true
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of induction schemes";
optkey = ["Elimination";"Schemes"];
optread = (fun () -> !elim_flag) ;
optwrite = (fun b -> elim_flag := b) }
let case_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of case analysis schemes";
optkey = ["Case";"Analysis";"Schemes"];
optread = (fun () -> !case_flag) ;
optwrite = (fun b -> case_flag := b) }
let eq_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of boolean equality";
optkey = ["Boolean";"Equality";"Schemes"];
optread = (fun () -> !eq_flag) ;
optwrite = (fun b -> eq_flag := b) }
declare_bool_option
{ optsync = true;
optdepr = true;
optname = "automatic declaration of boolean equality";
optkey = ["Equality";"Scheme"];
optread = (fun () -> !eq_flag) ;
optwrite = (fun b -> eq_flag := b) }
let is_eq_flag () = !eq_flag && Flags.version_strictly_greater Flags.V8_2
let eq_dec_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname = "automatic declaration of decidable equality";
optkey = ["Decidable";"Equality";"Schemes"];
optread = (fun () -> !eq_dec_flag) ;
optwrite = (fun b -> eq_dec_flag := b) }
let rewriting_flag = ref false
let _ =
declare_bool_option
{ optsync = true;
optdepr = false;
optname ="automatic declaration of rewriting schemes for equality types";
optkey = ["Rewriting";"Schemes"];
optread = (fun () -> !rewriting_flag) ;
optwrite = (fun b -> rewriting_flag := b) }
let define id internal c t =
let f = declare_constant ~internal in
let kn = f id
(DefinitionEntry
{ const_entry_body = c;
const_entry_secctx = None;
const_entry_type = t;
const_entry_opaque = false },
Decl_kinds.IsDefinition Scheme) in
definition_message id;
kn
Boolean equality
let declare_beq_scheme_gen internal names kn =
ignore (define_mutual_scheme beq_scheme_kind internal names kn)
let alarm what internal msg =
let debug = false in
match internal with
| KernelVerbose
| KernelSilent ->
(if debug then
Flags.if_warn Pp.msg_warning
(hov 0 msg ++ fnl () ++ what ++ str " not defined."))
| _ -> errorlabstrm "" msg
let try_declare_scheme what f internal names kn =
try f internal names kn
with
| ParameterWithoutEquality cst ->
alarm what internal
(str "Boolean equality not found for parameter " ++ pr_con cst ++
str".")
| InductiveWithProduct ->
alarm what internal
(str "Unable to decide equality of functional arguments.")
| InductiveWithSort ->
alarm what internal
(str "Unable to decide equality of type arguments.")
| NonSingletonProp ind ->
alarm what internal
(str "Cannot extract computational content from proposition " ++
quote (Printer.pr_inductive (Global.env()) ind) ++ str ".")
| EqNotFound (ind',ind) ->
alarm what internal
(str "Boolean equality on " ++
quote (Printer.pr_inductive (Global.env()) ind') ++
strbrk " is missing.")
| UndefinedCst s ->
alarm what internal
(strbrk "Required constant " ++ str s ++ str " undefined.")
| AlreadyDeclared msg ->
alarm what internal (msg ++ str ".")
| e when Errors.noncritical e ->
alarm what internal
(str "Unknown exception during scheme creation.")
let beq_scheme_msg mind =
let mib = Global.lookup_mind mind in
str "Boolean equality on " ++
pr_enum (fun ind -> quote (Printer.pr_inductive (Global.env()) ind))
(list_tabulate (fun i -> (mind,i)) (Array.length mib.mind_packets))
let declare_beq_scheme_with l kn =
try_declare_scheme (beq_scheme_msg kn) declare_beq_scheme_gen UserVerbose l kn
let try_declare_beq_scheme kn =
TODO : handle Fix , eventually handle
proof - irrelevance ; improve decidability by depending on decidability
for the parameters rather than on the bl and properties
proof-irrelevance; improve decidability by depending on decidability
for the parameters rather than on the bl and lb properties *)
try_declare_scheme (beq_scheme_msg kn) declare_beq_scheme_gen KernelVerbose [] kn
let declare_beq_scheme = declare_beq_scheme_with []
let declare_one_case_analysis_scheme ind =
let (mib,mip) = Global.lookup_inductive ind in
let kind = inductive_sort_family mip in
let dep = if kind = InProp then case_scheme_kind_from_prop else case_dep_scheme_kind_from_type in
let kelim = elim_sorts (mib,mip) in
in case the inductive has a type elimination , generates only one
induction scheme , the other ones share the same code with the
apropriate type
induction scheme, the other ones share the same code with the
apropriate type *)
if List.mem InType kelim then
ignore (define_individual_scheme dep KernelVerbose None ind)
Induction / recursion schemes
let kinds_from_prop =
[InType,rect_scheme_kind_from_prop;
InProp,ind_scheme_kind_from_prop;
InSet,rec_scheme_kind_from_prop]
let kinds_from_type =
[InType,rect_dep_scheme_kind_from_type;
InProp,ind_dep_scheme_kind_from_type;
InSet,rec_dep_scheme_kind_from_type]
let declare_one_induction_scheme ind =
let (mib,mip) = Global.lookup_inductive ind in
let kind = inductive_sort_family mip in
let from_prop = kind = InProp in
let kelim = elim_sorts (mib,mip) in
let elims =
list_map_filter (fun (sort,kind) ->
if List.mem sort kelim then Some kind else None)
(if from_prop then kinds_from_prop else kinds_from_type) in
List.iter (fun kind -> ignore (define_individual_scheme kind KernelVerbose None ind))
elims
let declare_induction_schemes kn =
let mib = Global.lookup_mind kn in
if mib.mind_finite then begin
for i = 0 to Array.length mib.mind_packets - 1 do
declare_one_induction_scheme (kn,i);
done;
end
equality
let declare_eq_decidability_gen internal names kn =
let mib = Global.lookup_mind kn in
if mib.mind_finite then
ignore (define_mutual_scheme eq_dec_scheme_kind internal names kn)
str "Decidable equality on " ++ quote (Printer.pr_inductive (Global.env()) ind)
let declare_eq_decidability_scheme_with l kn =
try_declare_scheme (eq_dec_scheme_msg (kn,0))
declare_eq_decidability_gen UserVerbose l kn
let try_declare_eq_decidability kn =
try_declare_scheme (eq_dec_scheme_msg (kn,0))
declare_eq_decidability_gen KernelVerbose [] kn
let declare_eq_decidability = declare_eq_decidability_scheme_with []
let ignore_error f x =
try ignore (f x) with e when Errors.noncritical e -> ()
let declare_rewriting_schemes ind =
if Hipattern.is_inductive_equality ind then begin
ignore (define_individual_scheme rew_r2l_scheme_kind KernelVerbose None ind);
ignore (define_individual_scheme rew_r2l_dep_scheme_kind KernelVerbose None ind);
ignore (define_individual_scheme rew_r2l_forward_dep_scheme_kind
KernelVerbose None ind);
These ones expect the equality to be symmetric ; the first one also
ignore_error (define_individual_scheme rew_l2r_scheme_kind KernelVerbose None) ind;
ignore_error
(define_individual_scheme rew_l2r_dep_scheme_kind KernelVerbose None) ind;
ignore_error
(define_individual_scheme rew_l2r_forward_dep_scheme_kind KernelVerbose None) ind
end
let declare_congr_scheme ind =
if Hipattern.is_equality_type (mkInd ind) then begin
if
try Coqlib.check_required_library Coqlib.logic_module_name; true
with e when Errors.noncritical e -> false
then
ignore (define_individual_scheme congr_scheme_kind KernelVerbose None ind)
else
warning "Cannot build congruence scheme because eq is not found"
end
let declare_sym_scheme ind =
if Hipattern.is_inductive_equality ind then
ignore_error (define_individual_scheme sym_scheme_kind KernelVerbose None) ind
let rec split_scheme l =
let env = Global.env() in
match l with
| [] -> [],[]
| (Some id,t)::q -> let l1,l2 = split_scheme q in
( match t with
| InductionScheme (x,y,z) -> ((id,x,smart_global_inductive y,z)::l1),l2
| CaseScheme (x,y,z) -> ((id,x,smart_global_inductive y,z)::l1),l2
| EqualityScheme x -> l1,((Some id,smart_global_inductive x)::l2)
)
if no name has been provided , we build one from the types of the ind
requested
if no name has been provided, we build one from the types of the ind
requested
*)
| (None,t)::q ->
let l1,l2 = split_scheme q in
let names inds recs isdep y z =
let ind = smart_global_inductive y in
let sort_of_ind = inductive_sort_family (snd (lookup_mind_specif env ind)) in
let z' = family_of_sort (interp_sort z) in
let suffix = (
match sort_of_ind with
| InProp ->
if isdep then (match z' with
| InProp -> inds ^ "_dep"
| InSet -> recs ^ "_dep"
| InType -> recs ^ "t_dep")
else ( match z' with
| InProp -> inds
| InSet -> recs
| InType -> recs ^ "t" )
| _ ->
if isdep then (match z' with
| InProp -> inds
| InSet -> recs
| InType -> recs ^ "t" )
else (match z' with
| InProp -> inds ^ "_nodep"
| InSet -> recs ^ "_nodep"
| InType -> recs ^ "t_nodep")
) in
let newid = add_suffix (basename_of_global (IndRef ind)) suffix in
let newref = (dummy_loc,newid) in
((newref,isdep,ind,z)::l1),l2
in
match t with
| CaseScheme (x,y,z) -> names "_case" "_case" x y z
| InductionScheme (x,y,z) -> names "_ind" "_rec" x y z
| EqualityScheme x -> l1,((None,smart_global_inductive x)::l2)
let do_mutual_induction_scheme lnamedepindsort =
let lrecnames = List.map (fun ((_,f),_,_,_) -> f) lnamedepindsort
and sigma = Evd.empty
and env0 = Global.env() in
let lrecspec =
List.map
(fun (_,dep,ind,sort) -> (ind,dep,interp_elimination_sort sort))
lnamedepindsort
in
let listdecl = Indrec.build_mutual_induction_scheme env0 sigma lrecspec in
let rec declare decl fi lrecref =
let decltype = Retyping.get_type_of env0 Evd.empty decl in
let decltype = refresh_universes decltype in
let cst = define fi UserVerbose decl (Some decltype) in
ConstRef cst :: lrecref
in
let _ = List.fold_right2 declare listdecl lrecnames [] in
fixpoint_message None lrecnames
let get_common_underlying_mutual_inductive = function
| [] -> assert false
| (id,(mind,i as ind))::l as all ->
match List.filter (fun (_,(mind',_)) -> mind <> mind') l with
| (_,ind')::_ ->
raise (RecursionSchemeError (NotMutualInScheme (ind,ind')))
| [] ->
if not (list_distinct (List.map snd (List.map snd all))) then
error "A type occurs twice";
mind,
list_map_filter
(function (Some id,(_,i)) -> Some (i,snd id) | (None,_) -> None) all
let do_scheme l =
let ischeme,escheme = split_scheme l in
we want 1 kind of scheme at a time so we check if the user
tried to declare different schemes at once
tried to declare different schemes at once *)
if (ischeme <> []) && (escheme <> [])
then
error "Do not declare equality and induction scheme at the same time."
else (
if ischeme <> [] then do_mutual_induction_scheme ischeme
else
let mind,l = get_common_underlying_mutual_inductive escheme in
declare_beq_scheme_with l mind;
declare_eq_decidability_scheme_with l mind
)
, Dec 2006
let list_split_rev_at index l =
let rec aux i acc = function
hd :: tl when i = index -> acc, tl
| hd :: tl -> aux (succ i) (hd :: acc) tl
| [] -> failwith "list_split_when: Invalid argument"
in aux 0 [] l
let fold_left' f = function
[] -> raise (Invalid_argument "fold_left'")
| hd :: tl -> List.fold_left f hd tl
let build_combined_scheme env schemes =
let defs = List.map (fun cst -> (cst, Typeops.type_of_constant env cst)) schemes in
let nschemes = schemes in
let find_inductive ty =
let (ctx, arity) = decompose_prod ty in
let (_, last) = List.hd ctx in
match kind_of_term last with
| App (ind, args) ->
let ind = destInd ind in
let (_,spec) = Inductive.lookup_mind_specif env ind in
ctx, ind, spec.mind_nrealargs
| _ -> ctx, destInd last, 0
in
let (c, t) = List.hd defs in
let ctx, ind, nargs = find_inductive t in
let prods = nb_prod t - (nargs + 1) in
let coqand = Coqlib.build_coq_and () and coqconj = Coqlib.build_coq_conj () in
let relargs = rel_vect 0 prods in
let concls = List.rev_map
(fun (cst, t) ->
mkApp(mkConst cst, relargs),
snd (decompose_prod_n prods t)) defs in
let concl_bod, concl_typ =
fold_left'
(fun (accb, acct) (cst, x) ->
mkApp (coqconj, [| x; acct; cst; accb |]),
mkApp (coqand, [| x; acct |])) concls
in
let ctx, _ =
list_split_rev_at prods
(List.rev_map (fun (x, y) -> x, None, y) ctx) in
let typ = it_mkProd_wo_LetIn concl_typ ctx in
let body = it_mkLambda_or_LetIn concl_bod ctx in
(body, typ)
let do_combined_scheme name schemes =
let csts =
List.map (fun x ->
let refe = Ident x in
let qualid = qualid_of_reference refe in
try Nametab.locate_constant (snd qualid)
with Not_found -> error ((string_of_qualid (snd qualid))^" is not declared."))
schemes
in
let body,typ = build_combined_scheme (Global.env ()) csts in
ignore (define (snd name) UserVerbose body (Some typ));
fixpoint_message None [snd name]
let map_inductive_block f kn n = for i=0 to n-1 do f (kn,i) done
let mutual_inductive_size kn = Array.length (Global.lookup_mind kn).mind_packets
let declare_default_schemes kn =
let n = mutual_inductive_size kn in
if !elim_flag then declare_induction_schemes kn;
if !case_flag then map_inductive_block declare_one_case_analysis_scheme kn n;
if is_eq_flag() then try_declare_beq_scheme kn;
if !eq_dec_flag then try_declare_eq_decidability kn;
if !rewriting_flag then map_inductive_block declare_congr_scheme kn n;
if !rewriting_flag then map_inductive_block declare_sym_scheme kn n;
if !rewriting_flag then map_inductive_block declare_rewriting_schemes kn n
|
6a1fd8e77abd1e9c7e822c213f984f19434c0f308b24c2cb3fee632c74437a3e | braintripping/lark | core.cljs | (ns lark.structure.core
(:require lark.structure.coords
lark.structure.loc
lark.structure.operation.edit
lark.structure.operation.select
lark.structure.operation
lark.structure.pointer
lark.structure.string
[cljs.spec.alpha :as s]
[expound.alpha :as expound]
[cljs.spec.test.alpha :as st]
[chia.util.dev-errors :as dev-errors]))
(set! s/*explain-out* expound/printer)
(defn ^:dev/after-load instrument []
(st/instrument '[lark.structure.operation
lark.structure.operation.edit
lark.structure.operation.select
lark.structure.operation.impl.replace
lark.structure.coords
lark.structure.delta
lark.structure.loc
lark.structure.path
lark.structure.pointer
lark.structure.string]))
(defonce _
(do (dev-errors/install-formatter!)
(instrument)))
| null | https://raw.githubusercontent.com/braintripping/lark/95038a823068681c39453c46a309a3514cf48800/tools/test/lark/structure/core.cljs | clojure | (ns lark.structure.core
(:require lark.structure.coords
lark.structure.loc
lark.structure.operation.edit
lark.structure.operation.select
lark.structure.operation
lark.structure.pointer
lark.structure.string
[cljs.spec.alpha :as s]
[expound.alpha :as expound]
[cljs.spec.test.alpha :as st]
[chia.util.dev-errors :as dev-errors]))
(set! s/*explain-out* expound/printer)
(defn ^:dev/after-load instrument []
(st/instrument '[lark.structure.operation
lark.structure.operation.edit
lark.structure.operation.select
lark.structure.operation.impl.replace
lark.structure.coords
lark.structure.delta
lark.structure.loc
lark.structure.path
lark.structure.pointer
lark.structure.string]))
(defonce _
(do (dev-errors/install-formatter!)
(instrument)))
| |
2c224c047c11c5a06fc14d1ad82343f385829a7b846d4b6521bf886f0b204b55 | gorillalabs/sparkling | scalaInterop.clj | (ns sparkling.scalaInterop
(:import [sparkling.scalaInterop ScalaFunction0 ScalaFunction1]
[scala Tuple1 Tuple2 Tuple3 Tuple4 Tuple5 Tuple6 Tuple7 Tuple8 Tuple9 Tuple10 Tuple11 Tuple12 Tuple13 Tuple14 Tuple15 Tuple16 Tuple17 Tuple18 Tuple19 Tuple20 Tuple21 Tuple22 Some]
[scala.reflect ClassTag$])
)
(defn class-tag [class]
(.apply ClassTag$/MODULE$ class))
;; lol scala
(def ^:no-doc OBJECT-CLASS-TAG (class-tag java.lang.Object))
(defmacro gen-function
[clazz wrapper-name]
`(defn ~wrapper-name [f#]
(new ~(symbol (str "sparkling.scalaInterop." clazz)) f#)))
(gen-function ScalaFunction0 function0)
(gen-function ScalaFunction1 function1)
(defn tuple
"Returns a Scala tuple. Uses the Scala tuple class that matches the
number of arguments.
($/tuple 1 2) => (instance-of scala.Tuple2)
(apply $/tuple (range 20)) => (instance-of scala.Tuple20)
(apply $/tuple (range 21)) => (instance-of scala.Tuple21)
(apply $/tuple (range 22)) => (instance-of scala.Tuple22)
(apply $/tuple (range 23)) => (throws ExceptionInfo)"
{:added "0.1.0"}
([a]
(Tuple1. a))
([a b]
(Tuple2. a b))
([a b c]
(Tuple3. a b c))
([a b c d]
(Tuple4. a b c d))
([a b c d e]
(Tuple5. a b c d e))
([a b c d e f]
(Tuple6. a b c d e f))
([a b c d e f g]
(Tuple7. a b c d e f g))
([a b c d e f g h]
(Tuple8. a b c d e f g h))
([a b c d e f g h i]
(Tuple9. a b c d e f g h i))
([a b c d e f g h i j]
(Tuple10. a b c d e f g h i j))
([a b c d e f g h i j k]
(Tuple11. a b c d e f g h i j k))
([a b c d e f g h i j k l]
(Tuple12. a b c d e f g h i j k l))
([a b c d e f g h i j k l m]
(Tuple13. a b c d e f g h i j k l m))
([a b c d e f g h i j k l m n]
(Tuple14. a b c d e f g h i j k l m n))
([a b c d e f g h i j k l m n o]
(Tuple15. a b c d e f g h i j k l m n o))
([a b c d e f g h i j k l m n o p]
(Tuple16. a b c d e f g h i j k l m n o p))
([a b c d e f g h i j k l m n o p q]
(Tuple17. a b c d e f g h i j k l m n o p q))
([a b c d e f g h i j k l m n o p q r]
(Tuple18. a b c d e f g h i j k l m n o p q r))
([a b c d e f g h i j k l m n o p q r s]
(Tuple19. a b c d e f g h i j k l m n o p q r s))
([a b c d e f g h i j k l m n o p q r s t]
(Tuple20. a b c d e f g h i j k l m n o p q r s t))
([a b c d e f g h i j k l m n o p q r s t & [u v :as args]]
(case (count args)
1 (Tuple21. a b c d e f g h i j k l m n o p q r s t u)
2 (Tuple22. a b c d e f g h i j k l m n o p q r s t u v)
(throw (ex-info "Can only create Scala tuples with up to 22 elements"
{:count (+ 20 (count args))})))))
(defn tuple-reader [v]
(apply tuple v))
(defmethod print-method Tuple2 [^Tuple2 o ^java.io.Writer w]
(.write w (str "#sparkling/tuple " (pr-str [(._1 o) (._2 o)]))))
(defmethod print-dup Tuple2 [o w]
(print-method o w))
(defn some-or-nil [option]
(when (instance? Some option)
(.get ^Some option)))
#_(defn Function0-apply [this]
(-apply this))
#_(defn Function1-apply [this x]
(-apply this x))
| null | https://raw.githubusercontent.com/gorillalabs/sparkling/ffedcc70fd46bf1b48405be8b1f5a1e1c4f9f578/src/clojure/sparkling/scalaInterop.clj | clojure | lol scala | (ns sparkling.scalaInterop
(:import [sparkling.scalaInterop ScalaFunction0 ScalaFunction1]
[scala Tuple1 Tuple2 Tuple3 Tuple4 Tuple5 Tuple6 Tuple7 Tuple8 Tuple9 Tuple10 Tuple11 Tuple12 Tuple13 Tuple14 Tuple15 Tuple16 Tuple17 Tuple18 Tuple19 Tuple20 Tuple21 Tuple22 Some]
[scala.reflect ClassTag$])
)
(defn class-tag [class]
(.apply ClassTag$/MODULE$ class))
(def ^:no-doc OBJECT-CLASS-TAG (class-tag java.lang.Object))
(defmacro gen-function
[clazz wrapper-name]
`(defn ~wrapper-name [f#]
(new ~(symbol (str "sparkling.scalaInterop." clazz)) f#)))
(gen-function ScalaFunction0 function0)
(gen-function ScalaFunction1 function1)
(defn tuple
"Returns a Scala tuple. Uses the Scala tuple class that matches the
number of arguments.
($/tuple 1 2) => (instance-of scala.Tuple2)
(apply $/tuple (range 20)) => (instance-of scala.Tuple20)
(apply $/tuple (range 21)) => (instance-of scala.Tuple21)
(apply $/tuple (range 22)) => (instance-of scala.Tuple22)
(apply $/tuple (range 23)) => (throws ExceptionInfo)"
{:added "0.1.0"}
([a]
(Tuple1. a))
([a b]
(Tuple2. a b))
([a b c]
(Tuple3. a b c))
([a b c d]
(Tuple4. a b c d))
([a b c d e]
(Tuple5. a b c d e))
([a b c d e f]
(Tuple6. a b c d e f))
([a b c d e f g]
(Tuple7. a b c d e f g))
([a b c d e f g h]
(Tuple8. a b c d e f g h))
([a b c d e f g h i]
(Tuple9. a b c d e f g h i))
([a b c d e f g h i j]
(Tuple10. a b c d e f g h i j))
([a b c d e f g h i j k]
(Tuple11. a b c d e f g h i j k))
([a b c d e f g h i j k l]
(Tuple12. a b c d e f g h i j k l))
([a b c d e f g h i j k l m]
(Tuple13. a b c d e f g h i j k l m))
([a b c d e f g h i j k l m n]
(Tuple14. a b c d e f g h i j k l m n))
([a b c d e f g h i j k l m n o]
(Tuple15. a b c d e f g h i j k l m n o))
([a b c d e f g h i j k l m n o p]
(Tuple16. a b c d e f g h i j k l m n o p))
([a b c d e f g h i j k l m n o p q]
(Tuple17. a b c d e f g h i j k l m n o p q))
([a b c d e f g h i j k l m n o p q r]
(Tuple18. a b c d e f g h i j k l m n o p q r))
([a b c d e f g h i j k l m n o p q r s]
(Tuple19. a b c d e f g h i j k l m n o p q r s))
([a b c d e f g h i j k l m n o p q r s t]
(Tuple20. a b c d e f g h i j k l m n o p q r s t))
([a b c d e f g h i j k l m n o p q r s t & [u v :as args]]
(case (count args)
1 (Tuple21. a b c d e f g h i j k l m n o p q r s t u)
2 (Tuple22. a b c d e f g h i j k l m n o p q r s t u v)
(throw (ex-info "Can only create Scala tuples with up to 22 elements"
{:count (+ 20 (count args))})))))
(defn tuple-reader [v]
(apply tuple v))
(defmethod print-method Tuple2 [^Tuple2 o ^java.io.Writer w]
(.write w (str "#sparkling/tuple " (pr-str [(._1 o) (._2 o)]))))
(defmethod print-dup Tuple2 [o w]
(print-method o w))
(defn some-or-nil [option]
(when (instance? Some option)
(.get ^Some option)))
#_(defn Function0-apply [this]
(-apply this))
#_(defn Function1-apply [this x]
(-apply this x))
|
bfdf7d1d96a320aabc3140c5531de161ac956d018329fd30d3d4c12b316a305a | robert-strandh/SICL | list-structure.lisp | (cl:in-package #:cleavir-code-utilities)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tools for checking for list structure.
For any object , return its structure as a list as two values : the
;;; first value contains the number of unique CONS cells in the list,
and the second value is one of the keywords : proper , : dotted , and
;;; :circular. For an atom, 0 and :dotted is returned.
;;;
;;; This function is useful for processing code because lists
;;; representing code are not often very long, so the method used is
;;; fast and appropriate, and because we often need to check that such
;;; lists are proper, but the simple method would go into an infinite
;;; computation if the list is circular, whereas we would like to give
;;; an error message in that case.
(defun list-structure (object)
First we attempt to just traverse the list as usual ,
;; assuming that it is fairly short. If we reach the end,
;; then that's great, and we return the result.
(loop for remaining = object then (cdr remaining)
for count from 0 to 100
while (consp remaining)
finally (when (atom remaining)
(return-from list-structure
(values count
(if (null remaining)
:proper
:dotted)))))
;; Come here if the list has more than a few CONS cells. We
;; traverse it again, this time entering each CONS cell in a hash
;; table. Stop when we reach the end of the list, or when we see
;; the same CONS cell twice.
(let ((table (make-hash-table :test #'eq)))
(loop for remaining = object then (cdr remaining)
while (consp remaining)
until (gethash remaining table)
do (setf (gethash remaining table) t)
finally (return (values (hash-table-count table)
(if (null remaining)
:proper
(if (atom remaining)
:dotted
:circular)))))))
;;; Check that an object is a proper list. Return true if the object
;;; is a proper list. Return false if the object is an atom other
than NIL or if the list is dotted or circular .
(defun proper-list-p (object)
(cond ((null object) t)
((atom object) nil)
(t (let ((slow object)
(fast (cdr object)))
(declare (type cons slow))
(tagbody
again
(unless (consp fast)
(return-from proper-list-p
(if (null fast) t nil)))
(when (eq fast slow)
(return-from proper-list-p nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from proper-list-p
(if (null fast) t nil)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(go again))))))
;;; Check that an object is a proper list, and if so, return the
;;; number of cons cells in the list. Return false if the object is
;;; an atom other than NIL or if the list is dotted or circular. If
the object is NIL , 0 is returned .
(defun proper-list-length (object)
(cond ((null object) 0)
((atom object) nil)
(t (let ((slow object)
(fast (cdr object))
(count 1))
(declare (type cons slow))
;; We assume that the implementation is such that a
;; fixnum is able to hold the maximum number of CONS
;; cells possible in the heap.
(declare (type fixnum count))
(tagbody
again
(unless (consp fast)
(return-from proper-list-length
(if (null fast) count nil)))
(when (eq fast slow)
(return-from proper-list-length nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from proper-list-length
(if (null fast) (1+ count) nil)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(incf count 2)
(go again))))))
;;; If all we want is to know whether some object is a dotted list, we
;;; use the method of the slow and the fast pointer. This function
;;; returns true if the object is an atom other than NIL (the
;;; degenerate case of a dotted list) or if the list is terminated by
some atom other than NIL . It returns false if the object is NIL ,
if the object is a list terminated by NIL , or of the object is a
;;; circular list.
(defun dotted-list-p (object)
(cond ((null object) nil)
((atom object) 0)
(t (let ((slow object)
(fast (cdr object)))
(declare (type cons slow))
(tagbody
again
(unless (consp fast)
(return-from dotted-list-p
(if (null fast) nil t)))
(when (eq fast slow)
(return-from dotted-list-p nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from dotted-list-p
(if (null fast) nil t)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(go again))))))
;;; Check that an object is a dotted list, and if so, return the
;;; number of cons cells in the list. Return false if the object is
NIL , if the object is a list terminated by NIL , or of the object
;;; is a circular list. Return 0 if the object is an atom other than
NIL ( the degenerate case of a dotted list ) .
(defun dotted-list-length (object)
(cond ((null object) nil)
((atom object) 0)
(t (let ((slow object)
(fast (cdr object))
(count 1))
(declare (type cons slow))
;; We assume that the implementation is such that a
;; fixnum is able to hold the maximum number of CONS
;; cells possible in the heap.
(declare (type fixnum count))
(tagbody
again
(unless (consp fast)
(return-from dotted-list-length
(if (null fast) nil count)))
(when (eq fast slow)
(return-from dotted-list-length nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from dotted-list-length
(if (null fast) nil (1+ count))))
(setq fast (cdr fast))
(setq slow (cdr slow))
(incf count 2)
(go again))))))
(defun proper-or-dotted-list-length (object)
(cond ((atom object) 0)
(t (let ((slow object)
(fast (cdr object))
(count 1))
(declare (type cons slow))
;; We assume that the implementation is such that a
;; fixnum is able to hold the maximum number of CONS
;; cells possible in the heap.
(declare (type fixnum count))
(tagbody
again
(unless (consp fast)
(return-from proper-or-dotted-list-length count))
(when (eq fast slow)
(return-from proper-or-dotted-list-length nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from proper-or-dotted-list-length (1+ count)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(incf count 2)
(go again))))))
;;; If all we want is to know whether some object is a circular list,
;;; we use the method of the slow and the fast pointer. This function
;;; returns true if the object is a circular list, and false for any
;;; other object.
(defun circular-list-p (object)
(cond ((atom object) nil)
(t (let ((slow object)
(fast (cdr object)))
(declare (type cons slow))
(tagbody
again
(unless (consp fast)
(return-from circular-list-p nil))
(when (eq fast slow)
(return-from circular-list-p t))
(setq fast (cdr fast))
(unless (consp fast)
(return-from circular-list-p nil))
(setq fast (cdr fast))
(setq slow (cdr slow))
(go again))))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/58865dbfca0ff62bc6568d17dd9c78e5f2420c9c/Code/Cleavir/Code-utilities/List-structure/list-structure.lisp | lisp |
Tools for checking for list structure.
first value contains the number of unique CONS cells in the list,
:circular. For an atom, 0 and :dotted is returned.
This function is useful for processing code because lists
representing code are not often very long, so the method used is
fast and appropriate, and because we often need to check that such
lists are proper, but the simple method would go into an infinite
computation if the list is circular, whereas we would like to give
an error message in that case.
assuming that it is fairly short. If we reach the end,
then that's great, and we return the result.
Come here if the list has more than a few CONS cells. We
traverse it again, this time entering each CONS cell in a hash
table. Stop when we reach the end of the list, or when we see
the same CONS cell twice.
Check that an object is a proper list. Return true if the object
is a proper list. Return false if the object is an atom other
Check that an object is a proper list, and if so, return the
number of cons cells in the list. Return false if the object is
an atom other than NIL or if the list is dotted or circular. If
We assume that the implementation is such that a
fixnum is able to hold the maximum number of CONS
cells possible in the heap.
If all we want is to know whether some object is a dotted list, we
use the method of the slow and the fast pointer. This function
returns true if the object is an atom other than NIL (the
degenerate case of a dotted list) or if the list is terminated by
circular list.
Check that an object is a dotted list, and if so, return the
number of cons cells in the list. Return false if the object is
is a circular list. Return 0 if the object is an atom other than
We assume that the implementation is such that a
fixnum is able to hold the maximum number of CONS
cells possible in the heap.
We assume that the implementation is such that a
fixnum is able to hold the maximum number of CONS
cells possible in the heap.
If all we want is to know whether some object is a circular list,
we use the method of the slow and the fast pointer. This function
returns true if the object is a circular list, and false for any
other object. | (cl:in-package #:cleavir-code-utilities)
For any object , return its structure as a list as two values : the
and the second value is one of the keywords : proper , : dotted , and
(defun list-structure (object)
First we attempt to just traverse the list as usual ,
(loop for remaining = object then (cdr remaining)
for count from 0 to 100
while (consp remaining)
finally (when (atom remaining)
(return-from list-structure
(values count
(if (null remaining)
:proper
:dotted)))))
(let ((table (make-hash-table :test #'eq)))
(loop for remaining = object then (cdr remaining)
while (consp remaining)
until (gethash remaining table)
do (setf (gethash remaining table) t)
finally (return (values (hash-table-count table)
(if (null remaining)
:proper
(if (atom remaining)
:dotted
:circular)))))))
than NIL or if the list is dotted or circular .
(defun proper-list-p (object)
(cond ((null object) t)
((atom object) nil)
(t (let ((slow object)
(fast (cdr object)))
(declare (type cons slow))
(tagbody
again
(unless (consp fast)
(return-from proper-list-p
(if (null fast) t nil)))
(when (eq fast slow)
(return-from proper-list-p nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from proper-list-p
(if (null fast) t nil)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(go again))))))
the object is NIL , 0 is returned .
(defun proper-list-length (object)
(cond ((null object) 0)
((atom object) nil)
(t (let ((slow object)
(fast (cdr object))
(count 1))
(declare (type cons slow))
(declare (type fixnum count))
(tagbody
again
(unless (consp fast)
(return-from proper-list-length
(if (null fast) count nil)))
(when (eq fast slow)
(return-from proper-list-length nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from proper-list-length
(if (null fast) (1+ count) nil)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(incf count 2)
(go again))))))
some atom other than NIL . It returns false if the object is NIL ,
if the object is a list terminated by NIL , or of the object is a
(defun dotted-list-p (object)
(cond ((null object) nil)
((atom object) 0)
(t (let ((slow object)
(fast (cdr object)))
(declare (type cons slow))
(tagbody
again
(unless (consp fast)
(return-from dotted-list-p
(if (null fast) nil t)))
(when (eq fast slow)
(return-from dotted-list-p nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from dotted-list-p
(if (null fast) nil t)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(go again))))))
NIL , if the object is a list terminated by NIL , or of the object
NIL ( the degenerate case of a dotted list ) .
(defun dotted-list-length (object)
(cond ((null object) nil)
((atom object) 0)
(t (let ((slow object)
(fast (cdr object))
(count 1))
(declare (type cons slow))
(declare (type fixnum count))
(tagbody
again
(unless (consp fast)
(return-from dotted-list-length
(if (null fast) nil count)))
(when (eq fast slow)
(return-from dotted-list-length nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from dotted-list-length
(if (null fast) nil (1+ count))))
(setq fast (cdr fast))
(setq slow (cdr slow))
(incf count 2)
(go again))))))
(defun proper-or-dotted-list-length (object)
(cond ((atom object) 0)
(t (let ((slow object)
(fast (cdr object))
(count 1))
(declare (type cons slow))
(declare (type fixnum count))
(tagbody
again
(unless (consp fast)
(return-from proper-or-dotted-list-length count))
(when (eq fast slow)
(return-from proper-or-dotted-list-length nil))
(setq fast (cdr fast))
(unless (consp fast)
(return-from proper-or-dotted-list-length (1+ count)))
(setq fast (cdr fast))
(setq slow (cdr slow))
(incf count 2)
(go again))))))
(defun circular-list-p (object)
(cond ((atom object) nil)
(t (let ((slow object)
(fast (cdr object)))
(declare (type cons slow))
(tagbody
again
(unless (consp fast)
(return-from circular-list-p nil))
(when (eq fast slow)
(return-from circular-list-p t))
(setq fast (cdr fast))
(unless (consp fast)
(return-from circular-list-p nil))
(setq fast (cdr fast))
(setq slow (cdr slow))
(go again))))))
|
d423f520760344aa7cb946eeae774d0ea8a38fdbe52b9c4f64f663650a57c1e7 | jyp/topics | Example0.hs | import Parsers.Incremental
import Control.Applicative
------------------------------------------------------------
-- Examples
data SExpr = S [SExpr] (Maybe Char)
| Atom Char
| Quoted [SExpr] (Maybe Char)
| Inserted Char
| Deleted Char
deriving Show
-- the only place we use disjunction is in many.
symb n c = Look (Shif n) (Shif . c)
manyx v = some v <|> oops "closing..." (pure [])
somex v = (:) <$> v <*> manyx v
parseExpr = symb
(oops "no input" $ pure (Inserted '?'))
-- empty
(\c ->case c of
'(' -> S <$> many parseExpr <*> closing ')'
')' -> oops ("unmatched )") $ pure $ Deleted ')'
c -> pure $ Atom c)
closing close = symb
(oops "not closed" $ pure Nothing)
-- empty
(\c ->if c == close then pure (Just ')')
else oops ("closed with: " ++ show c) $ pure (Just c)
)
eof' = symb (pure ()) (\_ -> oops "eof expected!" eof')
test = mkProcess (parseExpr <* eof')
| null | https://raw.githubusercontent.com/jyp/topics/8442d82711a02ba1356fd4eca598d1368684fa69/FunctionalIncrementalParsing/Example0.hs | haskell | ----------------------------------------------------------
Examples
the only place we use disjunction is in many.
empty
empty | import Parsers.Incremental
import Control.Applicative
data SExpr = S [SExpr] (Maybe Char)
| Atom Char
| Quoted [SExpr] (Maybe Char)
| Inserted Char
| Deleted Char
deriving Show
symb n c = Look (Shif n) (Shif . c)
manyx v = some v <|> oops "closing..." (pure [])
somex v = (:) <$> v <*> manyx v
parseExpr = symb
(oops "no input" $ pure (Inserted '?'))
(\c ->case c of
'(' -> S <$> many parseExpr <*> closing ')'
')' -> oops ("unmatched )") $ pure $ Deleted ')'
c -> pure $ Atom c)
closing close = symb
(oops "not closed" $ pure Nothing)
(\c ->if c == close then pure (Just ')')
else oops ("closed with: " ++ show c) $ pure (Just c)
)
eof' = symb (pure ()) (\_ -> oops "eof expected!" eof')
test = mkProcess (parseExpr <* eof')
|
4ec610a2ef1c92911db085961922f8b11004c052dad4d6f11b313863e959731b | BranchTaken/Hemlock | test_filter_map.ml | open! Basis.Rudiments
open! Basis
open! OrdmapTest
open Ordmap
let test () =
let test arr = begin
let ordmap = of_karray arr in
let ordmap' = filter_map ordmap ~f:(fun (k, v) ->
match k % 2L = 0L with
| true -> Some (Uns.to_string v)
| false -> None
) in
let arr' = to_array ordmap' in
File.Fmt.stdout
|> (Array.pp Uns.pp) arr
|> Fmt.fmt " -> "
|> (Array.pp (pp_kv_pair String.pp)) arr'
|> Fmt.fmt "\n"
|> ignore
end in
Range.Uns.iter (0L =:< 7L) ~f:(fun n ->
let arr = Array.init (0L =:< n) ~f:(fun i -> i) in
test arr
)
let _ = test ()
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/ed397cf3294ca397024e69eb3b1ed5f1db773db6/bootstrap/test/basis/ordmap/test_filter_map.ml | ocaml | open! Basis.Rudiments
open! Basis
open! OrdmapTest
open Ordmap
let test () =
let test arr = begin
let ordmap = of_karray arr in
let ordmap' = filter_map ordmap ~f:(fun (k, v) ->
match k % 2L = 0L with
| true -> Some (Uns.to_string v)
| false -> None
) in
let arr' = to_array ordmap' in
File.Fmt.stdout
|> (Array.pp Uns.pp) arr
|> Fmt.fmt " -> "
|> (Array.pp (pp_kv_pair String.pp)) arr'
|> Fmt.fmt "\n"
|> ignore
end in
Range.Uns.iter (0L =:< 7L) ~f:(fun n ->
let arr = Array.init (0L =:< n) ~f:(fun i -> i) in
test arr
)
let _ = test ()
| |
b20a580d6c33c167365eff80b87f388923f2893da5bf39da04360aa8486fd6c1 | azimut/shiny | incudine-env.lisp | somecepl.lisp
(in-package #:shiny)
;;; "somecepl" goes here. Hacks and glory await!
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defvar *env1* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! (- vert (v2! .4) ) 0 1))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(v4! 1.0))
(defpipeline-g draw-verts-pipeline (:points)
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport)))
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
;; (when *env1*
;; (incudine:free *env1*))
( setf * env1 *
;; (make-envelope '(0 1 0) '(.2 .8) :curve :exp))
( setf * gpu - verts - arr *
( make - gpu - array ( loop for beats below 0.99 by .001 collect ( v ! beats ( coerce ( envelope - at * env1 * beats ) ' single - float ) ) )
;; :element-type :vec2))
(setf *env1*
(make-perc .001 .4))
(setf *gpu-verts-arr*
(make-gpu-array
(loop for beats below 0.39 by .001
collect
(v! beats (coerce (envelope-at *env1* beats) 'single-float)))
:element-type :vec2))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:primitive :points)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/examples/incudine-env.lisp | lisp | "somecepl" goes here. Hacks and glory await!
(when *env1*
(incudine:free *env1*))
(make-envelope '(0 1 0) '(.2 .8) :curve :exp))
:element-type :vec2)) | somecepl.lisp
(in-package #:shiny)
(defvar *gpu-verts-arr* nil)
(defvar *gpu-index-arr* nil)
(defvar *vert-stream* nil)
(defvar *env1* nil)
(defun-g draw-verts-vert-stage ((vert :vec2))
(v! (- vert (v2! .4) ) 0 1))
(defun-g draw-verts-frag-stage (&uniform (resolution :vec2))
(v4! 1.0))
(defpipeline-g draw-verts-pipeline (:points)
:vertex (draw-verts-vert-stage :vec2)
:fragment (draw-verts-frag-stage))
(defun draw! ()
(step-host)
(setf (resolution (current-viewport))
(surface-resolution (current-surface *cepl-context*)))
(clear)
(map-g #'draw-verts-pipeline *vert-stream*
:resolution (viewport-resolution (current-viewport)))
(swap))
(defun init ()
(when *gpu-verts-arr*
(free *gpu-verts-arr*))
(when *gpu-index-arr*
(free *gpu-index-arr*))
(when *vert-stream*
(free *vert-stream*))
( setf * env1 *
( setf * gpu - verts - arr *
( make - gpu - array ( loop for beats below 0.99 by .001 collect ( v ! beats ( coerce ( envelope - at * env1 * beats ) ' single - float ) ) )
(setf *env1*
(make-perc .001 .4))
(setf *gpu-verts-arr*
(make-gpu-array
(loop for beats below 0.39 by .001
collect
(v! beats (coerce (envelope-at *env1* beats) 'single-float)))
:element-type :vec2))
(setf *vert-stream*
(make-buffer-stream *gpu-verts-arr*
:primitive :points)))
(def-simple-main-loop play (:on-start #'init)
(draw!))
|
8ba013439d1c236824b484574041a72caeff296ed2cb0d5c0f8b0f9df444b20f | conscell/hugs-android | Unlit.hs | -----------------------------------------------------------------------------
-- |
Module : Distribution . PreProcess .
-- Copyright : ...
--
Maintainer : < >
-- Stability : Stable
-- Portability : portable
--
Remove the \"literal\ " markups from a Haskell source file , including
\"@>@\ " , " , \"@\\end{code}@\ " , and \"@#@\ "
--
-- Part of the following code is from
-- /Report on the Programming Language Haskell/,
version 1.2 , appendix C.
module Distribution.PreProcess.Unlit(unlit,plain) where
import Data.Char
-- exports:
unlit :: String -> String -> String
unlit file lhs = (unlines . map unclassify . adjacent file (0::Int) Blank
. classify 0) (tolines lhs)
plain :: String -> String -> String -- no unliteration
plain _ hs = hs
----
data Classified = Program String | Blank | Comment
| Include Int String | Pre String
classify :: Int -> [String] -> [Classified]
classify _ [] = []
classify _ (('\\':x):xs) | x == "begin{code}" = Blank : allProg xs
where allProg [] = [] -- Should give an error message, but I have no
-- good position information.
allProg (('\\':x'):xs') | x' == "end{code}" = Blank : classify 0 xs'
allProg (x':xs') = Program x':allProg xs'
classify 0 (('>':x):xs) = let (sp,code) = span isSpace x in
Program code : classify (length sp + 1) xs
classify n (('>':x):xs) = Program (drop (n-1) x) : classify n xs
classify _ (('#':x):xs) =
(case words x of
(line:file:_) | all isDigit line -> Include (read line) file
_ -> Pre x
) : classify 0 xs
classify _ (x:xs) | all isSpace x = Blank:classify 0 xs
classify _ (_:xs) = Comment:classify 0 xs
unclassify :: Classified -> String
unclassify (Program s) = s
unclassify (Pre s) = '#':s
unclassify (Include i f) = '#':' ':show i ++ ' ':f
unclassify Blank = ""
unclassify Comment = ""
adjacent :: String -> Int -> Classified -> [Classified] -> [Classified]
adjacent file 0 _ (x :xs) = x: adjacent file 1 x xs
-- force evaluation of line number
adjacent file n (Program _) (Comment :_) =
error (message file n "program" "comment")
adjacent _ _ y@(Program _) (x@(Include i f):xs) = x: adjacent f i y xs
adjacent file n y@(Program _) (x@(Pre _) :xs) = x: adjacent file (n+1) y xs
adjacent file n Comment ((Program _) :_) =
error (message file n "comment" "program")
adjacent _ _ y@Comment (x@(Include i f):xs) = x: adjacent f i y xs
adjacent file n y@Comment (x@(Pre _) :xs) = x: adjacent file (n+1) y xs
adjacent _ _ y@Blank (x@(Include i f):xs) = x: adjacent f i y xs
adjacent file n y@Blank (x@(Pre _) :xs) = x: adjacent file (n+1) y xs
adjacent file n _ (x :xs) = x: adjacent file (n+1) x xs
adjacent _ _ _ [] = []
message :: (Show a) => String -> a -> String -> String -> String
message "\"\"" n p c = "Line "++show n++": "++p++ " line before "++c++" line.\n"
message [] n p c = "Line "++show n++": "++p++ " line before "++c++" line.\n"
message file n p c = "In file " ++ file ++ " at line "
++show n++": "++p++ " line before "++c++" line.\n"
-- Re-implementation of 'lines', for better efficiency (but decreased
laziness ) . Also , importantly , accepts non - standard DOS and Mac line
-- ending characters.
tolines :: String -> [String]
tolines s' = lines' s' id
where
lines' [] acc = [acc []]
lines' ('\^M':'\n':s) acc = acc [] : lines' s id -- DOS
MacOS
lines' ('\n':s) acc = acc [] : lines' s id -- Unix
lines' (c:s) acc = lines' s (acc . (c:))
-- A very naive version of unliteration ....
module Unlit(unlit ) where
-- This version does not handle \begin{code } & \end{code } , and it is
-- careless with indentation .
unlit = map unlitline
unlitline ( ' > ' : s ) = s
unlitline _ = " "
-- A very naive version of unliteration....
module Unlit(unlit) where
-- This version does not handle \begin{code} & \end{code}, and it is
-- careless with indentation.
unlit = map unlitline
unlitline ('>' : s) = s
unlitline _ = ""
-}
| null | https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/packages/Cabal/Distribution/PreProcess/Unlit.hs | haskell | ---------------------------------------------------------------------------
|
Copyright : ...
Stability : Stable
Portability : portable
Part of the following code is from
/Report on the Programming Language Haskell/,
exports:
no unliteration
--
Should give an error message, but I have no
good position information.
force evaluation of line number
Re-implementation of 'lines', for better efficiency (but decreased
ending characters.
DOS
Unix
A very naive version of unliteration ....
This version does not handle \begin{code } & \end{code } , and it is
careless with indentation .
A very naive version of unliteration....
This version does not handle \begin{code} & \end{code}, and it is
careless with indentation. | Module : Distribution . PreProcess .
Maintainer : < >
Remove the \"literal\ " markups from a Haskell source file , including
\"@>@\ " , " , \"@\\end{code}@\ " , and \"@#@\ "
version 1.2 , appendix C.
module Distribution.PreProcess.Unlit(unlit,plain) where
import Data.Char
unlit :: String -> String -> String
unlit file lhs = (unlines . map unclassify . adjacent file (0::Int) Blank
. classify 0) (tolines lhs)
plain _ hs = hs
data Classified = Program String | Blank | Comment
| Include Int String | Pre String
classify :: Int -> [String] -> [Classified]
classify _ [] = []
classify _ (('\\':x):xs) | x == "begin{code}" = Blank : allProg xs
allProg (('\\':x'):xs') | x' == "end{code}" = Blank : classify 0 xs'
allProg (x':xs') = Program x':allProg xs'
classify 0 (('>':x):xs) = let (sp,code) = span isSpace x in
Program code : classify (length sp + 1) xs
classify n (('>':x):xs) = Program (drop (n-1) x) : classify n xs
classify _ (('#':x):xs) =
(case words x of
(line:file:_) | all isDigit line -> Include (read line) file
_ -> Pre x
) : classify 0 xs
classify _ (x:xs) | all isSpace x = Blank:classify 0 xs
classify _ (_:xs) = Comment:classify 0 xs
unclassify :: Classified -> String
unclassify (Program s) = s
unclassify (Pre s) = '#':s
unclassify (Include i f) = '#':' ':show i ++ ' ':f
unclassify Blank = ""
unclassify Comment = ""
adjacent :: String -> Int -> Classified -> [Classified] -> [Classified]
adjacent file 0 _ (x :xs) = x: adjacent file 1 x xs
adjacent file n (Program _) (Comment :_) =
error (message file n "program" "comment")
adjacent _ _ y@(Program _) (x@(Include i f):xs) = x: adjacent f i y xs
adjacent file n y@(Program _) (x@(Pre _) :xs) = x: adjacent file (n+1) y xs
adjacent file n Comment ((Program _) :_) =
error (message file n "comment" "program")
adjacent _ _ y@Comment (x@(Include i f):xs) = x: adjacent f i y xs
adjacent file n y@Comment (x@(Pre _) :xs) = x: adjacent file (n+1) y xs
adjacent _ _ y@Blank (x@(Include i f):xs) = x: adjacent f i y xs
adjacent file n y@Blank (x@(Pre _) :xs) = x: adjacent file (n+1) y xs
adjacent file n _ (x :xs) = x: adjacent file (n+1) x xs
adjacent _ _ _ [] = []
message :: (Show a) => String -> a -> String -> String -> String
message "\"\"" n p c = "Line "++show n++": "++p++ " line before "++c++" line.\n"
message [] n p c = "Line "++show n++": "++p++ " line before "++c++" line.\n"
message file n p c = "In file " ++ file ++ " at line "
++show n++": "++p++ " line before "++c++" line.\n"
laziness ) . Also , importantly , accepts non - standard DOS and Mac line
tolines :: String -> [String]
tolines s' = lines' s' id
where
lines' [] acc = [acc []]
MacOS
lines' (c:s) acc = lines' s (acc . (c:))
module Unlit(unlit ) where
unlit = map unlitline
unlitline ( ' > ' : s ) = s
unlitline _ = " "
module Unlit(unlit) where
unlit = map unlitline
unlitline ('>' : s) = s
unlitline _ = ""
-}
|
ed97fe1527dc8a1f37321f81720ee379a3e1341be166949026d9eb67a3554cb4 | knupfer/type-of-html | Obsolete.hs | # OPTIONS_GHC -fno - warn - unticked - promoted - constructors #
# LANGUAGE TypeOperators #
# LANGUAGE TypeFamilies #
# LANGUAGE DataKinds #
module Html.Obsolete
( module Html.Obsolete
, module Html.Type
) where
import Html.Type
-- | Obsolete html elements.
--
-- Usage:
--
-- >>> Center :> "barf"
-- <center>barf</center>
data instance Element
"applet"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Applet
data instance Element
"acronym"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Acronym
data instance Element
"bgsound"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Bgsound
data instance Element
"dir"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Dir
data instance Element
"frame"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Frame
data instance Element
"frameset"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Frameset
data instance Element
"noframes"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Noframes
data instance Element
"isindex"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Isindex
data instance Element
"keygen"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Keygen
data instance Element
"listing"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Listing
data instance Element
"menuitem"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Menuitem
data instance Element
"nextid"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Nextid
data instance Element
"noembed"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Noembed
data instance Element
"plaintext"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Plaintext
data instance Element
"rb"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Rb
data instance Element
"rtc"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Rtc
data instance Element
"strike"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Strike
data instance Element
"xmp"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Xmp
data instance Element
"basefont"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Basefont
data instance Element
"big"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Big
data instance Element
"blink"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Blink
data instance Element
"center"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Center
data instance Element
"font"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Font
data instance Element
"marquee"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Marquee
data instance Element
"multicol"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Multicol
data instance Element
"nobr"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Nobr
data instance Element
"spacer"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Spacer
data instance Element
"tt"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Tt
| null | https://raw.githubusercontent.com/knupfer/type-of-html/eb89e30fcf5ab43103e0382f2521e715380d82eb/src/Html/Obsolete.hs | haskell | | Obsolete html elements.
Usage:
>>> Center :> "barf"
<center>barf</center> | # OPTIONS_GHC -fno - warn - unticked - promoted - constructors #
# LANGUAGE TypeOperators #
# LANGUAGE TypeFamilies #
# LANGUAGE DataKinds #
module Html.Obsolete
( module Html.Obsolete
, module Html.Type
) where
import Html.Type
data instance Element
"applet"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Applet
data instance Element
"acronym"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Acronym
data instance Element
"bgsound"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Bgsound
data instance Element
"dir"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Dir
data instance Element
"frame"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Frame
data instance Element
"frameset"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Frameset
data instance Element
"noframes"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Noframes
data instance Element
"isindex"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Isindex
data instance Element
"keygen"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Keygen
data instance Element
"listing"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Listing
data instance Element
"menuitem"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Menuitem
data instance Element
"nextid"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Nextid
data instance Element
"noembed"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Noembed
data instance Element
"plaintext"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Plaintext
data instance Element
"rb"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Rb
data instance Element
"rtc"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Rtc
data instance Element
"strike"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Strike
data instance Element
"xmp"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Xmp
data instance Element
"basefont"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Basefont
data instance Element
"big"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Big
data instance Element
"blink"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Blink
data instance Element
"center"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Center
data instance Element
"font"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Font
data instance Element
"marquee"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Marquee
data instance Element
"multicol"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Multicol
data instance Element
"nobr"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Nobr
data instance Element
"spacer"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Spacer
data instance Element
"tt"
'[Metadata, Flow, Sectioning, Heading, Phrasing, Embedded, Interactive, Palpable, Scripting]
(Metadata :|: Flow :|: Sectioning :|: Heading :|: Phrasing :|: Embedded :|: Interactive :|: Palpable :|: Scripting)
'[]
= Tt
|
0fa600a8033045e95fbec4550ff58135f6ba24d5dbf6e2c9918effeb3d2b5fe6 | aeternity/enoise | enoise_connection.erl | %%% ------------------------------------------------------------------
2018 , Aeternity Anstalt
%%%
%%% @doc Module implementing a gen_server for holding a handshaked
%%% Noise connection over gen_tcp.
%%%
%%% Some care is needed since the underlying transmission is broken up
%%% into Noise packets, so we need some buffering.
%%%
%%% @end
%%% ------------------------------------------------------------------
-module(enoise_connection).
-export([ controlling_process/2
, close/1
, send/2
, set_active/2
, start_link/5
]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(enoise, { pid }).
-record(state, {rx, tx, owner, owner_ref, tcp_sock, active, msgbuf = [], rawbuf = <<>>}).
%% -- API --------------------------------------------------------------------
start_link(TcpSock, Rx, Tx, Owner, {Active0, Buf}) ->
Active = case Active0 of
true -> true;
once -> {once, false}
end,
State = #state{ rx = Rx, tx = Tx, owner = Owner,
tcp_sock = TcpSock, active = Active },
case gen_server:start_link(?MODULE, [State], []) of
{ok, Pid} ->
case gen_tcp:controlling_process(TcpSock, Pid) of
ok ->
%% Changing controlling process require a bit of
%% fiddling with already received and delivered content...
[ Pid ! {tcp, TcpSock, Buf} || Buf /= <<>> ],
flush_tcp(Pid, TcpSock),
{ok, Pid};
Err = {error, _} ->
close(Pid),
Err
end;
Err = {error, _} ->
Err
end.
-spec send(Noise :: pid(), Data :: binary()) -> ok | {error, term()}.
send(Noise, Data) ->
gen_server:call(Noise, {send, Data}).
-spec set_active(Noise :: pid(), Active :: true | once) -> ok | {error, term()}.
set_active(Noise, Active) ->
gen_server:call(Noise, {active, self(), Active}).
-spec close(Noise :: pid()) -> ok | {error, term()}.
close(Noise) ->
gen_server:call(Noise, close).
-spec controlling_process(Noise :: pid(), NewPid :: pid()) -> ok | {error, term()}.
controlling_process(Noise, NewPid) ->
gen_server:call(Noise, {controlling_process, self(), NewPid}, 100).
%% -- gen_server callbacks ---------------------------------------------------
init([#state{owner = Owner} = State]) ->
OwnerRef = erlang:monitor(process, Owner),
{ok, State#state{owner_ref = OwnerRef}}.
handle_call(close, _From, S) ->
{stop, normal, ok, S};
handle_call(_Call, _From, S = #state{ tcp_sock = closed }) ->
{reply, {error, closed}, S};
handle_call({send, Data}, _From, S) ->
{Res, S1} = handle_send(S, Data),
{reply, Res, S1};
handle_call({controlling_process, OldPid, NewPid}, _From, S) ->
{Res, S1} = handle_control_change(S, OldPid, NewPid),
{reply, Res, S1};
handle_call({active, Pid, NewActive}, _From, S) ->
{Res, S1} = handle_active(S, Pid, NewActive),
{reply, Res, S1}.
handle_cast(_Msg, S) ->
{noreply, S}.
handle_info({tcp, TS, Data}, S = #state{ tcp_sock = TS, owner = O }) ->
try
{S1, Msgs} = handle_data(S, Data),
S2 = handle_msgs(S1#state{ msgbuf = S1#state.msgbuf ++ Msgs }),
set_active(S2),
{noreply, S2}
catch error:{enoise_error, _} ->
%% We are not likely to recover, but leave the decision to upstream
O ! {enoise_error, TS, decrypt_error},
{noreply, S}
end;
handle_info({tcp_closed, TS}, S = #state{ tcp_sock = TS, owner = O }) ->
O ! {tcp_closed, TS},
{noreply, S#state{ tcp_sock = closed }};
handle_info({'DOWN', OwnerRef, process, _, normal},
S = #state { tcp_sock = TS, owner_ref = OwnerRef }) ->
close_tcp(TS),
{stop, normal, S#state{ tcp_sock = closed, owner_ref = undefined }};
handle_info({'DOWN', _, _, _, _}, S) ->
%% Ignore non-normal monitor messages - we are linked.
{noreply, S};
handle_info(_Msg, S) ->
{noreply, S}.
terminate(_Reason, #state{ tcp_sock = TcpSock, owner_ref = ORef }) ->
[ gen_tcp:close(TcpSock) || TcpSock /= closed ],
[ erlang:demonitor(ORef, [flush]) || ORef /= undefined ],
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% -- Local functions --------------------------------------------------------
handle_control_change(S = #state{ owner = Pid, owner_ref = OldRef }, Pid, NewPid) ->
NewRef = erlang:monitor(process, NewPid),
erlang:demonitor(OldRef, [flush]),
{ok, S#state{ owner = NewPid, owner_ref = NewRef }};
handle_control_change(S, _OldPid, _NewPid) ->
{{error, not_owner}, S}.
handle_active(S = #state{ owner = Pid, tcp_sock = TcpSock }, Pid, Active) ->
case Active of
true ->
inet:setopts(TcpSock, [{active, true}]),
{ok, handle_msgs(S#state{ active = true })};
once ->
S1 = handle_msgs(S#state{ active = {once, false} }),
set_active(S1),
{ok, S1}
end;
handle_active(S, _Pid, _NewActive) ->
{{error, not_owner}, S}.
handle_data(S = #state{ rawbuf = Buf, rx = Rx }, Data) ->
case <<Buf/binary, Data/binary>> of
B = <<Len:16, Rest/binary>> when Len > byte_size(Rest) ->
{S#state{ rawbuf = B }, []}; %% Not a full Noise message - save it
<<Len:16, Rest/binary>> ->
<<Msg:Len/binary, Rest2/binary>> = Rest,
case enoise_cipher_state:decrypt_with_ad(Rx, <<>>, Msg) of
{ok, Rx1, Msg1} ->
{S1, Msgs} = handle_data(S#state{ rawbuf = Rest2, rx = Rx1 }, <<>>),
{S1, [Msg1 | Msgs]};
{error, _} ->
error({enoise_error, decrypt_input_failed})
end;
EmptyOrSingleByte ->
{S#state{ rawbuf = EmptyOrSingleByte }, []}
end.
handle_msgs(S = #state{ msgbuf = [] }) ->
S;
handle_msgs(S = #state{ msgbuf = Msgs, active = true, owner = Owner }) ->
[ Owner ! {noise, #enoise{ pid = self() }, Msg} || Msg <- Msgs ],
S#state{ msgbuf = [] };
handle_msgs(S = #state{ msgbuf = [Msg | Msgs], active = {once, Delivered}, owner = Owner }) ->
case Delivered of
true ->
S;
false ->
Owner ! {noise, #enoise{ pid = self() }, Msg},
S#state{ msgbuf = Msgs, active = {once, true} }
end.
handle_send(S = #state{ tcp_sock = TcpSock, tx = Tx }, Data) ->
{ok, Tx1, Msg} = enoise_cipher_state:encrypt_with_ad(Tx, <<>>, Data),
case gen_tcp:send(TcpSock, <<(byte_size(Msg)):16, Msg/binary>>) of
ok -> {ok, S#state{ tx = Tx1 }};
Err = {error, _} -> {Err, S}
end.
set_active(#state{ msgbuf = [], active = {once, _}, tcp_sock = TcpSock }) ->
inet:setopts(TcpSock, [{active, once}]);
set_active(_) ->
ok.
flush_tcp(Pid, TcpSock) ->
receive {tcp, TcpSock, Data} ->
Pid ! {tcp, TcpSock, Data},
flush_tcp(Pid, TcpSock)
after 1 -> ok
end.
close_tcp(closed) ->
ok;
close_tcp(Sock) ->
gen_tcp:close(Sock).
| null | https://raw.githubusercontent.com/aeternity/enoise/991d7390ea49216f0b170d7b9662b3ff0a925aaa/src/enoise_connection.erl | erlang | ------------------------------------------------------------------
@doc Module implementing a gen_server for holding a handshaked
Noise connection over gen_tcp.
Some care is needed since the underlying transmission is broken up
into Noise packets, so we need some buffering.
@end
------------------------------------------------------------------
gen_server callbacks
-- API --------------------------------------------------------------------
Changing controlling process require a bit of
fiddling with already received and delivered content...
-- gen_server callbacks ---------------------------------------------------
We are not likely to recover, but leave the decision to upstream
Ignore non-normal monitor messages - we are linked.
-- Local functions --------------------------------------------------------
Not a full Noise message - save it | 2018 , Aeternity Anstalt
-module(enoise_connection).
-export([ controlling_process/2
, close/1
, send/2
, set_active/2
, start_link/5
]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(enoise, { pid }).
-record(state, {rx, tx, owner, owner_ref, tcp_sock, active, msgbuf = [], rawbuf = <<>>}).
start_link(TcpSock, Rx, Tx, Owner, {Active0, Buf}) ->
Active = case Active0 of
true -> true;
once -> {once, false}
end,
State = #state{ rx = Rx, tx = Tx, owner = Owner,
tcp_sock = TcpSock, active = Active },
case gen_server:start_link(?MODULE, [State], []) of
{ok, Pid} ->
case gen_tcp:controlling_process(TcpSock, Pid) of
ok ->
[ Pid ! {tcp, TcpSock, Buf} || Buf /= <<>> ],
flush_tcp(Pid, TcpSock),
{ok, Pid};
Err = {error, _} ->
close(Pid),
Err
end;
Err = {error, _} ->
Err
end.
-spec send(Noise :: pid(), Data :: binary()) -> ok | {error, term()}.
send(Noise, Data) ->
gen_server:call(Noise, {send, Data}).
-spec set_active(Noise :: pid(), Active :: true | once) -> ok | {error, term()}.
set_active(Noise, Active) ->
gen_server:call(Noise, {active, self(), Active}).
-spec close(Noise :: pid()) -> ok | {error, term()}.
close(Noise) ->
gen_server:call(Noise, close).
-spec controlling_process(Noise :: pid(), NewPid :: pid()) -> ok | {error, term()}.
controlling_process(Noise, NewPid) ->
gen_server:call(Noise, {controlling_process, self(), NewPid}, 100).
init([#state{owner = Owner} = State]) ->
OwnerRef = erlang:monitor(process, Owner),
{ok, State#state{owner_ref = OwnerRef}}.
handle_call(close, _From, S) ->
{stop, normal, ok, S};
handle_call(_Call, _From, S = #state{ tcp_sock = closed }) ->
{reply, {error, closed}, S};
handle_call({send, Data}, _From, S) ->
{Res, S1} = handle_send(S, Data),
{reply, Res, S1};
handle_call({controlling_process, OldPid, NewPid}, _From, S) ->
{Res, S1} = handle_control_change(S, OldPid, NewPid),
{reply, Res, S1};
handle_call({active, Pid, NewActive}, _From, S) ->
{Res, S1} = handle_active(S, Pid, NewActive),
{reply, Res, S1}.
handle_cast(_Msg, S) ->
{noreply, S}.
handle_info({tcp, TS, Data}, S = #state{ tcp_sock = TS, owner = O }) ->
try
{S1, Msgs} = handle_data(S, Data),
S2 = handle_msgs(S1#state{ msgbuf = S1#state.msgbuf ++ Msgs }),
set_active(S2),
{noreply, S2}
catch error:{enoise_error, _} ->
O ! {enoise_error, TS, decrypt_error},
{noreply, S}
end;
handle_info({tcp_closed, TS}, S = #state{ tcp_sock = TS, owner = O }) ->
O ! {tcp_closed, TS},
{noreply, S#state{ tcp_sock = closed }};
handle_info({'DOWN', OwnerRef, process, _, normal},
S = #state { tcp_sock = TS, owner_ref = OwnerRef }) ->
close_tcp(TS),
{stop, normal, S#state{ tcp_sock = closed, owner_ref = undefined }};
handle_info({'DOWN', _, _, _, _}, S) ->
{noreply, S};
handle_info(_Msg, S) ->
{noreply, S}.
terminate(_Reason, #state{ tcp_sock = TcpSock, owner_ref = ORef }) ->
[ gen_tcp:close(TcpSock) || TcpSock /= closed ],
[ erlang:demonitor(ORef, [flush]) || ORef /= undefined ],
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
handle_control_change(S = #state{ owner = Pid, owner_ref = OldRef }, Pid, NewPid) ->
NewRef = erlang:monitor(process, NewPid),
erlang:demonitor(OldRef, [flush]),
{ok, S#state{ owner = NewPid, owner_ref = NewRef }};
handle_control_change(S, _OldPid, _NewPid) ->
{{error, not_owner}, S}.
handle_active(S = #state{ owner = Pid, tcp_sock = TcpSock }, Pid, Active) ->
case Active of
true ->
inet:setopts(TcpSock, [{active, true}]),
{ok, handle_msgs(S#state{ active = true })};
once ->
S1 = handle_msgs(S#state{ active = {once, false} }),
set_active(S1),
{ok, S1}
end;
handle_active(S, _Pid, _NewActive) ->
{{error, not_owner}, S}.
handle_data(S = #state{ rawbuf = Buf, rx = Rx }, Data) ->
case <<Buf/binary, Data/binary>> of
B = <<Len:16, Rest/binary>> when Len > byte_size(Rest) ->
<<Len:16, Rest/binary>> ->
<<Msg:Len/binary, Rest2/binary>> = Rest,
case enoise_cipher_state:decrypt_with_ad(Rx, <<>>, Msg) of
{ok, Rx1, Msg1} ->
{S1, Msgs} = handle_data(S#state{ rawbuf = Rest2, rx = Rx1 }, <<>>),
{S1, [Msg1 | Msgs]};
{error, _} ->
error({enoise_error, decrypt_input_failed})
end;
EmptyOrSingleByte ->
{S#state{ rawbuf = EmptyOrSingleByte }, []}
end.
handle_msgs(S = #state{ msgbuf = [] }) ->
S;
handle_msgs(S = #state{ msgbuf = Msgs, active = true, owner = Owner }) ->
[ Owner ! {noise, #enoise{ pid = self() }, Msg} || Msg <- Msgs ],
S#state{ msgbuf = [] };
handle_msgs(S = #state{ msgbuf = [Msg | Msgs], active = {once, Delivered}, owner = Owner }) ->
case Delivered of
true ->
S;
false ->
Owner ! {noise, #enoise{ pid = self() }, Msg},
S#state{ msgbuf = Msgs, active = {once, true} }
end.
handle_send(S = #state{ tcp_sock = TcpSock, tx = Tx }, Data) ->
{ok, Tx1, Msg} = enoise_cipher_state:encrypt_with_ad(Tx, <<>>, Data),
case gen_tcp:send(TcpSock, <<(byte_size(Msg)):16, Msg/binary>>) of
ok -> {ok, S#state{ tx = Tx1 }};
Err = {error, _} -> {Err, S}
end.
set_active(#state{ msgbuf = [], active = {once, _}, tcp_sock = TcpSock }) ->
inet:setopts(TcpSock, [{active, once}]);
set_active(_) ->
ok.
flush_tcp(Pid, TcpSock) ->
receive {tcp, TcpSock, Data} ->
Pid ! {tcp, TcpSock, Data},
flush_tcp(Pid, TcpSock)
after 1 -> ok
end.
close_tcp(closed) ->
ok;
close_tcp(Sock) ->
gen_tcp:close(Sock).
|
6adb5dffadcac101fc728f262dab029087a96646d7c8673db1e69109d6131353 | phoe/petri | threaded.lisp | ;;;; threaded.lisp
(uiop:define-package #:petri/threaded
(:mix #:closer-mop
#:cl
#:alexandria
#:split-sequence
#:phoe-toolbox/bag
#:trivial-backtrace
#:petri)
(:reexport #:phoe-toolbox/bag)
(:export ;; ASYNC
#:threaded-petri-net
#:make-threaded-petri-net
#:threaded-petri-net-error))
(in-package #:petri/threaded)
;;; THREADED
(defclass threaded-petri-net (petri-net)
((%lock :reader lock-of
:initform (bt:make-lock))
(%thread-queue :reader thread-queue
:initform (lparallel.queue:make-queue)))
(:metaclass closer-mop:funcallable-standard-class))
(defmethod petri::petri-net-transition-constructor
((petri-net threaded-petri-net))
#'make-threaded-transition)
(defmethod petri::make-petri-net-funcallable-function
((petri-net threaded-petri-net))
(named-lambda execute-threaded-petri-net
(&optional (compress t) ignore-errors)
(bt:with-lock-held ((lock-of petri-net))
(spawn-transitions petri-net))
(let ((errorp (join-all-threads petri-net ignore-errors)))
(when compress
(dolist (bag (hash-table-values (petri::bags petri-net)))
(bag-compress bag)))
(values petri-net errorp))))
(defun spawn-transitions (petri-net)
(flet ((spawn ()
(when-let ((transition (petri::find-ready-transition petri-net)))
(let ((input (petri::populate-input transition petri-net t)))
(bt:make-thread (curry transition input petri-net))))))
(loop with queue = (thread-queue petri-net)
for thread = (spawn)
while thread do (lparallel.queue:push-queue thread queue))))
(defun join-all-threads (petri-net ignore-errors)
(loop with errorp = nil
with queue = (thread-queue petri-net)
for thread = (lparallel.queue:try-pop-queue queue)
while thread
do (multiple-value-bind (condition backtrace) (bt:join-thread thread)
(cond ((not (typep condition 'condition)))
(ignore-errors (setf errorp t))
(t (threaded-petri-net-error condition backtrace))))
finally (return errorp)))
(defclass threaded-transition (petri::transition) ()
(:metaclass closer-mop:funcallable-standard-class))
(defmacro with-threaded-petri-net-handler ((condition backtrace) &body body)
(with-gensyms (e)
`(block nil
(handler-bind
((error (lambda (,e)
(setf ,condition ,e
,backtrace (print-backtrace ,e :output nil))
(return))))
,@body))))
(defmethod petri::make-transition-funcallable-function
((transition threaded-transition))
(named-lambda execute-threaded-transition (input petri-net)
(let (condition
backtrace
(output (petri::make-output-hash-table transition)))
(with-threaded-petri-net-handler (condition backtrace)
(petri::call-callback transition input output))
(unless condition
(with-threaded-petri-net-handler (condition backtrace)
(bt:with-lock-held ((lock-of petri-net))
(petri::populate-output transition petri-net output)
(spawn-transitions petri-net))))
(values condition backtrace))))
(defun make-threaded-transition (from to callback)
(petri::make-transition from to callback 'threaded-transition))
(defun make-threaded-petri-net (bags transitions)
(make-instance 'threaded-petri-net :bags bags :transitions transitions))
(defmacro threaded-petri-net (() &body forms)
`(petri::%petri-net #'make-threaded-petri-net ,@forms))
(define-condition threaded-petri-net-error (petri-net-error)
((%reason :reader reason
:initarg :reason
:initform (required-argument :reason))
(%backtrace :reader backtrace
:initarg :backtrace
:initform nil))
(:report (lambda (condition stream)
(format stream "Error while executing the threaded Petri net:~%~A
Backtrace: ~A" (reason condition) (backtrace condition)))))
(defun threaded-petri-net-error (reason backtrace)
(cerror "Continue executing the Petri net." 'threaded-petri-net-error
:reason reason :backtrace backtrace))
| null | https://raw.githubusercontent.com/phoe/petri/08e3a925d629e82bb2151acbecbf52d3b8be105f/threaded.lisp | lisp | threaded.lisp
ASYNC
THREADED |
(uiop:define-package #:petri/threaded
(:mix #:closer-mop
#:cl
#:alexandria
#:split-sequence
#:phoe-toolbox/bag
#:trivial-backtrace
#:petri)
(:reexport #:phoe-toolbox/bag)
#:threaded-petri-net
#:make-threaded-petri-net
#:threaded-petri-net-error))
(in-package #:petri/threaded)
(defclass threaded-petri-net (petri-net)
((%lock :reader lock-of
:initform (bt:make-lock))
(%thread-queue :reader thread-queue
:initform (lparallel.queue:make-queue)))
(:metaclass closer-mop:funcallable-standard-class))
(defmethod petri::petri-net-transition-constructor
((petri-net threaded-petri-net))
#'make-threaded-transition)
(defmethod petri::make-petri-net-funcallable-function
((petri-net threaded-petri-net))
(named-lambda execute-threaded-petri-net
(&optional (compress t) ignore-errors)
(bt:with-lock-held ((lock-of petri-net))
(spawn-transitions petri-net))
(let ((errorp (join-all-threads petri-net ignore-errors)))
(when compress
(dolist (bag (hash-table-values (petri::bags petri-net)))
(bag-compress bag)))
(values petri-net errorp))))
(defun spawn-transitions (petri-net)
(flet ((spawn ()
(when-let ((transition (petri::find-ready-transition petri-net)))
(let ((input (petri::populate-input transition petri-net t)))
(bt:make-thread (curry transition input petri-net))))))
(loop with queue = (thread-queue petri-net)
for thread = (spawn)
while thread do (lparallel.queue:push-queue thread queue))))
(defun join-all-threads (petri-net ignore-errors)
(loop with errorp = nil
with queue = (thread-queue petri-net)
for thread = (lparallel.queue:try-pop-queue queue)
while thread
do (multiple-value-bind (condition backtrace) (bt:join-thread thread)
(cond ((not (typep condition 'condition)))
(ignore-errors (setf errorp t))
(t (threaded-petri-net-error condition backtrace))))
finally (return errorp)))
(defclass threaded-transition (petri::transition) ()
(:metaclass closer-mop:funcallable-standard-class))
(defmacro with-threaded-petri-net-handler ((condition backtrace) &body body)
(with-gensyms (e)
`(block nil
(handler-bind
((error (lambda (,e)
(setf ,condition ,e
,backtrace (print-backtrace ,e :output nil))
(return))))
,@body))))
(defmethod petri::make-transition-funcallable-function
((transition threaded-transition))
(named-lambda execute-threaded-transition (input petri-net)
(let (condition
backtrace
(output (petri::make-output-hash-table transition)))
(with-threaded-petri-net-handler (condition backtrace)
(petri::call-callback transition input output))
(unless condition
(with-threaded-petri-net-handler (condition backtrace)
(bt:with-lock-held ((lock-of petri-net))
(petri::populate-output transition petri-net output)
(spawn-transitions petri-net))))
(values condition backtrace))))
(defun make-threaded-transition (from to callback)
(petri::make-transition from to callback 'threaded-transition))
(defun make-threaded-petri-net (bags transitions)
(make-instance 'threaded-petri-net :bags bags :transitions transitions))
(defmacro threaded-petri-net (() &body forms)
`(petri::%petri-net #'make-threaded-petri-net ,@forms))
(define-condition threaded-petri-net-error (petri-net-error)
((%reason :reader reason
:initarg :reason
:initform (required-argument :reason))
(%backtrace :reader backtrace
:initarg :backtrace
:initform nil))
(:report (lambda (condition stream)
(format stream "Error while executing the threaded Petri net:~%~A
Backtrace: ~A" (reason condition) (backtrace condition)))))
(defun threaded-petri-net-error (reason backtrace)
(cerror "Continue executing the Petri net." 'threaded-petri-net-error
:reason reason :backtrace backtrace))
|
45d98bc47f0513d4d20ade7157eac3b9f033e7e39488b3e4acb76a267fdc5cb5 | cxxxr/valtan | must-symbol.lisp | Copyright ( C ) 2002 - 2004 , < >
;; ALL RIGHTS RESERVED.
;;
$ I d : must - symbol.lisp , v 1.7 2004/02/20 07:23:42 yuji Exp $
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE 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.
(symbolp 'elephant)
(not (symbolp 12))
(symbolp nil)
(symbolp '())
(symbolp :test)
(not (symbolp "hello"))
(not (keywordp 'elephant))
(not (keywordp 12))
(keywordp :test)
(keywordp ':test)
(not (keywordp nil))
(keywordp :nil)
(not (keywordp '(:test)))
(not (keywordp "hello"))
(not (keywordp ":hello"))
(not (keywordp '&optional))
(let ((new (make-symbol "symbol")))
(string= (symbol-name new) "symbol"))
(let ((new (make-symbol "symbol")))
(not (boundp new)))
(let ((new (make-symbol "symbol")))
(not (fboundp new)))
(let ((new (make-symbol "symbol")))
(null (symbol-plist new)))
(let ((new (make-symbol "symbol")))
(null (symbol-package new)))
(let ((new (make-symbol "symbol")))
(not (member new (find-all-symbols "symbol"))))
(every #'identity
(mapcar
#'(lambda (name)
(let ((new (make-symbol name)))
(and (string= (symbol-name new) name)
(not (boundp new))
(not (fboundp new))
(null (symbol-plist new))
(not (member new (find-all-symbols name))))))
'("" "Symbol" "eat-this" "SYMBOL" ":S:Y:M:B:O:L:")))
(let ((copy (copy-symbol 'cl:car)))
(string= (symbol-name copy) (symbol-name 'cl:car)))
(let ((copy (copy-symbol 'cl:car)))
(not (boundp copy)))
(let ((copy (copy-symbol 'cl:car)))
(not (fboundp copy)))
(let ((copy (copy-symbol 'cl:car)))
(null (symbol-plist copy)))
(let ((copy (copy-symbol 'cl:car)))
(null (symbol-package copy)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(string= (symbol-name copy) (symbol-name 'cl:car)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(if (boundp 'cl:car)
(boundp copy)
(not (boundp copy))))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(eq (symbol-function copy) (symbol-function 'cl:car)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(equal (symbol-plist copy) (symbol-plist 'cl:car)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(null (symbol-package copy)))
(every #'identity
(mapcar
#'(lambda (symbol)
(let ((copy1 (copy-symbol symbol))
(copy2 (copy-symbol symbol "copy-properties")))
(and (string= (symbol-name copy1) (symbol-name symbol))
(string= (symbol-name copy2) (symbol-name symbol))
(not (boundp copy1))
(if (boundp symbol)
(boundp copy2)
(not (boundp copy2)))
(not (fboundp copy1))
(if (fboundp symbol)
(fboundp copy2)
(not (fboundp copy2)))
(null (symbol-plist copy1))
(equal (symbol-plist copy2) (symbol-plist symbol))
(null (symbol-package copy1))
(null (symbol-package copy2))
(not (member copy1 (find-all-symbols symbol)))
(not (member copy2 (find-all-symbols symbol))))))
'(nil cl:cdr cl:*package* cl:list symbol weird-symbol)))
(let ((new (gensym)))
(not (boundp new)))
(let ((new (gensym)))
(not (fboundp new)))
(let ((new (gensym)))
(null (symbol-plist new)))
(let ((new (gensym)))
(null (symbol-package new)))
(let ((new (gensym "How about this")))
(not (boundp new)))
(let ((new (gensym "How about this")))
(not (fboundp new)))
(let ((new (gensym "How about this")))
(null (symbol-plist new)))
(let ((new (gensym "How about this")))
(null (symbol-package new)))
(let ((new (gensym 100)))
(not (boundp new)))
(let ((new (gensym 10)))
(not (fboundp new)))
(let ((new (gensym 9)))
(null (symbol-plist new)))
(let ((new (gensym 8)))
(null (symbol-package new)))
(let* ((counter *gensym-counter*)
(new (gensym)))
(string= (symbol-name new)
(with-output-to-string (stream)
(format stream "G~D" counter))))
(let* ((counter *gensym-counter*)
(new (gensym "JJ")))
(string= (symbol-name new)
(with-output-to-string (stream)
(format stream "JJ~D" counter))))
(let* ((counter *gensym-counter*)
(new (gensym "")))
(string= (symbol-name new)
(with-output-to-string (stream)
(format stream "~D" counter))))
(let ((new (gensym 0)))
(string= (symbol-name new) "G0"))
(let ((new (gensym 1000)))
(string= (symbol-name new) "G1000"))
(let ((symbol (gentemp)))
(char= (aref (symbol-name symbol) 0) #\T))
(let ((symbol (gentemp)))
(not (boundp symbol)))
(let ((symbol (gentemp)))
(not (fboundp symbol)))
(let ((symbol (gentemp)))
(null (symbol-plist symbol)))
(let ((symbol (gentemp)))
(multiple-value-bind (symbol-found status)
(find-symbol (symbol-name symbol))
(and (eq symbol-found symbol)
(if (eq *package* (find-package "KEYWORD"))
(eq status :external)
(eq status :internal)))))
(let ((symbol-1 (gentemp))
(symbol-2 (gentemp)))
(not (string= (symbol-name symbol-1) (symbol-name symbol-2))))
(let ((symbol (gentemp "prefix")))
(string= (subseq (symbol-name symbol) 0 6) "prefix"))
(let ((symbol (gentemp "prefix")))
(not (boundp symbol)))
(let ((symbol (gentemp "prefix")))
(not (fboundp symbol)))
(let ((symbol (gentemp "prefix")))
(null (symbol-plist symbol)))
(let ((symbol (gentemp "prefix")))
(multiple-value-bind (symbol-found status)
(find-symbol (symbol-name symbol))
(and (eq symbol-found symbol)
(if (eq *package* (find-package "KEYWORD"))
(eq status :external)
(eq status :internal)))))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(string= (subseq (symbol-name symbol) 0 6) "prefix"))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(not (boundp symbol)))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(not (fboundp symbol)))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(null (symbol-plist symbol)))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(multiple-value-bind (symbol-found status)
(find-symbol (symbol-name symbol) package)
(and (eq symbol-found symbol)
(eq status :internal))))
(functionp (symbol-function 'cl:car))
(eq (symbol-function 'cl:car) (fdefinition 'cl:car))
(progn (setf (symbol-function 'symbol-for-test) #'car)
(eq (symbol-for-test '(a)) 'a))
(let ((f #'(lambda (a) a)))
(setf (symbol-function 'symbol-for-test) f)
(eq (symbol-function 'symbol-for-test) f))
(stringp (symbol-name 'symbol))
(string= (symbol-name (intern "TEST-SYMBOL")) "TEST-SYMBOL")
(eq (symbol-package 'cl:car) (find-package "COMMON-LISP"))
(eq (symbol-package ':key) (find-package "KEYWORD"))
(null (symbol-package (make-symbol "temp")))
(null (symbol-package (gensym)))
(packagep (symbol-package 'a))
(packagep (symbol-package 'my-symbol))
(listp (symbol-plist 'car))
(listp (symbol-plist 'cdr))
(null (symbol-plist (gensym)))
(null (symbol-plist (gentemp)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(equal (symbol-plist symbol) '(a 1 b 2 c 3)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(setf (symbol-plist symbol) '())
(null (symbol-plist symbol)))
(progn (setf (symbol-value 'a) 1)
(eql (symbol-value 'a) 1))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(eql (symbol-value 'a) 1)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(setq a 3)
(eql (symbol-value 'a) 1)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(declare (special a))
(eql (symbol-value 'a) 2)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(declare (special a))
(setq a 3)
(eql (symbol-value 'a) 3)))
(progn
(setf (symbol-value 'a) 1)
(and (eql (let ((a 2))
(setf (symbol-value 'a) 3)
a)
2)
(eql a 3)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 4))
(declare (special a))
(let ((b (symbol-value 'a)))
(setf (symbol-value 'a) 5)
(and (eql a 5)
(eql b 4)))))
(eq (symbol-value :any-keyword) :any-keyword)
(eq (symbol-value 'nil) nil)
(eq (symbol-value '()) nil)
(eq (symbol-value t) t)
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(and (eql (get symbol 'a) 1)
(eql (get symbol 'b) 2)
(eql (get symbol 'c) 3)
(eql (get symbol 'd) nil)
(eql (get symbol 'e 9) 9)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(and (eql (setf (get symbol 'a) 9) 9)
(eql (get symbol 'a) 9)
(eql (setf (get symbol 'b) 8) 8)
(eql (get symbol 'b) 8)
(eql (setf (get symbol 'c) 7) 7)
(eql (get symbol 'c) 7)
(eql (setf (get symbol 'd) 6) 6)
(eql (get symbol 'd) 6)
(eql (setf (get symbol 'e) 5) 5)
(eql (get symbol 'e) 5)))
(let ((symbol (gensym))
tmp)
(and (null (get symbol 'a))
(setf (get symbol 'a (setq tmp 1)) tmp)
(eql (get symbol 'a) 1)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3 'a 9))
(and (eql (setf (get symbol 'a) 5) 5)
(eql (get symbol 'a) 5)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(and (remprop symbol 'a)
(eq (get symbol 'a 'not-found) 'not-found)))
(let ((symbol (gensym)))
(not (remprop symbol 'a)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3 'a 9))
(and (remprop symbol 'a)
(eql (get symbol 'a) 9)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3 'a 9))
(and (remprop symbol 'a)
(eql (get symbol 'a) 9)
(remprop symbol 'a)
(eq (get symbol 'a 'not-found) 'not-found)))
(not (boundp (gensym)))
(let ((symbol (gensym)))
(set symbol 1)
(boundp symbol))
(let ((test-symbol 1))
(not (boundp 'test-symbol)))
(let ((test-symbol 1))
(declare (special test-symbol))
(boundp 'test-symbol))
(not (boundp (makunbound (gensym))))
(let ((test-symbol 0))
(declare (special test-symbol))
(and (let ((test-symbol 1))
(declare (special test-symbol))
(not (boundp (makunbound 'test-symbol))))
(boundp 'test-symbol)))
(let ((test-symbol 0))
(declare (special test-symbol))
(and (let ((test-symbol 1))
(makunbound 'test-symbol)
(eql test-symbol 1))
(not (boundp 'test-symbol))))
(let ((test-symbol 0))
(declare (special test-symbol))
(and
(eql test-symbol 0)
(setf (symbol-value 'test-symbol) 1)
(eql test-symbol 1)
(eql (set 'test-symbol 10) 10)
(eql test-symbol 10)))
(let ((test-symbol 0))
(declare (special test-symbol))
(and (let ((test-symbol 1))
(set 'test-symbol 100)
(eql test-symbol 1))
(eql test-symbol 100)))
| null | https://raw.githubusercontent.com/cxxxr/valtan/ec3164d42b86869357dc185b747c5dfba25c0a3c/tests/sacla-tests/must-symbol.lisp | lisp | ALL RIGHTS RESERVED.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | Copyright ( C ) 2002 - 2004 , < >
$ I d : must - symbol.lisp , v 1.7 2004/02/20 07:23:42 yuji Exp $
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(symbolp 'elephant)
(not (symbolp 12))
(symbolp nil)
(symbolp '())
(symbolp :test)
(not (symbolp "hello"))
(not (keywordp 'elephant))
(not (keywordp 12))
(keywordp :test)
(keywordp ':test)
(not (keywordp nil))
(keywordp :nil)
(not (keywordp '(:test)))
(not (keywordp "hello"))
(not (keywordp ":hello"))
(not (keywordp '&optional))
(let ((new (make-symbol "symbol")))
(string= (symbol-name new) "symbol"))
(let ((new (make-symbol "symbol")))
(not (boundp new)))
(let ((new (make-symbol "symbol")))
(not (fboundp new)))
(let ((new (make-symbol "symbol")))
(null (symbol-plist new)))
(let ((new (make-symbol "symbol")))
(null (symbol-package new)))
(let ((new (make-symbol "symbol")))
(not (member new (find-all-symbols "symbol"))))
(every #'identity
(mapcar
#'(lambda (name)
(let ((new (make-symbol name)))
(and (string= (symbol-name new) name)
(not (boundp new))
(not (fboundp new))
(null (symbol-plist new))
(not (member new (find-all-symbols name))))))
'("" "Symbol" "eat-this" "SYMBOL" ":S:Y:M:B:O:L:")))
(let ((copy (copy-symbol 'cl:car)))
(string= (symbol-name copy) (symbol-name 'cl:car)))
(let ((copy (copy-symbol 'cl:car)))
(not (boundp copy)))
(let ((copy (copy-symbol 'cl:car)))
(not (fboundp copy)))
(let ((copy (copy-symbol 'cl:car)))
(null (symbol-plist copy)))
(let ((copy (copy-symbol 'cl:car)))
(null (symbol-package copy)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(string= (symbol-name copy) (symbol-name 'cl:car)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(if (boundp 'cl:car)
(boundp copy)
(not (boundp copy))))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(eq (symbol-function copy) (symbol-function 'cl:car)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(equal (symbol-plist copy) (symbol-plist 'cl:car)))
(let ((copy (copy-symbol 'cl:car "copy properties too")))
(null (symbol-package copy)))
(every #'identity
(mapcar
#'(lambda (symbol)
(let ((copy1 (copy-symbol symbol))
(copy2 (copy-symbol symbol "copy-properties")))
(and (string= (symbol-name copy1) (symbol-name symbol))
(string= (symbol-name copy2) (symbol-name symbol))
(not (boundp copy1))
(if (boundp symbol)
(boundp copy2)
(not (boundp copy2)))
(not (fboundp copy1))
(if (fboundp symbol)
(fboundp copy2)
(not (fboundp copy2)))
(null (symbol-plist copy1))
(equal (symbol-plist copy2) (symbol-plist symbol))
(null (symbol-package copy1))
(null (symbol-package copy2))
(not (member copy1 (find-all-symbols symbol)))
(not (member copy2 (find-all-symbols symbol))))))
'(nil cl:cdr cl:*package* cl:list symbol weird-symbol)))
(let ((new (gensym)))
(not (boundp new)))
(let ((new (gensym)))
(not (fboundp new)))
(let ((new (gensym)))
(null (symbol-plist new)))
(let ((new (gensym)))
(null (symbol-package new)))
(let ((new (gensym "How about this")))
(not (boundp new)))
(let ((new (gensym "How about this")))
(not (fboundp new)))
(let ((new (gensym "How about this")))
(null (symbol-plist new)))
(let ((new (gensym "How about this")))
(null (symbol-package new)))
(let ((new (gensym 100)))
(not (boundp new)))
(let ((new (gensym 10)))
(not (fboundp new)))
(let ((new (gensym 9)))
(null (symbol-plist new)))
(let ((new (gensym 8)))
(null (symbol-package new)))
(let* ((counter *gensym-counter*)
(new (gensym)))
(string= (symbol-name new)
(with-output-to-string (stream)
(format stream "G~D" counter))))
(let* ((counter *gensym-counter*)
(new (gensym "JJ")))
(string= (symbol-name new)
(with-output-to-string (stream)
(format stream "JJ~D" counter))))
(let* ((counter *gensym-counter*)
(new (gensym "")))
(string= (symbol-name new)
(with-output-to-string (stream)
(format stream "~D" counter))))
(let ((new (gensym 0)))
(string= (symbol-name new) "G0"))
(let ((new (gensym 1000)))
(string= (symbol-name new) "G1000"))
(let ((symbol (gentemp)))
(char= (aref (symbol-name symbol) 0) #\T))
(let ((symbol (gentemp)))
(not (boundp symbol)))
(let ((symbol (gentemp)))
(not (fboundp symbol)))
(let ((symbol (gentemp)))
(null (symbol-plist symbol)))
(let ((symbol (gentemp)))
(multiple-value-bind (symbol-found status)
(find-symbol (symbol-name symbol))
(and (eq symbol-found symbol)
(if (eq *package* (find-package "KEYWORD"))
(eq status :external)
(eq status :internal)))))
(let ((symbol-1 (gentemp))
(symbol-2 (gentemp)))
(not (string= (symbol-name symbol-1) (symbol-name symbol-2))))
(let ((symbol (gentemp "prefix")))
(string= (subseq (symbol-name symbol) 0 6) "prefix"))
(let ((symbol (gentemp "prefix")))
(not (boundp symbol)))
(let ((symbol (gentemp "prefix")))
(not (fboundp symbol)))
(let ((symbol (gentemp "prefix")))
(null (symbol-plist symbol)))
(let ((symbol (gentemp "prefix")))
(multiple-value-bind (symbol-found status)
(find-symbol (symbol-name symbol))
(and (eq symbol-found symbol)
(if (eq *package* (find-package "KEYWORD"))
(eq status :external)
(eq status :internal)))))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(string= (subseq (symbol-name symbol) 0 6) "prefix"))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(not (boundp symbol)))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(not (fboundp symbol)))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(null (symbol-plist symbol)))
(let* ((package (defpackage "TEST-PACKAGE-FOR-GENTEMP"))
(symbol (gentemp "prefix" package)))
(multiple-value-bind (symbol-found status)
(find-symbol (symbol-name symbol) package)
(and (eq symbol-found symbol)
(eq status :internal))))
(functionp (symbol-function 'cl:car))
(eq (symbol-function 'cl:car) (fdefinition 'cl:car))
(progn (setf (symbol-function 'symbol-for-test) #'car)
(eq (symbol-for-test '(a)) 'a))
(let ((f #'(lambda (a) a)))
(setf (symbol-function 'symbol-for-test) f)
(eq (symbol-function 'symbol-for-test) f))
(stringp (symbol-name 'symbol))
(string= (symbol-name (intern "TEST-SYMBOL")) "TEST-SYMBOL")
(eq (symbol-package 'cl:car) (find-package "COMMON-LISP"))
(eq (symbol-package ':key) (find-package "KEYWORD"))
(null (symbol-package (make-symbol "temp")))
(null (symbol-package (gensym)))
(packagep (symbol-package 'a))
(packagep (symbol-package 'my-symbol))
(listp (symbol-plist 'car))
(listp (symbol-plist 'cdr))
(null (symbol-plist (gensym)))
(null (symbol-plist (gentemp)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(equal (symbol-plist symbol) '(a 1 b 2 c 3)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(setf (symbol-plist symbol) '())
(null (symbol-plist symbol)))
(progn (setf (symbol-value 'a) 1)
(eql (symbol-value 'a) 1))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(eql (symbol-value 'a) 1)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(setq a 3)
(eql (symbol-value 'a) 1)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(declare (special a))
(eql (symbol-value 'a) 2)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 2))
(declare (special a))
(setq a 3)
(eql (symbol-value 'a) 3)))
(progn
(setf (symbol-value 'a) 1)
(and (eql (let ((a 2))
(setf (symbol-value 'a) 3)
a)
2)
(eql a 3)))
(progn
(setf (symbol-value 'a) 1)
(let ((a 4))
(declare (special a))
(let ((b (symbol-value 'a)))
(setf (symbol-value 'a) 5)
(and (eql a 5)
(eql b 4)))))
(eq (symbol-value :any-keyword) :any-keyword)
(eq (symbol-value 'nil) nil)
(eq (symbol-value '()) nil)
(eq (symbol-value t) t)
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(and (eql (get symbol 'a) 1)
(eql (get symbol 'b) 2)
(eql (get symbol 'c) 3)
(eql (get symbol 'd) nil)
(eql (get symbol 'e 9) 9)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(and (eql (setf (get symbol 'a) 9) 9)
(eql (get symbol 'a) 9)
(eql (setf (get symbol 'b) 8) 8)
(eql (get symbol 'b) 8)
(eql (setf (get symbol 'c) 7) 7)
(eql (get symbol 'c) 7)
(eql (setf (get symbol 'd) 6) 6)
(eql (get symbol 'd) 6)
(eql (setf (get symbol 'e) 5) 5)
(eql (get symbol 'e) 5)))
(let ((symbol (gensym))
tmp)
(and (null (get symbol 'a))
(setf (get symbol 'a (setq tmp 1)) tmp)
(eql (get symbol 'a) 1)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3 'a 9))
(and (eql (setf (get symbol 'a) 5) 5)
(eql (get symbol 'a) 5)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3))
(and (remprop symbol 'a)
(eq (get symbol 'a 'not-found) 'not-found)))
(let ((symbol (gensym)))
(not (remprop symbol 'a)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3 'a 9))
(and (remprop symbol 'a)
(eql (get symbol 'a) 9)))
(let ((symbol (gensym)))
(setf (symbol-plist symbol) (list 'a 1 'b 2 'c 3 'a 9))
(and (remprop symbol 'a)
(eql (get symbol 'a) 9)
(remprop symbol 'a)
(eq (get symbol 'a 'not-found) 'not-found)))
(not (boundp (gensym)))
(let ((symbol (gensym)))
(set symbol 1)
(boundp symbol))
(let ((test-symbol 1))
(not (boundp 'test-symbol)))
(let ((test-symbol 1))
(declare (special test-symbol))
(boundp 'test-symbol))
(not (boundp (makunbound (gensym))))
(let ((test-symbol 0))
(declare (special test-symbol))
(and (let ((test-symbol 1))
(declare (special test-symbol))
(not (boundp (makunbound 'test-symbol))))
(boundp 'test-symbol)))
(let ((test-symbol 0))
(declare (special test-symbol))
(and (let ((test-symbol 1))
(makunbound 'test-symbol)
(eql test-symbol 1))
(not (boundp 'test-symbol))))
(let ((test-symbol 0))
(declare (special test-symbol))
(and
(eql test-symbol 0)
(setf (symbol-value 'test-symbol) 1)
(eql test-symbol 1)
(eql (set 'test-symbol 10) 10)
(eql test-symbol 10)))
(let ((test-symbol 0))
(declare (special test-symbol))
(and (let ((test-symbol 1))
(set 'test-symbol 100)
(eql test-symbol 1))
(eql test-symbol 100)))
|
0c8f6e298d0cbad300dba47a9d1c08c56e834355afa56d8841d236b23d1d15ea | christian-marie/oauth2-server | PostgreSQL.hs | --
Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
the 3 - clause BSD licence .
--
# LANGUAGE FlexibleInstances #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
-- | Description: OAuth2 token storage instance for PostgreSQL
--
-- OAuth2 token storage backend for PostgreSQL databases. This module exports
types to use either a ' Pool ' of PostgreSQL ' Connection 's or a single
-- 'Connection' to access the database.
module Network.OAuth2.Server.Store.PostgreSQL (
PSQLConn(..),
PSQLConnPool(..),
) where
import Control.Applicative ((<$>), (<*>))
import Control.Exception (SomeException, throw, try)
import Control.Lens.Review (review)
import Control.Monad (when)
import Crypto.Scrypt (getEncryptedPass)
import Data.Int (Int64)
import Data.Maybe (isNothing)
import Data.Monoid ((<>))
import Data.Pool (Pool, withResource)
import qualified Data.Vector as V (fromList)
import Database.PostgreSQL.Simple ((:.) (..), Connection,
Only (..), Query, execute,
query, query_)
import System.Log.Logger (criticalM, debugM, errorM,
warningM)
import Network.OAuth2.Server.Store.Base
import Network.OAuth2.Server.Types
-- | A wrapped Data.Pool of PostgreSQL.Simple Connections
newtype PSQLConnPool = PSQLConnPool (Pool Connection)
-- | A wrapped PostgreSQL.Simple Connection.
newtype PSQLConn = PSQLConn Connection
instance TokenStore PSQLConnPool where
storeCreateClient (PSQLConnPool pool) pass conf uris name desc site scp stat =
withResource pool $ \c -> storeCreateClient (PSQLConn c) pass conf uris name desc site scp stat
storeDeleteClient (PSQLConnPool pool) cid =
withResource pool $ \c -> storeDeleteClient (PSQLConn c) cid
storeLookupClient (PSQLConnPool pool) cid =
withResource pool $ \c -> storeLookupClient (PSQLConn c) cid
storeCreateCode (PSQLConnPool pool) uid cid uri scp st =
withResource pool $ \c -> storeCreateCode (PSQLConn c) uid cid uri scp st
storeActivateCode (PSQLConnPool pool) cd =
withResource pool $ \c -> storeActivateCode (PSQLConn c) cd
storeReadCode (PSQLConnPool pool) cd =
withResource pool $ \c -> storeReadCode (PSQLConn c) cd
storeDeleteCode (PSQLConnPool pool) cd =
withResource pool $ \c -> storeDeleteCode (PSQLConn c) cd
storeCreateToken (PSQLConnPool pool) grant tid =
withResource pool $ \c -> storeCreateToken (PSQLConn c) grant tid
storeReadToken (PSQLConnPool pool) tid =
withResource pool $ \c -> storeReadToken (PSQLConn c) tid
storeRevokeToken (PSQLConnPool pool) tid =
withResource pool $ \c -> storeRevokeToken (PSQLConn c) tid
storeListTokens (PSQLConnPool pool) uid sz pg =
withResource pool $ \c -> storeListTokens (PSQLConn c) uid sz pg
storeGatherStats (PSQLConnPool pool) =
withResource pool $ \c -> storeGatherStats (PSQLConn c)
instance TokenStore PSQLConn where
storeCreateClient (PSQLConn conn) pass confidential redirect_url name description app_url client_scope status = do
debugM logName $ "Attempting storeCreateClient with name " <> show name
res <- query conn "INSERT INTO clients (client_secret, confidential, redirect_url, name, description, app_url, scope, status) VALUES (?,?,?,?,?,?,?,?) RETURNING client_id"
(getEncryptedPass pass, confidential, V.fromList redirect_url, name, description, uriToBS app_url, client_scope, status)
case res of
[(Only client_id)] ->
return $ ClientDetails client_id pass confidential redirect_url name description app_url client_scope status
[] -> fail $ "Failed to save new client: " <> show name
_ -> fail "Impossible: multiple client_ids returned from single insert"
storeDeleteClient (PSQLConn conn) client_id = do
debugM logName $ "Attempting storeDeleteClient with " <> show client_id
rows <- execute conn "UPDATE clients SET status = 'deleted' WHERE (client_id = ?)" (Only client_id)
case rows of
0 -> do
let msg = "Failed to delete client " <> show client_id
errorM logName msg
fail msg
x -> debugM logName $ "Revoked multiple (" <> show x <> ") clients with id " <> show client_id
storeLookupClient (PSQLConn conn) client_id = do
debugM logName $ "Attempting storeLookupClient with " <> show client_id
res <- query conn "SELECT client_id, client_secret, confidential, redirect_url, name, description, app_url, scope, status FROM clients WHERE (client_id = ?) AND status = 'active'" (Only client_id)
return $ case res of
[] -> Nothing
[client] -> Just client
_ -> error "Expected client_id PK to be unique"
storeCreateCode p@(PSQLConn conn) requestCodeUserID requestCodeClientID requestCodeRedirectURI sc requestCodeState = do
debugM logName $ "Attempting storeCreateCode with " <> show sc
debugM logName $ "Checking existence of client " <> show requestCodeClientID
res <- storeLookupClient p requestCodeClientID
when (isNothing res) $ error $ "Expected client " <> show requestCodeClientID <> " would be present and active"
[(requestCodeCode, requestCodeExpires)] <- do
debugM logName $ "Attempting storeCreateCode with " <> show sc
query conn
"INSERT INTO request_codes (client_id, user_id, redirect_url, scope, state) VALUES (?,?,?,?,?) RETURNING code, expires"
(requestCodeClientID, requestCodeUserID, requestCodeRedirectURI, sc, requestCodeState)
let requestCodeScope = Just sc
requestCodeAuthorized = False
return RequestCode{..}
storeActivateCode (PSQLConn conn) code' = do
debugM logName $ "Attempting storeActivateCode with " <> show code'
res <- query conn "UPDATE request_codes SET authorized = TRUE WHERE code = ? RETURNING code, authorized, expires, user_id, client_id, redirect_url, scope, state" (Only code')
case res of
[] -> return Nothing
[reqCode] -> return $ Just reqCode
_ -> do
let errMsg = "Consistency error: multiple request codes found"
errorM logName errMsg
error errMsg
storeReadCode (PSQLConn conn) request_code = do
debugM logName $ "Attempting storeReadCode"
codes <- query conn "SELECT * FROM active_request_codes WHERE code = ?" (Only request_code)
return $ case codes of
[] -> Nothing
[rc] -> return rc
_ -> error "Expected code PK to be unique"
storeDeleteCode (PSQLConn conn) request_code = do
debugM logName $ "Attempting storeDeleteCode"
[Only res] <- query conn "WITH deleted AS (DELETE FROM request_codes WHERE (code = ?) RETURNING *) SELECT COUNT(*) FROM deleted"
(Only request_code)
return $ case res :: Int of
0 -> False
1 -> True
_ -> error "Expected code PK to be unique"
storeCreateToken p@(PSQLConn conn) grant parent_token = do
debugM logName $ "Attempting to save new token: " <> show grant
case grantClientID grant of
Just client_id -> do
debugM logName $ "Checking validity of client " <> show client_id
res <- storeLookupClient p client_id
when (isNothing res) $ error $ "client " <> show client_id <> " was not present and active"
Nothing -> return ()
debugM logName $ "Saving new token: " <> show grant
debugM logName $ "Attempting storeCreateToken"
res <- case parent_token of
Nothing -> query conn "INSERT INTO tokens (token_type, expires, user_id, client_id, scope, token, created) VALUES (?,?,?,?,?,uuid_generate_v4(), NOW()) RETURNING token_id, token_type, token, expires, user_id, client_id, scope" grant
Just tid -> query conn "INSERT INTO tokens (token_type, expires, user_id, client_id, scope, token, created, token_parent) VALUES (?,?,?,?,?,uuid_generate_v4(), NOW(), ?) RETURNING token_id, token_type, token, expires, user_id, client_id, scope" (grant :. Only tid)
case res of
[Only tid :. tok] -> return (tid, tok)
[] -> fail $ "Failed to save new token: " <> show grant
_ -> fail "Impossible: multiple tokens returned from single insert"
storeReadToken (PSQLConn conn) tok = do
debugM logName $ "Loading token: " <> show tok
let q = "SELECT token_id, token_type, token, expires, user_id, client_id, scope FROM active_tokens WHERE (created <= NOW()) AND ((NOW() < expires) OR (expires IS NULL)) AND (revoked IS NULL) "
tokens <- case tok of
Left tok' -> query conn (q <> "AND (token = ?)") (Only tok')
Right tid -> query conn (q <> "AND (token_id = ?)") (Only tid )
case tokens of
[Only tid :. tok'] -> return $ Just (tid, tok')
[] -> do
debugM logName $ "No tokens found matching " <> show tok
return Nothing
_ -> do
errorM logName $ "Consistency error: multiple tokens found matching " <> show tok
return Nothing
storeRevokeToken (PSQLConn conn) token_id = do
debugM logName $ "Revoking token with id " <> show token_id
rows <- execute conn "UPDATE tokens SET revoked = NOW() WHERE (token_id = ?) OR (token_parent = ?)" (token_id, token_id)
case rows of
0 -> do
let msg = "Failed to revoke token " <> show token_id
errorM logName msg
fail msg
x -> debugM logName $ "Revoked multiple (" <> show x <> ") tokens with id " <> show token_id
storeListTokens (PSQLConn conn) maybe_uid (review pageSize -> size :: Integer) (review page -> p) = do
(toks, n_toks) <- case maybe_uid of
Nothing -> do
debugM logName "Listing all tokens"
toks <- query conn "SELECT token_id, token_type, token, expires, user_id, client_id, scope FROM active_tokens WHERE revoked is NULL ORDER BY created DESC LIMIT ? OFFSET ?" (size, (p - 1) * size)
debugM logName "Counting all tokens"
[Only n_toks] <- query_ conn "SELECT COUNT(*) FROM active_tokens WHERE revoked is NULL"
return (toks, n_toks)
Just uid -> do
debugM logName $ "Listing tokens for " <> show uid
toks <- query conn "SELECT token_id, token_type, token, expires, user_id, client_id, scope FROM active_tokens WHERE (user_id = ?) AND revoked is NULL ORDER BY created DESC LIMIT ? OFFSET ?" (uid, size, (p - 1) * size)
debugM logName $ "Counting tokens for " <> show uid
[Only n_toks] <- query conn "SELECT COUNT(*) FROM active_tokens WHERE (user_id = ?) AND revoked is NULL" (Only uid)
return (toks, n_toks)
return (map (\((Only tid) :. tok) -> (tid, tok)) toks, n_toks)
storeGatherStats (PSQLConn conn) =
let gather :: Query -> Connection -> IO Int64
gather q conn = do
res <- try $ query_ conn q
case res of
Left e -> do
criticalM logName $ "storeGatherStats: error executing query "
<> show q <> " "
<> show (e :: SomeException)
throw e
Right [Only c] -> return c
Right x -> do
warningM logName $ "Expected singleton count from PGS, got: " <> show x <> " defaulting to 0"
return 0
gatherClients = gather "SELECT COUNT(*) FROM clients WHERE status = 'active'"
gatherUsers = gather "SELECT COUNT(DISTINCT user_id) FROM tokens"
gatherStatTokensIssued = gather "SELECT COUNT(*) FROM tokens"
gatherStatTokensExpired = gather "SELECT COUNT(*) FROM tokens WHERE expires IS NOT NULL AND expires <= NOW ()"
gatherStatTokensRevoked = gather "SELECT COUNT(*) FROM tokens WHERE revoked IS NOT NULL"
in StoreStats <$> gatherClients conn
<*> gatherUsers conn
<*> gatherStatTokensIssued conn
<*> gatherStatTokensExpired conn
<*> gatherStatTokensRevoked conn
| null | https://raw.githubusercontent.com/christian-marie/oauth2-server/ebb75be9d05dd52d478a6e069d32461d4e54544e/lib/Network/OAuth2/Server/Store/PostgreSQL.hs | haskell |
The code in this file, and the program it is a part of, is
made available to you by its authors as open source software:
you can redistribute it and/or modify it under the terms of
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
| Description: OAuth2 token storage instance for PostgreSQL
OAuth2 token storage backend for PostgreSQL databases. This module exports
'Connection' to access the database.
| A wrapped Data.Pool of PostgreSQL.Simple Connections
| A wrapped PostgreSQL.Simple Connection. | Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others
the 3 - clause BSD licence .
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
types to use either a ' Pool ' of PostgreSQL ' Connection 's or a single
module Network.OAuth2.Server.Store.PostgreSQL (
PSQLConn(..),
PSQLConnPool(..),
) where
import Control.Applicative ((<$>), (<*>))
import Control.Exception (SomeException, throw, try)
import Control.Lens.Review (review)
import Control.Monad (when)
import Crypto.Scrypt (getEncryptedPass)
import Data.Int (Int64)
import Data.Maybe (isNothing)
import Data.Monoid ((<>))
import Data.Pool (Pool, withResource)
import qualified Data.Vector as V (fromList)
import Database.PostgreSQL.Simple ((:.) (..), Connection,
Only (..), Query, execute,
query, query_)
import System.Log.Logger (criticalM, debugM, errorM,
warningM)
import Network.OAuth2.Server.Store.Base
import Network.OAuth2.Server.Types
newtype PSQLConnPool = PSQLConnPool (Pool Connection)
newtype PSQLConn = PSQLConn Connection
instance TokenStore PSQLConnPool where
storeCreateClient (PSQLConnPool pool) pass conf uris name desc site scp stat =
withResource pool $ \c -> storeCreateClient (PSQLConn c) pass conf uris name desc site scp stat
storeDeleteClient (PSQLConnPool pool) cid =
withResource pool $ \c -> storeDeleteClient (PSQLConn c) cid
storeLookupClient (PSQLConnPool pool) cid =
withResource pool $ \c -> storeLookupClient (PSQLConn c) cid
storeCreateCode (PSQLConnPool pool) uid cid uri scp st =
withResource pool $ \c -> storeCreateCode (PSQLConn c) uid cid uri scp st
storeActivateCode (PSQLConnPool pool) cd =
withResource pool $ \c -> storeActivateCode (PSQLConn c) cd
storeReadCode (PSQLConnPool pool) cd =
withResource pool $ \c -> storeReadCode (PSQLConn c) cd
storeDeleteCode (PSQLConnPool pool) cd =
withResource pool $ \c -> storeDeleteCode (PSQLConn c) cd
storeCreateToken (PSQLConnPool pool) grant tid =
withResource pool $ \c -> storeCreateToken (PSQLConn c) grant tid
storeReadToken (PSQLConnPool pool) tid =
withResource pool $ \c -> storeReadToken (PSQLConn c) tid
storeRevokeToken (PSQLConnPool pool) tid =
withResource pool $ \c -> storeRevokeToken (PSQLConn c) tid
storeListTokens (PSQLConnPool pool) uid sz pg =
withResource pool $ \c -> storeListTokens (PSQLConn c) uid sz pg
storeGatherStats (PSQLConnPool pool) =
withResource pool $ \c -> storeGatherStats (PSQLConn c)
instance TokenStore PSQLConn where
storeCreateClient (PSQLConn conn) pass confidential redirect_url name description app_url client_scope status = do
debugM logName $ "Attempting storeCreateClient with name " <> show name
res <- query conn "INSERT INTO clients (client_secret, confidential, redirect_url, name, description, app_url, scope, status) VALUES (?,?,?,?,?,?,?,?) RETURNING client_id"
(getEncryptedPass pass, confidential, V.fromList redirect_url, name, description, uriToBS app_url, client_scope, status)
case res of
[(Only client_id)] ->
return $ ClientDetails client_id pass confidential redirect_url name description app_url client_scope status
[] -> fail $ "Failed to save new client: " <> show name
_ -> fail "Impossible: multiple client_ids returned from single insert"
storeDeleteClient (PSQLConn conn) client_id = do
debugM logName $ "Attempting storeDeleteClient with " <> show client_id
rows <- execute conn "UPDATE clients SET status = 'deleted' WHERE (client_id = ?)" (Only client_id)
case rows of
0 -> do
let msg = "Failed to delete client " <> show client_id
errorM logName msg
fail msg
x -> debugM logName $ "Revoked multiple (" <> show x <> ") clients with id " <> show client_id
storeLookupClient (PSQLConn conn) client_id = do
debugM logName $ "Attempting storeLookupClient with " <> show client_id
res <- query conn "SELECT client_id, client_secret, confidential, redirect_url, name, description, app_url, scope, status FROM clients WHERE (client_id = ?) AND status = 'active'" (Only client_id)
return $ case res of
[] -> Nothing
[client] -> Just client
_ -> error "Expected client_id PK to be unique"
storeCreateCode p@(PSQLConn conn) requestCodeUserID requestCodeClientID requestCodeRedirectURI sc requestCodeState = do
debugM logName $ "Attempting storeCreateCode with " <> show sc
debugM logName $ "Checking existence of client " <> show requestCodeClientID
res <- storeLookupClient p requestCodeClientID
when (isNothing res) $ error $ "Expected client " <> show requestCodeClientID <> " would be present and active"
[(requestCodeCode, requestCodeExpires)] <- do
debugM logName $ "Attempting storeCreateCode with " <> show sc
query conn
"INSERT INTO request_codes (client_id, user_id, redirect_url, scope, state) VALUES (?,?,?,?,?) RETURNING code, expires"
(requestCodeClientID, requestCodeUserID, requestCodeRedirectURI, sc, requestCodeState)
let requestCodeScope = Just sc
requestCodeAuthorized = False
return RequestCode{..}
storeActivateCode (PSQLConn conn) code' = do
debugM logName $ "Attempting storeActivateCode with " <> show code'
res <- query conn "UPDATE request_codes SET authorized = TRUE WHERE code = ? RETURNING code, authorized, expires, user_id, client_id, redirect_url, scope, state" (Only code')
case res of
[] -> return Nothing
[reqCode] -> return $ Just reqCode
_ -> do
let errMsg = "Consistency error: multiple request codes found"
errorM logName errMsg
error errMsg
storeReadCode (PSQLConn conn) request_code = do
debugM logName $ "Attempting storeReadCode"
codes <- query conn "SELECT * FROM active_request_codes WHERE code = ?" (Only request_code)
return $ case codes of
[] -> Nothing
[rc] -> return rc
_ -> error "Expected code PK to be unique"
storeDeleteCode (PSQLConn conn) request_code = do
debugM logName $ "Attempting storeDeleteCode"
[Only res] <- query conn "WITH deleted AS (DELETE FROM request_codes WHERE (code = ?) RETURNING *) SELECT COUNT(*) FROM deleted"
(Only request_code)
return $ case res :: Int of
0 -> False
1 -> True
_ -> error "Expected code PK to be unique"
storeCreateToken p@(PSQLConn conn) grant parent_token = do
debugM logName $ "Attempting to save new token: " <> show grant
case grantClientID grant of
Just client_id -> do
debugM logName $ "Checking validity of client " <> show client_id
res <- storeLookupClient p client_id
when (isNothing res) $ error $ "client " <> show client_id <> " was not present and active"
Nothing -> return ()
debugM logName $ "Saving new token: " <> show grant
debugM logName $ "Attempting storeCreateToken"
res <- case parent_token of
Nothing -> query conn "INSERT INTO tokens (token_type, expires, user_id, client_id, scope, token, created) VALUES (?,?,?,?,?,uuid_generate_v4(), NOW()) RETURNING token_id, token_type, token, expires, user_id, client_id, scope" grant
Just tid -> query conn "INSERT INTO tokens (token_type, expires, user_id, client_id, scope, token, created, token_parent) VALUES (?,?,?,?,?,uuid_generate_v4(), NOW(), ?) RETURNING token_id, token_type, token, expires, user_id, client_id, scope" (grant :. Only tid)
case res of
[Only tid :. tok] -> return (tid, tok)
[] -> fail $ "Failed to save new token: " <> show grant
_ -> fail "Impossible: multiple tokens returned from single insert"
storeReadToken (PSQLConn conn) tok = do
debugM logName $ "Loading token: " <> show tok
let q = "SELECT token_id, token_type, token, expires, user_id, client_id, scope FROM active_tokens WHERE (created <= NOW()) AND ((NOW() < expires) OR (expires IS NULL)) AND (revoked IS NULL) "
tokens <- case tok of
Left tok' -> query conn (q <> "AND (token = ?)") (Only tok')
Right tid -> query conn (q <> "AND (token_id = ?)") (Only tid )
case tokens of
[Only tid :. tok'] -> return $ Just (tid, tok')
[] -> do
debugM logName $ "No tokens found matching " <> show tok
return Nothing
_ -> do
errorM logName $ "Consistency error: multiple tokens found matching " <> show tok
return Nothing
storeRevokeToken (PSQLConn conn) token_id = do
debugM logName $ "Revoking token with id " <> show token_id
rows <- execute conn "UPDATE tokens SET revoked = NOW() WHERE (token_id = ?) OR (token_parent = ?)" (token_id, token_id)
case rows of
0 -> do
let msg = "Failed to revoke token " <> show token_id
errorM logName msg
fail msg
x -> debugM logName $ "Revoked multiple (" <> show x <> ") tokens with id " <> show token_id
storeListTokens (PSQLConn conn) maybe_uid (review pageSize -> size :: Integer) (review page -> p) = do
(toks, n_toks) <- case maybe_uid of
Nothing -> do
debugM logName "Listing all tokens"
toks <- query conn "SELECT token_id, token_type, token, expires, user_id, client_id, scope FROM active_tokens WHERE revoked is NULL ORDER BY created DESC LIMIT ? OFFSET ?" (size, (p - 1) * size)
debugM logName "Counting all tokens"
[Only n_toks] <- query_ conn "SELECT COUNT(*) FROM active_tokens WHERE revoked is NULL"
return (toks, n_toks)
Just uid -> do
debugM logName $ "Listing tokens for " <> show uid
toks <- query conn "SELECT token_id, token_type, token, expires, user_id, client_id, scope FROM active_tokens WHERE (user_id = ?) AND revoked is NULL ORDER BY created DESC LIMIT ? OFFSET ?" (uid, size, (p - 1) * size)
debugM logName $ "Counting tokens for " <> show uid
[Only n_toks] <- query conn "SELECT COUNT(*) FROM active_tokens WHERE (user_id = ?) AND revoked is NULL" (Only uid)
return (toks, n_toks)
return (map (\((Only tid) :. tok) -> (tid, tok)) toks, n_toks)
storeGatherStats (PSQLConn conn) =
let gather :: Query -> Connection -> IO Int64
gather q conn = do
res <- try $ query_ conn q
case res of
Left e -> do
criticalM logName $ "storeGatherStats: error executing query "
<> show q <> " "
<> show (e :: SomeException)
throw e
Right [Only c] -> return c
Right x -> do
warningM logName $ "Expected singleton count from PGS, got: " <> show x <> " defaulting to 0"
return 0
gatherClients = gather "SELECT COUNT(*) FROM clients WHERE status = 'active'"
gatherUsers = gather "SELECT COUNT(DISTINCT user_id) FROM tokens"
gatherStatTokensIssued = gather "SELECT COUNT(*) FROM tokens"
gatherStatTokensExpired = gather "SELECT COUNT(*) FROM tokens WHERE expires IS NOT NULL AND expires <= NOW ()"
gatherStatTokensRevoked = gather "SELECT COUNT(*) FROM tokens WHERE revoked IS NOT NULL"
in StoreStats <$> gatherClients conn
<*> gatherUsers conn
<*> gatherStatTokensIssued conn
<*> gatherStatTokensExpired conn
<*> gatherStatTokensRevoked conn
|
d436a53645e59677f61a99fc4a1404a95ea25c1bb6414f372c3fbbc11377b70e | kelamg/HtDP2e-workthrough | ex391.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex391) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; [List-of Number] [List-of Number] -> [List-of Number]
; replaces the final '() in front with end
(check-expect (replace-eol-with '() '()) '())
(check-expect (replace-eol-with '() '(a b)) '(a b))
(check-expect (replace-eol-with '(1) '(a)) '(1 a))
(check-expect (replace-eol-with '(1 2) '()) '(1 2))
(check-expect (replace-eol-with '(2 1 ) '(a)) '(2 1 a))
(define (replace-eol-with front end)
(cond
[(empty? front) end]
[(empty? end) front]
[else
(cons (first front)
(replace-eol-with (rest front) end))]))
| null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Intertwined-Data/ex391.rkt | racket | about the language level of this file in a form that our tools can easily process.
[List-of Number] [List-of Number] -> [List-of Number]
replaces the final '() in front with end | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex391) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(check-expect (replace-eol-with '() '()) '())
(check-expect (replace-eol-with '() '(a b)) '(a b))
(check-expect (replace-eol-with '(1) '(a)) '(1 a))
(check-expect (replace-eol-with '(1 2) '()) '(1 2))
(check-expect (replace-eol-with '(2 1 ) '(a)) '(2 1 a))
(define (replace-eol-with front end)
(cond
[(empty? front) end]
[(empty? end) front]
[else
(cons (first front)
(replace-eol-with (rest front) end))]))
|
44821555ba5f89023b6339724dfc7eb7f26c4257cac848a9a5110a7bc4452143 | leksah/leksah-server | TestTool.hs | # LANGUAGE CPP , OverloadedStrings #
-----------------------------------------------------------------------------
--
-- Module : Main
Copyright : 2007 - 2011 ,
-- License : GPL
--
-- Maintainer :
-- Stability : provisional
-- Portability :
--
-- | Windows systems do not often have a real echo executable (so --with-ghc=echo fails)
--
-----------------------------------------------------------------------------
module Main (
main
) where
import System.Environment (getArgs)
import System.Exit (exitWith, exitSuccess, exitFailure, ExitCode(..))
import System.FilePath ((</>))
import Data.Monoid ((<>))
import IDE.Utils.Tool
(toolProcess, executeGhciCommand, ToolOutput(..), runTool',
newGhci')
import System.Process (interruptProcessGroupOf, getProcessExitCode)
import Test.HUnit
((@=?), (@?=), putTextToHandle, Counts(..), runTestTT, assertBool,
runTestText, (~:), Testable(..), Test(..))
import Test.DocTest (doctest)
import System.IO (hPutStr, stdout, hPutStrLn, stderr, hFlush)
import qualified Data.Conduit.List as EL (consume)
import Control.Concurrent
(threadDelay, forkIO, takeMVar, putMVar, newEmptyMVar)
import Control.Monad.IO.Class (liftIO)
import Control.Monad (void, forM_)
import System.Log.Logger
(setLevel, rootLoggerName, updateGlobalLogger)
import System.Log (Priority(..))
import IDE.Utils.CabalProject (findProjectRoot)
import System.Directory (getCurrentDirectory)
import qualified Data.Text as T (pack)
-- stderr and stdout may not be in sync
check output expected = do
checkFiltered notOut
checkFiltered notErr
where
checkFiltered f = filter f output @?= filter f expected
notErr (ToolError _) = False
notErr _ = True
notOut (ToolOutput _) = False
notOut _ = True
runTests testMVar = loop
where
loop = do
mbTest <- takeMVar testMVar
case mbTest of
Just test -> do
test
loop
Nothing -> return ()
sendTest testMVar test =
liftIO $ putMVar testMVar $ Just test
doneTesting testMVar =
liftIO $ putMVar testMVar Nothing
tests testTool =
let runSelf' args = runTool' testTool args Nothing Nothing
in test [
"Exit Success" ~: do
(output, _) <- runSelf' ["ExitSuccess"]
output `check` [ToolInput $ T.pack testTool <> " ExitSuccess", ToolExit ExitSuccess],
"Exit Failure" ~: do
(output, _) <- runSelf' ["Exit42"]
output `check` [ToolInput $ T.pack testTool <> " Exit42", ToolExit (ExitFailure 42)],
"Single Blank Out Line" ~: do
(output, _) <- runSelf' ["BlankLine", "StdOut"]
output `check` [ToolInput $ T.pack testTool <> " BlankLine StdOut", ToolOutput "", ToolExit ExitSuccess],
"Single Blank Err Line" ~: do
(output, _) <- runSelf' ["BlankLine", "StdErr"]
output `check` [ToolInput $ T.pack testTool <> " BlankLine StdErr", ToolError "", ToolExit ExitSuccess],
"Hello Out" ~: do
(output, _) <- runSelf' ["Hello", "StdOut"]
output `check` [ToolInput $ T.pack testTool <> " Hello StdOut", ToolOutput "Hello World", ToolExit ExitSuccess],
"Hello Err" ~: do
(output, _) <- runSelf' ["Hello", "StdErr"]
output `check` [ToolInput $ T.pack testTool <> " Hello StdErr", ToolError "Hello World", ToolExit ExitSuccess],
"Both" ~: do
(output, _) <- runSelf' ["ErrAndOut"]
output `check` [ToolInput $ T.pack testTool <> " ErrAndOut", ToolError "Error", ToolOutput "Output", ToolExit ExitSuccess],
"Unterminated Out" ~: do
(output, _) <- runSelf' ["Unterminated", "StdOut"]
output `check` [ToolInput $ T.pack testTool <> " Unterminated StdOut", ToolOutput "Unterminated", ToolExit ExitSuccess],
"Unterminated Err" ~: do
(output, _) <- runSelf' ["Unterminated", "StdErr"]
output `check` [ToolInput $ T.pack testTool <> " Unterminated StdErr", ToolError "Unterminated", ToolExit ExitSuccess],
"GHCi Failed Sart" ~: do
t <- newEmptyMVar
tool <- newGhci' ["MissingFile.hs"] (void EL.consume) $ do
output <- EL.consume
sendTest t $ last output @?= ToolPrompt ""
executeGhciCommand tool ":quit" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":quit",
ToolOutput "Leaving GHCi.",
ToolExit ExitSuccess],
"GHCi" ~: do
t <- newEmptyMVar
tool <- newGhci' [] (void EL.consume) $ do
output <- EL.consume
sendTest t $ last output @?= ToolPrompt ""
executeGhciCommand tool ":m +System.IO" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":m +System.IO",
ToolPrompt ""]
executeGhciCommand tool "hPutStr stderr \"Test\"" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "hPutStr stderr \"Test\"",
ToolError "Test",
ToolPrompt ""]
executeGhciCommand tool "1+1" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "1+1",
ToolOutput "2",
ToolPrompt ""]
executeGhciCommand tool "jfkdfjdkl" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "jfkdfjdkl",
ToolError "",
#if __GLASGOW_HASKELL__ >= 800
ToolError "<interactive>:22:1: error: Variable not in scope: jfkdfjdkl",
#elif __GLASGOW_HASKELL__ > 706
ToolError "<interactive>:23:1: Not in scope: ‘jfkdfjdkl’",
#elif __GLASGOW_HASKELL__ > 702
ToolError "<interactive>:23:1: Not in scope: `jfkdfjdkl'",
#else
ToolError "<interactive>:1:1: Not in scope: `jfkdfjdkl'",
#endif
ToolPrompt ""]
executeGhciCommand tool "\n1+1" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "",
ToolInput "1+1",
ToolOutput "2",
ToolPrompt ""]
executeGhciCommand tool ":m + Prelude" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":m + Prelude",
ToolPrompt ""]
executeGhciCommand tool "\njfkdfjdkl" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "",
ToolInput "jfkdfjdkl",
ToolError "",
#if __GLASGOW_HASKELL__ >= 800
ToolError "<interactive>:35:1: error: Variable not in scope: jfkdfjdkl",
#elif __GLASGOW_HASKELL__ > 706
ToolError "<interactive>:36:1: Not in scope: ‘jfkdfjdkl’",
#elif __GLASGOW_HASKELL__ > 702
ToolError "<interactive>:38:1: Not in scope: `jfkdfjdkl'",
#else
ToolError "<interactive>:1:1: Not in scope: `jfkdfjdkl'",
#endif
ToolPrompt ""]
executeGhciCommand tool "do\n putStrLn \"1\"\n putStrLn \"2\"\n putStrLn \"3\"\n putStrLn \"4\"\n putStrLn \"5\"\n" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "do",
ToolInput " putStrLn \"1\"",
ToolInput " putStrLn \"2\"",
ToolInput " putStrLn \"3\"",
ToolInput " putStrLn \"4\"",
ToolInput " putStrLn \"5\"",
ToolOutput "1",
ToolOutput "2",
ToolOutput "3",
ToolOutput "4",
ToolOutput "5",
ToolPrompt ""]
executeGhciCommand tool "do\n putStrLn \"| 1\"\n putStrLn \"| 2\"\n putStrLn \"| 3\"\n putStrLn \"| 4\"\n putStrLn \"| 5\"\n" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "do",
ToolInput " putStrLn \"| 1\"",
ToolInput " putStrLn \"| 2\"",
ToolInput " putStrLn \"| 3\"",
ToolInput " putStrLn \"| 4\"",
ToolInput " putStrLn \"| 5\"",
ToolOutput "| 1",
ToolOutput "| 2",
ToolOutput "| 3",
ToolOutput "| 4",
ToolOutput "| 5",
ToolPrompt ""]
executeGhciCommand tool "putStr \"ABC\"" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "putStr \"ABC\"",
ToolPrompt "ABC"]
executeGhciCommand tool ":m +Data.List" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":m +Data.List",
ToolPrompt ""]
executeGhciCommand tool ":quit" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":quit",
ToolOutput "Leaving GHCi.",
ToolExit ExitSuccess]
doneTesting t
runTests t]
main :: IO ()
main = do
projectRoot <- findProjectRoot =<< getCurrentDirectory
let testTool = projectRoot </> "dist-newstyle/build" </> ("leksah-server-" <> VERSION_leksah_server)
</> "build/test-tool/test-tool"
args <- getArgs
case args of
[] -> do
doctest ["-isrc", "src/IDE/Utils/CabalPlan.hs", "src/IDE/Utils/CabalProject.hs"] -- updateGlobalLogger rootLoggerName (\ l -> setLevel DEBUG l)
(Counts{failures=failures}, _) <- runTestText (putTextToHandle stderr False) (tests testTool)
if failures == 0
then exitSuccess
else exitFailure
["ExitSuccess"] -> exitSuccess
["Exit42"] -> exitWith (ExitFailure 42)
["BlankLine", o] -> hPutStrLn (h o) ""
["Hello", o] -> hPutStrLn (h o) "Hello World"
["ErrAndOut"] -> hPutStrLn stderr "Error" >> hPutStrLn stdout "Output"
["Unterminated", o] -> hPutStr (h o) "Unterminated" >> hFlush (h o)
_ -> exitFailure
where
h "StdErr" = stderr
h _ = stdout
| null | https://raw.githubusercontent.com/leksah/leksah-server/d4b735c17a36123dc97f79fabf1e9310d74984a6/tests/TestTool.hs | haskell | ---------------------------------------------------------------------------
Module : Main
License : GPL
Maintainer :
Stability : provisional
Portability :
| Windows systems do not often have a real echo executable (so --with-ghc=echo fails)
---------------------------------------------------------------------------
stderr and stdout may not be in sync
updateGlobalLogger rootLoggerName (\ l -> setLevel DEBUG l) | # LANGUAGE CPP , OverloadedStrings #
Copyright : 2007 - 2011 ,
module Main (
main
) where
import System.Environment (getArgs)
import System.Exit (exitWith, exitSuccess, exitFailure, ExitCode(..))
import System.FilePath ((</>))
import Data.Monoid ((<>))
import IDE.Utils.Tool
(toolProcess, executeGhciCommand, ToolOutput(..), runTool',
newGhci')
import System.Process (interruptProcessGroupOf, getProcessExitCode)
import Test.HUnit
((@=?), (@?=), putTextToHandle, Counts(..), runTestTT, assertBool,
runTestText, (~:), Testable(..), Test(..))
import Test.DocTest (doctest)
import System.IO (hPutStr, stdout, hPutStrLn, stderr, hFlush)
import qualified Data.Conduit.List as EL (consume)
import Control.Concurrent
(threadDelay, forkIO, takeMVar, putMVar, newEmptyMVar)
import Control.Monad.IO.Class (liftIO)
import Control.Monad (void, forM_)
import System.Log.Logger
(setLevel, rootLoggerName, updateGlobalLogger)
import System.Log (Priority(..))
import IDE.Utils.CabalProject (findProjectRoot)
import System.Directory (getCurrentDirectory)
import qualified Data.Text as T (pack)
check output expected = do
checkFiltered notOut
checkFiltered notErr
where
checkFiltered f = filter f output @?= filter f expected
notErr (ToolError _) = False
notErr _ = True
notOut (ToolOutput _) = False
notOut _ = True
runTests testMVar = loop
where
loop = do
mbTest <- takeMVar testMVar
case mbTest of
Just test -> do
test
loop
Nothing -> return ()
sendTest testMVar test =
liftIO $ putMVar testMVar $ Just test
doneTesting testMVar =
liftIO $ putMVar testMVar Nothing
tests testTool =
let runSelf' args = runTool' testTool args Nothing Nothing
in test [
"Exit Success" ~: do
(output, _) <- runSelf' ["ExitSuccess"]
output `check` [ToolInput $ T.pack testTool <> " ExitSuccess", ToolExit ExitSuccess],
"Exit Failure" ~: do
(output, _) <- runSelf' ["Exit42"]
output `check` [ToolInput $ T.pack testTool <> " Exit42", ToolExit (ExitFailure 42)],
"Single Blank Out Line" ~: do
(output, _) <- runSelf' ["BlankLine", "StdOut"]
output `check` [ToolInput $ T.pack testTool <> " BlankLine StdOut", ToolOutput "", ToolExit ExitSuccess],
"Single Blank Err Line" ~: do
(output, _) <- runSelf' ["BlankLine", "StdErr"]
output `check` [ToolInput $ T.pack testTool <> " BlankLine StdErr", ToolError "", ToolExit ExitSuccess],
"Hello Out" ~: do
(output, _) <- runSelf' ["Hello", "StdOut"]
output `check` [ToolInput $ T.pack testTool <> " Hello StdOut", ToolOutput "Hello World", ToolExit ExitSuccess],
"Hello Err" ~: do
(output, _) <- runSelf' ["Hello", "StdErr"]
output `check` [ToolInput $ T.pack testTool <> " Hello StdErr", ToolError "Hello World", ToolExit ExitSuccess],
"Both" ~: do
(output, _) <- runSelf' ["ErrAndOut"]
output `check` [ToolInput $ T.pack testTool <> " ErrAndOut", ToolError "Error", ToolOutput "Output", ToolExit ExitSuccess],
"Unterminated Out" ~: do
(output, _) <- runSelf' ["Unterminated", "StdOut"]
output `check` [ToolInput $ T.pack testTool <> " Unterminated StdOut", ToolOutput "Unterminated", ToolExit ExitSuccess],
"Unterminated Err" ~: do
(output, _) <- runSelf' ["Unterminated", "StdErr"]
output `check` [ToolInput $ T.pack testTool <> " Unterminated StdErr", ToolError "Unterminated", ToolExit ExitSuccess],
"GHCi Failed Sart" ~: do
t <- newEmptyMVar
tool <- newGhci' ["MissingFile.hs"] (void EL.consume) $ do
output <- EL.consume
sendTest t $ last output @?= ToolPrompt ""
executeGhciCommand tool ":quit" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":quit",
ToolOutput "Leaving GHCi.",
ToolExit ExitSuccess],
"GHCi" ~: do
t <- newEmptyMVar
tool <- newGhci' [] (void EL.consume) $ do
output <- EL.consume
sendTest t $ last output @?= ToolPrompt ""
executeGhciCommand tool ":m +System.IO" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":m +System.IO",
ToolPrompt ""]
executeGhciCommand tool "hPutStr stderr \"Test\"" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "hPutStr stderr \"Test\"",
ToolError "Test",
ToolPrompt ""]
executeGhciCommand tool "1+1" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "1+1",
ToolOutput "2",
ToolPrompt ""]
executeGhciCommand tool "jfkdfjdkl" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "jfkdfjdkl",
ToolError "",
#if __GLASGOW_HASKELL__ >= 800
ToolError "<interactive>:22:1: error: Variable not in scope: jfkdfjdkl",
#elif __GLASGOW_HASKELL__ > 706
ToolError "<interactive>:23:1: Not in scope: ‘jfkdfjdkl’",
#elif __GLASGOW_HASKELL__ > 702
ToolError "<interactive>:23:1: Not in scope: `jfkdfjdkl'",
#else
ToolError "<interactive>:1:1: Not in scope: `jfkdfjdkl'",
#endif
ToolPrompt ""]
executeGhciCommand tool "\n1+1" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "",
ToolInput "1+1",
ToolOutput "2",
ToolPrompt ""]
executeGhciCommand tool ":m + Prelude" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":m + Prelude",
ToolPrompt ""]
executeGhciCommand tool "\njfkdfjdkl" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "",
ToolInput "jfkdfjdkl",
ToolError "",
#if __GLASGOW_HASKELL__ >= 800
ToolError "<interactive>:35:1: error: Variable not in scope: jfkdfjdkl",
#elif __GLASGOW_HASKELL__ > 706
ToolError "<interactive>:36:1: Not in scope: ‘jfkdfjdkl’",
#elif __GLASGOW_HASKELL__ > 702
ToolError "<interactive>:38:1: Not in scope: `jfkdfjdkl'",
#else
ToolError "<interactive>:1:1: Not in scope: `jfkdfjdkl'",
#endif
ToolPrompt ""]
executeGhciCommand tool "do\n putStrLn \"1\"\n putStrLn \"2\"\n putStrLn \"3\"\n putStrLn \"4\"\n putStrLn \"5\"\n" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "do",
ToolInput " putStrLn \"1\"",
ToolInput " putStrLn \"2\"",
ToolInput " putStrLn \"3\"",
ToolInput " putStrLn \"4\"",
ToolInput " putStrLn \"5\"",
ToolOutput "1",
ToolOutput "2",
ToolOutput "3",
ToolOutput "4",
ToolOutput "5",
ToolPrompt ""]
executeGhciCommand tool "do\n putStrLn \"| 1\"\n putStrLn \"| 2\"\n putStrLn \"| 3\"\n putStrLn \"| 4\"\n putStrLn \"| 5\"\n" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "do",
ToolInput " putStrLn \"| 1\"",
ToolInput " putStrLn \"| 2\"",
ToolInput " putStrLn \"| 3\"",
ToolInput " putStrLn \"| 4\"",
ToolInput " putStrLn \"| 5\"",
ToolOutput "| 1",
ToolOutput "| 2",
ToolOutput "| 3",
ToolOutput "| 4",
ToolOutput "| 5",
ToolPrompt ""]
executeGhciCommand tool "putStr \"ABC\"" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput "putStr \"ABC\"",
ToolPrompt "ABC"]
executeGhciCommand tool ":m +Data.List" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":m +Data.List",
ToolPrompt ""]
executeGhciCommand tool ":quit" $ do
output <- EL.consume
sendTest t $ output `check` [
ToolInput ":quit",
ToolOutput "Leaving GHCi.",
ToolExit ExitSuccess]
doneTesting t
runTests t]
main :: IO ()
main = do
projectRoot <- findProjectRoot =<< getCurrentDirectory
let testTool = projectRoot </> "dist-newstyle/build" </> ("leksah-server-" <> VERSION_leksah_server)
</> "build/test-tool/test-tool"
args <- getArgs
case args of
[] -> do
(Counts{failures=failures}, _) <- runTestText (putTextToHandle stderr False) (tests testTool)
if failures == 0
then exitSuccess
else exitFailure
["ExitSuccess"] -> exitSuccess
["Exit42"] -> exitWith (ExitFailure 42)
["BlankLine", o] -> hPutStrLn (h o) ""
["Hello", o] -> hPutStrLn (h o) "Hello World"
["ErrAndOut"] -> hPutStrLn stderr "Error" >> hPutStrLn stdout "Output"
["Unterminated", o] -> hPutStr (h o) "Unterminated" >> hFlush (h o)
_ -> exitFailure
where
h "StdErr" = stderr
h _ = stdout
|
b7db1e82773433fd376b46c5423ea66cd98cb660dfeff22f28decea9f2348943 | 7even/endless-ships | outfit_page.cljs | (ns endless-ships.views.outfit-page
(:require [re-frame.core :as rf]
[endless-ships.subs :as subs]
[endless-ships.views.utils :refer [render-attribute render-description
kebabize nbspize]]
[endless-ships.routes :as routes]))
(defn- render-license [outfit]
(let [[license] (:licenses outfit)]
(when (some? license)
[:p.italic
{:style {:margin-top 20}}
(str "This outfit requires a " license " license.")])))
(defn- image-url [outfit]
(let [filename (str (-> outfit :thumbnail js/window.encodeURI) ".png")]
(str "-sky/endless-sky/master/images/" filename)))
(defn- render-ammo [outfit]
(when (contains? outfit :ammo)
[:li "ammo: " (routes/outfit-link (:ammo outfit))]))
(defn weapon-attributes [weapon]
[:div
[:br]
(render-ammo weapon)
(render-attribute weapon :missile-strength "missile strength")
(render-attribute weapon :anti-missile "anti-missile")
(render-attribute weapon :range "range")
(render-attribute weapon (comp :per-second :shield-damage) "shield damage / second")
(render-attribute weapon (comp :per-second :hull-damage) "hull damage / second")
(render-attribute weapon (comp :per-second :heat-damage) "heat damage / second")
(render-attribute weapon (comp :per-second :ion-damage) "ion damage / second")
(render-attribute weapon (comp :per-second :disruption-damage) "disruption damage / second")
(render-attribute weapon (comp :per-second :slowing-damage) "slowing damage / second")
(render-attribute weapon (comp :per-second :firing-energy) "firing energy / second")
(render-attribute weapon (comp :per-second :firing-heat) "firing heat / second")
(render-attribute weapon (comp :per-second :firing-fuel) "firing fuel / second")
(render-attribute weapon :shots-per-second "shots / second")
(render-attribute weapon :turret-turn "turret turn rate")
(when (and (contains? weapon :shots-per-second)
(number? (:shots-per-second weapon)))
[:br])
(render-attribute weapon (comp :per-shot :shield-damage) "shield damage / shot")
(render-attribute weapon (comp :per-shot :hull-damage) "hull damage / shot")
(render-attribute weapon (comp :per-shot :heat-damage) "heat damage / shot")
(render-attribute weapon (comp :per-shot :ion-damage) "ion damage / shot")
(render-attribute weapon (comp :per-shot :disruption-damage) "disruption damage / shot")
(render-attribute weapon (comp :per-shot :slowing-damage) "slowing damage / shot")
(render-attribute weapon (comp :per-shot :firing-energy) "firing energy / shot")
(render-attribute weapon (comp :per-shot :firing-heat) "firing heat / shot")
(render-attribute weapon :inaccuracy "inaccuracy")])
(defn outfit-page [outfit-name]
(let [outfit @(rf/subscribe [::subs/outfit outfit-name])
installations @(rf/subscribe [::subs/outfit-installations (:name outfit)])
planets @(rf/subscribe [::subs/outfit-planets (:name outfit)])]
[:div.app
[:div.row
[:div.col-md-12
[:div.panel.panel-default
[:div.panel-heading (:name outfit)]
[:div.panel-body
[:div.media
[:div.media-body
[:div.row
[:div.col-md-4
(if (seq (:description outfit))
(render-description outfit)
[:p.italic "No description."])
(render-license outfit)]
[:div.col-md-4
[:ul
(render-attribute outfit :category "category")
(render-attribute outfit :cost "cost")
(render-attribute outfit :outfit-space "outfit space needed")
(render-attribute outfit :weapon-capacity "weapon capacity needed")
(render-attribute outfit :engine-capacity "engine capacity needed")
(when (contains? outfit :gun-ports)
(render-attribute outfit (comp - :gun-ports) "gun ports needed"))
(when (contains? outfit :turret-mounts)
(render-attribute outfit (comp - :turret-mounts) "turret mounts needed"))]]
[:div.col-md-4
(when (contains? outfit :hyperdrive)
[:p.italic "Allows you to make hyperjumps."])
(when (contains? outfit :jump-drive)
[:p.italic "Lets you jump to any nearby system."])
(when (= (:installable outfit) -1)
[:p.italic "This is not an installable item."])
(when (contains? outfit :minable)
[:p.italic "This item is mined from asteroids."])
[:ul
(render-attribute outfit :mass "mass")
(render-attribute outfit :thrust "thrust")
(render-attribute outfit :thrusting-energy "thrusting energy")
(render-attribute outfit :thrusting-heat "thrusting heat")
(render-attribute outfit :turn "turn")
(render-attribute outfit :turning-energy "turning energy")
(render-attribute outfit :turning-heat "turning heat")
(render-attribute outfit :afterburner-energy "afterburner energy")
(render-attribute outfit :afterburner-fuel "afterburner fuel")
(render-attribute outfit :afterburner-heat "afterburner heat")
(render-attribute outfit :afterburner-thrust "afterburner thrust")
(render-attribute outfit :reverse-thrust "reverse thrust")
(render-attribute outfit :reverse-thrusting-energy "reverse thrusting energy")
(render-attribute outfit :reverse-thrusting-heat "reverse thrusting heat")
(render-attribute outfit :energy-generation "energy generation")
(render-attribute outfit :solar-collection "solar collection")
(render-attribute outfit :energy-capacity "energy capacity")
(render-attribute outfit :energy-consumption "energy consumption")
(render-attribute outfit :heat-generation "heat generation")
(render-attribute outfit :cooling "cooling")
(render-attribute outfit :active-cooling "active cooling")
(render-attribute outfit :cooling-energy "cooling energy")
(render-attribute outfit :hull-repair-rate "hull repair rate")
(render-attribute outfit :hull-energy "hull energy")
(render-attribute outfit :hull-heat "hull heat")
(render-attribute outfit :shield-generation "shield generation")
(render-attribute outfit :shield-energy "shield energy")
(render-attribute outfit :shield-heat "shield heat")
(render-attribute outfit :ramscoop "ramscoop")
(render-attribute outfit :required-crew "required crew")
(render-attribute outfit :capture-attack "capture attack")
(render-attribute outfit :capture-defense "capture defense")
(render-attribute outfit :illegal "illegal")
(render-attribute outfit :cargo-space "cargo space")
(render-attribute outfit :cooling-inefficiency "cooling inefficiency")
(render-attribute outfit :heat-dissipation "heat dissipation")
(render-attribute outfit :fuel-capacity "fuel capacity")
(render-attribute outfit :jump-fuel "jump fuel")
(render-attribute outfit :jump-speed "jump speed")
(render-attribute outfit :scram-drive "scram drive")
(render-attribute outfit :atmosphere-scan "atmosphere scan")
(render-attribute outfit :cargo-scan-power "cargo scan power")
(render-attribute outfit :cargo-scan-speed "cargo scan speed")
(render-attribute outfit :outfit-scan-power "outfit scan power")
(render-attribute outfit :outfit-scan-speed "outfit scan speed")
(render-attribute outfit :asteroid-scan-power "asteroid scan power")
(render-attribute outfit :tactical-scan-power "tactical scan power")
(render-attribute outfit :scan-interference "scan interference")
(render-attribute outfit :radar-jamming "radar jamming")
(render-attribute outfit :cloak "cloak")
(render-attribute outfit :cloaking-energy "cloaking energy")
(render-attribute outfit :cloaking-fuel "cloaking fuel")
(render-attribute outfit :bunks "bunks")
(render-attribute outfit :automaton "automaton")
(render-attribute outfit :quantum-keystone "quantum keystone")
(render-attribute outfit :map "map")
(render-ammo outfit)
(render-attribute outfit :gatling-round-capacity "gatling round capacity")
(render-attribute outfit :javelin-capacity "javelin capacity")
(render-attribute outfit :finisher-capacity "finisher capacity")
(render-attribute outfit :tracker-capacity "tracker capacity")
(render-attribute outfit :rocket-capacity "rocket capacity")
(render-attribute outfit :minelayer-capacity "minelayer capacity")
(render-attribute outfit :piercer-capacity "piercer capacity")
(render-attribute outfit :meteor-capacity "meteor capacity")
(render-attribute outfit :railgun-slug-capacity "railgun slug capacity")
(render-attribute outfit :sidewinder-capacity "sidewinder capacity")
(render-attribute outfit :thunderhead-capacity "thunderhead capacity")
(render-attribute outfit :torpedo-capacity "torpedo capacity")
(render-attribute outfit :typhoon-capacity "typhoon capacity")
(render-attribute outfit :emp-torpedo-capacity "EMP torpedo capacity")
(render-attribute outfit :firestorm-torpedo-capacity "firestorm torpedo capacity")
(render-attribute outfit :firelight-missile-capacity "firelight missile capacity")
(when (contains? outfit :weapon)
[weapon-attributes (:weapon outfit)])]
(when (contains? outfit :unplunderable)
[:p.italic "This outfit cannot be plundered."])]]]
[:div.media-right
(when (contains? outfit :thumbnail)
[:img {:src (image-url outfit)}])]]]]]]
[:div.row
[:div.col-md-6
[:div.panel.panel-default
[:div.panel-heading (str "Installed on " (count installations) " ships")]
(when (seq installations)
[:div.panel-body
[:ul.list-group
(for [{:keys [ship-name ship-modification quantity]} installations]
(let [link (if (some? ship-modification)
(routes/ship-modification-link ship-name ship-modification)
(routes/ship-link ship-name))
key [ship-name ship-modification]]
(if (= quantity 1)
^{:key key} [:li.list-group-item link]
^{:key key} [:li.list-group-item
[:span.badge quantity]
link])))]])]]
[:div.col-md-6
[:div.panel.panel-default
[:div.panel-heading (str "Sold at " (count planets) " planets")]
(when (seq planets)
[:div.panel-body
[:ul.list-group
(for [{:keys [name system]} planets]
^{:key name} [:li.list-group-item
name
" "
[:span.label.label-default system]])]])]]]]))
| null | https://raw.githubusercontent.com/7even/endless-ships/acb7ee2852a6bc2f80137bc8aa2e3541ceed83ff/src/cljs/endless_ships/views/outfit_page.cljs | clojure | (ns endless-ships.views.outfit-page
(:require [re-frame.core :as rf]
[endless-ships.subs :as subs]
[endless-ships.views.utils :refer [render-attribute render-description
kebabize nbspize]]
[endless-ships.routes :as routes]))
(defn- render-license [outfit]
(let [[license] (:licenses outfit)]
(when (some? license)
[:p.italic
{:style {:margin-top 20}}
(str "This outfit requires a " license " license.")])))
(defn- image-url [outfit]
(let [filename (str (-> outfit :thumbnail js/window.encodeURI) ".png")]
(str "-sky/endless-sky/master/images/" filename)))
(defn- render-ammo [outfit]
(when (contains? outfit :ammo)
[:li "ammo: " (routes/outfit-link (:ammo outfit))]))
(defn weapon-attributes [weapon]
[:div
[:br]
(render-ammo weapon)
(render-attribute weapon :missile-strength "missile strength")
(render-attribute weapon :anti-missile "anti-missile")
(render-attribute weapon :range "range")
(render-attribute weapon (comp :per-second :shield-damage) "shield damage / second")
(render-attribute weapon (comp :per-second :hull-damage) "hull damage / second")
(render-attribute weapon (comp :per-second :heat-damage) "heat damage / second")
(render-attribute weapon (comp :per-second :ion-damage) "ion damage / second")
(render-attribute weapon (comp :per-second :disruption-damage) "disruption damage / second")
(render-attribute weapon (comp :per-second :slowing-damage) "slowing damage / second")
(render-attribute weapon (comp :per-second :firing-energy) "firing energy / second")
(render-attribute weapon (comp :per-second :firing-heat) "firing heat / second")
(render-attribute weapon (comp :per-second :firing-fuel) "firing fuel / second")
(render-attribute weapon :shots-per-second "shots / second")
(render-attribute weapon :turret-turn "turret turn rate")
(when (and (contains? weapon :shots-per-second)
(number? (:shots-per-second weapon)))
[:br])
(render-attribute weapon (comp :per-shot :shield-damage) "shield damage / shot")
(render-attribute weapon (comp :per-shot :hull-damage) "hull damage / shot")
(render-attribute weapon (comp :per-shot :heat-damage) "heat damage / shot")
(render-attribute weapon (comp :per-shot :ion-damage) "ion damage / shot")
(render-attribute weapon (comp :per-shot :disruption-damage) "disruption damage / shot")
(render-attribute weapon (comp :per-shot :slowing-damage) "slowing damage / shot")
(render-attribute weapon (comp :per-shot :firing-energy) "firing energy / shot")
(render-attribute weapon (comp :per-shot :firing-heat) "firing heat / shot")
(render-attribute weapon :inaccuracy "inaccuracy")])
(defn outfit-page [outfit-name]
(let [outfit @(rf/subscribe [::subs/outfit outfit-name])
installations @(rf/subscribe [::subs/outfit-installations (:name outfit)])
planets @(rf/subscribe [::subs/outfit-planets (:name outfit)])]
[:div.app
[:div.row
[:div.col-md-12
[:div.panel.panel-default
[:div.panel-heading (:name outfit)]
[:div.panel-body
[:div.media
[:div.media-body
[:div.row
[:div.col-md-4
(if (seq (:description outfit))
(render-description outfit)
[:p.italic "No description."])
(render-license outfit)]
[:div.col-md-4
[:ul
(render-attribute outfit :category "category")
(render-attribute outfit :cost "cost")
(render-attribute outfit :outfit-space "outfit space needed")
(render-attribute outfit :weapon-capacity "weapon capacity needed")
(render-attribute outfit :engine-capacity "engine capacity needed")
(when (contains? outfit :gun-ports)
(render-attribute outfit (comp - :gun-ports) "gun ports needed"))
(when (contains? outfit :turret-mounts)
(render-attribute outfit (comp - :turret-mounts) "turret mounts needed"))]]
[:div.col-md-4
(when (contains? outfit :hyperdrive)
[:p.italic "Allows you to make hyperjumps."])
(when (contains? outfit :jump-drive)
[:p.italic "Lets you jump to any nearby system."])
(when (= (:installable outfit) -1)
[:p.italic "This is not an installable item."])
(when (contains? outfit :minable)
[:p.italic "This item is mined from asteroids."])
[:ul
(render-attribute outfit :mass "mass")
(render-attribute outfit :thrust "thrust")
(render-attribute outfit :thrusting-energy "thrusting energy")
(render-attribute outfit :thrusting-heat "thrusting heat")
(render-attribute outfit :turn "turn")
(render-attribute outfit :turning-energy "turning energy")
(render-attribute outfit :turning-heat "turning heat")
(render-attribute outfit :afterburner-energy "afterburner energy")
(render-attribute outfit :afterburner-fuel "afterburner fuel")
(render-attribute outfit :afterburner-heat "afterburner heat")
(render-attribute outfit :afterburner-thrust "afterburner thrust")
(render-attribute outfit :reverse-thrust "reverse thrust")
(render-attribute outfit :reverse-thrusting-energy "reverse thrusting energy")
(render-attribute outfit :reverse-thrusting-heat "reverse thrusting heat")
(render-attribute outfit :energy-generation "energy generation")
(render-attribute outfit :solar-collection "solar collection")
(render-attribute outfit :energy-capacity "energy capacity")
(render-attribute outfit :energy-consumption "energy consumption")
(render-attribute outfit :heat-generation "heat generation")
(render-attribute outfit :cooling "cooling")
(render-attribute outfit :active-cooling "active cooling")
(render-attribute outfit :cooling-energy "cooling energy")
(render-attribute outfit :hull-repair-rate "hull repair rate")
(render-attribute outfit :hull-energy "hull energy")
(render-attribute outfit :hull-heat "hull heat")
(render-attribute outfit :shield-generation "shield generation")
(render-attribute outfit :shield-energy "shield energy")
(render-attribute outfit :shield-heat "shield heat")
(render-attribute outfit :ramscoop "ramscoop")
(render-attribute outfit :required-crew "required crew")
(render-attribute outfit :capture-attack "capture attack")
(render-attribute outfit :capture-defense "capture defense")
(render-attribute outfit :illegal "illegal")
(render-attribute outfit :cargo-space "cargo space")
(render-attribute outfit :cooling-inefficiency "cooling inefficiency")
(render-attribute outfit :heat-dissipation "heat dissipation")
(render-attribute outfit :fuel-capacity "fuel capacity")
(render-attribute outfit :jump-fuel "jump fuel")
(render-attribute outfit :jump-speed "jump speed")
(render-attribute outfit :scram-drive "scram drive")
(render-attribute outfit :atmosphere-scan "atmosphere scan")
(render-attribute outfit :cargo-scan-power "cargo scan power")
(render-attribute outfit :cargo-scan-speed "cargo scan speed")
(render-attribute outfit :outfit-scan-power "outfit scan power")
(render-attribute outfit :outfit-scan-speed "outfit scan speed")
(render-attribute outfit :asteroid-scan-power "asteroid scan power")
(render-attribute outfit :tactical-scan-power "tactical scan power")
(render-attribute outfit :scan-interference "scan interference")
(render-attribute outfit :radar-jamming "radar jamming")
(render-attribute outfit :cloak "cloak")
(render-attribute outfit :cloaking-energy "cloaking energy")
(render-attribute outfit :cloaking-fuel "cloaking fuel")
(render-attribute outfit :bunks "bunks")
(render-attribute outfit :automaton "automaton")
(render-attribute outfit :quantum-keystone "quantum keystone")
(render-attribute outfit :map "map")
(render-ammo outfit)
(render-attribute outfit :gatling-round-capacity "gatling round capacity")
(render-attribute outfit :javelin-capacity "javelin capacity")
(render-attribute outfit :finisher-capacity "finisher capacity")
(render-attribute outfit :tracker-capacity "tracker capacity")
(render-attribute outfit :rocket-capacity "rocket capacity")
(render-attribute outfit :minelayer-capacity "minelayer capacity")
(render-attribute outfit :piercer-capacity "piercer capacity")
(render-attribute outfit :meteor-capacity "meteor capacity")
(render-attribute outfit :railgun-slug-capacity "railgun slug capacity")
(render-attribute outfit :sidewinder-capacity "sidewinder capacity")
(render-attribute outfit :thunderhead-capacity "thunderhead capacity")
(render-attribute outfit :torpedo-capacity "torpedo capacity")
(render-attribute outfit :typhoon-capacity "typhoon capacity")
(render-attribute outfit :emp-torpedo-capacity "EMP torpedo capacity")
(render-attribute outfit :firestorm-torpedo-capacity "firestorm torpedo capacity")
(render-attribute outfit :firelight-missile-capacity "firelight missile capacity")
(when (contains? outfit :weapon)
[weapon-attributes (:weapon outfit)])]
(when (contains? outfit :unplunderable)
[:p.italic "This outfit cannot be plundered."])]]]
[:div.media-right
(when (contains? outfit :thumbnail)
[:img {:src (image-url outfit)}])]]]]]]
[:div.row
[:div.col-md-6
[:div.panel.panel-default
[:div.panel-heading (str "Installed on " (count installations) " ships")]
(when (seq installations)
[:div.panel-body
[:ul.list-group
(for [{:keys [ship-name ship-modification quantity]} installations]
(let [link (if (some? ship-modification)
(routes/ship-modification-link ship-name ship-modification)
(routes/ship-link ship-name))
key [ship-name ship-modification]]
(if (= quantity 1)
^{:key key} [:li.list-group-item link]
^{:key key} [:li.list-group-item
[:span.badge quantity]
link])))]])]]
[:div.col-md-6
[:div.panel.panel-default
[:div.panel-heading (str "Sold at " (count planets) " planets")]
(when (seq planets)
[:div.panel-body
[:ul.list-group
(for [{:keys [name system]} planets]
^{:key name} [:li.list-group-item
name
" "
[:span.label.label-default system]])]])]]]]))
| |
aabaab1f633edee5510c8dc833860ff0d4382a0bf9eea09b084b062bf65b8e68 | qitab/cl-protobufs | serialization-test.lisp | Copyright 2012 - 2020 Google LLC
;;;
Use of this source code is governed by an MIT - style
;;; license that can be found in the LICENSE file or at
;;; .
(defpackage #:cl-protobufs.test.serialization
(:use #:cl
#:clunit
#:cl-protobufs
#:cl-protobufs.serialization-test)
(:local-nicknames (#:pi #:cl-protobufs.implementation))
(:export :run))
(in-package #:cl-protobufs.test.serialization)
(defsuite serialization-suite (cl-protobufs.test:root-suite))
(defun run (&key use-debugger)
"Run all tests in the test suite.
Parameters
USE-DEBUGGER: On assert failure bring up the debugger."
(clunit:run-suite 'serialization-suite :use-debugger use-debugger
:signal-condition-on-fail t))
(defvar *tser5-bytes* #(8 1 16 2 16 3 16 5 16 7 26 3 116 119
111 26 5 116 104 114 101 101 26 4 102
105 118 101 26 5 115 101 118 101 110))
(defvar *tser6-bytes* #(8 2 8 3 8 5 8 7 18 3 116 119 111 18 5
116 104 114 101 101 18 4 102 105 118
101 18 5 115 101 118 101 110 26 9 18
7 116 101 115 116 105 110 103 26 7 18
5 49 32 50 32 51))
(defvar *tser7-bytes* #(10 5 115 101 118 101 110 16 2 16 27
27 10 2 103 49 16 1 16 1 16 2 16 3 28
27 10 2 103 50 28 34 3 116 119 111))
(deftest basic-serialization (serialization-suite)
;; clunit2:deftest does very strange things with its &body, which makes
;; debugging more difficult, so let's not give it that chance.
(do-basic-serialization))
(defun do-basic-serialization ()
(loop :for optimized :in '(nil t)
:do
;; TODO(cgay): This makes the tests non-repeatable in the REPL. Either
;; find a safe way to delete the optimized serializers after the test,
;; separate into optimized and non-optimized tests, or remove the
;; non-optimized path completely. Similar problem in other tests.
(when optimized
(dolist (class '(basic-test1 basic-test2 basic-test3 basic-test4
basic-test5 basic-test6 basic-test7.subgroups))
(let ((message (find-message-descriptor class :error-p t)))
(handler-bind ((style-warning #'muffle-warning))
(eval (pi::generate-deserializer message))
(eval (pi::generate-serializer message))))))
(let* ((test1 (make-basic-test1 :intval 150))
(test1b (make-basic-test1 :intval -150))
(test2 (make-basic-test2 :strval "testing"))
(test2b (make-basic-test2 :strval "1 2 3"))
(test3 (make-basic-test3 :recval test1))
(test4 (make-basic-test4 :recval test2))
(test5 (make-basic-test5
:color :red :intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")))
(test6 (make-basic-test6
:intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")
:recvals (list test2 test2b)))
(group1 (make-basic-test7.subgroups
:strval "g1"
:intvals '(1 1 2 3)))
(group2 (make-basic-test7.subgroups
:strval "g2"))
(test7 (make-basic-test7
:strval1 "seven"
:intvals '(2 27)
:subgroups (list group1 group2)
:strval2 "two")))
(let ((tser1 (serialize-to-bytes test1 'basic-test1))
(tser1b (serialize-to-bytes test1b 'basic-test1))
(tser2 (serialize-to-bytes test2 'basic-test2))
(tser3 (serialize-to-bytes test3 'basic-test3))
(tser4 (serialize-to-bytes test4 'basic-test4))
(tser5 (serialize-to-bytes test5 'basic-test5))
(tser6 (serialize-to-bytes test6 'basic-test6))
(tser7 (serialize-to-bytes test7 'basic-test7)))
(assert-equalp #(#x08 #x96 #x01) tser1)
(assert-equalp #(#x08 #xEA #xFE #xFF #xFF #x0F) tser1b)
(assert-equalp #(#x12 #x07 #x74 #x65 #x73 #x74 #x69 #x6E #x67) tser2)
(assert-equalp #(#x1A #x03 #x08 #x96 #x01) tser3)
(assert-equalp #(#x1A #x09 #x12 #x07 #x74 #x65 #x73 #x74 #x69 #x6E #x67) tser4)
(assert-equalp *tser5-bytes* tser5)
(assert-equalp *tser6-bytes* tser6)
(assert-equalp *tser7-bytes* tser7)
(macrolet ((slots-equalp (obj1 obj2 &rest slots)
(pi::with-gensyms (vobj1 vobj2)
(pi::with-collectors ((forms collect-form))
(dolist (slot slots)
(collect-form
`(assert-equalp
(proto-slot-value ,vobj1 ',slot)
(proto-slot-value ,vobj2 ',slot))))
`(let ((,vobj1 ,obj1)
(,vobj2 ,obj2))
,@forms)))))
(slots-equalp test1 (deserialize-from-bytes 'basic-test1 tser1)
intval)
(slots-equalp test1b (deserialize-from-bytes 'basic-test1 tser1b)
intval)
(slots-equalp test2 (deserialize-from-bytes 'basic-test2 tser2)
intval strval)
(slots-equalp test3 (deserialize-from-bytes 'basic-test3 tser3)
intval strval)
(slots-equalp (recval test3)
(recval (deserialize-from-bytes 'basic-test3 tser3))
intval)
(slots-equalp test4 (deserialize-from-bytes 'basic-test4 tser4)
intval strval)
(slots-equalp (recval test4)
(recval (deserialize-from-bytes 'basic-test4 tser4))
intval strval)
(slots-equalp test5 (deserialize-from-bytes 'basic-test5 tser5)
color intvals strvals)
(slots-equalp test6 (deserialize-from-bytes 'basic-test6 tser6)
intvals strvals)
(slots-equalp (first (recvals test6))
(first (recvals (deserialize-from-bytes 'basic-test6 tser6)))
strval)
(slots-equalp (second (recvals test6))
(second (recvals (deserialize-from-bytes 'basic-test6 tser6)))
strval)
(slots-equalp test7 (deserialize-from-bytes 'basic-test7 tser7)
strval1 intvals strval2)
(slots-equalp (first (subgroups test7))
(first (subgroups (deserialize-from-bytes 'basic-test7 tser7)))
strval intvals)
(slots-equalp (second (subgroups test7))
(second (subgroups (deserialize-from-bytes 'basic-test7 tser7)))
strval intvals))))))
(deftest text-serialization (serialization-suite)
(let* ((test1 (make-basic-test1 :intval 150))
(test1b (make-basic-test1 :intval -150))
(test2 (make-basic-test2 :strval "testing"))
(test2b (make-basic-test2 :strval "1 2 3"))
(test3 (make-basic-test3 :recval test1))
(test4 (make-basic-test4 :recval test2))
(test5 (make-basic-test5
:color :red :intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")))
(test6 (make-basic-test6
:intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")
:recvals (list test2 test2b))))
(let ((tser1 (serialize-to-bytes test1 'basic-test1))
(tser1b (serialize-to-bytes test1b 'basic-test1))
(tser2 (serialize-to-bytes test2 'basic-test2))
(tser3 (serialize-to-bytes test3 'basic-test3))
(tser4 (serialize-to-bytes test4 'basic-test4))
(tser5 (serialize-to-bytes test5 'basic-test5))
(tser6 (serialize-to-bytes test6 'basic-test6)))
(macrolet ((slots-equalp (obj1 obj2 &rest slots)
(pi::with-gensyms (vobj1 vobj2)
(pi::with-collectors ((forms collect-form))
(dolist (slot slots)
(collect-form
`(assert-equalp (,slot ,vobj1) (,slot ,vobj2))))
`(let ((,vobj1 ,obj1)
(,vobj2 ,obj2))
,@forms)))))
(let ((text (with-output-to-string (s)
(print-text-format test1 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test1 tser1)
:stream s)))
(slots-equalp test1 (with-input-from-string (s text)
(parse-text-format 'basic-test1 :stream s))
intval))
(let ((text (with-output-to-string (s)
(print-text-format test1b :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test1 tser1b)
:stream s)))
(slots-equalp test1b (with-input-from-string (s text)
(parse-text-format 'basic-test1 :stream s))
intval))
(let ((text (with-output-to-string (s)
(print-text-format test2 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test2 tser2)
:stream s)))
(slots-equalp test2 (with-input-from-string (s text)
(parse-text-format 'basic-test2 :stream s))
intval strval))
(let ((text (with-output-to-string (s)
(print-text-format test3 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test3 tser3)
:stream s)))
(slots-equalp test3 (with-input-from-string (s text)
(parse-text-format 'basic-test3 :stream s))
intval strval)
(slots-equalp (recval test3)
(recval (with-input-from-string (s text)
(parse-text-format 'basic-test3 :stream s)))
intval))
(let ((text (with-output-to-string (s)
(print-text-format test4 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test4 tser4)
:stream s)))
(slots-equalp test4 (with-input-from-string (s text)
(parse-text-format 'basic-test4 :stream s))
intval strval)
(slots-equalp (recval test4)
(recval (with-input-from-string (s text)
(parse-text-format 'basic-test4 :stream s)))
intval strval))
(let ((text (with-output-to-string (s)
(print-text-format test5 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test5 tser5)
:stream s)))
(slots-equalp test5 (with-input-from-string (s text)
(parse-text-format 'basic-test5 :stream s))
color intvals strvals))
(let ((text (with-output-to-string (s)
(print-text-format test6 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test6 tser6)
:stream s)))
(slots-equalp test6 (with-input-from-string (s text)
(parse-text-format 'basic-test6 :stream s))
intvals strvals)
(slots-equalp (first (recvals test6))
(first (recvals
(with-input-from-string (s text)
(parse-text-format 'basic-test6 :stream s))))
strval)
(slots-equalp (second (recvals test6))
(second (recvals
(with-input-from-string (s text)
(parse-text-format 'basic-test6 :stream s))))
strval))))))
(deftest serialization-integrity (serialization-suite)
(flet ((do-test (message)
(let* ((type (type-of message))
(buf (serialize-to-bytes message type))
(new (deserialize-from-bytes type buf))
(newbuf (serialize-to-bytes new type)))
(assert-equalp (length buf) (length newbuf))
(assert-equalp buf newbuf)
(assert-equal
(with-output-to-string (s)
(print-text-format message :stream s))
(with-output-to-string (s)
(print-text-format new :stream s))))))
(do-test (make-outer :i 4))
(do-test (make-outer :i -4))
(let ((inner-1 (mapcar #'(lambda (i) (make-inner :i i)) '(1 2 3)))
(inner-2 (mapcar #'(lambda (i) (make-inner :i i)) '(-1 -2 -3)))
(simple-1 (make-inner :i 4))
(simple-2 (make-inner :i -4)))
(do-test (make-outer :inner inner-1))
(do-test (make-outer :inner inner-2))
(do-test (make-outer :simple simple-1))
(do-test (make-outer :simple simple-2)))))
(deftest empty-message-serialization (serialization-suite)
(let ((speed0 (make-speed-empty))
(speed1 (make-speed-optional))
(speed2 (make-speed-repeated))
(space0 (make-space-empty))
(space1 (make-space-optional))
(space2 (make-space-repeated)))
(setf (foo speed1) speed0)
(setf (foo space1) space0)
(push speed0 (foo speed2))
(push space0 (foo space2))
(let ((ser-speed0 (serialize-to-bytes speed0 (type-of speed0)))
(ser-speed1 (serialize-to-bytes speed1 (type-of speed1)))
(ser-speed2 (serialize-to-bytes speed2 (type-of speed2)))
(ser-space0 (serialize-to-bytes space0 (type-of space0)))
(ser-space1 (serialize-to-bytes space1 (type-of space1)))
(ser-space2 (serialize-to-bytes space2 (type-of space2))))
(assert-equalp ser-speed0 #())
(assert-equalp ser-speed1 #(#x0A #x00))
(assert-equalp ser-speed2 #(#x0A #x00))
(assert-equalp ser-space0 #())
(assert-equalp ser-space1 #(#x0A #x00))
(assert-equalp ser-space2 #(#x0A #x00)))))
;; Extension example
;; This test can not (or should not) work with optimize :SPEED because of poor Lisp style,
;; the behavior of which is undefined although practically speaking it does what you think.
;; The DEFINE-MESSAGE for AUTO-COLOR creates fast serialize/deserialize functions,
;; and so does the DEFINE-EXTEND AUTO-COLOR but with more fields.
It so happens that the behavior is to instate the second definition ,
while returning T for WARNING - P and ERROR - P from the compile - file operation in SBCL .
This used to work by accident , because DEFMETHOD never detects that you 've defined
a method twice in one file using the * exact * * same * qualifiers and specializers .
;; The introspection-based (de)serialize functions don't have this issue
;; because nothing happens with regard to (de)serialization until just-in-time.
;;; The define-service macro expands to code in a package named <current-package>-rpc.
;;; Normally the package would be created in the generated code but we do it manually
;;; here because we call define-service directly.
(defpackage #:cl-protobufs.test.serialization-rpc (:use))
(pi:define-service buy-car ()
(buy-car (buy-car-request => buy-car-response)
:options (:deadline 1.0)))
(deftest extension-serialization (serialization-suite)
(let* ((color1 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car1 (make-automobile :model "Audi" :color color1))
(request-1 (make-buy-car-request :auto car1))
(color2 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car2 (make-automobile :model "Audi" :color color2))
(request-2 (make-buy-car-request :auto car2)))
(setf (paint-type color2) :metallic)
(let ((ser1 (serialize-to-bytes request-1 'buy-car-request))
(ser2 (serialize-to-bytes request-2 'buy-car-request)))
(assert-false (equal ser1 ser2))
(assert-equal
(with-output-to-string (s)
(print-text-format request-1 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser1) :stream s)))
(assert-equal
(with-output-to-string (s)
(print-text-format request-2 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser2) :stream s))))
(let ((str1 (with-output-to-string (s)
(print-text-format request-1 :stream s)))
(str2 (with-output-to-string (s)
(print-text-format request-2 :stream s))))
(assert-false (string= str1 str2))
(assert-false (search "paint_type:" str1 :test #'char=))
(assert-true (search "paint_type:" str2 :test #'char=)))))
(defun clear-serialization-functions (proto-name)
#-sbcl
(setf (get `,proto-name :serialize) nil
(get `,proto-name :deserialize) nil)
#+sbcl (fmakunbound (list :protobuf :serialize proto-name))
#+sbcl (fmakunbound (list :protobuf :deserialize proto-name)))
(defun create-ext-serialization-functions ()
(pi::make-serializer auto-color)
(pi::make-serializer automobile)
(pi::make-serializer buy-car-request)
(pi::make-deserializer automobile)
(pi::make-deserializer auto-color)
(pi::make-deserializer buy-car-request))
(defun clear-ext-proto-serialization-functions ()
(loop for message in '(auto-color automobile buy-car-request)
do
(clear-serialization-functions message)))
(deftest extension-serialization-optimized (serialization-suite)
(create-ext-serialization-functions)
(let* ((color1 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car1 (make-automobile :model "Audi" :color color1))
(request-1 (make-buy-car-request :auto car1))
(color2 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car2 (make-automobile :model "Audi" :color color2))
(request-2 (make-buy-car-request :auto car2)))
(setf (paint-type color2) :metallic)
(let ((ser1 (serialize-to-bytes request-1 'buy-car-request))
(ser2 (serialize-to-bytes request-2 'buy-car-request)))
(assert-false (equal ser1 ser2))
(assert-equal
(with-output-to-string (s)
(print-text-format request-1 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser1) :stream s)))
(assert-equal
(with-output-to-string (s)
(print-text-format request-2 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser2) :stream s))))
(let ((str1 (with-output-to-string (s)
(print-text-format request-1 :stream s)))
(str2 (with-output-to-string (s)
(print-text-format request-2 :stream s))))
(assert-false (string= str1 str2))
(assert-false (search "paint_type:" str1 :test #'char=))
(assert-true (search "paint_type:" str2 :test #'char=))))
(clear-ext-proto-serialization-functions))
(deftest group-serialization (serialization-suite)
(let* ((meta1 (make-color-wheel1.metadata1 :revision "1.0"))
(wheel1 (make-color-wheel1 :name "Colors" :metadata meta1))
(color1 (make-color1 :r-value 100 :g-value 0 :b-value 100))
(request-1 (make-add-color1 :wheel wheel1 :color color1))
(meta2 (make-color-wheel2.metadata :revision "1.0"))
(wheel2 (make-color-wheel2 :name "Colors" :metadata meta2))
(color2 (make-color2 :r-value 100 :g-value 0 :b-value 100))
(request-2 (make-add-color2 :wheel wheel2 :color color2))
(request-3 (make-color-wheel2-wrap :id 9001 :wheel wheel2 :metaname "meta")))
(let ((ser1 (serialize-to-bytes request-1 'add-color1))
(ser2 (serialize-to-bytes request-2 'add-color2)))
(assert-equal
(subseq (with-output-to-string (s)
(print-text-format request-1 :stream s))
9)
(subseq (with-output-to-string (s)
(print-text-format request-2 :stream s))
9))
(assert-equal
(subseq (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'add-color1 ser1) :stream s))
9)
(subseq (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'add-color2 ser2) :stream s))
9))
;; This tests the optimized serializer's ability to serialize messages
;; which have nested messages which have group fields.
(pi::make-serializer color-wheel2.metadata)
(pi::make-serializer color2)
(pi::make-serializer color-wheel2)
(pi::make-serializer color-wheel2-wrap)
(let* ((ser3 (serialize-to-bytes request-3 'color-wheel2-wrap))
(res3 (deserialize-from-bytes 'color-wheel2-wrap ser3)))
(assert-true (proto-equal res3 request-3))))))
(defun clear-test-proto-backwards-compatibility ()
(loop for message in '(proto-on-wire
proto-different-than-wire)
do
(clear-serialization-functions message)))
We make two protos : ProtoOnWire and ProtoDifferentThanWire .
;;; The difference is that ProtoOnWire contains a superset of the
;;; fields ProtoOnWire contains.
;;;
;;; We create a ProtoOnWire, serialize, and then deserialize
;;; using the ProtoOnWire's bytes to a ProtoDifferentThanWire
;;;
;;; This aims to test updating a protocol buffer and deserializing
;;; on a binary containing the previous version.
(deftest test-proto-backwards-compatibility (serialization-suite)
(loop :for optimized :in '(nil t) :do
(format t "Testing optimized serializers: ~a~%" optimized)
(when optimized
(dolist (class '(proto-on-wire proto-different-than-wire))
(let ((message (find-message-descriptor class)))
(handler-bind ((style-warning #'muffle-warning))
(eval (pi::generate-deserializer message))
(eval (pi::generate-serializer message))))))
(let* ((proto-on-wire (make-proto-on-wire
:beginning "char"
:always "pika-pal"
:end (list "mander")))
(proto-on-wire-octet-bytes (serialize-to-bytes proto-on-wire))
(my-deserialized-proto
(deserialize-from-bytes 'proto-different-than-wire
proto-on-wire-octet-bytes))
(proto-different-than-wire (make-proto-different-than-wire
:beginning "char"
:always "pika-pal")))
(assert-true my-deserialized-proto)
(assert-true (proto-equal my-deserialized-proto proto-different-than-wire))
(let* ((reserialized-proto-octets (serialize-to-bytes my-deserialized-proto))
(should-be-original-proto
(deserialize-from-bytes 'proto-on-wire reserialized-proto-octets)))
(assert-true (proto-equal should-be-original-proto proto-on-wire))))))
Serialize a message - v2 proto and then try to deserialize it as a
message - v1 , which is missing the ` baz = 1 ` value in the enum it uses . This
;;; simulates interaction of a newer version of a proto in which an enum value
;;; has been added with an older version. In the old version the unknown enum
;;; values should be retained as :%undefined-n where n is the numerical value.
(deftest test-proto-backwards-compatibility-for-enums (serialization-suite)
(loop :for optimized :in '(nil t) :do
(format t "Testing optimized serializers: ~a~%" optimized)
(when optimized
(dolist (class '(message-v1 message-v2))
(let ((message (find-message-descriptor class)))
(handler-bind ((style-warning #'muffle-warning))
(eval (pi::generate-deserializer message))
(eval (pi::generate-serializer message))))))
(let* ((message-v2 (make-message-v2 :e :baz :e2 :baz
:e3 '(:baz) :e4 '(:baz)
:e5 :auto))
(v2-bytes (serialize-to-bytes message-v2))
(message-v1 (deserialize-from-bytes 'message-v1 v2-bytes)))
(assert-true message-v1)
(assert-eq (message-v1.e message-v1) :%undefined-1)
(assert-eq (message-v1.e2 message-v1) :%undefined-1)
(assert-equal (message-v1.e3 message-v1) '(:%undefined-1))
(assert-equal (message-v1.e4 message-v1) '(:%undefined-1))
(assert-eq (message-v1.e5 message-v1) :default)
(let* ((reserialized-proto-octets (serialize-to-bytes message-v1))
(should-be-original-proto
(deserialize-from-bytes 'message-v2 reserialized-proto-octets)))
(assert-true (proto-equal message-v2 should-be-original-proto))))))
| null | https://raw.githubusercontent.com/qitab/cl-protobufs/bf5447065714a9f5b1b6ce6d0512fd99b4105e76/tests/serialization-test.lisp | lisp |
license that can be found in the LICENSE file or at
.
clunit2:deftest does very strange things with its &body, which makes
debugging more difficult, so let's not give it that chance.
TODO(cgay): This makes the tests non-repeatable in the REPL. Either
find a safe way to delete the optimized serializers after the test,
separate into optimized and non-optimized tests, or remove the
non-optimized path completely. Similar problem in other tests.
Extension example
This test can not (or should not) work with optimize :SPEED because of poor Lisp style,
the behavior of which is undefined although practically speaking it does what you think.
The DEFINE-MESSAGE for AUTO-COLOR creates fast serialize/deserialize functions,
and so does the DEFINE-EXTEND AUTO-COLOR but with more fields.
The introspection-based (de)serialize functions don't have this issue
because nothing happens with regard to (de)serialization until just-in-time.
The define-service macro expands to code in a package named <current-package>-rpc.
Normally the package would be created in the generated code but we do it manually
here because we call define-service directly.
This tests the optimized serializer's ability to serialize messages
which have nested messages which have group fields.
The difference is that ProtoOnWire contains a superset of the
fields ProtoOnWire contains.
We create a ProtoOnWire, serialize, and then deserialize
using the ProtoOnWire's bytes to a ProtoDifferentThanWire
This aims to test updating a protocol buffer and deserializing
on a binary containing the previous version.
simulates interaction of a newer version of a proto in which an enum value
has been added with an older version. In the old version the unknown enum
values should be retained as :%undefined-n where n is the numerical value. | Copyright 2012 - 2020 Google LLC
Use of this source code is governed by an MIT - style
(defpackage #:cl-protobufs.test.serialization
(:use #:cl
#:clunit
#:cl-protobufs
#:cl-protobufs.serialization-test)
(:local-nicknames (#:pi #:cl-protobufs.implementation))
(:export :run))
(in-package #:cl-protobufs.test.serialization)
(defsuite serialization-suite (cl-protobufs.test:root-suite))
(defun run (&key use-debugger)
"Run all tests in the test suite.
Parameters
USE-DEBUGGER: On assert failure bring up the debugger."
(clunit:run-suite 'serialization-suite :use-debugger use-debugger
:signal-condition-on-fail t))
(defvar *tser5-bytes* #(8 1 16 2 16 3 16 5 16 7 26 3 116 119
111 26 5 116 104 114 101 101 26 4 102
105 118 101 26 5 115 101 118 101 110))
(defvar *tser6-bytes* #(8 2 8 3 8 5 8 7 18 3 116 119 111 18 5
116 104 114 101 101 18 4 102 105 118
101 18 5 115 101 118 101 110 26 9 18
7 116 101 115 116 105 110 103 26 7 18
5 49 32 50 32 51))
(defvar *tser7-bytes* #(10 5 115 101 118 101 110 16 2 16 27
27 10 2 103 49 16 1 16 1 16 2 16 3 28
27 10 2 103 50 28 34 3 116 119 111))
(deftest basic-serialization (serialization-suite)
(do-basic-serialization))
(defun do-basic-serialization ()
(loop :for optimized :in '(nil t)
:do
(when optimized
(dolist (class '(basic-test1 basic-test2 basic-test3 basic-test4
basic-test5 basic-test6 basic-test7.subgroups))
(let ((message (find-message-descriptor class :error-p t)))
(handler-bind ((style-warning #'muffle-warning))
(eval (pi::generate-deserializer message))
(eval (pi::generate-serializer message))))))
(let* ((test1 (make-basic-test1 :intval 150))
(test1b (make-basic-test1 :intval -150))
(test2 (make-basic-test2 :strval "testing"))
(test2b (make-basic-test2 :strval "1 2 3"))
(test3 (make-basic-test3 :recval test1))
(test4 (make-basic-test4 :recval test2))
(test5 (make-basic-test5
:color :red :intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")))
(test6 (make-basic-test6
:intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")
:recvals (list test2 test2b)))
(group1 (make-basic-test7.subgroups
:strval "g1"
:intvals '(1 1 2 3)))
(group2 (make-basic-test7.subgroups
:strval "g2"))
(test7 (make-basic-test7
:strval1 "seven"
:intvals '(2 27)
:subgroups (list group1 group2)
:strval2 "two")))
(let ((tser1 (serialize-to-bytes test1 'basic-test1))
(tser1b (serialize-to-bytes test1b 'basic-test1))
(tser2 (serialize-to-bytes test2 'basic-test2))
(tser3 (serialize-to-bytes test3 'basic-test3))
(tser4 (serialize-to-bytes test4 'basic-test4))
(tser5 (serialize-to-bytes test5 'basic-test5))
(tser6 (serialize-to-bytes test6 'basic-test6))
(tser7 (serialize-to-bytes test7 'basic-test7)))
(assert-equalp #(#x08 #x96 #x01) tser1)
(assert-equalp #(#x08 #xEA #xFE #xFF #xFF #x0F) tser1b)
(assert-equalp #(#x12 #x07 #x74 #x65 #x73 #x74 #x69 #x6E #x67) tser2)
(assert-equalp #(#x1A #x03 #x08 #x96 #x01) tser3)
(assert-equalp #(#x1A #x09 #x12 #x07 #x74 #x65 #x73 #x74 #x69 #x6E #x67) tser4)
(assert-equalp *tser5-bytes* tser5)
(assert-equalp *tser6-bytes* tser6)
(assert-equalp *tser7-bytes* tser7)
(macrolet ((slots-equalp (obj1 obj2 &rest slots)
(pi::with-gensyms (vobj1 vobj2)
(pi::with-collectors ((forms collect-form))
(dolist (slot slots)
(collect-form
`(assert-equalp
(proto-slot-value ,vobj1 ',slot)
(proto-slot-value ,vobj2 ',slot))))
`(let ((,vobj1 ,obj1)
(,vobj2 ,obj2))
,@forms)))))
(slots-equalp test1 (deserialize-from-bytes 'basic-test1 tser1)
intval)
(slots-equalp test1b (deserialize-from-bytes 'basic-test1 tser1b)
intval)
(slots-equalp test2 (deserialize-from-bytes 'basic-test2 tser2)
intval strval)
(slots-equalp test3 (deserialize-from-bytes 'basic-test3 tser3)
intval strval)
(slots-equalp (recval test3)
(recval (deserialize-from-bytes 'basic-test3 tser3))
intval)
(slots-equalp test4 (deserialize-from-bytes 'basic-test4 tser4)
intval strval)
(slots-equalp (recval test4)
(recval (deserialize-from-bytes 'basic-test4 tser4))
intval strval)
(slots-equalp test5 (deserialize-from-bytes 'basic-test5 tser5)
color intvals strvals)
(slots-equalp test6 (deserialize-from-bytes 'basic-test6 tser6)
intvals strvals)
(slots-equalp (first (recvals test6))
(first (recvals (deserialize-from-bytes 'basic-test6 tser6)))
strval)
(slots-equalp (second (recvals test6))
(second (recvals (deserialize-from-bytes 'basic-test6 tser6)))
strval)
(slots-equalp test7 (deserialize-from-bytes 'basic-test7 tser7)
strval1 intvals strval2)
(slots-equalp (first (subgroups test7))
(first (subgroups (deserialize-from-bytes 'basic-test7 tser7)))
strval intvals)
(slots-equalp (second (subgroups test7))
(second (subgroups (deserialize-from-bytes 'basic-test7 tser7)))
strval intvals))))))
(deftest text-serialization (serialization-suite)
(let* ((test1 (make-basic-test1 :intval 150))
(test1b (make-basic-test1 :intval -150))
(test2 (make-basic-test2 :strval "testing"))
(test2b (make-basic-test2 :strval "1 2 3"))
(test3 (make-basic-test3 :recval test1))
(test4 (make-basic-test4 :recval test2))
(test5 (make-basic-test5
:color :red :intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")))
(test6 (make-basic-test6
:intvals '(2 3 5 7)
:strvals '("two" "three" "five" "seven")
:recvals (list test2 test2b))))
(let ((tser1 (serialize-to-bytes test1 'basic-test1))
(tser1b (serialize-to-bytes test1b 'basic-test1))
(tser2 (serialize-to-bytes test2 'basic-test2))
(tser3 (serialize-to-bytes test3 'basic-test3))
(tser4 (serialize-to-bytes test4 'basic-test4))
(tser5 (serialize-to-bytes test5 'basic-test5))
(tser6 (serialize-to-bytes test6 'basic-test6)))
(macrolet ((slots-equalp (obj1 obj2 &rest slots)
(pi::with-gensyms (vobj1 vobj2)
(pi::with-collectors ((forms collect-form))
(dolist (slot slots)
(collect-form
`(assert-equalp (,slot ,vobj1) (,slot ,vobj2))))
`(let ((,vobj1 ,obj1)
(,vobj2 ,obj2))
,@forms)))))
(let ((text (with-output-to-string (s)
(print-text-format test1 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test1 tser1)
:stream s)))
(slots-equalp test1 (with-input-from-string (s text)
(parse-text-format 'basic-test1 :stream s))
intval))
(let ((text (with-output-to-string (s)
(print-text-format test1b :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test1 tser1b)
:stream s)))
(slots-equalp test1b (with-input-from-string (s text)
(parse-text-format 'basic-test1 :stream s))
intval))
(let ((text (with-output-to-string (s)
(print-text-format test2 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test2 tser2)
:stream s)))
(slots-equalp test2 (with-input-from-string (s text)
(parse-text-format 'basic-test2 :stream s))
intval strval))
(let ((text (with-output-to-string (s)
(print-text-format test3 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test3 tser3)
:stream s)))
(slots-equalp test3 (with-input-from-string (s text)
(parse-text-format 'basic-test3 :stream s))
intval strval)
(slots-equalp (recval test3)
(recval (with-input-from-string (s text)
(parse-text-format 'basic-test3 :stream s)))
intval))
(let ((text (with-output-to-string (s)
(print-text-format test4 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test4 tser4)
:stream s)))
(slots-equalp test4 (with-input-from-string (s text)
(parse-text-format 'basic-test4 :stream s))
intval strval)
(slots-equalp (recval test4)
(recval (with-input-from-string (s text)
(parse-text-format 'basic-test4 :stream s)))
intval strval))
(let ((text (with-output-to-string (s)
(print-text-format test5 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test5 tser5)
:stream s)))
(slots-equalp test5 (with-input-from-string (s text)
(parse-text-format 'basic-test5 :stream s))
color intvals strvals))
(let ((text (with-output-to-string (s)
(print-text-format test6 :stream s))))
(assert-equal text (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'basic-test6 tser6)
:stream s)))
(slots-equalp test6 (with-input-from-string (s text)
(parse-text-format 'basic-test6 :stream s))
intvals strvals)
(slots-equalp (first (recvals test6))
(first (recvals
(with-input-from-string (s text)
(parse-text-format 'basic-test6 :stream s))))
strval)
(slots-equalp (second (recvals test6))
(second (recvals
(with-input-from-string (s text)
(parse-text-format 'basic-test6 :stream s))))
strval))))))
(deftest serialization-integrity (serialization-suite)
(flet ((do-test (message)
(let* ((type (type-of message))
(buf (serialize-to-bytes message type))
(new (deserialize-from-bytes type buf))
(newbuf (serialize-to-bytes new type)))
(assert-equalp (length buf) (length newbuf))
(assert-equalp buf newbuf)
(assert-equal
(with-output-to-string (s)
(print-text-format message :stream s))
(with-output-to-string (s)
(print-text-format new :stream s))))))
(do-test (make-outer :i 4))
(do-test (make-outer :i -4))
(let ((inner-1 (mapcar #'(lambda (i) (make-inner :i i)) '(1 2 3)))
(inner-2 (mapcar #'(lambda (i) (make-inner :i i)) '(-1 -2 -3)))
(simple-1 (make-inner :i 4))
(simple-2 (make-inner :i -4)))
(do-test (make-outer :inner inner-1))
(do-test (make-outer :inner inner-2))
(do-test (make-outer :simple simple-1))
(do-test (make-outer :simple simple-2)))))
(deftest empty-message-serialization (serialization-suite)
(let ((speed0 (make-speed-empty))
(speed1 (make-speed-optional))
(speed2 (make-speed-repeated))
(space0 (make-space-empty))
(space1 (make-space-optional))
(space2 (make-space-repeated)))
(setf (foo speed1) speed0)
(setf (foo space1) space0)
(push speed0 (foo speed2))
(push space0 (foo space2))
(let ((ser-speed0 (serialize-to-bytes speed0 (type-of speed0)))
(ser-speed1 (serialize-to-bytes speed1 (type-of speed1)))
(ser-speed2 (serialize-to-bytes speed2 (type-of speed2)))
(ser-space0 (serialize-to-bytes space0 (type-of space0)))
(ser-space1 (serialize-to-bytes space1 (type-of space1)))
(ser-space2 (serialize-to-bytes space2 (type-of space2))))
(assert-equalp ser-speed0 #())
(assert-equalp ser-speed1 #(#x0A #x00))
(assert-equalp ser-speed2 #(#x0A #x00))
(assert-equalp ser-space0 #())
(assert-equalp ser-space1 #(#x0A #x00))
(assert-equalp ser-space2 #(#x0A #x00)))))
It so happens that the behavior is to instate the second definition ,
while returning T for WARNING - P and ERROR - P from the compile - file operation in SBCL .
This used to work by accident , because DEFMETHOD never detects that you 've defined
a method twice in one file using the * exact * * same * qualifiers and specializers .
(defpackage #:cl-protobufs.test.serialization-rpc (:use))
(pi:define-service buy-car ()
(buy-car (buy-car-request => buy-car-response)
:options (:deadline 1.0)))
(deftest extension-serialization (serialization-suite)
(let* ((color1 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car1 (make-automobile :model "Audi" :color color1))
(request-1 (make-buy-car-request :auto car1))
(color2 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car2 (make-automobile :model "Audi" :color color2))
(request-2 (make-buy-car-request :auto car2)))
(setf (paint-type color2) :metallic)
(let ((ser1 (serialize-to-bytes request-1 'buy-car-request))
(ser2 (serialize-to-bytes request-2 'buy-car-request)))
(assert-false (equal ser1 ser2))
(assert-equal
(with-output-to-string (s)
(print-text-format request-1 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser1) :stream s)))
(assert-equal
(with-output-to-string (s)
(print-text-format request-2 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser2) :stream s))))
(let ((str1 (with-output-to-string (s)
(print-text-format request-1 :stream s)))
(str2 (with-output-to-string (s)
(print-text-format request-2 :stream s))))
(assert-false (string= str1 str2))
(assert-false (search "paint_type:" str1 :test #'char=))
(assert-true (search "paint_type:" str2 :test #'char=)))))
(defun clear-serialization-functions (proto-name)
#-sbcl
(setf (get `,proto-name :serialize) nil
(get `,proto-name :deserialize) nil)
#+sbcl (fmakunbound (list :protobuf :serialize proto-name))
#+sbcl (fmakunbound (list :protobuf :deserialize proto-name)))
(defun create-ext-serialization-functions ()
(pi::make-serializer auto-color)
(pi::make-serializer automobile)
(pi::make-serializer buy-car-request)
(pi::make-deserializer automobile)
(pi::make-deserializer auto-color)
(pi::make-deserializer buy-car-request))
(defun clear-ext-proto-serialization-functions ()
(loop for message in '(auto-color automobile buy-car-request)
do
(clear-serialization-functions message)))
(deftest extension-serialization-optimized (serialization-suite)
(create-ext-serialization-functions)
(let* ((color1 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car1 (make-automobile :model "Audi" :color color1))
(request-1 (make-buy-car-request :auto car1))
(color2 (make-auto-color :r-value 100 :g-value 0 :b-value 100))
(car2 (make-automobile :model "Audi" :color color2))
(request-2 (make-buy-car-request :auto car2)))
(setf (paint-type color2) :metallic)
(let ((ser1 (serialize-to-bytes request-1 'buy-car-request))
(ser2 (serialize-to-bytes request-2 'buy-car-request)))
(assert-false (equal ser1 ser2))
(assert-equal
(with-output-to-string (s)
(print-text-format request-1 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser1) :stream s)))
(assert-equal
(with-output-to-string (s)
(print-text-format request-2 :stream s))
(with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'buy-car-request ser2) :stream s))))
(let ((str1 (with-output-to-string (s)
(print-text-format request-1 :stream s)))
(str2 (with-output-to-string (s)
(print-text-format request-2 :stream s))))
(assert-false (string= str1 str2))
(assert-false (search "paint_type:" str1 :test #'char=))
(assert-true (search "paint_type:" str2 :test #'char=))))
(clear-ext-proto-serialization-functions))
(deftest group-serialization (serialization-suite)
(let* ((meta1 (make-color-wheel1.metadata1 :revision "1.0"))
(wheel1 (make-color-wheel1 :name "Colors" :metadata meta1))
(color1 (make-color1 :r-value 100 :g-value 0 :b-value 100))
(request-1 (make-add-color1 :wheel wheel1 :color color1))
(meta2 (make-color-wheel2.metadata :revision "1.0"))
(wheel2 (make-color-wheel2 :name "Colors" :metadata meta2))
(color2 (make-color2 :r-value 100 :g-value 0 :b-value 100))
(request-2 (make-add-color2 :wheel wheel2 :color color2))
(request-3 (make-color-wheel2-wrap :id 9001 :wheel wheel2 :metaname "meta")))
(let ((ser1 (serialize-to-bytes request-1 'add-color1))
(ser2 (serialize-to-bytes request-2 'add-color2)))
(assert-equal
(subseq (with-output-to-string (s)
(print-text-format request-1 :stream s))
9)
(subseq (with-output-to-string (s)
(print-text-format request-2 :stream s))
9))
(assert-equal
(subseq (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'add-color1 ser1) :stream s))
9)
(subseq (with-output-to-string (s)
(print-text-format
(deserialize-from-bytes 'add-color2 ser2) :stream s))
9))
(pi::make-serializer color-wheel2.metadata)
(pi::make-serializer color2)
(pi::make-serializer color-wheel2)
(pi::make-serializer color-wheel2-wrap)
(let* ((ser3 (serialize-to-bytes request-3 'color-wheel2-wrap))
(res3 (deserialize-from-bytes 'color-wheel2-wrap ser3)))
(assert-true (proto-equal res3 request-3))))))
(defun clear-test-proto-backwards-compatibility ()
(loop for message in '(proto-on-wire
proto-different-than-wire)
do
(clear-serialization-functions message)))
We make two protos : ProtoOnWire and ProtoDifferentThanWire .
(deftest test-proto-backwards-compatibility (serialization-suite)
(loop :for optimized :in '(nil t) :do
(format t "Testing optimized serializers: ~a~%" optimized)
(when optimized
(dolist (class '(proto-on-wire proto-different-than-wire))
(let ((message (find-message-descriptor class)))
(handler-bind ((style-warning #'muffle-warning))
(eval (pi::generate-deserializer message))
(eval (pi::generate-serializer message))))))
(let* ((proto-on-wire (make-proto-on-wire
:beginning "char"
:always "pika-pal"
:end (list "mander")))
(proto-on-wire-octet-bytes (serialize-to-bytes proto-on-wire))
(my-deserialized-proto
(deserialize-from-bytes 'proto-different-than-wire
proto-on-wire-octet-bytes))
(proto-different-than-wire (make-proto-different-than-wire
:beginning "char"
:always "pika-pal")))
(assert-true my-deserialized-proto)
(assert-true (proto-equal my-deserialized-proto proto-different-than-wire))
(let* ((reserialized-proto-octets (serialize-to-bytes my-deserialized-proto))
(should-be-original-proto
(deserialize-from-bytes 'proto-on-wire reserialized-proto-octets)))
(assert-true (proto-equal should-be-original-proto proto-on-wire))))))
Serialize a message - v2 proto and then try to deserialize it as a
message - v1 , which is missing the ` baz = 1 ` value in the enum it uses . This
(deftest test-proto-backwards-compatibility-for-enums (serialization-suite)
(loop :for optimized :in '(nil t) :do
(format t "Testing optimized serializers: ~a~%" optimized)
(when optimized
(dolist (class '(message-v1 message-v2))
(let ((message (find-message-descriptor class)))
(handler-bind ((style-warning #'muffle-warning))
(eval (pi::generate-deserializer message))
(eval (pi::generate-serializer message))))))
(let* ((message-v2 (make-message-v2 :e :baz :e2 :baz
:e3 '(:baz) :e4 '(:baz)
:e5 :auto))
(v2-bytes (serialize-to-bytes message-v2))
(message-v1 (deserialize-from-bytes 'message-v1 v2-bytes)))
(assert-true message-v1)
(assert-eq (message-v1.e message-v1) :%undefined-1)
(assert-eq (message-v1.e2 message-v1) :%undefined-1)
(assert-equal (message-v1.e3 message-v1) '(:%undefined-1))
(assert-equal (message-v1.e4 message-v1) '(:%undefined-1))
(assert-eq (message-v1.e5 message-v1) :default)
(let* ((reserialized-proto-octets (serialize-to-bytes message-v1))
(should-be-original-proto
(deserialize-from-bytes 'message-v2 reserialized-proto-octets)))
(assert-true (proto-equal message-v2 should-be-original-proto))))))
|
bab8420e4fabe8f29476df33888cf453c76718b761a577935d461c7094d8c4de | binaryage/cljs-oops | defaults.clj | (ns oops.defaults
"Default configuration + specs."
(:require [cljs.env]
[oops.state]
[clojure.spec.alpha :as s]))
(def config ; falsy below means 'nil' or 'false'
{; -- compiler config -----------------------------------------------------------------------------------------------------
:diagnostics true ; #{true falsy}
:key-get :core ; #{:core :goog}
:key-set :core ; #{:core :goog}
:strict-punching true ; #{true falsy}
:skip-config-validation false ; #{true falsy}
:macroexpand-selectors true ; #{true falsy}
; compile-time warnings/errors
:dynamic-selector-usage :warn ; #{:error :warn falsy}
:static-nil-target-object :warn ; #{:error :warn falsy}
:static-unexpected-empty-selector :warn ; #{:error :warn falsy}
:static-unexpected-punching-selector :warn ; #{:error :warn falsy}
:static-unexpected-soft-selector :warn ; #{:error :warn falsy}
; -- runtime config ------------------------------------------------------------------------------------------------------
; run-time warnings/errors
:runtime-unexpected-object-value :error ; #{:error :warn falsy}
:runtime-expected-function-value :error ; #{:error :warn falsy}
:runtime-invalid-selector :error ; #{:error :warn falsy}
:runtime-missing-object-key :error ; #{:error :warn falsy}
:runtime-object-key-not-writable :error ; #{:error :warn falsy}
:runtime-object-is-sealed :error ; #{:error :warn falsy}
:runtime-object-is-frozen :error ; #{:error :warn falsy}
:runtime-unexpected-empty-selector :warn ; #{:error :warn falsy}
:runtime-unexpected-punching-selector :warn ; #{:error :warn falsy}
:runtime-unexpected-soft-selector :warn ; #{:error :warn falsy}
; reporting modes
:runtime-error-reporting :throw ; #{:throw :console falsy}
:runtime-warning-reporting :console ; #{:throw :console falsy}
:runtime-throw-errors-from-macro-call-sites true ; #{true falsy}
:runtime-child-factory :js-obj ; #{:js-obj :js-array}
:runtime-use-envelope true ; #{true falsy}
; -- development ---------------------------------------------------------------------------------------------------------
; enable debug if you want to debug/hack oops itself
:debug false ; #{true falsy}
})
(def advanced-mode-config-overrides
{:diagnostics false})
; -- config validation specs ------------------------------------------------------------------------------------------------
; please note that we want this code to be co-located with default config for easier maintenance
; but formally we want config spec to reside in oops.config namespace
(create-ns 'oops.config)
(alias 'config 'oops.config)
; -- config helpers ---------------------------------------------------------------------------------------------------------
(s/def ::config/boolish #(contains? #{true false nil} %))
(s/def ::config/key-impl #(contains? #{:goog :core} %))
(s/def ::config/message #(contains? #{:error :warn false nil} %))
(s/def ::config/reporting #(contains? #{:throw :console false nil} %))
(s/def ::config/child-factory #(contains? #{:js-obj :js-array} %))
; -- config keys ------------------------------------------------------------------------------------------------------------
(s/def ::config/diagnostics ::config/boolish)
(s/def ::config/key-get ::config/key-impl)
(s/def ::config/key-set ::config/key-impl)
(s/def ::config/strict-punching ::config/boolish)
(s/def ::config/skip-config-validation ::config/boolish)
(s/def ::config/macroexpand-selectors ::config/boolish)
(s/def ::config/dynamic-selector-usage ::config/message)
(s/def ::config/static-nil-target-object ::config/message)
(s/def ::config/static-unexpected-empty-selector ::config/message)
(s/def ::config/static-unexpected-punching-selector ::config/message)
(s/def ::config/static-unexpected-soft-selector ::config/message)
(s/def ::config/runtime-unexpected-object-value ::config/message)
(s/def ::config/runtime-expected-function-value ::config/message)
(s/def ::config/runtime-invalid-selector ::config/message)
(s/def ::config/runtime-missing-object-key ::config/message)
(s/def ::config/runtime-object-key-not-writable ::config/message)
(s/def ::config/runtime-object-is-sealed ::config/message)
(s/def ::config/runtime-object-is-frozen ::config/message)
(s/def ::config/runtime-unexpected-empty-selector ::config/message)
(s/def ::config/runtime-unexpected-punching-selector ::config/message)
(s/def ::config/runtime-unexpected-soft-selector ::config/message)
(s/def ::config/runtime-error-reporting ::config/reporting)
(s/def ::config/runtime-warning-reporting ::config/reporting)
(s/def ::config/runtime-throw-errors-from-macro-call-sites ::config/boolish)
(s/def ::config/runtime-child-factory ::config/child-factory)
(s/def ::config/runtime-use-envelope ::config/boolish)
(s/def ::config/debug ::config/boolish)
; -- config map -------------------------------------------------------------------------------------------------------------
(s/def ::config/config
(s/keys :req-un [::config/diagnostics
::config/key-get
::config/key-set
::config/strict-punching
::config/skip-config-validation
::config/macroexpand-selectors
::config/dynamic-selector-usage
::config/static-nil-target-object
::config/static-unexpected-empty-selector
::config/static-unexpected-punching-selector
::config/static-unexpected-soft-selector
::config/runtime-unexpected-object-value
::config/runtime-invalid-selector
::config/runtime-missing-object-key
::config/runtime-object-key-not-writable
::config/runtime-object-is-sealed
::config/runtime-object-is-frozen
::config/runtime-unexpected-empty-selector
::config/runtime-unexpected-punching-selector
::config/runtime-unexpected-soft-selector
::config/runtime-error-reporting
::config/runtime-warning-reporting
::config/runtime-throw-errors-from-macro-call-sites
::config/runtime-child-factory
::config/runtime-use-envelope
::config/debug]))
| null | https://raw.githubusercontent.com/binaryage/cljs-oops/a2b48d59047c28decb0d6334e2debbf21848e29c/src/lib/oops/defaults.clj | clojure | falsy below means 'nil' or 'false'
-- compiler config -----------------------------------------------------------------------------------------------------
#{true falsy}
#{:core :goog}
#{:core :goog}
#{true falsy}
#{true falsy}
#{true falsy}
compile-time warnings/errors
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
-- runtime config ------------------------------------------------------------------------------------------------------
run-time warnings/errors
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
#{:error :warn falsy}
reporting modes
#{:throw :console falsy}
#{:throw :console falsy}
#{true falsy}
#{:js-obj :js-array}
#{true falsy}
-- development ---------------------------------------------------------------------------------------------------------
enable debug if you want to debug/hack oops itself
#{true falsy}
-- config validation specs ------------------------------------------------------------------------------------------------
please note that we want this code to be co-located with default config for easier maintenance
but formally we want config spec to reside in oops.config namespace
-- config helpers ---------------------------------------------------------------------------------------------------------
-- config keys ------------------------------------------------------------------------------------------------------------
-- config map ------------------------------------------------------------------------------------------------------------- | (ns oops.defaults
"Default configuration + specs."
(:require [cljs.env]
[oops.state]
[clojure.spec.alpha :as s]))
})
(def advanced-mode-config-overrides
{:diagnostics false})
(create-ns 'oops.config)
(alias 'config 'oops.config)
(s/def ::config/boolish #(contains? #{true false nil} %))
(s/def ::config/key-impl #(contains? #{:goog :core} %))
(s/def ::config/message #(contains? #{:error :warn false nil} %))
(s/def ::config/reporting #(contains? #{:throw :console false nil} %))
(s/def ::config/child-factory #(contains? #{:js-obj :js-array} %))
(s/def ::config/diagnostics ::config/boolish)
(s/def ::config/key-get ::config/key-impl)
(s/def ::config/key-set ::config/key-impl)
(s/def ::config/strict-punching ::config/boolish)
(s/def ::config/skip-config-validation ::config/boolish)
(s/def ::config/macroexpand-selectors ::config/boolish)
(s/def ::config/dynamic-selector-usage ::config/message)
(s/def ::config/static-nil-target-object ::config/message)
(s/def ::config/static-unexpected-empty-selector ::config/message)
(s/def ::config/static-unexpected-punching-selector ::config/message)
(s/def ::config/static-unexpected-soft-selector ::config/message)
(s/def ::config/runtime-unexpected-object-value ::config/message)
(s/def ::config/runtime-expected-function-value ::config/message)
(s/def ::config/runtime-invalid-selector ::config/message)
(s/def ::config/runtime-missing-object-key ::config/message)
(s/def ::config/runtime-object-key-not-writable ::config/message)
(s/def ::config/runtime-object-is-sealed ::config/message)
(s/def ::config/runtime-object-is-frozen ::config/message)
(s/def ::config/runtime-unexpected-empty-selector ::config/message)
(s/def ::config/runtime-unexpected-punching-selector ::config/message)
(s/def ::config/runtime-unexpected-soft-selector ::config/message)
(s/def ::config/runtime-error-reporting ::config/reporting)
(s/def ::config/runtime-warning-reporting ::config/reporting)
(s/def ::config/runtime-throw-errors-from-macro-call-sites ::config/boolish)
(s/def ::config/runtime-child-factory ::config/child-factory)
(s/def ::config/runtime-use-envelope ::config/boolish)
(s/def ::config/debug ::config/boolish)
(s/def ::config/config
(s/keys :req-un [::config/diagnostics
::config/key-get
::config/key-set
::config/strict-punching
::config/skip-config-validation
::config/macroexpand-selectors
::config/dynamic-selector-usage
::config/static-nil-target-object
::config/static-unexpected-empty-selector
::config/static-unexpected-punching-selector
::config/static-unexpected-soft-selector
::config/runtime-unexpected-object-value
::config/runtime-invalid-selector
::config/runtime-missing-object-key
::config/runtime-object-key-not-writable
::config/runtime-object-is-sealed
::config/runtime-object-is-frozen
::config/runtime-unexpected-empty-selector
::config/runtime-unexpected-punching-selector
::config/runtime-unexpected-soft-selector
::config/runtime-error-reporting
::config/runtime-warning-reporting
::config/runtime-throw-errors-from-macro-call-sites
::config/runtime-child-factory
::config/runtime-use-envelope
::config/debug]))
|
e3c8d8fa3e429a29d974309661381fecc42e00de662b58d78f0953c5312b4dab | mirleft/ocaml-x509 | host.ml | type t = [ `Strict | `Wildcard ] * [ `host ] Domain_name.t
let pp_typ ppf = function
| `Strict -> Fmt.nop ppf ()
| `Wildcard -> Fmt.string ppf "*."
let pp ppf (typ, nam) =
Fmt.pf ppf "%a%a" pp_typ typ Domain_name.pp nam
module Set = struct
include Set.Make(struct
type nonrec t = t
let compare a b = match a, b with
| (`Strict, a), (`Strict, b)
| (`Wildcard, a), (`Wildcard, b) -> Domain_name.compare a b
| (`Strict, _), (`Wildcard, _) -> -1
| (`Wildcard, _), (`Strict, _) -> 1
end)
let pp ppf s =
Fmt.(list ~sep:(any ", ") pp) ppf (elements s)
end
let is_wildcard name =
match Domain_name.get_label name 0 with
| Ok "*" -> Some (Domain_name.drop_label_exn name)
| _ -> None
let host name =
match Domain_name.of_string name with
| Error _ -> None
| Ok dn ->
let wild, name = match is_wildcard dn with
| None -> `Strict, dn
| Some dn' -> `Wildcard, dn'
in
match Domain_name.host name with
| Error _ -> None
| Ok hostname -> Some (wild, hostname)
| null | https://raw.githubusercontent.com/mirleft/ocaml-x509/13eda5db42d6a68c6f5ad1e59a0878a2c57b77e6/lib/host.ml | ocaml | type t = [ `Strict | `Wildcard ] * [ `host ] Domain_name.t
let pp_typ ppf = function
| `Strict -> Fmt.nop ppf ()
| `Wildcard -> Fmt.string ppf "*."
let pp ppf (typ, nam) =
Fmt.pf ppf "%a%a" pp_typ typ Domain_name.pp nam
module Set = struct
include Set.Make(struct
type nonrec t = t
let compare a b = match a, b with
| (`Strict, a), (`Strict, b)
| (`Wildcard, a), (`Wildcard, b) -> Domain_name.compare a b
| (`Strict, _), (`Wildcard, _) -> -1
| (`Wildcard, _), (`Strict, _) -> 1
end)
let pp ppf s =
Fmt.(list ~sep:(any ", ") pp) ppf (elements s)
end
let is_wildcard name =
match Domain_name.get_label name 0 with
| Ok "*" -> Some (Domain_name.drop_label_exn name)
| _ -> None
let host name =
match Domain_name.of_string name with
| Error _ -> None
| Ok dn ->
let wild, name = match is_wildcard dn with
| None -> `Strict, dn
| Some dn' -> `Wildcard, dn'
in
match Domain_name.host name with
| Error _ -> None
| Ok hostname -> Some (wild, hostname)
| |
87e04267f189db9157829876e9b1817376adaa265de1ee689ebddbedd798ce6e | tnelson/Forge | struct.rkt | #lang racket/base
(provide
(struct-out type)
(struct-out nametype)
(struct-out consttype)
(struct-out sigtype)
(struct-out predtype)
(struct-out fieldtype)
(struct-out paramtype)
(struct-out reltype)
the-int-type
the-bool-type
the-unknown-type
unknown-type?
type-kind)
(require
syntax/parse/define
(for-syntax racket/base racket/syntax))
;; ---
(define-simple-macro (struct/froglet id x ...)
#:with make-id (format-id this-syntax "make-~a" #'id)
(struct id x ... #:prefab #:extra-constructor-name make-id))
(struct/froglet type (name))
(struct/froglet nametype type ())
(struct/froglet consttype type ())
(struct/froglet sigtype type (mult extends field*))
(struct/froglet predtype type (param*))
(struct/froglet fieldtype type (mult sig))
(struct/froglet paramtype type (mult sig))
(struct/froglet reltype (col-type* singleton?))
;; reltype type (arity singleton?) ;; relation
(define (symbol->type sym)
(sigtype (datum->syntax #f sym) #f #f '()))
(define the-int-type (symbol->type 'Int))
(define the-bool-type (symbol->type 'Bool))
(define the-unknown-type (type (datum->syntax #f 'Unknown)))
(define (unknown-type? t)
(eq? t the-unknown-type))
(define (type-kind tt)
(cond
[(nametype? tt) "name"]
[(consttype? tt) "constant"]
[(sigtype? tt) "sig"]
[(predtype? tt) "pred"]
[(fieldtype? tt) "field"]
[(paramtype? tt) "parameter"]
[(reltype? tt) "relation"]
[(unknown-type? tt) "unknown-type"]
[else "type"]))
| null | https://raw.githubusercontent.com/tnelson/Forge/912b34b335608e9f9e373e2455a34fcbcedf6072/froglet/typecheck/struct.rkt | racket | ---
reltype type (arity singleton?) ;; relation | #lang racket/base
(provide
(struct-out type)
(struct-out nametype)
(struct-out consttype)
(struct-out sigtype)
(struct-out predtype)
(struct-out fieldtype)
(struct-out paramtype)
(struct-out reltype)
the-int-type
the-bool-type
the-unknown-type
unknown-type?
type-kind)
(require
syntax/parse/define
(for-syntax racket/base racket/syntax))
(define-simple-macro (struct/froglet id x ...)
#:with make-id (format-id this-syntax "make-~a" #'id)
(struct id x ... #:prefab #:extra-constructor-name make-id))
(struct/froglet type (name))
(struct/froglet nametype type ())
(struct/froglet consttype type ())
(struct/froglet sigtype type (mult extends field*))
(struct/froglet predtype type (param*))
(struct/froglet fieldtype type (mult sig))
(struct/froglet paramtype type (mult sig))
(struct/froglet reltype (col-type* singleton?))
(define (symbol->type sym)
(sigtype (datum->syntax #f sym) #f #f '()))
(define the-int-type (symbol->type 'Int))
(define the-bool-type (symbol->type 'Bool))
(define the-unknown-type (type (datum->syntax #f 'Unknown)))
(define (unknown-type? t)
(eq? t the-unknown-type))
(define (type-kind tt)
(cond
[(nametype? tt) "name"]
[(consttype? tt) "constant"]
[(sigtype? tt) "sig"]
[(predtype? tt) "pred"]
[(fieldtype? tt) "field"]
[(paramtype? tt) "parameter"]
[(reltype? tt) "relation"]
[(unknown-type? tt) "unknown-type"]
[else "type"]))
|
94750566a9cbeac0d7ed07644e18cdc9fd1f715d29e3056529847b470049f91f | teburd/hottub | ht_worker.erl | @author < >
2011 .
@doc Hot Tub Worker .
-module(ht_worker).
-export([start_worker/2]).
%% @doc The pool manager needs to know when a worker is alive.
%% It turns out the simplest way is to simply wrap the function the
%% supervisor calls to start a process with another that does some additional
%% work.
%% @end
-spec start_worker(atom(), {atom(), atom(), list(any())})
-> {ok, pid()}.
start_worker(PoolName, {Module, Function, Arguments}) ->
{ok, Pid} = erlang:apply(Module, Function, Arguments),
ht_pool:add_worker(PoolName, Pid),
{ok, Pid}.
| null | https://raw.githubusercontent.com/teburd/hottub/dcf9d0bfdadb94e535b3964c513d673c2fc2ac2d/src/ht_worker.erl | erlang | @doc The pool manager needs to know when a worker is alive.
It turns out the simplest way is to simply wrap the function the
supervisor calls to start a process with another that does some additional
work.
@end | @author < >
2011 .
@doc Hot Tub Worker .
-module(ht_worker).
-export([start_worker/2]).
-spec start_worker(atom(), {atom(), atom(), list(any())})
-> {ok, pid()}.
start_worker(PoolName, {Module, Function, Arguments}) ->
{ok, Pid} = erlang:apply(Module, Function, Arguments),
ht_pool:add_worker(PoolName, Pid),
{ok, Pid}.
|
ee49eb06411393d2a4db754d80570554d778ddc75d792ce5c5420e3c1020db67 | ocamllabs/ocaml-modular-implicits | parmatch.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Detection of partial matches and unused match cases. *)
open Asttypes
open Typedtree
open Types
val pretty_const : constant -> string
val top_pretty : Format.formatter -> pattern -> unit
val pretty_pat : pattern -> unit
val pretty_line : pattern list -> unit
val pretty_matrix : pattern list list -> unit
val omega : pattern
val omegas : int -> pattern list
val omega_list : 'a list -> pattern list
val normalize_pat : pattern -> pattern
val all_record_args :
(Longident.t loc * label_description * pattern) list ->
(Longident.t loc * label_description * pattern) list
val const_compare : constant -> constant -> int
val le_pat : pattern -> pattern -> bool
val le_pats : pattern list -> pattern list -> bool
val compat : pattern -> pattern -> bool
val compats : pattern list -> pattern list -> bool
exception Empty
val lub : pattern -> pattern -> pattern
val lubs : pattern list -> pattern list -> pattern list
val get_mins : ('a -> 'a -> bool) -> 'a list -> 'a list
Those two functions recombine one pattern and its arguments :
For instance :
( _ , _ ): : p1::p2::rem - > ( p1 , p2)::rem
The second one will replace mutable arguments by ' _ '
For instance:
(_,_)::p1::p2::rem -> (p1, p2)::rem
The second one will replace mutable arguments by '_'
*)
val set_args : pattern -> pattern list -> pattern list
val set_args_erase_mutable : pattern -> pattern list -> pattern list
val pat_of_constr : pattern -> constructor_description -> pattern
val complete_constrs :
pattern -> constructor_tag list -> constructor_description list
val pressure_variants: Env.t -> pattern list -> unit
val check_partial: Location.t -> case list -> partial
val check_partial_gadt:
((string, constructor_description) Hashtbl.t ->
(string, label_description) Hashtbl.t ->
Parsetree.pattern -> pattern option) ->
Location.t -> case list -> partial
val check_unused: Env.t -> case list -> unit
Irrefutability tests
val irrefutable : pattern -> bool
val fluid : pattern -> bool
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/typing/parmatch.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
Detection of partial matches and unused match cases. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Asttypes
open Typedtree
open Types
val pretty_const : constant -> string
val top_pretty : Format.formatter -> pattern -> unit
val pretty_pat : pattern -> unit
val pretty_line : pattern list -> unit
val pretty_matrix : pattern list list -> unit
val omega : pattern
val omegas : int -> pattern list
val omega_list : 'a list -> pattern list
val normalize_pat : pattern -> pattern
val all_record_args :
(Longident.t loc * label_description * pattern) list ->
(Longident.t loc * label_description * pattern) list
val const_compare : constant -> constant -> int
val le_pat : pattern -> pattern -> bool
val le_pats : pattern list -> pattern list -> bool
val compat : pattern -> pattern -> bool
val compats : pattern list -> pattern list -> bool
exception Empty
val lub : pattern -> pattern -> pattern
val lubs : pattern list -> pattern list -> pattern list
val get_mins : ('a -> 'a -> bool) -> 'a list -> 'a list
Those two functions recombine one pattern and its arguments :
For instance :
( _ , _ ): : p1::p2::rem - > ( p1 , p2)::rem
The second one will replace mutable arguments by ' _ '
For instance:
(_,_)::p1::p2::rem -> (p1, p2)::rem
The second one will replace mutable arguments by '_'
*)
val set_args : pattern -> pattern list -> pattern list
val set_args_erase_mutable : pattern -> pattern list -> pattern list
val pat_of_constr : pattern -> constructor_description -> pattern
val complete_constrs :
pattern -> constructor_tag list -> constructor_description list
val pressure_variants: Env.t -> pattern list -> unit
val check_partial: Location.t -> case list -> partial
val check_partial_gadt:
((string, constructor_description) Hashtbl.t ->
(string, label_description) Hashtbl.t ->
Parsetree.pattern -> pattern option) ->
Location.t -> case list -> partial
val check_unused: Env.t -> case list -> unit
Irrefutability tests
val irrefutable : pattern -> bool
val fluid : pattern -> bool
|
bb783afb037f3534fee69b649d19264b9407d4fb3aa49aec1f9233caf1d76800 | GaloisInc/elf-edit | Sections.hs | module Data.ElfEdit.HighLevel.Sections
( -- * ElfSection
ElfSection(..)
, elfSectionFileSize
) where
import Data.ByteString as B
import Data.Word
import Data.ElfEdit.Prim.Shdr
------------------------------------------------------------------------
ElfSection
| A section in the Elf file .
data ElfSection w = ElfSection
{ elfSectionIndex :: !Word16
-- ^ Unique index to identify section.
, elfSectionName :: !B.ByteString
-- ^ Name of the section.
, elfSectionType :: !ElfSectionType
-- ^ Type of the section.
, elfSectionFlags :: !(ElfSectionFlags w)
-- ^ Attributes of the section.
, elfSectionAddr :: !w
-- ^ The virtual address of the beginning of the section in memory.
--
-- This should be 0 for sections that are not loaded into target memory.
, elfSectionSize :: !w
-- ^ The size of the section. Except for @SHT_NOBITS@ sections, this is the
-- size of elfSectionData.
, elfSectionLink :: !Word32
-- ^ Contains a section index of an associated section, depending on section type.
, elfSectionInfo :: !Word32
-- ^ Contains extra information for the index, depending on type.
, elfSectionAddrAlign :: !w
-- ^ Contains the required alignment of the section. This
should be a power of two , and the address of the section
-- should be a multiple of the alignment.
--
-- Note that when writing files, no effort is made to add
-- padding so that the alignment constraint is correct. It is
-- up to the user to insert raw data segments as needed for
-- padding. We considered inserting padding automatically, but
-- this can result in extra bytes inadvertently appearing in
-- loadable segments, thus breaking layout constraints. In
particular , @ld@ sometimes generates files where the @.bss@
-- section address is not a multiple of the alignment.
, elfSectionEntSize :: !w
-- ^ Size of entries if section has a table.
, elfSectionData :: !B.ByteString
-- ^ Data in section.
} deriving (Eq, Show)
-- | Returns number of bytes in file used by section.
elfSectionFileSize :: Integral w => ElfSection w -> w
elfSectionFileSize = fromIntegral . B.length . elfSectionData
| null | https://raw.githubusercontent.com/GaloisInc/elf-edit/fb4699a2bba68c4d46ea3dee436f640c328fb682/src/Data/ElfEdit/HighLevel/Sections.hs | haskell | * ElfSection
----------------------------------------------------------------------
^ Unique index to identify section.
^ Name of the section.
^ Type of the section.
^ Attributes of the section.
^ The virtual address of the beginning of the section in memory.
This should be 0 for sections that are not loaded into target memory.
^ The size of the section. Except for @SHT_NOBITS@ sections, this is the
size of elfSectionData.
^ Contains a section index of an associated section, depending on section type.
^ Contains extra information for the index, depending on type.
^ Contains the required alignment of the section. This
should be a multiple of the alignment.
Note that when writing files, no effort is made to add
padding so that the alignment constraint is correct. It is
up to the user to insert raw data segments as needed for
padding. We considered inserting padding automatically, but
this can result in extra bytes inadvertently appearing in
loadable segments, thus breaking layout constraints. In
section address is not a multiple of the alignment.
^ Size of entries if section has a table.
^ Data in section.
| Returns number of bytes in file used by section. | module Data.ElfEdit.HighLevel.Sections
ElfSection(..)
, elfSectionFileSize
) where
import Data.ByteString as B
import Data.Word
import Data.ElfEdit.Prim.Shdr
ElfSection
| A section in the Elf file .
data ElfSection w = ElfSection
{ elfSectionIndex :: !Word16
, elfSectionName :: !B.ByteString
, elfSectionType :: !ElfSectionType
, elfSectionFlags :: !(ElfSectionFlags w)
, elfSectionAddr :: !w
, elfSectionSize :: !w
, elfSectionLink :: !Word32
, elfSectionInfo :: !Word32
, elfSectionAddrAlign :: !w
should be a power of two , and the address of the section
particular , @ld@ sometimes generates files where the @.bss@
, elfSectionEntSize :: !w
, elfSectionData :: !B.ByteString
} deriving (Eq, Show)
elfSectionFileSize :: Integral w => ElfSection w -> w
elfSectionFileSize = fromIntegral . B.length . elfSectionData
|
88a63f3776ba12c6df9e8ed38a68e8cd6c1cc2242442246d32a38bd2da2131e5 | static-analysis-engineering/codehawk | xprToPretty.mli | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Analyzer Infrastructure Utilities
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2019 Kestrel Technology LLC
Copyright ( c ) 2020 ( c ) 2021 - 2022 Aarno Labs LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Analyzer Infrastructure Utilities
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2019 Kestrel Technology LLC
Copyright (c) 2020 Henny Sipma
Copyright (c) 2021-2022 Aarno Labs LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
(* chutil *)
open CHLanguage
open CHPretty
(* xprlib *)
open XprTypes
val xop_to_string: xop_t -> string
val xpr_printer : xpr_pretty_printer_int
val xpr_formatter: xpr_pretty_printer_int
val default_sym_to_pretty: symbol_t -> pretty_t
val default_var_to_pretty: variable_t -> pretty_t
val make_xpr_formatter:
(symbol_t -> pretty_t) -> (variable_t -> pretty_t) -> xpr_pretty_printer_int
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/45f39248b404eeab91ae225243d79ec0583c3331/CodeHawk/CH/xprlib/xprToPretty.mli | ocaml | chutil
xprlib | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Analyzer Infrastructure Utilities
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2019 Kestrel Technology LLC
Copyright ( c ) 2020 ( c ) 2021 - 2022 Aarno Labs LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Analyzer Infrastructure Utilities
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2019 Kestrel Technology LLC
Copyright (c) 2020 Henny Sipma
Copyright (c) 2021-2022 Aarno Labs LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open CHLanguage
open CHPretty
open XprTypes
val xop_to_string: xop_t -> string
val xpr_printer : xpr_pretty_printer_int
val xpr_formatter: xpr_pretty_printer_int
val default_sym_to_pretty: symbol_t -> pretty_t
val default_var_to_pretty: variable_t -> pretty_t
val make_xpr_formatter:
(symbol_t -> pretty_t) -> (variable_t -> pretty_t) -> xpr_pretty_printer_int
|
b0bc70dee7c5b63281e564cd371269ebe0a73d03a14162c7d02ee99aa99e9794 | asivitz/Hickory | Uniforms.hs | # LANGUAGE FlexibleInstances #
module Hickory.Graphics.Uniforms where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Hickory.Graphics.Shader (Shader, retrieveLoc, UniformLoc)
import Hickory.Math.Matrix
import Linear (V2, V3, V4, M44, M33,transpose)
import Graphics.GL.Compatibility41 as GL
import Foreign.Ptr (Ptr, castPtr)
import Foreign.Marshal.Array (withArray)
import Data.List (genericLength)
bindShaderUniform :: (Uniform a, MonadIO m) => String -> a -> Shader -> m ()
bindShaderUniform name val shader = case retrieveLoc name shader of
Just loc -> liftIO $ bindUniformLoc loc val
Nothing -> pure ()
class Uniform a where
bindUniformLoc :: UniformLoc -> a -> IO ()
instance Uniform Int where
bindUniformLoc loc i = glUniform1i loc (fromIntegral i)
instance Uniform Float where
bindUniformLoc loc f = glUniform1f loc f
instance Uniform Double where
bindUniformLoc loc f = glUniform1f loc (realToFrac f)
instance Uniform (V2 Double) where
bindUniformLoc loc v = uniform2fv loc [v]
instance Uniform [V3 Double] where
bindUniformLoc loc v = uniform3fv loc v
instance Uniform (V3 Double) where
bindUniformLoc loc v = uniform3fv loc [v]
instance Uniform [V4 Double] where
bindUniformLoc loc v = uniform4fv loc v
instance Uniform (V4 Double) where
bindUniformLoc loc v = uniform4fv loc [v]
instance Uniform [Mat33] where
bindUniformLoc loc m = uniformMatrix3fv loc m
instance Uniform Mat33 where
bindUniformLoc loc m = uniformMatrix3fv loc [m]
instance Uniform [Mat44] where
bindUniformLoc loc m = uniformMatrix4fv loc m
instance Uniform Mat44 where
bindUniformLoc loc m = uniformMatrix4fv loc [m]
uniform4fv :: GLint -> [V4 Double] -> IO ()
uniform4fv loc vs =
withVec4s vs $ \ptr ->
glUniform4fv loc (genericLength vs) (castPtr ptr)
uniform3fv :: GLint -> [V3 Double] -> IO ()
uniform3fv loc vs =
withVec3s vs $ \ptr ->
glUniform3fv loc (genericLength vs) (castPtr ptr)
uniform2fv :: GLint -> [V2 Double] -> IO ()
uniform2fv loc vs =
withVec2s vs $ \ptr ->
glUniform2fv loc (genericLength vs) (castPtr ptr)
withVec4s :: [V4 Double] -> (Ptr GLfloat -> IO b) -> IO b
withVec4s vecs f = withArray (map (fmap realToFrac) vecs :: [V4 GLfloat]) (f . castPtr)
withVec3s :: [V3 Double] -> (Ptr GLfloat -> IO b) -> IO b
withVec3s vecs f = withArray (map (fmap realToFrac) vecs :: [V3 GLfloat]) (f . castPtr)
withVec2s :: [V2 Double] -> (Ptr GLfloat -> IO b) -> IO b
withVec2s vecs f = withArray (map (fmap realToFrac) vecs :: [V2 GLfloat]) (f . castPtr)
withVec4s vecs f = withVec4 ( vecs ! ! 0 ) ( f . castPtr ) --withArray vecs ( f . castPtr )
withMat44s :: [Mat44] -> (Ptr GLfloat -> IO b) -> IO b
withMat44s mats f = withArray (map (\mat -> (fmap realToFrac <$> transpose mat :: M44 GLfloat)) mats) (f . castPtr)
withMat33s :: [Mat33] -> (Ptr GLfloat -> IO b) -> IO b
withMat33s mats f = withArray (map (\mat -> (fmap realToFrac <$> transpose mat :: M33 GLfloat)) mats) (f . castPtr)
uniformMatrix4fv :: GLint -> [Mat44] -> IO ()
uniformMatrix4fv loc mats =
withMat44s mats $ \ptr ->
glUniformMatrix4fv loc (genericLength mats) GL_FALSE (castPtr ptr)
uniformMatrix3fv :: GLint -> [Mat33] -> IO ()
uniformMatrix3fv loc mats =
withMat33s mats $ \ptr ->
glUniformMatrix3fv loc (genericLength mats) GL_FALSE (castPtr ptr)
| null | https://raw.githubusercontent.com/asivitz/Hickory/e668f0ca6cc4d8bf19b1463b6a7525844786e2c7/core/Hickory/Graphics/Uniforms.hs | haskell | withArray vecs ( f . castPtr ) | # LANGUAGE FlexibleInstances #
module Hickory.Graphics.Uniforms where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Hickory.Graphics.Shader (Shader, retrieveLoc, UniformLoc)
import Hickory.Math.Matrix
import Linear (V2, V3, V4, M44, M33,transpose)
import Graphics.GL.Compatibility41 as GL
import Foreign.Ptr (Ptr, castPtr)
import Foreign.Marshal.Array (withArray)
import Data.List (genericLength)
bindShaderUniform :: (Uniform a, MonadIO m) => String -> a -> Shader -> m ()
bindShaderUniform name val shader = case retrieveLoc name shader of
Just loc -> liftIO $ bindUniformLoc loc val
Nothing -> pure ()
class Uniform a where
bindUniformLoc :: UniformLoc -> a -> IO ()
instance Uniform Int where
bindUniformLoc loc i = glUniform1i loc (fromIntegral i)
instance Uniform Float where
bindUniformLoc loc f = glUniform1f loc f
instance Uniform Double where
bindUniformLoc loc f = glUniform1f loc (realToFrac f)
instance Uniform (V2 Double) where
bindUniformLoc loc v = uniform2fv loc [v]
instance Uniform [V3 Double] where
bindUniformLoc loc v = uniform3fv loc v
instance Uniform (V3 Double) where
bindUniformLoc loc v = uniform3fv loc [v]
instance Uniform [V4 Double] where
bindUniformLoc loc v = uniform4fv loc v
instance Uniform (V4 Double) where
bindUniformLoc loc v = uniform4fv loc [v]
instance Uniform [Mat33] where
bindUniformLoc loc m = uniformMatrix3fv loc m
instance Uniform Mat33 where
bindUniformLoc loc m = uniformMatrix3fv loc [m]
instance Uniform [Mat44] where
bindUniformLoc loc m = uniformMatrix4fv loc m
instance Uniform Mat44 where
bindUniformLoc loc m = uniformMatrix4fv loc [m]
uniform4fv :: GLint -> [V4 Double] -> IO ()
uniform4fv loc vs =
withVec4s vs $ \ptr ->
glUniform4fv loc (genericLength vs) (castPtr ptr)
uniform3fv :: GLint -> [V3 Double] -> IO ()
uniform3fv loc vs =
withVec3s vs $ \ptr ->
glUniform3fv loc (genericLength vs) (castPtr ptr)
uniform2fv :: GLint -> [V2 Double] -> IO ()
uniform2fv loc vs =
withVec2s vs $ \ptr ->
glUniform2fv loc (genericLength vs) (castPtr ptr)
withVec4s :: [V4 Double] -> (Ptr GLfloat -> IO b) -> IO b
withVec4s vecs f = withArray (map (fmap realToFrac) vecs :: [V4 GLfloat]) (f . castPtr)
withVec3s :: [V3 Double] -> (Ptr GLfloat -> IO b) -> IO b
withVec3s vecs f = withArray (map (fmap realToFrac) vecs :: [V3 GLfloat]) (f . castPtr)
withVec2s :: [V2 Double] -> (Ptr GLfloat -> IO b) -> IO b
withVec2s vecs f = withArray (map (fmap realToFrac) vecs :: [V2 GLfloat]) (f . castPtr)
withMat44s :: [Mat44] -> (Ptr GLfloat -> IO b) -> IO b
withMat44s mats f = withArray (map (\mat -> (fmap realToFrac <$> transpose mat :: M44 GLfloat)) mats) (f . castPtr)
withMat33s :: [Mat33] -> (Ptr GLfloat -> IO b) -> IO b
withMat33s mats f = withArray (map (\mat -> (fmap realToFrac <$> transpose mat :: M33 GLfloat)) mats) (f . castPtr)
uniformMatrix4fv :: GLint -> [Mat44] -> IO ()
uniformMatrix4fv loc mats =
withMat44s mats $ \ptr ->
glUniformMatrix4fv loc (genericLength mats) GL_FALSE (castPtr ptr)
uniformMatrix3fv :: GLint -> [Mat33] -> IO ()
uniformMatrix3fv loc mats =
withMat33s mats $ \ptr ->
glUniformMatrix3fv loc (genericLength mats) GL_FALSE (castPtr ptr)
|
fee2caf1c9c235ca81afbe3825b1fdd6fa3fdef1262a15d5da2252d3351258f0 | lloda/guile-newra | newra.scm | -*- mode : scheme ; coding : utf-8 -*-
( c ) 2016 - 2019
; This library 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.
;;; Commentary:
newra is a replacement for 's C - based arrays . This is the hub module .
;;; Code:
(define-module (newra))
(import (newra base) (newra map) (newra print) (newra read) (newra from)
(newra cat) (newra reshape) (newra lib))
(re-export ra?
make-ra-root ra-root ra-zero ra-dims ra-vlen ra-vref ra-vset!
ra-check %%ra-rank %%ra-root %%ra-zero %%ra-dims
ra-rank ra-type make-ra-new make-ra-root
make-aseq aseq? aseq-org aseq-inc aseq-ref
make-dim dim? dim-len dim-lo dim-hi dim-step
c-dims
ra-offset
ra-slice ra-cell ra-ref ra-set!
ra-slice-for-each ra-slice-for-each-in-order
ra-fill! ra-copy! ra-swap! ra-swap-in-order! ra-map! ra-map-in-order! ra-for-each
ra-equal? ra-any ra-every
ra-index-map!
ra-len ra-lo ra-size make-ra make-typed-ra make-ra-shared ra->list
ra-dimensions ra-shape ra-offset
array->ra ra->array as-ra
ra-i ra-iota
ra-copy ra-map
ra-reverse ra-transpose ra-untranspose ra-order-c?
ra-ravel ra-reshape ra-tile
ra-fold
ra-rotate! ra-rotate
ra-singletonize ra-clip
ra-from ra-from-copy ra-amend! dots
ra-cat ra-cats
list->ra list->typed-ra
ra-format)
| null | https://raw.githubusercontent.com/lloda/guile-newra/d6e76544e202ad69e8c38128c5518045bc09299b/mod/newra.scm | scheme | coding : utf-8 -*-
This library is free software; you can redistribute it and/or modify it under
either version 3 of the License , or ( at your option ) any
later version.
Commentary:
Code: |
( c ) 2016 - 2019
the terms of the GNU General Public License as published by the Free
newra is a replacement for 's C - based arrays . This is the hub module .
(define-module (newra))
(import (newra base) (newra map) (newra print) (newra read) (newra from)
(newra cat) (newra reshape) (newra lib))
(re-export ra?
make-ra-root ra-root ra-zero ra-dims ra-vlen ra-vref ra-vset!
ra-check %%ra-rank %%ra-root %%ra-zero %%ra-dims
ra-rank ra-type make-ra-new make-ra-root
make-aseq aseq? aseq-org aseq-inc aseq-ref
make-dim dim? dim-len dim-lo dim-hi dim-step
c-dims
ra-offset
ra-slice ra-cell ra-ref ra-set!
ra-slice-for-each ra-slice-for-each-in-order
ra-fill! ra-copy! ra-swap! ra-swap-in-order! ra-map! ra-map-in-order! ra-for-each
ra-equal? ra-any ra-every
ra-index-map!
ra-len ra-lo ra-size make-ra make-typed-ra make-ra-shared ra->list
ra-dimensions ra-shape ra-offset
array->ra ra->array as-ra
ra-i ra-iota
ra-copy ra-map
ra-reverse ra-transpose ra-untranspose ra-order-c?
ra-ravel ra-reshape ra-tile
ra-fold
ra-rotate! ra-rotate
ra-singletonize ra-clip
ra-from ra-from-copy ra-amend! dots
ra-cat ra-cats
list->ra list->typed-ra
ra-format)
|
8fb2729f8c95c2a342f81c2fd9c252d7a2bd8dd165d46a148c5755f1b64d579b | everpeace/programming-erlang-code | udp_test.erl | -module(udp_test).
-export([start_server/0, client/1]).
start_server() ->
spawn(fun() -> server(4000) end).
%% The server
server(Port) ->
{ok, Socket} = gen_udp:open(Port, [binary]),
io:format("server opened socket:~p~n",[Socket]),
loop(Socket).
loop(Socket) ->
receive
{udp, Socket, Host, Port, Bin} = Msg ->
io:format("server received:~p~n",[Msg]),
N = binary_to_term(Bin),
Fac = fac(N),
gen_udp:send(Socket, Host, Port, term_to_binary(Fac)),
loop(Socket)
end.
fac(0) -> 1;
fac(N) -> N * fac(N-1).
%% The client
client(N) ->
{ok, Socket} = gen_udp:open(0, [binary]),
io:format("client opened socket=~p~n",[Socket]),
ok = gen_udp:send(Socket, "localhost", 4000,
term_to_binary(N)),
Value = receive
{udp, Socket, _, _, Bin} = Msg ->
io:format("client received:~p~n",[Msg]),
binary_to_term(Bin)
after 2000 ->
0
end,
gen_udp:close(Socket),
Value.
| null | https://raw.githubusercontent.com/everpeace/programming-erlang-code/8ef31aa13d15b41754dda225c50284915c29cb48/code/udp_test.erl | erlang | The server
The client | -module(udp_test).
-export([start_server/0, client/1]).
start_server() ->
spawn(fun() -> server(4000) end).
server(Port) ->
{ok, Socket} = gen_udp:open(Port, [binary]),
io:format("server opened socket:~p~n",[Socket]),
loop(Socket).
loop(Socket) ->
receive
{udp, Socket, Host, Port, Bin} = Msg ->
io:format("server received:~p~n",[Msg]),
N = binary_to_term(Bin),
Fac = fac(N),
gen_udp:send(Socket, Host, Port, term_to_binary(Fac)),
loop(Socket)
end.
fac(0) -> 1;
fac(N) -> N * fac(N-1).
client(N) ->
{ok, Socket} = gen_udp:open(0, [binary]),
io:format("client opened socket=~p~n",[Socket]),
ok = gen_udp:send(Socket, "localhost", 4000,
term_to_binary(N)),
Value = receive
{udp, Socket, _, _, Bin} = Msg ->
io:format("client received:~p~n",[Msg]),
binary_to_term(Bin)
after 2000 ->
0
end,
gen_udp:close(Socket),
Value.
|
c20d2944b62da2a60b4ff267ca57169f3d5c9d6b31fa707a155947f55c720341 | fetburner/Coq2SML | configwin_types.ml | (*********************************************************************************)
Cameleon
(* *)
Copyright ( C ) 2005 Institut National de Recherche en Informatique et
(* en Automatique. All rights reserved. *)
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
(* License, or 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 Library General Public License for more details .
(* *)
You should have received a copy of the GNU Library General Public
License along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
(* *)
(* Contact: *)
(* *)
(*********************************************************************************)
* This module contains the types used in Configwin .
open Config_file
let name_to_keysym =
("Button1", Configwin_keys.xk_Pointer_Button1) ::
("Button2", Configwin_keys.xk_Pointer_Button2) ::
("Button3", Configwin_keys.xk_Pointer_Button3) ::
("Button4", Configwin_keys.xk_Pointer_Button4) ::
("Button5", Configwin_keys.xk_Pointer_Button5) ::
Configwin_keys.name_to_keysym
let string_to_key s =
let mask = ref [] in
let key = try
let pos = String.rindex s '-' in
for i = 0 to pos - 1 do
let m = match s.[i] with
'C' -> `CONTROL
| 'S' -> `SHIFT
| 'L' -> `LOCK
| 'M' -> `MOD1
| 'A' -> `MOD1
| '1' -> `MOD1
| '2' -> `MOD2
| '3' -> `MOD3
| '4' -> `MOD4
| '5' -> `MOD5
| _ ->
prerr_endline s;
raise Not_found
in
mask := m :: !mask
done;
String.sub s (pos+1) (String.length s - pos - 1)
with _ ->
s
in
try
!mask, List.assoc key name_to_keysym
with
e ->
prerr_endline s;
raise e
let key_to_string (m, k) =
let s = List.assoc k Configwin_keys.keysym_to_name in
match m with
[] -> s
| _ ->
let rec iter m s =
match m with
[] -> s
| c :: m ->
iter m ((
match c with
`CONTROL -> "C"
| `SHIFT -> "S"
| `LOCK -> "L"
| `MOD1 -> "A"
| `MOD2 -> "2"
| `MOD3 -> "3"
| `MOD4 -> "4"
| `MOD5 -> "5"
| _ -> raise Not_found
) ^ s)
in
iter m ("-" ^ s)
let modifiers_to_string m =
let rec iter m s =
match m with
[] -> s
| c :: m ->
iter m ((
match c with
`CONTROL -> "<ctrl>"
| `SHIFT -> "<shft>"
| `LOCK -> "<lock>"
| `MOD1 -> "<alt>"
| `MOD2 -> "<mod2>"
| `MOD3 -> "<mod3>"
| `MOD4 -> "<mod4>"
| `MOD5 -> "<mod5>"
| _ -> raise Not_found
) ^ s)
in
iter m ""
let value_to_key v =
match v with
Raw.String s -> string_to_key s
| _ ->
prerr_endline "value_to_key";
raise Not_found
let key_to_value k =
Raw.String (key_to_string k)
let key_cp_wrapper =
{
to_raw = key_to_value ;
of_raw = value_to_key ;
}
(** A class to define key options, with the {!Config_file} module. *)
class key_cp =
[(Gdk.Tags.modifier list * int)] Config_file.cp_custom_type key_cp_wrapper
(** This type represents a string or filename parameter, or
any other type, depending on the given conversion functions. *)
type 'a string_param = {
string_label : string; (** the label of the parameter *)
mutable string_value : 'a; (** the current value of the parameter *)
string_editable : bool ; (** indicates if the value can be changed *)
string_f_apply : ('a -> unit) ; (** the function to call to apply the new value of the parameter *)
string_help : string option ; (** optional help string *)
string_expand : bool ; (** expand or not *)
string_to_string : 'a -> string ;
string_of_string : string -> 'a ;
} ;;
(** This type represents a boolean parameter. *)
type bool_param = {
bool_label : string; (** the label of the parameter *)
mutable bool_value : bool; (** the current value of the parameter *)
bool_editable : bool ; (** indicates if the value can be changed *)
bool_f_apply : (bool -> unit) ; (** the function to call to apply the new value of the parameter *)
bool_help : string option ; (** optional help string *)
} ;;
(** This type represents a parameter whose value is a list of ['a]. *)
type 'a list_param = {
list_label : string; (** the label of the parameter *)
mutable list_value : 'a list; (** the current value of the parameter *)
list_titles : string list option; (** the titles of columns, if they must be displayed *)
list_f_edit : ('a -> 'a) option; (** optional edition function *)
list_eq : ('a -> 'a -> bool) ; (** the comparison function used to get list without doubles *)
list_strings : ('a -> string list); (** the function to get a string list from a ['a]. *)
list_color : ('a -> string option) ; (** a function to get the optional color of an element *)
list_editable : bool ; (** indicates if the value can be changed *)
list_f_add : unit -> 'a list ; (** the function to call to add list *)
list_f_apply : ('a list -> unit) ; (** the function to call to apply the new value of the parameter *)
list_help : string option ; (** optional help string *)
} ;;
type combo_param = {
combo_label : string ;
mutable combo_value : string ;
combo_choices : string list ;
combo_editable : bool ;
combo_blank_allowed : bool ;
combo_new_allowed : bool ;
combo_f_apply : (string -> unit);
combo_help : string option ; (** optional help string *)
combo_expand : bool ; (** expand the entry widget or not *)
} ;;
type custom_param = {
custom_box : GPack.box ;
custom_f_apply : (unit -> unit) ;
custom_expand : bool ;
custom_framed : string option ; (** optional label for an optional frame *)
} ;;
type color_param = {
color_label : string; (** the label of the parameter *)
mutable color_value : string; (** the current value of the parameter *)
color_editable : bool ; (** indicates if the value can be changed *)
color_f_apply : (string -> unit) ; (** the function to call to apply the new value of the parameter *)
color_help : string option ; (** optional help string *)
color_expand : bool ; (** expand the entry widget or not *)
} ;;
type date_param = {
date_label : string ; (** the label of the parameter *)
mutable date_value : int * int * int ; (** day, month, year *)
date_editable : bool ; (** indicates if the value can be changed *)
date_f_string : (int * int * int) -> string ;
(** the function used to display the current value (day, month, year) *)
date_f_apply : ((int * int * int) -> unit) ;
(** the function to call to apply the new value (day, month, year) of the parameter *)
date_help : string option ; (** optional help string *)
date_expand : bool ; (** expand the entry widget or not *)
} ;;
type font_param = {
font_label : string ; (** the label of the parameter *)
mutable font_value : string ; (** the font name *)
font_editable : bool ; (** indicates if the value can be changed *)
font_f_apply : (string -> unit) ;
(** the function to call to apply the new value of the parameter *)
font_help : string option ; (** optional help string *)
font_expand : bool ; (** expand the entry widget or not *)
} ;;
type hotkey_param = {
hk_label : string ; (** the label of the parameter *)
mutable hk_value : (Gdk.Tags.modifier list * int) ;
(** The value, as a list of modifiers and a key code *)
hk_editable : bool ; (** indicates if the value can be changed *)
hk_f_apply : ((Gdk.Tags.modifier list * int) -> unit) ;
(** the function to call to apply the new value of the paramter *)
hk_help : string option ; (** optional help string *)
hk_expand : bool ; (** expand or not *)
}
type modifiers_param = {
md_label : string ; (** the label of the parameter *)
mutable md_value : Gdk.Tags.modifier list ;
(** The value, as a list of modifiers and a key code *)
md_editable : bool ; (** indicates if the value can be changed *)
md_f_apply : Gdk.Tags.modifier list -> unit ;
(** the function to call to apply the new value of the paramter *)
md_help : string option ; (** optional help string *)
md_expand : bool ; (** expand or not *)
md_allow : Gdk.Tags.modifier list
}
(** This type represents the different kinds of parameters. *)
type parameter_kind =
String_param of string string_param
| List_param of (GData.tooltips -> <box: GObj.widget ; apply : unit>)
| Filename_param of string string_param
| Bool_param of bool_param
| Text_param of string string_param
| Combo_param of combo_param
| Custom_param of custom_param
| Color_param of color_param
| Date_param of date_param
| Font_param of font_param
| Hotkey_param of hotkey_param
| Modifiers_param of modifiers_param
| Html_param of string string_param
;;
(** This type represents the structure of the configuration window. *)
type configuration_structure =
| Section of string * GtkStock.id option * parameter_kind list (** label of the section, icon, parameters *)
| Section_list of string * GtkStock.id option * configuration_structure list (** label of the section, list of the sub sections *)
;;
(** To indicate what button was pushed by the user when the window is closed. *)
type return_button =
Return_apply (** The user clicked on Apply at least once before
closing the window with Cancel or the window manager. *)
| Return_ok (** The user closed the window with the ok button. *)
| Return_cancel (** The user closed the window with the cancel
button or the window manager but never clicked
on the apply button.*)
* { 2 Bindings in the html editor }
type html_binding = {
mutable html_key : (Gdk.Tags.modifier list * int) ;
mutable html_begin : string ;
mutable html_end : string ;
}
let htmlbinding_cp_wrapper =
let w = Config_file.tuple3_wrappers
key_cp_wrapper
Config_file.string_wrappers
Config_file.string_wrappers
in
{
to_raw = (fun v -> w.to_raw (v.html_key, v.html_begin, v.html_end)) ;
of_raw =
(fun r -> let (k,b,e) = w.of_raw r in
{ html_key = k ; html_begin = b ; html_end = e }
) ;
}
class htmlbinding_cp =
[html_binding] Config_file.option_cp htmlbinding_cp_wrapper
| null | https://raw.githubusercontent.com/fetburner/Coq2SML/322d613619edbb62edafa999bff24b1993f37612/coq-8.4pl4/ide/utils/configwin_types.ml | ocaml | *******************************************************************************
en Automatique. All rights reserved.
This program is free software; you can redistribute it and/or modify
License, or 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
Contact:
*******************************************************************************
* A class to define key options, with the {!Config_file} module.
* This type represents a string or filename parameter, or
any other type, depending on the given conversion functions.
* the label of the parameter
* the current value of the parameter
* indicates if the value can be changed
* the function to call to apply the new value of the parameter
* optional help string
* expand or not
* This type represents a boolean parameter.
* the label of the parameter
* the current value of the parameter
* indicates if the value can be changed
* the function to call to apply the new value of the parameter
* optional help string
* This type represents a parameter whose value is a list of ['a].
* the label of the parameter
* the current value of the parameter
* the titles of columns, if they must be displayed
* optional edition function
* the comparison function used to get list without doubles
* the function to get a string list from a ['a].
* a function to get the optional color of an element
* indicates if the value can be changed
* the function to call to add list
* the function to call to apply the new value of the parameter
* optional help string
* optional help string
* expand the entry widget or not
* optional label for an optional frame
* the label of the parameter
* the current value of the parameter
* indicates if the value can be changed
* the function to call to apply the new value of the parameter
* optional help string
* expand the entry widget or not
* the label of the parameter
* day, month, year
* indicates if the value can be changed
* the function used to display the current value (day, month, year)
* the function to call to apply the new value (day, month, year) of the parameter
* optional help string
* expand the entry widget or not
* the label of the parameter
* the font name
* indicates if the value can be changed
* the function to call to apply the new value of the parameter
* optional help string
* expand the entry widget or not
* the label of the parameter
* The value, as a list of modifiers and a key code
* indicates if the value can be changed
* the function to call to apply the new value of the paramter
* optional help string
* expand or not
* the label of the parameter
* The value, as a list of modifiers and a key code
* indicates if the value can be changed
* the function to call to apply the new value of the paramter
* optional help string
* expand or not
* This type represents the different kinds of parameters.
* This type represents the structure of the configuration window.
* label of the section, icon, parameters
* label of the section, list of the sub sections
* To indicate what button was pushed by the user when the window is closed.
* The user clicked on Apply at least once before
closing the window with Cancel or the window manager.
* The user closed the window with the ok button.
* The user closed the window with the cancel
button or the window manager but never clicked
on the apply button. | Cameleon
Copyright ( C ) 2005 Institut National de Recherche en Informatique et
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
GNU Library General Public License for more details .
You should have received a copy of the GNU Library General Public
License along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
* This module contains the types used in Configwin .
open Config_file
let name_to_keysym =
("Button1", Configwin_keys.xk_Pointer_Button1) ::
("Button2", Configwin_keys.xk_Pointer_Button2) ::
("Button3", Configwin_keys.xk_Pointer_Button3) ::
("Button4", Configwin_keys.xk_Pointer_Button4) ::
("Button5", Configwin_keys.xk_Pointer_Button5) ::
Configwin_keys.name_to_keysym
let string_to_key s =
let mask = ref [] in
let key = try
let pos = String.rindex s '-' in
for i = 0 to pos - 1 do
let m = match s.[i] with
'C' -> `CONTROL
| 'S' -> `SHIFT
| 'L' -> `LOCK
| 'M' -> `MOD1
| 'A' -> `MOD1
| '1' -> `MOD1
| '2' -> `MOD2
| '3' -> `MOD3
| '4' -> `MOD4
| '5' -> `MOD5
| _ ->
prerr_endline s;
raise Not_found
in
mask := m :: !mask
done;
String.sub s (pos+1) (String.length s - pos - 1)
with _ ->
s
in
try
!mask, List.assoc key name_to_keysym
with
e ->
prerr_endline s;
raise e
let key_to_string (m, k) =
let s = List.assoc k Configwin_keys.keysym_to_name in
match m with
[] -> s
| _ ->
let rec iter m s =
match m with
[] -> s
| c :: m ->
iter m ((
match c with
`CONTROL -> "C"
| `SHIFT -> "S"
| `LOCK -> "L"
| `MOD1 -> "A"
| `MOD2 -> "2"
| `MOD3 -> "3"
| `MOD4 -> "4"
| `MOD5 -> "5"
| _ -> raise Not_found
) ^ s)
in
iter m ("-" ^ s)
let modifiers_to_string m =
let rec iter m s =
match m with
[] -> s
| c :: m ->
iter m ((
match c with
`CONTROL -> "<ctrl>"
| `SHIFT -> "<shft>"
| `LOCK -> "<lock>"
| `MOD1 -> "<alt>"
| `MOD2 -> "<mod2>"
| `MOD3 -> "<mod3>"
| `MOD4 -> "<mod4>"
| `MOD5 -> "<mod5>"
| _ -> raise Not_found
) ^ s)
in
iter m ""
let value_to_key v =
match v with
Raw.String s -> string_to_key s
| _ ->
prerr_endline "value_to_key";
raise Not_found
let key_to_value k =
Raw.String (key_to_string k)
let key_cp_wrapper =
{
to_raw = key_to_value ;
of_raw = value_to_key ;
}
class key_cp =
[(Gdk.Tags.modifier list * int)] Config_file.cp_custom_type key_cp_wrapper
type 'a string_param = {
string_to_string : 'a -> string ;
string_of_string : string -> 'a ;
} ;;
type bool_param = {
} ;;
type 'a list_param = {
} ;;
type combo_param = {
combo_label : string ;
mutable combo_value : string ;
combo_choices : string list ;
combo_editable : bool ;
combo_blank_allowed : bool ;
combo_new_allowed : bool ;
combo_f_apply : (string -> unit);
} ;;
type custom_param = {
custom_box : GPack.box ;
custom_f_apply : (unit -> unit) ;
custom_expand : bool ;
} ;;
type color_param = {
} ;;
type date_param = {
date_f_string : (int * int * int) -> string ;
date_f_apply : ((int * int * int) -> unit) ;
} ;;
type font_param = {
font_f_apply : (string -> unit) ;
} ;;
type hotkey_param = {
mutable hk_value : (Gdk.Tags.modifier list * int) ;
hk_f_apply : ((Gdk.Tags.modifier list * int) -> unit) ;
}
type modifiers_param = {
mutable md_value : Gdk.Tags.modifier list ;
md_f_apply : Gdk.Tags.modifier list -> unit ;
md_allow : Gdk.Tags.modifier list
}
type parameter_kind =
String_param of string string_param
| List_param of (GData.tooltips -> <box: GObj.widget ; apply : unit>)
| Filename_param of string string_param
| Bool_param of bool_param
| Text_param of string string_param
| Combo_param of combo_param
| Custom_param of custom_param
| Color_param of color_param
| Date_param of date_param
| Font_param of font_param
| Hotkey_param of hotkey_param
| Modifiers_param of modifiers_param
| Html_param of string string_param
;;
type configuration_structure =
;;
type return_button =
* { 2 Bindings in the html editor }
type html_binding = {
mutable html_key : (Gdk.Tags.modifier list * int) ;
mutable html_begin : string ;
mutable html_end : string ;
}
let htmlbinding_cp_wrapper =
let w = Config_file.tuple3_wrappers
key_cp_wrapper
Config_file.string_wrappers
Config_file.string_wrappers
in
{
to_raw = (fun v -> w.to_raw (v.html_key, v.html_begin, v.html_end)) ;
of_raw =
(fun r -> let (k,b,e) = w.of_raw r in
{ html_key = k ; html_begin = b ; html_end = e }
) ;
}
class htmlbinding_cp =
[html_binding] Config_file.option_cp htmlbinding_cp_wrapper
|
35e6e605db655f6907f02ebdf5ee12eeeb5221c444c69894c8d06b15b45b6f87 | haskell-checkers/checkers | Ord.hs | module Test.QuickCheck.Instances.Ord where
import Test.QuickCheck
import Control.Monad.Extensions
greaterThan :: (Ord a) => a -> Gen a -> Gen a
greaterThan v = satisfiesM (> v)
lessThan :: (Ord a) => a -> Gen a -> Gen a
lessThan v = satisfiesM (< v)
| null | https://raw.githubusercontent.com/haskell-checkers/checkers/6cdc62e3fa50db3458f88f268682e5f1cfd9ab2c/src/Test/QuickCheck/Instances/Ord.hs | haskell | module Test.QuickCheck.Instances.Ord where
import Test.QuickCheck
import Control.Monad.Extensions
greaterThan :: (Ord a) => a -> Gen a -> Gen a
greaterThan v = satisfiesM (> v)
lessThan :: (Ord a) => a -> Gen a -> Gen a
lessThan v = satisfiesM (< v)
| |
01aade70f5cde1986f3c0ed08717207a485a22551ae98273f1e654ce8be50584 | vult-dsp/vult | float.ml |
The MIT License ( MIT )
Copyright ( c ) 2017
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE .
The MIT License (MIT)
Copyright (c) 2017 Leonardo Laguna Ruiz
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.
*)
let reduce_precision = ref false
let to_string (f : float) = CCString.map (fun c -> if c = ',' then '.' else c) (string_of_float f)
let crop (f : float) =
if !reduce_precision
then (
let ff = f *. 10000000.0 in
ceil ff /. 10000000.0)
else f
;;
| null | https://raw.githubusercontent.com/vult-dsp/vult/860b2b7a8e891aa729578175a931ce2a9345428b/src/util/float.ml | ocaml |
The MIT License ( MIT )
Copyright ( c ) 2017
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE .
The MIT License (MIT)
Copyright (c) 2017 Leonardo Laguna Ruiz
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.
*)
let reduce_precision = ref false
let to_string (f : float) = CCString.map (fun c -> if c = ',' then '.' else c) (string_of_float f)
let crop (f : float) =
if !reduce_precision
then (
let ff = f *. 10000000.0 in
ceil ff /. 10000000.0)
else f
;;
| |
a3d42730e4ccdc9fd25f75223a8b1ea48a7f3af1a183d277f34bcd557a9ecd8e | neil-lindquist/linear-programming | test-utils.lisp | (uiop:define-package :linear-programming-test/test-utils
(:use :cl)
(:export #:set-equal
#:simple-linear-constraint-set-equal))
(in-package :linear-programming-test/test-utils)
(defun set-equal (s1 s2 &key (test #'equal))
"Helper method to test for set equality"
(null (set-exclusive-or s1 s2 :test test)))
(defun simple-linear-constraint-set-equal (s1 s2)
"Helper method to test that two sets of simplified linear constraints are equal"
(set-equal s1 s2
:test (lambda (c1 c2)
(and (= 3 (length c1) (length c2))
(eq (first c1) (first c2))
(set-equal (second c1) (second c2))
(= (third c1) (third c2))))))
| null | https://raw.githubusercontent.com/neil-lindquist/linear-programming/417f764e65be1a92f7f9fc0f1ed8092700e916c6/t/test-utils.lisp | lisp | (uiop:define-package :linear-programming-test/test-utils
(:use :cl)
(:export #:set-equal
#:simple-linear-constraint-set-equal))
(in-package :linear-programming-test/test-utils)
(defun set-equal (s1 s2 &key (test #'equal))
"Helper method to test for set equality"
(null (set-exclusive-or s1 s2 :test test)))
(defun simple-linear-constraint-set-equal (s1 s2)
"Helper method to test that two sets of simplified linear constraints are equal"
(set-equal s1 s2
:test (lambda (c1 c2)
(and (= 3 (length c1) (length c2))
(eq (first c1) (first c2))
(set-equal (second c1) (second c2))
(= (third c1) (third c2))))))
| |
a97b888830b84abbd75e8fef32971505c3f8fb4ae1e007a2b835dca420dba418 | glguy/advent | KnotHash.hs | # Language ImportQualifiedPost , DataKinds #
module KnotHash (knotHash, tieKnots) where
import Advent (chunks)
import Advent.Permutation (mkPermutation, runPermutation, Permutation)
import Data.Bits (Bits(xor))
import Data.Char (ord)
import Data.Foldable (Foldable(foldl'))
import Data.List (foldl1')
import Data.Word (Word8)
-- | Given a rope size and an input string, compute the resulting hash.
knotHash ::
String {- ^ input string -} ->
Integer {- ^ knot value -}
knotHash =
bytesToInteger . map (foldl1' xor) .
chunks 16 . tieKnots . concat . replicate 64 .
(++ [17, 31, 73, 47, 23]) . map ord
-- | Convert list of bytes into integer in big-endian order.
bytesToInteger :: [Word8] -> Integer
bytesToInteger = foldl' (\acc x -> acc * 0x100 + fromIntegral x) 0
-- | Create a rope, tie knots of the given lengths while skipping
-- according to the increasing skip rule.
tieKnots ::
[Int] {- ^ knot lengths -} ->
[Word8] {- ^ resulting rope -}
tieKnots lengths = runPermutation fromIntegral
$ mconcat [ p o l
| (o,l) <- zip (scanl (+) 0 (zipWith (+) [0..] lengths)) lengths
]
p :: Int -> Int -> Permutation 256
p o l = mkPermutation $ \i -> if (i-o)`mod`256 < l
then l-1-i+o+o
else i
| null | https://raw.githubusercontent.com/glguy/advent/cba905b5efd876aa0044995a7d0dbe5a40246a3b/knothash/KnotHash.hs | haskell | | Given a rope size and an input string, compute the resulting hash.
^ input string
^ knot value
| Convert list of bytes into integer in big-endian order.
| Create a rope, tie knots of the given lengths while skipping
according to the increasing skip rule.
^ knot lengths
^ resulting rope | # Language ImportQualifiedPost , DataKinds #
module KnotHash (knotHash, tieKnots) where
import Advent (chunks)
import Advent.Permutation (mkPermutation, runPermutation, Permutation)
import Data.Bits (Bits(xor))
import Data.Char (ord)
import Data.Foldable (Foldable(foldl'))
import Data.List (foldl1')
import Data.Word (Word8)
knotHash ::
knotHash =
bytesToInteger . map (foldl1' xor) .
chunks 16 . tieKnots . concat . replicate 64 .
(++ [17, 31, 73, 47, 23]) . map ord
bytesToInteger :: [Word8] -> Integer
bytesToInteger = foldl' (\acc x -> acc * 0x100 + fromIntegral x) 0
tieKnots ::
tieKnots lengths = runPermutation fromIntegral
$ mconcat [ p o l
| (o,l) <- zip (scanl (+) 0 (zipWith (+) [0..] lengths)) lengths
]
p :: Int -> Int -> Permutation 256
p o l = mkPermutation $ \i -> if (i-o)`mod`256 < l
then l-1-i+o+o
else i
|
bd5acd17142abdb7c790533471bc936f498a63b842f257e066c402f7d9e5ec70 | erlang/otp | ssl_eqc_handshake.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2018 - 2022 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%
-module(ssl_eqc_handshake).
-compile(export_all).
-proptest(eqc).
-proptest([triq,proper]).
-ifndef(EQC).
-ifndef(PROPER).
-ifndef(TRIQ).
-define(EQC,true).
-endif.
-endif.
-endif.
-ifdef(EQC).
-include_lib("eqc/include/eqc.hrl").
-define(MOD_eqc,eqc).
-else.
-ifdef(PROPER).
-include_lib("proper/include/proper.hrl").
-define(MOD_eqc,proper).
-else.
-ifdef(TRIQ).
-define(MOD_eqc,triq).
-include_lib("triq/include/triq.hrl").
-endif.
-endif.
-endif.
-include_lib("kernel/include/inet.hrl").
-include_lib("ssl/src/tls_handshake_1_3.hrl").
-include_lib("ssl/src/tls_handshake.hrl").
-include_lib("ssl/src/ssl_handshake.hrl").
-include_lib("ssl/src/ssl_alert.hrl").
-include_lib("ssl/src/ssl_internal.hrl").
-define('TLS_v1.3', {3,4}).
-define('TLS_v1.2', {3,3}).
-define('TLS_v1.1', {3,2}).
-define('TLS_v1', {3,1}).
%%--------------------------------------------------------------------
%% Properties --------------------------------------------------------
%%--------------------------------------------------------------------
prop_tls_hs_encode_decode() ->
?FORALL({Handshake, TLSVersion}, ?LET(Version, tls_version(), {tls_msg(Version), Version}),
try
[Type, _Length, Data] = tls_handshake:encode_handshake(Handshake, TLSVersion),
case tls_handshake:decode_handshake(TLSVersion, Type, Data) of
Handshake ->
true;
_ ->
false
end
catch
throw:#alert{} ->
true
end
).
%%--------------------------------------------------------------------
%% Message Generators -----------------------------------------------
%%--------------------------------------------------------------------
tls_msg(?'TLS_v1.3'= Version) ->
oneof([client_hello(Version),
server_hello(Version),
%%new_session_ticket()
#end_of_early_data{},
encrypted_extensions(),
certificate(),
certificate_request_1_3(),
certificate_verify_1_3(),
finished(),
key_update()
]);
tls_msg(Version) ->
oneof([
#hello_request{},
client_hello(Version),
server_hello(Version),
certificate(),
%%server_key_exchange()
certificate_request(Version),
#server_hello_done{},
%%certificate_verify()
%%client_key_exchange()
finished()
]).
%%
%% Shared messages
%%
client_hello(?'TLS_v1.3' = Version) ->
#client_hello{session_id = session_id(),
client_version = ?'TLS_v1.2',
cipher_suites = cipher_suites(Version),
compression_methods = compressions(Version),
random = client_random(Version),
extensions = client_hello_extensions(Version)
};
client_hello(Version) ->
#client_hello{session_id = session_id(),
client_version = Version,
cipher_suites = cipher_suites(Version),
compression_methods = compressions(Version),
random = client_random(Version),
extensions = client_hello_extensions(Version)
}.
server_hello(?'TLS_v1.3' = Version) ->
#server_hello{server_version = ?'TLS_v1.2',
session_id = session_id(),
random = server_random(Version),
cipher_suite = cipher_suite(Version),
compression_method = compression(Version),
extensions = server_hello_extensions(Version)
};
server_hello(Version) ->
#server_hello{server_version = Version,
session_id = session_id(),
random = server_random(Version),
cipher_suite = cipher_suite(Version),
compression_method = compression(Version),
extensions = server_hello_extensions(Version)
}.
certificate() ->
#certificate{
asn1_certificates = certificate_chain()
}.
certificate_1_3() ->
?LET(Certs, certificate_chain(),
#certificate_1_3{
certificate_request_context = certificate_request_context(),
certificate_list = certificate_entries(Certs, [])
}).
certificate_verify_1_3() ->
?LET(Certs, certificate_chain(),
#certificate_verify_1_3{
algorithm = sig_scheme(),
signature = signature()
}).
finished() ->
?LET(Size, digest_size(),
#finished{verify_data = crypto:strong_rand_bytes(Size)}).
%%
%% TLS 1.0-1.2 messages
%%
%%
%% TLS 1.3 messages
%%
encrypted_extensions() ->
?LET(Exts, extensions(?'TLS_v1.3', encrypted_extensions),
#encrypted_extensions{extensions = Exts}).
key_update() ->
#key_update{request_update = request_update()}.
%%--------------------------------------------------------------------
%% Message Data Generators -------------------------------------------
%%--------------------------------------------------------------------
tls_version() ->
oneof([?'TLS_v1.3', ?'TLS_v1.2', ?'TLS_v1.1', ?'TLS_v1']).
cipher_suite(Version) ->
oneof(cipher_suites(Version)).
cipher_suites(Version) ->
ssl_cipher:suites(Version).
session_id() ->
crypto:strong_rand_bytes(?NUM_OF_SESSION_ID_BYTES).
compression(Version) ->
oneof(compressions(Version)).
compressions(_) ->
ssl_record:compressions().
client_random(_) ->
crypto:strong_rand_bytes(32).
server_random(_) ->
crypto:strong_rand_bytes(32).
client_hello_extensions(Version) ->
?LET(Exts, extensions(Version, client_hello),
maps:merge(ssl_handshake:empty_extensions(Version, client_hello),
Exts)).
server_hello_extensions(Version) ->
?LET(Exts, extensions(Version, server_hello),
maps:merge(ssl_handshake:empty_extensions(Version, server_hello),
Exts)).
key_share_client_hello() ->
oneof([undefined]).
%%oneof([#key_share_client_hello{}, undefined]).
key_share_server_hello() ->
oneof([undefined]).
%%oneof([#key_share_server_hello{}, undefined]).
pre_shared_keyextension() ->
oneof([undefined]).
%%oneof([#pre_shared_keyextension{},undefined]).
%% +--------------------------------------------------+-------------+
%% | Extension | TLS 1.3 |
%% +--------------------------------------------------+-------------+
| server_name [ RFC6066 ] | CH , EE |
%% | | |
%% | max_fragment_length [RFC6066] | CH, EE |
%% | | |
| status_request [ ] | CH , CR , CT |
%% | | |
%% | supported_groups [RFC7919] | CH, EE |
%% | | |
| signature_algorithms ( RFC 8446 ) | CH , CR |
%% | | |
%% | use_srtp [RFC5764] | CH, EE |
%% | | |
%% | heartbeat [RFC6520] | CH, EE |
%% | | |
%% | application_layer_protocol_negotiation [RFC7301] | CH, EE |
%% | | |
| signed_certificate_timestamp [ RFC6962 ] | CH , CR , CT |
%% | | |
%% | client_certificate_type [RFC7250] | CH, EE |
%% | | |
%% | server_certificate_type [RFC7250] | CH, EE |
%% | | |
%% | padding [RFC7685] | CH |
%% | | |
| key_share ( RFC 8446 ) | CH , SH , HRR |
%% | | |
%% | pre_shared_key (RFC 8446) | CH, SH |
%% | | |
%% | psk_key_exchange_modes (RFC 8446) | CH |
%% | | |
| early_data ( RFC 8446 ) | CH , EE , NST |
%% | | |
| cookie ( RFC 8446 ) | CH , HRR |
%% | | |
| supported_versions ( RFC 8446 ) | CH , SH , HRR |
%% | | |
| certificate_authorities ( RFC 8446 ) | CH , CR |
%% | | |
| oid_filters ( RFC 8446 ) | CR |
%% | | |
%% | post_handshake_auth (RFC 8446) | CH |
%% | | |
| signature_algorithms_cert ( RFC 8446 ) | CH , CR |
%% +--------------------------------------------------+-------------+
extensions(?'TLS_v1.3' = Version, MsgType = client_hello) ->
?LET({
ServerName,
%% MaxFragmentLength,
StatusRequest ,
SupportedGroups,
SignatureAlgorithms,
UseSrtp,
%% Heartbeat,
ALPN,
%% SignedCertTimestamp,
%% ClientCertiticateType,
%% ServerCertificateType,
%% Padding,
KeyShare,
PreSharedKey,
PSKKeyExchangeModes,
EarlyData ,
%% Cookie,
SupportedVersions,
CertAuthorities,
%% PostHandshakeAuth,
SignatureAlgorithmsCert
},
{
oneof([server_name(), undefined]),
%% oneof([max_fragment_length(), undefined]),
%% oneof([status_request(), undefined]),
oneof([supported_groups(Version), undefined]),
oneof([signature_algs(Version), undefined]),
oneof([use_srtp(), undefined]),
%% oneof([heartbeat(), undefined]),
oneof([alpn(), undefined]),
%% oneof([signed_cert_timestamp(), undefined]),
%% oneof([client_cert_type(), undefined]),
%% oneof([server_cert_type(), undefined]),
%% oneof([padding(), undefined]),
oneof([key_share(MsgType), undefined]),
oneof([pre_shared_key(MsgType), undefined]),
oneof([psk_key_exchange_modes(), undefined]),
%% oneof([early_data(), undefined]),
( ) , undefined ] ) ,
oneof([client_hello_versions(Version)]),
oneof([cert_auths(), undefined]),
oneof([post_handshake_auth ( ) , undefined ] ) ,
oneof([signature_algs_cert(), undefined])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
sni => ServerName,
max_fragment_length = > MaxFragmentLength ,
status_request = > StatusRequest ,
elliptic_curves => SupportedGroups,
signature_algs => SignatureAlgorithms,
use_srtp => UseSrtp,
%% heartbeat => Heartbeat,
alpn => ALPN,
%% signed_cert_timestamp => SignedCertTimestamp,
client_cert_type = > ClientCertificateType ,
%% server_cert_type => ServerCertificateType,
%% padding => Padding,
key_share => KeyShare,
pre_shared_key => PreSharedKey,
psk_key_exchange_modes => PSKKeyExchangeModes,
%% early_data => EarlyData,
%% cookie => Cookie,
client_hello_versions => SupportedVersions,
certificate_authorities => CertAuthorities,
%% post_handshake_auth => PostHandshakeAuth,
signature_algs_cert => SignatureAlgorithmsCert
}));
extensions(Version, client_hello) ->
?LET({
SNI,
ECPoitF,
ECCurves,
ALPN,
NextP,
SRP
RenegotiationInfo
},
{
oneof([sni(), undefined]),
oneof([ec_point_formats(), undefined]),
oneof([elliptic_curves(Version), undefined]),
oneof([alpn(), undefined]),
oneof([next_protocol_negotiation(), undefined]),
oneof([srp(), undefined])
%% oneof([renegotiation_info(), undefined])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
sni => SNI,
ec_point_formats => ECPoitF,
elliptic_curves => ECCurves,
alpn => ALPN,
next_protocol_negotiation => NextP,
srp => SRP
renegotiation_info = > RenegotiationInfo
}));
extensions(?'TLS_v1.3' = Version, MsgType = server_hello) ->
?LET({
KeyShare,
PreSharedKey,
SupportedVersions
},
{
oneof([key_share(MsgType), undefined]),
oneof([pre_shared_key(MsgType), undefined]),
oneof([server_hello_selected_version()])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
key_share => KeyShare,
pre_shared_key => PreSharedKey,
server_hello_selected_version => SupportedVersions
}));
extensions(Version, server_hello) ->
?LET({
ECPoitF,
ALPN,
NextP
RenegotiationInfo ,
},
{
oneof([ec_point_formats(), undefined]),
oneof([alpn(), undefined]),
oneof([next_protocol_negotiation(), undefined])
%% oneof([renegotiation_info(), undefined]),
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
ec_point_formats => ECPoitF,
alpn => ALPN,
next_protocol_negotiation => NextP
renegotiation_info = > RenegotiationInfo
}));
extensions(?'TLS_v1.3' = Version, encrypted_extensions) ->
?LET({
ServerName,
%% MaxFragmentLength,
SupportedGroups,
UseSrtp ,
%% Heartbeat,
ALPN
%% ClientCertiticateType,
%% ServerCertificateType,
EarlyData
},
{
oneof([server_name(), undefined]),
%% oneof([max_fragment_length(), undefined]),
oneof([supported_groups(Version), undefined]),
%% oneof([use_srtp(), undefined]),
%% oneof([heartbeat(), undefined]),
oneof([alpn(), undefined])
%% oneof([client_cert_type(), undefined]),
%% oneof([server_cert_type(), undefined]),
%% oneof([early_data(), undefined])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
sni => ServerName,
max_fragment_length = > MaxFragmentLength ,
elliptic_curves => SupportedGroups,
use_srtp = > UseSrtp ,
%% heartbeat => Heartbeat,
alpn => ALPN
client_cert_type = > ClientCertificateType ,
%% server_cert_type => ServerCertificateType,
%% early_data => EarlyData
})).
server_name() ->
?LET(ServerName, sni(),
ServerName).
%% sni().
signature_algs_cert() ->
?LET(List, sig_scheme_list(),
#signature_algorithms_cert{signature_scheme_list = List}).
signature_algorithms() ->
?LET(List, sig_scheme_list(),
#signature_algorithms{signature_scheme_list = List}).
sig_scheme_list() ->
oneof([[rsa_pkcs1_sha256],
[rsa_pkcs1_sha256, ecdsa_sha1],
[rsa_pkcs1_sha256,
rsa_pkcs1_sha384,
rsa_pkcs1_sha512,
ecdsa_secp256r1_sha256,
ecdsa_secp384r1_sha384,
ecdsa_secp521r1_sha512,
rsa_pss_rsae_sha256,
rsa_pss_rsae_sha384,
rsa_pss_rsae_sha512,
rsa_pss_pss_sha256,
rsa_pss_pss_sha384,
rsa_pss_pss_sha512,
rsa_pkcs1_sha1,
ecdsa_sha1]
]).
sig_scheme() ->
oneof([rsa_pkcs1_sha256,
rsa_pkcs1_sha384,
rsa_pkcs1_sha512,
ecdsa_secp256r1_sha256,
ecdsa_secp384r1_sha384,
ecdsa_secp521r1_sha512,
rsa_pss_rsae_sha256,
rsa_pss_rsae_sha384,
rsa_pss_rsae_sha512,
rsa_pss_pss_sha256,
rsa_pss_pss_sha384,
rsa_pss_pss_sha512,
rsa_pkcs1_sha1,
ecdsa_sha1]).
signature() ->
<<44,119,215,137,54,84,156,26,121,212,64,173,189,226,
191,46,76,89,204,2,78,79,163,228,90,21,89,179,4,198,
109,14,52,26,230,22,56,8,170,129,86,0,7,132,245,81,
181,131,62,70,79,167,112,85,14,171,175,162,110,29,
212,198,45,188,83,176,251,197,224,104,95,74,89,59,
26,60,63,79,238,196,137,65,23,199,127,145,176,184,
216,3,48,116,172,106,97,83,227,172,246,137,91,79,
173,119,169,60,67,1,177,117,9,93,38,86,232,253,73,
140,17,147,130,110,136,245,73,10,91,70,105,53,225,
158,107,60,190,30,14,26,92,147,221,60,117,104,53,70,
142,204,7,131,11,183,192,120,246,243,68,99,147,183,
49,149,48,188,8,218,17,150,220,121,2,99,194,140,35,
13,249,201,37,216,68,45,87,58,18,10,106,11,132,241,
71,170,225,216,197,212,29,107,36,80,189,184,202,56,
86,213,45,70,34,74,71,48,137,79,212,194,172,151,57,
57,30,126,24,157,198,101,220,84,162,89,105,185,245,
76,105,212,176,25,6,148,49,194,106,253,241,212,200,
37,154,227,53,49,216,72,82,163>>.
client_hello_versions(?'TLS_v1.3') ->
?LET(SupportedVersions,
oneof([[{3,4}],
%% This list breaks the property but can be used for negative tests
[ { 3,3},{3,4 } ] ,
[{3,4},{3,3}],
[{3,4},{3,3},{3,2},{3,1},{3,0}]
]),
#client_hello_versions{versions = SupportedVersions});
client_hello_versions(_) ->
?LET(SupportedVersions,
oneof([[{3,3}],
[{3,3},{3,2}],
[{3,3},{3,2},{3,1},{3,0}]
]),
#client_hello_versions{versions = SupportedVersions}).
server_hello_selected_version() ->
#server_hello_selected_version{selected_version = {3,4}}.
request_update() ->
oneof([update_not_requested, update_requested]).
certificate_chain()->
Conf = cert_conf(),
?LET(Chain,
choose_certificate_chain(Conf),
Chain).
choose_certificate_chain(#{server_config := ServerConf,
client_config := ClientConf}) ->
oneof([certificate_chain(ServerConf), certificate_chain(ClientConf)]).
certificate_request_context() ->
oneof([<<>>,
<<1>>,
<<"foobar">>
]).
certificate_entries([], Acc) ->
lists:reverse(Acc);
certificate_entries([Cert | Rest], Acc) ->
certificate_entries(Rest, [certificate_entry(Cert) | Acc]).
certificate_entry(Cert) ->
#certificate_entry{data = Cert,
extensions = certificate_entry_extensions()
}.
certificate_entry_extensions() ->
#{}.
certificate_chain(Conf) ->
CAs = proplists:get_value(cacerts, Conf),
Cert = proplists:get_value(cert, Conf),
%% Middle argument are of correct type but will not be used
{ok, _, Chain} = ssl_certificate:certificate_chain(Cert, ets:new(foo, []), make_ref(), CAs, encoded),
Chain.
cert_conf()->
Hostname = net_adm:localhost(),
{ok, #hostent{h_addr_list = [_IP |_]}} = inet:gethostbyname(net_adm:localhost()),
public_key:pkix_test_data(#{server_chain =>
#{root => [{key, ssl_test_lib:hardcode_rsa_key(1)}],
intermediates => [[{key, ssl_test_lib:hardcode_rsa_key(2)}]],
peer => [{extensions, [#'Extension'{extnID =
?'id-ce-subjectAltName',
extnValue = [{dNSName, Hostname}],
critical = false}]},
{key, ssl_test_lib:hardcode_rsa_key(3)}
]},
client_chain =>
#{root => [{key, ssl_test_lib:hardcode_rsa_key(4)}],
intermediates => [[{key, ssl_test_lib:hardcode_rsa_key(5)}]],
peer => [{key, ssl_test_lib:hardcode_rsa_key(6)}]}}).
cert_auths() ->
certificate_authorities(?'TLS_v1.3').
certificate_request_1_3() ->
#certificate_request_1_3{certificate_request_context = <<>>,
extensions = #{certificate_authorities => certificate_authorities(?'TLS_v1.3')}
}.
certificate_request(Version) ->
#certificate_request{certificate_types = certificate_types(Version),
hashsign_algorithms = hashsign_algorithms(Version),
certificate_authorities = certificate_authorities(Version)}.
certificate_types(_) ->
iolist_to_binary([<<?BYTE(?ECDSA_SIGN)>>, <<?BYTE(?RSA_SIGN)>>, <<?BYTE(?DSS_SIGN)>>]).
signature_algs({3,4}) ->
?LET(Algs, signature_algorithms(),
Algs);
signature_algs({3,3} = Version) ->
#hash_sign_algos{hash_sign_algos = hash_alg_list(Version)};
signature_algs(Version) when Version < {3,3} ->
undefined.
hashsign_algorithms({_, N} = Version) when N >= 3 ->
#hash_sign_algos{hash_sign_algos = hash_alg_list(Version)};
hashsign_algorithms(_) ->
undefined.
hash_alg_list(Version) ->
?LET(NumOf, choose(1,15),
?LET(List, [hash_alg(Version) || _ <- lists:seq(1,NumOf)],
lists:usort(List)
)).
hash_alg(Version) ->
?LET(Alg, sign_algorithm(Version),
{hash_algorithm(Version, Alg), Alg}
).
hash_algorithm(?'TLS_v1.3', _) ->
oneof([sha, sha224, sha256, sha384, sha512]);
hash_algorithm(?'TLS_v1.2', rsa) ->
oneof([sha, sha224, sha256, sha384, sha512]);
hash_algorithm(_, rsa) ->
oneof([md5, sha, sha224, sha256, sha384, sha512]);
hash_algorithm(_, ecdsa) ->
oneof([sha, sha224, sha256, sha384, sha512]);
hash_algorithm(_, dsa) ->
sha.
sign_algorithm(?'TLS_v1.3') ->
oneof([rsa, ecdsa]);
sign_algorithm(_) ->
oneof([rsa, dsa, ecdsa]).
use_srtp() ->
FullProfiles = [<<0,1>>, <<0,2>>, <<0,5>>],
NullProfiles = [<<0,5>>],
?LET(PP, oneof([FullProfiles, NullProfiles]), #use_srtp{protection_profiles = PP, mki = <<>>}).
certificate_authorities(?'TLS_v1.3') ->
Auths = certificate_authorities(?'TLS_v1.2'),
#certificate_authorities{authorities = Auths};
certificate_authorities(_) ->
#{server_config := ServerConf} = cert_conf(),
Certs = proplists:get_value(cacerts, ServerConf),
Auths = fun(#'OTPCertificate'{tbsCertificate = TBSCert}) ->
public_key:pkix_normalize_name(TBSCert#'OTPTBSCertificate'.subject)
end,
[Auths(public_key:pkix_decode_cert(Cert, otp)) || Cert <- Certs].
digest_size()->
oneof([160,224,256,384,512]).
key_share_entry() ->
undefined.
%%#key_share_entry{}.
server_hello_selected_version(Version) ->
#server_hello_selected_version{selected_version = Version}.
sni() ->
#sni{hostname = net_adm:localhost()}.
ec_point_formats() ->
#ec_point_formats{ec_point_format_list = ec_point_format_list()}.
ec_point_format_list() ->
[?ECPOINT_UNCOMPRESSED].
elliptic_curves({_, Minor}) when Minor < 4 ->
Curves = tls_v1:ecc_curves(Minor),
#elliptic_curves{elliptic_curve_list = Curves}.
%% RFC 8446 (TLS 1.3) renamed the "elliptic_curve" extension.
supported_groups({_, Minor}) when Minor >= 4 ->
SupportedGroups = tls_v1:groups(Minor),
#supported_groups{supported_groups = SupportedGroups}.
alpn() ->
?LET(ExtD, alpn_protocols(), #alpn{extension_data = ExtD}).
alpn_protocols() ->
oneof([<<"spdy/2">>, <<"spdy/3">>, <<"http/2">>, <<"http/1.0">>, <<"http/1.1">>]).
next_protocol_negotiation() ->
%% Predecessor to APLN
?LET(ExtD, alpn_protocols(), #next_protocol_negotiation{extension_data = ExtD}).
srp() ->
?LET(Name, gen_name(), #srp{username = list_to_binary(Name)}).
renegotiation_info() ->
#renegotiation_info{renegotiated_connection = 0}.
gen_name() ->
?LET(Size, choose(1,10), gen_string(Size)).
gen_char() ->
choose($a,$z).
gen_string(N) ->
gen_string(N, []).
gen_string(0, Acc) ->
Acc;
gen_string(N, Acc) ->
?LET(Char, gen_char(), gen_string(N-1, [Char | Acc])).
key_share(client_hello) ->
?LET(ClientShares, key_share_entry_list(),
#key_share_client_hello{
client_shares = ClientShares});
key_share(server_hello) ->
?LET([ServerShare], key_share_entry_list(1),
#key_share_server_hello{
server_share = ServerShare}).
key_share_entry_list() ->
Max = length(ssl:groups()),
?LET(Size, choose(1,Max), key_share_entry_list(Size)).
%%
key_share_entry_list(N) ->
key_share_entry_list(N, ssl:groups(), []).
%%
key_share_entry_list(0, _Pool, Acc) ->
Acc;
key_share_entry_list(N, Pool, Acc) ->
R = rand:uniform(length(Pool)),
G = lists:nth(R, Pool),
P = generate_public_key(G),
KeyShareEntry =
#key_share_entry{
group = G,
key_exchange = P},
key_share_entry_list(N - 1, Pool -- [G], [KeyShareEntry|Acc]).
%% TODO: fix curve generation
generate_public_key(Group)
when Group =:= secp256r1 orelse
Group =:= secp384r1 orelse
Group =:= secp521r1 orelse
Group =:= x448 orelse
Group =:= x25519 ->
#'ECPrivateKey'{publicKey = PublicKey} =
public_key:generate_key({namedCurve, secp256r1}),
PublicKey;
generate_public_key(Group) ->
{PublicKey, _} =
public_key:generate_key(ssl_dh_groups:dh_params(Group)),
PublicKey.
groups() ->
Max = length(ssl:groups()),
?LET(Size, choose(1,Max), group_list(Size)).
group_list(N) ->
group_list(N, ssl:groups(), []).
%%
group_list(0, _Pool, Acc) ->
Acc;
group_list(N, Pool, Acc) ->
R = rand:uniform(length(Pool)),
G = lists:nth(R, Pool),
group_list(N - 1, Pool -- [G], [G|Acc]).
ke_modes() ->
oneof([[psk_ke],[psk_dhe_ke],[psk_ke,psk_dhe_ke]]).
psk_key_exchange_modes() ->
?LET(KEModes, ke_modes(),
#psk_key_exchange_modes{
ke_modes = KEModes}).
pre_shared_key(client_hello) ->
?LET(OfferedPsks, offered_psks(),
#pre_shared_key_client_hello{
offered_psks = OfferedPsks});
pre_shared_key(server_hello) ->
?LET(SelectedIdentity, selected_identity(),
#pre_shared_key_server_hello{
selected_identity = SelectedIdentity}).
selected_identity() ->
rand:uniform(32).
offered_psks() ->
?LET(Size, choose(1,5),
#offered_psks{
identities = psk_identities(Size),
binders = psk_binders(Size)}).
psk_identities(Size) ->
psk_identities(Size, []).
%%
psk_identities(0, Acc) ->
Acc;
psk_identities(N, Acc) ->
psk_identities(N - 1, [psk_identity()|Acc]).
psk_identity() ->
Len = 8 + rand:uniform(8),
Identity = crypto:strong_rand_bytes(Len),
<<?UINT32(Age)>> = crypto:strong_rand_bytes(4),
#psk_identity{
identity = Identity,
obfuscated_ticket_age = Age}.
psk_binders(Size) ->
psk_binders(Size, []).
%%
psk_binders(0, Acc) ->
Acc;
psk_binders(N, Acc) ->
psk_binders(N - 1, [psk_binder()|Acc]).
psk_binder() ->
Len = rand:uniform(224) + 31,
crypto:strong_rand_bytes(Len).
| null | https://raw.githubusercontent.com/erlang/otp/44c972d35910ed70d8efd797ae59bc6428794406/lib/ssl/test/property_test/ssl_eqc_handshake.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
--------------------------------------------------------------------
Properties --------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Message Generators -----------------------------------------------
--------------------------------------------------------------------
new_session_ticket()
server_key_exchange()
certificate_verify()
client_key_exchange()
Shared messages
TLS 1.0-1.2 messages
TLS 1.3 messages
--------------------------------------------------------------------
Message Data Generators -------------------------------------------
--------------------------------------------------------------------
oneof([#key_share_client_hello{}, undefined]).
oneof([#key_share_server_hello{}, undefined]).
oneof([#pre_shared_keyextension{},undefined]).
+--------------------------------------------------+-------------+
| Extension | TLS 1.3 |
+--------------------------------------------------+-------------+
| | |
| max_fragment_length [RFC6066] | CH, EE |
| | |
| | |
| supported_groups [RFC7919] | CH, EE |
| | |
| | |
| use_srtp [RFC5764] | CH, EE |
| | |
| heartbeat [RFC6520] | CH, EE |
| | |
| application_layer_protocol_negotiation [RFC7301] | CH, EE |
| | |
| | |
| client_certificate_type [RFC7250] | CH, EE |
| | |
| server_certificate_type [RFC7250] | CH, EE |
| | |
| padding [RFC7685] | CH |
| | |
| | |
| pre_shared_key (RFC 8446) | CH, SH |
| | |
| psk_key_exchange_modes (RFC 8446) | CH |
| | |
| | |
| | |
| | |
| | |
| | |
| post_handshake_auth (RFC 8446) | CH |
| | |
+--------------------------------------------------+-------------+
MaxFragmentLength,
Heartbeat,
SignedCertTimestamp,
ClientCertiticateType,
ServerCertificateType,
Padding,
Cookie,
PostHandshakeAuth,
oneof([max_fragment_length(), undefined]),
oneof([status_request(), undefined]),
oneof([heartbeat(), undefined]),
oneof([signed_cert_timestamp(), undefined]),
oneof([client_cert_type(), undefined]),
oneof([server_cert_type(), undefined]),
oneof([padding(), undefined]),
oneof([early_data(), undefined]),
heartbeat => Heartbeat,
signed_cert_timestamp => SignedCertTimestamp,
server_cert_type => ServerCertificateType,
padding => Padding,
early_data => EarlyData,
cookie => Cookie,
post_handshake_auth => PostHandshakeAuth,
oneof([renegotiation_info(), undefined])
oneof([renegotiation_info(), undefined]),
MaxFragmentLength,
Heartbeat,
ClientCertiticateType,
ServerCertificateType,
oneof([max_fragment_length(), undefined]),
oneof([use_srtp(), undefined]),
oneof([heartbeat(), undefined]),
oneof([client_cert_type(), undefined]),
oneof([server_cert_type(), undefined]),
oneof([early_data(), undefined])
heartbeat => Heartbeat,
server_cert_type => ServerCertificateType,
early_data => EarlyData
sni().
This list breaks the property but can be used for negative tests
Middle argument are of correct type but will not be used
#key_share_entry{}.
RFC 8446 (TLS 1.3) renamed the "elliptic_curve" extension.
Predecessor to APLN
TODO: fix curve generation
| Copyright Ericsson AB 2018 - 2022 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(ssl_eqc_handshake).
-compile(export_all).
-proptest(eqc).
-proptest([triq,proper]).
-ifndef(EQC).
-ifndef(PROPER).
-ifndef(TRIQ).
-define(EQC,true).
-endif.
-endif.
-endif.
-ifdef(EQC).
-include_lib("eqc/include/eqc.hrl").
-define(MOD_eqc,eqc).
-else.
-ifdef(PROPER).
-include_lib("proper/include/proper.hrl").
-define(MOD_eqc,proper).
-else.
-ifdef(TRIQ).
-define(MOD_eqc,triq).
-include_lib("triq/include/triq.hrl").
-endif.
-endif.
-endif.
-include_lib("kernel/include/inet.hrl").
-include_lib("ssl/src/tls_handshake_1_3.hrl").
-include_lib("ssl/src/tls_handshake.hrl").
-include_lib("ssl/src/ssl_handshake.hrl").
-include_lib("ssl/src/ssl_alert.hrl").
-include_lib("ssl/src/ssl_internal.hrl").
-define('TLS_v1.3', {3,4}).
-define('TLS_v1.2', {3,3}).
-define('TLS_v1.1', {3,2}).
-define('TLS_v1', {3,1}).
prop_tls_hs_encode_decode() ->
?FORALL({Handshake, TLSVersion}, ?LET(Version, tls_version(), {tls_msg(Version), Version}),
try
[Type, _Length, Data] = tls_handshake:encode_handshake(Handshake, TLSVersion),
case tls_handshake:decode_handshake(TLSVersion, Type, Data) of
Handshake ->
true;
_ ->
false
end
catch
throw:#alert{} ->
true
end
).
tls_msg(?'TLS_v1.3'= Version) ->
oneof([client_hello(Version),
server_hello(Version),
#end_of_early_data{},
encrypted_extensions(),
certificate(),
certificate_request_1_3(),
certificate_verify_1_3(),
finished(),
key_update()
]);
tls_msg(Version) ->
oneof([
#hello_request{},
client_hello(Version),
server_hello(Version),
certificate(),
certificate_request(Version),
#server_hello_done{},
finished()
]).
client_hello(?'TLS_v1.3' = Version) ->
#client_hello{session_id = session_id(),
client_version = ?'TLS_v1.2',
cipher_suites = cipher_suites(Version),
compression_methods = compressions(Version),
random = client_random(Version),
extensions = client_hello_extensions(Version)
};
client_hello(Version) ->
#client_hello{session_id = session_id(),
client_version = Version,
cipher_suites = cipher_suites(Version),
compression_methods = compressions(Version),
random = client_random(Version),
extensions = client_hello_extensions(Version)
}.
server_hello(?'TLS_v1.3' = Version) ->
#server_hello{server_version = ?'TLS_v1.2',
session_id = session_id(),
random = server_random(Version),
cipher_suite = cipher_suite(Version),
compression_method = compression(Version),
extensions = server_hello_extensions(Version)
};
server_hello(Version) ->
#server_hello{server_version = Version,
session_id = session_id(),
random = server_random(Version),
cipher_suite = cipher_suite(Version),
compression_method = compression(Version),
extensions = server_hello_extensions(Version)
}.
certificate() ->
#certificate{
asn1_certificates = certificate_chain()
}.
certificate_1_3() ->
?LET(Certs, certificate_chain(),
#certificate_1_3{
certificate_request_context = certificate_request_context(),
certificate_list = certificate_entries(Certs, [])
}).
certificate_verify_1_3() ->
?LET(Certs, certificate_chain(),
#certificate_verify_1_3{
algorithm = sig_scheme(),
signature = signature()
}).
finished() ->
?LET(Size, digest_size(),
#finished{verify_data = crypto:strong_rand_bytes(Size)}).
encrypted_extensions() ->
?LET(Exts, extensions(?'TLS_v1.3', encrypted_extensions),
#encrypted_extensions{extensions = Exts}).
key_update() ->
#key_update{request_update = request_update()}.
tls_version() ->
oneof([?'TLS_v1.3', ?'TLS_v1.2', ?'TLS_v1.1', ?'TLS_v1']).
cipher_suite(Version) ->
oneof(cipher_suites(Version)).
cipher_suites(Version) ->
ssl_cipher:suites(Version).
session_id() ->
crypto:strong_rand_bytes(?NUM_OF_SESSION_ID_BYTES).
compression(Version) ->
oneof(compressions(Version)).
compressions(_) ->
ssl_record:compressions().
client_random(_) ->
crypto:strong_rand_bytes(32).
server_random(_) ->
crypto:strong_rand_bytes(32).
client_hello_extensions(Version) ->
?LET(Exts, extensions(Version, client_hello),
maps:merge(ssl_handshake:empty_extensions(Version, client_hello),
Exts)).
server_hello_extensions(Version) ->
?LET(Exts, extensions(Version, server_hello),
maps:merge(ssl_handshake:empty_extensions(Version, server_hello),
Exts)).
key_share_client_hello() ->
oneof([undefined]).
key_share_server_hello() ->
oneof([undefined]).
pre_shared_keyextension() ->
oneof([undefined]).
| server_name [ RFC6066 ] | CH , EE |
| status_request [ ] | CH , CR , CT |
| signature_algorithms ( RFC 8446 ) | CH , CR |
| signed_certificate_timestamp [ RFC6962 ] | CH , CR , CT |
| key_share ( RFC 8446 ) | CH , SH , HRR |
| early_data ( RFC 8446 ) | CH , EE , NST |
| cookie ( RFC 8446 ) | CH , HRR |
| supported_versions ( RFC 8446 ) | CH , SH , HRR |
| certificate_authorities ( RFC 8446 ) | CH , CR |
| oid_filters ( RFC 8446 ) | CR |
| signature_algorithms_cert ( RFC 8446 ) | CH , CR |
extensions(?'TLS_v1.3' = Version, MsgType = client_hello) ->
?LET({
ServerName,
StatusRequest ,
SupportedGroups,
SignatureAlgorithms,
UseSrtp,
ALPN,
KeyShare,
PreSharedKey,
PSKKeyExchangeModes,
EarlyData ,
SupportedVersions,
CertAuthorities,
SignatureAlgorithmsCert
},
{
oneof([server_name(), undefined]),
oneof([supported_groups(Version), undefined]),
oneof([signature_algs(Version), undefined]),
oneof([use_srtp(), undefined]),
oneof([alpn(), undefined]),
oneof([key_share(MsgType), undefined]),
oneof([pre_shared_key(MsgType), undefined]),
oneof([psk_key_exchange_modes(), undefined]),
( ) , undefined ] ) ,
oneof([client_hello_versions(Version)]),
oneof([cert_auths(), undefined]),
oneof([post_handshake_auth ( ) , undefined ] ) ,
oneof([signature_algs_cert(), undefined])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
sni => ServerName,
max_fragment_length = > MaxFragmentLength ,
status_request = > StatusRequest ,
elliptic_curves => SupportedGroups,
signature_algs => SignatureAlgorithms,
use_srtp => UseSrtp,
alpn => ALPN,
client_cert_type = > ClientCertificateType ,
key_share => KeyShare,
pre_shared_key => PreSharedKey,
psk_key_exchange_modes => PSKKeyExchangeModes,
client_hello_versions => SupportedVersions,
certificate_authorities => CertAuthorities,
signature_algs_cert => SignatureAlgorithmsCert
}));
extensions(Version, client_hello) ->
?LET({
SNI,
ECPoitF,
ECCurves,
ALPN,
NextP,
SRP
RenegotiationInfo
},
{
oneof([sni(), undefined]),
oneof([ec_point_formats(), undefined]),
oneof([elliptic_curves(Version), undefined]),
oneof([alpn(), undefined]),
oneof([next_protocol_negotiation(), undefined]),
oneof([srp(), undefined])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
sni => SNI,
ec_point_formats => ECPoitF,
elliptic_curves => ECCurves,
alpn => ALPN,
next_protocol_negotiation => NextP,
srp => SRP
renegotiation_info = > RenegotiationInfo
}));
extensions(?'TLS_v1.3' = Version, MsgType = server_hello) ->
?LET({
KeyShare,
PreSharedKey,
SupportedVersions
},
{
oneof([key_share(MsgType), undefined]),
oneof([pre_shared_key(MsgType), undefined]),
oneof([server_hello_selected_version()])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
key_share => KeyShare,
pre_shared_key => PreSharedKey,
server_hello_selected_version => SupportedVersions
}));
extensions(Version, server_hello) ->
?LET({
ECPoitF,
ALPN,
NextP
RenegotiationInfo ,
},
{
oneof([ec_point_formats(), undefined]),
oneof([alpn(), undefined]),
oneof([next_protocol_negotiation(), undefined])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
ec_point_formats => ECPoitF,
alpn => ALPN,
next_protocol_negotiation => NextP
renegotiation_info = > RenegotiationInfo
}));
extensions(?'TLS_v1.3' = Version, encrypted_extensions) ->
?LET({
ServerName,
SupportedGroups,
UseSrtp ,
ALPN
EarlyData
},
{
oneof([server_name(), undefined]),
oneof([supported_groups(Version), undefined]),
oneof([alpn(), undefined])
},
maps:filter(fun(_, undefined) ->
false;
(_,_) ->
true
end,
#{
sni => ServerName,
max_fragment_length = > MaxFragmentLength ,
elliptic_curves => SupportedGroups,
use_srtp = > UseSrtp ,
alpn => ALPN
client_cert_type = > ClientCertificateType ,
})).
server_name() ->
?LET(ServerName, sni(),
ServerName).
signature_algs_cert() ->
?LET(List, sig_scheme_list(),
#signature_algorithms_cert{signature_scheme_list = List}).
signature_algorithms() ->
?LET(List, sig_scheme_list(),
#signature_algorithms{signature_scheme_list = List}).
sig_scheme_list() ->
oneof([[rsa_pkcs1_sha256],
[rsa_pkcs1_sha256, ecdsa_sha1],
[rsa_pkcs1_sha256,
rsa_pkcs1_sha384,
rsa_pkcs1_sha512,
ecdsa_secp256r1_sha256,
ecdsa_secp384r1_sha384,
ecdsa_secp521r1_sha512,
rsa_pss_rsae_sha256,
rsa_pss_rsae_sha384,
rsa_pss_rsae_sha512,
rsa_pss_pss_sha256,
rsa_pss_pss_sha384,
rsa_pss_pss_sha512,
rsa_pkcs1_sha1,
ecdsa_sha1]
]).
sig_scheme() ->
oneof([rsa_pkcs1_sha256,
rsa_pkcs1_sha384,
rsa_pkcs1_sha512,
ecdsa_secp256r1_sha256,
ecdsa_secp384r1_sha384,
ecdsa_secp521r1_sha512,
rsa_pss_rsae_sha256,
rsa_pss_rsae_sha384,
rsa_pss_rsae_sha512,
rsa_pss_pss_sha256,
rsa_pss_pss_sha384,
rsa_pss_pss_sha512,
rsa_pkcs1_sha1,
ecdsa_sha1]).
signature() ->
<<44,119,215,137,54,84,156,26,121,212,64,173,189,226,
191,46,76,89,204,2,78,79,163,228,90,21,89,179,4,198,
109,14,52,26,230,22,56,8,170,129,86,0,7,132,245,81,
181,131,62,70,79,167,112,85,14,171,175,162,110,29,
212,198,45,188,83,176,251,197,224,104,95,74,89,59,
26,60,63,79,238,196,137,65,23,199,127,145,176,184,
216,3,48,116,172,106,97,83,227,172,246,137,91,79,
173,119,169,60,67,1,177,117,9,93,38,86,232,253,73,
140,17,147,130,110,136,245,73,10,91,70,105,53,225,
158,107,60,190,30,14,26,92,147,221,60,117,104,53,70,
142,204,7,131,11,183,192,120,246,243,68,99,147,183,
49,149,48,188,8,218,17,150,220,121,2,99,194,140,35,
13,249,201,37,216,68,45,87,58,18,10,106,11,132,241,
71,170,225,216,197,212,29,107,36,80,189,184,202,56,
86,213,45,70,34,74,71,48,137,79,212,194,172,151,57,
57,30,126,24,157,198,101,220,84,162,89,105,185,245,
76,105,212,176,25,6,148,49,194,106,253,241,212,200,
37,154,227,53,49,216,72,82,163>>.
client_hello_versions(?'TLS_v1.3') ->
?LET(SupportedVersions,
oneof([[{3,4}],
[ { 3,3},{3,4 } ] ,
[{3,4},{3,3}],
[{3,4},{3,3},{3,2},{3,1},{3,0}]
]),
#client_hello_versions{versions = SupportedVersions});
client_hello_versions(_) ->
?LET(SupportedVersions,
oneof([[{3,3}],
[{3,3},{3,2}],
[{3,3},{3,2},{3,1},{3,0}]
]),
#client_hello_versions{versions = SupportedVersions}).
server_hello_selected_version() ->
#server_hello_selected_version{selected_version = {3,4}}.
request_update() ->
oneof([update_not_requested, update_requested]).
certificate_chain()->
Conf = cert_conf(),
?LET(Chain,
choose_certificate_chain(Conf),
Chain).
choose_certificate_chain(#{server_config := ServerConf,
client_config := ClientConf}) ->
oneof([certificate_chain(ServerConf), certificate_chain(ClientConf)]).
certificate_request_context() ->
oneof([<<>>,
<<1>>,
<<"foobar">>
]).
certificate_entries([], Acc) ->
lists:reverse(Acc);
certificate_entries([Cert | Rest], Acc) ->
certificate_entries(Rest, [certificate_entry(Cert) | Acc]).
certificate_entry(Cert) ->
#certificate_entry{data = Cert,
extensions = certificate_entry_extensions()
}.
certificate_entry_extensions() ->
#{}.
certificate_chain(Conf) ->
CAs = proplists:get_value(cacerts, Conf),
Cert = proplists:get_value(cert, Conf),
{ok, _, Chain} = ssl_certificate:certificate_chain(Cert, ets:new(foo, []), make_ref(), CAs, encoded),
Chain.
cert_conf()->
Hostname = net_adm:localhost(),
{ok, #hostent{h_addr_list = [_IP |_]}} = inet:gethostbyname(net_adm:localhost()),
public_key:pkix_test_data(#{server_chain =>
#{root => [{key, ssl_test_lib:hardcode_rsa_key(1)}],
intermediates => [[{key, ssl_test_lib:hardcode_rsa_key(2)}]],
peer => [{extensions, [#'Extension'{extnID =
?'id-ce-subjectAltName',
extnValue = [{dNSName, Hostname}],
critical = false}]},
{key, ssl_test_lib:hardcode_rsa_key(3)}
]},
client_chain =>
#{root => [{key, ssl_test_lib:hardcode_rsa_key(4)}],
intermediates => [[{key, ssl_test_lib:hardcode_rsa_key(5)}]],
peer => [{key, ssl_test_lib:hardcode_rsa_key(6)}]}}).
cert_auths() ->
certificate_authorities(?'TLS_v1.3').
certificate_request_1_3() ->
#certificate_request_1_3{certificate_request_context = <<>>,
extensions = #{certificate_authorities => certificate_authorities(?'TLS_v1.3')}
}.
certificate_request(Version) ->
#certificate_request{certificate_types = certificate_types(Version),
hashsign_algorithms = hashsign_algorithms(Version),
certificate_authorities = certificate_authorities(Version)}.
certificate_types(_) ->
iolist_to_binary([<<?BYTE(?ECDSA_SIGN)>>, <<?BYTE(?RSA_SIGN)>>, <<?BYTE(?DSS_SIGN)>>]).
signature_algs({3,4}) ->
?LET(Algs, signature_algorithms(),
Algs);
signature_algs({3,3} = Version) ->
#hash_sign_algos{hash_sign_algos = hash_alg_list(Version)};
signature_algs(Version) when Version < {3,3} ->
undefined.
hashsign_algorithms({_, N} = Version) when N >= 3 ->
#hash_sign_algos{hash_sign_algos = hash_alg_list(Version)};
hashsign_algorithms(_) ->
undefined.
hash_alg_list(Version) ->
?LET(NumOf, choose(1,15),
?LET(List, [hash_alg(Version) || _ <- lists:seq(1,NumOf)],
lists:usort(List)
)).
hash_alg(Version) ->
?LET(Alg, sign_algorithm(Version),
{hash_algorithm(Version, Alg), Alg}
).
hash_algorithm(?'TLS_v1.3', _) ->
oneof([sha, sha224, sha256, sha384, sha512]);
hash_algorithm(?'TLS_v1.2', rsa) ->
oneof([sha, sha224, sha256, sha384, sha512]);
hash_algorithm(_, rsa) ->
oneof([md5, sha, sha224, sha256, sha384, sha512]);
hash_algorithm(_, ecdsa) ->
oneof([sha, sha224, sha256, sha384, sha512]);
hash_algorithm(_, dsa) ->
sha.
sign_algorithm(?'TLS_v1.3') ->
oneof([rsa, ecdsa]);
sign_algorithm(_) ->
oneof([rsa, dsa, ecdsa]).
use_srtp() ->
FullProfiles = [<<0,1>>, <<0,2>>, <<0,5>>],
NullProfiles = [<<0,5>>],
?LET(PP, oneof([FullProfiles, NullProfiles]), #use_srtp{protection_profiles = PP, mki = <<>>}).
certificate_authorities(?'TLS_v1.3') ->
Auths = certificate_authorities(?'TLS_v1.2'),
#certificate_authorities{authorities = Auths};
certificate_authorities(_) ->
#{server_config := ServerConf} = cert_conf(),
Certs = proplists:get_value(cacerts, ServerConf),
Auths = fun(#'OTPCertificate'{tbsCertificate = TBSCert}) ->
public_key:pkix_normalize_name(TBSCert#'OTPTBSCertificate'.subject)
end,
[Auths(public_key:pkix_decode_cert(Cert, otp)) || Cert <- Certs].
digest_size()->
oneof([160,224,256,384,512]).
key_share_entry() ->
undefined.
server_hello_selected_version(Version) ->
#server_hello_selected_version{selected_version = Version}.
sni() ->
#sni{hostname = net_adm:localhost()}.
ec_point_formats() ->
#ec_point_formats{ec_point_format_list = ec_point_format_list()}.
ec_point_format_list() ->
[?ECPOINT_UNCOMPRESSED].
elliptic_curves({_, Minor}) when Minor < 4 ->
Curves = tls_v1:ecc_curves(Minor),
#elliptic_curves{elliptic_curve_list = Curves}.
supported_groups({_, Minor}) when Minor >= 4 ->
SupportedGroups = tls_v1:groups(Minor),
#supported_groups{supported_groups = SupportedGroups}.
alpn() ->
?LET(ExtD, alpn_protocols(), #alpn{extension_data = ExtD}).
alpn_protocols() ->
oneof([<<"spdy/2">>, <<"spdy/3">>, <<"http/2">>, <<"http/1.0">>, <<"http/1.1">>]).
next_protocol_negotiation() ->
?LET(ExtD, alpn_protocols(), #next_protocol_negotiation{extension_data = ExtD}).
srp() ->
?LET(Name, gen_name(), #srp{username = list_to_binary(Name)}).
renegotiation_info() ->
#renegotiation_info{renegotiated_connection = 0}.
gen_name() ->
?LET(Size, choose(1,10), gen_string(Size)).
gen_char() ->
choose($a,$z).
gen_string(N) ->
gen_string(N, []).
gen_string(0, Acc) ->
Acc;
gen_string(N, Acc) ->
?LET(Char, gen_char(), gen_string(N-1, [Char | Acc])).
key_share(client_hello) ->
?LET(ClientShares, key_share_entry_list(),
#key_share_client_hello{
client_shares = ClientShares});
key_share(server_hello) ->
?LET([ServerShare], key_share_entry_list(1),
#key_share_server_hello{
server_share = ServerShare}).
key_share_entry_list() ->
Max = length(ssl:groups()),
?LET(Size, choose(1,Max), key_share_entry_list(Size)).
key_share_entry_list(N) ->
key_share_entry_list(N, ssl:groups(), []).
key_share_entry_list(0, _Pool, Acc) ->
Acc;
key_share_entry_list(N, Pool, Acc) ->
R = rand:uniform(length(Pool)),
G = lists:nth(R, Pool),
P = generate_public_key(G),
KeyShareEntry =
#key_share_entry{
group = G,
key_exchange = P},
key_share_entry_list(N - 1, Pool -- [G], [KeyShareEntry|Acc]).
generate_public_key(Group)
when Group =:= secp256r1 orelse
Group =:= secp384r1 orelse
Group =:= secp521r1 orelse
Group =:= x448 orelse
Group =:= x25519 ->
#'ECPrivateKey'{publicKey = PublicKey} =
public_key:generate_key({namedCurve, secp256r1}),
PublicKey;
generate_public_key(Group) ->
{PublicKey, _} =
public_key:generate_key(ssl_dh_groups:dh_params(Group)),
PublicKey.
groups() ->
Max = length(ssl:groups()),
?LET(Size, choose(1,Max), group_list(Size)).
group_list(N) ->
group_list(N, ssl:groups(), []).
group_list(0, _Pool, Acc) ->
Acc;
group_list(N, Pool, Acc) ->
R = rand:uniform(length(Pool)),
G = lists:nth(R, Pool),
group_list(N - 1, Pool -- [G], [G|Acc]).
ke_modes() ->
oneof([[psk_ke],[psk_dhe_ke],[psk_ke,psk_dhe_ke]]).
psk_key_exchange_modes() ->
?LET(KEModes, ke_modes(),
#psk_key_exchange_modes{
ke_modes = KEModes}).
pre_shared_key(client_hello) ->
?LET(OfferedPsks, offered_psks(),
#pre_shared_key_client_hello{
offered_psks = OfferedPsks});
pre_shared_key(server_hello) ->
?LET(SelectedIdentity, selected_identity(),
#pre_shared_key_server_hello{
selected_identity = SelectedIdentity}).
selected_identity() ->
rand:uniform(32).
offered_psks() ->
?LET(Size, choose(1,5),
#offered_psks{
identities = psk_identities(Size),
binders = psk_binders(Size)}).
psk_identities(Size) ->
psk_identities(Size, []).
psk_identities(0, Acc) ->
Acc;
psk_identities(N, Acc) ->
psk_identities(N - 1, [psk_identity()|Acc]).
psk_identity() ->
Len = 8 + rand:uniform(8),
Identity = crypto:strong_rand_bytes(Len),
<<?UINT32(Age)>> = crypto:strong_rand_bytes(4),
#psk_identity{
identity = Identity,
obfuscated_ticket_age = Age}.
psk_binders(Size) ->
psk_binders(Size, []).
psk_binders(0, Acc) ->
Acc;
psk_binders(N, Acc) ->
psk_binders(N - 1, [psk_binder()|Acc]).
psk_binder() ->
Len = rand:uniform(224) + 31,
crypto:strong_rand_bytes(Len).
|
d01fa375e0a856389a44a99a7388a9e75bd3cf92bacd8aed64b9019a5e4f42a2 | ralph-schleicher/rs-colors | cielch.lisp | cielch.lisp --- CIE L*C*h color space .
Copyright ( C ) 2016
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; * Neither the name of the copyright holder nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
;; ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;; POSSIBILITY OF SUCH DAMAGE.
;;; Code:
(in-package :rs-colors)
(defvar *cielch-default-white-point* cie-1931-white-point-d50
"The default white point for colors in the CIE L*C*h color space.
Default value is the CIE 1931 D50 standard illuminant.")
(defclass cielch-color (color-object)
((L*
:initarg :L*
:initform 0
:type (real 0)
:documentation "Lightness, default zero.")
(C*
:initarg :C*
:initform 0
:type (real 0)
:documentation "Chroma, default zero.")
(h
:initarg :h
:initform 0
:type (real 0 (360))
:documentation "Hue, default zero.")
(white-point
:initarg :white-point
:initform *cielch-default-white-point*
:type color-object
:documentation "White point, default ‘*cielch-default-white-point*’."))
(:documentation "Color class for the CIE L*C*h color space.
Hue is measured in degree angle."))
(defmethod color-coordinates ((color cielch-color))
(with-slots (L* C* h) color
(values L* C* h)))
(defmethod white-point ((color cielch-color))
(slot-value color 'white-point))
(defun make-cielch-color (L* C* h &optional (white-point *cielch-default-white-point*))
"Create a new color in the CIE L*C*h color space."
(make-instance 'cielch-color :L* L* :C* C* :h (mod h 360) :white-point white-point))
(defun cielch-from-cielab (L* a* b*)
"Convert CIE L*a*b* color space coordinates
into CIE L*C*h color space coordinates."
(declare (type real L* a* b*))
;; Attempt to be exact, see also ‘cielab-from-cielch’ below.
(cond ((zerop b*)
(values L* (abs a*) (if (minusp a*) 180 0)))
((zerop a*)
(values L* (abs b*) (if (minusp b*) 270 90)))
(t
(let ((C*h (complex (float a* pi) (float b* pi))))
(values L* (abs C*h) (mod (degree-from-radian (phase C*h)) 360))))))
(defun cielab-from-cielch (L* C* h)
"Convert CIE L*C*h color space coordinates
into CIE L*a*b* color space coordinates."
(declare (type real L* C* h))
On IEEE 754 machines , and maybe others , values of sin(π ) and
cos(π/2 ) are usually non - zero .
(cond ((zerop C*)
(values L* 0 0))
((= h 0)
(values L* C* 0))
((= h 90)
(values L* 0 C*))
((= h 180)
(values L* (- C*) 0))
((= h 270)
(values L* 0 (- C*)))
(t
(let ((C*h (* C* (cis (radian-from-degree (float h pi))))))
(values L* (realpart C*h) (imagpart C*h))))))
(defgeneric cielch-color-coordinates (color)
(:documentation "Return the CIE L*C*h color space coordinates of the color.
Argument COLOR is a color object.")
(:method ((color cielch-color))
(color-coordinates color))
Otherwise , go via CIE L*a*b * .
(:method ((color color-object))
(multiple-value-bind (L* a* b*)
(cielab-color-coordinates color)
(cielch-from-cielab L* a* b*))))
(defmethod cielab-color-coordinates ((color cielch-color))
(multiple-value-bind (L* C* h)
(cielch-color-coordinates color)
(cielab-from-cielch L* C* h)))
(defmethod ciexyz-color-coordinates ((color cielch-color))
(multiple-value-bind (L* a* b*)
(cielab-color-coordinates color)
(ciexyz-from-cielab L* a* b* (white-point color))))
(defmethod update-instance-for-different-class :after ((old color-object) (new cielch-color) &key)
(with-slots (L* C* h white-point) new
(multiple-value-setq (L* C* h)
(cielch-color-coordinates old))
(setf white-point (or (white-point old) *cielch-default-white-point*))))
cielch.lisp ends here
| null | https://raw.githubusercontent.com/ralph-schleicher/rs-colors/0604867895fab0ea9b8a6bb0ac4a08d452c53c59/cielch.lisp | lisp | Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
OR BUSINESS INTERRUPTION ) HOWEVER
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.
Code:
Attempt to be exact, see also ‘cielab-from-cielch’ below. | cielch.lisp --- CIE L*C*h color space .
Copyright ( C ) 2016
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(in-package :rs-colors)
(defvar *cielch-default-white-point* cie-1931-white-point-d50
"The default white point for colors in the CIE L*C*h color space.
Default value is the CIE 1931 D50 standard illuminant.")
(defclass cielch-color (color-object)
((L*
:initarg :L*
:initform 0
:type (real 0)
:documentation "Lightness, default zero.")
(C*
:initarg :C*
:initform 0
:type (real 0)
:documentation "Chroma, default zero.")
(h
:initarg :h
:initform 0
:type (real 0 (360))
:documentation "Hue, default zero.")
(white-point
:initarg :white-point
:initform *cielch-default-white-point*
:type color-object
:documentation "White point, default ‘*cielch-default-white-point*’."))
(:documentation "Color class for the CIE L*C*h color space.
Hue is measured in degree angle."))
(defmethod color-coordinates ((color cielch-color))
(with-slots (L* C* h) color
(values L* C* h)))
(defmethod white-point ((color cielch-color))
(slot-value color 'white-point))
(defun make-cielch-color (L* C* h &optional (white-point *cielch-default-white-point*))
"Create a new color in the CIE L*C*h color space."
(make-instance 'cielch-color :L* L* :C* C* :h (mod h 360) :white-point white-point))
(defun cielch-from-cielab (L* a* b*)
"Convert CIE L*a*b* color space coordinates
into CIE L*C*h color space coordinates."
(declare (type real L* a* b*))
(cond ((zerop b*)
(values L* (abs a*) (if (minusp a*) 180 0)))
((zerop a*)
(values L* (abs b*) (if (minusp b*) 270 90)))
(t
(let ((C*h (complex (float a* pi) (float b* pi))))
(values L* (abs C*h) (mod (degree-from-radian (phase C*h)) 360))))))
(defun cielab-from-cielch (L* C* h)
"Convert CIE L*C*h color space coordinates
into CIE L*a*b* color space coordinates."
(declare (type real L* C* h))
On IEEE 754 machines , and maybe others , values of sin(π ) and
cos(π/2 ) are usually non - zero .
(cond ((zerop C*)
(values L* 0 0))
((= h 0)
(values L* C* 0))
((= h 90)
(values L* 0 C*))
((= h 180)
(values L* (- C*) 0))
((= h 270)
(values L* 0 (- C*)))
(t
(let ((C*h (* C* (cis (radian-from-degree (float h pi))))))
(values L* (realpart C*h) (imagpart C*h))))))
(defgeneric cielch-color-coordinates (color)
(:documentation "Return the CIE L*C*h color space coordinates of the color.
Argument COLOR is a color object.")
(:method ((color cielch-color))
(color-coordinates color))
Otherwise , go via CIE L*a*b * .
(:method ((color color-object))
(multiple-value-bind (L* a* b*)
(cielab-color-coordinates color)
(cielch-from-cielab L* a* b*))))
(defmethod cielab-color-coordinates ((color cielch-color))
(multiple-value-bind (L* C* h)
(cielch-color-coordinates color)
(cielab-from-cielch L* C* h)))
(defmethod ciexyz-color-coordinates ((color cielch-color))
(multiple-value-bind (L* a* b*)
(cielab-color-coordinates color)
(ciexyz-from-cielab L* a* b* (white-point color))))
(defmethod update-instance-for-different-class :after ((old color-object) (new cielch-color) &key)
(with-slots (L* C* h white-point) new
(multiple-value-setq (L* C* h)
(cielch-color-coordinates old))
(setf white-point (or (white-point old) *cielch-default-white-point*))))
cielch.lisp ends here
|
0e02471d6a68499beeaef11531847385baa9925e5a40a05164dff1703b297aaf | appleshan/cl-http | cl-http-70-202.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : USER ; Base : 10 ; Patch - File : T -*-
Patch file for CL - HTTP version 70.202
;;; Reason: Function HTTP::SET-LOGICAL-HOST-DIRECTORY: turn into generic function.
;;; Function (CLOS:METHOD HTTP::SET-LOGICAL-HOST-DIRECTORY (STRING STRING CL:PATHNAME)): smarten up.
;;; Function (CLOS:METHOD HTTP::SET-LOGICAL-HOST-DIRECTORY (STRING STRING STRING)): coerce string to pathname.
Written by , 8/08/05 20:33:31
while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod
with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 ,
Compare Merge 404.0 , VC Documentation 401.0 ,
Logical Pathnames Translation Files NEWEST , Metering 444.0 ,
Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 ,
Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 ,
CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 ,
Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 ,
Genera 8 5 Metering Patches 1.0 , 8 5 ,
Genera 8 5 Jericho Patches 1.0 , 8 5 ,
Genera 8 5 , 8 5 Statice Runtime Patches 1.0 ,
Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 ,
Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 ,
Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 ,
Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 ,
Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 ,
Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 ,
Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 ,
Genera 8 5 Concordia Patches 1.2 , 8 5 ,
Genera 8 5 C Patches 1.0 , 8 5 ,
Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 ,
MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 ,
Genera Extensions 16.0 , Essential Image Substrate 433.0 ,
Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 ,
Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 ,
Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 ,
Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 ,
Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 ,
Concordia Documentation 432.0 , , ,
Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , ,
438.0 , , Lalr 1 434.0 ,
Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 ,
Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 ,
Syntax Editor Runtime 434.0 , C Library Headers 434 ,
Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 ,
C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 ,
Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , ,
Pascal 433.0 , , Pascal Package 434.0 , ,
HTTP Server 70.201 , Showable Procedures 36.3 , Binary Tree 34.0 ,
Experimental W3 Presentation System 8.1 , CL - HTTP Server Interface 54.0 ,
HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 ,
W4 Constraint - Guide Web Walker 45.13 , HTTP Client 51.9 , Ivory Revision 5 ,
VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) ,
1728x985 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) ,
Machine serial number -2142637960 ,
;;; Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10),
;;; Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7),
Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) ,
Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) ,
Background dns refreshing ( from > background - dns - refreshing ) .
(SCT:FILES-PATCHED-IN-THIS-PATCH-FILE
"HTTP:SERVER;UTILS.LISP.553")
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(eval-when (load eval compile)
(unintern 'set-logical-host-directory :http))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(define-generic set-logical-host-directory (logical-host directory physical-pathname)
(:documentation "Sets the directory, DIRECTORY, for the logical host, LOGICAL-HOST, to be PHYSICAL-PATHNAME."))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(defmethod set-logical-host-directory ((logical-host string) (directory string) (physical-pathname pathname))
(flet ((directory-match-p (key entry key-length)
(destructuring-bind (dir path) entry
(declare (ignore path))
(and (>= (length dir) key-length)
(string-equal key dir :end2 key-length))))
(make-dir-spec (directory length)
(cond ((not (char-equal #\; (aref directory (1- length)))) directory)
((char-equal #\* (aref directory (- length 2)))
(concatenate 'string directory #+Genera "*.*.*" #-Genera "*.*"))
(t (concatenate 'string directory #+Genera "**;*.*.*" #-Genera "**;*.*")))))
(declare (inline directory-match-p make-dir-spec))
(loop with directory-length fixnum = (length directory)
with http-translations = (logical-pathname-translations logical-host)
for entry in http-translations
when (directory-match-p directory entry directory-length)
do (progn (setf (second entry) (translated-pathname physical-pathname))
(return (setf (logical-pathname-translations logical-host) http-translations)))
finally (return (setf (logical-pathname-translations logical-host) (push (list (make-dir-spec directory directory-length)
(translated-pathname physical-pathname))
(logical-pathname-translations logical-host)))))))
;========================
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(defmethod set-logical-host-directory ((logical-host string) (directory string) (physical-pathname string))
(set-logical-host-directory logical-host directory (pathname physical-pathname)))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/lispm/server/patch/cl-http-70/cl-http-70-202.lisp | lisp | Syntax : Common - Lisp ; Package : USER ; Base : 10 ; Patch - File : T -*-
Reason: Function HTTP::SET-LOGICAL-HOST-DIRECTORY: turn into generic function.
Function (CLOS:METHOD HTTP::SET-LOGICAL-HOST-DIRECTORY (STRING STRING CL:PATHNAME)): smarten up.
Function (CLOS:METHOD HTTP::SET-LOGICAL-HOST-DIRECTORY (STRING STRING STRING)): coerce string to pathname.
Patch TCP hang on close when client drops connection. (from HTTP:LISPM;SERVER;TCP-PATCH-HANG-ON-CLOSE.LISP.10),
Prevent reset of input buffer on tcp reset by HTTP servers. (from HTTP:LISPM;W4;RECEIVE-TCP-SEGMENT-PATCH.LISP.7),
========================
========================
========================
(aref directory (1- length)))) directory)
======================== | Patch file for CL - HTTP version 70.202
Written by , 8/08/05 20:33:31
while running on FUJI - VLM from FUJI:/usr / lib / symbolics / Plus - CL - HTTP - A - CSAIL-8 - 5.vlod
with Open Genera 2.0 , Genera 8.5 , Lock Simple 437.0 , Version Control 405.0 ,
Compare Merge 404.0 , VC Documentation 401.0 ,
Logical Pathnames Translation Files NEWEST , Metering 444.0 ,
Metering Substrate 444.1 , Conversion Tools 436.0 , Hacks 440.0 , CLIM 72.0 ,
Genera CLIM 72.0 , CLX CLIM 72.0 , PostScript CLIM 72.0 , CLIM Demo 72.0 ,
CLIM Documentation 72.0 , Experimental Genera 8 5 Patches 1.0 ,
Genera 8 5 System Patches 1.40 , 8 5 Support Patches 1.0 ,
Genera 8 5 Metering Patches 1.0 , 8 5 ,
Genera 8 5 Jericho Patches 1.0 , 8 5 ,
Genera 8 5 , 8 5 Statice Runtime Patches 1.0 ,
Genera 8 5 Statice Patches 1.0 , Genera 8 5 Statice Server Patches 1.0 ,
Genera 8 5 Statice Documentation Patches 1.0 , 8 5 Clim Patches 1.3 ,
Genera 8 5 Patches 1.0 , Genera 8 5 Postscript Clim Patches 1.0 ,
Genera 8 5 Clx Clim Patches 1.0 , 8 5 Clim Doc Patches 1.0 ,
Genera 8 5 Clim Demo Patches 1.0 , 8 5 Color Patches 1.1 ,
Genera 8 5 Images Patches 1.0 , 8 5 Color Demo Patches 1.0 ,
Genera 8 5 Image Substrate Patches 1.0 , 8 5 Lock Simple Patches 1.0 ,
Genera 8 5 Concordia Patches 1.2 , 8 5 ,
Genera 8 5 C Patches 1.0 , 8 5 ,
Genera 8 5 Fortran Patches 1.0 , MAC 415.2 , MacIvory Support 447.0 ,
MacIvory Development 434.0 , Color 427.1 , Graphics Support 431.0 ,
Genera Extensions 16.0 , Essential Image Substrate 433.0 ,
Color System Documentation 10.0 , SGD Book Design 10.0 , Color Demo 422.0 ,
Images 431.2 , Image Substrate 440.4 , Statice Runtime 466.1 , Statice 466.0 ,
Statice Browser 466.0 , Statice Server 466.2 , Statice Documentation 426.0 ,
Symbolics Concordia 444.0 , Graphic Editor 440.0 , Graphic Editing 441.0 ,
Bitmap Editor 441.0 , Graphic Editing Documentation 432.0 , Postscript 436.0 ,
Concordia Documentation 432.0 , , ,
Joshua Metering 206.0 , Jericho 237.0 , C 440.0 , ,
438.0 , , Lalr 1 434.0 ,
Context Free Grammar 439.0 , Context Free Grammar Package 439.0 , C Runtime 438.0 ,
Compiler Tools Package 434.0 , Compiler Tools Runtime 434.0 , C Packages 436.0 ,
Syntax Editor Runtime 434.0 , C Library Headers 434 ,
Compiler Tools Development 435.0 , Compiler Tools Debugger 434.0 ,
C Documentation 426.0 , Syntax Editor Support 434.0 , LL-1 support system 438.0 ,
Fortran 434.0 , Fortran Runtime 434.0 , Fortran Package 434.0 , ,
Pascal 433.0 , , Pascal Package 434.0 , ,
HTTP Server 70.201 , Showable Procedures 36.3 , Binary Tree 34.0 ,
Experimental W3 Presentation System 8.1 , CL - HTTP Server Interface 54.0 ,
HTTP Proxy Server 6.34 , HTTP Client Substrate 4.23 ,
W4 Constraint - Guide Web Walker 45.13 , HTTP Client 51.9 , Ivory Revision 5 ,
VLM Debugger 329 , Genera program 8.18 , DEC OSF/1 V4.0 ( Rev. 110 ) ,
1728x985 24 - bit TRUE - COLOR X Screen FUJI:1.0 with 224 Genera fonts ( The Olivetti & Oracle Research Laboratory R3323 ) ,
Machine serial number -2142637960 ,
Get Xauthority pathname from user namespace object . ( from W:>jcma > fixes > xauthority - pathname.lisp.2 ) ,
Domain ad host patch ( from > domain - ad - host - patch.lisp.21 ) ,
Background dns refreshing ( from > background - dns - refreshing ) .
(SCT:FILES-PATCHED-IN-THIS-PATCH-FILE
"HTTP:SERVER;UTILS.LISP.553")
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(eval-when (load eval compile)
(unintern 'set-logical-host-directory :http))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(define-generic set-logical-host-directory (logical-host directory physical-pathname)
(:documentation "Sets the directory, DIRECTORY, for the logical host, LOGICAL-HOST, to be PHYSICAL-PATHNAME."))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(defmethod set-logical-host-directory ((logical-host string) (directory string) (physical-pathname pathname))
(flet ((directory-match-p (key entry key-length)
(destructuring-bind (dir path) entry
(declare (ignore path))
(and (>= (length dir) key-length)
(string-equal key dir :end2 key-length))))
(make-dir-spec (directory length)
((char-equal #\* (aref directory (- length 2)))
(concatenate 'string directory #+Genera "*.*.*" #-Genera "*.*"))
(t (concatenate 'string directory #+Genera "**;*.*.*" #-Genera "**;*.*")))))
(declare (inline directory-match-p make-dir-spec))
(loop with directory-length fixnum = (length directory)
with http-translations = (logical-pathname-translations logical-host)
for entry in http-translations
when (directory-match-p directory entry directory-length)
do (progn (setf (second entry) (translated-pathname physical-pathname))
(return (setf (logical-pathname-translations logical-host) http-translations)))
finally (return (setf (logical-pathname-translations logical-host) (push (list (make-dir-spec directory directory-length)
(translated-pathname physical-pathname))
(logical-pathname-translations logical-host)))))))
(SCT:BEGIN-PATCH-SECTION)
(SCT:PATCH-SECTION-SOURCE-FILE "HTTP:SERVER;UTILS.LISP.553")
(SCT:PATCH-SECTION-ATTRIBUTES
"-*- Syntax: Ansi-common-lisp; Package: HTTP; Base: 10; Mode: lisp -*-")
(defmethod set-logical-host-directory ((logical-host string) (directory string) (physical-pathname string))
(set-logical-host-directory logical-host directory (pathname physical-pathname)))
|
c8de31bd5b4b46f34d0e8b843b9c7ed4ea4b1d898eeabf71f4dee701dd769831 | yuriy-chumak/ol | texture_border_clamp.scm | ; ===========================================================================
ARB_texture_border_clamp ( included in OpenGL 1.3 )
;
;
; Version
;
; Overview
;
(define-library (OpenGL ARB texture_border_clamp)
; ---------------------------------------------------------------------------
; Dependencies
(import (scheme core) (OpenGL platform))
; ---------------------------------------------------------------------------
(export ARB_texture_border_clamp
; ---------------------------------------------------------------------------
; New Procedures and Functions
; ---------------------------------------------------------------------------
; New Tokens
)
; ---------------------------------------------------------------------------
(begin
(define ARB_texture_border_clamp (gl:QueryExtension "GL_ARB_texture_border_clamp"))
))
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/libraries/OpenGL/ARB/texture_border_clamp.scm | scheme | ===========================================================================
Version
Overview
---------------------------------------------------------------------------
Dependencies
---------------------------------------------------------------------------
---------------------------------------------------------------------------
New Procedures and Functions
---------------------------------------------------------------------------
New Tokens
--------------------------------------------------------------------------- | ARB_texture_border_clamp ( included in OpenGL 1.3 )
(define-library (OpenGL ARB texture_border_clamp)
(import (scheme core) (OpenGL platform))
(export ARB_texture_border_clamp
)
(begin
(define ARB_texture_border_clamp (gl:QueryExtension "GL_ARB_texture_border_clamp"))
))
|
0ac847c5661e8d4de876bbc0ebbc7833eb91fdde263e10c2a1b4f5720834558b | rabbitmq/rabbitmq-erlang-client | amqp_gen_connection.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
@private
-module(amqp_gen_connection).
-include("amqp_client_internal.hrl").
-behaviour(gen_server).
-export([start_link/2, connect/1, open_channel/3, hard_error_in_channel/3,
channel_internal_error/3, server_misbehaved/2, channels_terminated/1,
close/3, server_close/2, info/2, info_keys/0, info_keys/1,
register_blocked_handler/2, update_secret/2]).
-export([behaviour_info/1]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2]).
-define(INFO_KEYS, [server_properties, is_closing, amqp_params, num_channels,
channel_max]).
-record(state, {module,
module_state,
channels_manager,
amqp_params,
channel_max,
server_properties,
%% connection.block, connection.unblock handler
block_handler,
closing = false %% #closing{} | false
}).
-record(closing, {reason,
close,
from = none}).
%%---------------------------------------------------------------------------
Interface
%%---------------------------------------------------------------------------
start_link(TypeSup, AMQPParams) ->
gen_server:start_link(?MODULE, {TypeSup, AMQPParams}, []).
connect(Pid) ->
gen_server:call(Pid, connect, amqp_util:call_timeout()).
open_channel(Pid, ProposedNumber, Consumer) ->
case gen_server:call(Pid,
{command, {open_channel, ProposedNumber, Consumer}},
amqp_util:call_timeout()) of
{ok, ChannelPid} -> ok = amqp_channel:open(ChannelPid),
{ok, ChannelPid};
Error -> Error
end.
hard_error_in_channel(Pid, ChannelPid, Reason) ->
gen_server:cast(Pid, {hard_error_in_channel, ChannelPid, Reason}).
channel_internal_error(Pid, ChannelPid, Reason) ->
gen_server:cast(Pid, {channel_internal_error, ChannelPid, Reason}).
server_misbehaved(Pid, AmqpError) ->
gen_server:cast(Pid, {server_misbehaved, AmqpError}).
channels_terminated(Pid) ->
gen_server:cast(Pid, channels_terminated).
close(Pid, Close, Timeout) ->
gen_server:call(Pid, {command, {close, Close, Timeout}}, amqp_util:call_timeout()).
server_close(Pid, Close) ->
gen_server:cast(Pid, {server_close, Close}).
update_secret(Pid, Method) ->
gen_server:call(Pid, {command, {update_secret, Method}}, amqp_util:call_timeout()).
info(Pid, Items) ->
gen_server:call(Pid, {info, Items}, amqp_util:call_timeout()).
info_keys() ->
?INFO_KEYS.
info_keys(Pid) ->
gen_server:call(Pid, info_keys, amqp_util:call_timeout()).
%%---------------------------------------------------------------------------
%% Behaviour
%%---------------------------------------------------------------------------
behaviour_info(callbacks) ->
[
init ( ) - > { ok , InitialState }
{init, 0},
%% terminate(Reason, FinalState) -> Ignored
{terminate, 2},
connect(AmqpParams , SIF , TypeSup , State ) - >
{ ok , ConnectParams } | { closing , ConnectParams , AmqpError , Reply } |
%% {error, Error}
%% where
ConnectParams = { ServerProperties , , , NewState }
{connect, 4},
do(Method , State ) - > Ignored
{do, 2},
%% open_channel_args(State) -> OpenChannelArgs
{open_channel_args, 1},
i(InfoItem , State ) - > Info
{i, 2},
%% info_keys() -> [InfoItem]
{info_keys, 0},
CallbackReply = { ok , NewState } | { stop , , FinalState }
handle_message(Message , State ) - > CallbackReply
{handle_message, 2},
closing(flush|abrupt , , State ) - > CallbackReply
{closing, 3},
%% channels_terminated(State) -> CallbackReply
{channels_terminated, 1}
];
behaviour_info(_Other) ->
undefined.
callback(Function, Params, State = #state{module = Mod,
module_state = MState}) ->
case erlang:apply(Mod, Function, Params ++ [MState]) of
{ok, NewMState} -> {noreply,
State#state{module_state = NewMState}};
{stop, Reason, NewMState} -> {stop, Reason,
State#state{module_state = NewMState}}
end.
%%---------------------------------------------------------------------------
%% gen_server callbacks
%%---------------------------------------------------------------------------
init({TypeSup, AMQPParams}) ->
%% Trapping exits since we need to make sure that the `terminate/2' is
%% called in the case of direct connection (it does not matter for a network
%% connection). See bug25116.
process_flag(trap_exit, true),
connect ( ) has to be called first , so we can use a special state here
{ok, {TypeSup, AMQPParams}}.
handle_call(connect, _From, {TypeSup, AMQPParams}) ->
{Type, Mod} = amqp_connection_type_sup:type_module(AMQPParams),
{ok, MState} = Mod:init(),
SIF = amqp_connection_type_sup:start_infrastructure_fun(
TypeSup, self(), Type),
State = #state{module = Mod,
module_state = MState,
amqp_params = AMQPParams,
block_handler = none},
case Mod:connect(AMQPParams, SIF, TypeSup, MState) of
{ok, Params} ->
{reply, {ok, self()}, after_connect(Params, State)};
{closing, #amqp_error{name = access_refused} = AmqpError, Error} ->
{stop, {shutdown, AmqpError}, Error, State};
{closing, Params, #amqp_error{} = AmqpError, Error} ->
server_misbehaved(self(), AmqpError),
{reply, Error, after_connect(Params, State)};
{error, _} = Error ->
{stop, {shutdown, Error}, Error, State}
end;
handle_call({command, Command}, From, State = #state{closing = false}) ->
handle_command(Command, From, State);
handle_call({command, _Command}, _From, State) ->
{reply, closing, State};
handle_call({info, Items}, _From, State) ->
{reply, [{Item, i(Item, State)} || Item <- Items], State};
handle_call(info_keys, _From, State = #state{module = Mod}) ->
{reply, ?INFO_KEYS ++ Mod:info_keys(), State}.
after_connect({ServerProperties, ChannelMax, ChMgr, NewMState}, State) ->
case ChannelMax of
0 -> ok;
_ -> amqp_channels_manager:set_channel_max(ChMgr, ChannelMax)
end,
State1 = State#state{server_properties = ServerProperties,
channel_max = ChannelMax,
channels_manager = ChMgr,
module_state = NewMState},
rabbit_misc:store_proc_name(?MODULE, i(name, State1)),
State1.
handle_cast({method, Method, none, noflow}, State) ->
handle_method(Method, State);
handle_cast(channels_terminated, State) ->
handle_channels_terminated(State);
handle_cast({hard_error_in_channel, _Pid, Reason}, State) ->
server_initiated_close(Reason, State);
handle_cast({channel_internal_error, Pid, Reason}, State) ->
?LOG_WARN("Connection (~p) closing: internal error in channel (~p): ~p~n",
[self(), Pid, Reason]),
internal_error(Pid, Reason, State);
handle_cast({server_misbehaved, AmqpError}, State) ->
server_misbehaved_close(AmqpError, State);
handle_cast({server_close, #'connection.close'{} = Close}, State) ->
server_initiated_close(Close, State);
handle_cast({register_blocked_handler, HandlerPid}, State) ->
Ref = erlang:monitor(process, HandlerPid),
{noreply, State#state{block_handler = {HandlerPid, Ref}}}.
@private
handle_info({'DOWN', _, process, BlockHandler, Reason},
State = #state{block_handler = {BlockHandler, _Ref}}) ->
?LOG_WARN("Connection (~p): Unregistering connection.{blocked,unblocked} handler ~p because it died. "
"Reason: ~p~n", [self(), BlockHandler, Reason]),
{noreply, State#state{block_handler = none}};
handle_info({'EXIT', BlockHandler, Reason},
State = #state{block_handler = {BlockHandler, Ref}}) ->
?LOG_WARN("Connection (~p): Unregistering connection.{blocked,unblocked} handler ~p because it died. "
"Reason: ~p~n", [self(), BlockHandler, Reason]),
erlang:demonitor(Ref, [flush]),
{noreply, State#state{block_handler = none}};
%% propagate the exit to the module that will stop with a sensible reason logged
handle_info({'EXIT', _Pid, _Reason} = Info, State) ->
callback(handle_message, [Info], State);
handle_info(Info, State) ->
callback(handle_message, [Info], State).
terminate(Reason, #state{module = Mod, module_state = MState}) ->
Mod:terminate(Reason, MState).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%---------------------------------------------------------------------------
Infos
%%---------------------------------------------------------------------------
i(server_properties, State) -> State#state.server_properties;
i(is_closing, State) -> State#state.closing =/= false;
i(amqp_params, State) -> State#state.amqp_params;
i(channel_max, State) -> State#state.channel_max;
i(num_channels, State) -> amqp_channels_manager:num_channels(
State#state.channels_manager);
i(Item, #state{module = Mod, module_state = MState}) -> Mod:i(Item, MState).
%%---------------------------------------------------------------------------
%% connection.blocked, connection.unblocked
%%---------------------------------------------------------------------------
register_blocked_handler(Pid, HandlerPid) ->
gen_server:cast(Pid, {register_blocked_handler, HandlerPid}).
%%---------------------------------------------------------------------------
%% Command handling
%%---------------------------------------------------------------------------
handle_command({open_channel, ProposedNumber, Consumer}, _From,
State = #state{channels_manager = ChMgr,
module = Mod,
module_state = MState}) ->
{reply, amqp_channels_manager:open_channel(ChMgr, ProposedNumber, Consumer,
Mod:open_channel_args(MState)),
State};
handle_command({close, #'connection.close'{} = Close, Timeout}, From, State) ->
app_initiated_close(Close, From, Timeout, State);
handle_command({update_secret, #'connection.update_secret'{} = Method}, _From,
State = #state{module = Mod,
module_state = MState}) ->
{reply, Mod:do(Method, MState), State}.
%%---------------------------------------------------------------------------
%% Handling methods from broker
%%---------------------------------------------------------------------------
handle_method(#'connection.close'{} = Close, State) ->
server_initiated_close(Close, State);
handle_method(#'connection.close_ok'{}, State = #state{closing = Closing}) ->
case Closing of #closing{from = none} -> ok;
#closing{from = From} -> gen_server:reply(From, ok)
end,
{stop, {shutdown, closing_to_reason(Closing)}, State};
handle_method(#'connection.blocked'{} = Blocked, State = #state{block_handler = BlockHandler}) ->
case BlockHandler of none -> ok;
{Pid, _Ref} -> Pid ! Blocked
end,
{noreply, State};
handle_method(#'connection.unblocked'{} = Unblocked, State = #state{block_handler = BlockHandler}) ->
case BlockHandler of none -> ok;
{Pid, _Ref} -> Pid ! Unblocked
end,
{noreply, State};
handle_method(#'connection.update_secret_ok'{} = _Method, State) ->
{noreply, State};
handle_method(Other, State) ->
server_misbehaved_close(#amqp_error{name = command_invalid,
explanation = "unexpected method on "
"channel 0",
method = element(1, Other)},
State).
%%---------------------------------------------------------------------------
%% Closing
%%---------------------------------------------------------------------------
app_initiated_close(Close, From, Timeout, State) ->
case Timeout of
infinity -> ok;
_ -> erlang:send_after(Timeout, self(), closing_timeout)
end,
set_closing_state(flush, #closing{reason = app_initiated_close,
close = Close,
from = From}, State).
internal_error(Pid, Reason, State) ->
Str = list_to_binary(rabbit_misc:format("~p:~p", [Pid, Reason])),
Close = #'connection.close'{reply_text = Str,
reply_code = ?INTERNAL_ERROR,
class_id = 0,
method_id = 0},
set_closing_state(abrupt, #closing{reason = internal_error, close = Close},
State).
server_initiated_close(Close, State) ->
?LOG_WARN("Connection (~p) closing: received hard error ~p "
"from server~n", [self(), Close]),
set_closing_state(abrupt, #closing{reason = server_initiated_close,
close = Close}, State).
server_misbehaved_close(AmqpError, State) ->
?LOG_WARN("Connection (~p) closing: server misbehaved: ~p~n",
[self(), AmqpError]),
{0, Close} = rabbit_binary_generator:map_exception(0, AmqpError, ?PROTOCOL),
set_closing_state(abrupt, #closing{reason = server_misbehaved,
close = Close}, State).
set_closing_state(ChannelCloseType, NewClosing,
State = #state{channels_manager = ChMgr,
closing = CurClosing}) ->
ResClosing =
case closing_priority(NewClosing) =< closing_priority(CurClosing) of
true -> NewClosing;
false -> CurClosing
end,
ClosingReason = closing_to_reason(ResClosing),
amqp_channels_manager:signal_connection_closing(ChMgr, ChannelCloseType,
ClosingReason),
callback(closing, [ChannelCloseType, ClosingReason],
State#state{closing = ResClosing}).
closing_priority(false) -> 99;
closing_priority(#closing{reason = app_initiated_close}) -> 4;
closing_priority(#closing{reason = internal_error}) -> 3;
closing_priority(#closing{reason = server_misbehaved}) -> 2;
closing_priority(#closing{reason = server_initiated_close}) -> 1.
closing_to_reason(#closing{close = #'connection.close'{reply_code = 200}}) ->
normal;
closing_to_reason(#closing{reason = Reason,
close = #'connection.close'{reply_code = Code,
reply_text = Text}}) ->
{Reason, Code, Text};
closing_to_reason(#closing{reason = Reason,
close = {Reason, _Code, _Text} = Close}) ->
Close.
handle_channels_terminated(State = #state{closing = Closing,
module = Mod,
module_state = MState}) ->
#closing{reason = Reason, close = Close, from = From} = Closing,
case Reason of
server_initiated_close ->
Mod:do(#'connection.close_ok'{}, MState);
_ ->
Mod:do(Close, MState)
end,
case callback(channels_terminated, [], State) of
{stop, _, _} = Stop -> case From of none -> ok;
_ -> gen_server:reply(From, ok)
end,
Stop;
Other -> Other
end.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-erlang-client/2022e01c515d93ed1883e9e9e987be2e58fe15c9/src/amqp_gen_connection.erl | erlang |
connection.block, connection.unblock handler
#closing{} | false
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Behaviour
---------------------------------------------------------------------------
terminate(Reason, FinalState) -> Ignored
{error, Error}
where
open_channel_args(State) -> OpenChannelArgs
info_keys() -> [InfoItem]
channels_terminated(State) -> CallbackReply
---------------------------------------------------------------------------
gen_server callbacks
---------------------------------------------------------------------------
Trapping exits since we need to make sure that the `terminate/2' is
called in the case of direct connection (it does not matter for a network
connection). See bug25116.
propagate the exit to the module that will stop with a sensible reason logged
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
connection.blocked, connection.unblocked
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Command handling
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Handling methods from broker
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Closing
--------------------------------------------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
@private
-module(amqp_gen_connection).
-include("amqp_client_internal.hrl").
-behaviour(gen_server).
-export([start_link/2, connect/1, open_channel/3, hard_error_in_channel/3,
channel_internal_error/3, server_misbehaved/2, channels_terminated/1,
close/3, server_close/2, info/2, info_keys/0, info_keys/1,
register_blocked_handler/2, update_secret/2]).
-export([behaviour_info/1]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2]).
-define(INFO_KEYS, [server_properties, is_closing, amqp_params, num_channels,
channel_max]).
-record(state, {module,
module_state,
channels_manager,
amqp_params,
channel_max,
server_properties,
block_handler,
}).
-record(closing, {reason,
close,
from = none}).
Interface
start_link(TypeSup, AMQPParams) ->
gen_server:start_link(?MODULE, {TypeSup, AMQPParams}, []).
connect(Pid) ->
gen_server:call(Pid, connect, amqp_util:call_timeout()).
open_channel(Pid, ProposedNumber, Consumer) ->
case gen_server:call(Pid,
{command, {open_channel, ProposedNumber, Consumer}},
amqp_util:call_timeout()) of
{ok, ChannelPid} -> ok = amqp_channel:open(ChannelPid),
{ok, ChannelPid};
Error -> Error
end.
hard_error_in_channel(Pid, ChannelPid, Reason) ->
gen_server:cast(Pid, {hard_error_in_channel, ChannelPid, Reason}).
channel_internal_error(Pid, ChannelPid, Reason) ->
gen_server:cast(Pid, {channel_internal_error, ChannelPid, Reason}).
server_misbehaved(Pid, AmqpError) ->
gen_server:cast(Pid, {server_misbehaved, AmqpError}).
channels_terminated(Pid) ->
gen_server:cast(Pid, channels_terminated).
close(Pid, Close, Timeout) ->
gen_server:call(Pid, {command, {close, Close, Timeout}}, amqp_util:call_timeout()).
server_close(Pid, Close) ->
gen_server:cast(Pid, {server_close, Close}).
update_secret(Pid, Method) ->
gen_server:call(Pid, {command, {update_secret, Method}}, amqp_util:call_timeout()).
info(Pid, Items) ->
gen_server:call(Pid, {info, Items}, amqp_util:call_timeout()).
info_keys() ->
?INFO_KEYS.
info_keys(Pid) ->
gen_server:call(Pid, info_keys, amqp_util:call_timeout()).
behaviour_info(callbacks) ->
[
init ( ) - > { ok , InitialState }
{init, 0},
{terminate, 2},
connect(AmqpParams , SIF , TypeSup , State ) - >
{ ok , ConnectParams } | { closing , ConnectParams , AmqpError , Reply } |
ConnectParams = { ServerProperties , , , NewState }
{connect, 4},
do(Method , State ) - > Ignored
{do, 2},
{open_channel_args, 1},
i(InfoItem , State ) - > Info
{i, 2},
{info_keys, 0},
CallbackReply = { ok , NewState } | { stop , , FinalState }
handle_message(Message , State ) - > CallbackReply
{handle_message, 2},
closing(flush|abrupt , , State ) - > CallbackReply
{closing, 3},
{channels_terminated, 1}
];
behaviour_info(_Other) ->
undefined.
callback(Function, Params, State = #state{module = Mod,
module_state = MState}) ->
case erlang:apply(Mod, Function, Params ++ [MState]) of
{ok, NewMState} -> {noreply,
State#state{module_state = NewMState}};
{stop, Reason, NewMState} -> {stop, Reason,
State#state{module_state = NewMState}}
end.
init({TypeSup, AMQPParams}) ->
process_flag(trap_exit, true),
connect ( ) has to be called first , so we can use a special state here
{ok, {TypeSup, AMQPParams}}.
handle_call(connect, _From, {TypeSup, AMQPParams}) ->
{Type, Mod} = amqp_connection_type_sup:type_module(AMQPParams),
{ok, MState} = Mod:init(),
SIF = amqp_connection_type_sup:start_infrastructure_fun(
TypeSup, self(), Type),
State = #state{module = Mod,
module_state = MState,
amqp_params = AMQPParams,
block_handler = none},
case Mod:connect(AMQPParams, SIF, TypeSup, MState) of
{ok, Params} ->
{reply, {ok, self()}, after_connect(Params, State)};
{closing, #amqp_error{name = access_refused} = AmqpError, Error} ->
{stop, {shutdown, AmqpError}, Error, State};
{closing, Params, #amqp_error{} = AmqpError, Error} ->
server_misbehaved(self(), AmqpError),
{reply, Error, after_connect(Params, State)};
{error, _} = Error ->
{stop, {shutdown, Error}, Error, State}
end;
handle_call({command, Command}, From, State = #state{closing = false}) ->
handle_command(Command, From, State);
handle_call({command, _Command}, _From, State) ->
{reply, closing, State};
handle_call({info, Items}, _From, State) ->
{reply, [{Item, i(Item, State)} || Item <- Items], State};
handle_call(info_keys, _From, State = #state{module = Mod}) ->
{reply, ?INFO_KEYS ++ Mod:info_keys(), State}.
after_connect({ServerProperties, ChannelMax, ChMgr, NewMState}, State) ->
case ChannelMax of
0 -> ok;
_ -> amqp_channels_manager:set_channel_max(ChMgr, ChannelMax)
end,
State1 = State#state{server_properties = ServerProperties,
channel_max = ChannelMax,
channels_manager = ChMgr,
module_state = NewMState},
rabbit_misc:store_proc_name(?MODULE, i(name, State1)),
State1.
handle_cast({method, Method, none, noflow}, State) ->
handle_method(Method, State);
handle_cast(channels_terminated, State) ->
handle_channels_terminated(State);
handle_cast({hard_error_in_channel, _Pid, Reason}, State) ->
server_initiated_close(Reason, State);
handle_cast({channel_internal_error, Pid, Reason}, State) ->
?LOG_WARN("Connection (~p) closing: internal error in channel (~p): ~p~n",
[self(), Pid, Reason]),
internal_error(Pid, Reason, State);
handle_cast({server_misbehaved, AmqpError}, State) ->
server_misbehaved_close(AmqpError, State);
handle_cast({server_close, #'connection.close'{} = Close}, State) ->
server_initiated_close(Close, State);
handle_cast({register_blocked_handler, HandlerPid}, State) ->
Ref = erlang:monitor(process, HandlerPid),
{noreply, State#state{block_handler = {HandlerPid, Ref}}}.
@private
handle_info({'DOWN', _, process, BlockHandler, Reason},
State = #state{block_handler = {BlockHandler, _Ref}}) ->
?LOG_WARN("Connection (~p): Unregistering connection.{blocked,unblocked} handler ~p because it died. "
"Reason: ~p~n", [self(), BlockHandler, Reason]),
{noreply, State#state{block_handler = none}};
handle_info({'EXIT', BlockHandler, Reason},
State = #state{block_handler = {BlockHandler, Ref}}) ->
?LOG_WARN("Connection (~p): Unregistering connection.{blocked,unblocked} handler ~p because it died. "
"Reason: ~p~n", [self(), BlockHandler, Reason]),
erlang:demonitor(Ref, [flush]),
{noreply, State#state{block_handler = none}};
handle_info({'EXIT', _Pid, _Reason} = Info, State) ->
callback(handle_message, [Info], State);
handle_info(Info, State) ->
callback(handle_message, [Info], State).
terminate(Reason, #state{module = Mod, module_state = MState}) ->
Mod:terminate(Reason, MState).
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Infos
i(server_properties, State) -> State#state.server_properties;
i(is_closing, State) -> State#state.closing =/= false;
i(amqp_params, State) -> State#state.amqp_params;
i(channel_max, State) -> State#state.channel_max;
i(num_channels, State) -> amqp_channels_manager:num_channels(
State#state.channels_manager);
i(Item, #state{module = Mod, module_state = MState}) -> Mod:i(Item, MState).
register_blocked_handler(Pid, HandlerPid) ->
gen_server:cast(Pid, {register_blocked_handler, HandlerPid}).
handle_command({open_channel, ProposedNumber, Consumer}, _From,
State = #state{channels_manager = ChMgr,
module = Mod,
module_state = MState}) ->
{reply, amqp_channels_manager:open_channel(ChMgr, ProposedNumber, Consumer,
Mod:open_channel_args(MState)),
State};
handle_command({close, #'connection.close'{} = Close, Timeout}, From, State) ->
app_initiated_close(Close, From, Timeout, State);
handle_command({update_secret, #'connection.update_secret'{} = Method}, _From,
State = #state{module = Mod,
module_state = MState}) ->
{reply, Mod:do(Method, MState), State}.
handle_method(#'connection.close'{} = Close, State) ->
server_initiated_close(Close, State);
handle_method(#'connection.close_ok'{}, State = #state{closing = Closing}) ->
case Closing of #closing{from = none} -> ok;
#closing{from = From} -> gen_server:reply(From, ok)
end,
{stop, {shutdown, closing_to_reason(Closing)}, State};
handle_method(#'connection.blocked'{} = Blocked, State = #state{block_handler = BlockHandler}) ->
case BlockHandler of none -> ok;
{Pid, _Ref} -> Pid ! Blocked
end,
{noreply, State};
handle_method(#'connection.unblocked'{} = Unblocked, State = #state{block_handler = BlockHandler}) ->
case BlockHandler of none -> ok;
{Pid, _Ref} -> Pid ! Unblocked
end,
{noreply, State};
handle_method(#'connection.update_secret_ok'{} = _Method, State) ->
{noreply, State};
handle_method(Other, State) ->
server_misbehaved_close(#amqp_error{name = command_invalid,
explanation = "unexpected method on "
"channel 0",
method = element(1, Other)},
State).
app_initiated_close(Close, From, Timeout, State) ->
case Timeout of
infinity -> ok;
_ -> erlang:send_after(Timeout, self(), closing_timeout)
end,
set_closing_state(flush, #closing{reason = app_initiated_close,
close = Close,
from = From}, State).
internal_error(Pid, Reason, State) ->
Str = list_to_binary(rabbit_misc:format("~p:~p", [Pid, Reason])),
Close = #'connection.close'{reply_text = Str,
reply_code = ?INTERNAL_ERROR,
class_id = 0,
method_id = 0},
set_closing_state(abrupt, #closing{reason = internal_error, close = Close},
State).
server_initiated_close(Close, State) ->
?LOG_WARN("Connection (~p) closing: received hard error ~p "
"from server~n", [self(), Close]),
set_closing_state(abrupt, #closing{reason = server_initiated_close,
close = Close}, State).
server_misbehaved_close(AmqpError, State) ->
?LOG_WARN("Connection (~p) closing: server misbehaved: ~p~n",
[self(), AmqpError]),
{0, Close} = rabbit_binary_generator:map_exception(0, AmqpError, ?PROTOCOL),
set_closing_state(abrupt, #closing{reason = server_misbehaved,
close = Close}, State).
set_closing_state(ChannelCloseType, NewClosing,
State = #state{channels_manager = ChMgr,
closing = CurClosing}) ->
ResClosing =
case closing_priority(NewClosing) =< closing_priority(CurClosing) of
true -> NewClosing;
false -> CurClosing
end,
ClosingReason = closing_to_reason(ResClosing),
amqp_channels_manager:signal_connection_closing(ChMgr, ChannelCloseType,
ClosingReason),
callback(closing, [ChannelCloseType, ClosingReason],
State#state{closing = ResClosing}).
closing_priority(false) -> 99;
closing_priority(#closing{reason = app_initiated_close}) -> 4;
closing_priority(#closing{reason = internal_error}) -> 3;
closing_priority(#closing{reason = server_misbehaved}) -> 2;
closing_priority(#closing{reason = server_initiated_close}) -> 1.
closing_to_reason(#closing{close = #'connection.close'{reply_code = 200}}) ->
normal;
closing_to_reason(#closing{reason = Reason,
close = #'connection.close'{reply_code = Code,
reply_text = Text}}) ->
{Reason, Code, Text};
closing_to_reason(#closing{reason = Reason,
close = {Reason, _Code, _Text} = Close}) ->
Close.
handle_channels_terminated(State = #state{closing = Closing,
module = Mod,
module_state = MState}) ->
#closing{reason = Reason, close = Close, from = From} = Closing,
case Reason of
server_initiated_close ->
Mod:do(#'connection.close_ok'{}, MState);
_ ->
Mod:do(Close, MState)
end,
case callback(channels_terminated, [], State) of
{stop, _, _} = Stop -> case From of none -> ok;
_ -> gen_server:reply(From, ok)
end,
Stop;
Other -> Other
end.
|
34839d4e47fd576fa039cb0953d1e48e61ea76b82cea70a2f8b33f6891342fb8 | karamellpelle/grid | FontShade.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see </>.
--
module Game.Font.FontShade
(
FontShade (..),
loadFontShade,
fontShade,
fontShadePlane2D,
fontShadePlane3D,
fontSetAlpha,
fontSetPlane2D,
fontSetPlane3D,
valueFontMaxCharacters,
) where
import MyPrelude
import File
import Game.Font.Buffer
import OpenGL
import OpenGL.Helpers
import OpenGL.Shade
data FontShade =
FontShade
{
fontShadePrg :: !GLuint,
fontShadeUniAlpha :: !GLint,
fontShadeUniProjModvMatrix :: !GLint,
fontShadeUniPos :: !GLint,
fontShadeUniPlaneX :: !GLint,
fontShadeUniPlaneY :: !GLint,
fontShadeUniTranslate :: !GLint,
fontShadeUniCharSize :: !GLint,
fontShadeUniColor :: !GLint,
fontShadeUniColorContour : : ! GLint ,
fontShadeIBO :: !GLuint,
fontShadeDefaultVAO :: !GLuint,
fontShadeDefaultVBOPos :: !GLuint,
fontShadeDefaultVBOCoord :: !GLuint
}
--------------------------------------------------------------------------------
-- load
loadFontShade :: FilePath -> IO FontShade
loadFontShade path = do
prg <- createPrg (path ++ "/FontShade.vsh") (path ++ "/FontShade.fsh") [
(attPos, "a_pos"),
(attStencilCoord, "a_stencil_coord") ] [
(tex0, "u_stencil") ]
-- uniforms
uniAlpha <- getUniformLocation prg "u_alpha"
uniProjModvMatrix <- getUniformLocation prg "u_projmodv_matrix"
uniPos <- getUniformLocation prg "u_pos"
uniPlaneX <- getUniformLocation prg "u_plane_x"
uniPlaneY <- getUniformLocation prg "u_plane_y"
uniColor <- getUniformLocation prg "u_color"
--uniColorContour <- getUniformLocation prg "u_color_contour"
uniCharSize <- getUniformLocation prg "u_char_size"
uniTranslate <- getUniformLocation prg "u_translate"
-- IBO for triangle strips
ibo <- makeGroupIBO 4 valueFontMaxCharacters
glBindBuffer gl_ELEMENT_ARRAY_BUFFER ibo
-- Default
(vao, vboPos, vboCoord) <- makeDefault ibo
return $ FontShade
{
fontShadePrg = prg,
fontShadeUniAlpha = uniAlpha,
fontShadeUniProjModvMatrix = uniProjModvMatrix,
fontShadeUniPos = uniPos,
fontShadeUniPlaneX = uniPlaneX,
fontShadeUniPlaneY = uniPlaneY,
fontShadeUniTranslate = uniTranslate,
fontShadeUniColor = uniColor,
--fontShadeUniColorBack = uniColorBack,
fontShadeUniCharSize = uniCharSize,
fontShadeIBO = ibo,
fontShadeDefaultVAO = vao,
fontShadeDefaultVBOPos = vboPos,
fontShadeDefaultVBOCoord = vboCoord
}
makeDefault :: GLuint -> IO (GLuint, GLuint, GLuint)
makeDefault ibo = do
vao
vao <- bindNewVAO
glEnableVertexAttribArray attPos
glEnableVertexAttribArray attStencilCoord
bind ibo to vao
glBindBuffer gl_ELEMENT_ARRAY_BUFFER ibo
-- vbo pos
vboPos <- bindNewBuf gl_ARRAY_BUFFER
let bytesize = valueFontMaxCharacters * 16
glBufferData gl_ARRAY_BUFFER (fI bytesize) nullPtr gl_STATIC_DRAW
glVertexAttribPointer attPos 2 gl_UNSIGNED_SHORT gl_FALSE 0 $
mkPtrGLvoid 0
writeBuf gl_ARRAY_BUFFER $ \ptr ->
writeDefaultPosLen ptr valueFontMaxCharacters
-- vbo coord
vboCoord <- bindNewBuf gl_ARRAY_BUFFER
let bytesize = valueFontMaxCharacters * 16
glBufferData gl_ARRAY_BUFFER (fI bytesize) nullPtr gl_STREAM_DRAW
glVertexAttribPointer attStencilCoord 2 gl_UNSIGNED_SHORT gl_TRUE 0 $
mkPtrGLvoid 0
return (vao, vboPos, vboCoord)
--------------------------------------------------------------------------------
-- shade
| note : FrontFace is GL_CCW in 3D and GL_CW in 2D.
so 2D drawing should typically disable !
fontShade :: FontShade -> Float -> Mat4 -> IO ()
fontShade sh alpha projmodv =
fontShadePlane3D sh alpha projmodv 1.0 0.0 0.0 0.0 1.0 0.0
fontShadePlane2D :: FontShade -> Float -> Mat4 -> Float -> Float -> Float -> Float ->
IO ()
fontShadePlane2D sh alpha projmodv x0 x1 y0 y1 =
fontShadePlane3D sh alpha projmodv x0 x1 0.0 y0 y1 0.0
fontShadePlane3D :: FontShade -> Float -> Mat4 ->
Float -> Float -> Float ->
Float -> Float -> Float ->
IO ()
fontShadePlane3D sh alpha projmodv x0 x1 x2 y0 y1 y2 = do
glUseProgram (fontShadePrg sh)
-- alpha
glUniform1f (fontShadeUniAlpha sh) $ rTF alpha
projmodv
uniformMat4 (fontShadeUniProjModvMatrix sh) projmodv
-- plane
glUniform3f (fontShadeUniPlaneX sh) (rTF x0) (rTF x1) (rTF x2)
glUniform3f (fontShadeUniPlaneY sh) (rTF y0) (rTF y1) (rTF y2)
--------------------------------------------------------------------------------
-- configure shade
fontSetAlpha :: FontShade -> Float -> IO ()
fontSetAlpha sh alpha =
glUniform1f (fontShadeUniAlpha sh) $ rTF alpha
fontSetPlane2D :: FontShade -> Float -> Float -> Float -> Float -> IO ()
fontSetPlane2D sh x0 x1 y0 y1 =
fontSetPlane3D sh x0 x1 0.0 y0 y1 0.0
fontSetPlane3D :: FontShade -> Float -> Float -> Float ->
Float -> Float -> Float -> IO ()
fontSetPlane3D sh x0 x1 x2 y0 y1 y2 = do
glUniform3f (fontShadeUniPlaneX sh) (rTF x0) (rTF x1) (rTF x2)
glUniform3f (fontShadeUniPlaneY sh) (rTF y0) (rTF y1) (rTF y2)
--------------------------------------------------------------------------------
-- values
valueFontMaxCharacters :: UInt
valueFontMaxCharacters =
64
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/Font/FontShade.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with grid. If not, see </>.
------------------------------------------------------------------------------
load
uniforms
uniColorContour <- getUniformLocation prg "u_color_contour"
IBO for triangle strips
Default
fontShadeUniColorBack = uniColorBack,
vbo pos
vbo coord
------------------------------------------------------------------------------
shade
alpha
plane
------------------------------------------------------------------------------
configure shade
------------------------------------------------------------------------------
values | grid is a game written in Haskell
Copyright ( C ) 2018
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
module Game.Font.FontShade
(
FontShade (..),
loadFontShade,
fontShade,
fontShadePlane2D,
fontShadePlane3D,
fontSetAlpha,
fontSetPlane2D,
fontSetPlane3D,
valueFontMaxCharacters,
) where
import MyPrelude
import File
import Game.Font.Buffer
import OpenGL
import OpenGL.Helpers
import OpenGL.Shade
data FontShade =
FontShade
{
fontShadePrg :: !GLuint,
fontShadeUniAlpha :: !GLint,
fontShadeUniProjModvMatrix :: !GLint,
fontShadeUniPos :: !GLint,
fontShadeUniPlaneX :: !GLint,
fontShadeUniPlaneY :: !GLint,
fontShadeUniTranslate :: !GLint,
fontShadeUniCharSize :: !GLint,
fontShadeUniColor :: !GLint,
fontShadeUniColorContour : : ! GLint ,
fontShadeIBO :: !GLuint,
fontShadeDefaultVAO :: !GLuint,
fontShadeDefaultVBOPos :: !GLuint,
fontShadeDefaultVBOCoord :: !GLuint
}
loadFontShade :: FilePath -> IO FontShade
loadFontShade path = do
prg <- createPrg (path ++ "/FontShade.vsh") (path ++ "/FontShade.fsh") [
(attPos, "a_pos"),
(attStencilCoord, "a_stencil_coord") ] [
(tex0, "u_stencil") ]
uniAlpha <- getUniformLocation prg "u_alpha"
uniProjModvMatrix <- getUniformLocation prg "u_projmodv_matrix"
uniPos <- getUniformLocation prg "u_pos"
uniPlaneX <- getUniformLocation prg "u_plane_x"
uniPlaneY <- getUniformLocation prg "u_plane_y"
uniColor <- getUniformLocation prg "u_color"
uniCharSize <- getUniformLocation prg "u_char_size"
uniTranslate <- getUniformLocation prg "u_translate"
ibo <- makeGroupIBO 4 valueFontMaxCharacters
glBindBuffer gl_ELEMENT_ARRAY_BUFFER ibo
(vao, vboPos, vboCoord) <- makeDefault ibo
return $ FontShade
{
fontShadePrg = prg,
fontShadeUniAlpha = uniAlpha,
fontShadeUniProjModvMatrix = uniProjModvMatrix,
fontShadeUniPos = uniPos,
fontShadeUniPlaneX = uniPlaneX,
fontShadeUniPlaneY = uniPlaneY,
fontShadeUniTranslate = uniTranslate,
fontShadeUniColor = uniColor,
fontShadeUniCharSize = uniCharSize,
fontShadeIBO = ibo,
fontShadeDefaultVAO = vao,
fontShadeDefaultVBOPos = vboPos,
fontShadeDefaultVBOCoord = vboCoord
}
makeDefault :: GLuint -> IO (GLuint, GLuint, GLuint)
makeDefault ibo = do
vao
vao <- bindNewVAO
glEnableVertexAttribArray attPos
glEnableVertexAttribArray attStencilCoord
bind ibo to vao
glBindBuffer gl_ELEMENT_ARRAY_BUFFER ibo
vboPos <- bindNewBuf gl_ARRAY_BUFFER
let bytesize = valueFontMaxCharacters * 16
glBufferData gl_ARRAY_BUFFER (fI bytesize) nullPtr gl_STATIC_DRAW
glVertexAttribPointer attPos 2 gl_UNSIGNED_SHORT gl_FALSE 0 $
mkPtrGLvoid 0
writeBuf gl_ARRAY_BUFFER $ \ptr ->
writeDefaultPosLen ptr valueFontMaxCharacters
vboCoord <- bindNewBuf gl_ARRAY_BUFFER
let bytesize = valueFontMaxCharacters * 16
glBufferData gl_ARRAY_BUFFER (fI bytesize) nullPtr gl_STREAM_DRAW
glVertexAttribPointer attStencilCoord 2 gl_UNSIGNED_SHORT gl_TRUE 0 $
mkPtrGLvoid 0
return (vao, vboPos, vboCoord)
| note : FrontFace is GL_CCW in 3D and GL_CW in 2D.
so 2D drawing should typically disable !
fontShade :: FontShade -> Float -> Mat4 -> IO ()
fontShade sh alpha projmodv =
fontShadePlane3D sh alpha projmodv 1.0 0.0 0.0 0.0 1.0 0.0
fontShadePlane2D :: FontShade -> Float -> Mat4 -> Float -> Float -> Float -> Float ->
IO ()
fontShadePlane2D sh alpha projmodv x0 x1 y0 y1 =
fontShadePlane3D sh alpha projmodv x0 x1 0.0 y0 y1 0.0
fontShadePlane3D :: FontShade -> Float -> Mat4 ->
Float -> Float -> Float ->
Float -> Float -> Float ->
IO ()
fontShadePlane3D sh alpha projmodv x0 x1 x2 y0 y1 y2 = do
glUseProgram (fontShadePrg sh)
glUniform1f (fontShadeUniAlpha sh) $ rTF alpha
projmodv
uniformMat4 (fontShadeUniProjModvMatrix sh) projmodv
glUniform3f (fontShadeUniPlaneX sh) (rTF x0) (rTF x1) (rTF x2)
glUniform3f (fontShadeUniPlaneY sh) (rTF y0) (rTF y1) (rTF y2)
fontSetAlpha :: FontShade -> Float -> IO ()
fontSetAlpha sh alpha =
glUniform1f (fontShadeUniAlpha sh) $ rTF alpha
fontSetPlane2D :: FontShade -> Float -> Float -> Float -> Float -> IO ()
fontSetPlane2D sh x0 x1 y0 y1 =
fontSetPlane3D sh x0 x1 0.0 y0 y1 0.0
fontSetPlane3D :: FontShade -> Float -> Float -> Float ->
Float -> Float -> Float -> IO ()
fontSetPlane3D sh x0 x1 x2 y0 y1 y2 = do
glUniform3f (fontShadeUniPlaneX sh) (rTF x0) (rTF x1) (rTF x2)
glUniform3f (fontShadeUniPlaneY sh) (rTF y0) (rTF y1) (rTF y2)
valueFontMaxCharacters :: UInt
valueFontMaxCharacters =
64
|
74eb97d9c8da32d94147b556aaf88ccc4556565b2a7e589644ca270ce34168db | jrh13/hol-light | Inductive_definitions.ml | (* ------------------------------------------------------------------------- *)
(* Bug puzzle. *)
(* ------------------------------------------------------------------------- *)
prioritize_real();;
let move = new_definition
`move ((ax,ay),(bx,by),(cx,cy)) ((ax',ay'),(bx',by'),(cx',cy')) <=>
(?a. ax' = ax + a * (cx - bx) /\ ay' = ay + a * (cy - by) /\
bx' = bx /\ by' = by /\ cx' = cx /\ cy' = cy) \/
(?b. bx' = bx + b * (ax - cx) /\ by' = by + b * (ay - cy) /\
ax' = ax /\ ay' = ay /\ cx' = cx /\ cy' = cy) \/
(?c. ax' = ax /\ ay' = ay /\ bx' = bx /\ by' = by /\
cx' = cx + c * (bx - ax) /\ cy' = cy + c * (by - ay))`;;
let reachable_RULES,reachable_INDUCT,reachable_CASES =
new_inductive_definition
`(!p. reachable p p) /\
(!p q r. move p q /\ reachable q r ==> reachable p r)`;;
let oriented_area = new_definition
`oriented_area ((ax,ay),(bx,by),(cx,cy)) =
((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / &2`;;
let MOVE_INVARIANT = prove
(`!p p'. move p p' ==> oriented_area p = oriented_area p'`,
REWRITE_TAC[FORALL_PAIR_THM; move; oriented_area] THEN CONV_TAC REAL_RING);;
let REACHABLE_INVARIANT = prove
(`!p p'. reachable p p' ==> oriented_area p = oriented_area p'`,
MATCH_MP_TAC reachable_INDUCT THEN MESON_TAC[MOVE_INVARIANT]);;
let IMPOSSIBILITY_B = prove
(`~(reachable ((&0,&0),(&3,&0),(&0,&3)) ((&1,&2),(&2,&5),(-- &2,&3)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((&1,&2),(-- &2,&3),(&2,&5)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((&2,&5),(&1,&2),(-- &2,&3)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((&2,&5),(-- &2,&3),(&1,&2)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((-- &2,&3),(&1,&2),(&2,&5)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((-- &2,&3),(&2,&5),(&1,&2)))`,
STRIP_TAC THEN FIRST_ASSUM(MP_TAC o MATCH_MP REACHABLE_INVARIANT) THEN
REWRITE_TAC[oriented_area] THEN REAL_ARITH_TAC);;
(* ------------------------------------------------------------------------- *)
(* Verification of a simple concurrent program. *)
(* ------------------------------------------------------------------------- *)
let init = new_definition
`init (x,y,pc1,pc2,sem) <=>
pc1 = 10 /\ pc2 = 10 /\ x = 0 /\ y = 0 /\ sem = 1`;;
let trans = new_definition
`trans (x,y,pc1,pc2,sem) (x',y',pc1',pc2',sem') <=>
pc1 = 10 /\ sem > 0 /\ pc1' = 20 /\ sem' = sem - 1 /\
(x',y',pc2') = (x,y,pc2) \/
pc2 = 10 /\ sem > 0 /\ pc2' = 20 /\ sem' = sem - 1 /\
(x',y',pc1') = (x,y,pc1) \/
pc1 = 20 /\ pc1' = 30 /\ x' = x + 1 /\
(y',pc2',sem') = (y,pc2,sem) \/
pc2 = 20 /\ pc2' = 30 /\ y' = y + 1 /\ x' = x /\
pc1' = pc1 /\ sem' = sem \/
pc1 = 30 /\ pc1' = 10 /\ sem' = sem + 1 /\
(x',y',pc2') = (x,y,pc2) \/
pc2 = 30 /\ pc2' = 10 /\ sem' = sem + 1 /\
(x',y',pc1') = (x,y,pc1)`;;
let mutex = new_definition
`mutex (x,y,pc1,pc2,sem) <=> pc1 = 10 \/ pc2 = 10`;;
let indinv = new_definition
`indinv (x:num,y:num,pc1,pc2,sem) <=>
sem + (if pc1 = 10 then 0 else 1) + (if pc2 = 10 then 0 else 1) = 1`;;
needs "Library/rstc.ml";;
let INDUCTIVE_INVARIANT = prove
(`!init invariant transition P.
(!s. init s ==> invariant s) /\
(!s s'. invariant s /\ transition s s' ==> invariant s') /\
(!s. invariant s ==> P s)
==> !s s':A. init s /\ RTC transition s s' ==> P s'`,
REPEAT GEN_TAC THEN MP_TAC(ISPECL
[`transition:A->A->bool`;
`\s s':A. invariant s ==> invariant s'`] RTC_INDUCT) THEN
MESON_TAC[]);;
let MUTEX = prove
(`!s s'. init s /\ RTC trans s s' ==> mutex s'`,
MATCH_MP_TAC INDUCTIVE_INVARIANT THEN EXISTS_TAC `indinv` THEN
REWRITE_TAC[init; trans; indinv; mutex; FORALL_PAIR_THM; PAIR_EQ] THEN
ARITH_TAC);;
| null | https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/Tutorial/Inductive_definitions.ml | ocaml | -------------------------------------------------------------------------
Bug puzzle.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Verification of a simple concurrent program.
------------------------------------------------------------------------- |
prioritize_real();;
let move = new_definition
`move ((ax,ay),(bx,by),(cx,cy)) ((ax',ay'),(bx',by'),(cx',cy')) <=>
(?a. ax' = ax + a * (cx - bx) /\ ay' = ay + a * (cy - by) /\
bx' = bx /\ by' = by /\ cx' = cx /\ cy' = cy) \/
(?b. bx' = bx + b * (ax - cx) /\ by' = by + b * (ay - cy) /\
ax' = ax /\ ay' = ay /\ cx' = cx /\ cy' = cy) \/
(?c. ax' = ax /\ ay' = ay /\ bx' = bx /\ by' = by /\
cx' = cx + c * (bx - ax) /\ cy' = cy + c * (by - ay))`;;
let reachable_RULES,reachable_INDUCT,reachable_CASES =
new_inductive_definition
`(!p. reachable p p) /\
(!p q r. move p q /\ reachable q r ==> reachable p r)`;;
let oriented_area = new_definition
`oriented_area ((ax,ay),(bx,by),(cx,cy)) =
((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)) / &2`;;
let MOVE_INVARIANT = prove
(`!p p'. move p p' ==> oriented_area p = oriented_area p'`,
REWRITE_TAC[FORALL_PAIR_THM; move; oriented_area] THEN CONV_TAC REAL_RING);;
let REACHABLE_INVARIANT = prove
(`!p p'. reachable p p' ==> oriented_area p = oriented_area p'`,
MATCH_MP_TAC reachable_INDUCT THEN MESON_TAC[MOVE_INVARIANT]);;
let IMPOSSIBILITY_B = prove
(`~(reachable ((&0,&0),(&3,&0),(&0,&3)) ((&1,&2),(&2,&5),(-- &2,&3)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((&1,&2),(-- &2,&3),(&2,&5)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((&2,&5),(&1,&2),(-- &2,&3)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((&2,&5),(-- &2,&3),(&1,&2)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((-- &2,&3),(&1,&2),(&2,&5)) \/
reachable ((&0,&0),(&3,&0),(&0,&3)) ((-- &2,&3),(&2,&5),(&1,&2)))`,
STRIP_TAC THEN FIRST_ASSUM(MP_TAC o MATCH_MP REACHABLE_INVARIANT) THEN
REWRITE_TAC[oriented_area] THEN REAL_ARITH_TAC);;
let init = new_definition
`init (x,y,pc1,pc2,sem) <=>
pc1 = 10 /\ pc2 = 10 /\ x = 0 /\ y = 0 /\ sem = 1`;;
let trans = new_definition
`trans (x,y,pc1,pc2,sem) (x',y',pc1',pc2',sem') <=>
pc1 = 10 /\ sem > 0 /\ pc1' = 20 /\ sem' = sem - 1 /\
(x',y',pc2') = (x,y,pc2) \/
pc2 = 10 /\ sem > 0 /\ pc2' = 20 /\ sem' = sem - 1 /\
(x',y',pc1') = (x,y,pc1) \/
pc1 = 20 /\ pc1' = 30 /\ x' = x + 1 /\
(y',pc2',sem') = (y,pc2,sem) \/
pc2 = 20 /\ pc2' = 30 /\ y' = y + 1 /\ x' = x /\
pc1' = pc1 /\ sem' = sem \/
pc1 = 30 /\ pc1' = 10 /\ sem' = sem + 1 /\
(x',y',pc2') = (x,y,pc2) \/
pc2 = 30 /\ pc2' = 10 /\ sem' = sem + 1 /\
(x',y',pc1') = (x,y,pc1)`;;
let mutex = new_definition
`mutex (x,y,pc1,pc2,sem) <=> pc1 = 10 \/ pc2 = 10`;;
let indinv = new_definition
`indinv (x:num,y:num,pc1,pc2,sem) <=>
sem + (if pc1 = 10 then 0 else 1) + (if pc2 = 10 then 0 else 1) = 1`;;
needs "Library/rstc.ml";;
let INDUCTIVE_INVARIANT = prove
(`!init invariant transition P.
(!s. init s ==> invariant s) /\
(!s s'. invariant s /\ transition s s' ==> invariant s') /\
(!s. invariant s ==> P s)
==> !s s':A. init s /\ RTC transition s s' ==> P s'`,
REPEAT GEN_TAC THEN MP_TAC(ISPECL
[`transition:A->A->bool`;
`\s s':A. invariant s ==> invariant s'`] RTC_INDUCT) THEN
MESON_TAC[]);;
let MUTEX = prove
(`!s s'. init s /\ RTC trans s s' ==> mutex s'`,
MATCH_MP_TAC INDUCTIVE_INVARIANT THEN EXISTS_TAC `indinv` THEN
REWRITE_TAC[init; trans; indinv; mutex; FORALL_PAIR_THM; PAIR_EQ] THEN
ARITH_TAC);;
|
9051cc2f86c333ddd8213c2bb5ec5a0cd3c7641602ef0326df1ac448d56a9afb | ocaml/ocaml | field_kind.ml | (* TEST
* expect
*)
type _ t = Int : int t;;
[%%expect{|
type _ t = Int : int t
|}]
let o =
object (self)
method private x = 3
method m : type a. a t -> a = fun Int -> (self#x : int)
end;;
[%%expect{|
val o : < m : 'a. 'a t -> 'a > = <obj>
|}]
let o' =
object (self : 's)
method private x = 3
method m : type a. a t -> 's -> a = fun Int other -> (other#x : int)
end;;
let aargh = assert (o'#m Int o' = 3);;
[%%expect{|
Lines 2-5, characters 2-5:
2 | ..object (self : 's)
3 | method private x = 3
4 | method m : type a. a t -> 's -> a = fun Int other -> (other#x : int)
5 | end..
Warning 15 [implicit-public-methods]: the following private methods were made public implicitly:
x.
val o' : < m : 'a. 'a t -> 'b -> 'a; x : int > as 'b = <obj>
val aargh : unit = ()
|}]
let o2 =
object (self : 's)
method private x = 3
method m : 's -> int = fun other -> (other#x : int)
end;;
[%%expect{|
Lines 2-5, characters 2-5:
2 | ..object (self : 's)
3 | method private x = 3
4 | method m : 's -> int = fun other -> (other#x : int)
5 | end..
Warning 15 [implicit-public-methods]: the following private methods were made public implicitly:
x.
val o2 : < m : 'a -> int; x : int > as 'a = <obj>
|}]
let o3 =
object (self : 's)
method private x = 3
method m : 's -> int = fun other ->
let module M = struct let other = other end in (M.other#x : int)
end;;
let aargh = assert (o3#m o3 = 3);;
[%%expect{|
Lines 2-6, characters 2-5:
2 | ..object (self : 's)
3 | method private x = 3
4 | method m : 's -> int = fun other ->
5 | let module M = struct let other = other end in (M.other#x : int)
6 | end..
Warning 15 [implicit-public-methods]: the following private methods were made public implicitly:
x.
val o3 : < m : 'a -> int; x : int > as 'a = <obj>
val aargh : unit = ()
|}]
| null | https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-objects/field_kind.ml | ocaml | TEST
* expect
|
type _ t = Int : int t;;
[%%expect{|
type _ t = Int : int t
|}]
let o =
object (self)
method private x = 3
method m : type a. a t -> a = fun Int -> (self#x : int)
end;;
[%%expect{|
val o : < m : 'a. 'a t -> 'a > = <obj>
|}]
let o' =
object (self : 's)
method private x = 3
method m : type a. a t -> 's -> a = fun Int other -> (other#x : int)
end;;
let aargh = assert (o'#m Int o' = 3);;
[%%expect{|
Lines 2-5, characters 2-5:
2 | ..object (self : 's)
3 | method private x = 3
4 | method m : type a. a t -> 's -> a = fun Int other -> (other#x : int)
5 | end..
Warning 15 [implicit-public-methods]: the following private methods were made public implicitly:
x.
val o' : < m : 'a. 'a t -> 'b -> 'a; x : int > as 'b = <obj>
val aargh : unit = ()
|}]
let o2 =
object (self : 's)
method private x = 3
method m : 's -> int = fun other -> (other#x : int)
end;;
[%%expect{|
Lines 2-5, characters 2-5:
2 | ..object (self : 's)
3 | method private x = 3
4 | method m : 's -> int = fun other -> (other#x : int)
5 | end..
Warning 15 [implicit-public-methods]: the following private methods were made public implicitly:
x.
val o2 : < m : 'a -> int; x : int > as 'a = <obj>
|}]
let o3 =
object (self : 's)
method private x = 3
method m : 's -> int = fun other ->
let module M = struct let other = other end in (M.other#x : int)
end;;
let aargh = assert (o3#m o3 = 3);;
[%%expect{|
Lines 2-6, characters 2-5:
2 | ..object (self : 's)
3 | method private x = 3
4 | method m : 's -> int = fun other ->
5 | let module M = struct let other = other end in (M.other#x : int)
6 | end..
Warning 15 [implicit-public-methods]: the following private methods were made public implicitly:
x.
val o3 : < m : 'a -> int; x : int > as 'a = <obj>
val aargh : unit = ()
|}]
|
4fb5cf22a53bd9a5d6f0f77bf30d1a9b58576185af2c1817e2c38610a0cb9765 | SNePS/SNePS2 | restr.lisp | -*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNEPS ; Base : 10 -*-
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
Version : $ I d : restr.lisp , v 1.2 2013/08/28 19:07:26 shapiro Exp $
;; This file is part of SNePS.
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Buffalo Public License Version 1.0 ( the " License " ) ; you may
;;; not use this file except in compliance with the License. You
;;; may obtain a copy of the License at
;;; . edu/sneps/Downloads/ubpl.pdf.
;;;
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 gov
;;; erning rights and limitations under the License.
;;;
The Original Code is SNePS 2.8 .
;;;
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
;;;
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :sneps)
; ==============================================================================
; addrestr
; --------
;
; arguments : r - <context set>
; c - <context>
;
; returns : <context>
;
; description : It adds the context "r" to the restriction slot of
; context "c".
;
;
; written : njm 09/14/88
; modified:
;
;
(defmacro addrestr (r c)
"It adds the context 'r' to the restriction slot of context 'c'.
Returns the context 'c'."
`(prog2 (setf (context-restriction ,c)
(sigma (union.cts ,r (context-restriction ,c))))
,c))
;
; =============================================================================
; DEITAR FORA ?
;
;
; newrestriction
; --------------
;
;
arguments : hyps - < node set >
;
; returns : <context set>
;
; description : Computes the restriction associated with a recently
created context defined by the assertions ' hyps ' .
; Returns the computed restriction set.
;
;
;
;
; written : jpm 12/02/82
; modified: njm 10/06/88
;
;
;
( defun newrestriction ( hyps )
( if ( null hyps )
; nil
; (sigma (psi (apply
; #'append
; (mapcar #'(lambda (n)
; (context-restriction (exists.ct (list n))))
; hyps))
( exists.ct hyps ) ) ) ) )
;
;
; =============================================================================
;
;
; psi
; ---
;
;
; arguments : fullrs - <context set>
; ct - <context>
;
; returns : <context set>
;
description : Implements the psi function of the SWM logic .
; 'fullrs' is the union of all the restrictions
; associated with the contexts defined by each
; single hypothesis of 'ct'.
;
;
;
; written : jpm 12/02/82
; modified: njm 10/06/88
;
;
;
(defun psi (fullrs ct)
(cond ((isnew.cts fullrs) (new.cts))
((issubset.ct (choose.cts fullrs) ct)
(makeone.cts (getcontext (new.ns))))
((isdisjoin (choose.cts fullrs) ct)
(insert.cts (choose.cts fullrs) (psi (others.cts fullrs) ct)))
(t (insert.cts
(fullbuildcontext (compl.ns (context-hyps (choose.cts fullrs))
(context-hyps ct))
(new.cts))
(psi (others.cts fullrs) ct)))))
;
; =============================================================================
;
;
; sigma
; -----
;
;
; arguments : ctset - <context set>
;
; returns : <context set>
;
description : Implements the sigma function of the SWM logic .
;
;
;
;
; written : jpm 12/02/82
; modified: njm 10/06/88
;
;
;
(defun sigma (ctset)
(let ((empty (getcontext (new.ns))))
(if (ismemb.cts empty ctset)
(makeone.cts empty)
(sigma-1 ctset ctset))))
(defun sigma-1 (wset oset)
(cond ((isnew.cts wset) (new.cts))
((existsubset (choose.cts wset) oset)
(sigma-1 (others.cts wset) oset))
(t (insert.cts (choose.cts wset) (sigma-1 (others.cts wset) oset)))))
;
; =============================================================================
;
;
; existsubset
; -----------
;
;
; arguments : c - <context>
; cs - <context set>
;
; returns : <boolean>
;
; description : Returns T if 'c' is a superset of any context
; present in 'cs', NIL otherwise.
;
;
;
;
; written : jpm 12/02/82
; modified: njm 10/06/88
;
;
;
(defun existsubset (c cs)
(cond ((isnew.cts cs) nil)
((and (issubset.ct (choose.cts cs) c)
(not (iseq.ct c (choose.cts cs)))) t)
(t (existsubset c (others.cts cs)))))
;
; =============================================================================
;
;
; isdisjoin
; ---------
;
;
; arguments : c1 - <context>
; c2 - <context>
;
; returns : <boolean>
;
; description : Returns T if 'c1' and 'c2' have not any hypothesis in
; common, NIL otherwise.
;
;
;
;
; written : jpm 12/02/82
; modified: njm 10/06/88
;
;
;
(defun isdisjoin (c1 c2)
(isnew.cts (intersect.ns (context-hyps c1) (context-hyps c2))))
;
; =============================================================================
;
;
; updateall
; ---------
;
;
; arguments : ct - <context>
;
; returns : ???
;
; description : 'ct' is an inconsistent context. This function upadtes
; the restriction sets of all contexts with this information.
;
;
;
;
written : mrc 10/20/88
;
;
;
(defun updateall (ct)
(updateall-1 ct (allct)))
(defun updateall-1 (ct cts)
(cond ((isnew.cts cts) t)
((isdisjoin ct (choose.cts cts)) (addrestr (makeone.cts ct) (choose.cts cts))
(updateall-1 ct (others.cts cts)))
(t (updateall-1 ct (others.cts cts)))))
| null | https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/sneps/fns/restr.lisp | lisp | Syntax : Common - Lisp ; Package : SNEPS ; Base : 10 -*-
This file is part of SNePS.
you may
not use this file except in compliance with the License. You
may obtain a copy of the License at
. edu/sneps/Downloads/ubpl.pdf.
or implied. See the License for the specific language gov
erning rights and limitations under the License.
==============================================================================
addrestr
--------
arguments : r - <context set>
c - <context>
returns : <context>
description : It adds the context "r" to the restriction slot of
context "c".
written : njm 09/14/88
modified:
=============================================================================
DEITAR FORA ?
newrestriction
--------------
returns : <context set>
description : Computes the restriction associated with a recently
Returns the computed restriction set.
written : jpm 12/02/82
modified: njm 10/06/88
nil
(sigma (psi (apply
#'append
(mapcar #'(lambda (n)
(context-restriction (exists.ct (list n))))
hyps))
=============================================================================
psi
---
arguments : fullrs - <context set>
ct - <context>
returns : <context set>
'fullrs' is the union of all the restrictions
associated with the contexts defined by each
single hypothesis of 'ct'.
written : jpm 12/02/82
modified: njm 10/06/88
=============================================================================
sigma
-----
arguments : ctset - <context set>
returns : <context set>
written : jpm 12/02/82
modified: njm 10/06/88
=============================================================================
existsubset
-----------
arguments : c - <context>
cs - <context set>
returns : <boolean>
description : Returns T if 'c' is a superset of any context
present in 'cs', NIL otherwise.
written : jpm 12/02/82
modified: njm 10/06/88
=============================================================================
isdisjoin
---------
arguments : c1 - <context>
c2 - <context>
returns : <boolean>
description : Returns T if 'c1' and 'c2' have not any hypothesis in
common, NIL otherwise.
written : jpm 12/02/82
modified: njm 10/06/88
=============================================================================
updateall
---------
arguments : ct - <context>
returns : ???
description : 'ct' is an inconsistent context. This function upadtes
the restriction sets of all contexts with this information.
|
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
Version : $ I d : restr.lisp , v 1.2 2013/08/28 19:07:26 shapiro Exp $
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
The Original Code is SNePS 2.8 .
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :sneps)
(defmacro addrestr (r c)
"It adds the context 'r' to the restriction slot of context 'c'.
Returns the context 'c'."
`(prog2 (setf (context-restriction ,c)
(sigma (union.cts ,r (context-restriction ,c))))
,c))
arguments : hyps - < node set >
created context defined by the assertions ' hyps ' .
( defun newrestriction ( hyps )
( if ( null hyps )
( exists.ct hyps ) ) ) ) )
description : Implements the psi function of the SWM logic .
(defun psi (fullrs ct)
(cond ((isnew.cts fullrs) (new.cts))
((issubset.ct (choose.cts fullrs) ct)
(makeone.cts (getcontext (new.ns))))
((isdisjoin (choose.cts fullrs) ct)
(insert.cts (choose.cts fullrs) (psi (others.cts fullrs) ct)))
(t (insert.cts
(fullbuildcontext (compl.ns (context-hyps (choose.cts fullrs))
(context-hyps ct))
(new.cts))
(psi (others.cts fullrs) ct)))))
description : Implements the sigma function of the SWM logic .
(defun sigma (ctset)
(let ((empty (getcontext (new.ns))))
(if (ismemb.cts empty ctset)
(makeone.cts empty)
(sigma-1 ctset ctset))))
(defun sigma-1 (wset oset)
(cond ((isnew.cts wset) (new.cts))
((existsubset (choose.cts wset) oset)
(sigma-1 (others.cts wset) oset))
(t (insert.cts (choose.cts wset) (sigma-1 (others.cts wset) oset)))))
(defun existsubset (c cs)
(cond ((isnew.cts cs) nil)
((and (issubset.ct (choose.cts cs) c)
(not (iseq.ct c (choose.cts cs)))) t)
(t (existsubset c (others.cts cs)))))
(defun isdisjoin (c1 c2)
(isnew.cts (intersect.ns (context-hyps c1) (context-hyps c2))))
written : mrc 10/20/88
(defun updateall (ct)
(updateall-1 ct (allct)))
(defun updateall-1 (ct cts)
(cond ((isnew.cts cts) t)
((isdisjoin ct (choose.cts cts)) (addrestr (makeone.cts ct) (choose.cts cts))
(updateall-1 ct (others.cts cts)))
(t (updateall-1 ct (others.cts cts)))))
|
1012d7f3c6c66ebe414a620557a22de3e12f4a464ff36fed7b9a7e2a0b33b1e0 | CrossRef/event-data-query | work_cache_test.clj | (ns event-data-query.work-cache-test
(:require [clojure.test :refer :all]
[event-data-query.work-cache :as work-cache]
[clj-http.fake :as fake]
[qbits.spandex :as s]
[event-data-query.elastic :as elastic]
[slingshot.slingshot :refer [try+]]
[config.core :refer [env]]))
(deftest doi->id
(testing "The same DOI expressed different ways results in the same cache ID.
Case-insentitivity is not desired."
(is (=
(work-cache/doi->id "10.5555/12345678abc")
(work-cache/doi->id "doi:10.5555/12345678abc")
(work-cache/doi->id "doi.org/10.5555/12345678abc")
(work-cache/doi->id "")))))
(deftest get-for-dois-mixed-input
(testing "get-for-dois can cope with nils, dois and non-dois"
(try
(:status (s/request @elastic/connection {:url @work-cache/index-id :method :delete}))
(catch Exception _))
(work-cache/ensure-index)
(fake/with-fake-routes-in-isolation
{
; Fake lookups for RA
"-9006%2899%2900007-0"
(fn [request] {:status 200 :body "[{\"DOI\": \"10.1016/s0305-9006(99)00007-0\", \"RA\": \"Crossref\"}]"})
"-doi-but-not-crossref-api"
(fn [request] {:status 200 :body "[{\"DOI\": \"10.5555/in-doi-but-not-crossref-api\", \"RA\": \"Crossref\"}]"})
"-30455"
(fn [request] {:status 200 :body "[{\"DOI\": \"10.5167/uzh-30455\",\"RA\": \"DataCite\"}]"})
doiRA uses 200 to report a missing DOI . Not 400 or 404 .
""
(fn [request] {:status 200 :body "[{\"DOI\": \"10.999999/999999999999999999999999999999999999\",\"status\": \"DOI does not exist\"}]"})
"-9006%2899%2900007-0?mailto="
(fn [request] {:status 200 :body "{\"message\": {\"type\": \"journal-article\"}}"})
This one 's in the DOI system , but is missing from the REST API for some reason .
"-doi-but-not-crossref-api?mailto="
(fn [request] {:status 404})
"-30455?include=resource-type"
(fn [request] {:status 200 :body "{\"data\": {\"attributes\": {\"resource-type-id\": \"text\"}}}"})}
(let [inputs
; Nil may find its way here.
[nil
; We could find any nonsense in a subj-id or obj-id field.
"blah"
; We could find non-DOI urls.
""
Non - URL form Crossref
"10.1016/s0305-9006(99)00007-0"
URL - form DataCite
"-30455"
; Non-existent
"10.999999/999999999999999999999999999999999999"
In the DOI API but the Crossref API does n't have it .
"10.5555/in-doi-but-not-crossref-api"]
result (work-cache/get-for-dois inputs)]
(is (= result
Non - DOI has empty response .
nil
nil
""
nil
Non - DOI has empty response .
"blah"
nil
DOI - looking , but non - existent , has empty response .
Explicitly returning nil in this case ensures we do n't get a false - negative in future e.g. if the DOI is subsequently registered .
"10.999999/999999999999999999999999999999999999"
nil
Non - URL DOI returned OK .
"10.1016/s0305-9006(99)00007-0"
{:content-type "journal-article"
:ra :crossref
:doi "10.1016/s0305-9006(99)00007-0"}
URL DOI returned OK with correct info .
DOI is normalized to non - url , lower - case form .
"-30455"
{:content-type "text"
:ra :datacite
:doi "10.5167/uzh-30455"}
"10.5555/in-doi-but-not-crossref-api"
nil}))))))
| null | https://raw.githubusercontent.com/CrossRef/event-data-query/ede3c91afccd89dbb7053e81dd425bc3c3ad966a/test/event_data_query/work_cache_test.clj | clojure | Fake lookups for RA
Nil may find its way here.
We could find any nonsense in a subj-id or obj-id field.
We could find non-DOI urls.
Non-existent | (ns event-data-query.work-cache-test
(:require [clojure.test :refer :all]
[event-data-query.work-cache :as work-cache]
[clj-http.fake :as fake]
[qbits.spandex :as s]
[event-data-query.elastic :as elastic]
[slingshot.slingshot :refer [try+]]
[config.core :refer [env]]))
(deftest doi->id
(testing "The same DOI expressed different ways results in the same cache ID.
Case-insentitivity is not desired."
(is (=
(work-cache/doi->id "10.5555/12345678abc")
(work-cache/doi->id "doi:10.5555/12345678abc")
(work-cache/doi->id "doi.org/10.5555/12345678abc")
(work-cache/doi->id "")))))
(deftest get-for-dois-mixed-input
(testing "get-for-dois can cope with nils, dois and non-dois"
(try
(:status (s/request @elastic/connection {:url @work-cache/index-id :method :delete}))
(catch Exception _))
(work-cache/ensure-index)
(fake/with-fake-routes-in-isolation
{
"-9006%2899%2900007-0"
(fn [request] {:status 200 :body "[{\"DOI\": \"10.1016/s0305-9006(99)00007-0\", \"RA\": \"Crossref\"}]"})
"-doi-but-not-crossref-api"
(fn [request] {:status 200 :body "[{\"DOI\": \"10.5555/in-doi-but-not-crossref-api\", \"RA\": \"Crossref\"}]"})
"-30455"
(fn [request] {:status 200 :body "[{\"DOI\": \"10.5167/uzh-30455\",\"RA\": \"DataCite\"}]"})
doiRA uses 200 to report a missing DOI . Not 400 or 404 .
""
(fn [request] {:status 200 :body "[{\"DOI\": \"10.999999/999999999999999999999999999999999999\",\"status\": \"DOI does not exist\"}]"})
"-9006%2899%2900007-0?mailto="
(fn [request] {:status 200 :body "{\"message\": {\"type\": \"journal-article\"}}"})
This one 's in the DOI system , but is missing from the REST API for some reason .
"-doi-but-not-crossref-api?mailto="
(fn [request] {:status 404})
"-30455?include=resource-type"
(fn [request] {:status 200 :body "{\"data\": {\"attributes\": {\"resource-type-id\": \"text\"}}}"})}
(let [inputs
[nil
"blah"
""
Non - URL form Crossref
"10.1016/s0305-9006(99)00007-0"
URL - form DataCite
"-30455"
"10.999999/999999999999999999999999999999999999"
In the DOI API but the Crossref API does n't have it .
"10.5555/in-doi-but-not-crossref-api"]
result (work-cache/get-for-dois inputs)]
(is (= result
Non - DOI has empty response .
nil
nil
""
nil
Non - DOI has empty response .
"blah"
nil
DOI - looking , but non - existent , has empty response .
Explicitly returning nil in this case ensures we do n't get a false - negative in future e.g. if the DOI is subsequently registered .
"10.999999/999999999999999999999999999999999999"
nil
Non - URL DOI returned OK .
"10.1016/s0305-9006(99)00007-0"
{:content-type "journal-article"
:ra :crossref
:doi "10.1016/s0305-9006(99)00007-0"}
URL DOI returned OK with correct info .
DOI is normalized to non - url , lower - case form .
"-30455"
{:content-type "text"
:ra :datacite
:doi "10.5167/uzh-30455"}
"10.5555/in-doi-but-not-crossref-api"
nil}))))))
|
4d02b5dfe45a8a064c020b59da44ebb2db4e3ed2a1bbac5e0caea5ca00f184fc | nikita-volkov/rebase | Types.hs | module Rebase.GHC.IO.Encoding.Types
(
module GHC.IO.Encoding.Types
)
where
import GHC.IO.Encoding.Types
| null | https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/GHC/IO/Encoding/Types.hs | haskell | module Rebase.GHC.IO.Encoding.Types
(
module GHC.IO.Encoding.Types
)
where
import GHC.IO.Encoding.Types
| |
ecbc5f2c6ce0a6a145a55f487ea394f1a6769a83fdfd30e6657ce56933537f7a | simedw/Kandidat | Interpreter.hs | {-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PackageImports #-}
# LANGUAGE ViewPatterns #
# LANGUAGE RecordWildCards #
module Stg.Interpreter where
interpreter
import Control.Monad
import "mtl" Control.Monad.State
import Data.Char
import "syb" Data.Generics
import Data.Maybe
import Data . )
import qualified Data . Map as M
import Data.Map(Map)
import qualified Data.Map as M
-}
import Stg.AST
import Stg.GC
import Stg.Input
import Stg.Variable
import Stg.Stack
import Stg.Optimise
import Stg.Rules
import Stg.Substitution
import Stg.Types
import Stg.Branch
import Stg.Heap (Heap, Location(..))
import Shared.Primitives
import qualified Stg.Heap as H
topCase :: ContStack t -> Bool
topCase (CtCase _ : _) = True
topCase _ = False
topArg :: ContStack t -> Bool
topArg (CtArg _ : _) = True
topArg _ = False
topUpd :: ContStack t -> Bool
topUpd (CtUpd _ : _) = True
topUpd (CtOUpd _ : _) = True
topUpd _ = False
topOpt :: ContStack t -> Bool
topOpt (CtOpt _ : _) = True
topOpt _ = False
topPrint :: ContStack t -> Bool
topPrint (CtPrint : _) = True
topPrint _ = False
topPrintCon :: ContStack t -> Bool
topPrintCon (CtPrintCon _ _ _ : _) = True
topPrintCon _ = False
topIsO :: ContStack t -> Bool
topIsO (cont : _) = case cont of
CtOFun _ _ _ -> True
CtOCase _ -> True
CtOLet _ -> True
CtOBranch{} -> True
CtOApp _ _ -> True
_ -> False
topIsO _ = False
topOInstant :: ContStack t -> Bool
topOInstant (CtOInstant n: _) = n <= 0
topOInstant _ = False
decTop :: ContStack t -> ContStack t
decTop (CtOInstant n : xs) = CtOInstant (n-1) : xs
decTop xs = xs
numArgs :: ContStack t -> Int
numArgs = length . takeWhile isArg
where
isArg (CtArg _) = True
isArg _ = False
unArg :: Show t => Cont t -> Atom t
unArg (CtArg a) = a
unArg o = error $ "unArg: not an arg: " ++ show o
initialState :: Variable t => [Function t] -> StgState t
initialState funs = StgState
{ code = mainF
, cstack = [CtPrint]
, astack = newFrame []
, heap = initialHeap funs
, settings = []
} where
(mainF, size) = getMain funs
--initialNames :: [String]
--initialNames = map ("i." ++) $ [1..] >>= flip replicateM ['a'..'z']
initialStgMState :: Variable t => StgMState t
initialStgMState = StgMState
{ nameSupply = namesupply
, mkCons = mkcons --- is this really needed?
}
getMain :: Variable t => [Function t] -> (Expr t, Int)
getMain = getFunction mainFunction
getFunction :: Variable t => t -> [Function t] -> (Expr t, Int)
getFunction s ((Function name o):xs) | s == name = let OThunk [] size c = o in (c, size)
| otherwise = getFunction s xs
getFunction s [] = error $ "No \"" ++ show s ++ "\" function"
initialHeap :: Variable t => [Function t] -> Heap t
initialHeap = H.fromList . map (\(Function name obj) -> (name, obj))
step :: Variable t => StgState t -> StgM t (Maybe (Rule, StgState t))
step st@(OmegaState {..}) = omega' cstack astack heap code settings
step st@(IrrState {..}) = irr' cstack astack heap code settings
step st@(PsiState {..}) = case code of
EAtom code -> psi' cstack astack heap code letBinds settings
step st@(StgState {..}) = step' $ st {cstack = decTop cstack}
where
step' st'@(StgState {..}) = case code of
_ | topOInstant cstack -> omega (ROmega "from machine after OInstant")
(drop 1 cstack) astack heap code settings -- for inlining
ECase expr branch -> case expr of
EAtom a -> case lookupAtom a of
a'@(AVar (Heap var)) -> case H.lookup var heap of
Nothing -> error "var not in heap (maybe on abyss)" -- return Nothing
Just (OThunk _ _ _) -> rcase expr branch
Just (OCon c atoms) -> case instantiateBranch c atoms branch of
Nothing -> rany expr a' branch
lagg till atoms
rcasecon st atoms expr
_ -> rany expr a' branch
_ -> rany expr a branch
_ -> rcase expr branch
ELet defs exp -> rlet st defs exp
EPop op args -> rprimop st op args
ECall ident args -> rpush st ident args
EAtom a
-- Top is a I# 2, but we should save it in a thunk
| not (isVar a) && topUpd cstack -> rupdate st (OThunk [] 0 code)
| not (isVar (lookupAtom a)) && topCase cstack -> rret st
| not (isVar (lookupAtom a)) && topPrint cstack -> rprintval st a
| not (isVar (lookupAtom a)) && topIsO cstack
-> psi (RPsi "Machine found atom and can continue to optimise")
cstack (popFrame astack) heap (lookupAtom a) [] settings
EAtom a -> case lookupAtom a of
(AVar (Heap var)) -> case H.lookup var heap of
Nothing -> return Nothing
Just obj -> case obj of
OThunk fv size expr -> rthunk st (map lookupAtom fv) size expr var
_ | topIsO cstack
-> psi (RPsi "machine found non-thunk, continue optimise")
cstack (popFrame astack) heap (lookupAtom a) [] settings
OOpt alpha sets -> roptimise st alpha sets var
_ | topUpd cstack -> rupdate st obj
_ | topCase cstack -> rret st
-- _ | topContOpt stack -> rcontopt st
OCon t atoms | topPrint cstack -> rprintcon st t atoms
_ | topPrintCon cstack -> rprintfun st
OPap ident atoms | topArg cstack -> rpenter st ident atoms
| topOpt cstack -> roptpap st ident atoms
OFun args size expr
| topOpt cstack -> roptfun st args size expr
| otherwise ->
let lenArgs = length args
stackArgs = numArgs cstack
-- depending on the number of arguments the function is either
-- saturated or not
in case lenArgs <= stackArgs of
True -> rfenter st args lenArgs size expr
False -> rpap st stackArgs var
_ | topOpt cstack -> rupdateopt st obj (Heap var)
_ -> return Nothing
s -> error $ show s
ESVal sval | topPrintCon cstack -> rprintcont st sval
-- if there is no rule to apply, do nothing
_ -> return Nothing
where
lookupAtom (AVar v) = case v of
Heap x -> AVar v
Local x _ -> lookupStackFrame x astack
det har ar farligt
for det kan vara i en
lookupAtom (AUnknown i t) = lookupStackFrame i astack
lookupAtom a = a
allocObj o = case o of
OCon c atoms -> OCon c (map lookupAtom atoms)
OThunk fv s exp -> OThunk (map lookupAtom fv) s exp
OPap t atoms -> OPap t (map lookupAtom atoms)
OOpt alpha set -> OOpt (lookupAtom alpha) set
_ -> o
st = st' { cstack = cstack }
rlet st@(StgState { .. } ) = do
vars < - replicateM ( length ( ) ) newVar
let ids = map fst ( )
code'@(ELet defs ' e ' ) = substList ids ( map AVar vars ) code
objs = map snd $ ( )
heap ' = foldr ( \(v , o ) h - > H.insert v o h ) heap ( zip vars objs )
returnJust ( RLet , st { code = e '
, heap = heap ' } )
rlet st@(StgState {..}) defs = do
vars <- replicateM (length (getBinds defs)) newVar
let ids = map fst (getBinds defs)
code'@(ELet defs' e') = substList ids (map AVar vars) code
objs = map snd $ (getBinds defs')
heap' = foldr (\(v,o) h -> H.insert v o h) heap (zip vars objs)
returnJust (RLet, st { code = e'
, heap = heap' })
-}
rlet st@(StgState {..}) (NonRec t obj) e = do
var <- newVar
let astack' = pushArgs [AVar $ Heap var] astack
heap' = H.insert var (allocObj obj) heap
returnJust (RLet, st { code = e
, heap = heap'
, astack = astack'})
rlet st@(StgState {..}) (Rec list) e = do
vars <- replicateM (length list) newVar
let astack' = pushArgs (map (AVar . Heap) vars) astack
objs = map (allocObjRec vars . snd) list
heap' = foldr (\(var,obj) heap -> H.insert var obj heap) heap (zip vars objs)
returnJust (RLet, st { code = e
, heap = heap'
, astack = astack'})
where
allocObjRec v o = case o of
OThunk fv s exp -> OThunk (map (AVar . Heap) v
++ map lookupAtom (drop (length v) fv)) s exp
_ -> o
-- fixed
rcase expr branch = returnJust
(RCaseCon
, st { code = expr
, cstack = CtCase branch : cstack
, astack = duplicateFrame astack
}
)
-- fixed
rany (EAtom var) defvar branch = case findDefaultBranch (lookupAtom var) branch of
Nothing -> return Nothing
Just expr' -> returnJust
( RCaseAny
, st { code = expr'
, astack = pushArgs [defvar] astack
}
)
-- fixed
rcasecon st@(StgState {..}) atoms expr = returnJust
( RCaseCon
, st { code = expr
, astack = pushArgs atoms astack
}
)
-- fixed
rprimop st op args = do
returnJust
( RPrimOP
, st { code = applyPrimOp op (map lookupAtom args) }
)
-- fixed
rpush st@(StgState {..}) ident args = returnJust
(RPush
, st { code = EAtom (AVar ident)
, cstack = map (CtArg . lookupAtom) args ++ cstack})
-- fixed
rret st@(StgState {..}) =
let CtCase bs : rest = cstack
EAtom a = code
in returnJust
( RRet
, st { code = ECase (EAtom $ lookupAtom a) bs
, cstack = rest
, astack = popFrame astack})
intressant ,
rthunk st@(StgState {..}) as size e v = returnJust
( RThunk
, st { code = e
, cstack = CtUpd v : cstack
, astack = pushArgs as $ callFrame astack
, heap = H.insert v OBlackhole heap})
-- fixad
rupdate st@(StgState {..}) obj = case cstack of
CtUpd x : res -> returnJust
( RUpdate
, st { cstack = res
, heap = H.insert x obj heap})
CtOUpd x : res -> returnJust
( RUpdate
, st { cstack = res
, heap = H.insertAbyss x obj heap})
-- fixed
rfenter st@(StgState {..}) args lenArgs size e = do
let args' = map unArg $ take lenArgs cstack
args '' < - replicateM lenArgs newVar
okey this is the thing ...
if we just subst names can clash = > bad :/
please if you can read this , save , you are our last hope
if we just subst names can clash => bad :/
please if you can read this, save us callstack, you are our last hope
-}
returnJust
( RFEnter
, st { code = e
, cstack = drop lenArgs cstack
, astack = pushArgs args' (callFrame astack) })
-- fixed
rpap st@(StgState {..}) stackArgs var = do
p <- newVar
let args' = map (lookupAtom . unArg) $ take stackArgs cstack
pap = OPap var args'
returnJust ( RPap1
, st { code = EAtom (AVar (Heap p))
, cstack = drop stackArgs cstack
, heap = H.insert p pap heap }
)
-- fixed
rpenter st@(StgState {..}) var atoms = returnJust
( RPEnter
, st { code = EAtom (AVar (Heap var))
, cstack = map CtArg atoms ++ cstack
})
roptimise st@(StgState {..}) omeg sets alpha =
returnJust
( ROptimise
, st
{ code = EAtom omeg
, cstack = CtOpt alpha : cstack
, heap = H.insert alpha OBlackhole heap
, settings = makeSettings astack heap sets : settings
}
)
roptpap st@(StgState {..}) var atoms =
case H.lookup var heap of
Nothing -> error $ "OPTPAP: var not in heap: " -- ++ var
Just (OFun args i e) ->
let (argsA, argsL) = splitAt (length atoms) args
CtOpt alpha : stack' = cstack
astack' = pushArgs (zipWith AUnknown [0..] argsL) (newFrame astack)
e ' = subtractLocal var ( length atoms ) $ substList argsA ( map lookupAtom atoms ) e
in omega ROptPap (CtOFun argsL (i - length atoms) alpha:stack') astack' heap (inltM atoms 0 e) settings
_ -> error "OPTPAP: pap doesn't point to FUN"
roptfun st@(StgState {..}) args i expr = do
let CtOpt alpha : cstack' = cstack
astack' = pushArgs (zipWith AUnknown [0..] args) (newFrame astack)
omega (ROmega "from machine found fun to optimise") (CtOFun args i alpha : cstack') astack' heap expr settings
rcontopt st@(StgState { .. } ) = do
let CtContOpt alpha : cstack ' = cstack
case alpha heap of
Nothing - > error $ " ContOpt rule : alpha not in heap buh huh : " + + show alpha
Just obj - > omega alpha cstack ' heap obj
let CtContOpt alpha : cstack' = cstack
case H.lookup alpha heap of
Nothing -> error $ "ContOpt rule: alpha not in heap buh huh: " ++ show alpha
Just obj -> omega alpha cstack' heap obj
-}
rupdateopt st@(StgState {..}) obj var = do
let CtOpt alpha : cstack' = cstack
returnJust
( RUpdateOpt
, st
{ code = EAtom (AVar var)
, cstack = cstack'
, heap = H.insert alpha obj heap
}
)
rprintcon st@(StgState {..}) c atoms = do
let CtPrint : cstack' = cstack
case null atoms of
True -> returnJust
( RPrintCon
, st
{ code = ESVal (SCon c [])
, cstack = cstack'})
False -> returnJust
( RPrintCon
, st
{ code = EAtom (head atoms)
, cstack = CtPrint : CtPrintCon c [] (tail atoms) : cstack'})
rprintval st@(StgState {..}) atom = do
let CtPrint : cstack' = cstack
returnJust
( RPrintVal
, st
{ code = ESVal (SAtom (lookupAtom atom))
, cstack = cstack'})
rprintfun st@(StgState {..}) = do
let CtPrint : cstack' = cstack
returnJust
( RPrintFun
, st
{ code = ESVal SFun
, cstack = cstack'})
rprintcont st@(StgState {..}) sval = do
let CtPrintCon c ps ns : cstack' = cstack
case ns of
[] -> returnJust
( RPrintCont
, st
{ code = ESVal (SCon c (reverse (sval:ps)))
, cstack = cstack'})
n : ns -> returnJust
( RPrintCont
, st
{ code = EAtom n
, cstack = CtPrint : CtPrintCon c (sval:ps) ns : cstack'})
-- if we find anything that is point to a OThunk
-- we try to evalutate it
force st@(StgState { .. } ) = do
res < - step case res of
Nothing - > case code of
( EAtom var ) | AVar ( Heap v ) < - lookupAtom var - > case v heap of
Nothing - > return $ show v
Just ( OThunk expr ) - > force ( st { code = expr } )
Just ( OCon t [ ] ) - > return t
Just ( OCon t atoms )
- > do list < - mapM ( \x - > force ( st { code = EAtom x } ) ) atoms
return $ " ( " + + t + + " " + + concat ( space list ) + + " ) "
( EAtom ( ANum n ) ) - > return $ show n
other - > return $ show other
Just ( r , st ' ) - > force st '
where
space xs = let len = length xs - 1
in map ( + + " " ) ( take len xs ) + + drop len xs
-- start the force evaluation
-- actually quite ugly
runForce : : Variable t = > Input - > [ Function t ] - > t
runForce inp funs = evalStgM ( go st ) initialStgMState
where
gc = mkGC $ map mkcons $ [ trueCon , falseCon ]
st = gc ( createGetFuns inp + + funs )
go st = do
res < - step st
case res of
Nothing - > force st
Just ( r , st ' ) - > go st '
-- if we find anything that is point to a OThunk
-- we try to evalutate it
force st@(StgState {..}) = do
res <- step st
case res of
Nothing -> case code of
(EAtom var) | AVar (Heap v) <- lookupAtom var -> case H.lookup v heap of
Nothing -> return $ show v
Just (OThunk expr) -> force (st {code = expr})
Just (OCon t []) -> return t
Just (OCon t atoms)
-> do list <- mapM (\x -> force (st {code = EAtom x})) atoms
return $ "(" ++ t ++ " " ++ concat (space list) ++ ")"
(EAtom (ANum n)) -> return $ show n
other -> return $ show other
Just (r, st') -> force st'
where
space xs = let len = length xs - 1
in map (++" ") (take len xs) ++ drop len xs
-- start the force evaluation
-- actually quite ugly
runForce :: Variable t => Input -> [Function t] -> t
runForce inp funs = evalStgM (go st) initialStgMState
where
gc = mkGC $ map mkcons $ [trueCon, falseCon]
st = gc $ initialState (createGetFuns inp ++ funs)
go st = do
res <- step st
case res of
Nothing -> force st
Just (r, st') -> go st'
-}
eval :: Variable t => [Function t] -> [(Rule, StgState t)]
eval funs = (RInitial, st) : evalStgM (go st) initialStgMState
where
gc = mkGC $ map mkcons $ [trueCon, falseCon]
st = gc $ initialState funs
go st = do
res <- step st
case res of
Nothing -> return []
Just (r, st') -> ((r, st') :) `fmap` go ({-gc-} st')
applyPrimOp :: Variable t => Primitive t -> [Atom t] -> Expr t
applyPrimOp op args = case (op,args) of
(IntOp {intOp = (+)}, [ANum x,ANum y]) -> EAtom $ ANum $ x + y
(IntCmp{intCmp = (+)}, [ANum x,ANum y]) -> EAtom $ avar $ x + y
(DblOp {dblOp = (+)}, [ADec x,ADec y]) -> EAtom $ ADec $ x + y
(DblCmp{dblCmp = (+)}, [ADec x,ADec y]) -> EAtom $ avar $ x + y
(ChrCmp{chrCmp = (+)}, [AChr x,AChr y]) -> EAtom $ avar $ x + y
(MathFun{mathFun = f}, [ADec x]) -> EAtom $ ADec $ f x
_ -> err
where
avar = AVar . Heap . boolToCon
err =
error $ "applyPrimOp: Primitive operation ("
++ show op
++ ") applied to arguments of the wrong type "
++ "( " ++ show args ++ ")"
++ ", or not the correct number of arguments."
| null | https://raw.githubusercontent.com/simedw/Kandidat/fbf68edf5b003aba2ce13dac32ee1b94172d57d8/src/Stg/Interpreter.hs | haskell | # LANGUAGE NamedFieldPuns #
# LANGUAGE PackageImports #
initialNames :: [String]
initialNames = map ("i." ++) $ [1..] >>= flip replicateM ['a'..'z']
- is this really needed?
for inlining
return Nothing
Top is a I# 2, but we should save it in a thunk
_ | topContOpt stack -> rcontopt st
depending on the number of arguments the function is either
saturated or not
if there is no rule to apply, do nothing
fixed
fixed
fixed
fixed
fixed
fixed
fixad
fixed
fixed
fixed
++ var
if we find anything that is point to a OThunk
we try to evalutate it
start the force evaluation
actually quite ugly
if we find anything that is point to a OThunk
we try to evalutate it
start the force evaluation
actually quite ugly
gc | # LANGUAGE ViewPatterns #
# LANGUAGE RecordWildCards #
module Stg.Interpreter where
interpreter
import Control.Monad
import "mtl" Control.Monad.State
import Data.Char
import "syb" Data.Generics
import Data.Maybe
import Data . )
import qualified Data . Map as M
import Data.Map(Map)
import qualified Data.Map as M
-}
import Stg.AST
import Stg.GC
import Stg.Input
import Stg.Variable
import Stg.Stack
import Stg.Optimise
import Stg.Rules
import Stg.Substitution
import Stg.Types
import Stg.Branch
import Stg.Heap (Heap, Location(..))
import Shared.Primitives
import qualified Stg.Heap as H
topCase :: ContStack t -> Bool
topCase (CtCase _ : _) = True
topCase _ = False
topArg :: ContStack t -> Bool
topArg (CtArg _ : _) = True
topArg _ = False
topUpd :: ContStack t -> Bool
topUpd (CtUpd _ : _) = True
topUpd (CtOUpd _ : _) = True
topUpd _ = False
topOpt :: ContStack t -> Bool
topOpt (CtOpt _ : _) = True
topOpt _ = False
topPrint :: ContStack t -> Bool
topPrint (CtPrint : _) = True
topPrint _ = False
topPrintCon :: ContStack t -> Bool
topPrintCon (CtPrintCon _ _ _ : _) = True
topPrintCon _ = False
topIsO :: ContStack t -> Bool
topIsO (cont : _) = case cont of
CtOFun _ _ _ -> True
CtOCase _ -> True
CtOLet _ -> True
CtOBranch{} -> True
CtOApp _ _ -> True
_ -> False
topIsO _ = False
topOInstant :: ContStack t -> Bool
topOInstant (CtOInstant n: _) = n <= 0
topOInstant _ = False
decTop :: ContStack t -> ContStack t
decTop (CtOInstant n : xs) = CtOInstant (n-1) : xs
decTop xs = xs
numArgs :: ContStack t -> Int
numArgs = length . takeWhile isArg
where
isArg (CtArg _) = True
isArg _ = False
unArg :: Show t => Cont t -> Atom t
unArg (CtArg a) = a
unArg o = error $ "unArg: not an arg: " ++ show o
initialState :: Variable t => [Function t] -> StgState t
initialState funs = StgState
{ code = mainF
, cstack = [CtPrint]
, astack = newFrame []
, heap = initialHeap funs
, settings = []
} where
(mainF, size) = getMain funs
initialStgMState :: Variable t => StgMState t
initialStgMState = StgMState
{ nameSupply = namesupply
}
getMain :: Variable t => [Function t] -> (Expr t, Int)
getMain = getFunction mainFunction
getFunction :: Variable t => t -> [Function t] -> (Expr t, Int)
getFunction s ((Function name o):xs) | s == name = let OThunk [] size c = o in (c, size)
| otherwise = getFunction s xs
getFunction s [] = error $ "No \"" ++ show s ++ "\" function"
initialHeap :: Variable t => [Function t] -> Heap t
initialHeap = H.fromList . map (\(Function name obj) -> (name, obj))
step :: Variable t => StgState t -> StgM t (Maybe (Rule, StgState t))
step st@(OmegaState {..}) = omega' cstack astack heap code settings
step st@(IrrState {..}) = irr' cstack astack heap code settings
step st@(PsiState {..}) = case code of
EAtom code -> psi' cstack astack heap code letBinds settings
step st@(StgState {..}) = step' $ st {cstack = decTop cstack}
where
step' st'@(StgState {..}) = case code of
_ | topOInstant cstack -> omega (ROmega "from machine after OInstant")
ECase expr branch -> case expr of
EAtom a -> case lookupAtom a of
a'@(AVar (Heap var)) -> case H.lookup var heap of
Just (OThunk _ _ _) -> rcase expr branch
Just (OCon c atoms) -> case instantiateBranch c atoms branch of
Nothing -> rany expr a' branch
lagg till atoms
rcasecon st atoms expr
_ -> rany expr a' branch
_ -> rany expr a branch
_ -> rcase expr branch
ELet defs exp -> rlet st defs exp
EPop op args -> rprimop st op args
ECall ident args -> rpush st ident args
EAtom a
| not (isVar a) && topUpd cstack -> rupdate st (OThunk [] 0 code)
| not (isVar (lookupAtom a)) && topCase cstack -> rret st
| not (isVar (lookupAtom a)) && topPrint cstack -> rprintval st a
| not (isVar (lookupAtom a)) && topIsO cstack
-> psi (RPsi "Machine found atom and can continue to optimise")
cstack (popFrame astack) heap (lookupAtom a) [] settings
EAtom a -> case lookupAtom a of
(AVar (Heap var)) -> case H.lookup var heap of
Nothing -> return Nothing
Just obj -> case obj of
OThunk fv size expr -> rthunk st (map lookupAtom fv) size expr var
_ | topIsO cstack
-> psi (RPsi "machine found non-thunk, continue optimise")
cstack (popFrame astack) heap (lookupAtom a) [] settings
OOpt alpha sets -> roptimise st alpha sets var
_ | topUpd cstack -> rupdate st obj
_ | topCase cstack -> rret st
OCon t atoms | topPrint cstack -> rprintcon st t atoms
_ | topPrintCon cstack -> rprintfun st
OPap ident atoms | topArg cstack -> rpenter st ident atoms
| topOpt cstack -> roptpap st ident atoms
OFun args size expr
| topOpt cstack -> roptfun st args size expr
| otherwise ->
let lenArgs = length args
stackArgs = numArgs cstack
in case lenArgs <= stackArgs of
True -> rfenter st args lenArgs size expr
False -> rpap st stackArgs var
_ | topOpt cstack -> rupdateopt st obj (Heap var)
_ -> return Nothing
s -> error $ show s
ESVal sval | topPrintCon cstack -> rprintcont st sval
_ -> return Nothing
where
lookupAtom (AVar v) = case v of
Heap x -> AVar v
Local x _ -> lookupStackFrame x astack
det har ar farligt
for det kan vara i en
lookupAtom (AUnknown i t) = lookupStackFrame i astack
lookupAtom a = a
allocObj o = case o of
OCon c atoms -> OCon c (map lookupAtom atoms)
OThunk fv s exp -> OThunk (map lookupAtom fv) s exp
OPap t atoms -> OPap t (map lookupAtom atoms)
OOpt alpha set -> OOpt (lookupAtom alpha) set
_ -> o
st = st' { cstack = cstack }
rlet st@(StgState { .. } ) = do
vars < - replicateM ( length ( ) ) newVar
let ids = map fst ( )
code'@(ELet defs ' e ' ) = substList ids ( map AVar vars ) code
objs = map snd $ ( )
heap ' = foldr ( \(v , o ) h - > H.insert v o h ) heap ( zip vars objs )
returnJust ( RLet , st { code = e '
, heap = heap ' } )
rlet st@(StgState {..}) defs = do
vars <- replicateM (length (getBinds defs)) newVar
let ids = map fst (getBinds defs)
code'@(ELet defs' e') = substList ids (map AVar vars) code
objs = map snd $ (getBinds defs')
heap' = foldr (\(v,o) h -> H.insert v o h) heap (zip vars objs)
returnJust (RLet, st { code = e'
, heap = heap' })
-}
rlet st@(StgState {..}) (NonRec t obj) e = do
var <- newVar
let astack' = pushArgs [AVar $ Heap var] astack
heap' = H.insert var (allocObj obj) heap
returnJust (RLet, st { code = e
, heap = heap'
, astack = astack'})
rlet st@(StgState {..}) (Rec list) e = do
vars <- replicateM (length list) newVar
let astack' = pushArgs (map (AVar . Heap) vars) astack
objs = map (allocObjRec vars . snd) list
heap' = foldr (\(var,obj) heap -> H.insert var obj heap) heap (zip vars objs)
returnJust (RLet, st { code = e
, heap = heap'
, astack = astack'})
where
allocObjRec v o = case o of
OThunk fv s exp -> OThunk (map (AVar . Heap) v
++ map lookupAtom (drop (length v) fv)) s exp
_ -> o
rcase expr branch = returnJust
(RCaseCon
, st { code = expr
, cstack = CtCase branch : cstack
, astack = duplicateFrame astack
}
)
rany (EAtom var) defvar branch = case findDefaultBranch (lookupAtom var) branch of
Nothing -> return Nothing
Just expr' -> returnJust
( RCaseAny
, st { code = expr'
, astack = pushArgs [defvar] astack
}
)
rcasecon st@(StgState {..}) atoms expr = returnJust
( RCaseCon
, st { code = expr
, astack = pushArgs atoms astack
}
)
rprimop st op args = do
returnJust
( RPrimOP
, st { code = applyPrimOp op (map lookupAtom args) }
)
rpush st@(StgState {..}) ident args = returnJust
(RPush
, st { code = EAtom (AVar ident)
, cstack = map (CtArg . lookupAtom) args ++ cstack})
rret st@(StgState {..}) =
let CtCase bs : rest = cstack
EAtom a = code
in returnJust
( RRet
, st { code = ECase (EAtom $ lookupAtom a) bs
, cstack = rest
, astack = popFrame astack})
intressant ,
rthunk st@(StgState {..}) as size e v = returnJust
( RThunk
, st { code = e
, cstack = CtUpd v : cstack
, astack = pushArgs as $ callFrame astack
, heap = H.insert v OBlackhole heap})
rupdate st@(StgState {..}) obj = case cstack of
CtUpd x : res -> returnJust
( RUpdate
, st { cstack = res
, heap = H.insert x obj heap})
CtOUpd x : res -> returnJust
( RUpdate
, st { cstack = res
, heap = H.insertAbyss x obj heap})
rfenter st@(StgState {..}) args lenArgs size e = do
let args' = map unArg $ take lenArgs cstack
args '' < - replicateM lenArgs newVar
okey this is the thing ...
if we just subst names can clash = > bad :/
please if you can read this , save , you are our last hope
if we just subst names can clash => bad :/
please if you can read this, save us callstack, you are our last hope
-}
returnJust
( RFEnter
, st { code = e
, cstack = drop lenArgs cstack
, astack = pushArgs args' (callFrame astack) })
rpap st@(StgState {..}) stackArgs var = do
p <- newVar
let args' = map (lookupAtom . unArg) $ take stackArgs cstack
pap = OPap var args'
returnJust ( RPap1
, st { code = EAtom (AVar (Heap p))
, cstack = drop stackArgs cstack
, heap = H.insert p pap heap }
)
rpenter st@(StgState {..}) var atoms = returnJust
( RPEnter
, st { code = EAtom (AVar (Heap var))
, cstack = map CtArg atoms ++ cstack
})
roptimise st@(StgState {..}) omeg sets alpha =
returnJust
( ROptimise
, st
{ code = EAtom omeg
, cstack = CtOpt alpha : cstack
, heap = H.insert alpha OBlackhole heap
, settings = makeSettings astack heap sets : settings
}
)
roptpap st@(StgState {..}) var atoms =
case H.lookup var heap of
Just (OFun args i e) ->
let (argsA, argsL) = splitAt (length atoms) args
CtOpt alpha : stack' = cstack
astack' = pushArgs (zipWith AUnknown [0..] argsL) (newFrame astack)
e ' = subtractLocal var ( length atoms ) $ substList argsA ( map lookupAtom atoms ) e
in omega ROptPap (CtOFun argsL (i - length atoms) alpha:stack') astack' heap (inltM atoms 0 e) settings
_ -> error "OPTPAP: pap doesn't point to FUN"
roptfun st@(StgState {..}) args i expr = do
let CtOpt alpha : cstack' = cstack
astack' = pushArgs (zipWith AUnknown [0..] args) (newFrame astack)
omega (ROmega "from machine found fun to optimise") (CtOFun args i alpha : cstack') astack' heap expr settings
rcontopt st@(StgState { .. } ) = do
let CtContOpt alpha : cstack ' = cstack
case alpha heap of
Nothing - > error $ " ContOpt rule : alpha not in heap buh huh : " + + show alpha
Just obj - > omega alpha cstack ' heap obj
let CtContOpt alpha : cstack' = cstack
case H.lookup alpha heap of
Nothing -> error $ "ContOpt rule: alpha not in heap buh huh: " ++ show alpha
Just obj -> omega alpha cstack' heap obj
-}
rupdateopt st@(StgState {..}) obj var = do
let CtOpt alpha : cstack' = cstack
returnJust
( RUpdateOpt
, st
{ code = EAtom (AVar var)
, cstack = cstack'
, heap = H.insert alpha obj heap
}
)
rprintcon st@(StgState {..}) c atoms = do
let CtPrint : cstack' = cstack
case null atoms of
True -> returnJust
( RPrintCon
, st
{ code = ESVal (SCon c [])
, cstack = cstack'})
False -> returnJust
( RPrintCon
, st
{ code = EAtom (head atoms)
, cstack = CtPrint : CtPrintCon c [] (tail atoms) : cstack'})
rprintval st@(StgState {..}) atom = do
let CtPrint : cstack' = cstack
returnJust
( RPrintVal
, st
{ code = ESVal (SAtom (lookupAtom atom))
, cstack = cstack'})
rprintfun st@(StgState {..}) = do
let CtPrint : cstack' = cstack
returnJust
( RPrintFun
, st
{ code = ESVal SFun
, cstack = cstack'})
rprintcont st@(StgState {..}) sval = do
let CtPrintCon c ps ns : cstack' = cstack
case ns of
[] -> returnJust
( RPrintCont
, st
{ code = ESVal (SCon c (reverse (sval:ps)))
, cstack = cstack'})
n : ns -> returnJust
( RPrintCont
, st
{ code = EAtom n
, cstack = CtPrint : CtPrintCon c (sval:ps) ns : cstack'})
force st@(StgState { .. } ) = do
res < - step case res of
Nothing - > case code of
( EAtom var ) | AVar ( Heap v ) < - lookupAtom var - > case v heap of
Nothing - > return $ show v
Just ( OThunk expr ) - > force ( st { code = expr } )
Just ( OCon t [ ] ) - > return t
Just ( OCon t atoms )
- > do list < - mapM ( \x - > force ( st { code = EAtom x } ) ) atoms
return $ " ( " + + t + + " " + + concat ( space list ) + + " ) "
( EAtom ( ANum n ) ) - > return $ show n
other - > return $ show other
Just ( r , st ' ) - > force st '
where
space xs = let len = length xs - 1
in map ( + + " " ) ( take len xs ) + + drop len xs
runForce : : Variable t = > Input - > [ Function t ] - > t
runForce inp funs = evalStgM ( go st ) initialStgMState
where
gc = mkGC $ map mkcons $ [ trueCon , falseCon ]
st = gc ( createGetFuns inp + + funs )
go st = do
res < - step st
case res of
Nothing - > force st
Just ( r , st ' ) - > go st '
force st@(StgState {..}) = do
res <- step st
case res of
Nothing -> case code of
(EAtom var) | AVar (Heap v) <- lookupAtom var -> case H.lookup v heap of
Nothing -> return $ show v
Just (OThunk expr) -> force (st {code = expr})
Just (OCon t []) -> return t
Just (OCon t atoms)
-> do list <- mapM (\x -> force (st {code = EAtom x})) atoms
return $ "(" ++ t ++ " " ++ concat (space list) ++ ")"
(EAtom (ANum n)) -> return $ show n
other -> return $ show other
Just (r, st') -> force st'
where
space xs = let len = length xs - 1
in map (++" ") (take len xs) ++ drop len xs
runForce :: Variable t => Input -> [Function t] -> t
runForce inp funs = evalStgM (go st) initialStgMState
where
gc = mkGC $ map mkcons $ [trueCon, falseCon]
st = gc $ initialState (createGetFuns inp ++ funs)
go st = do
res <- step st
case res of
Nothing -> force st
Just (r, st') -> go st'
-}
eval :: Variable t => [Function t] -> [(Rule, StgState t)]
eval funs = (RInitial, st) : evalStgM (go st) initialStgMState
where
gc = mkGC $ map mkcons $ [trueCon, falseCon]
st = gc $ initialState funs
go st = do
res <- step st
case res of
Nothing -> return []
applyPrimOp :: Variable t => Primitive t -> [Atom t] -> Expr t
applyPrimOp op args = case (op,args) of
(IntOp {intOp = (+)}, [ANum x,ANum y]) -> EAtom $ ANum $ x + y
(IntCmp{intCmp = (+)}, [ANum x,ANum y]) -> EAtom $ avar $ x + y
(DblOp {dblOp = (+)}, [ADec x,ADec y]) -> EAtom $ ADec $ x + y
(DblCmp{dblCmp = (+)}, [ADec x,ADec y]) -> EAtom $ avar $ x + y
(ChrCmp{chrCmp = (+)}, [AChr x,AChr y]) -> EAtom $ avar $ x + y
(MathFun{mathFun = f}, [ADec x]) -> EAtom $ ADec $ f x
_ -> err
where
avar = AVar . Heap . boolToCon
err =
error $ "applyPrimOp: Primitive operation ("
++ show op
++ ") applied to arguments of the wrong type "
++ "( " ++ show args ++ ")"
++ ", or not the correct number of arguments."
|
f921e290695769f6ce6fc47ba196a3b4d599c96145e8bfc44b25142d3c070c76 | open-company/open-company-auth | utils.clj | (ns oc.auth.lib.utils
"Namespace for tests utilities"
(:require [clojure.string :as s]
[cheshire.core :as json]
[ring.mock.request :refer (request body content-type header)]
[oc.auth.lib.test-setup :as ts]))
(defn base-mime-type
"Base mime type"
[full-mime-type]
(first (s/split full-mime-type #";")))
(defn response-mime-type
"Get a response mime type"
[response]
(base-mime-type (get-in response [:headers "Content-Type"])))
(defn- apply-headers
"Add the map of headers to the ring mock request."
[request headers]
(if (= headers {})
request
(let [key (first (keys headers))]
(recur (header request key (get headers key)) (dissoc headers key)))))
(defn api-request
"Pretends to execute a REST API request using ring mock."
[method url options]
(let [initial-request (request method url)
headers (merge {:Accept-Charset "utf-8"} (:headers options))
headers-request (apply-headers initial-request headers)
body-value (:body options)
body-request (body headers-request (json/generate-string body-value))]
((-> ts/test-system deref :handler :handler) body-request))) | null | https://raw.githubusercontent.com/open-company/open-company-auth/79275bd3b877e70048a80960d7fa2d14be0abfe9/test/oc/auth/lib/utils.clj | clojure | (ns oc.auth.lib.utils
"Namespace for tests utilities"
(:require [clojure.string :as s]
[cheshire.core :as json]
[ring.mock.request :refer (request body content-type header)]
[oc.auth.lib.test-setup :as ts]))
(defn base-mime-type
"Base mime type"
[full-mime-type]
(first (s/split full-mime-type #";")))
(defn response-mime-type
"Get a response mime type"
[response]
(base-mime-type (get-in response [:headers "Content-Type"])))
(defn- apply-headers
"Add the map of headers to the ring mock request."
[request headers]
(if (= headers {})
request
(let [key (first (keys headers))]
(recur (header request key (get headers key)) (dissoc headers key)))))
(defn api-request
"Pretends to execute a REST API request using ring mock."
[method url options]
(let [initial-request (request method url)
headers (merge {:Accept-Charset "utf-8"} (:headers options))
headers-request (apply-headers initial-request headers)
body-value (:body options)
body-request (body headers-request (json/generate-string body-value))]
((-> ts/test-system deref :handler :handler) body-request))) | |
5bbf34d6df6797138ac3a1b2303429b0e6b96cb835ef626fbb969340f8dc6fa3 | twosigma/Cook | monitor.clj | ;;
Copyright ( c ) Two Sigma Open Source , LLC
;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -2.0
;;
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns cook.monitor
(:require [chime :refer [chime-at]]
[clj-time.core :as time]
[clojure.set :refer [difference union]]
[clojure.tools.logging :as log]
[cook.cached-queries :as cached-queries]
[cook.config :as config :refer [config]]
[cook.datomic :as datomic]
[cook.pool :as pool]
[cook.prometheus-metrics :as prometheus]
[cook.queries :as queries]
[cook.quota :as quota]
[cook.scheduler.share :as share]
[cook.util :as util]
[cook.tools :as tools]
[datomic.api :as d :refer [q]]
[metrics.counters :as counters]
[plumbing.core :refer [map-keys]]))
(defn job-ent-in-pool
[pool-name job-ent]
(let [cached-pool (cached-queries/job->pool-name job-ent)]
(or (= pool-name cached-pool) (= pool-name (get (config/quota-grouping-config) cached-pool)))))
(defn- get-job-stats
"Given all jobs for a particular job state, e.g. running or
waiting, produces basic stats per user.
Return a map from users to their stats where a stats is a map from stats
types to amounts."
[job-ents pool-name]
(->> job-ents
(filter #(job-ent-in-pool pool-name %))
;; Produce a list of maps from user's name to his stats.
(mapv (fn [job-ent]
(let [user (:job/user job-ent)
stats (-> job-ent
tools/job-ent->resources
(select-keys [:cpus :mem])
(assoc :jobs 1))]
{user stats})))
(reduce (partial merge-with (partial merge-with +)) {})))
(defn- add-aggregated-stats
"Given a map from users to their stats, associcate a special user
\"all\" for the sum of all users stats."
[stats]
(if (seq stats)
(->> (vals stats)
(apply merge-with +)
(assoc stats "all"))
{"all" {:cpus 0, :mem 0, :jobs 0}}))
(defn- get-starved-job-stats
"Return a map from starved users ONLY to their stats where a stats is a map
from stats types to amounts."
([db running-stats waiting-stats pool-name]
(let [waiting-users (keys waiting-stats)
shares (share/get-shares db waiting-users pool-name [:cpus :mem])
promised-resources (fn [user] (get shares user))
compute-starvation (fn [user]
(->> (merge-with - (promised-resources user) (get running-stats user))
(merge-with min (get waiting-stats user))))]
(loop [[user & users] waiting-users
starved-stats {}]
(if user
(let [used-resources (get running-stats user)]
;; Check if a user is not starved.
(if (every? true? (map (fn [[resource amount]]
(< (or (resource used-resources) 0.0)
amount))
(promised-resources user)))
(recur users (assoc starved-stats user (compute-starvation user)))
(recur users starved-stats)))
starved-stats)))))
(defn- get-waiting-under-quota-job-stats
"Return a map from users waiting under quota ONLY to their stats where a stats is a map
from stats types to amounts."
([db running-stats waiting-stats pool-name]
(let [waiting-users (keys waiting-stats)
user->quota (quota/create-user->quota-fn db pool-name)
promised-resources (fn [user] (map-keys (fn [k] (if (= k :count) :jobs k)) (user->quota user)))
; remaining-quota = max(quota - running, 0)
; waiting-under-quota = min(remaining-quota, waiting)
compute-waiting-under-quota (fn [user]
(->> (merge-with (fn [quota running] (max (- quota running) 0))
(promised-resources user) (get running-stats user))
(merge-with min (get waiting-stats user))))]
(loop [[user & users] waiting-users
waiting-under-quota-stats {}]
(if user
(let [used-resources (get running-stats user)]
;; Check if a user is under quota.
(if (every? true? (map (fn [[resource amount]]
(< (or (resource used-resources) 0.0)
amount))
(promised-resources user)))
(recur users (assoc waiting-under-quota-stats user (compute-waiting-under-quota user)))
(recur users waiting-under-quota-stats)))
waiting-under-quota-stats)))))
(defn set-counter!
"Sets the value of the counter to the new value.
A data race is possible if two threads invoke this function concurrently."
[counter value]
(let [amount-to-inc (- (long (min value Long/MAX_VALUE)) (counters/value counter))]
(counters/inc! counter amount-to-inc)))
(defn set-prometheus-gauge!
"Sets the value of the counter to the new value."
[pool-name user state type amount]
; Metrics need to be pre-registered in prometheus, so only record them if the metric exists
; Log a warning otherwise so that we know to add a metric if we add a new resource type.
(if (contains? prometheus/resource-metric-map type)
(prometheus/set (prometheus/resource-metric-map type) {:pool pool-name :user user :state state} amount)
(log/warn "Encountered unknown type for prometheus user metrics:" type)))
(defn- clear-old-counters!
"Clears counters that were present on the previous iteration
but not in the current iteration. This avoids the situation
where a user's job changes state but the old state's counter
doesn't reflect the change."
[state stats state->previous-stats-atom pool-name]
(let [previous-stats (get-in @state->previous-stats-atom [pool-name state])
previous-users (set (keys previous-stats))
current-users (set (keys stats))
users-to-clear (difference previous-users current-users)]
(run! (fn [user]
(run! (fn [[type _]]
(do
(set-counter! (counters/counter [state user (name type) (str "pool-" pool-name)]) 0)
(set-prometheus-gauge! pool-name user state type 0)))
(get previous-stats user)))
users-to-clear)))
(defn- set-user-counters!
"Sets counters for jobs with the given state, e.g. running, waiting and starved."
[state stats state->previous-stats-atom pool-name]
(clear-old-counters! state stats state->previous-stats-atom pool-name)
(swap! state->previous-stats-atom #(assoc-in % [pool-name state] stats))
(run!
(fn [[user stats]]
(run! (fn [[type amount]]
(do
(-> [state user (name type) (str "pool-" pool-name)]
counters/counter
(set-counter! amount))
(set-prometheus-gauge! pool-name user state type amount)))
stats))
(add-aggregated-stats stats)))
(defn set-total-counter!
"Given a state (e.g. starved) and a value, sets the corresponding counter."
[state value pool-name]
(do (-> [state "users" (str "pool-" pool-name)]
counters/counter
(set-counter! value))
(prometheus/set prometheus/user-state-count {:pool pool-name :state state} value)))
(defn set-stats-counters!
"Queries the database for running and waiting jobs per user, and sets
counters for running, waiting, starved, hungry and satisifed users."
[db state->previous-stats-atom pending-job-ents running-job-ents pool-name]
(log/info "Setting stats counters for running and waiting jobs per user for" pool-name "pool")
(let [running-stats (get-job-stats running-job-ents pool-name)
waiting-stats (get-job-stats pending-job-ents pool-name)
starved-stats (get-starved-job-stats db running-stats waiting-stats pool-name)
waiting-under-quota-stats (get-waiting-under-quota-job-stats db running-stats waiting-stats pool-name)
running-users (set (keys running-stats))
waiting-users (set (keys waiting-stats))
satisfied-users (difference running-users waiting-users)
starved-users (set (keys starved-stats))
waiting-under-quota-users (set (keys waiting-under-quota-stats))
hungry-users (difference waiting-users starved-users)
total-count (count (union running-users waiting-users))
starved-count (count starved-users)
waiting-under-quota-count (count waiting-under-quota-users)
hungry-count (count hungry-users)
satisfied-count (count satisfied-users)]
(set-user-counters! "running" running-stats state->previous-stats-atom pool-name)
(set-user-counters! "waiting" waiting-stats state->previous-stats-atom pool-name)
(set-user-counters! "starved" starved-stats state->previous-stats-atom pool-name)
(set-user-counters! "waiting-under-quota" waiting-under-quota-stats state->previous-stats-atom pool-name)
(set-total-counter! "total" total-count pool-name)
(set-total-counter! "starved" starved-count pool-name)
(set-total-counter! "waiting-under-quota" waiting-under-quota-count pool-name)
(set-total-counter! "hungry" hungry-count pool-name)
(set-total-counter! "satisfied" satisfied-count pool-name)
(log/info "Pool" pool-name "user stats: total" total-count "starved" starved-count
"waiting-under-quota" waiting-under-quota-count "hungry" hungry-count "satisfied" satisfied-count)))
(defn start-collecting-stats
"Starts a periodic timer to collect stats about running, waiting, and starved jobs per user.
Return a function which can be used to stop collecting stats if invoked."
[]
(let [interval-seconds (-> config :settings :user-metrics-interval-seconds)]
(if interval-seconds
(let [state->previous-stats-atom (atom {})]
(log/info "Starting user stats collection at intervals of" interval-seconds "seconds")
(chime-at (util/time-seq (time/now) (time/seconds interval-seconds))
(fn [_]
(log/info "Querying database for running and waiting jobs")
(let [mesos-db (d/db datomic/conn)
pending-job-ents (queries/get-pending-job-ents mesos-db)
running-job-ents (tools/get-running-job-ents mesos-db)
; Merge explicit pools as well as quota-grouping pools.
all-pools (tools/all-and-quota-group-pools mesos-db)
pools (if (seq all-pools) all-pools "no-pool")]
(run!
(fn [name]
(set-stats-counters! mesos-db state->previous-stats-atom
pending-job-ents running-job-ents name))
pools)))
{:error-handler (fn [ex]
(log/error ex "Setting user stats counters failed!"))}))
(log/info "User stats collection is disabled"))))
| null | https://raw.githubusercontent.com/twosigma/Cook/85d759fc71a80506aa383a4f23eccb6c12c6a330/scheduler/src/cook/monitor.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Produce a list of maps from user's name to his stats.
Check if a user is not starved.
remaining-quota = max(quota - running, 0)
waiting-under-quota = min(remaining-quota, waiting)
Check if a user is under quota.
Metrics need to be pre-registered in prometheus, so only record them if the metric exists
Log a warning otherwise so that we know to add a metric if we add a new resource type.
Merge explicit pools as well as quota-grouping pools. | Copyright ( c ) Two Sigma Open Source , LLC
distributed under the License is distributed on an " AS IS " BASIS ,
(ns cook.monitor
(:require [chime :refer [chime-at]]
[clj-time.core :as time]
[clojure.set :refer [difference union]]
[clojure.tools.logging :as log]
[cook.cached-queries :as cached-queries]
[cook.config :as config :refer [config]]
[cook.datomic :as datomic]
[cook.pool :as pool]
[cook.prometheus-metrics :as prometheus]
[cook.queries :as queries]
[cook.quota :as quota]
[cook.scheduler.share :as share]
[cook.util :as util]
[cook.tools :as tools]
[datomic.api :as d :refer [q]]
[metrics.counters :as counters]
[plumbing.core :refer [map-keys]]))
(defn job-ent-in-pool
[pool-name job-ent]
(let [cached-pool (cached-queries/job->pool-name job-ent)]
(or (= pool-name cached-pool) (= pool-name (get (config/quota-grouping-config) cached-pool)))))
(defn- get-job-stats
"Given all jobs for a particular job state, e.g. running or
waiting, produces basic stats per user.
Return a map from users to their stats where a stats is a map from stats
types to amounts."
[job-ents pool-name]
(->> job-ents
(filter #(job-ent-in-pool pool-name %))
(mapv (fn [job-ent]
(let [user (:job/user job-ent)
stats (-> job-ent
tools/job-ent->resources
(select-keys [:cpus :mem])
(assoc :jobs 1))]
{user stats})))
(reduce (partial merge-with (partial merge-with +)) {})))
(defn- add-aggregated-stats
"Given a map from users to their stats, associcate a special user
\"all\" for the sum of all users stats."
[stats]
(if (seq stats)
(->> (vals stats)
(apply merge-with +)
(assoc stats "all"))
{"all" {:cpus 0, :mem 0, :jobs 0}}))
(defn- get-starved-job-stats
"Return a map from starved users ONLY to their stats where a stats is a map
from stats types to amounts."
([db running-stats waiting-stats pool-name]
(let [waiting-users (keys waiting-stats)
shares (share/get-shares db waiting-users pool-name [:cpus :mem])
promised-resources (fn [user] (get shares user))
compute-starvation (fn [user]
(->> (merge-with - (promised-resources user) (get running-stats user))
(merge-with min (get waiting-stats user))))]
(loop [[user & users] waiting-users
starved-stats {}]
(if user
(let [used-resources (get running-stats user)]
(if (every? true? (map (fn [[resource amount]]
(< (or (resource used-resources) 0.0)
amount))
(promised-resources user)))
(recur users (assoc starved-stats user (compute-starvation user)))
(recur users starved-stats)))
starved-stats)))))
(defn- get-waiting-under-quota-job-stats
"Return a map from users waiting under quota ONLY to their stats where a stats is a map
from stats types to amounts."
([db running-stats waiting-stats pool-name]
(let [waiting-users (keys waiting-stats)
user->quota (quota/create-user->quota-fn db pool-name)
promised-resources (fn [user] (map-keys (fn [k] (if (= k :count) :jobs k)) (user->quota user)))
compute-waiting-under-quota (fn [user]
(->> (merge-with (fn [quota running] (max (- quota running) 0))
(promised-resources user) (get running-stats user))
(merge-with min (get waiting-stats user))))]
(loop [[user & users] waiting-users
waiting-under-quota-stats {}]
(if user
(let [used-resources (get running-stats user)]
(if (every? true? (map (fn [[resource amount]]
(< (or (resource used-resources) 0.0)
amount))
(promised-resources user)))
(recur users (assoc waiting-under-quota-stats user (compute-waiting-under-quota user)))
(recur users waiting-under-quota-stats)))
waiting-under-quota-stats)))))
(defn set-counter!
"Sets the value of the counter to the new value.
A data race is possible if two threads invoke this function concurrently."
[counter value]
(let [amount-to-inc (- (long (min value Long/MAX_VALUE)) (counters/value counter))]
(counters/inc! counter amount-to-inc)))
(defn set-prometheus-gauge!
"Sets the value of the counter to the new value."
[pool-name user state type amount]
(if (contains? prometheus/resource-metric-map type)
(prometheus/set (prometheus/resource-metric-map type) {:pool pool-name :user user :state state} amount)
(log/warn "Encountered unknown type for prometheus user metrics:" type)))
(defn- clear-old-counters!
"Clears counters that were present on the previous iteration
but not in the current iteration. This avoids the situation
where a user's job changes state but the old state's counter
doesn't reflect the change."
[state stats state->previous-stats-atom pool-name]
(let [previous-stats (get-in @state->previous-stats-atom [pool-name state])
previous-users (set (keys previous-stats))
current-users (set (keys stats))
users-to-clear (difference previous-users current-users)]
(run! (fn [user]
(run! (fn [[type _]]
(do
(set-counter! (counters/counter [state user (name type) (str "pool-" pool-name)]) 0)
(set-prometheus-gauge! pool-name user state type 0)))
(get previous-stats user)))
users-to-clear)))
(defn- set-user-counters!
"Sets counters for jobs with the given state, e.g. running, waiting and starved."
[state stats state->previous-stats-atom pool-name]
(clear-old-counters! state stats state->previous-stats-atom pool-name)
(swap! state->previous-stats-atom #(assoc-in % [pool-name state] stats))
(run!
(fn [[user stats]]
(run! (fn [[type amount]]
(do
(-> [state user (name type) (str "pool-" pool-name)]
counters/counter
(set-counter! amount))
(set-prometheus-gauge! pool-name user state type amount)))
stats))
(add-aggregated-stats stats)))
(defn set-total-counter!
"Given a state (e.g. starved) and a value, sets the corresponding counter."
[state value pool-name]
(do (-> [state "users" (str "pool-" pool-name)]
counters/counter
(set-counter! value))
(prometheus/set prometheus/user-state-count {:pool pool-name :state state} value)))
(defn set-stats-counters!
"Queries the database for running and waiting jobs per user, and sets
counters for running, waiting, starved, hungry and satisifed users."
[db state->previous-stats-atom pending-job-ents running-job-ents pool-name]
(log/info "Setting stats counters for running and waiting jobs per user for" pool-name "pool")
(let [running-stats (get-job-stats running-job-ents pool-name)
waiting-stats (get-job-stats pending-job-ents pool-name)
starved-stats (get-starved-job-stats db running-stats waiting-stats pool-name)
waiting-under-quota-stats (get-waiting-under-quota-job-stats db running-stats waiting-stats pool-name)
running-users (set (keys running-stats))
waiting-users (set (keys waiting-stats))
satisfied-users (difference running-users waiting-users)
starved-users (set (keys starved-stats))
waiting-under-quota-users (set (keys waiting-under-quota-stats))
hungry-users (difference waiting-users starved-users)
total-count (count (union running-users waiting-users))
starved-count (count starved-users)
waiting-under-quota-count (count waiting-under-quota-users)
hungry-count (count hungry-users)
satisfied-count (count satisfied-users)]
(set-user-counters! "running" running-stats state->previous-stats-atom pool-name)
(set-user-counters! "waiting" waiting-stats state->previous-stats-atom pool-name)
(set-user-counters! "starved" starved-stats state->previous-stats-atom pool-name)
(set-user-counters! "waiting-under-quota" waiting-under-quota-stats state->previous-stats-atom pool-name)
(set-total-counter! "total" total-count pool-name)
(set-total-counter! "starved" starved-count pool-name)
(set-total-counter! "waiting-under-quota" waiting-under-quota-count pool-name)
(set-total-counter! "hungry" hungry-count pool-name)
(set-total-counter! "satisfied" satisfied-count pool-name)
(log/info "Pool" pool-name "user stats: total" total-count "starved" starved-count
"waiting-under-quota" waiting-under-quota-count "hungry" hungry-count "satisfied" satisfied-count)))
(defn start-collecting-stats
"Starts a periodic timer to collect stats about running, waiting, and starved jobs per user.
Return a function which can be used to stop collecting stats if invoked."
[]
(let [interval-seconds (-> config :settings :user-metrics-interval-seconds)]
(if interval-seconds
(let [state->previous-stats-atom (atom {})]
(log/info "Starting user stats collection at intervals of" interval-seconds "seconds")
(chime-at (util/time-seq (time/now) (time/seconds interval-seconds))
(fn [_]
(log/info "Querying database for running and waiting jobs")
(let [mesos-db (d/db datomic/conn)
pending-job-ents (queries/get-pending-job-ents mesos-db)
running-job-ents (tools/get-running-job-ents mesos-db)
all-pools (tools/all-and-quota-group-pools mesos-db)
pools (if (seq all-pools) all-pools "no-pool")]
(run!
(fn [name]
(set-stats-counters! mesos-db state->previous-stats-atom
pending-job-ents running-job-ents name))
pools)))
{:error-handler (fn [ex]
(log/error ex "Setting user stats counters failed!"))}))
(log/info "User stats collection is disabled"))))
|
12fb06f5d91ae8a312c25e7a8a0be513cf698393e64c815a70ed9df1edfb0683 | FlowerWrong/mblog | my_bank.erl | %% ---
Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
%% Copyrights apply to this code. It may not be used to create training material,
%% courses, books, articles, and the like. Contact us if you are in doubt.
%% We make no guarantees that this code is fit for any purpose.
%% Visit for more book information.
%%---
-module(my_bank).
-behaviour(gen_server).
-export([start/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-compile(export_all).
-define(SERVER, ?MODULE).
start() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
stop() -> gen_server:call(?MODULE, stop).
new_account(Who) -> gen_server:call(?MODULE, {new, Who}).
deposit(Who, Amount) -> gen_server:call(?MODULE, {add, Who, Amount}).
withdraw(Who, Amount) -> gen_server:call(?MODULE, {remove, Who, Amount}).
init([]) -> {ok, ets:new(?MODULE,[])}.
handle_call({new,Who}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> ets:insert(Tab, {Who,0}),
{welcome, Who};
[_] -> {Who, you_already_are_a_customer}
end,
{reply, Reply, Tab};
handle_call({add,Who,X}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> not_a_customer;
[{Who,Balance}] ->
NewBalance = Balance + X,
ets:insert(Tab, {Who, NewBalance}),
{thanks, Who, your_balance_is, NewBalance}
end,
{reply, Reply, Tab};
handle_call({remove,Who, X}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> not_a_customer;
[{Who,Balance}] when X =< Balance ->
NewBalance = Balance - X,
ets:insert(Tab, {Who, NewBalance}),
{thanks, Who, your_balance_is, NewBalance};
[{Who,Balance}] ->
{sorry,Who,you_only_have,Balance,in_the_bank}
end,
{reply, Reply, Tab};
handle_call(stop, _From, Tab) ->
{stop, normal, stopped, Tab}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
| null | https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/my_bank.erl | erlang | ---
Copyrights apply to this code. It may not be used to create training material,
courses, books, articles, and the like. Contact us if you are in doubt.
We make no guarantees that this code is fit for any purpose.
Visit for more book information.
---
gen_server callbacks | Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
-module(my_bank).
-behaviour(gen_server).
-export([start/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-compile(export_all).
-define(SERVER, ?MODULE).
start() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
stop() -> gen_server:call(?MODULE, stop).
new_account(Who) -> gen_server:call(?MODULE, {new, Who}).
deposit(Who, Amount) -> gen_server:call(?MODULE, {add, Who, Amount}).
withdraw(Who, Amount) -> gen_server:call(?MODULE, {remove, Who, Amount}).
init([]) -> {ok, ets:new(?MODULE,[])}.
handle_call({new,Who}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> ets:insert(Tab, {Who,0}),
{welcome, Who};
[_] -> {Who, you_already_are_a_customer}
end,
{reply, Reply, Tab};
handle_call({add,Who,X}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> not_a_customer;
[{Who,Balance}] ->
NewBalance = Balance + X,
ets:insert(Tab, {Who, NewBalance}),
{thanks, Who, your_balance_is, NewBalance}
end,
{reply, Reply, Tab};
handle_call({remove,Who, X}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> not_a_customer;
[{Who,Balance}] when X =< Balance ->
NewBalance = Balance - X,
ets:insert(Tab, {Who, NewBalance}),
{thanks, Who, your_balance_is, NewBalance};
[{Who,Balance}] ->
{sorry,Who,you_only_have,Balance,in_the_bank}
end,
{reply, Reply, Tab};
handle_call(stop, _From, Tab) ->
{stop, normal, stopped, Tab}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
|
e8719039d9a5a69cea9c0a747eff636e8b4cc9f7b8d125116c55788e51489ad3 | coccinelle/coccinelle | visitor_ast.mli |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
type 'a combiner =
{combiner_ident : Ast_cocci.ident -> 'a;
combiner_expression : Ast_cocci.expression -> 'a;
combiner_fragment : Ast_cocci.string_fragment -> 'a;
combiner_format : Ast_cocci.string_format -> 'a;
combiner_assignOp : Ast_cocci.assignOp -> 'a;
combiner_binaryOp : Ast_cocci.binaryOp -> 'a;
combiner_fullType : Ast_cocci.fullType -> 'a;
combiner_typeC : Ast_cocci.typeC -> 'a;
combiner_declaration : Ast_cocci.declaration -> 'a;
combiner_field : Ast_cocci.field -> 'a;
combiner_ann_field : Ast_cocci.annotated_field -> 'a;
combiner_enumdecl : Ast_cocci.enum_decl -> 'a;
combiner_initialiser : Ast_cocci.initialiser -> 'a;
combiner_parameter : Ast_cocci.parameterTypeDef -> 'a;
combiner_parameter_list : Ast_cocci.parameter_list -> 'a;
combiner_rule_elem : Ast_cocci.rule_elem -> 'a;
combiner_statement : Ast_cocci.statement -> 'a;
combiner_case_line : Ast_cocci.case_line -> 'a;
combiner_attribute : Ast_cocci.attr -> 'a;
combiner_attr_arg : Ast_cocci.attr_arg -> 'a;
combiner_top_level : Ast_cocci.top_level -> 'a;
combiner_anything : Ast_cocci.anything -> 'a;
combiner_expression_dots : Ast_cocci.expression Ast_cocci.dots -> 'a;
combiner_statement_dots : Ast_cocci.statement Ast_cocci.dots -> 'a;
combiner_anndecl_dots : Ast_cocci.annotated_decl Ast_cocci.dots -> 'a;
combiner_annfield_dots : Ast_cocci.annotated_field Ast_cocci.dots -> 'a;
combiner_enumdecl_dots : Ast_cocci.enum_decl Ast_cocci.dots -> 'a;
combiner_initialiser_dots : Ast_cocci.initialiser Ast_cocci.dots -> 'a}
type ('mc,'a) cmcode = 'a combiner -> 'mc Ast_cocci.mcode -> 'a
type ('cd,'a) ccode = 'a combiner -> ('cd -> 'a) -> 'cd -> 'a
val combiner :
('a -> 'a -> 'a) -> 'a ->
((Ast_cocci.meta_name,'a) cmcode) ->
((string,'a) cmcode) ->
((Ast_cocci.constant,'a) cmcode) ->
((Ast_cocci.simpleAssignOp,'a) cmcode) ->
((Ast_cocci.arithOp,'a) cmcode) ->
((Ast_cocci.fixOp,'a) cmcode) ->
((Ast_cocci.unaryOp,'a) cmcode) ->
((Ast_cocci.arithOp,'a) cmcode) ->
((Ast_cocci.logicalOp,'a) cmcode) ->
((Ast_cocci.const_vol,'a) cmcode) ->
((Ast_cocci.sign,'a) cmcode) ->
((Ast_cocci.structUnion,'a) cmcode) ->
((Ast_cocci.storage,'a) cmcode) ->
((Ast_cocci.inc_file,'a) cmcode) ->
((Ast_cocci.expression Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.parameterTypeDef Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.statement Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.annotated_decl Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.annotated_field Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.enum_decl Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.initialiser Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.ident,'a) ccode) ->
((Ast_cocci.expression,'a) ccode) ->
((Ast_cocci.string_fragment,'a) ccode) ->
((Ast_cocci.string_format,'a) ccode) ->
((Ast_cocci.assignOp,'a) ccode) ->
((Ast_cocci.binaryOp,'a) ccode) ->
((Ast_cocci.fullType,'a) ccode) ->
((Ast_cocci.typeC,'a) ccode) ->
((Ast_cocci.initialiser,'a) ccode) ->
((Ast_cocci.parameterTypeDef,'a) ccode) ->
((Ast_cocci.define_param,'a) ccode) ->
((Ast_cocci.declaration,'a) ccode) ->
((Ast_cocci.annotated_decl,'a) ccode) ->
((Ast_cocci.field,'a) ccode) ->
((Ast_cocci.annotated_field,'a) ccode) ->
((Ast_cocci.enum_decl,'a) ccode) ->
((Ast_cocci.rule_elem,'a) ccode) ->
((Ast_cocci.statement,'a) ccode) ->
((Ast_cocci.case_line,'a) ccode) ->
((Ast_cocci.attr,'a) ccode) ->
((Ast_cocci.attr_arg,'a) ccode) ->
((Ast_cocci.top_level,'a) ccode) ->
((Ast_cocci.anything,'a) ccode) ->
'a combiner
type 'a inout = 'a -> 'a (* for specifying the type of rebuilder *)
type rebuilder =
{rebuilder_ident : Ast_cocci.ident inout;
rebuilder_expression : Ast_cocci.expression inout;
rebuilder_fragment : Ast_cocci.string_fragment inout;
rebuilder_format : Ast_cocci.string_format inout;
rebuilder_assignOp : Ast_cocci.assignOp inout;
rebuilder_binaryOp : Ast_cocci.binaryOp inout;
rebuilder_fullType : Ast_cocci.fullType inout;
rebuilder_typeC : Ast_cocci.typeC inout;
rebuilder_declaration : Ast_cocci.declaration inout;
rebuilder_field : Ast_cocci.field inout;
rebuilder_ann_field : Ast_cocci.annotated_field inout;
rebuilder_enumdecl : Ast_cocci.enum_decl inout;
rebuilder_initialiser : Ast_cocci.initialiser inout;
rebuilder_parameter : Ast_cocci.parameterTypeDef inout;
rebuilder_parameter_list : Ast_cocci.parameter_list inout;
rebuilder_statement : Ast_cocci.statement inout;
rebuilder_case_line : Ast_cocci.case_line inout;
rebuilder_attribute : Ast_cocci.attr inout;
rebuilder_attr_arg : Ast_cocci.attr_arg inout;
rebuilder_rule_elem : Ast_cocci.rule_elem inout;
rebuilder_top_level : Ast_cocci.top_level inout;
rebuilder_expression_dots : Ast_cocci.expression Ast_cocci.dots inout;
rebuilder_statement_dots : Ast_cocci.statement Ast_cocci.dots inout;
rebuilder_anndecl_dots : Ast_cocci.annotated_decl Ast_cocci.dots inout;
rebuilder_annfield_dots : Ast_cocci.annotated_field Ast_cocci.dots inout;
rebuilder_enumdecl_dots : Ast_cocci.enum_decl Ast_cocci.dots inout;
rebuilder_initialiser_dots : Ast_cocci.initialiser Ast_cocci.dots inout;
rebuilder_define_param_dots: Ast_cocci.define_param Ast_cocci.dots inout;
rebuilder_define_param : Ast_cocci.define_param inout;
rebuilder_define_parameters : Ast_cocci.define_parameters inout;
rebuilder_anything : Ast_cocci.anything inout}
type 'mc rmcode = 'mc Ast_cocci.mcode inout
type 'cd rcode = rebuilder -> ('cd inout) -> 'cd inout
val rebuilder :
(Ast_cocci.meta_name rmcode) ->
(string rmcode) ->
(Ast_cocci.constant rmcode) ->
(Ast_cocci.simpleAssignOp rmcode) ->
(Ast_cocci.arithOp rmcode) ->
(Ast_cocci.fixOp rmcode) ->
(Ast_cocci.unaryOp rmcode) ->
(Ast_cocci.arithOp rmcode) ->
(Ast_cocci.logicalOp rmcode) ->
(Ast_cocci.const_vol rmcode) ->
(Ast_cocci.sign rmcode) ->
(Ast_cocci.structUnion rmcode) ->
(Ast_cocci.storage rmcode) ->
(Ast_cocci.inc_file rmcode) ->
(Ast_cocci.expression Ast_cocci.dots rcode) ->
(Ast_cocci.parameterTypeDef Ast_cocci.dots rcode) ->
(Ast_cocci.statement Ast_cocci.dots rcode) ->
(Ast_cocci.annotated_decl Ast_cocci.dots rcode) ->
(Ast_cocci.annotated_field Ast_cocci.dots rcode) ->
(Ast_cocci.enum_decl Ast_cocci.dots rcode) ->
(Ast_cocci.initialiser Ast_cocci.dots rcode) ->
(Ast_cocci.ident rcode) ->
(Ast_cocci.expression rcode) ->
(Ast_cocci.string_fragment rcode) ->
(Ast_cocci.string_format rcode) ->
(Ast_cocci.assignOp rcode) ->
(Ast_cocci.binaryOp rcode) ->
(Ast_cocci.fullType rcode) ->
(Ast_cocci.typeC rcode) ->
(Ast_cocci.initialiser rcode) ->
(Ast_cocci.parameterTypeDef rcode) ->
(Ast_cocci.define_param rcode) ->
(Ast_cocci.declaration rcode) ->
(Ast_cocci.annotated_decl rcode) ->
(Ast_cocci.field rcode) ->
(Ast_cocci.annotated_field rcode) ->
(Ast_cocci.enum_decl rcode) ->
(Ast_cocci.rule_elem rcode) ->
(Ast_cocci.statement rcode) ->
(Ast_cocci.case_line rcode) ->
(Ast_cocci.attr rcode) ->
(Ast_cocci.attr_arg rcode) ->
(Ast_cocci.top_level rcode) ->
(Ast_cocci.anything rcode) ->
rebuilder
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/parsing_cocci/visitor_ast.mli | ocaml | for specifying the type of rebuilder |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
type 'a combiner =
{combiner_ident : Ast_cocci.ident -> 'a;
combiner_expression : Ast_cocci.expression -> 'a;
combiner_fragment : Ast_cocci.string_fragment -> 'a;
combiner_format : Ast_cocci.string_format -> 'a;
combiner_assignOp : Ast_cocci.assignOp -> 'a;
combiner_binaryOp : Ast_cocci.binaryOp -> 'a;
combiner_fullType : Ast_cocci.fullType -> 'a;
combiner_typeC : Ast_cocci.typeC -> 'a;
combiner_declaration : Ast_cocci.declaration -> 'a;
combiner_field : Ast_cocci.field -> 'a;
combiner_ann_field : Ast_cocci.annotated_field -> 'a;
combiner_enumdecl : Ast_cocci.enum_decl -> 'a;
combiner_initialiser : Ast_cocci.initialiser -> 'a;
combiner_parameter : Ast_cocci.parameterTypeDef -> 'a;
combiner_parameter_list : Ast_cocci.parameter_list -> 'a;
combiner_rule_elem : Ast_cocci.rule_elem -> 'a;
combiner_statement : Ast_cocci.statement -> 'a;
combiner_case_line : Ast_cocci.case_line -> 'a;
combiner_attribute : Ast_cocci.attr -> 'a;
combiner_attr_arg : Ast_cocci.attr_arg -> 'a;
combiner_top_level : Ast_cocci.top_level -> 'a;
combiner_anything : Ast_cocci.anything -> 'a;
combiner_expression_dots : Ast_cocci.expression Ast_cocci.dots -> 'a;
combiner_statement_dots : Ast_cocci.statement Ast_cocci.dots -> 'a;
combiner_anndecl_dots : Ast_cocci.annotated_decl Ast_cocci.dots -> 'a;
combiner_annfield_dots : Ast_cocci.annotated_field Ast_cocci.dots -> 'a;
combiner_enumdecl_dots : Ast_cocci.enum_decl Ast_cocci.dots -> 'a;
combiner_initialiser_dots : Ast_cocci.initialiser Ast_cocci.dots -> 'a}
type ('mc,'a) cmcode = 'a combiner -> 'mc Ast_cocci.mcode -> 'a
type ('cd,'a) ccode = 'a combiner -> ('cd -> 'a) -> 'cd -> 'a
val combiner :
('a -> 'a -> 'a) -> 'a ->
((Ast_cocci.meta_name,'a) cmcode) ->
((string,'a) cmcode) ->
((Ast_cocci.constant,'a) cmcode) ->
((Ast_cocci.simpleAssignOp,'a) cmcode) ->
((Ast_cocci.arithOp,'a) cmcode) ->
((Ast_cocci.fixOp,'a) cmcode) ->
((Ast_cocci.unaryOp,'a) cmcode) ->
((Ast_cocci.arithOp,'a) cmcode) ->
((Ast_cocci.logicalOp,'a) cmcode) ->
((Ast_cocci.const_vol,'a) cmcode) ->
((Ast_cocci.sign,'a) cmcode) ->
((Ast_cocci.structUnion,'a) cmcode) ->
((Ast_cocci.storage,'a) cmcode) ->
((Ast_cocci.inc_file,'a) cmcode) ->
((Ast_cocci.expression Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.parameterTypeDef Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.statement Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.annotated_decl Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.annotated_field Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.enum_decl Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.initialiser Ast_cocci.dots,'a) ccode) ->
((Ast_cocci.ident,'a) ccode) ->
((Ast_cocci.expression,'a) ccode) ->
((Ast_cocci.string_fragment,'a) ccode) ->
((Ast_cocci.string_format,'a) ccode) ->
((Ast_cocci.assignOp,'a) ccode) ->
((Ast_cocci.binaryOp,'a) ccode) ->
((Ast_cocci.fullType,'a) ccode) ->
((Ast_cocci.typeC,'a) ccode) ->
((Ast_cocci.initialiser,'a) ccode) ->
((Ast_cocci.parameterTypeDef,'a) ccode) ->
((Ast_cocci.define_param,'a) ccode) ->
((Ast_cocci.declaration,'a) ccode) ->
((Ast_cocci.annotated_decl,'a) ccode) ->
((Ast_cocci.field,'a) ccode) ->
((Ast_cocci.annotated_field,'a) ccode) ->
((Ast_cocci.enum_decl,'a) ccode) ->
((Ast_cocci.rule_elem,'a) ccode) ->
((Ast_cocci.statement,'a) ccode) ->
((Ast_cocci.case_line,'a) ccode) ->
((Ast_cocci.attr,'a) ccode) ->
((Ast_cocci.attr_arg,'a) ccode) ->
((Ast_cocci.top_level,'a) ccode) ->
((Ast_cocci.anything,'a) ccode) ->
'a combiner
type rebuilder =
{rebuilder_ident : Ast_cocci.ident inout;
rebuilder_expression : Ast_cocci.expression inout;
rebuilder_fragment : Ast_cocci.string_fragment inout;
rebuilder_format : Ast_cocci.string_format inout;
rebuilder_assignOp : Ast_cocci.assignOp inout;
rebuilder_binaryOp : Ast_cocci.binaryOp inout;
rebuilder_fullType : Ast_cocci.fullType inout;
rebuilder_typeC : Ast_cocci.typeC inout;
rebuilder_declaration : Ast_cocci.declaration inout;
rebuilder_field : Ast_cocci.field inout;
rebuilder_ann_field : Ast_cocci.annotated_field inout;
rebuilder_enumdecl : Ast_cocci.enum_decl inout;
rebuilder_initialiser : Ast_cocci.initialiser inout;
rebuilder_parameter : Ast_cocci.parameterTypeDef inout;
rebuilder_parameter_list : Ast_cocci.parameter_list inout;
rebuilder_statement : Ast_cocci.statement inout;
rebuilder_case_line : Ast_cocci.case_line inout;
rebuilder_attribute : Ast_cocci.attr inout;
rebuilder_attr_arg : Ast_cocci.attr_arg inout;
rebuilder_rule_elem : Ast_cocci.rule_elem inout;
rebuilder_top_level : Ast_cocci.top_level inout;
rebuilder_expression_dots : Ast_cocci.expression Ast_cocci.dots inout;
rebuilder_statement_dots : Ast_cocci.statement Ast_cocci.dots inout;
rebuilder_anndecl_dots : Ast_cocci.annotated_decl Ast_cocci.dots inout;
rebuilder_annfield_dots : Ast_cocci.annotated_field Ast_cocci.dots inout;
rebuilder_enumdecl_dots : Ast_cocci.enum_decl Ast_cocci.dots inout;
rebuilder_initialiser_dots : Ast_cocci.initialiser Ast_cocci.dots inout;
rebuilder_define_param_dots: Ast_cocci.define_param Ast_cocci.dots inout;
rebuilder_define_param : Ast_cocci.define_param inout;
rebuilder_define_parameters : Ast_cocci.define_parameters inout;
rebuilder_anything : Ast_cocci.anything inout}
type 'mc rmcode = 'mc Ast_cocci.mcode inout
type 'cd rcode = rebuilder -> ('cd inout) -> 'cd inout
val rebuilder :
(Ast_cocci.meta_name rmcode) ->
(string rmcode) ->
(Ast_cocci.constant rmcode) ->
(Ast_cocci.simpleAssignOp rmcode) ->
(Ast_cocci.arithOp rmcode) ->
(Ast_cocci.fixOp rmcode) ->
(Ast_cocci.unaryOp rmcode) ->
(Ast_cocci.arithOp rmcode) ->
(Ast_cocci.logicalOp rmcode) ->
(Ast_cocci.const_vol rmcode) ->
(Ast_cocci.sign rmcode) ->
(Ast_cocci.structUnion rmcode) ->
(Ast_cocci.storage rmcode) ->
(Ast_cocci.inc_file rmcode) ->
(Ast_cocci.expression Ast_cocci.dots rcode) ->
(Ast_cocci.parameterTypeDef Ast_cocci.dots rcode) ->
(Ast_cocci.statement Ast_cocci.dots rcode) ->
(Ast_cocci.annotated_decl Ast_cocci.dots rcode) ->
(Ast_cocci.annotated_field Ast_cocci.dots rcode) ->
(Ast_cocci.enum_decl Ast_cocci.dots rcode) ->
(Ast_cocci.initialiser Ast_cocci.dots rcode) ->
(Ast_cocci.ident rcode) ->
(Ast_cocci.expression rcode) ->
(Ast_cocci.string_fragment rcode) ->
(Ast_cocci.string_format rcode) ->
(Ast_cocci.assignOp rcode) ->
(Ast_cocci.binaryOp rcode) ->
(Ast_cocci.fullType rcode) ->
(Ast_cocci.typeC rcode) ->
(Ast_cocci.initialiser rcode) ->
(Ast_cocci.parameterTypeDef rcode) ->
(Ast_cocci.define_param rcode) ->
(Ast_cocci.declaration rcode) ->
(Ast_cocci.annotated_decl rcode) ->
(Ast_cocci.field rcode) ->
(Ast_cocci.annotated_field rcode) ->
(Ast_cocci.enum_decl rcode) ->
(Ast_cocci.rule_elem rcode) ->
(Ast_cocci.statement rcode) ->
(Ast_cocci.case_line rcode) ->
(Ast_cocci.attr rcode) ->
(Ast_cocci.attr_arg rcode) ->
(Ast_cocci.top_level rcode) ->
(Ast_cocci.anything rcode) ->
rebuilder
|
84216f20a206eb58203b057ce9e594099dc21489cc023f5e64894694aef02fb7 | ashinkarov/heh | test_value.ml | open OUnit
open Ordinals
open Value
open Valueops
let vv = List.map (fun x -> Valueops.mk_int_value x)
let test_value_const _ =
assert_equal ~msg:"mk_false" (mk_false_value) (VFalse);
assert_equal ~msg:"mk_true" (mk_true_value) (VTrue);
assert_equal ~msg:"mk_int 0"
(mk_int_value 0) (VNum (zero));
assert_equal ~msg:"mk_int 42"
(mk_int_value 42) (VNum (int_to_ord 42));
assert_equal ~msg:"mk_ord 0"
(mk_ord_value zero) (VNum (zero))
let test_value_array _ =
assert_equal ~msg:"empty array of shape [0]"
(mk_array_value (vv [0]) (vv [])) (VArray (vv [0], vv []));
assert_equal ~msg:"empty array of shape [0;4;4]"
(mk_array_value (vv [0;4;4]) (vv [])) (VArray (vv [0;4;4], vv []));
assert_equal ~msg:"empty array of shape [0;omega]"
(mk_array_value [VNum (zero); VNum (omega)] (vv []))
(VArray ([VNum zero; VNum omega], vv []));
let try_non_number_shape () =
mk_array_value [VFalse] []
in
assert_raises (ValueFailure
"mk_array: invalid shape vector [vfalse]")
try_non_number_shape;
let try_omega_shape () =
mk_array_value [VNum (omega)] []
in
assert_raises (ValueFailure
"mk_array: shape [ω] suggests that arrray will have more than omega elements")
try_omega_shape;
let try_wrong_data_size () =
mk_array_value (vv [3;3]) (vv [1;2;3])
in
assert_raises (ValueFailure
"mk_array: shape [3, 3] does not match data [1, 2, 3]")
try_wrong_data_size;
| null | https://raw.githubusercontent.com/ashinkarov/heh/42866803b2ffacdc42b8f06203bf4e5bd18e03b0/tests/test_value.ml | ocaml | open OUnit
open Ordinals
open Value
open Valueops
let vv = List.map (fun x -> Valueops.mk_int_value x)
let test_value_const _ =
assert_equal ~msg:"mk_false" (mk_false_value) (VFalse);
assert_equal ~msg:"mk_true" (mk_true_value) (VTrue);
assert_equal ~msg:"mk_int 0"
(mk_int_value 0) (VNum (zero));
assert_equal ~msg:"mk_int 42"
(mk_int_value 42) (VNum (int_to_ord 42));
assert_equal ~msg:"mk_ord 0"
(mk_ord_value zero) (VNum (zero))
let test_value_array _ =
assert_equal ~msg:"empty array of shape [0]"
(mk_array_value (vv [0]) (vv [])) (VArray (vv [0], vv []));
assert_equal ~msg:"empty array of shape [0;4;4]"
(mk_array_value (vv [0;4;4]) (vv [])) (VArray (vv [0;4;4], vv []));
assert_equal ~msg:"empty array of shape [0;omega]"
(mk_array_value [VNum (zero); VNum (omega)] (vv []))
(VArray ([VNum zero; VNum omega], vv []));
let try_non_number_shape () =
mk_array_value [VFalse] []
in
assert_raises (ValueFailure
"mk_array: invalid shape vector [vfalse]")
try_non_number_shape;
let try_omega_shape () =
mk_array_value [VNum (omega)] []
in
assert_raises (ValueFailure
"mk_array: shape [ω] suggests that arrray will have more than omega elements")
try_omega_shape;
let try_wrong_data_size () =
mk_array_value (vv [3;3]) (vv [1;2;3])
in
assert_raises (ValueFailure
"mk_array: shape [3, 3] does not match data [1, 2, 3]")
try_wrong_data_size;
| |
be17442b3c64c2119c5e11ef1a598a2b7a9d55342a0c56a34043997621fa89f7 | yallop/ocaml-asp | json_tokens_base.ml |
* Copyright ( c ) 2018 and
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2018 Neelakantan Krishnaswami and Jeremy Yallop
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
type _ tag =
| LBRACKET : unit tag
| RBRACKET : unit tag
| LBRACE : unit tag
| RBRACE : unit tag
| COMMA : unit tag
| COLON : unit tag
| NULL : unit tag
| TRUE : unit tag
| FALSE : unit tag
| STRING : string tag
| DECIMAL : string tag
module Tag =
struct
type 'a t = 'a tag
let print : type a. Format.formatter -> a t -> unit =
fun fmt -> function
| LBRACKET -> Format.fprintf fmt "LBRACKET"
| RBRACKET -> Format.fprintf fmt "RBRACKET"
| LBRACE -> Format.fprintf fmt "LBRACE"
| RBRACE -> Format.fprintf fmt "RBRACE"
| COMMA -> Format.fprintf fmt "COMMA"
| COLON -> Format.fprintf fmt "COLON"
| NULL -> Format.fprintf fmt "NULL"
| TRUE -> Format.fprintf fmt "TRUE"
| FALSE -> Format.fprintf fmt "FALSE"
| STRING -> Format.fprintf fmt "STRING"
| DECIMAL -> Format.fprintf fmt "DECIMAL"
let compare : type a b.a t -> b t -> (a, b) Asp.Types.cmp =
fun x y ->
match x, y with
| LBRACKET , LBRACKET -> Eql
| RBRACKET , RBRACKET -> Eql
| LBRACE , LBRACE -> Eql
| RBRACE , RBRACE -> Eql
| COMMA , COMMA -> Eql
| COLON , COLON -> Eql
| NULL , NULL -> Eql
| TRUE , TRUE -> Eql
| FALSE , FALSE -> Eql
| STRING , STRING -> Eql
| DECIMAL , DECIMAL -> Eql
| x , y -> if Obj.repr x < Obj.repr y then Leq else Geq
end
let format_tok : type a. Format.formatter -> (a tag * a) -> unit =
fun ppf -> function
| LBRACKET , () -> Format.fprintf ppf "LBRACKET"
| RBRACKET , () -> Format.fprintf ppf "RBRACKET"
| LBRACE , () -> Format.fprintf ppf "LBRACE"
| RBRACE , () -> Format.fprintf ppf "RBRACE"
| COMMA , () -> Format.fprintf ppf "COMMA"
| COLON , () -> Format.fprintf ppf "COLON"
| NULL , () -> Format.fprintf ppf "NULL"
| TRUE , () -> Format.fprintf ppf "TRUE"
| FALSE , () -> Format.fprintf ppf "FALSE"
| STRING , s -> Format.fprintf ppf "STRING %s" s
| DECIMAL , s -> Format.fprintf ppf "DECIMAL %s" s
type utag = U : _ tag -> utag [@@unboxed]
type t = T : 'a tag * 'a -> t
let to_int : utag -> int = Obj.magic
let tag : t -> utag = function (T (tag,_)) -> U tag
module Ord =
struct
type t = utag
let compare l r = Pervasives.compare (to_int l) (to_int r)
end
module TagSet = Set.Make(Ord)
let all = TagSet.of_list
[U LBRACKET;
U RBRACKET;
U LBRACE;
U RBRACE;
U COMMA;
U COLON;
U NULL;
U TRUE;
U FALSE;
U STRING;
U DECIMAL]
let inj t = U t
let match_ : type a b. t -> a tag -> (a -> b) -> (unit -> b) -> b =
fun (T (tag, v)) tag' yes no ->
if U tag = U tag' then yes (Obj.magic v) else no ()
let matchlist_ : type a b. t -> a tag list -> (a -> b) -> (unit -> b) -> b =
fun (T (tag, v)) tags yes no ->
if List.mem (Obj.magic tag) tags then yes (Obj.magic v) else no ()
| null | https://raw.githubusercontent.com/yallop/ocaml-asp/a092f17ea55d427c63414899e39a8fe80b30db14/benchmarks/json/json_tokens_base.ml | ocaml |
* Copyright ( c ) 2018 and
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2018 Neelakantan Krishnaswami and Jeremy Yallop
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
type _ tag =
| LBRACKET : unit tag
| RBRACKET : unit tag
| LBRACE : unit tag
| RBRACE : unit tag
| COMMA : unit tag
| COLON : unit tag
| NULL : unit tag
| TRUE : unit tag
| FALSE : unit tag
| STRING : string tag
| DECIMAL : string tag
module Tag =
struct
type 'a t = 'a tag
let print : type a. Format.formatter -> a t -> unit =
fun fmt -> function
| LBRACKET -> Format.fprintf fmt "LBRACKET"
| RBRACKET -> Format.fprintf fmt "RBRACKET"
| LBRACE -> Format.fprintf fmt "LBRACE"
| RBRACE -> Format.fprintf fmt "RBRACE"
| COMMA -> Format.fprintf fmt "COMMA"
| COLON -> Format.fprintf fmt "COLON"
| NULL -> Format.fprintf fmt "NULL"
| TRUE -> Format.fprintf fmt "TRUE"
| FALSE -> Format.fprintf fmt "FALSE"
| STRING -> Format.fprintf fmt "STRING"
| DECIMAL -> Format.fprintf fmt "DECIMAL"
let compare : type a b.a t -> b t -> (a, b) Asp.Types.cmp =
fun x y ->
match x, y with
| LBRACKET , LBRACKET -> Eql
| RBRACKET , RBRACKET -> Eql
| LBRACE , LBRACE -> Eql
| RBRACE , RBRACE -> Eql
| COMMA , COMMA -> Eql
| COLON , COLON -> Eql
| NULL , NULL -> Eql
| TRUE , TRUE -> Eql
| FALSE , FALSE -> Eql
| STRING , STRING -> Eql
| DECIMAL , DECIMAL -> Eql
| x , y -> if Obj.repr x < Obj.repr y then Leq else Geq
end
let format_tok : type a. Format.formatter -> (a tag * a) -> unit =
fun ppf -> function
| LBRACKET , () -> Format.fprintf ppf "LBRACKET"
| RBRACKET , () -> Format.fprintf ppf "RBRACKET"
| LBRACE , () -> Format.fprintf ppf "LBRACE"
| RBRACE , () -> Format.fprintf ppf "RBRACE"
| COMMA , () -> Format.fprintf ppf "COMMA"
| COLON , () -> Format.fprintf ppf "COLON"
| NULL , () -> Format.fprintf ppf "NULL"
| TRUE , () -> Format.fprintf ppf "TRUE"
| FALSE , () -> Format.fprintf ppf "FALSE"
| STRING , s -> Format.fprintf ppf "STRING %s" s
| DECIMAL , s -> Format.fprintf ppf "DECIMAL %s" s
type utag = U : _ tag -> utag [@@unboxed]
type t = T : 'a tag * 'a -> t
let to_int : utag -> int = Obj.magic
let tag : t -> utag = function (T (tag,_)) -> U tag
module Ord =
struct
type t = utag
let compare l r = Pervasives.compare (to_int l) (to_int r)
end
module TagSet = Set.Make(Ord)
let all = TagSet.of_list
[U LBRACKET;
U RBRACKET;
U LBRACE;
U RBRACE;
U COMMA;
U COLON;
U NULL;
U TRUE;
U FALSE;
U STRING;
U DECIMAL]
let inj t = U t
let match_ : type a b. t -> a tag -> (a -> b) -> (unit -> b) -> b =
fun (T (tag, v)) tag' yes no ->
if U tag = U tag' then yes (Obj.magic v) else no ()
let matchlist_ : type a b. t -> a tag list -> (a -> b) -> (unit -> b) -> b =
fun (T (tag, v)) tags yes no ->
if List.mem (Obj.magic tag) tags then yes (Obj.magic v) else no ()
| |
89137d52ca0f97d90a8f84362253ef99423a85e1de592da303eb8cc9160f8d5f | ates/netspire-core | mod_ippool.erl | -module(mod_ippool).
-behaviour(gen_module).
%% API
-export([info/0,
allocate/1,
add_framed_ip/1,
renew_framed_ip/1,
release_framed_ip/1]).
%% gen_module callbacks
-export([start/1, stop/0]).
-include("../netspire.hrl").
-include("../radius/radius.hrl").
-record(ippool_entry, {ip, pool, expires_at = 0}).
-define(TIMEOUT, 300).
start(Options) ->
?INFO_MSG("Starting dynamic module ~p~n", [?MODULE]),
mnesia:create_table(ippool, [{disc_copies, [node()]},
{type, ordered_set},
{record_name, ippool_entry},
{attributes, record_info(fields, ippool_entry)}]),
mnesia:add_table_copy(ippool, node(), disc_copies),
case proplists:get_value(allocate, Options, true) of
false ->
ok;
true ->
mnesia:clear_table(ippool),
?INFO_MSG("Cleaning up ippool~n", []),
Pools = proplists:get_value(pools, Options, []),
mod_ippool:allocate(Pools)
end,
netspire_hooks:add(ippool_lease_ip, ?MODULE, add_framed_ip),
netspire_hooks:add(ippool_renew_ip, ?MODULE, renew_framed_ip),
netspire_hooks:add(ippool_release_ip, ?MODULE, release_framed_ip).
allocate(Pools) ->
?INFO_MSG("Allocating ip pools~n", []),
lists:foreach(fun add_pool/1, Pools).
add_pool({Pool, Ranges}) ->
lists:foreach(fun(Range) -> add_range(Pool, Range) end, Ranges).
add_range(Pool, Range) ->
F = fun(IP) ->
Rec = #ippool_entry{pool = Pool, ip = IP},
mnesia:dirty_write(ippool, Rec)
end,
lists:foreach(F, iplib:range2list(Range)).
lease(Pool) ->
Timeout = gen_module:get_option(?MODULE, timeout, ?TIMEOUT),
Now = netspire_util:timestamp(),
ExpiresAt = Now + Timeout,
MatchHead = #ippool_entry{ip = '$1', pool = Pool, expires_at = '$3'},
MatchSpec = [{MatchHead, [{'=<', '$3', Now}], ['$1']}],
F = fun() ->
case mnesia:select(ippool, MatchSpec, 1, write) of
'$end_of_table' ->
case gen_module:get_option(?MODULE, use_another_one_free_pool) of
yes ->
MatchHead1 = #ippool_entry{ip = '_', pool = '$1', expires_at = 0},
MatchSpec1 = [{MatchHead1, [], ['$1']}],
FreePools = mnesia:dirty_select(ippool, MatchSpec1),
try
FreePool = lists:nth(1, FreePools),
lease(FreePool)
catch
_:_ ->
{error, empty}
end;
_ ->
{error, empty}
end;
{[IP], _} ->
Rec = #ippool_entry{ip = IP, pool = Pool, expires_at = ExpiresAt},
mnesia:write(ippool, Rec, write),
{ok, IP}
end
end,
case mnesia:transaction(F) of
{atomic, Result} ->
Result;
{aborted, Reason} ->
{error, Reason}
end.
renew(IP) ->
Timeout = gen_module:get_option(?MODULE, timeout, ?TIMEOUT),
Now = netspire_util:timestamp(),
ExpiresAt = Now + Timeout,
F = fun() ->
case mnesia:read({ippool, IP}) of
[Rec] ->
Entry = Rec#ippool_entry{expires_at = ExpiresAt},
mnesia:write(ippool, Entry, write),
{ok, IP};
_ ->
{error, not_found}
end
end,
case mnesia:transaction(F) of
{atomic, Result} ->
Result;
{aborted, Reason} ->
{error, Reason}
end.
info() ->
[mnesia:dirty_read({ippool, K}) || K <- mnesia:dirty_all_keys(ippool)].
add_framed_ip({reject, _} = Response) ->
Response;
add_framed_ip(Response) ->
case radius:attribute_value("Framed-IP-Address", Response) of
undefined ->
Pool = case radius:attribute_value("Netspire-Framed-Pool", Response) of
undefined ->
gen_module:get_option(?MODULE, default, main);
Value ->
list_to_atom(Value)
end,
case lease(Pool) of
{ok, IP} ->
?INFO_MSG("Adding Framed-IP-Address ~s~n", [inet_parse:ntoa(IP)]),
Attrs = Response#radius_packet.attrs,
Response#radius_packet{attrs = [{"Framed-IP-Address", IP} | Attrs]};
{error, empty} ->
?WARNING_MSG("No more free ip addresses~n", []),
{stop, {reject, []}};
{error, Reason} ->
?WARNING_MSG("Cannot lease Framed-IP-Address due to ~p~n", [Reason]),
{stop, {reject, []}}
end;
_ -> Response
end.
renew_framed_ip(Request) ->
IP = radius:attribute_value("Framed-IP-Address", Request),
case renew(IP) of
{ok, _} ->
?INFO_MSG("Framed-IP-Address ~s is renewed~n", [inet_parse:ntoa(IP)]);
{error, not_found} ->
ok;
{error, Reason} ->
?WARNING_MSG("Cannot renew Framed-IP-Address ~s"
"due to ~p~n", [inet_parse:ntoa(IP), Reason])
end.
release_framed_ip(Request) ->
IP = radius:attribute_value("Framed-IP-Address", Request),
case mnesia:dirty_read({ippool, IP}) of
[Rec] ->
?INFO_MSG("Release Framed-IP-Address ~s~n", [inet_parse:ntoa(IP)]),
Entry = Rec#ippool_entry{expires_at = 0},
mnesia:dirty_write(ippool, Entry);
_ -> ok
end.
stop() ->
?INFO_MSG("Stopping dynamic module ~p~n", [?MODULE]),
netspire_hooks:delete_all(?MODULE).
| null | https://raw.githubusercontent.com/ates/netspire-core/746c0f254aa6f2669040d954096b4a95ae58b3ce/src/modules/mod_ippool.erl | erlang | API
gen_module callbacks | -module(mod_ippool).
-behaviour(gen_module).
-export([info/0,
allocate/1,
add_framed_ip/1,
renew_framed_ip/1,
release_framed_ip/1]).
-export([start/1, stop/0]).
-include("../netspire.hrl").
-include("../radius/radius.hrl").
-record(ippool_entry, {ip, pool, expires_at = 0}).
-define(TIMEOUT, 300).
start(Options) ->
?INFO_MSG("Starting dynamic module ~p~n", [?MODULE]),
mnesia:create_table(ippool, [{disc_copies, [node()]},
{type, ordered_set},
{record_name, ippool_entry},
{attributes, record_info(fields, ippool_entry)}]),
mnesia:add_table_copy(ippool, node(), disc_copies),
case proplists:get_value(allocate, Options, true) of
false ->
ok;
true ->
mnesia:clear_table(ippool),
?INFO_MSG("Cleaning up ippool~n", []),
Pools = proplists:get_value(pools, Options, []),
mod_ippool:allocate(Pools)
end,
netspire_hooks:add(ippool_lease_ip, ?MODULE, add_framed_ip),
netspire_hooks:add(ippool_renew_ip, ?MODULE, renew_framed_ip),
netspire_hooks:add(ippool_release_ip, ?MODULE, release_framed_ip).
allocate(Pools) ->
?INFO_MSG("Allocating ip pools~n", []),
lists:foreach(fun add_pool/1, Pools).
add_pool({Pool, Ranges}) ->
lists:foreach(fun(Range) -> add_range(Pool, Range) end, Ranges).
add_range(Pool, Range) ->
F = fun(IP) ->
Rec = #ippool_entry{pool = Pool, ip = IP},
mnesia:dirty_write(ippool, Rec)
end,
lists:foreach(F, iplib:range2list(Range)).
lease(Pool) ->
Timeout = gen_module:get_option(?MODULE, timeout, ?TIMEOUT),
Now = netspire_util:timestamp(),
ExpiresAt = Now + Timeout,
MatchHead = #ippool_entry{ip = '$1', pool = Pool, expires_at = '$3'},
MatchSpec = [{MatchHead, [{'=<', '$3', Now}], ['$1']}],
F = fun() ->
case mnesia:select(ippool, MatchSpec, 1, write) of
'$end_of_table' ->
case gen_module:get_option(?MODULE, use_another_one_free_pool) of
yes ->
MatchHead1 = #ippool_entry{ip = '_', pool = '$1', expires_at = 0},
MatchSpec1 = [{MatchHead1, [], ['$1']}],
FreePools = mnesia:dirty_select(ippool, MatchSpec1),
try
FreePool = lists:nth(1, FreePools),
lease(FreePool)
catch
_:_ ->
{error, empty}
end;
_ ->
{error, empty}
end;
{[IP], _} ->
Rec = #ippool_entry{ip = IP, pool = Pool, expires_at = ExpiresAt},
mnesia:write(ippool, Rec, write),
{ok, IP}
end
end,
case mnesia:transaction(F) of
{atomic, Result} ->
Result;
{aborted, Reason} ->
{error, Reason}
end.
renew(IP) ->
Timeout = gen_module:get_option(?MODULE, timeout, ?TIMEOUT),
Now = netspire_util:timestamp(),
ExpiresAt = Now + Timeout,
F = fun() ->
case mnesia:read({ippool, IP}) of
[Rec] ->
Entry = Rec#ippool_entry{expires_at = ExpiresAt},
mnesia:write(ippool, Entry, write),
{ok, IP};
_ ->
{error, not_found}
end
end,
case mnesia:transaction(F) of
{atomic, Result} ->
Result;
{aborted, Reason} ->
{error, Reason}
end.
info() ->
[mnesia:dirty_read({ippool, K}) || K <- mnesia:dirty_all_keys(ippool)].
add_framed_ip({reject, _} = Response) ->
Response;
add_framed_ip(Response) ->
case radius:attribute_value("Framed-IP-Address", Response) of
undefined ->
Pool = case radius:attribute_value("Netspire-Framed-Pool", Response) of
undefined ->
gen_module:get_option(?MODULE, default, main);
Value ->
list_to_atom(Value)
end,
case lease(Pool) of
{ok, IP} ->
?INFO_MSG("Adding Framed-IP-Address ~s~n", [inet_parse:ntoa(IP)]),
Attrs = Response#radius_packet.attrs,
Response#radius_packet{attrs = [{"Framed-IP-Address", IP} | Attrs]};
{error, empty} ->
?WARNING_MSG("No more free ip addresses~n", []),
{stop, {reject, []}};
{error, Reason} ->
?WARNING_MSG("Cannot lease Framed-IP-Address due to ~p~n", [Reason]),
{stop, {reject, []}}
end;
_ -> Response
end.
renew_framed_ip(Request) ->
IP = radius:attribute_value("Framed-IP-Address", Request),
case renew(IP) of
{ok, _} ->
?INFO_MSG("Framed-IP-Address ~s is renewed~n", [inet_parse:ntoa(IP)]);
{error, not_found} ->
ok;
{error, Reason} ->
?WARNING_MSG("Cannot renew Framed-IP-Address ~s"
"due to ~p~n", [inet_parse:ntoa(IP), Reason])
end.
release_framed_ip(Request) ->
IP = radius:attribute_value("Framed-IP-Address", Request),
case mnesia:dirty_read({ippool, IP}) of
[Rec] ->
?INFO_MSG("Release Framed-IP-Address ~s~n", [inet_parse:ntoa(IP)]),
Entry = Rec#ippool_entry{expires_at = 0},
mnesia:dirty_write(ippool, Entry);
_ -> ok
end.
stop() ->
?INFO_MSG("Stopping dynamic module ~p~n", [?MODULE]),
netspire_hooks:delete_all(?MODULE).
|
460108b06d39223f164e1c02bf8f54af1f6fa65511140ccaf574524a48383054 | sbcl/specializable | signum-specializer.lisp | ;;;; signum-specializer.lisp --- signum specializer examples.
;;;;
Copyright ( C ) 2013 , 2014 ,
;;;;
Author : < >
(cl:defpackage #:signum-specializer.example
(:use
#:cl
#:specializable))
(cl:in-package #:signum-specializer.example)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass signum-specializer (extended-specializer)
((signum :initarg :signum :reader %signum)))
(defclass signum-generic-function (specializable-generic-function)
()
(:metaclass sb-mop:funcallable-standard-class))
(define-extended-specializer-syntax signum
(:class signum-specializer)
(:parser (generic-function signum)
(declare (ignore generic-function))
(make-instance 'signum-specializer :signum signum))
(:unparser (generic-function specializer)
(declare (ignore generic-function))
(list (%signum specializer)))))
(defmethod sb-pcl::same-specializer-p
((s1 signum-specializer) (s2 signum-specializer))
(= (%signum s1) (%signum s2)))
(defmethod generalizer-equal-hash-key ((gf signum-generic-function)
(g signum-specializer))
(%signum g))
(defmethod generalizer-of-using-class ((gf signum-generic-function)
object arg-position)
(typecase object
(real (make-instance 'signum-specializer :signum (signum object)))
(t (call-next-method))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod sb-pcl:specializer-type-specifier
((proto-generic-function signum-generic-function)
(proto-method standard-method)
(specializer signum-specializer))
(case (%signum specializer)
(-1 '(real * (0)))
(0 '(real 0 0))
(1 '(real (0) *)))))
(defmethod specializer-accepts-generalizer-p
((gf signum-generic-function)
(specializer signum-specializer)
(thing signum-specializer))
(if (= (%signum specializer) (%signum thing))
(values t t)
(values nil t)))
(defmethod specializer-accepts-generalizer-p ((gf signum-generic-function)
(specializer sb-mop:specializer)
(thing signum-specializer))
(specializer-accepts-generalizer-p gf specializer (class-of (%signum thing))))
;;; note: this method operates in full knowledge of the object, and so
;;; does not require the generic function as an argument.
(defmethod specializer-accepts-p ((specializer signum-specializer) obj)
(and (realp obj)
(= (signum obj) (%signum specializer))))
(defmethod specializer< ((gf signum-generic-function)
(s1 signum-specializer)
(s2 signum-specializer) generalizer)
(declare (ignore generalizer))
(if (= (%signum s1) (%signum s2))
'=
'//))
(defmethod specializer< ((gf signum-generic-function)
(s1 signum-specializer)
(s2 class)
generalizer)
'<)
(defmethod specializer< ((gf signum-generic-function)
(s1 signum-specializer)
(s2 sb-mop:eql-specializer)
generalizer)
'>)
(defmethod specializer< ((gf signum-generic-function)
(s1 sb-mop:specializer)
(s2 signum-specializer)
generalizer)
(invert-specializer<-relation (specializer< gf s2 s1 generalizer)))
;;; note: the need for this method is tricky: we need to translate
;;; from generalizers that our specializers "know" about to those that
ordinary generic functions and specializers might know about .
(defmethod specializer< ((gf signum-generic-function)
(s1 sb-mop:specializer)
(s2 sb-mop:specializer)
(generalizer signum-specializer))
(specializer< gf s1 s2 (class-of (%signum generalizer))))
;;; tests / examples
(eval-when (:compile-toplevel :load-toplevel :execute)
(defgeneric fact (n)
(:generic-function-class signum-generic-function)))
(defmethod fact ((n (signum 0))) 1)
(defmethod fact ((n (signum 1))) (* n (fact (1- n))))
(assert (eql (fact 6) 720))
(assert (eql (fact 6.0) 720.0))
(defmethod no-applicable-method ((gf (eql #'fact)) &rest args)
(declare (ignore args))
'gotcha)
(assert (eql (fact -6) 'gotcha))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defgeneric signum-class-specializers (x)
(:generic-function-class signum-generic-function)
(:method-combination list)))
(defmethod signum-class-specializers list ((x float)) 'float)
(defmethod signum-class-specializers list ((x integer)) 'integer)
(defmethod signum-class-specializers list ((x (signum 1))) 1)
(assert (equal (signum-class-specializers 1.0) '(1 float)))
(assert (equal (signum-class-specializers 1) '(1 integer)))
(assert (equal (signum-class-specializers -1.0) '(float)))
(assert (equal (signum-class-specializers -1) '(integer)))
| null | https://raw.githubusercontent.com/sbcl/specializable/a08048ce874a2a8c58e4735d88de3bf3da0de052/examples/signum-specializer.lisp | lisp | signum-specializer.lisp --- signum specializer examples.
note: this method operates in full knowledge of the object, and so
does not require the generic function as an argument.
note: the need for this method is tricky: we need to translate
from generalizers that our specializers "know" about to those that
tests / examples | Copyright ( C ) 2013 , 2014 ,
Author : < >
(cl:defpackage #:signum-specializer.example
(:use
#:cl
#:specializable))
(cl:in-package #:signum-specializer.example)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass signum-specializer (extended-specializer)
((signum :initarg :signum :reader %signum)))
(defclass signum-generic-function (specializable-generic-function)
()
(:metaclass sb-mop:funcallable-standard-class))
(define-extended-specializer-syntax signum
(:class signum-specializer)
(:parser (generic-function signum)
(declare (ignore generic-function))
(make-instance 'signum-specializer :signum signum))
(:unparser (generic-function specializer)
(declare (ignore generic-function))
(list (%signum specializer)))))
(defmethod sb-pcl::same-specializer-p
((s1 signum-specializer) (s2 signum-specializer))
(= (%signum s1) (%signum s2)))
(defmethod generalizer-equal-hash-key ((gf signum-generic-function)
(g signum-specializer))
(%signum g))
(defmethod generalizer-of-using-class ((gf signum-generic-function)
object arg-position)
(typecase object
(real (make-instance 'signum-specializer :signum (signum object)))
(t (call-next-method))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod sb-pcl:specializer-type-specifier
((proto-generic-function signum-generic-function)
(proto-method standard-method)
(specializer signum-specializer))
(case (%signum specializer)
(-1 '(real * (0)))
(0 '(real 0 0))
(1 '(real (0) *)))))
(defmethod specializer-accepts-generalizer-p
((gf signum-generic-function)
(specializer signum-specializer)
(thing signum-specializer))
(if (= (%signum specializer) (%signum thing))
(values t t)
(values nil t)))
(defmethod specializer-accepts-generalizer-p ((gf signum-generic-function)
(specializer sb-mop:specializer)
(thing signum-specializer))
(specializer-accepts-generalizer-p gf specializer (class-of (%signum thing))))
(defmethod specializer-accepts-p ((specializer signum-specializer) obj)
(and (realp obj)
(= (signum obj) (%signum specializer))))
(defmethod specializer< ((gf signum-generic-function)
(s1 signum-specializer)
(s2 signum-specializer) generalizer)
(declare (ignore generalizer))
(if (= (%signum s1) (%signum s2))
'=
'//))
(defmethod specializer< ((gf signum-generic-function)
(s1 signum-specializer)
(s2 class)
generalizer)
'<)
(defmethod specializer< ((gf signum-generic-function)
(s1 signum-specializer)
(s2 sb-mop:eql-specializer)
generalizer)
'>)
(defmethod specializer< ((gf signum-generic-function)
(s1 sb-mop:specializer)
(s2 signum-specializer)
generalizer)
(invert-specializer<-relation (specializer< gf s2 s1 generalizer)))
ordinary generic functions and specializers might know about .
(defmethod specializer< ((gf signum-generic-function)
(s1 sb-mop:specializer)
(s2 sb-mop:specializer)
(generalizer signum-specializer))
(specializer< gf s1 s2 (class-of (%signum generalizer))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defgeneric fact (n)
(:generic-function-class signum-generic-function)))
(defmethod fact ((n (signum 0))) 1)
(defmethod fact ((n (signum 1))) (* n (fact (1- n))))
(assert (eql (fact 6) 720))
(assert (eql (fact 6.0) 720.0))
(defmethod no-applicable-method ((gf (eql #'fact)) &rest args)
(declare (ignore args))
'gotcha)
(assert (eql (fact -6) 'gotcha))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defgeneric signum-class-specializers (x)
(:generic-function-class signum-generic-function)
(:method-combination list)))
(defmethod signum-class-specializers list ((x float)) 'float)
(defmethod signum-class-specializers list ((x integer)) 'integer)
(defmethod signum-class-specializers list ((x (signum 1))) 1)
(assert (equal (signum-class-specializers 1.0) '(1 float)))
(assert (equal (signum-class-specializers 1) '(1 integer)))
(assert (equal (signum-class-specializers -1.0) '(float)))
(assert (equal (signum-class-specializers -1) '(integer)))
|
8bc3be2efe988a57653be45f8373abcd11a51c3c6eafae2c2d3ece41e15ac026 | caradoc-org/caradoc | operator.ml | (*****************************************************************************)
(* Caradoc: a PDF parser and validator *)
Copyright ( C ) 2016 - 2017
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
(* *)
(* 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 .
(*****************************************************************************)
open Boundedint
open Directobject
open Errors
open Params
module Operator = struct
type num_t =
| Int of BoundedInt.t
| Real of string
type coord_t = num_t * num_t
type matrix6_t = num_t * num_t * num_t * num_t * num_t * num_t
type rgb_t = {r : num_t; g : num_t; b : num_t}
type cmyk_t = {c : num_t; m : num_t; y : num_t; k : num_t}
type numstr_t =
| Num of num_t
| Str of string
type t =
| Op_q
| Op_Q
| Op_cm of matrix6_t
| Op_w of num_t
| Op_J of num_t
| Op_j of num_t
| Op_M of num_t
| Op_d of num_t list * num_t
| Op_m of coord_t
| Op_l of coord_t
| Op_c of coord_t * coord_t * coord_t
| Op_v of coord_t * coord_t
| Op_y of coord_t * coord_t
| Op_h
| Op_re of coord_t * coord_t
| Op_ri of string
| Op_i of num_t
| Op_gs of string
| Op_S
| Op_s
| Op_f
| Op_F
| Op_f_star
| Op_B
| Op_B_star
| Op_b
| Op_b_star
| Op_n
| Op_W
| Op_W_star
| Op_BT
| Op_ET
| Op_Tc of num_t
| Op_Tw of num_t
| Op_Tz of num_t
| Op_TL of num_t
| Op_Tf of string * num_t
| Op_Tr of num_t
| Op_Ts of num_t
| Op_Td of coord_t
| Op_TD of coord_t
| Op_Tm of matrix6_t
| Op_T_star
| Op_Tj of string
| Op_quote of string
| Op_dblquote of num_t * num_t * string
| Op_TJ of numstr_t list
| Op_d0 of coord_t
| Op_d1 of coord_t * coord_t * coord_t
| Op_CS of string
| Op_cs of string
| Op_SC of DirectObject.t list
| Op_SCN of DirectObject.t list
| Op_sc of DirectObject.t list
| Op_scn of DirectObject.t list
| Op_G of num_t
| Op_g of num_t
| Op_RG of rgb_t
| Op_rg of rgb_t
| Op_K of cmyk_t
| Op_k of cmyk_t
| Op_sh of string
| Op_INLINE_IMAGE of DirectObject.dict_t * string
| Op_Do of string
| Op_MP of string
| Op_DP1 of string * DirectObject.dict_t
| Op_DP2 of string * string
| Op_BMC of string
| Op_BDC1 of string * DirectObject.dict_t
| Op_BDC2 of string * string
| Op_EMC
| Op_BX
| Op_EX
(*********************)
PDF reference 8.2
(*********************)
type category_t =
| Compatibility
| GeneralGraphicsState
| SpecialGraphicsState
| PathConstruction
| PathPainting
| ClippingPath (* W W* *)
| TextState
| TextPositioning
| TextShowing
Specific to fonts
| Color
| MarkedContent
| Other
type state_t =
| S_PageDescription
| S_TextObject
| S_PathObject
| S_ClippingPath
let command_to_string (command : t) : string =
match command with
| Op_q -> "q"
| Op_Q -> "Q"
| Op_cm _ -> "cm"
| Op_w _ -> "w"
| Op_J _ -> "J"
| Op_j _ -> "j"
| Op_M _ -> "M"
| Op_d _ -> "d"
| Op_m _ -> "m"
| Op_l _ -> "l"
| Op_c _ -> "c"
| Op_v _ -> "v"
| Op_y _ -> "y"
| Op_h -> "h"
| Op_re _ -> "re"
| Op_ri _ -> "ri"
| Op_i _ -> "i"
| Op_gs _ -> "gs"
| Op_S -> "S"
| Op_s -> "s"
| Op_f -> "f"
| Op_F -> "F"
| Op_f_star -> "f*"
| Op_B -> "B"
| Op_B_star -> "B*"
| Op_b -> "b"
| Op_b_star -> "B*"
| Op_n -> "n"
| Op_W -> "W"
| Op_W_star -> "W*"
| Op_BT -> "BT"
| Op_ET -> "ET"
| Op_Tc _ -> "Tc"
| Op_Tw _ -> "Tw"
| Op_Tz _ -> "Tz"
| Op_TL _ -> "TL"
| Op_Tf _ -> "Tf"
| Op_Tr _ -> "Tr"
| Op_Ts _ -> "Ts"
| Op_Td _ -> "Td"
| Op_TD _ -> "TD"
| Op_Tm _ -> "Tm"
| Op_T_star -> "T*"
| Op_Tj _ -> "Tj"
| Op_quote _ -> "'"
| Op_dblquote _ -> "\""
| Op_TJ _ -> "TJ"
| Op_d0 _ -> "d0"
| Op_d1 _ -> "d1"
| Op_CS _ -> "CS"
| Op_cs _ -> "cs"
| Op_SC _ -> "SC"
| Op_SCN _ -> "SCN"
| Op_sc _ -> "sc"
| Op_scn _ -> "scn"
| Op_G _ -> "G"
| Op_g _ -> "g"
| Op_RG _ -> "RG"
| Op_rg _ -> "rg"
| Op_K _ -> "K"
| Op_k _ -> "k"
| Op_sh _ -> "sh"
| Op_INLINE_IMAGE _ -> "BI"
| Op_Do _ -> "Do"
| Op_MP _ -> "MP"
| Op_DP1 _
| Op_DP2 _ -> "DP"
| Op_BMC _ -> "BMC"
| Op_BDC1 _
| Op_BDC2 _ -> "BDC"
| Op_EMC -> "EMC"
| Op_BX -> "BX"
| Op_EX -> "EX"
let state_to_string (state : state_t) : string =
match state with
| S_PageDescription ->
"page description"
| S_TextObject ->
"text object"
| S_PathObject ->
"path object"
| S_ClippingPath ->
"clipping path"
(*********************)
PDF reference 8.2
(*********************)
let get_category (command : t) : category_t =
match command with
| Op_BX | Op_EX ->
Compatibility
| Op_w _ | Op_J _ | Op_j _ | Op_M _ | Op_d _ | Op_ri _ | Op_i _ | Op_gs _ ->
GeneralGraphicsState
| Op_q | Op_Q | Op_cm _ ->
SpecialGraphicsState
| Op_m _ | Op_l _ | Op_c _ | Op_v _ | Op_y _ | Op_h | Op_re _ ->
PathConstruction
| Op_S | Op_s | Op_f | Op_F | Op_f_star | Op_B | Op_B_star | Op_b | Op_b_star | Op_n ->
PathPainting
| Op_W | Op_W_star ->
ClippingPath
| Op_Tc _ | Op_Tw _ | Op_Tz _ | Op_TL _ | Op_Tf _ | Op_Tr _ | Op_Ts _ ->
TextState
| Op_Td _ | Op_TD _ | Op_Tm _ | Op_T_star ->
TextPositioning
| Op_Tj _ | Op_quote _ | Op_dblquote _ | Op_TJ _ ->
TextShowing
| Op_d0 _ | Op_d1 _ ->
Type3Font
| Op_CS _ | Op_cs _ | Op_SC _ | Op_SCN _ | Op_sc _ | Op_scn _ | Op_G _ | Op_g _ | Op_RG _ | Op_rg _ | Op_K _ | Op_k _ ->
Color
| Op_MP _ | Op_DP1 _ | Op_DP2 _ | Op_BMC _ | Op_BDC1 _ | Op_BDC2 _ | Op_EMC ->
MarkedContent
| Op_BT | Op_ET
| Op_sh _
| Op_INLINE_IMAGE _
| Op_Do _ ->
Other
let check_command_page (command : t) : state_t option =
match command with
| Op_sh _
| Op_INLINE_IMAGE _
| Op_Do _ ->
Some S_PageDescription
| Op_BT ->
Some S_TextObject
| Op_m _
| Op_re _ ->
Some S_PathObject
| _ ->
begin
match get_category command with
| Compatibility
| GeneralGraphicsState
| SpecialGraphicsState
| Color
| TextState
| MarkedContent ->
Some S_PageDescription
| PathConstruction
| PathPainting
| ClippingPath
| TextPositioning
| TextShowing
| Type3Font
| Other ->
None
end
let check_command_text (command : t) : state_t option =
match command with
| Op_ET ->
Some S_PageDescription
| _ ->
begin
match get_category command with
| Compatibility
| GeneralGraphicsState
| Color
| TextState
| TextPositioning
| TextShowing
| MarkedContent ->
Some S_TextObject
| SpecialGraphicsState
| PathConstruction
| PathPainting
| ClippingPath
| Type3Font
| Other ->
None
end
let check_command_path (command : t) : state_t option =
match get_category command with
| Compatibility
| PathConstruction ->
Some S_PathObject
| PathPainting ->
Some S_PageDescription
| ClippingPath ->
Some S_ClippingPath
| GeneralGraphicsState
| SpecialGraphicsState
| TextState
| TextPositioning
| TextShowing
| Type3Font
| Color
| MarkedContent
| Other ->
None
let check_command_clip (command : t) : state_t option =
match get_category command with
| Compatibility ->
Some S_ClippingPath
| PathPainting ->
Some S_PageDescription
| GeneralGraphicsState
| SpecialGraphicsState
| PathConstruction
| ClippingPath
| TextState
| TextPositioning
| TextShowing
| Type3Font
| Color
| MarkedContent
| Other ->
None
let check_command (state : state_t) (command : t) : state_t option =
match state with
| S_PageDescription ->
check_command_page command
| S_TextObject ->
check_command_text command
| S_PathObject ->
check_command_path command
| S_ClippingPath ->
check_command_clip command
let check_font3 (commands : t list) (is_font3 : bool) (error_ctxt : Errors.error_ctxt) : t list =
if not is_font3 then
commands
else
match commands with
| a::b when (get_category a) = Type3Font ->
b
| _ ->
raise (Errors.PDFError ("Expected d0 or d1 as first command in content stream of Type 3 font", error_ctxt))
let check_commands_statemachine (commands : t list) (is_font3 : bool) (error_ctxt : Errors.error_ctxt) : unit =
let last_state = List.fold_left (fun state command ->
Print.debug ( " State = " ^ ( state_to_string state ) ^ " , command = " ^ ( command ) ) ;
Print.debug ("State = " ^ (state_to_string state) ^ ", command = " ^ (command_to_string command));
*)
match check_command state command with
| Some next_state ->
next_state
| None ->
raise (Errors.PDFError (Printf.sprintf "Unexpected command %s in state \"%s\" of content stream" (command_to_string command) (state_to_string state), error_ctxt))
) S_PageDescription (check_font3 commands is_font3 error_ctxt)
in
if last_state != S_PageDescription then
Errors.warning (Printf.sprintf "Content stream does not finish in state \"%s\" but in state \"%s\"" (state_to_string S_PageDescription) (state_to_string last_state)) error_ctxt
let check_commands_statestack (commands : t list) (error_ctxt : Errors.error_ctxt) : unit =
let balance = List.fold_left (fun count command ->
match command with
| Op_q ->
count +: ~:1
| Op_Q ->
let result = count -: ~:1 in
if result <: ~:0 then
raise (Errors.PDFError ("Content stream contains unbalanced q and Q operators", error_ctxt));
result
| _ ->
count
) ~:0 commands
in
if balance >: ~:0 then
Errors.warning "Content stream contains useless q operator" error_ctxt
let check_commands (commands : t list) (is_font3 : bool) (error_ctxt : Errors.error_ctxt) : unit =
check_commands_statemachine commands is_font3 error_ctxt;
check_commands_statestack commands error_ctxt
TODO : check nesting of BT / ET and BMC / EMC operators ( see 14.6.1 )
TODO : check SC / SCN operands
(* TODO : check INLINE_IMAGE *)
end
| null | https://raw.githubusercontent.com/caradoc-org/caradoc/100f53bc55ef682049e10fabf24869bc019dc6ce/src/contentstream/operator.ml | ocaml | ***************************************************************************
Caradoc: a PDF parser and validator
This program is free software; you can redistribute it and/or modify
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.
***************************************************************************
*******************
*******************
W W*
*******************
*******************
TODO : check INLINE_IMAGE | Copyright ( C ) 2016 - 2017
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
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 .
open Boundedint
open Directobject
open Errors
open Params
module Operator = struct
type num_t =
| Int of BoundedInt.t
| Real of string
type coord_t = num_t * num_t
type matrix6_t = num_t * num_t * num_t * num_t * num_t * num_t
type rgb_t = {r : num_t; g : num_t; b : num_t}
type cmyk_t = {c : num_t; m : num_t; y : num_t; k : num_t}
type numstr_t =
| Num of num_t
| Str of string
type t =
| Op_q
| Op_Q
| Op_cm of matrix6_t
| Op_w of num_t
| Op_J of num_t
| Op_j of num_t
| Op_M of num_t
| Op_d of num_t list * num_t
| Op_m of coord_t
| Op_l of coord_t
| Op_c of coord_t * coord_t * coord_t
| Op_v of coord_t * coord_t
| Op_y of coord_t * coord_t
| Op_h
| Op_re of coord_t * coord_t
| Op_ri of string
| Op_i of num_t
| Op_gs of string
| Op_S
| Op_s
| Op_f
| Op_F
| Op_f_star
| Op_B
| Op_B_star
| Op_b
| Op_b_star
| Op_n
| Op_W
| Op_W_star
| Op_BT
| Op_ET
| Op_Tc of num_t
| Op_Tw of num_t
| Op_Tz of num_t
| Op_TL of num_t
| Op_Tf of string * num_t
| Op_Tr of num_t
| Op_Ts of num_t
| Op_Td of coord_t
| Op_TD of coord_t
| Op_Tm of matrix6_t
| Op_T_star
| Op_Tj of string
| Op_quote of string
| Op_dblquote of num_t * num_t * string
| Op_TJ of numstr_t list
| Op_d0 of coord_t
| Op_d1 of coord_t * coord_t * coord_t
| Op_CS of string
| Op_cs of string
| Op_SC of DirectObject.t list
| Op_SCN of DirectObject.t list
| Op_sc of DirectObject.t list
| Op_scn of DirectObject.t list
| Op_G of num_t
| Op_g of num_t
| Op_RG of rgb_t
| Op_rg of rgb_t
| Op_K of cmyk_t
| Op_k of cmyk_t
| Op_sh of string
| Op_INLINE_IMAGE of DirectObject.dict_t * string
| Op_Do of string
| Op_MP of string
| Op_DP1 of string * DirectObject.dict_t
| Op_DP2 of string * string
| Op_BMC of string
| Op_BDC1 of string * DirectObject.dict_t
| Op_BDC2 of string * string
| Op_EMC
| Op_BX
| Op_EX
PDF reference 8.2
type category_t =
| Compatibility
| GeneralGraphicsState
| SpecialGraphicsState
| PathConstruction
| PathPainting
| TextState
| TextPositioning
| TextShowing
Specific to fonts
| Color
| MarkedContent
| Other
type state_t =
| S_PageDescription
| S_TextObject
| S_PathObject
| S_ClippingPath
let command_to_string (command : t) : string =
match command with
| Op_q -> "q"
| Op_Q -> "Q"
| Op_cm _ -> "cm"
| Op_w _ -> "w"
| Op_J _ -> "J"
| Op_j _ -> "j"
| Op_M _ -> "M"
| Op_d _ -> "d"
| Op_m _ -> "m"
| Op_l _ -> "l"
| Op_c _ -> "c"
| Op_v _ -> "v"
| Op_y _ -> "y"
| Op_h -> "h"
| Op_re _ -> "re"
| Op_ri _ -> "ri"
| Op_i _ -> "i"
| Op_gs _ -> "gs"
| Op_S -> "S"
| Op_s -> "s"
| Op_f -> "f"
| Op_F -> "F"
| Op_f_star -> "f*"
| Op_B -> "B"
| Op_B_star -> "B*"
| Op_b -> "b"
| Op_b_star -> "B*"
| Op_n -> "n"
| Op_W -> "W"
| Op_W_star -> "W*"
| Op_BT -> "BT"
| Op_ET -> "ET"
| Op_Tc _ -> "Tc"
| Op_Tw _ -> "Tw"
| Op_Tz _ -> "Tz"
| Op_TL _ -> "TL"
| Op_Tf _ -> "Tf"
| Op_Tr _ -> "Tr"
| Op_Ts _ -> "Ts"
| Op_Td _ -> "Td"
| Op_TD _ -> "TD"
| Op_Tm _ -> "Tm"
| Op_T_star -> "T*"
| Op_Tj _ -> "Tj"
| Op_quote _ -> "'"
| Op_dblquote _ -> "\""
| Op_TJ _ -> "TJ"
| Op_d0 _ -> "d0"
| Op_d1 _ -> "d1"
| Op_CS _ -> "CS"
| Op_cs _ -> "cs"
| Op_SC _ -> "SC"
| Op_SCN _ -> "SCN"
| Op_sc _ -> "sc"
| Op_scn _ -> "scn"
| Op_G _ -> "G"
| Op_g _ -> "g"
| Op_RG _ -> "RG"
| Op_rg _ -> "rg"
| Op_K _ -> "K"
| Op_k _ -> "k"
| Op_sh _ -> "sh"
| Op_INLINE_IMAGE _ -> "BI"
| Op_Do _ -> "Do"
| Op_MP _ -> "MP"
| Op_DP1 _
| Op_DP2 _ -> "DP"
| Op_BMC _ -> "BMC"
| Op_BDC1 _
| Op_BDC2 _ -> "BDC"
| Op_EMC -> "EMC"
| Op_BX -> "BX"
| Op_EX -> "EX"
let state_to_string (state : state_t) : string =
match state with
| S_PageDescription ->
"page description"
| S_TextObject ->
"text object"
| S_PathObject ->
"path object"
| S_ClippingPath ->
"clipping path"
PDF reference 8.2
let get_category (command : t) : category_t =
match command with
| Op_BX | Op_EX ->
Compatibility
| Op_w _ | Op_J _ | Op_j _ | Op_M _ | Op_d _ | Op_ri _ | Op_i _ | Op_gs _ ->
GeneralGraphicsState
| Op_q | Op_Q | Op_cm _ ->
SpecialGraphicsState
| Op_m _ | Op_l _ | Op_c _ | Op_v _ | Op_y _ | Op_h | Op_re _ ->
PathConstruction
| Op_S | Op_s | Op_f | Op_F | Op_f_star | Op_B | Op_B_star | Op_b | Op_b_star | Op_n ->
PathPainting
| Op_W | Op_W_star ->
ClippingPath
| Op_Tc _ | Op_Tw _ | Op_Tz _ | Op_TL _ | Op_Tf _ | Op_Tr _ | Op_Ts _ ->
TextState
| Op_Td _ | Op_TD _ | Op_Tm _ | Op_T_star ->
TextPositioning
| Op_Tj _ | Op_quote _ | Op_dblquote _ | Op_TJ _ ->
TextShowing
| Op_d0 _ | Op_d1 _ ->
Type3Font
| Op_CS _ | Op_cs _ | Op_SC _ | Op_SCN _ | Op_sc _ | Op_scn _ | Op_G _ | Op_g _ | Op_RG _ | Op_rg _ | Op_K _ | Op_k _ ->
Color
| Op_MP _ | Op_DP1 _ | Op_DP2 _ | Op_BMC _ | Op_BDC1 _ | Op_BDC2 _ | Op_EMC ->
MarkedContent
| Op_BT | Op_ET
| Op_sh _
| Op_INLINE_IMAGE _
| Op_Do _ ->
Other
let check_command_page (command : t) : state_t option =
match command with
| Op_sh _
| Op_INLINE_IMAGE _
| Op_Do _ ->
Some S_PageDescription
| Op_BT ->
Some S_TextObject
| Op_m _
| Op_re _ ->
Some S_PathObject
| _ ->
begin
match get_category command with
| Compatibility
| GeneralGraphicsState
| SpecialGraphicsState
| Color
| TextState
| MarkedContent ->
Some S_PageDescription
| PathConstruction
| PathPainting
| ClippingPath
| TextPositioning
| TextShowing
| Type3Font
| Other ->
None
end
let check_command_text (command : t) : state_t option =
match command with
| Op_ET ->
Some S_PageDescription
| _ ->
begin
match get_category command with
| Compatibility
| GeneralGraphicsState
| Color
| TextState
| TextPositioning
| TextShowing
| MarkedContent ->
Some S_TextObject
| SpecialGraphicsState
| PathConstruction
| PathPainting
| ClippingPath
| Type3Font
| Other ->
None
end
let check_command_path (command : t) : state_t option =
match get_category command with
| Compatibility
| PathConstruction ->
Some S_PathObject
| PathPainting ->
Some S_PageDescription
| ClippingPath ->
Some S_ClippingPath
| GeneralGraphicsState
| SpecialGraphicsState
| TextState
| TextPositioning
| TextShowing
| Type3Font
| Color
| MarkedContent
| Other ->
None
let check_command_clip (command : t) : state_t option =
match get_category command with
| Compatibility ->
Some S_ClippingPath
| PathPainting ->
Some S_PageDescription
| GeneralGraphicsState
| SpecialGraphicsState
| PathConstruction
| ClippingPath
| TextState
| TextPositioning
| TextShowing
| Type3Font
| Color
| MarkedContent
| Other ->
None
let check_command (state : state_t) (command : t) : state_t option =
match state with
| S_PageDescription ->
check_command_page command
| S_TextObject ->
check_command_text command
| S_PathObject ->
check_command_path command
| S_ClippingPath ->
check_command_clip command
let check_font3 (commands : t list) (is_font3 : bool) (error_ctxt : Errors.error_ctxt) : t list =
if not is_font3 then
commands
else
match commands with
| a::b when (get_category a) = Type3Font ->
b
| _ ->
raise (Errors.PDFError ("Expected d0 or d1 as first command in content stream of Type 3 font", error_ctxt))
let check_commands_statemachine (commands : t list) (is_font3 : bool) (error_ctxt : Errors.error_ctxt) : unit =
let last_state = List.fold_left (fun state command ->
Print.debug ( " State = " ^ ( state_to_string state ) ^ " , command = " ^ ( command ) ) ;
Print.debug ("State = " ^ (state_to_string state) ^ ", command = " ^ (command_to_string command));
*)
match check_command state command with
| Some next_state ->
next_state
| None ->
raise (Errors.PDFError (Printf.sprintf "Unexpected command %s in state \"%s\" of content stream" (command_to_string command) (state_to_string state), error_ctxt))
) S_PageDescription (check_font3 commands is_font3 error_ctxt)
in
if last_state != S_PageDescription then
Errors.warning (Printf.sprintf "Content stream does not finish in state \"%s\" but in state \"%s\"" (state_to_string S_PageDescription) (state_to_string last_state)) error_ctxt
let check_commands_statestack (commands : t list) (error_ctxt : Errors.error_ctxt) : unit =
let balance = List.fold_left (fun count command ->
match command with
| Op_q ->
count +: ~:1
| Op_Q ->
let result = count -: ~:1 in
if result <: ~:0 then
raise (Errors.PDFError ("Content stream contains unbalanced q and Q operators", error_ctxt));
result
| _ ->
count
) ~:0 commands
in
if balance >: ~:0 then
Errors.warning "Content stream contains useless q operator" error_ctxt
let check_commands (commands : t list) (is_font3 : bool) (error_ctxt : Errors.error_ctxt) : unit =
check_commands_statemachine commands is_font3 error_ctxt;
check_commands_statestack commands error_ctxt
TODO : check nesting of BT / ET and BMC / EMC operators ( see 14.6.1 )
TODO : check SC / SCN operands
end
|
14106bed14b5a607abf20aa48d1f1c15ba508e49822074c4f84bf678e37fb198 | c-cube/stimsym | Base_types.ml |
(* This file is free software. See file "license" for more details. *)
(** {1 Basic Types} *)
module Properties = Bit_set.Make(struct end)
type mime_content = {
mime_ty: string;
mime_data: string;
mime_base64: bool;
}
type eval_side_effect =
| Print_doc of Document.t
| Print_mime of mime_content
type const = {
cst_name: string;
cst_id: int;
mutable cst_properties: Properties.t;
mutable cst_rules: def list;
mutable cst_doc: Document.t;
mutable cst_printer: (int * const_printer) option;
mutable cst_display : mime_printer option;
}
and expr =
| Const of const
| App of expr * expr array
| Z of Z.t
| Q of Q.t
| String of string
| Reg of int (* only in rules RHS *)
and const_printer = const -> (int -> expr CCFormat.printer) -> expr array CCFormat.printer
(* (partial) definition of a symbol *)
and def =
| Rewrite of rewrite_rule
| Fun of prim_fun
and rewrite_rule = {
rr_pat: pattern;
rr_pat_as_expr: expr;
rr_rhs: expr;
}
and pattern =
| P_const of const
| P_z of Z.t
| P_q of Q.t
| P_string of string
| P_app of pattern * pattern array
| P_blank of const option (* anything, or anything with the given head *)
> = 1 elements
> = 0 elements
| P_fail
| P_bind of int * pattern
(* match, then bind register *)
| P_check_same of int * pattern
(* match, then check syntactic equality with content of register *)
| P_alt of pattern list
| P_app_slice of pattern * slice_pattern (* for slices *)
| P_app_slice_unordered of pattern * slice_unordered_pattern
| P_conditional of pattern * expr (* pattern if condition *)
| P_test of pattern * expr (* `p?t` pattern + test on value *)
and slice_pattern =
| SP_vantage of slice_pattern_vantage
only sequence / sequencenull ; min size
(* a subtree used for associative pattern matching *)
and slice_pattern_vantage = {
sp_min_size: int; (* minimum length of matched slice *)
sp_left: slice_pattern; (* matches left slice *)
match this unary pattern first
sp_right: slice_pattern; (* matches right slice *)
}
and slice_unordered_pattern =
pattern to match first , rec , min size
| SUP_pure of pattern list * int (* only sequence/null; min size *)
and binding_seq_body_item =
| Comp_match of pattern * expr
| Comp_match1 of pattern * expr
| Comp_test of expr
and binding_seq = {
comp_body: binding_seq_body_item list;
comp_yield: expr;
}
(* TODO? *)
and prim_fun_args = eval_state
and prim_fun = prim_fun_args -> expr -> expr option
(* function using for tracing evaluation *)
and trace_fun = expr -> expr -> unit
(* state for evaluation *)
and eval_state = {
mutable st_iter_count: int;
(* number of iterations *)
mutable st_rules: rewrite_rule list;
(* permanent list of rules *)
st_effects: (eval_side_effect Stack.t) option;
(* temporary messages *)
mutable st_trace: trace_fun;
(* called on intermediate forms *)
}
(* custom display for expressions *)
and mime_printer = expr -> mime_content list
| null | https://raw.githubusercontent.com/c-cube/stimsym/38c744b5f770b52980abbfe7636a0dc2b91bbeb7/src/core/Base_types.ml | ocaml | This file is free software. See file "license" for more details.
* {1 Basic Types}
only in rules RHS
(partial) definition of a symbol
anything, or anything with the given head
match, then bind register
match, then check syntactic equality with content of register
for slices
pattern if condition
`p?t` pattern + test on value
a subtree used for associative pattern matching
minimum length of matched slice
matches left slice
matches right slice
only sequence/null; min size
TODO?
function using for tracing evaluation
state for evaluation
number of iterations
permanent list of rules
temporary messages
called on intermediate forms
custom display for expressions |
module Properties = Bit_set.Make(struct end)
type mime_content = {
mime_ty: string;
mime_data: string;
mime_base64: bool;
}
type eval_side_effect =
| Print_doc of Document.t
| Print_mime of mime_content
type const = {
cst_name: string;
cst_id: int;
mutable cst_properties: Properties.t;
mutable cst_rules: def list;
mutable cst_doc: Document.t;
mutable cst_printer: (int * const_printer) option;
mutable cst_display : mime_printer option;
}
and expr =
| Const of const
| App of expr * expr array
| Z of Z.t
| Q of Q.t
| String of string
and const_printer = const -> (int -> expr CCFormat.printer) -> expr array CCFormat.printer
and def =
| Rewrite of rewrite_rule
| Fun of prim_fun
and rewrite_rule = {
rr_pat: pattern;
rr_pat_as_expr: expr;
rr_rhs: expr;
}
and pattern =
| P_const of const
| P_z of Z.t
| P_q of Q.t
| P_string of string
| P_app of pattern * pattern array
> = 1 elements
> = 0 elements
| P_fail
| P_bind of int * pattern
| P_check_same of int * pattern
| P_alt of pattern list
| P_app_slice_unordered of pattern * slice_unordered_pattern
and slice_pattern =
| SP_vantage of slice_pattern_vantage
only sequence / sequencenull ; min size
and slice_pattern_vantage = {
match this unary pattern first
}
and slice_unordered_pattern =
pattern to match first , rec , min size
and binding_seq_body_item =
| Comp_match of pattern * expr
| Comp_match1 of pattern * expr
| Comp_test of expr
and binding_seq = {
comp_body: binding_seq_body_item list;
comp_yield: expr;
}
and prim_fun_args = eval_state
and prim_fun = prim_fun_args -> expr -> expr option
and trace_fun = expr -> expr -> unit
and eval_state = {
mutable st_iter_count: int;
mutable st_rules: rewrite_rule list;
st_effects: (eval_side_effect Stack.t) option;
mutable st_trace: trace_fun;
}
and mime_printer = expr -> mime_content list
|
692b9657eae216fbeb345da8fd76a82e588fa4124938861f1f1e08c222cc2f1c | dongcarl/guix | chemistry.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2018 < >
Copyright © 2018 , 2021 < >
Copyright © 2018 < >
Copyright © 2018 < >
Copyright © 2020 < >
Copyright © 2020 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages chemistry)
#:use-module (guix packages)
#:use-module (guix utils)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (gnu packages)
#:use-module (gnu packages algebra)
#:use-module (gnu packages autotools)
#:use-module (gnu packages backup)
#:use-module (gnu packages boost)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages documentation)
#:use-module (gnu packages gl)
#:use-module (gnu packages graphviz)
#:use-module (gnu packages gv)
#:use-module (gnu packages maths)
#:use-module (gnu packages mpi)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages qt)
#:use-module (gnu packages serialization)
#:use-module (gnu packages sphinx)
#:use-module (gnu packages xml)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python))
(define-public avogadrolibs
(package
(name "avogadrolibs")
(version "1.93.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256
(base32 "1xivga626n5acnmwmym8svl0pdri8hkp59czf04ri2zflnviyh39"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(native-inputs
`(("eigen" ,eigen)
("mmtf-cpp" ,mmtf-cpp)
("msgpack" ,msgpack)
("googletest" ,googletest)
("pkg-config" ,pkg-config)
("pybind11" ,pybind11)))
(inputs
`(("glew" ,glew)
("libarchive" ,libarchive)
("libmsym" ,libmsym)
("molequeue" ,molequeue)
("python" ,python)
("spglib" ,spglib)
("qtbase" ,qtbase-5)))
(arguments
'(#:configure-flags (list "-DENABLE_TESTING=ON"
(string-append "-DSPGLIB_INCLUDE_DIR="
(assoc-ref %build-inputs "spglib")
"/include"))))
(home-page "/")
(synopsis "Libraries for chemistry, bioinformatics, and related areas")
(description
"Avogadro libraries provide 3D rendering, visualization, analysis and data
processing useful in computational chemistry, molecular modeling,
bioinformatics, materials science, and related areas.")
(license license:bsd-3)))
(define-public avogadro2
(package
(name "avogadro2")
(version "1.93.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256
(base32
"1z3pjlwja778a1dmvx9aqz2hlw5q9g3kqxhm9slz08452600jsv7"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(native-inputs
`(("eigen" ,eigen)
("pkg-config" ,pkg-config)))
(inputs
`(("avogadrolibs" ,avogadrolibs)
("hdf5" ,hdf5)
("molequeue" ,molequeue)
("qtbase" ,qtbase-5)))
;; TODO: Enable tests with "-DENABLE_TESTING" configure flag.
(arguments
'(#:tests? #f))
(home-page "/")
(synopsis "Advanced molecule editor")
(description
"Avogadro 2 is an advanced molecule editor and visualizer designed for use
in computational chemistry, molecular modeling, bioinformatics, materials
science, and related areas. It offers flexible high quality rendering and a
powerful plugin architecture.")
(license license:bsd-3)))
(define-public domainfinder
(package
(name "domainfinder")
(version "2.0.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"domainfinder/downloads/DomainFinder-"
version ".tar.gz"))
(sha256
(base32
"1z26lsyf7xwnzwjvimmbla7ckipx6p734w7y0jk2a2fzci8fkdcr"))))
(build-system python-build-system)
(inputs
`(("python-mmtk" ,python2-mmtk)))
(arguments
`(#:python ,python-2
;; No test suite
#:tests? #f))
(home-page "-orleans.fr/DomainFinder.html")
(synopsis "Analysis of dynamical domains in proteins")
(description "DomainFinder is an interactive program for the determination
and characterization of dynamical domains in proteins. It can infer dynamical
domains by comparing two protein structures, or from normal mode analysis on a
single structure. The software is currently not actively maintained and works
only with Python 2 and NumPy < 1.9.")
(license license:cecill-c)))
(define-public inchi
(package
(name "inchi")
;; Update the inchi-doc native input when updating inchi.
(version "1.06")
(source (origin
(method url-fetch)
(uri (string-append "-trust.org/download/"
(string-join (string-split version #\.) "")
"/INCHI-1-SRC.zip"))
(sha256
(base32
"1zbygqn0443p0gxwr4kx3m1bkqaj8x9hrpch3s41py7jq08f6x28"))
(file-name (string-append name "-" version ".zip"))))
(build-system gnu-build-system)
(arguments
'(#:tests? #f ; no check target
#:phases
(modify-phases %standard-phases
(delete 'configure) ; no configure script
(add-before 'build 'chdir-to-build-directory
(lambda _ (chdir "INCHI_EXE/inchi-1/gcc") #t))
(add-after 'build 'build-library
(lambda _
(chdir "../../../INCHI_API/libinchi/gcc")
(invoke "make")))
(replace 'install
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(doc (string-append out "/share/doc/inchi"))
(include-dir (string-append out "/include/inchi"))
(lib (string-append out "/lib/inchi"))
(inchi-doc (assoc-ref inputs "inchi-doc"))
(unzip (string-append (assoc-ref inputs "unzip")
"/bin/unzip")))
(chdir "../../..")
;; Install binary.
(with-directory-excursion "INCHI_EXE/bin/Linux"
(rename-file "inchi-1" "inchi")
(install-file "inchi" bin))
;; Install libraries.
(with-directory-excursion "INCHI_API/bin/Linux"
(for-each (lambda (file)
(install-file file lib))
(find-files "." "libinchi\\.so\\.1\\.*")))
;; Install header files.
(with-directory-excursion "INCHI_BASE/src"
(for-each (lambda (file)
(install-file file include-dir))
(find-files "." "\\.h$")))
;; Install documentation.
(mkdir-p doc)
(invoke unzip "-j" "-d" doc inchi-doc)
#t))))))
(native-inputs
`(("unzip" ,unzip)
("inchi-doc"
,(origin
(method url-fetch)
(uri (string-append "-trust.org/download/"
(string-join (string-split version #\.) "")
"/INCHI-1-DOC.zip"))
(sha256
(base32
"1kyda09i9p89xfq90ninwi7w13k1w3ljpl4gqdhpfhi5g8fgxx7f"))
(file-name (string-append name "-" version ".zip"))))))
(home-page "-trust.org")
(synopsis "Utility for manipulating machine-readable chemical structures")
(description
"The @dfn{InChI} (IUPAC International Chemical Identifier) algorithm turns
chemical structures into machine-readable strings of information. InChIs are
unique to the compound they describe and can encode absolute stereochemistry
making chemicals and chemistry machine-readable and discoverable. A simple
analogy is that InChI is the bar-code for chemistry and chemical structures.")
(license (license:non-copyleft
"file"
"See LICENCE in the distribution."))))
(define-public libmsym
(package
(name "libmsym")
(version "0.2.3")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(sha256
(base32
"0a9j28irdsr461qpzlc9z1yjyb9kp64fh5zw7ylspc9zn3189qwk"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(arguments
'(#:configure-flags '("-DBUILD_SHARED_LIBS=ON")
#:tests? #f)) ; no check target
(home-page "")
(synopsis "C library dealing with point group symmetry in molecules")
(description "libmsym is a C library dealing with point group symmetry in
molecules.")
(license license:expat)))
(define-public mmtf-cpp
(package
(name "mmtf-cpp")
(version "1.0.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-cpp")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"17ylramda69plf5w0v5hxbl4ggkdi5s15z55cv0pljl12yvyva8l"))))
(build-system cmake-build-system)
Tests require the soon - to - be - deprecated version 1 of the catch - framework .
(arguments
'(#:tests? #f))
(home-page "/")
(synopsis "C++ API for the Macromolecular Transmission Format")
(description "This package is a library for the
@acronym{MMTF,macromolecular transmission format}, a binary encoding of
biological structures.")
(license license:expat)))
(define-public molequeue
(package
(name "molequeue")
(version "0.9.0")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"releases/download/" version "/molequeue-"
version ".tar.bz2"))
(sha256
(base32
"1w1fgxzqrb5yxvpmnc3c9ymnvixy0z1nfafkd9whg9zw8nbgl998"))))
(build-system cmake-build-system)
(inputs
`(("qtbase" ,qtbase-5)))
(arguments
'(#:configure-flags '("-DENABLE_TESTING=ON")
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-tests
(lambda _
;; TODO: Fix/enable the failing message and clientserver tests.
In the message test , the floating - point value " 5.36893473232 " on
line 165 of molequeue / app / testing / messagetest.cpp should
;; (apparently) be truncated, but it is not.
(substitute* "molequeue/app/testing/messagetest.cpp"
(("5\\.36893473232") "5.36893"))
;; It is unclear why the clientserver test fails, so it is
;; completely disabled.
(substitute* "molequeue/app/testing/CMakeLists.txt"
((".*clientserver.*") ""))
#t))
(add-before 'check 'set-display
(lambda _
;; Make Qt render "offscreen" for the sake of tests.
(setenv "QT_QPA_PLATFORM" "offscreen")
#t)))))
(home-page "/")
(synopsis "Application for coordinating computational jobs")
(description "MoleQueue is a system-tray resident desktop application for
abstracting, managing, and coordinating the execution of tasks both locally and
on remote computational resources. Users can set up local and remote queues
that describe where the task will be executed. Each queue can have programs,
with templates to facilitate the execution of the program. Input files can be
staged, and output files collected using a standard interface.")
(license license:bsd-3)))
(define with-numpy-1.8
(package-input-rewriting `((,python2-numpy . ,python2-numpy-1.8))))
(define-public nmoldyn
(package
(name "nmoldyn")
(version "3.0.11")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"016h4bqg419p6s7bcx55q5iik91gqmk26hbnfgj2j6zl0j36w51r"))))
(build-system python-build-system)
(inputs
`(("python-matplotlib" ,(with-numpy-1.8 python2-matplotlib))
("python-scientific" ,python2-scientific)
("netcdf" ,netcdf)
("gv" ,gv)))
(propagated-inputs
`(("python-mmtk" ,python2-mmtk)))
(arguments
`(#:python ,python-2
#:tests? #f ; No test suite
#:phases
(modify-phases %standard-phases
(add-before 'build 'create-linux2-directory
(lambda _
(mkdir-p "nMOLDYN/linux2")))
(add-before 'build 'change-PDF-viewer
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "nMOLDYN/Preferences.py"
;; Set the paths for external executables, substituting
;; gv for acroread.
;; There is also vmd_path, but VMD is not free software
and contains currently no free molecular viewer that
;; could be substituted.
(("PREFERENCES\\['acroread_path'\\] = ''")
(format #f "PREFERENCES['acroread_path'] = '~a'"
(which "gv")))
(("PREFERENCES\\['ncdump_path'\\] = ''")
(format #f "PREFERENCES['ncdump_path'] = '~a'"
(which "ncdump")))
(("PREFERENCES\\['ncgen_path'\\] = ''")
(format #f "PREFERENCES['ncgen_path'] = '~a'"
(which "ncgen3")))
(("PREFERENCES\\['task_manager_path'\\] = ''")
(format #f "PREFERENCES['task_manager_path'] = '~a'"
(which "task_manager")))
;; Show documentation as PDF
(("PREFERENCES\\['documentation_style'\\] = 'html'")
"PREFERENCES['documentation_style'] = 'pdf'") ))))))
(home-page "-orleans.fr/nMOLDYN.html")
(synopsis "Analysis software for Molecular Dynamics trajectories")
(description "nMOLDYN is an interactive analysis program for Molecular Dynamics
simulations. It is especially designed for the computation and decomposition of
neutron scattering spectra, but also computes other quantities. The software
is currently not actively maintained and works only with Python 2 and
NumPy < 1.9.")
(license license:cecill)))
(define-public tng
(package
(name "tng")
(version "1.8.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1apf2n8nb34z09xarj7k4jgriq283l769sakjmj5aalpbilvai4q"))))
(build-system cmake-build-system)
(inputs
`(("zlib" ,zlib)))
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'remove-bundled-zlib
(lambda _
(delete-file-recursively "external")
#t))
(replace 'check
(lambda _
(invoke "../build/bin/tests/tng_testing")
#t)))))
(home-page "")
(synopsis "Trajectory Next Generation binary format manipulation library")
(description "TRAJNG (Trajectory next generation) is a program library for
handling molecular dynamics (MD) trajectories. It can store coordinates, and
optionally velocities and the H-matrix. Coordinates and velocities are
stored with user-specified precision.")
(license license:bsd-3)))
(define-public gromacs
(package
(name "gromacs")
(version "2020.2")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.gz"))
(sha256
(base32
"1wyjgcdl30wy4hy6jvi9lkq53bqs9fgfq6fri52dhnb3c76y8rbl"))
;; Our version of tinyxml2 is far newer than the bundled one and
;; require fixing `testutils' code. See patch header for more info
(patches (search-patches "gromacs-tinyxml2.patch"))))
(build-system cmake-build-system)
(arguments
`(#:configure-flags
(list "-DGMX_DEVELOPER_BUILD=on" ; Needed to run tests
;; Unbundling
"-DGMX_USE_LMFIT=EXTERNAL"
"-DGMX_BUILD_OWN_FFTW=off"
"-DGMX_EXTERNAL_BLAS=on"
"-DGMX_EXTERNAL_LAPACK=on"
"-DGMX_EXTERNAL_TNG=on"
"-DGMX_EXTERNAL_ZLIB=on"
"-DGMX_EXTERNAL_TINYXML2=on"
(string-append "-DTinyXML2_DIR="
(assoc-ref %build-inputs "tinyxml2"))
;; Workaround for cmake/FindSphinx.cmake version parsing that does
;; not understand the guix-wrapped `sphinx-build --version' answer
(string-append "-DSPHINX_EXECUTABLE_VERSION="
,(package-version python-sphinx)))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'fixes
(lambda* (#:key inputs #:allow-other-keys)
;; Still bundled: part of gromacs, source behind registration
;; but free software anyways
;;(delete-file-recursively "src/external/vmd_molfile")
;; Still bundled: threads-based OpenMPI-compatible fallback
;; designed to be bundled like that
;;(delete-file-recursively "src/external/thread_mpi")
;; Unbundling
(delete-file-recursively "src/external/lmfit")
(delete-file-recursively "src/external/clFFT")
(delete-file-recursively "src/external/fftpack")
(delete-file-recursively "src/external/build-fftw")
(delete-file-recursively "src/external/tng_io")
(delete-file-recursively "src/external/tinyxml2")
(delete-file-recursively "src/external/googletest")
(copy-recursively (assoc-ref inputs "googletest-source")
"src/external/googletest")
;; This test warns about the build host hardware, disable
(substitute* "src/gromacs/hardware/tests/hardwaretopology.cpp"
(("TEST\\(HardwareTopologyTest, HwlocExecute\\)")
"void __guix_disabled()"))
#t)))))
(native-inputs
`(("doxygen" ,doxygen)
("googletest-source" ,(package-source googletest))
("graphviz" ,graphviz)
("pkg-config" ,pkg-config)
("python" ,python)
("python-pygments" ,python-pygments)
("python-sphinx" ,python-sphinx)))
(inputs
`(("fftwf" ,fftwf)
("hwloc" ,hwloc-2 "lib")
("lmfit" ,lmfit)
("openblas" ,openblas)
("perl" ,perl)
("tinyxml2" ,tinyxml2)
("tng" ,tng)))
(home-page "/")
(synopsis "Molecular dynamics software package")
(description "GROMACS is a versatile package to perform molecular dynamics,
i.e. simulate the Newtonian equations of motion for systems with hundreds to
millions of particles. It is primarily designed for biochemical molecules like
proteins, lipids and nucleic acids that have a lot of complicated bonded
interactions, but since GROMACS is extremely fast at calculating the nonbonded
interactions (that usually dominate simulations) many groups are also using it
for research on non-biological systems, e.g. polymers. GROMACS supports all the
usual algorithms you expect from a modern molecular dynamics implementation.")
(license license:lgpl2.1+)))
(define-public openbabel
(package
(name "openbabel")
(version "3.1.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
"releases/download/openbabel-"
(string-replace-substring version "." "-")
"/openbabel-" version "-source.tar.bz2"))
(sha256
(base32
"0s0f4zib8vshfaywsr5bjjz55jwsg6yiz2qw4i5jm8wysn0q7v56"))))
(build-system cmake-build-system)
(arguments
`(;; FIXME: Disable tests on i686 to work around
;; .
#:tests? ,(or (%current-target-system)
(not (string=? "i686-linux" (%current-system))))
#:configure-flags
(list "-DOPENBABEL_USE_SYSTEM_INCHI=ON"
(string-append "-DINCHI_LIBRARY="
(assoc-ref %build-inputs "inchi")
"/lib/inchi/libinchi.so.1")
(string-append "-DINCHI_INCLUDE_DIR="
(assoc-ref %build-inputs "inchi") "/include/inchi"))
#:test-target "test"))
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("eigen" ,eigen)
("inchi" ,inchi)
("libxml2" ,libxml2)
("zlib" ,zlib)))
(home-page "")
(synopsis "Chemistry data manipulation toolbox")
(description
"Open Babel is a chemical toolbox designed to speak the many languages of
chemical data. It's a collaborative project allowing anyone to search, convert,
analyze, or store data from molecular modeling, chemistry, solid-state
materials, biochemistry, or related areas.")
(license license:gpl2)))
(define-public spglib
(package
(name "spglib")
(version "1.16.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(sha256
(base32 "1kzc956m1pnazhz52vspqridlw72wd8x5l3dsilpdxl491aa2nws"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(arguments
'(#:test-target "check"
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-header-install-dir
(lambda _
;; As of the writing of this package, CMake and GNU build systems
install the header to two different location . This patch makes
;; the CMake build system's choice of header directory compatible
with the GNU build system 's choice and with what avogadrolibs
;; expects.
;; See and the relevant
part of .
(substitute* "CMakeLists.txt"
(("\\$\\{CMAKE_INSTALL_INCLUDEDIR\\}" include-dir)
(string-append include-dir "/spglib")))
#t)))))
(home-page "")
(synopsis "Library for crystal symmetry search")
(description "Spglib is a library for finding and handling crystal
symmetries written in C. Spglib can be used to:
@enumerate
@item Find symmetry operations
@item Identify space-group type
@item Wyckoff position assignment
@item Refine crystal structure
@item Find a primitive cell
@item Search irreducible k-points
@end enumerate")
(license license:bsd-3)))
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/chemistry.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
TODO: Enable tests with "-DENABLE_TESTING" configure flag.
No test suite
Update the inchi-doc native input when updating inchi.
no check target
no configure script
Install binary.
Install libraries.
Install header files.
Install documentation.
no check target
TODO: Fix/enable the failing message and clientserver tests.
(apparently) be truncated, but it is not.
It is unclear why the clientserver test fails, so it is
completely disabled.
Make Qt render "offscreen" for the sake of tests.
No test suite
Set the paths for external executables, substituting
gv for acroread.
There is also vmd_path, but VMD is not free software
could be substituted.
Show documentation as PDF
Our version of tinyxml2 is far newer than the bundled one and
require fixing `testutils' code. See patch header for more info
Needed to run tests
Unbundling
Workaround for cmake/FindSphinx.cmake version parsing that does
not understand the guix-wrapped `sphinx-build --version' answer
Still bundled: part of gromacs, source behind registration
but free software anyways
(delete-file-recursively "src/external/vmd_molfile")
Still bundled: threads-based OpenMPI-compatible fallback
designed to be bundled like that
(delete-file-recursively "src/external/thread_mpi")
Unbundling
This test warns about the build host hardware, disable
FIXME: Disable tests on i686 to work around
.
As of the writing of this package, CMake and GNU build systems
the CMake build system's choice of header directory compatible
expects.
See and the relevant | Copyright © 2018 < >
Copyright © 2018 , 2021 < >
Copyright © 2018 < >
Copyright © 2018 < >
Copyright © 2020 < >
Copyright © 2020 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages chemistry)
#:use-module (guix packages)
#:use-module (guix utils)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (gnu packages)
#:use-module (gnu packages algebra)
#:use-module (gnu packages autotools)
#:use-module (gnu packages backup)
#:use-module (gnu packages boost)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages documentation)
#:use-module (gnu packages gl)
#:use-module (gnu packages graphviz)
#:use-module (gnu packages gv)
#:use-module (gnu packages maths)
#:use-module (gnu packages mpi)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages qt)
#:use-module (gnu packages serialization)
#:use-module (gnu packages sphinx)
#:use-module (gnu packages xml)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python))
(define-public avogadrolibs
(package
(name "avogadrolibs")
(version "1.93.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256
(base32 "1xivga626n5acnmwmym8svl0pdri8hkp59czf04ri2zflnviyh39"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(native-inputs
`(("eigen" ,eigen)
("mmtf-cpp" ,mmtf-cpp)
("msgpack" ,msgpack)
("googletest" ,googletest)
("pkg-config" ,pkg-config)
("pybind11" ,pybind11)))
(inputs
`(("glew" ,glew)
("libarchive" ,libarchive)
("libmsym" ,libmsym)
("molequeue" ,molequeue)
("python" ,python)
("spglib" ,spglib)
("qtbase" ,qtbase-5)))
(arguments
'(#:configure-flags (list "-DENABLE_TESTING=ON"
(string-append "-DSPGLIB_INCLUDE_DIR="
(assoc-ref %build-inputs "spglib")
"/include"))))
(home-page "/")
(synopsis "Libraries for chemistry, bioinformatics, and related areas")
(description
"Avogadro libraries provide 3D rendering, visualization, analysis and data
processing useful in computational chemistry, molecular modeling,
bioinformatics, materials science, and related areas.")
(license license:bsd-3)))
(define-public avogadro2
(package
(name "avogadro2")
(version "1.93.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256
(base32
"1z3pjlwja778a1dmvx9aqz2hlw5q9g3kqxhm9slz08452600jsv7"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(native-inputs
`(("eigen" ,eigen)
("pkg-config" ,pkg-config)))
(inputs
`(("avogadrolibs" ,avogadrolibs)
("hdf5" ,hdf5)
("molequeue" ,molequeue)
("qtbase" ,qtbase-5)))
(arguments
'(#:tests? #f))
(home-page "/")
(synopsis "Advanced molecule editor")
(description
"Avogadro 2 is an advanced molecule editor and visualizer designed for use
in computational chemistry, molecular modeling, bioinformatics, materials
science, and related areas. It offers flexible high quality rendering and a
powerful plugin architecture.")
(license license:bsd-3)))
(define-public domainfinder
(package
(name "domainfinder")
(version "2.0.5")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"domainfinder/downloads/DomainFinder-"
version ".tar.gz"))
(sha256
(base32
"1z26lsyf7xwnzwjvimmbla7ckipx6p734w7y0jk2a2fzci8fkdcr"))))
(build-system python-build-system)
(inputs
`(("python-mmtk" ,python2-mmtk)))
(arguments
`(#:python ,python-2
#:tests? #f))
(home-page "-orleans.fr/DomainFinder.html")
(synopsis "Analysis of dynamical domains in proteins")
(description "DomainFinder is an interactive program for the determination
and characterization of dynamical domains in proteins. It can infer dynamical
domains by comparing two protein structures, or from normal mode analysis on a
single structure. The software is currently not actively maintained and works
only with Python 2 and NumPy < 1.9.")
(license license:cecill-c)))
(define-public inchi
(package
(name "inchi")
(version "1.06")
(source (origin
(method url-fetch)
(uri (string-append "-trust.org/download/"
(string-join (string-split version #\.) "")
"/INCHI-1-SRC.zip"))
(sha256
(base32
"1zbygqn0443p0gxwr4kx3m1bkqaj8x9hrpch3s41py7jq08f6x28"))
(file-name (string-append name "-" version ".zip"))))
(build-system gnu-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(add-before 'build 'chdir-to-build-directory
(lambda _ (chdir "INCHI_EXE/inchi-1/gcc") #t))
(add-after 'build 'build-library
(lambda _
(chdir "../../../INCHI_API/libinchi/gcc")
(invoke "make")))
(replace 'install
(lambda* (#:key inputs outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin"))
(doc (string-append out "/share/doc/inchi"))
(include-dir (string-append out "/include/inchi"))
(lib (string-append out "/lib/inchi"))
(inchi-doc (assoc-ref inputs "inchi-doc"))
(unzip (string-append (assoc-ref inputs "unzip")
"/bin/unzip")))
(chdir "../../..")
(with-directory-excursion "INCHI_EXE/bin/Linux"
(rename-file "inchi-1" "inchi")
(install-file "inchi" bin))
(with-directory-excursion "INCHI_API/bin/Linux"
(for-each (lambda (file)
(install-file file lib))
(find-files "." "libinchi\\.so\\.1\\.*")))
(with-directory-excursion "INCHI_BASE/src"
(for-each (lambda (file)
(install-file file include-dir))
(find-files "." "\\.h$")))
(mkdir-p doc)
(invoke unzip "-j" "-d" doc inchi-doc)
#t))))))
(native-inputs
`(("unzip" ,unzip)
("inchi-doc"
,(origin
(method url-fetch)
(uri (string-append "-trust.org/download/"
(string-join (string-split version #\.) "")
"/INCHI-1-DOC.zip"))
(sha256
(base32
"1kyda09i9p89xfq90ninwi7w13k1w3ljpl4gqdhpfhi5g8fgxx7f"))
(file-name (string-append name "-" version ".zip"))))))
(home-page "-trust.org")
(synopsis "Utility for manipulating machine-readable chemical structures")
(description
"The @dfn{InChI} (IUPAC International Chemical Identifier) algorithm turns
chemical structures into machine-readable strings of information. InChIs are
unique to the compound they describe and can encode absolute stereochemistry
making chemicals and chemistry machine-readable and discoverable. A simple
analogy is that InChI is the bar-code for chemistry and chemical structures.")
(license (license:non-copyleft
"file"
"See LICENCE in the distribution."))))
(define-public libmsym
(package
(name "libmsym")
(version "0.2.3")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(sha256
(base32
"0a9j28irdsr461qpzlc9z1yjyb9kp64fh5zw7ylspc9zn3189qwk"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(arguments
'(#:configure-flags '("-DBUILD_SHARED_LIBS=ON")
(home-page "")
(synopsis "C library dealing with point group symmetry in molecules")
(description "libmsym is a C library dealing with point group symmetry in
molecules.")
(license license:expat)))
(define-public mmtf-cpp
(package
(name "mmtf-cpp")
(version "1.0.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-cpp")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"17ylramda69plf5w0v5hxbl4ggkdi5s15z55cv0pljl12yvyva8l"))))
(build-system cmake-build-system)
Tests require the soon - to - be - deprecated version 1 of the catch - framework .
(arguments
'(#:tests? #f))
(home-page "/")
(synopsis "C++ API for the Macromolecular Transmission Format")
(description "This package is a library for the
@acronym{MMTF,macromolecular transmission format}, a binary encoding of
biological structures.")
(license license:expat)))
(define-public molequeue
(package
(name "molequeue")
(version "0.9.0")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"releases/download/" version "/molequeue-"
version ".tar.bz2"))
(sha256
(base32
"1w1fgxzqrb5yxvpmnc3c9ymnvixy0z1nfafkd9whg9zw8nbgl998"))))
(build-system cmake-build-system)
(inputs
`(("qtbase" ,qtbase-5)))
(arguments
'(#:configure-flags '("-DENABLE_TESTING=ON")
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-tests
(lambda _
In the message test , the floating - point value " 5.36893473232 " on
line 165 of molequeue / app / testing / messagetest.cpp should
(substitute* "molequeue/app/testing/messagetest.cpp"
(("5\\.36893473232") "5.36893"))
(substitute* "molequeue/app/testing/CMakeLists.txt"
((".*clientserver.*") ""))
#t))
(add-before 'check 'set-display
(lambda _
(setenv "QT_QPA_PLATFORM" "offscreen")
#t)))))
(home-page "/")
(synopsis "Application for coordinating computational jobs")
(description "MoleQueue is a system-tray resident desktop application for
abstracting, managing, and coordinating the execution of tasks both locally and
on remote computational resources. Users can set up local and remote queues
that describe where the task will be executed. Each queue can have programs,
with templates to facilitate the execution of the program. Input files can be
staged, and output files collected using a standard interface.")
(license license:bsd-3)))
(define with-numpy-1.8
(package-input-rewriting `((,python2-numpy . ,python2-numpy-1.8))))
(define-public nmoldyn
(package
(name "nmoldyn")
(version "3.0.11")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"016h4bqg419p6s7bcx55q5iik91gqmk26hbnfgj2j6zl0j36w51r"))))
(build-system python-build-system)
(inputs
`(("python-matplotlib" ,(with-numpy-1.8 python2-matplotlib))
("python-scientific" ,python2-scientific)
("netcdf" ,netcdf)
("gv" ,gv)))
(propagated-inputs
`(("python-mmtk" ,python2-mmtk)))
(arguments
`(#:python ,python-2
#:phases
(modify-phases %standard-phases
(add-before 'build 'create-linux2-directory
(lambda _
(mkdir-p "nMOLDYN/linux2")))
(add-before 'build 'change-PDF-viewer
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "nMOLDYN/Preferences.py"
and contains currently no free molecular viewer that
(("PREFERENCES\\['acroread_path'\\] = ''")
(format #f "PREFERENCES['acroread_path'] = '~a'"
(which "gv")))
(("PREFERENCES\\['ncdump_path'\\] = ''")
(format #f "PREFERENCES['ncdump_path'] = '~a'"
(which "ncdump")))
(("PREFERENCES\\['ncgen_path'\\] = ''")
(format #f "PREFERENCES['ncgen_path'] = '~a'"
(which "ncgen3")))
(("PREFERENCES\\['task_manager_path'\\] = ''")
(format #f "PREFERENCES['task_manager_path'] = '~a'"
(which "task_manager")))
(("PREFERENCES\\['documentation_style'\\] = 'html'")
"PREFERENCES['documentation_style'] = 'pdf'") ))))))
(home-page "-orleans.fr/nMOLDYN.html")
(synopsis "Analysis software for Molecular Dynamics trajectories")
(description "nMOLDYN is an interactive analysis program for Molecular Dynamics
simulations. It is especially designed for the computation and decomposition of
neutron scattering spectra, but also computes other quantities. The software
is currently not actively maintained and works only with Python 2 and
NumPy < 1.9.")
(license license:cecill)))
(define-public tng
(package
(name "tng")
(version "1.8.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1apf2n8nb34z09xarj7k4jgriq283l769sakjmj5aalpbilvai4q"))))
(build-system cmake-build-system)
(inputs
`(("zlib" ,zlib)))
(arguments
`(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'remove-bundled-zlib
(lambda _
(delete-file-recursively "external")
#t))
(replace 'check
(lambda _
(invoke "../build/bin/tests/tng_testing")
#t)))))
(home-page "")
(synopsis "Trajectory Next Generation binary format manipulation library")
(description "TRAJNG (Trajectory next generation) is a program library for
handling molecular dynamics (MD) trajectories. It can store coordinates, and
optionally velocities and the H-matrix. Coordinates and velocities are
stored with user-specified precision.")
(license license:bsd-3)))
(define-public gromacs
(package
(name "gromacs")
(version "2020.2")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.gz"))
(sha256
(base32
"1wyjgcdl30wy4hy6jvi9lkq53bqs9fgfq6fri52dhnb3c76y8rbl"))
(patches (search-patches "gromacs-tinyxml2.patch"))))
(build-system cmake-build-system)
(arguments
`(#:configure-flags
"-DGMX_USE_LMFIT=EXTERNAL"
"-DGMX_BUILD_OWN_FFTW=off"
"-DGMX_EXTERNAL_BLAS=on"
"-DGMX_EXTERNAL_LAPACK=on"
"-DGMX_EXTERNAL_TNG=on"
"-DGMX_EXTERNAL_ZLIB=on"
"-DGMX_EXTERNAL_TINYXML2=on"
(string-append "-DTinyXML2_DIR="
(assoc-ref %build-inputs "tinyxml2"))
(string-append "-DSPHINX_EXECUTABLE_VERSION="
,(package-version python-sphinx)))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'fixes
(lambda* (#:key inputs #:allow-other-keys)
(delete-file-recursively "src/external/lmfit")
(delete-file-recursively "src/external/clFFT")
(delete-file-recursively "src/external/fftpack")
(delete-file-recursively "src/external/build-fftw")
(delete-file-recursively "src/external/tng_io")
(delete-file-recursively "src/external/tinyxml2")
(delete-file-recursively "src/external/googletest")
(copy-recursively (assoc-ref inputs "googletest-source")
"src/external/googletest")
(substitute* "src/gromacs/hardware/tests/hardwaretopology.cpp"
(("TEST\\(HardwareTopologyTest, HwlocExecute\\)")
"void __guix_disabled()"))
#t)))))
(native-inputs
`(("doxygen" ,doxygen)
("googletest-source" ,(package-source googletest))
("graphviz" ,graphviz)
("pkg-config" ,pkg-config)
("python" ,python)
("python-pygments" ,python-pygments)
("python-sphinx" ,python-sphinx)))
(inputs
`(("fftwf" ,fftwf)
("hwloc" ,hwloc-2 "lib")
("lmfit" ,lmfit)
("openblas" ,openblas)
("perl" ,perl)
("tinyxml2" ,tinyxml2)
("tng" ,tng)))
(home-page "/")
(synopsis "Molecular dynamics software package")
(description "GROMACS is a versatile package to perform molecular dynamics,
i.e. simulate the Newtonian equations of motion for systems with hundreds to
millions of particles. It is primarily designed for biochemical molecules like
proteins, lipids and nucleic acids that have a lot of complicated bonded
interactions, but since GROMACS is extremely fast at calculating the nonbonded
interactions (that usually dominate simulations) many groups are also using it
for research on non-biological systems, e.g. polymers. GROMACS supports all the
usual algorithms you expect from a modern molecular dynamics implementation.")
(license license:lgpl2.1+)))
(define-public openbabel
(package
(name "openbabel")
(version "3.1.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
"releases/download/openbabel-"
(string-replace-substring version "." "-")
"/openbabel-" version "-source.tar.bz2"))
(sha256
(base32
"0s0f4zib8vshfaywsr5bjjz55jwsg6yiz2qw4i5jm8wysn0q7v56"))))
(build-system cmake-build-system)
(arguments
#:tests? ,(or (%current-target-system)
(not (string=? "i686-linux" (%current-system))))
#:configure-flags
(list "-DOPENBABEL_USE_SYSTEM_INCHI=ON"
(string-append "-DINCHI_LIBRARY="
(assoc-ref %build-inputs "inchi")
"/lib/inchi/libinchi.so.1")
(string-append "-DINCHI_INCLUDE_DIR="
(assoc-ref %build-inputs "inchi") "/include/inchi"))
#:test-target "test"))
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("eigen" ,eigen)
("inchi" ,inchi)
("libxml2" ,libxml2)
("zlib" ,zlib)))
(home-page "")
(synopsis "Chemistry data manipulation toolbox")
(description
"Open Babel is a chemical toolbox designed to speak the many languages of
chemical data. It's a collaborative project allowing anyone to search, convert,
analyze, or store data from molecular modeling, chemistry, solid-state
materials, biochemistry, or related areas.")
(license license:gpl2)))
(define-public spglib
(package
(name "spglib")
(version "1.16.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(sha256
(base32 "1kzc956m1pnazhz52vspqridlw72wd8x5l3dsilpdxl491aa2nws"))
(file-name (git-file-name name version))))
(build-system cmake-build-system)
(arguments
'(#:test-target "check"
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-header-install-dir
(lambda _
install the header to two different location . This patch makes
with the GNU build system 's choice and with what avogadrolibs
part of .
(substitute* "CMakeLists.txt"
(("\\$\\{CMAKE_INSTALL_INCLUDEDIR\\}" include-dir)
(string-append include-dir "/spglib")))
#t)))))
(home-page "")
(synopsis "Library for crystal symmetry search")
(description "Spglib is a library for finding and handling crystal
symmetries written in C. Spglib can be used to:
@enumerate
@item Find symmetry operations
@item Identify space-group type
@item Wyckoff position assignment
@item Refine crystal structure
@item Find a primitive cell
@item Search irreducible k-points
@end enumerate")
(license license:bsd-3)))
|
2838fb920e84d4fe2a95e645b4e6d013b0484cf53b1dd4ef76d4c37797e72d30 | emqx/lc | load_ctl.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2021 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(load_ctl).
-include("lc.hrl").
-export([ is_overloaded/0
, is_high_mem/0
, maydelay/1
, accompany/2
, join/1
, leave/1
, whereis_runq_flagman/0
, whereis_mem_flagman/0
, stop_runq_flagman/0
, stop_runq_flagman/1
, stop_mem_flagman/0
, stop_mem_flagman/1
, restart_runq_flagman/0
, restart_mem_flagman/0
, put_config/1
, get_config/0
, get_memory_usage/0
, get_sys_memory/0
]).
%% overload check for realtime processing
-spec is_overloaded() -> boolean().
is_overloaded() ->
not (undefined =:= whereis(?RUNQ_MON_FLAG_NAME)).
%% overload check for realtime processing
-spec is_high_mem() -> boolean().
is_high_mem() ->
not (undefined =:= whereis(?MEM_MON_FLAG_NAME)).
-spec maydelay(timer:timeout()) -> ok | timeout | false.
maydelay(Timeout) ->
case is_overloaded() andalso accompany(?RUNQ_MON_FLAG_NAME, Timeout) of
ok ->
ok;
{error, timeout} ->
timeout;
false ->
false
end.
%% process is put into a process priority group
%% process will be killed if system is overloaded when priority is under threshold
-spec join(non_neg_integer()) -> ok.
join(Priority) ->
ok = pg:join(?LC_SCOPE, {?LC_GROUP, Priority}, self()).
%% Leave process priority group, the number of leaves should match the number of join
-spec leave(non_neg_integer()) -> ok.
leave(Priority) ->
ok = pg:leave(?LC_SCOPE, {?LC_GROUP, Priority}, self()).
-spec put_config(map()) -> ok | {error, badarg}.
put_config(Config) when is_map(Config) ->
@TODO config validation .
persistent_term:put(?FLAG_MAN_CONFIGS_TERM, filter_config(Config));
put_config(_) ->
{error, badarg}.
-spec stop_runq_flagman() -> ok.
stop_runq_flagman() ->
lc_sup:stop_runq_flagman(infinity).
-spec stop_runq_flagman(timer:timeout()) -> ok | {error, timeout}.
stop_runq_flagman(Timeout) ->
lc_sup:stop_runq_flagman(Timeout).
-spec stop_mem_flagman() -> ok.
stop_mem_flagman() ->
lc_sup:stop_mem_flagman(infinity).
-spec stop_mem_flagman(timer:timeout()) -> ok | {error, timeout}.
stop_mem_flagman(Timeout) ->
lc_sup:stop_mem_flagman(Timeout).
-spec whereis_runq_flagman() -> pid() | undefined.
whereis_runq_flagman() ->
lc_sup:whereis_runq_flagman().
-spec whereis_mem_flagman() -> pid() | undefined.
whereis_mem_flagman() ->
lc_sup:whereis_mem_flagman().
-spec restart_runq_flagman() -> {ok, pid()} | {error, running | restarting | disabled}.
restart_runq_flagman() ->
case get_config() of
#{?RUNQ_MON_F0 := false} ->
{error, disabled};
_ ->
lc_sup:restart_runq_flagman()
end.
-spec restart_mem_flagman() -> {ok, pid()} | {error, running | restarting | disabled}.
restart_mem_flagman() ->
case get_config() of
#{?MEM_MON_F0 := false} ->
{error, disabled};
_ ->
lc_sup:restart_mem_flagman()
end.
-spec get_config() -> map().
get_config() ->
case persistent_term:get(?FLAG_MAN_CONFIGS_TERM, undefined) of
undefined ->
%% return defaults
#{ ?RUNQ_MON_F0 => ?RUNQ_MON_F0_DEFAULT
, ?RUNQ_MON_F1 => ?RUNQ_MON_F1_DEFAULT
, ?RUNQ_MON_F2 => ?RUNQ_MON_F2_DEFAULT
, ?RUNQ_MON_F3 => ?RUNQ_MON_F3_DEFAULT
, ?RUNQ_MON_F4 => ?RUNQ_MON_F4_DEFAULT
, ?RUNQ_MON_T1 => ?RUNQ_MON_T1_DEFAULT
, ?RUNQ_MON_T2 => ?RUNQ_MON_T2_DEFAULT
, ?RUNQ_MON_C1 => ?RUNQ_MON_C1_DEFAULT
, ?MEM_MON_F0 => ?MEM_MON_F0_DEFAULT
, ?MEM_MON_F1 => ?MEM_MON_F1_DEFAULT
, ?MEM_MON_T1 => ?MEM_MON_T1_DEFAULT
};
Other ->
Other
end.
filter_config(Config) ->
maps:with([ ?RUNQ_MON_F0
, ?RUNQ_MON_F1
, ?RUNQ_MON_F2
, ?RUNQ_MON_F3
, ?RUNQ_MON_F4
, ?RUNQ_MON_T1
, ?RUNQ_MON_T2
, ?RUNQ_MON_C1
, ?MEM_MON_F0
, ?MEM_MON_F1
, ?MEM_MON_T1
], Config).
-spec accompany(atom() | pid(), timer:timeout()) -> ok | {error, timeout}.
accompany(Target, Timeout) ->
Mref = erlang:monitor(process, Target),
receive
{'DOWN', Mref, process, _Object, _Info} -> ok
after Timeout ->
erlang:demonitor(Mref, [flush]),
{error, timeout}
end.
%% @doc Return RAM usage ratio and total number of bytes.
%% `{0, 0}' indicates an error in collecting the stats.
-spec get_memory_usage() -> number().
get_memory_usage() ->
lc_lib:get_memory_usage().
@doc Return RAM usage ratio ( from 0 to 1 ) .
%% `0' probably indicates an error in collecting the stats.
-spec get_sys_memory() -> {number(), number()}.
get_sys_memory() ->
lc_lib:get_sys_memory().
%%%_* Emacs ====================================================================
%%% Local Variables:
%%% allout-layout: t
erlang - indent - level : 2
%%% End:
| null | https://raw.githubusercontent.com/emqx/lc/32dc4a56960d96112cee4de77cd14a6f2e78d311/src/load_ctl.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
overload check for realtime processing
overload check for realtime processing
process is put into a process priority group
process will be killed if system is overloaded when priority is under threshold
Leave process priority group, the number of leaves should match the number of join
return defaults
@doc Return RAM usage ratio and total number of bytes.
`{0, 0}' indicates an error in collecting the stats.
`0' probably indicates an error in collecting the stats.
_* Emacs ====================================================================
Local Variables:
allout-layout: t
End: | Copyright ( c ) 2021 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(load_ctl).
-include("lc.hrl").
-export([ is_overloaded/0
, is_high_mem/0
, maydelay/1
, accompany/2
, join/1
, leave/1
, whereis_runq_flagman/0
, whereis_mem_flagman/0
, stop_runq_flagman/0
, stop_runq_flagman/1
, stop_mem_flagman/0
, stop_mem_flagman/1
, restart_runq_flagman/0
, restart_mem_flagman/0
, put_config/1
, get_config/0
, get_memory_usage/0
, get_sys_memory/0
]).
-spec is_overloaded() -> boolean().
is_overloaded() ->
not (undefined =:= whereis(?RUNQ_MON_FLAG_NAME)).
-spec is_high_mem() -> boolean().
is_high_mem() ->
not (undefined =:= whereis(?MEM_MON_FLAG_NAME)).
-spec maydelay(timer:timeout()) -> ok | timeout | false.
maydelay(Timeout) ->
case is_overloaded() andalso accompany(?RUNQ_MON_FLAG_NAME, Timeout) of
ok ->
ok;
{error, timeout} ->
timeout;
false ->
false
end.
-spec join(non_neg_integer()) -> ok.
join(Priority) ->
ok = pg:join(?LC_SCOPE, {?LC_GROUP, Priority}, self()).
-spec leave(non_neg_integer()) -> ok.
leave(Priority) ->
ok = pg:leave(?LC_SCOPE, {?LC_GROUP, Priority}, self()).
-spec put_config(map()) -> ok | {error, badarg}.
put_config(Config) when is_map(Config) ->
@TODO config validation .
persistent_term:put(?FLAG_MAN_CONFIGS_TERM, filter_config(Config));
put_config(_) ->
{error, badarg}.
-spec stop_runq_flagman() -> ok.
stop_runq_flagman() ->
lc_sup:stop_runq_flagman(infinity).
-spec stop_runq_flagman(timer:timeout()) -> ok | {error, timeout}.
stop_runq_flagman(Timeout) ->
lc_sup:stop_runq_flagman(Timeout).
-spec stop_mem_flagman() -> ok.
stop_mem_flagman() ->
lc_sup:stop_mem_flagman(infinity).
-spec stop_mem_flagman(timer:timeout()) -> ok | {error, timeout}.
stop_mem_flagman(Timeout) ->
lc_sup:stop_mem_flagman(Timeout).
-spec whereis_runq_flagman() -> pid() | undefined.
whereis_runq_flagman() ->
lc_sup:whereis_runq_flagman().
-spec whereis_mem_flagman() -> pid() | undefined.
whereis_mem_flagman() ->
lc_sup:whereis_mem_flagman().
-spec restart_runq_flagman() -> {ok, pid()} | {error, running | restarting | disabled}.
restart_runq_flagman() ->
case get_config() of
#{?RUNQ_MON_F0 := false} ->
{error, disabled};
_ ->
lc_sup:restart_runq_flagman()
end.
-spec restart_mem_flagman() -> {ok, pid()} | {error, running | restarting | disabled}.
restart_mem_flagman() ->
case get_config() of
#{?MEM_MON_F0 := false} ->
{error, disabled};
_ ->
lc_sup:restart_mem_flagman()
end.
-spec get_config() -> map().
get_config() ->
case persistent_term:get(?FLAG_MAN_CONFIGS_TERM, undefined) of
undefined ->
#{ ?RUNQ_MON_F0 => ?RUNQ_MON_F0_DEFAULT
, ?RUNQ_MON_F1 => ?RUNQ_MON_F1_DEFAULT
, ?RUNQ_MON_F2 => ?RUNQ_MON_F2_DEFAULT
, ?RUNQ_MON_F3 => ?RUNQ_MON_F3_DEFAULT
, ?RUNQ_MON_F4 => ?RUNQ_MON_F4_DEFAULT
, ?RUNQ_MON_T1 => ?RUNQ_MON_T1_DEFAULT
, ?RUNQ_MON_T2 => ?RUNQ_MON_T2_DEFAULT
, ?RUNQ_MON_C1 => ?RUNQ_MON_C1_DEFAULT
, ?MEM_MON_F0 => ?MEM_MON_F0_DEFAULT
, ?MEM_MON_F1 => ?MEM_MON_F1_DEFAULT
, ?MEM_MON_T1 => ?MEM_MON_T1_DEFAULT
};
Other ->
Other
end.
filter_config(Config) ->
maps:with([ ?RUNQ_MON_F0
, ?RUNQ_MON_F1
, ?RUNQ_MON_F2
, ?RUNQ_MON_F3
, ?RUNQ_MON_F4
, ?RUNQ_MON_T1
, ?RUNQ_MON_T2
, ?RUNQ_MON_C1
, ?MEM_MON_F0
, ?MEM_MON_F1
, ?MEM_MON_T1
], Config).
-spec accompany(atom() | pid(), timer:timeout()) -> ok | {error, timeout}.
accompany(Target, Timeout) ->
Mref = erlang:monitor(process, Target),
receive
{'DOWN', Mref, process, _Object, _Info} -> ok
after Timeout ->
erlang:demonitor(Mref, [flush]),
{error, timeout}
end.
-spec get_memory_usage() -> number().
get_memory_usage() ->
lc_lib:get_memory_usage().
@doc Return RAM usage ratio ( from 0 to 1 ) .
-spec get_sys_memory() -> {number(), number()}.
get_sys_memory() ->
lc_lib:get_sys_memory().
erlang - indent - level : 2
|
dcff3330c8a4a26a728e856b2e8870c9de4daae5862c04ae6ff31ca48d8c262a | kelamg/HtDP2e-workthrough | ex80.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex80) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; designing with structures
(define-struct movie (title director year))
#;
(define (fn-for-movie m)
(... (movie-title m)
(movie-director m)
(movie-year m)))
;; =========================================
(define-struct pet (name number))
#;
(define (fn-for-pet p)
(... (pet-name p)
(pet-number p)))
;;==========================================
(define-struct CD (artist title price))
#;
(define (fn-for-CD cd)
(... (CD-artist cd)
(CD-title cd)
(CD-price cd)))
;; =========================================
(define-struct sweater (material size color))
#;
(define (fn-for-sweater s)
(... (sweater-material s)
(sweater-size s)
(sweater-color s)))
| null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Fixed-size-Data/ex80.rkt | racket | about the language level of this file in a form that our tools can easily process.
designing with structures
=========================================
==========================================
=========================================
| The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex80) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define-struct movie (title director year))
(define (fn-for-movie m)
(... (movie-title m)
(movie-director m)
(movie-year m)))
(define-struct pet (name number))
(define (fn-for-pet p)
(... (pet-name p)
(pet-number p)))
(define-struct CD (artist title price))
(define (fn-for-CD cd)
(... (CD-artist cd)
(CD-title cd)
(CD-price cd)))
(define-struct sweater (material size color))
(define (fn-for-sweater s)
(... (sweater-material s)
(sweater-size s)
(sweater-color s)))
|
165a7d8698809c931f4e3fa92becc9a753e61844cace6714e5002336c8cccdda | aryx/xix | menu_ui.ml | open Common
open Point
open Rectangle
module I = Display (* image type is in display.ml *)
module D = Display
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(* old: called menuhit.c in draw-C
*)
(*****************************************************************************)
(* Types and constants *)
(*****************************************************************************)
inspiration is GToolbox in lablgtk
type item = (string * (unit -> unit))
type items = item list
(* outside | outline | space | text ...
* <----------------->
* margin
* <--------->
* border size
*)
let margin = 4 (* outside to text *)
let border_size = 2 (* width of outlining border *)
let vspacing = 2 (* extra spacing between lines of text *)
let background = ref Display.fake_image
let background_highlighted = ref Display.fake_image
let border_color = ref Display.fake_image
let text_color = ref Display.fake_image
let text_highlighted = ref Display.fake_image
(*let menutext = ref Display.fake_image *)
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let init_colors display =
if !background == Display.fake_image
then begin
(* less: could use try and default to black/white if can not alloc image*)
less : opti : use view->chan instead of rgb24 used by Image.alloc_color
background := Draw.alloc_mix_colors display Color.palegreen Color.white;
background_highlighted := Image.alloc_color display (Color.darkgreen);
border_color := Image.alloc_color display (Color.medgreen);
text_color := display.D.black;
text_highlighted := !background;
end
(* "Text is the rectangle holding the text elements.
* Return the rectangle, including its black edge, holding element i."
*)
let rect_of_menu_entry textr i font =
if i < 0
then failwith (spf "rect_of_menu_entry with negative entry %d" i);
let line_height = font.Font.height + vspacing in
let rminy = textr.min.y + i * line_height in
let r = { min = { textr.min with y = rminy };
max = { textr.max with y = rminy + line_height };
}
in
(* include black edge for selection *)
Rectangle.insetrect (border_size - margin) r
type action =
| SaveOn of Image.t
| RestoreFrom of Image.t
| Nothing
let paint_item (img:Image.t) (font:Font.t) (i:int) (entries: string array) textr highlight action =
let line_height = font.Font.height + vspacing in
let r = rect_of_menu_entry textr i font in
let str = entries.(i) in
(match action with
| Nothing -> ()
| SaveOn save -> Draw.draw save save.I.r img None r.min
| RestoreFrom save -> Draw.draw img r save None save.I.r.min
);
let pt = { x = (textr.min.x + textr.max.x - Text.string_width font str) / 2;
y = textr.min.y + i * line_height
}
in
Draw.draw img r
(if highlight then !background_highlighted else !background) None
(*pt??*) Point.zero;
Text.string img pt
(if highlight then !text_highlighted else !text_color)
(*pt??*) Point.zero font str;
()
let paint_item_opt img font iopt entries textr highlight action =
iopt |> Common.if_some (fun i ->
paint_item img font i entries textr highlight action
)
let menu_selection font textr p =
let line_height = font.Font.height + vspacing in
(* todo? insetrect Margin? *)
let r = textr in
if not (Rectangle.pt_in_rect p r)
then None
else
let i = (p.y - r.min.y) / line_height in
Some i
let scan_items img font mouse button iopt entries textr save =
paint_item_opt img font iopt entries textr true (SaveOn save);
let rec loop_while_button m iopt =
if Mouse.has_button m button
then
let i_opt = menu_selection font textr m.Mouse.pos in
(match i_opt with
| Some i when (Some i) = iopt ->
loop_while_button (Mouse.flush_and_read img.I.display mouse) iopt
| None ->
paint_item_opt img font iopt entries textr false (RestoreFrom save);
None
| Some i ->
paint_item_opt img font iopt entries textr false(RestoreFrom save);
let iopt = Some i in
paint_item_opt img font iopt entries textr true (SaveOn save);
loop_while_button (Mouse.flush_and_read img.I.display mouse) iopt
)
else iopt
in
loop_while_button (Mouse.flush_and_read img.I.display mouse) iopt
(*****************************************************************************)
(* Entry point *)
(*****************************************************************************)
let menu items pos button mouse (display, desktop, view, font) =
init_colors display;
less : reset and repl on view ?
(* compute width and height and basic config *)
let max_width =
items |> List.map (fun (str, _f) -> Text.string_width font str)
|> List.fold_left max 0
in
(* todo: if scrolling *)
let width = max_width in
let nitems_to_draw = List.length items in
let entries = items |> List.map fst |> Array.of_list in
less : save between calls to menu and restore it here
let lasti = 0 in
let line_height = font.Font.height + vspacing in
let height = nitems_to_draw * line_height in
(* compute rectangles *)
let r =
Rectangle.r 0 0 width height
|> Rectangle.insetrect (-margin)
(* center on lasti entry *)
|> Rectangle.sub_pt
(Point.p (width / 2) (lasti * line_height + font.Font.height / 2))
(* adjust to mouse position *)
|> Rectangle.add_pt pos
in
(* less: adjust if outside view *)
let pt_adjust = Point.zero in
let menur = Rectangle.add_pt pt_adjust r in
(* less: do the more complex calculation?*)
let textr = Rectangle.insetrect margin menur in
(* set images to draw on *)
(* less: handle case where no desktop? *)
let img = Layer.alloc desktop menur Color.white in
let save =
Image.alloc display (rect_of_menu_entry textr 0 font) view.I.chans false
Color.black
in
(* painting *)
Draw.draw img menur !background None Point.zero;
Polygon.border img menur border_size !border_color Point.zero;
less : nitems_to_draw if scrolling
for i = 0 to nitems_to_draw - 1 do
paint_item img font i entries textr false Nothing
done;
(* interact *)
(* todo? have a state machine instead? and inline code of scan_items? *)
let rec loop_while_button m acc =
if Mouse.has_button m button
then begin
let acc = scan_items img font mouse button acc entries textr save in
(match acc with
| Some _ -> acc
| None ->
let rec loop_while_outside_textr_and_button m =
if not (Rectangle.pt_in_rect m.Mouse.pos textr) &&
Mouse.has_button m button
then
(* less: if scrolling *)
loop_while_outside_textr_and_button
(Mouse.flush_and_read display mouse)
else
(* maybe back in the textr! *)
loop_while_button m None
in
(* bugfix: need to read another 'm', not pass the old 'm' above *)
loop_while_outside_textr_and_button
(Mouse.flush_and_read display mouse)
)
end else acc
in
let iopt = loop_while_button (Mouse.mk pos button) (Some lasti) in
Layer.free img;
Display.flush display;
(* bugfix: must run callback after menu has been erased! *)
iopt |> Common.if_some (fun i ->
let (_, f) = List.nth items i in
f ()
);
| null | https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/lib_graphics/ui/menu_ui.ml | ocaml | image type is in display.ml
***************************************************************************
Prelude
***************************************************************************
old: called menuhit.c in draw-C
***************************************************************************
Types and constants
***************************************************************************
outside | outline | space | text ...
* <----------------->
* margin
* <--------->
* border size
outside to text
width of outlining border
extra spacing between lines of text
let menutext = ref Display.fake_image
***************************************************************************
Helpers
***************************************************************************
less: could use try and default to black/white if can not alloc image
"Text is the rectangle holding the text elements.
* Return the rectangle, including its black edge, holding element i."
include black edge for selection
pt??
pt??
todo? insetrect Margin?
***************************************************************************
Entry point
***************************************************************************
compute width and height and basic config
todo: if scrolling
compute rectangles
center on lasti entry
adjust to mouse position
less: adjust if outside view
less: do the more complex calculation?
set images to draw on
less: handle case where no desktop?
painting
interact
todo? have a state machine instead? and inline code of scan_items?
less: if scrolling
maybe back in the textr!
bugfix: need to read another 'm', not pass the old 'm' above
bugfix: must run callback after menu has been erased! | open Common
open Point
open Rectangle
module D = Display
inspiration is GToolbox in lablgtk
type item = (string * (unit -> unit))
type items = item list
let background = ref Display.fake_image
let background_highlighted = ref Display.fake_image
let border_color = ref Display.fake_image
let text_color = ref Display.fake_image
let text_highlighted = ref Display.fake_image
let init_colors display =
if !background == Display.fake_image
then begin
less : opti : use view->chan instead of rgb24 used by Image.alloc_color
background := Draw.alloc_mix_colors display Color.palegreen Color.white;
background_highlighted := Image.alloc_color display (Color.darkgreen);
border_color := Image.alloc_color display (Color.medgreen);
text_color := display.D.black;
text_highlighted := !background;
end
let rect_of_menu_entry textr i font =
if i < 0
then failwith (spf "rect_of_menu_entry with negative entry %d" i);
let line_height = font.Font.height + vspacing in
let rminy = textr.min.y + i * line_height in
let r = { min = { textr.min with y = rminy };
max = { textr.max with y = rminy + line_height };
}
in
Rectangle.insetrect (border_size - margin) r
type action =
| SaveOn of Image.t
| RestoreFrom of Image.t
| Nothing
let paint_item (img:Image.t) (font:Font.t) (i:int) (entries: string array) textr highlight action =
let line_height = font.Font.height + vspacing in
let r = rect_of_menu_entry textr i font in
let str = entries.(i) in
(match action with
| Nothing -> ()
| SaveOn save -> Draw.draw save save.I.r img None r.min
| RestoreFrom save -> Draw.draw img r save None save.I.r.min
);
let pt = { x = (textr.min.x + textr.max.x - Text.string_width font str) / 2;
y = textr.min.y + i * line_height
}
in
Draw.draw img r
(if highlight then !background_highlighted else !background) None
Text.string img pt
(if highlight then !text_highlighted else !text_color)
()
let paint_item_opt img font iopt entries textr highlight action =
iopt |> Common.if_some (fun i ->
paint_item img font i entries textr highlight action
)
let menu_selection font textr p =
let line_height = font.Font.height + vspacing in
let r = textr in
if not (Rectangle.pt_in_rect p r)
then None
else
let i = (p.y - r.min.y) / line_height in
Some i
let scan_items img font mouse button iopt entries textr save =
paint_item_opt img font iopt entries textr true (SaveOn save);
let rec loop_while_button m iopt =
if Mouse.has_button m button
then
let i_opt = menu_selection font textr m.Mouse.pos in
(match i_opt with
| Some i when (Some i) = iopt ->
loop_while_button (Mouse.flush_and_read img.I.display mouse) iopt
| None ->
paint_item_opt img font iopt entries textr false (RestoreFrom save);
None
| Some i ->
paint_item_opt img font iopt entries textr false(RestoreFrom save);
let iopt = Some i in
paint_item_opt img font iopt entries textr true (SaveOn save);
loop_while_button (Mouse.flush_and_read img.I.display mouse) iopt
)
else iopt
in
loop_while_button (Mouse.flush_and_read img.I.display mouse) iopt
let menu items pos button mouse (display, desktop, view, font) =
init_colors display;
less : reset and repl on view ?
let max_width =
items |> List.map (fun (str, _f) -> Text.string_width font str)
|> List.fold_left max 0
in
let width = max_width in
let nitems_to_draw = List.length items in
let entries = items |> List.map fst |> Array.of_list in
less : save between calls to menu and restore it here
let lasti = 0 in
let line_height = font.Font.height + vspacing in
let height = nitems_to_draw * line_height in
let r =
Rectangle.r 0 0 width height
|> Rectangle.insetrect (-margin)
|> Rectangle.sub_pt
(Point.p (width / 2) (lasti * line_height + font.Font.height / 2))
|> Rectangle.add_pt pos
in
let pt_adjust = Point.zero in
let menur = Rectangle.add_pt pt_adjust r in
let textr = Rectangle.insetrect margin menur in
let img = Layer.alloc desktop menur Color.white in
let save =
Image.alloc display (rect_of_menu_entry textr 0 font) view.I.chans false
Color.black
in
Draw.draw img menur !background None Point.zero;
Polygon.border img menur border_size !border_color Point.zero;
less : nitems_to_draw if scrolling
for i = 0 to nitems_to_draw - 1 do
paint_item img font i entries textr false Nothing
done;
let rec loop_while_button m acc =
if Mouse.has_button m button
then begin
let acc = scan_items img font mouse button acc entries textr save in
(match acc with
| Some _ -> acc
| None ->
let rec loop_while_outside_textr_and_button m =
if not (Rectangle.pt_in_rect m.Mouse.pos textr) &&
Mouse.has_button m button
then
loop_while_outside_textr_and_button
(Mouse.flush_and_read display mouse)
else
loop_while_button m None
in
loop_while_outside_textr_and_button
(Mouse.flush_and_read display mouse)
)
end else acc
in
let iopt = loop_while_button (Mouse.mk pos button) (Some lasti) in
Layer.free img;
Display.flush display;
iopt |> Common.if_some (fun i ->
let (_, f) = List.nth items i in
f ()
);
|
dd2ac88fa3e0f93e9b6c1d86daa8c7d6e220453410e3a0620b06f268476cb950 | mpenet/hayt | joda_time.clj | (ns qbits.hayt.codec.joda-time
"require/use this namespace if you want hayt to support Joda DateTime
encoding when generating raw queries"
(:require
[qbits.hayt.cql :as cql]
[clj-time.coerce :as ct]))
(extend-protocol cql/CQLEntities
org.joda.time.DateTime
(cql-value [x]
(ct/to-long x)))
| null | https://raw.githubusercontent.com/mpenet/hayt/7bbc06fae481bda89295dcc39d06382c4ba64568/src/clj/qbits/hayt/codec/joda_time.clj | clojure | (ns qbits.hayt.codec.joda-time
"require/use this namespace if you want hayt to support Joda DateTime
encoding when generating raw queries"
(:require
[qbits.hayt.cql :as cql]
[clj-time.coerce :as ct]))
(extend-protocol cql/CQLEntities
org.joda.time.DateTime
(cql-value [x]
(ct/to-long x)))
| |
b3471f2d76a0fc8abc7f6a4a669f9ac8579d0f71b8704fc469190aa6a7b0c2a0 | argp/bap | batInt64.mli |
* BatInt64 - Extended 64 - bit integers
* Copyright ( C ) 2005
* 2007 Bluestorm < bluestorm dot dylc on - the - server gmail dot com >
* 2008
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* BatInt64 - Extended 64-bit integers
* Copyright (C) 2005 Damien Doligez
* 2007 Bluestorm <bluestorm dot dylc on-the-server gmail dot com>
* 2008 David Teller
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
* 64 - bit integers .
This module provides operations on the type [ int64 ]
of signed 64 - bit integers . Unlike the built - in [ int ] type ,
the type [ int64 ] is guaranteed to be exactly 64 - bit wide on all
platforms . All arithmetic operations over [ int64 ] are taken
modulo 2{^64 } .
Performance notice : values of type [ int64 ] occupy more memory
space than values of type [ int ] , and arithmetic operations on
[ int64 ] are generally slower than those on [ int ] . Use [ int64 ]
only when the application requires exact 64 - bit arithmetic .
Any integer literal followed by [ L ] is taken to be an [ int64 ] .
For instance , [ 1L ] is { ! Int64.one } .
This module extends 's
{ { : -ocaml/libref/Int64.html}Int64 }
module , go there for documentation on the rest of the functions
and types .
@author ( base module )
@author @author
This module provides operations on the type [int64]
of signed 64-bit integers. Unlike the built-in [int] type,
the type [int64] is guaranteed to be exactly 64-bit wide on all
platforms. All arithmetic operations over [int64] are taken
modulo 2{^64}.
Performance notice: values of type [int64] occupy more memory
space than values of type [int], and arithmetic operations on
[int64] are generally slower than those on [int]. Use [int64]
only when the application requires exact 64-bit arithmetic.
Any integer literal followed by [L] is taken to be an [int64].
For instance, [1L] is {!Int64.one}.
This module extends Stdlib's
{{:-ocaml/libref/Int64.html}Int64}
module, go there for documentation on the rest of the functions
and types.
@author Xavier Leroy (base module)
@author Gabriel Scherer
@author David Teller
*)
type t = int64
val zero : int64
* The 64 - bit integer 0 .
val one : int64
* The 64 - bit integer 1 .
val minus_one : int64
* The 64 - bit integer -1 .
external neg : int64 -> int64 = "%int64_neg"
(** Unary negation. *)
external add : int64 -> int64 -> int64 = "%int64_add"
(** Addition. *)
external sub : int64 -> int64 -> int64 = "%int64_sub"
(** Subtraction. *)
external mul : int64 -> int64 -> int64 = "%int64_mul"
(** Multiplication. *)
external div : int64 -> int64 -> int64 = "%int64_div"
* Integer division .
This division rounds the real quotient of
its arguments towards zero , as specified for { ! Pervasives.(/ ) } .
@raise Division_by_zero if the second argument is zero .
This division rounds the real quotient of
its arguments towards zero, as specified for {!Pervasives.(/)}.
@raise Division_by_zero if the second argument is zero. *)
external rem : int64 -> int64 -> int64 = "%int64_mod"
* Integer remainder . If [ y ] is not zero , the result
of [ Int64.rem x y ] satisfies the following property :
[ x = ( ( Int64.div x y ) y ) ( Int64.rem x y ) ] .
@raise Division_by_zero if the second argument is zero .
of [Int64.rem x y] satisfies the following property:
[x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)].
@raise Division_by_zero if the second argument is zero. *)
val succ : int64 -> int64
(** Successor. [Int64.succ x] is [Int64.add x Int64.one]. *)
val pred : int64 -> int64
(** Predecessor. [Int64.pred x] is [Int64.sub x Int64.one]. *)
val abs : int64 -> int64
(** Return the absolute value of its argument. *)
val max_int : int64
* The greatest representable 64 - bit integer , 2{^63 } - 1 .
val min_int : int64
* The smallest representable 64 - bit integer , -2{^63 } .
external logand : int64 -> int64 -> int64 = "%int64_and"
(** Bitwise logical and. *)
external logor : int64 -> int64 -> int64 = "%int64_or"
(** Bitwise logical or. *)
external logxor : int64 -> int64 -> int64 = "%int64_xor"
(** Bitwise logical exclusive or. *)
val lognot : int64 -> int64
(** Bitwise logical negation *)
external shift_left : int64 -> int -> int64 = "%int64_lsl"
* [ Int64.shift_left x y ] shifts [ x ] to the left by [ y ] bits .
The result is unspecified if [ y < 0 ] or [ y > = 64 ] .
The result is unspecified if [y < 0] or [y >= 64]. *)
external shift_right : int64 -> int -> int64 = "%int64_asr"
* [ Int64.shift_right x y ] shifts [ x ] to the right by [ y ] bits .
This is an arithmetic shift : the sign bit of [ x ] is replicated
and inserted in the vacated bits .
The result is unspecified if [ y < 0 ] or [ y > = 64 ] .
This is an arithmetic shift: the sign bit of [x] is replicated
and inserted in the vacated bits.
The result is unspecified if [y < 0] or [y >= 64]. *)
external shift_right_logical : int64 -> int -> int64 = "%int64_lsr"
* [ Int64.shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits .
This is a logical shift : zeroes are inserted in the vacated bits
regardless of the sign of [ x ] .
The result is unspecified if [ y < 0 ] or [ y > = 64 ] .
This is a logical shift: zeroes are inserted in the vacated bits
regardless of the sign of [x].
The result is unspecified if [y < 0] or [y >= 64]. *)
val ( -- ) : t -> t -> t BatEnum.t
* Enumerate an interval .
[ 5L -- 10L ] is the enumeration 5L,6L,7L,8L,9L,10L.
[ 10L -- 5L ] is the empty enumeration
[5L -- 10L] is the enumeration 5L,6L,7L,8L,9L,10L.
[10L -- 5L] is the empty enumeration*)
val ( --- ) : t -> t -> t BatEnum.t
* Enumerate an interval .
[ 5L -- 10L ] is the enumeration 5L,6L,7L,8L,9L,10L.
[ 10L -- 5L ] is the enumeration 10L,9L,8L,7L,6L,5L.
[5L -- 10L] is the enumeration 5L,6L,7L,8L,9L,10L.
[10L -- 5L] is the enumeration 10L,9L,8L,7L,6L,5L.*)
external of_int : int -> int64 = "%int64_of_int"
* Convert the given integer ( type [ int ] ) to a 64 - bit integer
( type [ int64 ] ) .
(type [int64]). *)
external to_int : int64 -> int = "%int64_to_int"
* Convert the given 64 - bit integer ( type [ int64 ] ) to an
integer ( type [ int ] ) . On 64 - bit platforms , the 64 - bit integer
is taken modulo 2{^63 } , i.e. the high - order bit is lost
during the conversion . On 32 - bit platforms , the 64 - bit integer
is taken modulo 2{^31 } , i.e. the top 33 bits are lost
during the conversion .
integer (type [int]). On 64-bit platforms, the 64-bit integer
is taken modulo 2{^63}, i.e. the high-order bit is lost
during the conversion. On 32-bit platforms, the 64-bit integer
is taken modulo 2{^31}, i.e. the top 33 bits are lost
during the conversion. *)
external of_float : float -> int64 = "caml_int64_of_float"
* Convert the given floating - point number to a 64 - bit integer ,
discarding the fractional part ( truncate towards 0 ) .
The result of the conversion is undefined if , after truncation ,
the number is outside the range \[{!Int64.min_int } , { ! Int64.max_int}\ ] .
discarding the fractional part (truncate towards 0).
The result of the conversion is undefined if, after truncation,
the number is outside the range \[{!Int64.min_int}, {!Int64.max_int}\]. *)
external to_float : int64 -> float = "caml_int64_to_float"
* Convert the given 64 - bit integer to a floating - point number .
external of_int32 : int32 -> int64 = "%int64_of_int32"
* Convert the given 32 - bit integer ( type [ int32 ] )
to a 64 - bit integer ( type [ int64 ] ) .
to a 64-bit integer (type [int64]). *)
external to_int32 : int64 -> int32 = "%int64_to_int32"
* Convert the given 64 - bit integer ( type [ int64 ] ) to a
32 - bit integer ( type [ int32 ] ) . The 64 - bit integer
is taken modulo 2{^32 } , i.e. the top 32 bits are lost
during the conversion .
32-bit integer (type [int32]). The 64-bit integer
is taken modulo 2{^32}, i.e. the top 32 bits are lost
during the conversion. *)
external of_nativeint : nativeint -> int64 = "%int64_of_nativeint"
* Convert the given native integer ( type [ nativeint ] )
to a 64 - bit integer ( type [ int64 ] ) .
to a 64-bit integer (type [int64]). *)
external to_nativeint : int64 -> nativeint = "%int64_to_nativeint"
* Convert the given 64 - bit integer ( type [ int64 ] ) to a
native integer . On 32 - bit platforms , the 64 - bit integer
is taken modulo 2{^32 } . On 64 - bit platforms ,
the conversion is exact .
native integer. On 32-bit platforms, the 64-bit integer
is taken modulo 2{^32}. On 64-bit platforms,
the conversion is exact. *)
external of_string : string -> int64 = "caml_int64_of_string"
* Convert the given string to a 64 - bit integer .
The string is read in decimal ( by default ) or in hexadecimal ,
octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ]
respectively .
@raise Failure if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ int64 ] .
The string is read in decimal (by default) or in hexadecimal,
octal or binary if the string begins with [0x], [0o] or [0b]
respectively.
@raise Failure if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [int64]. *)
val to_string : int64 -> string
(** Return the string representation of its argument, in decimal. *)
external bits_of_float : float -> int64 = "caml_int64_bits_of_float"
* Return the internal representation of the given float according
to the IEEE 754 floating - point ` ` double format '' bit layout .
Bit 63 of the result represents the sign of the float ;
bits 62 to 52 represent the ( biased ) exponent ; bits 51 to 0
represent the mantissa .
to the IEEE 754 floating-point ``double format'' bit layout.
Bit 63 of the result represents the sign of the float;
bits 62 to 52 represent the (biased) exponent; bits 51 to 0
represent the mantissa. *)
external float_of_bits : int64 -> float = "caml_int64_float_of_bits"
* Return the floating - point number whose internal representation ,
according to the IEEE 754 floating - point ` ` double format '' bit layout ,
is the given [ int64 ] .
according to the IEEE 754 floating-point ``double format'' bit layout,
is the given [int64]. *)
val compare : t -> t -> int
* The comparison function for 64 - bit integers , with the same specification as
{ ! Pervasives.compare } . Along with the type [ t ] , this function [ compare ]
allows the module [ Int64 ] to be passed as argument to the functors
{ ! Set . Make } and { ! Map . Make } .
{!Pervasives.compare}. Along with the type [t], this function [compare]
allows the module [Int64] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
val equal : t -> t -> bool
* Equality function for 64 - bit integers , useful for { ! HashedType } .
val ord : t -> t -> BatOrd.order
* { 6 Submodules grouping all infix operators }
module Infix : BatNumber.Infix with type bat__infix_t = t
module Compare: BatNumber.Compare with type bat__compare_t = t
(**/**)
* { 6 Deprecated functions }
external format : string -> int64 -> string = "caml_int64_format"
* [ fmt n ] return the string representation of the
64 - bit integer [ n ] in the format specified by [ fmt ] .
[ fmt ] is a { ! Printf}-style format consisting of exactly one
[ % d ] , [ % i ] , [ % u ] , [ % x ] , [ % X ] or [ % o ] conversion specification .
This function is deprecated ; use { ! Printf.sprintf } with a [ % Lx ] format
instead .
64-bit integer [n] in the format specified by [fmt].
[fmt] is a {!Printf}-style format consisting of exactly one
[%d], [%i], [%u], [%x], [%X] or [%o] conversion specification.
This function is deprecated; use {!Printf.sprintf} with a [%Lx] format
instead. *)
(**/**)
val modulo : int64 -> int64 -> int64
val pow : int64 -> int64 -> int64
val ( + ) : t -> t -> t
val ( - ) : t -> t -> t
val ( * ) : t -> t -> t
val ( / ) : t -> t -> t
val ( ** ) : t -> t -> t
(* Available only in `Compare` submodule
val ( <> ) : t -> t -> bool
val ( >= ) : t -> t -> bool
val ( <= ) : t -> t -> bool
val ( > ) : t -> t -> bool
val ( < ) : t -> t -> bool
val ( = ) : t -> t -> bool
*)
val operations : t BatNumber.numeric
(** {6 Boilerplate code}*)
* { 7 Printing }
val print: 'a BatInnerIO.output -> t -> unit
(** prints as decimal string *)
val print_hex: 'a BatInnerIO.output -> t -> unit
(** prints as hex string *)
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batInt64.mli | ocaml | * Unary negation.
* Addition.
* Subtraction.
* Multiplication.
* Successor. [Int64.succ x] is [Int64.add x Int64.one].
* Predecessor. [Int64.pred x] is [Int64.sub x Int64.one].
* Return the absolute value of its argument.
* Bitwise logical and.
* Bitwise logical or.
* Bitwise logical exclusive or.
* Bitwise logical negation
* Return the string representation of its argument, in decimal.
*/*
*/*
Available only in `Compare` submodule
val ( <> ) : t -> t -> bool
val ( >= ) : t -> t -> bool
val ( <= ) : t -> t -> bool
val ( > ) : t -> t -> bool
val ( < ) : t -> t -> bool
val ( = ) : t -> t -> bool
* {6 Boilerplate code}
* prints as decimal string
* prints as hex string |
* BatInt64 - Extended 64 - bit integers
* Copyright ( C ) 2005
* 2007 Bluestorm < bluestorm dot dylc on - the - server gmail dot com >
* 2008
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* BatInt64 - Extended 64-bit integers
* Copyright (C) 2005 Damien Doligez
* 2007 Bluestorm <bluestorm dot dylc on-the-server gmail dot com>
* 2008 David Teller
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
* 64 - bit integers .
This module provides operations on the type [ int64 ]
of signed 64 - bit integers . Unlike the built - in [ int ] type ,
the type [ int64 ] is guaranteed to be exactly 64 - bit wide on all
platforms . All arithmetic operations over [ int64 ] are taken
modulo 2{^64 } .
Performance notice : values of type [ int64 ] occupy more memory
space than values of type [ int ] , and arithmetic operations on
[ int64 ] are generally slower than those on [ int ] . Use [ int64 ]
only when the application requires exact 64 - bit arithmetic .
Any integer literal followed by [ L ] is taken to be an [ int64 ] .
For instance , [ 1L ] is { ! Int64.one } .
This module extends 's
{ { : -ocaml/libref/Int64.html}Int64 }
module , go there for documentation on the rest of the functions
and types .
@author ( base module )
@author @author
This module provides operations on the type [int64]
of signed 64-bit integers. Unlike the built-in [int] type,
the type [int64] is guaranteed to be exactly 64-bit wide on all
platforms. All arithmetic operations over [int64] are taken
modulo 2{^64}.
Performance notice: values of type [int64] occupy more memory
space than values of type [int], and arithmetic operations on
[int64] are generally slower than those on [int]. Use [int64]
only when the application requires exact 64-bit arithmetic.
Any integer literal followed by [L] is taken to be an [int64].
For instance, [1L] is {!Int64.one}.
This module extends Stdlib's
{{:-ocaml/libref/Int64.html}Int64}
module, go there for documentation on the rest of the functions
and types.
@author Xavier Leroy (base module)
@author Gabriel Scherer
@author David Teller
*)
type t = int64
val zero : int64
* The 64 - bit integer 0 .
val one : int64
* The 64 - bit integer 1 .
val minus_one : int64
* The 64 - bit integer -1 .
external neg : int64 -> int64 = "%int64_neg"
external add : int64 -> int64 -> int64 = "%int64_add"
external sub : int64 -> int64 -> int64 = "%int64_sub"
external mul : int64 -> int64 -> int64 = "%int64_mul"
external div : int64 -> int64 -> int64 = "%int64_div"
* Integer division .
This division rounds the real quotient of
its arguments towards zero , as specified for { ! Pervasives.(/ ) } .
@raise Division_by_zero if the second argument is zero .
This division rounds the real quotient of
its arguments towards zero, as specified for {!Pervasives.(/)}.
@raise Division_by_zero if the second argument is zero. *)
external rem : int64 -> int64 -> int64 = "%int64_mod"
* Integer remainder . If [ y ] is not zero , the result
of [ Int64.rem x y ] satisfies the following property :
[ x = ( ( Int64.div x y ) y ) ( Int64.rem x y ) ] .
@raise Division_by_zero if the second argument is zero .
of [Int64.rem x y] satisfies the following property:
[x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)].
@raise Division_by_zero if the second argument is zero. *)
val succ : int64 -> int64
val pred : int64 -> int64
val abs : int64 -> int64
val max_int : int64
* The greatest representable 64 - bit integer , 2{^63 } - 1 .
val min_int : int64
* The smallest representable 64 - bit integer , -2{^63 } .
external logand : int64 -> int64 -> int64 = "%int64_and"
external logor : int64 -> int64 -> int64 = "%int64_or"
external logxor : int64 -> int64 -> int64 = "%int64_xor"
val lognot : int64 -> int64
external shift_left : int64 -> int -> int64 = "%int64_lsl"
* [ Int64.shift_left x y ] shifts [ x ] to the left by [ y ] bits .
The result is unspecified if [ y < 0 ] or [ y > = 64 ] .
The result is unspecified if [y < 0] or [y >= 64]. *)
external shift_right : int64 -> int -> int64 = "%int64_asr"
* [ Int64.shift_right x y ] shifts [ x ] to the right by [ y ] bits .
This is an arithmetic shift : the sign bit of [ x ] is replicated
and inserted in the vacated bits .
The result is unspecified if [ y < 0 ] or [ y > = 64 ] .
This is an arithmetic shift: the sign bit of [x] is replicated
and inserted in the vacated bits.
The result is unspecified if [y < 0] or [y >= 64]. *)
external shift_right_logical : int64 -> int -> int64 = "%int64_lsr"
* [ Int64.shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits .
This is a logical shift : zeroes are inserted in the vacated bits
regardless of the sign of [ x ] .
The result is unspecified if [ y < 0 ] or [ y > = 64 ] .
This is a logical shift: zeroes are inserted in the vacated bits
regardless of the sign of [x].
The result is unspecified if [y < 0] or [y >= 64]. *)
val ( -- ) : t -> t -> t BatEnum.t
* Enumerate an interval .
[ 5L -- 10L ] is the enumeration 5L,6L,7L,8L,9L,10L.
[ 10L -- 5L ] is the empty enumeration
[5L -- 10L] is the enumeration 5L,6L,7L,8L,9L,10L.
[10L -- 5L] is the empty enumeration*)
val ( --- ) : t -> t -> t BatEnum.t
* Enumerate an interval .
[ 5L -- 10L ] is the enumeration 5L,6L,7L,8L,9L,10L.
[ 10L -- 5L ] is the enumeration 10L,9L,8L,7L,6L,5L.
[5L -- 10L] is the enumeration 5L,6L,7L,8L,9L,10L.
[10L -- 5L] is the enumeration 10L,9L,8L,7L,6L,5L.*)
external of_int : int -> int64 = "%int64_of_int"
* Convert the given integer ( type [ int ] ) to a 64 - bit integer
( type [ int64 ] ) .
(type [int64]). *)
external to_int : int64 -> int = "%int64_to_int"
* Convert the given 64 - bit integer ( type [ int64 ] ) to an
integer ( type [ int ] ) . On 64 - bit platforms , the 64 - bit integer
is taken modulo 2{^63 } , i.e. the high - order bit is lost
during the conversion . On 32 - bit platforms , the 64 - bit integer
is taken modulo 2{^31 } , i.e. the top 33 bits are lost
during the conversion .
integer (type [int]). On 64-bit platforms, the 64-bit integer
is taken modulo 2{^63}, i.e. the high-order bit is lost
during the conversion. On 32-bit platforms, the 64-bit integer
is taken modulo 2{^31}, i.e. the top 33 bits are lost
during the conversion. *)
external of_float : float -> int64 = "caml_int64_of_float"
* Convert the given floating - point number to a 64 - bit integer ,
discarding the fractional part ( truncate towards 0 ) .
The result of the conversion is undefined if , after truncation ,
the number is outside the range \[{!Int64.min_int } , { ! Int64.max_int}\ ] .
discarding the fractional part (truncate towards 0).
The result of the conversion is undefined if, after truncation,
the number is outside the range \[{!Int64.min_int}, {!Int64.max_int}\]. *)
external to_float : int64 -> float = "caml_int64_to_float"
* Convert the given 64 - bit integer to a floating - point number .
external of_int32 : int32 -> int64 = "%int64_of_int32"
* Convert the given 32 - bit integer ( type [ int32 ] )
to a 64 - bit integer ( type [ int64 ] ) .
to a 64-bit integer (type [int64]). *)
external to_int32 : int64 -> int32 = "%int64_to_int32"
* Convert the given 64 - bit integer ( type [ int64 ] ) to a
32 - bit integer ( type [ int32 ] ) . The 64 - bit integer
is taken modulo 2{^32 } , i.e. the top 32 bits are lost
during the conversion .
32-bit integer (type [int32]). The 64-bit integer
is taken modulo 2{^32}, i.e. the top 32 bits are lost
during the conversion. *)
external of_nativeint : nativeint -> int64 = "%int64_of_nativeint"
* Convert the given native integer ( type [ nativeint ] )
to a 64 - bit integer ( type [ int64 ] ) .
to a 64-bit integer (type [int64]). *)
external to_nativeint : int64 -> nativeint = "%int64_to_nativeint"
* Convert the given 64 - bit integer ( type [ int64 ] ) to a
native integer . On 32 - bit platforms , the 64 - bit integer
is taken modulo 2{^32 } . On 64 - bit platforms ,
the conversion is exact .
native integer. On 32-bit platforms, the 64-bit integer
is taken modulo 2{^32}. On 64-bit platforms,
the conversion is exact. *)
external of_string : string -> int64 = "caml_int64_of_string"
* Convert the given string to a 64 - bit integer .
The string is read in decimal ( by default ) or in hexadecimal ,
octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ]
respectively .
@raise Failure if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ int64 ] .
The string is read in decimal (by default) or in hexadecimal,
octal or binary if the string begins with [0x], [0o] or [0b]
respectively.
@raise Failure if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [int64]. *)
val to_string : int64 -> string
external bits_of_float : float -> int64 = "caml_int64_bits_of_float"
* Return the internal representation of the given float according
to the IEEE 754 floating - point ` ` double format '' bit layout .
Bit 63 of the result represents the sign of the float ;
bits 62 to 52 represent the ( biased ) exponent ; bits 51 to 0
represent the mantissa .
to the IEEE 754 floating-point ``double format'' bit layout.
Bit 63 of the result represents the sign of the float;
bits 62 to 52 represent the (biased) exponent; bits 51 to 0
represent the mantissa. *)
external float_of_bits : int64 -> float = "caml_int64_float_of_bits"
* Return the floating - point number whose internal representation ,
according to the IEEE 754 floating - point ` ` double format '' bit layout ,
is the given [ int64 ] .
according to the IEEE 754 floating-point ``double format'' bit layout,
is the given [int64]. *)
val compare : t -> t -> int
* The comparison function for 64 - bit integers , with the same specification as
{ ! Pervasives.compare } . Along with the type [ t ] , this function [ compare ]
allows the module [ Int64 ] to be passed as argument to the functors
{ ! Set . Make } and { ! Map . Make } .
{!Pervasives.compare}. Along with the type [t], this function [compare]
allows the module [Int64] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
val equal : t -> t -> bool
* Equality function for 64 - bit integers , useful for { ! HashedType } .
val ord : t -> t -> BatOrd.order
* { 6 Submodules grouping all infix operators }
module Infix : BatNumber.Infix with type bat__infix_t = t
module Compare: BatNumber.Compare with type bat__compare_t = t
* { 6 Deprecated functions }
external format : string -> int64 -> string = "caml_int64_format"
* [ fmt n ] return the string representation of the
64 - bit integer [ n ] in the format specified by [ fmt ] .
[ fmt ] is a { ! Printf}-style format consisting of exactly one
[ % d ] , [ % i ] , [ % u ] , [ % x ] , [ % X ] or [ % o ] conversion specification .
This function is deprecated ; use { ! Printf.sprintf } with a [ % Lx ] format
instead .
64-bit integer [n] in the format specified by [fmt].
[fmt] is a {!Printf}-style format consisting of exactly one
[%d], [%i], [%u], [%x], [%X] or [%o] conversion specification.
This function is deprecated; use {!Printf.sprintf} with a [%Lx] format
instead. *)
val modulo : int64 -> int64 -> int64
val pow : int64 -> int64 -> int64
val ( + ) : t -> t -> t
val ( - ) : t -> t -> t
val ( * ) : t -> t -> t
val ( / ) : t -> t -> t
val ( ** ) : t -> t -> t
val operations : t BatNumber.numeric
* { 7 Printing }
val print: 'a BatInnerIO.output -> t -> unit
val print_hex: 'a BatInnerIO.output -> t -> unit
|
b6f855218328dc152865ca2b680966cdc9ceeb3bf715811ada2d59d726eada3e | achirkin/vulkan | VK_EXT_shader_atomic_float.hs | # OPTIONS_HADDOCK not - home #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MagicHash #-}
# LANGUAGE PatternSynonyms #
{-# LANGUAGE Strict #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.Vulkan.Ext.VK_EXT_shader_atomic_float
* Vulkan extension : @VK_EXT_shader_atomic_float@
-- |
--
-- supported: @vulkan@
--
-- contact: @Vikram Kushwaha @vkushwaha-nv@
--
author :
--
-- type: @device@
--
-- Extension number: @261@
--
-- Required extensions: 'VK_KHR_get_physical_device_properties2'.
--
-- ** Required extensions: 'VK_KHR_get_physical_device_properties2'.
module Graphics.Vulkan.Marshal, AHardwareBuffer(),
ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkPhysicalDeviceFeatures,
VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderAtomicFloatFeaturesEXT, VkStructureType(..),
-- > #include "vk_platform.h"
VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION,
pattern VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION,
VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME,
pattern VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderAtomicFloatFeaturesEXT)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
pattern VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION :: (Num a, Eq a) =>
a
pattern VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION = 1
type VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION = 1
pattern VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME :: CString
pattern VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME <-
(is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME -> True)
where
VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
= _VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
# INLINE _ VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME #
_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME :: CString
_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
= Ptr "VK_EXT_shader_atomic_float\NUL"#
# INLINE is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME #
is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME :: CString -> Bool
is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
= (EQ ==) . cmpCStrings _VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
type VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME =
"VK_EXT_shader_atomic_float"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT
= VkStructureType 1000260000
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_EXT_shader_atomic_float.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE Strict #
# LANGUAGE ViewPatterns #
|
supported: @vulkan@
contact: @Vikram Kushwaha @vkushwaha-nv@
type: @device@
Extension number: @261@
Required extensions: 'VK_KHR_get_physical_device_properties2'.
** Required extensions: 'VK_KHR_get_physical_device_properties2'.
> #include "vk_platform.h" | # OPTIONS_HADDOCK not - home #
# LANGUAGE PatternSynonyms #
module Graphics.Vulkan.Ext.VK_EXT_shader_atomic_float
* Vulkan extension : @VK_EXT_shader_atomic_float@
author :
module Graphics.Vulkan.Marshal, AHardwareBuffer(),
ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkPhysicalDeviceFeatures,
VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderAtomicFloatFeaturesEXT, VkStructureType(..),
VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION,
pattern VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION,
VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME,
pattern VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderAtomicFloatFeaturesEXT)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
pattern VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION :: (Num a, Eq a) =>
a
pattern VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION = 1
type VK_EXT_SHADER_ATOMIC_FLOAT_SPEC_VERSION = 1
pattern VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME :: CString
pattern VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME <-
(is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME -> True)
where
VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
= _VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
# INLINE _ VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME #
_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME :: CString
_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
= Ptr "VK_EXT_shader_atomic_float\NUL"#
# INLINE is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME #
is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME :: CString -> Bool
is_VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
= (EQ ==) . cmpCStrings _VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME
type VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME =
"VK_EXT_shader_atomic_float"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT
= VkStructureType 1000260000
|
a94e66026c21d4442c73f3890e0c3cb2ca7373f75173d6657e4ec7033ed996e9 | AeneasVerif/aeneas | InterpreterBorrows.mli | module T = Types
module V = Values
module C = Contexts
module Subst = Substitute
module L = Logging
module S = SynthesizeSymbolic
open Cps
open InterpreterProjectors
(** When copying values, we duplicate the shared borrows. This is tantamount to
reborrowing the shared value. The [reborrow_shared original_id new_bid ctx]
applies this change to an environment [ctx] by inserting a new borrow id in
the set of borrows tracked by a shared value, referenced by the
[original_bid] argument. *)
val reborrow_shared : V.BorrowId.id -> V.BorrowId.id -> C.eval_ctx -> C.eval_ctx
* End a borrow identified by its i d , while preserving the invariants .
If the borrow is inside another borrow / an abstraction or contains loans ,
[ end_borrow ] will end those borrows / abstractions / loans first .
If the borrow is inside another borrow/an abstraction or contains loans,
[end_borrow] will end those borrows/abstractions/loans first.
*)
val end_borrow : C.config -> V.BorrowId.id -> cm_fun
(** End a set of borrows identified by their ids, while preserving the invariants. *)
val end_borrows : C.config -> V.BorrowId.Set.t -> cm_fun
(** End an abstraction while preserving the invariants. *)
val end_abstraction : C.config -> V.AbstractionId.id -> cm_fun
(** End a set of abstractions while preserving the invariants. *)
val end_abstractions : C.config -> V.AbstractionId.Set.t -> cm_fun
(** End a borrow and return the resulting environment, ignoring synthesis *)
val end_borrow_no_synth : C.config -> V.BorrowId.id -> C.eval_ctx -> C.eval_ctx
(** End a set of borrows and return the resulting environment, ignoring synthesis *)
val end_borrows_no_synth :
C.config -> V.BorrowId.Set.t -> C.eval_ctx -> C.eval_ctx
(** End an abstraction and return the resulting environment, ignoring synthesis *)
val end_abstraction_no_synth :
C.config -> V.AbstractionId.id -> C.eval_ctx -> C.eval_ctx
(** End a set of abstractions and return the resulting environment, ignoring synthesis *)
val end_abstractions_no_synth :
C.config -> V.AbstractionId.Set.t -> C.eval_ctx -> C.eval_ctx
* Promote a reserved mut borrow to a mut borrow , while preserving the invariants .
Reserved borrows are special mutable borrows which are created as shared borrows
then promoted to mutable borrows upon their first use .
This function replaces the reserved borrow with a mutable borrow , then replaces
the corresponding shared loan with a mutable loan ( after having ended the
other shared borrows which point to this loan ) .
Reserved borrows are special mutable borrows which are created as shared borrows
then promoted to mutable borrows upon their first use.
This function replaces the reserved borrow with a mutable borrow, then replaces
the corresponding shared loan with a mutable loan (after having ended the
other shared borrows which point to this loan).
*)
val promote_reserved_mut_borrow : C.config -> V.BorrowId.id -> cm_fun
* Transform an abstraction to an abstraction where the values are not
structured .
For instance :
{ [
abs {
( , , _ )
}
~~ >
abs {
}
] }
Rem . : we do this to simplify the merging of abstractions . We can do this
because for now we do n't support nested borrows . In order to implement
support for nested borrows , we will probably need to maintain the structure
of the avalues .
Paramters :
- [ abs_kind ]
- [ can_end ]
- [ destructure_shared_values ] : if [ true ] , explore shared values and whenever we find
a shared loan , move it elsewhere by replacing it with the same value without
the shared loan , and adding another ashared loan in the abstraction .
For instance :
{ [
ML { l0 } ( 0 , ML { l1 } 1 )
~~ >
ML { l0 } ( 0 , 1 )
ML { l1 } 1
] }
- [ ctx ]
- [ abs ]
structured.
For instance:
{[
abs {
(mut_borrow l0, mut_borrow l1, _)
}
~~>
abs {
mut_borrow l0
mut_borrow l1
}
]}
Rem.: we do this to simplify the merging of abstractions. We can do this
because for now we don't support nested borrows. In order to implement
support for nested borrows, we will probably need to maintain the structure
of the avalues.
Paramters:
- [abs_kind]
- [can_end]
- [destructure_shared_values]: if [true], explore shared values and whenever we find
a shared loan, move it elsewhere by replacing it with the same value without
the shared loan, and adding another ashared loan in the abstraction.
For instance:
{[
ML {l0} (0, ML {l1} 1)
~~>
ML {l0} (0, 1)
ML {l1} 1
]}
- [ctx]
- [abs]
*)
val destructure_abs : V.abs_kind -> bool -> bool -> C.eval_ctx -> V.abs -> V.abs
(** Return [true] if the values in an abstraction are destructured.
We simply destructure it and check that it gives the identity.
The input boolean is [destructure_shared_value]. See {!destructure_abs}.
*)
val abs_is_destructured : bool -> C.eval_ctx -> V.abs -> bool
* Turn a value into a abstractions .
We are conservative , and do n't group borrows / loans into the same abstraction
unless necessary .
For instance :
{ [
_ - > ( mut_borrow l1 ( mut_loan l2 ) , mut_borrow l3 )
~~ >
abs'0 { mut_borrow l1 , mut_loan l2 }
abs'1 { mut_borrow l3 }
] }
Parameters :
- [ abs_kind ]
- [ can_end ]
- [ destructure_shared_values ] : this is similar to [ destructure_shared_values ]
for { ! destructure_abs } .
- [ ctx ]
- [ v ]
We are conservative, and don't group borrows/loans into the same abstraction
unless necessary.
For instance:
{[
_ -> (mut_borrow l1 (mut_loan l2), mut_borrow l3)
~~>
abs'0 { mut_borrow l1, mut_loan l2 }
abs'1 { mut_borrow l3 }
]}
Parameters:
- [abs_kind]
- [can_end]
- [destructure_shared_values]: this is similar to [destructure_shared_values]
for {!destructure_abs}.
- [ctx]
- [v]
*)
val convert_value_to_abstractions :
V.abs_kind -> bool -> bool -> C.eval_ctx -> V.typed_value -> V.abs list
(** See {!merge_into_abstraction}.
Rem.: it may be more idiomatic to have a functor, but this seems a bit
heavyweight, though.
*)
type merge_duplicates_funcs = {
merge_amut_borrows :
V.borrow_id ->
T.rty ->
V.typed_avalue ->
T.rty ->
V.typed_avalue ->
V.typed_avalue;
(** Parameters:
- [id]
- [ty0]
- [child0]
- [ty1]
- [child1]
The children should be [AIgnored].
*)
merge_ashared_borrows : V.borrow_id -> T.rty -> T.rty -> V.typed_avalue;
(** Parameters:
- [id]
- [ty0]
- [ty1]
*)
merge_amut_loans :
V.loan_id ->
T.rty ->
V.typed_avalue ->
T.rty ->
V.typed_avalue ->
V.typed_avalue;
(** Parameters:
- [id]
- [ty0]
- [child0]
- [ty1]
- [child1]
The children should be [AIgnored].
*)
merge_ashared_loans :
V.loan_id_set ->
T.rty ->
V.typed_value ->
V.typed_avalue ->
T.rty ->
V.typed_value ->
V.typed_avalue ->
V.typed_avalue;
(** Parameters:
- [ids]
- [ty0]
- [sv0]
- [child0]
- [ty1]
- [sv1]
- [child1]
*)
}
* Merge an abstraction into another abstraction .
We insert the result of the merge in place of the second abstraction ( and in
particular , we do n't simply push the merged abstraction at the end of the
environment : this helps preserving the structure of the environment , when
computing loop fixed points for instance ) .
When we merge two abstractions together , we remove the loans / borrows
which appear in one and whose associated loans / borrows appear in the
other . For instance :
{ [
abs'0 { mut_borrow l0 , mut_loan l1 } // Rem . : mut_loan l1
abs'1 { , } // Rem . : mut_borrow l1
~~ >
abs'01 { , }
] }
Also , we merge all their regions together . For instance , if [ abs'0 ] projects
region [ r0 ] and [ abs'1 ] projects region [ r1 ] , we pick one of the two , say [ r0 ]
( the one with the smallest index in practice ) and substitute [ r1 ] with [ r0 ]
in the whole context .
Parameters :
- [ kind ]
- [ can_end ]
- [ merge_funs ] : Those functions are used to merge borrows / loans with the
* same ids * . For instance , when performing environment joins we may introduce
abstractions which both contain loans / borrows with the same ids . When we
later merge those abstractions together , we need to call a merge function
to reconcile the borrows / loans . For instance , if both abstractions contain
the same shared loan [ l0 ] , we will call { ! merge_ashared_borrows } to derive
a shared value for the merged shared loans .
For instance , this happens for the following abstractions :
{ [
abs'0 { mut_borrow l0 , mut_loan l1 } //
abs'1 { , // !
] }
If you want to forbid this , provide [ None ] . In that case , [ merge_into_abstraction ]
actually simply performs some sort of a union .
- [ ctx ]
- [ abs_id0 ]
- [ abs_id1 ]
We return the updated context as well as the i d of the new abstraction which
results from the merge .
We insert the result of the merge in place of the second abstraction (and in
particular, we don't simply push the merged abstraction at the end of the
environment: this helps preserving the structure of the environment, when
computing loop fixed points for instance).
When we merge two abstractions together, we remove the loans/borrows
which appear in one and whose associated loans/borrows appear in the
other. For instance:
{[
abs'0 { mut_borrow l0, mut_loan l1 } // Rem.: mut_loan l1
abs'1 { mut_borrow l1, mut_borrow l2 } // Rem.: mut_borrow l1
~~>
abs'01 { mut_borrow l0, mut_borrow l2 }
]}
Also, we merge all their regions together. For instance, if [abs'0] projects
region [r0] and [abs'1] projects region [r1], we pick one of the two, say [r0]
(the one with the smallest index in practice) and substitute [r1] with [r0]
in the whole context.
Parameters:
- [kind]
- [can_end]
- [merge_funs]: Those functions are used to merge borrows/loans with the
*same ids*. For instance, when performing environment joins we may introduce
abstractions which both contain loans/borrows with the same ids. When we
later merge those abstractions together, we need to call a merge function
to reconcile the borrows/loans. For instance, if both abstractions contain
the same shared loan [l0], we will call {!merge_ashared_borrows} to derive
a shared value for the merged shared loans.
For instance, this happens for the following abstractions:
{[
abs'0 { mut_borrow l0, mut_loan l1 } // mut_borrow l0 !
abs'1 { mut_borrow l0, mut_loan l2 } // mut_borrow l0 !
]}
If you want to forbid this, provide [None]. In that case, [merge_into_abstraction]
actually simply performs some sort of a union.
- [ctx]
- [abs_id0]
- [abs_id1]
We return the updated context as well as the id of the new abstraction which
results from the merge.
*)
val merge_into_abstraction :
V.abs_kind ->
bool ->
merge_duplicates_funcs option ->
C.eval_ctx ->
V.AbstractionId.id ->
V.AbstractionId.id ->
C.eval_ctx * V.AbstractionId.id
| null | https://raw.githubusercontent.com/AeneasVerif/aeneas/1535b37ae84ddb1d2679c19b8fcc734351e5ce5d/compiler/InterpreterBorrows.mli | ocaml | * When copying values, we duplicate the shared borrows. This is tantamount to
reborrowing the shared value. The [reborrow_shared original_id new_bid ctx]
applies this change to an environment [ctx] by inserting a new borrow id in
the set of borrows tracked by a shared value, referenced by the
[original_bid] argument.
* End a set of borrows identified by their ids, while preserving the invariants.
* End an abstraction while preserving the invariants.
* End a set of abstractions while preserving the invariants.
* End a borrow and return the resulting environment, ignoring synthesis
* End a set of borrows and return the resulting environment, ignoring synthesis
* End an abstraction and return the resulting environment, ignoring synthesis
* End a set of abstractions and return the resulting environment, ignoring synthesis
* Return [true] if the values in an abstraction are destructured.
We simply destructure it and check that it gives the identity.
The input boolean is [destructure_shared_value]. See {!destructure_abs}.
* See {!merge_into_abstraction}.
Rem.: it may be more idiomatic to have a functor, but this seems a bit
heavyweight, though.
* Parameters:
- [id]
- [ty0]
- [child0]
- [ty1]
- [child1]
The children should be [AIgnored].
* Parameters:
- [id]
- [ty0]
- [ty1]
* Parameters:
- [id]
- [ty0]
- [child0]
- [ty1]
- [child1]
The children should be [AIgnored].
* Parameters:
- [ids]
- [ty0]
- [sv0]
- [child0]
- [ty1]
- [sv1]
- [child1]
| module T = Types
module V = Values
module C = Contexts
module Subst = Substitute
module L = Logging
module S = SynthesizeSymbolic
open Cps
open InterpreterProjectors
val reborrow_shared : V.BorrowId.id -> V.BorrowId.id -> C.eval_ctx -> C.eval_ctx
* End a borrow identified by its i d , while preserving the invariants .
If the borrow is inside another borrow / an abstraction or contains loans ,
[ end_borrow ] will end those borrows / abstractions / loans first .
If the borrow is inside another borrow/an abstraction or contains loans,
[end_borrow] will end those borrows/abstractions/loans first.
*)
val end_borrow : C.config -> V.BorrowId.id -> cm_fun
val end_borrows : C.config -> V.BorrowId.Set.t -> cm_fun
val end_abstraction : C.config -> V.AbstractionId.id -> cm_fun
val end_abstractions : C.config -> V.AbstractionId.Set.t -> cm_fun
val end_borrow_no_synth : C.config -> V.BorrowId.id -> C.eval_ctx -> C.eval_ctx
val end_borrows_no_synth :
C.config -> V.BorrowId.Set.t -> C.eval_ctx -> C.eval_ctx
val end_abstraction_no_synth :
C.config -> V.AbstractionId.id -> C.eval_ctx -> C.eval_ctx
val end_abstractions_no_synth :
C.config -> V.AbstractionId.Set.t -> C.eval_ctx -> C.eval_ctx
* Promote a reserved mut borrow to a mut borrow , while preserving the invariants .
Reserved borrows are special mutable borrows which are created as shared borrows
then promoted to mutable borrows upon their first use .
This function replaces the reserved borrow with a mutable borrow , then replaces
the corresponding shared loan with a mutable loan ( after having ended the
other shared borrows which point to this loan ) .
Reserved borrows are special mutable borrows which are created as shared borrows
then promoted to mutable borrows upon their first use.
This function replaces the reserved borrow with a mutable borrow, then replaces
the corresponding shared loan with a mutable loan (after having ended the
other shared borrows which point to this loan).
*)
val promote_reserved_mut_borrow : C.config -> V.BorrowId.id -> cm_fun
* Transform an abstraction to an abstraction where the values are not
structured .
For instance :
{ [
abs {
( , , _ )
}
~~ >
abs {
}
] }
Rem . : we do this to simplify the merging of abstractions . We can do this
because for now we do n't support nested borrows . In order to implement
support for nested borrows , we will probably need to maintain the structure
of the avalues .
Paramters :
- [ abs_kind ]
- [ can_end ]
- [ destructure_shared_values ] : if [ true ] , explore shared values and whenever we find
a shared loan , move it elsewhere by replacing it with the same value without
the shared loan , and adding another ashared loan in the abstraction .
For instance :
{ [
ML { l0 } ( 0 , ML { l1 } 1 )
~~ >
ML { l0 } ( 0 , 1 )
ML { l1 } 1
] }
- [ ctx ]
- [ abs ]
structured.
For instance:
{[
abs {
(mut_borrow l0, mut_borrow l1, _)
}
~~>
abs {
mut_borrow l0
mut_borrow l1
}
]}
Rem.: we do this to simplify the merging of abstractions. We can do this
because for now we don't support nested borrows. In order to implement
support for nested borrows, we will probably need to maintain the structure
of the avalues.
Paramters:
- [abs_kind]
- [can_end]
- [destructure_shared_values]: if [true], explore shared values and whenever we find
a shared loan, move it elsewhere by replacing it with the same value without
the shared loan, and adding another ashared loan in the abstraction.
For instance:
{[
ML {l0} (0, ML {l1} 1)
~~>
ML {l0} (0, 1)
ML {l1} 1
]}
- [ctx]
- [abs]
*)
val destructure_abs : V.abs_kind -> bool -> bool -> C.eval_ctx -> V.abs -> V.abs
val abs_is_destructured : bool -> C.eval_ctx -> V.abs -> bool
* Turn a value into a abstractions .
We are conservative , and do n't group borrows / loans into the same abstraction
unless necessary .
For instance :
{ [
_ - > ( mut_borrow l1 ( mut_loan l2 ) , mut_borrow l3 )
~~ >
abs'0 { mut_borrow l1 , mut_loan l2 }
abs'1 { mut_borrow l3 }
] }
Parameters :
- [ abs_kind ]
- [ can_end ]
- [ destructure_shared_values ] : this is similar to [ destructure_shared_values ]
for { ! destructure_abs } .
- [ ctx ]
- [ v ]
We are conservative, and don't group borrows/loans into the same abstraction
unless necessary.
For instance:
{[
_ -> (mut_borrow l1 (mut_loan l2), mut_borrow l3)
~~>
abs'0 { mut_borrow l1, mut_loan l2 }
abs'1 { mut_borrow l3 }
]}
Parameters:
- [abs_kind]
- [can_end]
- [destructure_shared_values]: this is similar to [destructure_shared_values]
for {!destructure_abs}.
- [ctx]
- [v]
*)
val convert_value_to_abstractions :
V.abs_kind -> bool -> bool -> C.eval_ctx -> V.typed_value -> V.abs list
type merge_duplicates_funcs = {
merge_amut_borrows :
V.borrow_id ->
T.rty ->
V.typed_avalue ->
T.rty ->
V.typed_avalue ->
V.typed_avalue;
merge_ashared_borrows : V.borrow_id -> T.rty -> T.rty -> V.typed_avalue;
merge_amut_loans :
V.loan_id ->
T.rty ->
V.typed_avalue ->
T.rty ->
V.typed_avalue ->
V.typed_avalue;
merge_ashared_loans :
V.loan_id_set ->
T.rty ->
V.typed_value ->
V.typed_avalue ->
T.rty ->
V.typed_value ->
V.typed_avalue ->
V.typed_avalue;
}
* Merge an abstraction into another abstraction .
We insert the result of the merge in place of the second abstraction ( and in
particular , we do n't simply push the merged abstraction at the end of the
environment : this helps preserving the structure of the environment , when
computing loop fixed points for instance ) .
When we merge two abstractions together , we remove the loans / borrows
which appear in one and whose associated loans / borrows appear in the
other . For instance :
{ [
abs'0 { mut_borrow l0 , mut_loan l1 } // Rem . : mut_loan l1
abs'1 { , } // Rem . : mut_borrow l1
~~ >
abs'01 { , }
] }
Also , we merge all their regions together . For instance , if [ abs'0 ] projects
region [ r0 ] and [ abs'1 ] projects region [ r1 ] , we pick one of the two , say [ r0 ]
( the one with the smallest index in practice ) and substitute [ r1 ] with [ r0 ]
in the whole context .
Parameters :
- [ kind ]
- [ can_end ]
- [ merge_funs ] : Those functions are used to merge borrows / loans with the
* same ids * . For instance , when performing environment joins we may introduce
abstractions which both contain loans / borrows with the same ids . When we
later merge those abstractions together , we need to call a merge function
to reconcile the borrows / loans . For instance , if both abstractions contain
the same shared loan [ l0 ] , we will call { ! merge_ashared_borrows } to derive
a shared value for the merged shared loans .
For instance , this happens for the following abstractions :
{ [
abs'0 { mut_borrow l0 , mut_loan l1 } //
abs'1 { , // !
] }
If you want to forbid this , provide [ None ] . In that case , [ merge_into_abstraction ]
actually simply performs some sort of a union .
- [ ctx ]
- [ abs_id0 ]
- [ abs_id1 ]
We return the updated context as well as the i d of the new abstraction which
results from the merge .
We insert the result of the merge in place of the second abstraction (and in
particular, we don't simply push the merged abstraction at the end of the
environment: this helps preserving the structure of the environment, when
computing loop fixed points for instance).
When we merge two abstractions together, we remove the loans/borrows
which appear in one and whose associated loans/borrows appear in the
other. For instance:
{[
abs'0 { mut_borrow l0, mut_loan l1 } // Rem.: mut_loan l1
abs'1 { mut_borrow l1, mut_borrow l2 } // Rem.: mut_borrow l1
~~>
abs'01 { mut_borrow l0, mut_borrow l2 }
]}
Also, we merge all their regions together. For instance, if [abs'0] projects
region [r0] and [abs'1] projects region [r1], we pick one of the two, say [r0]
(the one with the smallest index in practice) and substitute [r1] with [r0]
in the whole context.
Parameters:
- [kind]
- [can_end]
- [merge_funs]: Those functions are used to merge borrows/loans with the
*same ids*. For instance, when performing environment joins we may introduce
abstractions which both contain loans/borrows with the same ids. When we
later merge those abstractions together, we need to call a merge function
to reconcile the borrows/loans. For instance, if both abstractions contain
the same shared loan [l0], we will call {!merge_ashared_borrows} to derive
a shared value for the merged shared loans.
For instance, this happens for the following abstractions:
{[
abs'0 { mut_borrow l0, mut_loan l1 } // mut_borrow l0 !
abs'1 { mut_borrow l0, mut_loan l2 } // mut_borrow l0 !
]}
If you want to forbid this, provide [None]. In that case, [merge_into_abstraction]
actually simply performs some sort of a union.
- [ctx]
- [abs_id0]
- [abs_id1]
We return the updated context as well as the id of the new abstraction which
results from the merge.
*)
val merge_into_abstraction :
V.abs_kind ->
bool ->
merge_duplicates_funcs option ->
C.eval_ctx ->
V.AbstractionId.id ->
V.AbstractionId.id ->
C.eval_ctx * V.AbstractionId.id
|
c021371d873ef93a8f86b518c8df26e87927ba06d9c8239755f153827d579961 | blamario/construct | Bits.hs | {-# LANGUAGE GADTs, TypeOperators #-}
-- | This module exports the primitives and combinators for constructing formats with sub- or cross-byte
-- components. See @test/MBR.hs@ for an example of its use.
--
> > > ( bigEndianBytesOf $ pair ( count 5 bit ) ( count 3 bit ) ) ( ByteString.pack [ 9 ] )
-- Right [(([False,False,False,False,True],[False,False,True]),"")]
module Construct.Bits
(Bits, bit,
* The combinators for converting between ' Bits ' and ' ByteString ' input streams
bigEndianBitsOf, bigEndianBytesOf, littleEndianBitsOf, littleEndianBytesOf) where
import Data.Bits (setBit, testBit)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.List as List
import Data.Word (Word8)
import Text.Parser.Input (InputParsing (ParserInput, anyToken))
import Construct
import Construct.Classes
import Construct.Internal
-- | The list of bits
type Bits = [Bool]
bit :: (Applicative n, InputParsing m, ParserInput m ~ Bits) => Format m n Bits Bool
bigEndianBitsOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m ByteString) n ByteString a -> Format (m Bits) n Bits a
bigEndianBytesOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m Bits) n Bits a -> Format (m ByteString) n ByteString a
littleEndianBitsOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m ByteString) n ByteString a -> Format (m Bits) n Bits a
littleEndianBytesOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m Bits) n Bits a -> Format (m ByteString) n ByteString a
-- | The primitive format of a single bit
--
> > > bit [ True , False , False , True ]
-- Right [(True,[False,False,True])]
bit = Format{
parse = head <$> anyToken,
serialize = pure . (:[])}
bigEndianBitsOf = mapMaybeSerialized (Just . enumerateFromMostSignificant) collectFromMostSignificant
bigEndianBytesOf = mapMaybeSerialized collectFromMostSignificant (Just . enumerateFromMostSignificant)
littleEndianBitsOf = mapMaybeSerialized (Just . enumerateFromLeastSignificant) collectFromLeastSignificant
littleEndianBytesOf = mapMaybeSerialized collectFromLeastSignificant (Just . enumerateFromLeastSignificant)
collectFromMostSignificant :: Bits -> Maybe ByteString
collectFromLeastSignificant :: Bits -> Maybe ByteString
enumerateFromMostSignificant :: ByteString -> Bits
enumerateFromLeastSignificant :: ByteString -> Bits
collectFromMostSignificant bits = (ByteString.pack . map toByte) <$> splitEach8 bits
where toByte octet = List.foldl' setBit (0 :: Word8) (map snd $ filter fst $ zip octet [7,6..0])
collectFromLeastSignificant bits = (ByteString.pack . map toByte) <$> splitEach8 bits
where toByte octet = List.foldl' setBit (0 :: Word8) (map snd $ filter fst $ zip octet [0..7])
enumerateFromMostSignificant = ByteString.foldr ((++) . enumerateByte) []
where enumerateByte b = [testBit b i | i <- [7,6..0]]
enumerateFromLeastSignificant = ByteString.foldr ((++) . enumerateByte) []
where enumerateByte b = [testBit b i | i <- [0..7]]
splitEach8 :: [a] -> Maybe [[a]]
splitEach8 [] = Just []
splitEach8 list
| length first8 == 8 = (first8 :) <$> splitEach8 rest
| otherwise = Nothing
where (first8, rest) = splitAt 8 list
| null | https://raw.githubusercontent.com/blamario/construct/ab6ab76d8fafef9912531e3e648b4fb7e074e631/src/Construct/Bits.hs | haskell | # LANGUAGE GADTs, TypeOperators #
| This module exports the primitives and combinators for constructing formats with sub- or cross-byte
components. See @test/MBR.hs@ for an example of its use.
Right [(([False,False,False,False,True],[False,False,True]),"")]
| The list of bits
| The primitive format of a single bit
Right [(True,[False,False,True])] |
> > > ( bigEndianBytesOf $ pair ( count 5 bit ) ( count 3 bit ) ) ( ByteString.pack [ 9 ] )
module Construct.Bits
(Bits, bit,
* The combinators for converting between ' Bits ' and ' ByteString ' input streams
bigEndianBitsOf, bigEndianBytesOf, littleEndianBitsOf, littleEndianBytesOf) where
import Data.Bits (setBit, testBit)
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.List as List
import Data.Word (Word8)
import Text.Parser.Input (InputParsing (ParserInput, anyToken))
import Construct
import Construct.Classes
import Construct.Internal
type Bits = [Bool]
bit :: (Applicative n, InputParsing m, ParserInput m ~ Bits) => Format m n Bits Bool
bigEndianBitsOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m ByteString) n ByteString a -> Format (m Bits) n Bits a
bigEndianBytesOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m Bits) n Bits a -> Format (m ByteString) n ByteString a
littleEndianBitsOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m ByteString) n ByteString a -> Format (m Bits) n Bits a
littleEndianBytesOf :: (InputParsing (m Bits), InputParsing (m ByteString), InputMappableParsing m, Functor n,
ParserInput (m Bits) ~ Bits, ParserInput (m ByteString) ~ ByteString) =>
Format (m Bits) n Bits a -> Format (m ByteString) n ByteString a
> > > bit [ True , False , False , True ]
bit = Format{
parse = head <$> anyToken,
serialize = pure . (:[])}
bigEndianBitsOf = mapMaybeSerialized (Just . enumerateFromMostSignificant) collectFromMostSignificant
bigEndianBytesOf = mapMaybeSerialized collectFromMostSignificant (Just . enumerateFromMostSignificant)
littleEndianBitsOf = mapMaybeSerialized (Just . enumerateFromLeastSignificant) collectFromLeastSignificant
littleEndianBytesOf = mapMaybeSerialized collectFromLeastSignificant (Just . enumerateFromLeastSignificant)
collectFromMostSignificant :: Bits -> Maybe ByteString
collectFromLeastSignificant :: Bits -> Maybe ByteString
enumerateFromMostSignificant :: ByteString -> Bits
enumerateFromLeastSignificant :: ByteString -> Bits
collectFromMostSignificant bits = (ByteString.pack . map toByte) <$> splitEach8 bits
where toByte octet = List.foldl' setBit (0 :: Word8) (map snd $ filter fst $ zip octet [7,6..0])
collectFromLeastSignificant bits = (ByteString.pack . map toByte) <$> splitEach8 bits
where toByte octet = List.foldl' setBit (0 :: Word8) (map snd $ filter fst $ zip octet [0..7])
enumerateFromMostSignificant = ByteString.foldr ((++) . enumerateByte) []
where enumerateByte b = [testBit b i | i <- [7,6..0]]
enumerateFromLeastSignificant = ByteString.foldr ((++) . enumerateByte) []
where enumerateByte b = [testBit b i | i <- [0..7]]
splitEach8 :: [a] -> Maybe [[a]]
splitEach8 [] = Just []
splitEach8 list
| length first8 == 8 = (first8 :) <$> splitEach8 rest
| otherwise = Nothing
where (first8, rest) = splitAt 8 list
|
3b31c5d666e8055b93c5b74a3afd4ac7c52dd711e66b6c262c2188b6459675c0 | ghcjs/ghcjs | cgrun060.hs | tickled a bug in stack squeezing in 6.8.2 . unsafePerformIO calls
-- noDuplicate#, which marks the update frames on the stack, and was
-- preventing subsequent update frames from being collapsed with the
-- marked frame.
module Main where
import System.IO.Unsafe
main = print (sim (replicate 100000 ()))
sim [] = True
sim (_:xs) = badStack (sim xs)
goodStack x = fromJust (Just x) --no stack overflow
badStack x = unsafePerformIO (return x) --stack overflow
fromJust (Just x) = x
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/codeGen/cgrun060.hs | haskell | noDuplicate#, which marks the update frames on the stack, and was
preventing subsequent update frames from being collapsed with the
marked frame.
no stack overflow
stack overflow | tickled a bug in stack squeezing in 6.8.2 . unsafePerformIO calls
module Main where
import System.IO.Unsafe
main = print (sim (replicate 100000 ()))
sim [] = True
sim (_:xs) = badStack (sim xs)
fromJust (Just x) = x
|
1e68e9da77b249d1f19be1c67499738da809e70a2a477b94ee6acdc4b6fddc48 | exoscale/clojure-kubernetes-client | v1alpha1_webhook_throttle_config.clj | (ns clojure-kubernetes-client.specs.v1alpha1-webhook-throttle-config
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1alpha1-webhook-throttle-config-data v1alpha1-webhook-throttle-config)
(def v1alpha1-webhook-throttle-config-data
{
(ds/opt :burst) int?
(ds/opt :qps) int?
})
(def v1alpha1-webhook-throttle-config
(ds/spec
{:name ::v1alpha1-webhook-throttle-config
:spec v1alpha1-webhook-throttle-config-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1alpha1_webhook_throttle_config.clj | clojure | (ns clojure-kubernetes-client.specs.v1alpha1-webhook-throttle-config
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1alpha1-webhook-throttle-config-data v1alpha1-webhook-throttle-config)
(def v1alpha1-webhook-throttle-config-data
{
(ds/opt :burst) int?
(ds/opt :qps) int?
})
(def v1alpha1-webhook-throttle-config
(ds/spec
{:name ::v1alpha1-webhook-throttle-config
:spec v1alpha1-webhook-throttle-config-data}))
| |
782e73be3b66466fcba1b8453e9bff1203689d03d0c92c4a56814ff968b4dad2 | armedbear/abcl | with-hash-table-iterator.lisp | with-hash-table-iterator.lisp
;;;
Copyright ( C ) 2003
$ Id$
;;;
;;; 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. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module. An independent module is a module which is not derived from
;;; or based on this library. If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so. If you do not wish to do so, delete this
;;; exception statement from your version.
(in-package "SYSTEM")
(defun hash-table-iterator-function (hash-table)
(let ((entries (hash-table-entries hash-table)))
#'(lambda () (let ((entry (car entries)))
(setq entries (cdr entries))
(if entry
(values t (car entry) (cdr entry))
nil)))))
(defmacro with-hash-table-iterator ((name hash-table) &body body)
(let ((iter (gensym)))
`(let ((,iter (hash-table-iterator-function ,hash-table)))
(macrolet ((,name () '(funcall ,iter)))
,@body))))
| null | https://raw.githubusercontent.com/armedbear/abcl/36a4b5994227d768882ff6458b3df9f79caac664/src/org/armedbear/lisp/with-hash-table-iterator.lisp | lisp |
This program is free software; you can redistribute it and/or
either version 2
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. | with-hash-table-iterator.lisp
Copyright ( C ) 2003
$ Id$
modify it under the terms of the GNU General Public License
of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
(in-package "SYSTEM")
(defun hash-table-iterator-function (hash-table)
(let ((entries (hash-table-entries hash-table)))
#'(lambda () (let ((entry (car entries)))
(setq entries (cdr entries))
(if entry
(values t (car entry) (cdr entry))
nil)))))
(defmacro with-hash-table-iterator ((name hash-table) &body body)
(let ((iter (gensym)))
`(let ((,iter (hash-table-iterator-function ,hash-table)))
(macrolet ((,name () '(funcall ,iter)))
,@body))))
|
bf59990370a12bdb9e334483ba01202ab6aa314320920b7ecdebd476a4691fd3 | freizl/dive-into-haskell | Main.hs | module Main where
import Data.Foldable
import Data.Monoid
main :: IO ()
main = putStrLn "Hello, Haskell!"
s1 = foldr (++) "" ["hello", " haskell"]
s2 = fold ["hello", " haskell", "!!"]
s3 = concat ["hello", " haskell", "!!"]
t1 = fmap length Just 2
| null | https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/readings/haskell-book/20/Main.hs | haskell | module Main where
import Data.Foldable
import Data.Monoid
main :: IO ()
main = putStrLn "Hello, Haskell!"
s1 = foldr (++) "" ["hello", " haskell"]
s2 = fold ["hello", " haskell", "!!"]
s3 = concat ["hello", " haskell", "!!"]
t1 = fmap length Just 2
| |
0b915459937c42ec991194dc2fa1c8c9c2302fac97bcecdcafd79a63d78da592 | vorotynsky/Kroha | Nasm.hs | module Kroha.Backends.Nasm (nasm) where
import Data.Bifunctor (first)
import Data.Graph (buildG)
import Data.List (intercalate)
import Data.Maybe (fromJust)
import Kroha.Backends.Common
import Kroha.Errors
import Kroha.Instructions (Instruction (..), LabelTarget (..), Section, Target (..))
import Kroha.Syntax.Syntax
import Kroha.Types
bytes :: Int -> Int
bytes x = ceiling (toEnum x / (8 :: Double))
label :: LabelTarget -> Label
label (CommonLabel l) = l
label (BeginLabel l) = l ++ "_begin"
label (EndLabel l) = l ++ "_end"
nasmType :: TypeName -> (String, String)
nasmType (TypeName "int8" ) = ("db", "byte")
nasmType (TypeName "int16") = ("dw", "word")
nasmType (PointerType _) = ("dw", "word")
nasmType (TypeName name ) = error $ "[Exception]: Unexpected type `" ++ name ++ "` in backend"
size2type :: Int -> TypeName
nasmTypeG , nasmTypeL, untyped :: TypeName -> String
(nasmTypeG, nasmTypeL, untyped) = (fst . nasmType, append " " . snd . nasmType, const "")
where append x s = s ++ x
target :: (TypeName -> String) -> Target -> String
target tf (LiteralTarget (IntegerLiteral num)) = show num
target tf (StackTarget (offset, s)) = (tf . size2type) s ++ "[bp - " ++ show (bytes offset) ++ "]"
target tf (RegisterTarget reg) = reg
target tf (VariableTarget name t) = tf t ++ "[" ++ name ++ "]"
jump :: Comparator -> String
jump Equals = "je"
jump NotEquals = "jne"
jump Less = "jl"
jump Greater = "jg"
nasm16I :: Instruction -> [String]
nasm16I (Body _ _) = []
nasm16I (Assembly asm) = [asm]
nasm16I (Label lbl) = [label lbl ++ ":"]
nasm16I (Move l r) = ["mov " ++ target nasmTypeL l ++ ", " ++ target untyped r]
nasm16I (CallI l args) = (fmap (("push " ++) . target nasmTypeL) . reverse $ args) ++ ["call " ++ label l, "add sp, " ++ show ((length args) * 2)]
nasm16I (Jump l Nothing) = ["jmp " ++ label l]
nasm16I (Jump lbl (Just (l, c, r))) = ["cmp " ++ target nasmTypeL l ++ ", " ++ target untyped r, jump c ++ " " ++ label lbl]
nasm16I (StackAlloc s) = ["enter " ++ show (bytes s) ++ ", 0"]
nasmSection :: Section -> String -> String
nasmSection section body = header <> body <> "\n\n"
where header = "section ." ++ section ++ "\n"
nasmDeclaration :: Declaration d -> [String] -> String
nasmDeclaration (Frame l _ _) body = l ++ ":\n" ++ intercalate "\n" body ++ "\nleave\nret"
nasmDeclaration (ManualVariable v _ _ _) [body] = v ++ ": " ++ body ++ "\n"
nasmDeclaration (ManualFrame l _ _) body = l ++ ":\n" ++ intercalate "\n" (fmap (" " ++) body)
nasmDeclaration (ManualVariable v _ _ _) body = v ++ ":\n" ++ intercalate "\n" (fmap (" " ++) body)
nasmDeclaration (GlobalVariable n t (IntegerLiteral l) _) _ = n ++ ": " ++ nasmTypeG t ++ " " ++ show l
nasmDeclaration (ConstantVariable n t (IntegerLiteral l) _) _ = n ++ ": " ++ nasmTypeG t ++ " " ++ show l
litType :: Literal -> Result TypeId
litType l@(IntegerLiteral x) | x >= 0 && x < 65536 = Right 2
| otherwise = Left (BackendError (show l ++ " is not in [0; 65536)"))
nasmTypes = TypeConfig
{ types = (fmap . first) TypeName [("int8", 8), ("int16", 16), ("+literal+", 16)]
, pointerType = 1
, registers = zip ((\x -> fmap ((:) x . pure) "lhx") =<< "abcd") (cycle [0, 0, 1])
, typeCasts = buildG (0, 3) [(0, 2), (1, 2)]
, literalType = litType }
size2type size = fromJust . lookup size . fmap (\(a, b) -> (b, a)) $ types nasmTypes
nasm = Backend
{ instruction = nasm16I
, bodyWrap = id
, indent = " "
, section = nasmSection
, declaration = nasmDeclaration
, typeConfig = nasmTypes }
| null | https://raw.githubusercontent.com/vorotynsky/Kroha/e5d11c5f3612d3ea9b0701c7945ff8cc51ea12d6/src/Kroha/Backends/Nasm.hs | haskell | module Kroha.Backends.Nasm (nasm) where
import Data.Bifunctor (first)
import Data.Graph (buildG)
import Data.List (intercalate)
import Data.Maybe (fromJust)
import Kroha.Backends.Common
import Kroha.Errors
import Kroha.Instructions (Instruction (..), LabelTarget (..), Section, Target (..))
import Kroha.Syntax.Syntax
import Kroha.Types
bytes :: Int -> Int
bytes x = ceiling (toEnum x / (8 :: Double))
label :: LabelTarget -> Label
label (CommonLabel l) = l
label (BeginLabel l) = l ++ "_begin"
label (EndLabel l) = l ++ "_end"
nasmType :: TypeName -> (String, String)
nasmType (TypeName "int8" ) = ("db", "byte")
nasmType (TypeName "int16") = ("dw", "word")
nasmType (PointerType _) = ("dw", "word")
nasmType (TypeName name ) = error $ "[Exception]: Unexpected type `" ++ name ++ "` in backend"
size2type :: Int -> TypeName
nasmTypeG , nasmTypeL, untyped :: TypeName -> String
(nasmTypeG, nasmTypeL, untyped) = (fst . nasmType, append " " . snd . nasmType, const "")
where append x s = s ++ x
target :: (TypeName -> String) -> Target -> String
target tf (LiteralTarget (IntegerLiteral num)) = show num
target tf (StackTarget (offset, s)) = (tf . size2type) s ++ "[bp - " ++ show (bytes offset) ++ "]"
target tf (RegisterTarget reg) = reg
target tf (VariableTarget name t) = tf t ++ "[" ++ name ++ "]"
jump :: Comparator -> String
jump Equals = "je"
jump NotEquals = "jne"
jump Less = "jl"
jump Greater = "jg"
nasm16I :: Instruction -> [String]
nasm16I (Body _ _) = []
nasm16I (Assembly asm) = [asm]
nasm16I (Label lbl) = [label lbl ++ ":"]
nasm16I (Move l r) = ["mov " ++ target nasmTypeL l ++ ", " ++ target untyped r]
nasm16I (CallI l args) = (fmap (("push " ++) . target nasmTypeL) . reverse $ args) ++ ["call " ++ label l, "add sp, " ++ show ((length args) * 2)]
nasm16I (Jump l Nothing) = ["jmp " ++ label l]
nasm16I (Jump lbl (Just (l, c, r))) = ["cmp " ++ target nasmTypeL l ++ ", " ++ target untyped r, jump c ++ " " ++ label lbl]
nasm16I (StackAlloc s) = ["enter " ++ show (bytes s) ++ ", 0"]
nasmSection :: Section -> String -> String
nasmSection section body = header <> body <> "\n\n"
where header = "section ." ++ section ++ "\n"
nasmDeclaration :: Declaration d -> [String] -> String
nasmDeclaration (Frame l _ _) body = l ++ ":\n" ++ intercalate "\n" body ++ "\nleave\nret"
nasmDeclaration (ManualVariable v _ _ _) [body] = v ++ ": " ++ body ++ "\n"
nasmDeclaration (ManualFrame l _ _) body = l ++ ":\n" ++ intercalate "\n" (fmap (" " ++) body)
nasmDeclaration (ManualVariable v _ _ _) body = v ++ ":\n" ++ intercalate "\n" (fmap (" " ++) body)
nasmDeclaration (GlobalVariable n t (IntegerLiteral l) _) _ = n ++ ": " ++ nasmTypeG t ++ " " ++ show l
nasmDeclaration (ConstantVariable n t (IntegerLiteral l) _) _ = n ++ ": " ++ nasmTypeG t ++ " " ++ show l
litType :: Literal -> Result TypeId
litType l@(IntegerLiteral x) | x >= 0 && x < 65536 = Right 2
| otherwise = Left (BackendError (show l ++ " is not in [0; 65536)"))
nasmTypes = TypeConfig
{ types = (fmap . first) TypeName [("int8", 8), ("int16", 16), ("+literal+", 16)]
, pointerType = 1
, registers = zip ((\x -> fmap ((:) x . pure) "lhx") =<< "abcd") (cycle [0, 0, 1])
, typeCasts = buildG (0, 3) [(0, 2), (1, 2)]
, literalType = litType }
size2type size = fromJust . lookup size . fmap (\(a, b) -> (b, a)) $ types nasmTypes
nasm = Backend
{ instruction = nasm16I
, bodyWrap = id
, indent = " "
, section = nasmSection
, declaration = nasmDeclaration
, typeConfig = nasmTypes }
| |
21c06689ed93304a6fb26a10c3ac94cf773a2c799b67a4d45dbf2c775b409446 | Copilot-Language/copilot-core | Render.hs | --------------------------------------------------------------------------------
Copyright © 2011 National Institute of Aerospace / Galois , Inc.
--------------------------------------------------------------------------------
-- | Pretty-print the results of a simulation.
{-# LANGUAGE Safe #-}
module Copilot.Core.Interpret.Render
( renderAsTable
, renderAsCSV
) where
import Data.List (intersperse, transpose, foldl')
import Data.Maybe (catMaybes)
import Copilot.Core.Interpret.Eval (Output, ExecTrace (..))
import Text.PrettyPrint
import Prelude hiding ((<>))
--------------------------------------------------------------------------------
-- | Render an execution trace as a table, formatted to faciliate readability.
renderAsTable :: ExecTrace -> String
renderAsTable
ExecTrace
{ interpTriggers = trigs
, interpObservers = obsvs } = ( render
. asColumns
. transpose
. (:) (ppTriggerNames ++ ppObserverNames)
. transpose
) (ppTriggerOutputs ++ ppObserverOutputs)
where
ppTriggerNames :: [Doc]
ppTriggerNames = map (text . (++ ":")) (map fst trigs)
ppObserverNames :: [Doc]
ppObserverNames = map (text . (++ ":")) (map fst obsvs)
ppTriggerOutputs :: [[Doc]]
ppTriggerOutputs = map (map ppTriggerOutput) (map snd trigs)
ppTriggerOutput :: Maybe [Output] -> Doc
ppTriggerOutput (Just vs) = text $ "(" ++ concat (intersperse "," vs) ++ ")"
ppTriggerOutput Nothing = text "--"
ppObserverOutputs :: [[Doc]]
ppObserverOutputs = map (map text) (map snd obsvs)
--------------------------------------------------------------------------------
-- | Render an execution trace as using comma-separate value (CSV) format.
renderAsCSV :: ExecTrace -> String
renderAsCSV = render . unfold
-- | Pretty print all the steps of the execution trace and concatenate the
-- results.
unfold :: ExecTrace -> Doc
unfold r =
case step r of
(cs, Nothing) -> cs
(cs, Just r') -> cs $$ unfold r'
-- | Pretty print the state of the triggers, and provide a continuation
-- for the execution trace at the next point in time.
step :: ExecTrace -> (Doc, Maybe ExecTrace)
step ExecTrace
{ interpTriggers = trigs
} =
if null trigs then (empty, Nothing)
else (foldl' ($$) empty (text "#" : ppTriggerOutputs), tails)
where
ppTriggerOutputs :: [Doc]
ppTriggerOutputs =
catMaybes
. fmap ppTriggerOutput
. map (fmap head)
$ trigs
ppTriggerOutput :: (String, Maybe [Output]) -> Maybe Doc
ppTriggerOutput (_, Nothing) = Nothing
ppTriggerOutput (cs, Just xs) = Just $
text cs <> text "," <>
(foldr (<>) empty . map text . intersperse ",") xs
tails :: Maybe ExecTrace
tails =
if any null (fmap (tail.snd) trigs)
then Nothing
else Just
ExecTrace
{ interpTriggers = map (fmap tail) trigs
, interpObservers = []
}
--------------------------------------------------------------------------------
Copied from pretty - ncols because of incompatibility with newer GHC versions .
asColumns :: [[Doc]] -> Doc
asColumns = flip asColumnsWithBuff $ 1
asColumnsWithBuff :: [[Doc]] -> Int -> Doc
asColumnsWithBuff lls q = normalize
where normalize = vcat $ map hsep
$ map (\x -> pad (length x) longColumnLen empty x)
$ pad' longEntryLen q
$ transpose lls -- normalize column height
longColumnLen = maximum (map length lls)
longEntryLen = maximum $ map docLen (concat lls)
docLen d = length $ render d
-- | Pad a string on the right to reach an expected length.
pad :: Int -> Int -> a -> [a] -> [a]
pad lx max b ls = ls ++ replicate (max - lx) b
-- | Pad a list of strings on the right with spaces.
pad' :: Int -- ^ Mininum number of spaces to add
-> Int -- ^ Maximum number of spaces to add
-> [[Doc]] -- ^ List of documents to pad
-> [[Doc]]
pad' _ _ [] = []
pad' mx q (ls:xs) = map buf ls : pad' mx q xs
where buf x = x <> (hcat $ replicate q space) <> (hcat $ replicate (mx - (docLen x)) space)
| null | https://raw.githubusercontent.com/Copilot-Language/copilot-core/a8b79da96b11da20c36c4d4e0624e234a4d04323/src/Copilot/Core/Interpret/Render.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Pretty-print the results of a simulation.
# LANGUAGE Safe #
------------------------------------------------------------------------------
| Render an execution trace as a table, formatted to faciliate readability.
------------------------------------------------------------------------------
| Render an execution trace as using comma-separate value (CSV) format.
| Pretty print all the steps of the execution trace and concatenate the
results.
| Pretty print the state of the triggers, and provide a continuation
for the execution trace at the next point in time.
------------------------------------------------------------------------------
normalize column height
| Pad a string on the right to reach an expected length.
| Pad a list of strings on the right with spaces.
^ Mininum number of spaces to add
^ Maximum number of spaces to add
^ List of documents to pad | Copyright © 2011 National Institute of Aerospace / Galois , Inc.
module Copilot.Core.Interpret.Render
( renderAsTable
, renderAsCSV
) where
import Data.List (intersperse, transpose, foldl')
import Data.Maybe (catMaybes)
import Copilot.Core.Interpret.Eval (Output, ExecTrace (..))
import Text.PrettyPrint
import Prelude hiding ((<>))
renderAsTable :: ExecTrace -> String
renderAsTable
ExecTrace
{ interpTriggers = trigs
, interpObservers = obsvs } = ( render
. asColumns
. transpose
. (:) (ppTriggerNames ++ ppObserverNames)
. transpose
) (ppTriggerOutputs ++ ppObserverOutputs)
where
ppTriggerNames :: [Doc]
ppTriggerNames = map (text . (++ ":")) (map fst trigs)
ppObserverNames :: [Doc]
ppObserverNames = map (text . (++ ":")) (map fst obsvs)
ppTriggerOutputs :: [[Doc]]
ppTriggerOutputs = map (map ppTriggerOutput) (map snd trigs)
ppTriggerOutput :: Maybe [Output] -> Doc
ppTriggerOutput (Just vs) = text $ "(" ++ concat (intersperse "," vs) ++ ")"
ppTriggerOutput Nothing = text "--"
ppObserverOutputs :: [[Doc]]
ppObserverOutputs = map (map text) (map snd obsvs)
renderAsCSV :: ExecTrace -> String
renderAsCSV = render . unfold
unfold :: ExecTrace -> Doc
unfold r =
case step r of
(cs, Nothing) -> cs
(cs, Just r') -> cs $$ unfold r'
step :: ExecTrace -> (Doc, Maybe ExecTrace)
step ExecTrace
{ interpTriggers = trigs
} =
if null trigs then (empty, Nothing)
else (foldl' ($$) empty (text "#" : ppTriggerOutputs), tails)
where
ppTriggerOutputs :: [Doc]
ppTriggerOutputs =
catMaybes
. fmap ppTriggerOutput
. map (fmap head)
$ trigs
ppTriggerOutput :: (String, Maybe [Output]) -> Maybe Doc
ppTriggerOutput (_, Nothing) = Nothing
ppTriggerOutput (cs, Just xs) = Just $
text cs <> text "," <>
(foldr (<>) empty . map text . intersperse ",") xs
tails :: Maybe ExecTrace
tails =
if any null (fmap (tail.snd) trigs)
then Nothing
else Just
ExecTrace
{ interpTriggers = map (fmap tail) trigs
, interpObservers = []
}
Copied from pretty - ncols because of incompatibility with newer GHC versions .
asColumns :: [[Doc]] -> Doc
asColumns = flip asColumnsWithBuff $ 1
asColumnsWithBuff :: [[Doc]] -> Int -> Doc
asColumnsWithBuff lls q = normalize
where normalize = vcat $ map hsep
$ map (\x -> pad (length x) longColumnLen empty x)
$ pad' longEntryLen q
longColumnLen = maximum (map length lls)
longEntryLen = maximum $ map docLen (concat lls)
docLen d = length $ render d
pad :: Int -> Int -> a -> [a] -> [a]
pad lx max b ls = ls ++ replicate (max - lx) b
-> [[Doc]]
pad' _ _ [] = []
pad' mx q (ls:xs) = map buf ls : pad' mx q xs
where buf x = x <> (hcat $ replicate q space) <> (hcat $ replicate (mx - (docLen x)) space)
|
ad16747187bc21ccf9a7612488b41d6d1e366533dace80d94360eb2fe564a596 | JHU-PL-Lab/jaylang | toChurch02.ml |
let rec bot _ = bot ()
let fail _ = assert false
let rec c10_COEFFICIENT_1129 = 0
let rec c9_COEFFICIENT_1128 = 0
let rec c8_COEFFICIENT_1127 = 0
let rec c7_COEFFICIENT_1125 = 0
let rec c6_COEFFICIENT_1124 = 0
let rec c5_COEFFICIENT_1123 = 0
let rec c4_COEFFICIENT_1122 = 0
let rec c3_COEFFICIENT_1121 = 0
let rec c2_COEFFICIENT_1120 = 0
let rec c1_COEFFICIENT_1117 = 0
let rec c0_COEFFICIENT_1116 = 0
let compose_1030 x_DO_NOT_CARE_1445 x_DO_NOT_CARE_1446 f_EXPARAM_1133 x_DO_NOT_CARE_1443 x_DO_NOT_CARE_1444 f_1031 x_DO_NOT_CARE_1441 x_DO_NOT_CARE_1442 g_EXPARAM_1134 x_DO_NOT_CARE_1439 x_DO_NOT_CARE_1440 g_1032 set_flag_succ_1296 s_succ_x_1293 x_1033 =
f_1031 set_flag_succ_1296 s_succ_x_1293
(g_1032 set_flag_succ_1296 s_succ_x_1293 x_1033)
let id_1034 set_flag_succ_1296 s_succ_x_1293 x_1035 = x_1035
let succ_without_checking_1316 set_flag_succ_1296 s_succ_x_1293 x_1037 =
let set_flag_succ_1296 = true
in
let s_succ_x_1293 = x_1037
in
x_1037 + 1
let rec succ_1036 prev_set_flag_succ_1295 s_prev_succ_x_1294 x_1037 =
let u = if prev_set_flag_succ_1295 then
let u_8154 = fail ()
in
bot()
else () in
succ_without_checking_1316 prev_set_flag_succ_1295
s_prev_succ_x_1294 x_1037
let rec toChurch_1038 x_DO_NOT_CARE_1437 x_DO_NOT_CARE_1438 n_1039 x_DO_NOT_CARE_1435 x_DO_NOT_CARE_1436 f_EXPARAM_1119 set_flag_succ_1296 s_succ_x_1293 f_1040 =
if n_1039 = 0 then
id_1034
else
compose_1030 set_flag_succ_1296 s_succ_x_1293
((c2_COEFFICIENT_1120 * f_EXPARAM_1119) +
((c3_COEFFICIENT_1121 * n_1039) + c4_COEFFICIENT_1122))
set_flag_succ_1296 s_succ_x_1293 f_1040 set_flag_succ_1296
s_succ_x_1293
((c8_COEFFICIENT_1127 * f_EXPARAM_1119) +
((c9_COEFFICIENT_1128 * n_1039) + c10_COEFFICIENT_1129))
set_flag_succ_1296 s_succ_x_1293
(toChurch_1038 set_flag_succ_1296 s_succ_x_1293 (n_1039 - 1)
set_flag_succ_1296 s_succ_x_1293
((c5_COEFFICIENT_1123 * f_EXPARAM_1119) +
((c6_COEFFICIENT_1124 * n_1039) + c7_COEFFICIENT_1125))
set_flag_succ_1296 s_succ_x_1293 f_1040)
let main_1041 x_1043 =
let set_flag_succ_1296 = false in
let s_succ_x_1293 = 0 in
if x_1043 >= 0 then
let tos_1044 =
toChurch_1038 set_flag_succ_1296 s_succ_x_1293 x_1043
set_flag_succ_1296 s_succ_x_1293
((c0_COEFFICIENT_1116 * x_1043) + c1_COEFFICIENT_1117)
set_flag_succ_1296 s_succ_x_1293 succ_1036
in
()
else
()
| null | https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/484b3876986a515fb57b11768a1b3b50418cde0c/benchmark/cases/mochi_origin/termination/toChurch02.ml | ocaml |
let rec bot _ = bot ()
let fail _ = assert false
let rec c10_COEFFICIENT_1129 = 0
let rec c9_COEFFICIENT_1128 = 0
let rec c8_COEFFICIENT_1127 = 0
let rec c7_COEFFICIENT_1125 = 0
let rec c6_COEFFICIENT_1124 = 0
let rec c5_COEFFICIENT_1123 = 0
let rec c4_COEFFICIENT_1122 = 0
let rec c3_COEFFICIENT_1121 = 0
let rec c2_COEFFICIENT_1120 = 0
let rec c1_COEFFICIENT_1117 = 0
let rec c0_COEFFICIENT_1116 = 0
let compose_1030 x_DO_NOT_CARE_1445 x_DO_NOT_CARE_1446 f_EXPARAM_1133 x_DO_NOT_CARE_1443 x_DO_NOT_CARE_1444 f_1031 x_DO_NOT_CARE_1441 x_DO_NOT_CARE_1442 g_EXPARAM_1134 x_DO_NOT_CARE_1439 x_DO_NOT_CARE_1440 g_1032 set_flag_succ_1296 s_succ_x_1293 x_1033 =
f_1031 set_flag_succ_1296 s_succ_x_1293
(g_1032 set_flag_succ_1296 s_succ_x_1293 x_1033)
let id_1034 set_flag_succ_1296 s_succ_x_1293 x_1035 = x_1035
let succ_without_checking_1316 set_flag_succ_1296 s_succ_x_1293 x_1037 =
let set_flag_succ_1296 = true
in
let s_succ_x_1293 = x_1037
in
x_1037 + 1
let rec succ_1036 prev_set_flag_succ_1295 s_prev_succ_x_1294 x_1037 =
let u = if prev_set_flag_succ_1295 then
let u_8154 = fail ()
in
bot()
else () in
succ_without_checking_1316 prev_set_flag_succ_1295
s_prev_succ_x_1294 x_1037
let rec toChurch_1038 x_DO_NOT_CARE_1437 x_DO_NOT_CARE_1438 n_1039 x_DO_NOT_CARE_1435 x_DO_NOT_CARE_1436 f_EXPARAM_1119 set_flag_succ_1296 s_succ_x_1293 f_1040 =
if n_1039 = 0 then
id_1034
else
compose_1030 set_flag_succ_1296 s_succ_x_1293
((c2_COEFFICIENT_1120 * f_EXPARAM_1119) +
((c3_COEFFICIENT_1121 * n_1039) + c4_COEFFICIENT_1122))
set_flag_succ_1296 s_succ_x_1293 f_1040 set_flag_succ_1296
s_succ_x_1293
((c8_COEFFICIENT_1127 * f_EXPARAM_1119) +
((c9_COEFFICIENT_1128 * n_1039) + c10_COEFFICIENT_1129))
set_flag_succ_1296 s_succ_x_1293
(toChurch_1038 set_flag_succ_1296 s_succ_x_1293 (n_1039 - 1)
set_flag_succ_1296 s_succ_x_1293
((c5_COEFFICIENT_1123 * f_EXPARAM_1119) +
((c6_COEFFICIENT_1124 * n_1039) + c7_COEFFICIENT_1125))
set_flag_succ_1296 s_succ_x_1293 f_1040)
let main_1041 x_1043 =
let set_flag_succ_1296 = false in
let s_succ_x_1293 = 0 in
if x_1043 >= 0 then
let tos_1044 =
toChurch_1038 set_flag_succ_1296 s_succ_x_1293 x_1043
set_flag_succ_1296 s_succ_x_1293
((c0_COEFFICIENT_1116 * x_1043) + c1_COEFFICIENT_1117)
set_flag_succ_1296 s_succ_x_1293 succ_1036
in
()
else
()
| |
aa9effcbefb19ab345c63e0d8ecf64fb098e95336cf403cb6a621420c018a446 | Decentralized-Pictures/T4L3NT | test_lwt_addition_output.ml | let _ =
Tezos_time_measurement_runtime.Default.Time_measurement.duration_lwt
("addition", [])
(fun () -> Lwt.return (1 + 3))
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/lib_time_measurement/ppx/test/valid/test_lwt_addition_output.ml | ocaml | let _ =
Tezos_time_measurement_runtime.Default.Time_measurement.duration_lwt
("addition", [])
(fun () -> Lwt.return (1 + 3))
| |
e8d2ab0b67b6d6c24827ccacd63b81c6e71ea3a7ca639fab6df2838ef73faa34 | NixOS/cabal2nix | Builder.hs | {-# LANGUAGE BangPatterns #-}
{- |
Maintainer:
Stability: provisional
Portability: portable
-}
module Distribution.Hackage.DB.Builder
( readTarball, parseTarball
, Builder(..)
)
where
import Distribution.Hackage.DB.Errors
import Distribution.Hackage.DB.Utility
import Codec.Archive.Tar as Tar
import Codec.Archive.Tar.Entry as Tar
import Control.Monad.Catch
import qualified Data.ByteString.Lazy as BSL
import Distribution.Types.PackageName
import Distribution.Types.Version
import System.FilePath
readTarball :: FilePath -> IO (Entries FormatError)
readTarball = fmap Tar.read . BSL.readFile
data Builder m a = Builder
{ insertPreferredVersions :: PackageName -> EpochTime -> BSL.ByteString -> a -> m a
, insertCabalFile :: PackageName -> Version -> EpochTime -> BSL.ByteString -> a -> m a
, insertMetaFile :: PackageName -> Version -> EpochTime -> BSL.ByteString -> a -> m a
}
# INLINABLE parseTarball #
parseTarball :: MonadThrow m => Builder m a -> Maybe EpochTime -> Entries FormatError -> a -> m a
parseTarball b (Just et) (Next e es) !db = if entryTime e > et then return db else insertEntry b e db >>= parseTarball b (Just et) es
parseTarball b Nothing (Next e es) !db = insertEntry b e db >>= parseTarball b Nothing es
parseTarball _ _ (Fail err) _ = throwM err
parseTarball _ _ Done !db = return db
# INLINABLE insertEntry #
insertEntry :: MonadThrow m => Builder m a -> Entry -> a -> m a
insertEntry b e db =
case (splitDirectories (entryPath e), entryContent e) of
([pn,"preferred-versions"], NormalFile buf _) -> insertPreferredVersions b (mkPackageName pn) (entryTime e) buf db
([pn,v,file], NormalFile buf _)
| takeExtension file == ".cabal" -> insertCabalFile b (mkPackageName pn) (parseText "Version" v) (entryTime e) buf db
| takeExtension file == ".json" -> insertMetaFile b (mkPackageName pn) (parseText "Version" v) (entryTime e) buf db
_ -> throwM (UnsupportedTarEntry e)
| null | https://raw.githubusercontent.com/NixOS/cabal2nix/0d1a5a7d227683e9d099665f645a8618ec48ef94/hackage-db/src/Distribution/Hackage/DB/Builder.hs | haskell | # LANGUAGE BangPatterns #
|
Maintainer:
Stability: provisional
Portability: portable
|
module Distribution.Hackage.DB.Builder
( readTarball, parseTarball
, Builder(..)
)
where
import Distribution.Hackage.DB.Errors
import Distribution.Hackage.DB.Utility
import Codec.Archive.Tar as Tar
import Codec.Archive.Tar.Entry as Tar
import Control.Monad.Catch
import qualified Data.ByteString.Lazy as BSL
import Distribution.Types.PackageName
import Distribution.Types.Version
import System.FilePath
readTarball :: FilePath -> IO (Entries FormatError)
readTarball = fmap Tar.read . BSL.readFile
data Builder m a = Builder
{ insertPreferredVersions :: PackageName -> EpochTime -> BSL.ByteString -> a -> m a
, insertCabalFile :: PackageName -> Version -> EpochTime -> BSL.ByteString -> a -> m a
, insertMetaFile :: PackageName -> Version -> EpochTime -> BSL.ByteString -> a -> m a
}
# INLINABLE parseTarball #
parseTarball :: MonadThrow m => Builder m a -> Maybe EpochTime -> Entries FormatError -> a -> m a
parseTarball b (Just et) (Next e es) !db = if entryTime e > et then return db else insertEntry b e db >>= parseTarball b (Just et) es
parseTarball b Nothing (Next e es) !db = insertEntry b e db >>= parseTarball b Nothing es
parseTarball _ _ (Fail err) _ = throwM err
parseTarball _ _ Done !db = return db
# INLINABLE insertEntry #
insertEntry :: MonadThrow m => Builder m a -> Entry -> a -> m a
insertEntry b e db =
case (splitDirectories (entryPath e), entryContent e) of
([pn,"preferred-versions"], NormalFile buf _) -> insertPreferredVersions b (mkPackageName pn) (entryTime e) buf db
([pn,v,file], NormalFile buf _)
| takeExtension file == ".cabal" -> insertCabalFile b (mkPackageName pn) (parseText "Version" v) (entryTime e) buf db
| takeExtension file == ".json" -> insertMetaFile b (mkPackageName pn) (parseText "Version" v) (entryTime e) buf db
_ -> throwM (UnsupportedTarEntry e)
|
73465010045c981bbb0f28f150c1f03215dd2deda1d392eefe90ba713d5dcd11 | OCamlPro/ocp-build | a.ml | (**************************************************************************)
(* *)
(* OCamlPro TypeRex *)
(* *)
Copyright OCamlPro 2011 - 2016 . All rights reserved .
(* This file is distributed under the terms of the GPL v3.0 *)
( GNU Public Licence version 3.0 ) .
(* *)
(* Contact: <> (/) *)
(* *)
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. *)
(**************************************************************************)
let x = 1
open B
| null | https://raw.githubusercontent.com/OCamlPro/ocp-build/56aff560bb438c12b2929feaf8379bc6f31b9840/tests/ocp-build/cycle/a.ml | ocaml | ************************************************************************
OCamlPro TypeRex
This file is distributed under the terms of the GPL v3.0
Contact: <> (/)
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
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.
************************************************************************ | Copyright OCamlPro 2011 - 2016 . All rights reserved .
( GNU Public Licence version 3.0 ) .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
let x = 1
open B
|
ac12f24302e957d9e8fb7a22b2f55ddbc20c2cbd17c7f17a7bd0798bf4ca5c54 | Glue42/glue-core-gateways | common.cljs | (ns gateway.cljs.common
(:require [gateway.node :as node]
[gateway.common.utilities :as util]
[taoensso.timbre :as timbre]
[clojure.string :as string]))
(defn now [] (.getTime (js/Date.)))
(defn- valid-message? [message] true)
(defn- transform-incoming [message]
(let [message (util/keywordize message)]
(if-let [type (:type message)]
(assoc message :type (keyword type))
message)))
(defn process-message
[message clients node key]
(if (valid-message? message)
(let [t (transform-incoming message)]
(if-let [source (get-in @clients [key :source])]
(do
(when-not (= :ping (:type t))
(node/message node
{:origin :local
:source source
:body t}))
(let [n (now)]
(swap! clients (fn [p] (assoc-in p [key :last-access] n)))))
(timbre/warn "Cannot process message for not-registered key" key)))
(timbre/warn "Ignoring invalid message " message)))
(defn- cleanup!
[source node]
(util/close-and-flush! (:channel source))
(try
(node/remove-source node source)
(catch js/Error ex (timbre/error ex "Unable to remove client for" key))))
(defn remove-client!
[clients node key]
(timbre/info "removing client for" key)
(let [[o _] (swap-vals! clients dissoc key)]
(when-let [source (get-in o [key :source])]
(cleanup! source node))))
(defn add-client!
[clients node key source]
(let [n (now)]
(swap! clients assoc key {:source source
:last-access n}))
(node/add-source node source))
(defn older-clients
[f older-than clients]
(into {} (f (fn [[_ v]] (< (:last-access v) older-than)) clients)))
(defn scavenge-clients!
[clients node older-than]
(timbre/debug "running client scavenger. collecting everything older than" older-than)
(let [[o _] (swap-vals! clients (partial older-clients remove older-than))
to-remove (older-clients filter older-than o)]
(doseq [[key v] to-remove
:let [source (:source v)]]
(timbre/info "scavenging client for" key)
(cleanup! source node))))
(defn regexify [v]
(if (and (string? v)
(string/starts-with? v "#")
(pos? (count v)))
(re-pattern (subs v 1))
v))
| null | https://raw.githubusercontent.com/Glue42/glue-core-gateways/f334ad9a043f5185dc5ee5f342a8c1b2cf1c1554/packages/common/src/gateway/cljs/common.cljs | clojure | (ns gateway.cljs.common
(:require [gateway.node :as node]
[gateway.common.utilities :as util]
[taoensso.timbre :as timbre]
[clojure.string :as string]))
(defn now [] (.getTime (js/Date.)))
(defn- valid-message? [message] true)
(defn- transform-incoming [message]
(let [message (util/keywordize message)]
(if-let [type (:type message)]
(assoc message :type (keyword type))
message)))
(defn process-message
[message clients node key]
(if (valid-message? message)
(let [t (transform-incoming message)]
(if-let [source (get-in @clients [key :source])]
(do
(when-not (= :ping (:type t))
(node/message node
{:origin :local
:source source
:body t}))
(let [n (now)]
(swap! clients (fn [p] (assoc-in p [key :last-access] n)))))
(timbre/warn "Cannot process message for not-registered key" key)))
(timbre/warn "Ignoring invalid message " message)))
(defn- cleanup!
[source node]
(util/close-and-flush! (:channel source))
(try
(node/remove-source node source)
(catch js/Error ex (timbre/error ex "Unable to remove client for" key))))
(defn remove-client!
[clients node key]
(timbre/info "removing client for" key)
(let [[o _] (swap-vals! clients dissoc key)]
(when-let [source (get-in o [key :source])]
(cleanup! source node))))
(defn add-client!
[clients node key source]
(let [n (now)]
(swap! clients assoc key {:source source
:last-access n}))
(node/add-source node source))
(defn older-clients
[f older-than clients]
(into {} (f (fn [[_ v]] (< (:last-access v) older-than)) clients)))
(defn scavenge-clients!
[clients node older-than]
(timbre/debug "running client scavenger. collecting everything older than" older-than)
(let [[o _] (swap-vals! clients (partial older-clients remove older-than))
to-remove (older-clients filter older-than o)]
(doseq [[key v] to-remove
:let [source (:source v)]]
(timbre/info "scavenging client for" key)
(cleanup! source node))))
(defn regexify [v]
(if (and (string? v)
(string/starts-with? v "#")
(pos? (count v)))
(re-pattern (subs v 1))
v))
| |
4bcd4339af7426ff9ebaf5d59a4f2df67dee1732aa165f107d6d5943b7c45ee2 | arttuka/reagent-material-ui | desktop_windows.cljs | (ns reagent-mui.icons.desktop-windows
"Imports @mui/icons-material/DesktopWindows 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 desktop-windows (create-svg-icon (e "path" #js {"d" "M20 3H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h6v2H8v2h8v-2h-2v-2h6c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2"})
"DesktopWindows"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/desktop_windows.cljs | clojure | (ns reagent-mui.icons.desktop-windows
"Imports @mui/icons-material/DesktopWindows 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 desktop-windows (create-svg-icon (e "path" #js {"d" "M20 3H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h6v2H8v2h8v-2h-2v-2h6c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2"})
"DesktopWindows"))
| |
85ec5fd0432c7f1a75afff04ab2c0dbe08ab8307634913afc328f7ba05e57508 | bbusching/libgit2 | refspec.rkt | #lang racket
(require ffi/unsafe
"define.rkt"
"types.rkt"
"net.rkt"
"buffer.rkt"
"utils.rkt")
(provide (all-defined-out))
(define-libgit2 git_refspec_direction
(_fun _refspec -> _git_direction))
(define-libgit2 git_refspec_dst
(_fun _refspec -> _string))
(define-libgit2 git_refspec_dst_matches
(_fun _refspec _string -> _bool))
(define-libgit2 git_refspec_force
(_fun _refspec -> _bool))
(define-libgit2/check git_refspec_transform
(_fun _buf _refspec _string -> _int))
(define-libgit2 git_refspec_src
(_fun _refspec -> _string))
(define-libgit2 git_refspec_src_matches
(_fun _refspec _string -> _bool))
(define-libgit2 git_refspec_string
(_fun _refspec -> _string))
(define-libgit2/check git_refspec_rtransform
(_fun _buf _refspec _string -> _int))
| null | https://raw.githubusercontent.com/bbusching/libgit2/6d6a007543900eb7a6fbbeba55850288665bdde5/libgit2/include/refspec.rkt | racket | #lang racket
(require ffi/unsafe
"define.rkt"
"types.rkt"
"net.rkt"
"buffer.rkt"
"utils.rkt")
(provide (all-defined-out))
(define-libgit2 git_refspec_direction
(_fun _refspec -> _git_direction))
(define-libgit2 git_refspec_dst
(_fun _refspec -> _string))
(define-libgit2 git_refspec_dst_matches
(_fun _refspec _string -> _bool))
(define-libgit2 git_refspec_force
(_fun _refspec -> _bool))
(define-libgit2/check git_refspec_transform
(_fun _buf _refspec _string -> _int))
(define-libgit2 git_refspec_src
(_fun _refspec -> _string))
(define-libgit2 git_refspec_src_matches
(_fun _refspec _string -> _bool))
(define-libgit2 git_refspec_string
(_fun _refspec -> _string))
(define-libgit2/check git_refspec_rtransform
(_fun _buf _refspec _string -> _int))
| |
35ebd03341a578c3e9d82f0604a795626deafd4a800c24bf0442c1da10448e13 | mkremins/starfreighter | app.cljs | (ns starfreighter.app
(:refer-clojure :exclude [rand rand-int rand-nth shuffle])
(:require [clojure.string :as str]
[om.core :as om]
[om-tools.core :refer-macros [defcomponent]]
[om-tools.dom :as dom]
[starfreighter.db :as db]
[starfreighter.desc :as desc]
[starfreighter.game :as game]
[starfreighter.util :as util]))
(enable-console-print!)
(defonce app-state
(atom (game/restart-game)))
(defcomponent info-link [data owner]
(render [_]
(let [linked (cond->> data (sequential? data) (get-in @app-state))]
(dom/a {:class "info-link"
:on-click #(do (.stopPropagation %)
(om/update! (om/root-cursor app-state) :info-target linked))}
(:name linked)))))
(defcomponent content-span [data owner]
(render [_]
(if (sequential? data)
(case (first data)
:cash
(let [amount (second data)]
(dom/span {:class (str "cash-value " (if (neg? amount) "neg" "pos"))}
(js/Math.abs (second data))))
:subject
(dom/strong (om/build-all content-span (rest data)))
:link
(om/build info-link (second data))
;else
(dom/span (om/build-all content-span data)))
(dom/span data))))
(defcomponent card-view [data owner]
(render [_]
(dom/div {:class "card"}
(let [speaker (:speaker data)
role (some-> speaker :role name)]
(dom/span {:class (str "speaker " role)}
(if role (om/build info-link speaker) (:name speaker))))
" "
(om/build content-span (:text data))
(when (= (:type data) :game-over)
(dom/p {:class "game-over"} "[Game Over]")))))
(defcomponent choice-buttons [data owner]
(render [_]
(dom/div {:class "choices"}
(for [choice (:choices (:card data))]
(dom/div {:class "choice"
:style {:background (:background choice)}
:on-click (fn [ev]
(.stopPropagation ev)
(om/transact! data #(game/handle-choice % (:effects choice))))}
(:icon choice))))))
(defn mood->icon [mood]
(util/bucket mood [[20 "😡"] [40 "😒"] [60 "😐"] [80 "🙂"] [100 "😃"]]))
(def trait->icon
{:fighter "👊"
:medic "💊"
:mechanic "🔧"
:unconscious "😵"
:injured "🤕"
:sick "🤒"})
(defcomponent status-bar [data owner]
(render [_]
(dom/div {:class "status-bar"}
(dom/span {:class "status cash"} (:cash data))
(dom/span {:class "status ship"} (:ship data))
(dom/span {:class "status mood"} (mood->icon (db/avg-crew-mood data)))
(dom/span {:class (str "status here " (name (:stage (:travel data))))}
(om/build info-link
(if (db/in-transit? data)
(db/current-dest data)
(db/current-place data))))
(dom/span {:class "status time"} (:turn data)))))
(defcomponent slot-details [data owner]
(render [_]
(dom/span {:class "details"}
(let [traits (:traits data)
mood (when (= (:type data) :char) (mood->icon (db/calc-mood data)))
dest (:destination data)
cash (or (:pay-after data) (:price data))]
(dom/span {}
(dom/span {:class "mood"} mood)
(dom/span {:class "traits"} (str/join (map trait->icon traits)))
(when dest
(dom/span {:class "dest"}
(when (or mood traits) " ")
(dom/span {:class "dest-icon"} "➡️ ")
(om/build info-link [:places dest])))
(when cash
(dom/span {:class "pay"}
(when (or mood traits dest) " ")
(dom/span {:class "pay-icon"} "💰")
cash))
" ")))))
(defcomponent slot [data owner]
(render [_]
(dom/p {:class "slot crew"}
(if data
(dom/span {} (om/build info-link data))
" ")
(om/build slot-details data))))
(defcomponent crew-list [data owner]
(render [_]
(dom/div {:class "list crew"}
(dom/h2 "Crew")
(let [crew (vec (db/crew data))]
(dom/div {}
(for [i (range (:max-crew data))]
(om/build slot (get crew i))))))))
(defcomponent cargo-list [data owner]
(render [_]
(dom/div {:class "list cargo"}
(dom/h2 "Cargo")
(dom/div {}
(for [i (range (:max-cargo data))]
(om/build slot (get (:cargo data) i)))))))
;;; map rendering stuff
(def ^:private map-colors ["lightcoral" "gold" "darkseagreen" "cadetblue" "mediumpurple" "lightsalmon"])
(def ^:private map-size 480)
(defcomponent starmap [data owner]
(render [_]
(let [{:keys [info-target places]} data
location (:name (db/current-place data))
destination (:name (db/current-dest data))
target-place (when (= (:type info-target) :place) info-target)
set-target! (fn [target]
#(do (.stopPropagation %)
(om/update! data :info-target target)))]
(dom/svg
{:class "starmap"
:xmlns ""
:width map-size :height map-size
:viewBox (str "0 0 " map-size " " map-size)}
;; draw connections
(let [target-path (some->> target-place (db/pathfind data) set)
travel-ends [(or location (:from (:travel data))) destination]
connections (->> (vals places)
(mapcat (fn [{:keys [name connections]}]
(map #(-> [name %]) connections)))
(util/distinct-by set))]
(dom/g {:class "connections"}
(for [[end1 end2 :as conn-ends] connections
:let [here? (= (set conn-ends) (set travel-ends))
ends (if here? travel-ends conn-ends)
target? (every? (partial contains? target-path) ends)
[p1 p2] (map places ends)]]
(dom/line
{:class (cond here? "travel" target? "target")
:x1 (:x p1) :y1 (:y p1) :x2 (:x p2) :y2 (:y p2)}))))
;; draw places
(let [culture-ids (distinct (map :culture (vals places)))
culture-colors (zipmap culture-ids map-colors)
job-dests (set (map :destination (:cargo data)))]
(dom/g {:class "places"}
(for [{:keys [x y name] :as place} (vals places)
:let [color (get culture-colors (:culture place))
dest? (= name destination)
here? (= name location)
travel? (or dest? here?
(#{(:from (:travel data)) (:to (:travel data))} name))
job? (contains? job-dests name)
target? (= name (:name target-place))
radius (if (:hub? place) 16 10)]]
(dom/g {:class (cond-> "map-location" travel? (str " travel") target? (str " target"))}
(dom/circle
{:cx x :cy y :r radius :fill color
:on-click (set-target! place)})
(dom/text
{:x x :y (- y (+ radius 4))
:text-anchor "middle" :font-size 12
:on-click (set-target! place)}
(dom/tspan (cond here? "📍" dest? "➡️ " job? "🚩"))
(dom/tspan name))))))
;; draw button to depart for target (if any)
(when (some-> target-place :name (not= location))
(let [enabled? (and (db/in-port? data) (game/interruptible? (:card data)))]
(dom/text {:class (cond-> "depart-button" (not enabled?) (str " disabled"))
:x 468 :y 462 :text-anchor "end" :font-size 18
:on-click (if enabled?
#(do (.stopPropagation %)
(om/transact! data game/prepare-to-depart))
#(.stopPropagation %))}
(str "➡️ " (:name target-place)))))))))
(defcomponent info-box [data owner]
(render [_]
(when-let [target (or (:info-target data)
(db/current-place data)
(db/current-dest data))]
(dom/div {:class "info-box"}
(for [paragraph (desc/describe target)]
(dom/p (om/build-all content-span paragraph)))))))
(defcomponent app [data owner]
(render [_]
(dom/div {:class "app"
;; clicking anywhere *except* on an info link should reset :info-target
:on-click #(do (.stopPropagation %)
(om/update! data :info-target nil))}
(dom/div {:class "left"}
(om/build status-bar data)
(om/build card-view (:card data))
(om/build choice-buttons data)
(dom/div {:class "lists"}
(om/build crew-list data)
(om/build cargo-list data)))
(dom/div {:class "right"}
(om/build starmap data)
(om/build info-box data)))))
(defn init! []
(om/root app app-state {:target (js/document.getElementById "app")}))
(init!)
| null | https://raw.githubusercontent.com/mkremins/starfreighter/2be40b4aa5f288bb9829a2e1362a7bfc1e7f12dc/src/starfreighter/app.cljs | clojure | else
map rendering stuff
draw connections
draw places
draw button to depart for target (if any)
clicking anywhere *except* on an info link should reset :info-target | (ns starfreighter.app
(:refer-clojure :exclude [rand rand-int rand-nth shuffle])
(:require [clojure.string :as str]
[om.core :as om]
[om-tools.core :refer-macros [defcomponent]]
[om-tools.dom :as dom]
[starfreighter.db :as db]
[starfreighter.desc :as desc]
[starfreighter.game :as game]
[starfreighter.util :as util]))
(enable-console-print!)
(defonce app-state
(atom (game/restart-game)))
(defcomponent info-link [data owner]
(render [_]
(let [linked (cond->> data (sequential? data) (get-in @app-state))]
(dom/a {:class "info-link"
:on-click #(do (.stopPropagation %)
(om/update! (om/root-cursor app-state) :info-target linked))}
(:name linked)))))
(defcomponent content-span [data owner]
(render [_]
(if (sequential? data)
(case (first data)
:cash
(let [amount (second data)]
(dom/span {:class (str "cash-value " (if (neg? amount) "neg" "pos"))}
(js/Math.abs (second data))))
:subject
(dom/strong (om/build-all content-span (rest data)))
:link
(om/build info-link (second data))
(dom/span (om/build-all content-span data)))
(dom/span data))))
(defcomponent card-view [data owner]
(render [_]
(dom/div {:class "card"}
(let [speaker (:speaker data)
role (some-> speaker :role name)]
(dom/span {:class (str "speaker " role)}
(if role (om/build info-link speaker) (:name speaker))))
" "
(om/build content-span (:text data))
(when (= (:type data) :game-over)
(dom/p {:class "game-over"} "[Game Over]")))))
(defcomponent choice-buttons [data owner]
(render [_]
(dom/div {:class "choices"}
(for [choice (:choices (:card data))]
(dom/div {:class "choice"
:style {:background (:background choice)}
:on-click (fn [ev]
(.stopPropagation ev)
(om/transact! data #(game/handle-choice % (:effects choice))))}
(:icon choice))))))
(defn mood->icon [mood]
(util/bucket mood [[20 "😡"] [40 "😒"] [60 "😐"] [80 "🙂"] [100 "😃"]]))
(def trait->icon
{:fighter "👊"
:medic "💊"
:mechanic "🔧"
:unconscious "😵"
:injured "🤕"
:sick "🤒"})
(defcomponent status-bar [data owner]
(render [_]
(dom/div {:class "status-bar"}
(dom/span {:class "status cash"} (:cash data))
(dom/span {:class "status ship"} (:ship data))
(dom/span {:class "status mood"} (mood->icon (db/avg-crew-mood data)))
(dom/span {:class (str "status here " (name (:stage (:travel data))))}
(om/build info-link
(if (db/in-transit? data)
(db/current-dest data)
(db/current-place data))))
(dom/span {:class "status time"} (:turn data)))))
(defcomponent slot-details [data owner]
(render [_]
(dom/span {:class "details"}
(let [traits (:traits data)
mood (when (= (:type data) :char) (mood->icon (db/calc-mood data)))
dest (:destination data)
cash (or (:pay-after data) (:price data))]
(dom/span {}
(dom/span {:class "mood"} mood)
(dom/span {:class "traits"} (str/join (map trait->icon traits)))
(when dest
(dom/span {:class "dest"}
(when (or mood traits) " ")
(dom/span {:class "dest-icon"} "➡️ ")
(om/build info-link [:places dest])))
(when cash
(dom/span {:class "pay"}
(when (or mood traits dest) " ")
(dom/span {:class "pay-icon"} "💰")
cash))
" ")))))
(defcomponent slot [data owner]
(render [_]
(dom/p {:class "slot crew"}
(if data
(dom/span {} (om/build info-link data))
" ")
(om/build slot-details data))))
(defcomponent crew-list [data owner]
(render [_]
(dom/div {:class "list crew"}
(dom/h2 "Crew")
(let [crew (vec (db/crew data))]
(dom/div {}
(for [i (range (:max-crew data))]
(om/build slot (get crew i))))))))
(defcomponent cargo-list [data owner]
(render [_]
(dom/div {:class "list cargo"}
(dom/h2 "Cargo")
(dom/div {}
(for [i (range (:max-cargo data))]
(om/build slot (get (:cargo data) i)))))))
(def ^:private map-colors ["lightcoral" "gold" "darkseagreen" "cadetblue" "mediumpurple" "lightsalmon"])
(def ^:private map-size 480)
(defcomponent starmap [data owner]
(render [_]
(let [{:keys [info-target places]} data
location (:name (db/current-place data))
destination (:name (db/current-dest data))
target-place (when (= (:type info-target) :place) info-target)
set-target! (fn [target]
#(do (.stopPropagation %)
(om/update! data :info-target target)))]
(dom/svg
{:class "starmap"
:xmlns ""
:width map-size :height map-size
:viewBox (str "0 0 " map-size " " map-size)}
(let [target-path (some->> target-place (db/pathfind data) set)
travel-ends [(or location (:from (:travel data))) destination]
connections (->> (vals places)
(mapcat (fn [{:keys [name connections]}]
(map #(-> [name %]) connections)))
(util/distinct-by set))]
(dom/g {:class "connections"}
(for [[end1 end2 :as conn-ends] connections
:let [here? (= (set conn-ends) (set travel-ends))
ends (if here? travel-ends conn-ends)
target? (every? (partial contains? target-path) ends)
[p1 p2] (map places ends)]]
(dom/line
{:class (cond here? "travel" target? "target")
:x1 (:x p1) :y1 (:y p1) :x2 (:x p2) :y2 (:y p2)}))))
(let [culture-ids (distinct (map :culture (vals places)))
culture-colors (zipmap culture-ids map-colors)
job-dests (set (map :destination (:cargo data)))]
(dom/g {:class "places"}
(for [{:keys [x y name] :as place} (vals places)
:let [color (get culture-colors (:culture place))
dest? (= name destination)
here? (= name location)
travel? (or dest? here?
(#{(:from (:travel data)) (:to (:travel data))} name))
job? (contains? job-dests name)
target? (= name (:name target-place))
radius (if (:hub? place) 16 10)]]
(dom/g {:class (cond-> "map-location" travel? (str " travel") target? (str " target"))}
(dom/circle
{:cx x :cy y :r radius :fill color
:on-click (set-target! place)})
(dom/text
{:x x :y (- y (+ radius 4))
:text-anchor "middle" :font-size 12
:on-click (set-target! place)}
(dom/tspan (cond here? "📍" dest? "➡️ " job? "🚩"))
(dom/tspan name))))))
(when (some-> target-place :name (not= location))
(let [enabled? (and (db/in-port? data) (game/interruptible? (:card data)))]
(dom/text {:class (cond-> "depart-button" (not enabled?) (str " disabled"))
:x 468 :y 462 :text-anchor "end" :font-size 18
:on-click (if enabled?
#(do (.stopPropagation %)
(om/transact! data game/prepare-to-depart))
#(.stopPropagation %))}
(str "➡️ " (:name target-place)))))))))
(defcomponent info-box [data owner]
(render [_]
(when-let [target (or (:info-target data)
(db/current-place data)
(db/current-dest data))]
(dom/div {:class "info-box"}
(for [paragraph (desc/describe target)]
(dom/p (om/build-all content-span paragraph)))))))
(defcomponent app [data owner]
(render [_]
(dom/div {:class "app"
:on-click #(do (.stopPropagation %)
(om/update! data :info-target nil))}
(dom/div {:class "left"}
(om/build status-bar data)
(om/build card-view (:card data))
(om/build choice-buttons data)
(dom/div {:class "lists"}
(om/build crew-list data)
(om/build cargo-list data)))
(dom/div {:class "right"}
(om/build starmap data)
(om/build info-box data)))))
(defn init! []
(om/root app app-state {:target (js/document.getElementById "app")}))
(init!)
|
5e8cc92d234f8a67569166260e3d8c57cbeeaf79e74879b1f1f78f454aa7a623 | babashka/babashka | jdbc.clj | (ns babashka.impl.jdbc
{:no-doc true}
(:require
[next.jdbc :as njdbc]
[next.jdbc.result-set :as rs]
[next.jdbc.sql :as sql]
[sci.core :as sci]))
(def next-ns (sci/create-ns 'next.jdbc nil))
(defn with-transaction
"Given a transactable object, gets a connection and binds it to `sym`,
then executes the `body` in that context, committing any changes if the body
completes successfully, otherwise rolling back any changes made.
The options map supports:
* `:isolation` -- `:none`, `:read-committed`, `:read-uncommitted`,
`:repeatable-read`, `:serializable`,
* `:read-only` -- `true` / `false`,
* `:rollback-only` -- `true` / `false`."
[_ _ [sym transactable opts] & body]
(let [con (vary-meta sym assoc :tag 'java.sql.Connection)]
`(njdbc/transact ~transactable (^{:once true} fn* [~con] ~@body) ~(or opts {}))))
(def njdbc-namespace
{'get-datasource (sci/copy-var njdbc/get-datasource next-ns)
'execute! (sci/copy-var njdbc/execute! next-ns)
'execute-one! (sci/copy-var njdbc/execute-one! next-ns)
'get-connection (sci/copy-var njdbc/get-connection next-ns)
'plan (sci/copy-var njdbc/plan next-ns)
'prepare (sci/copy-var njdbc/prepare next-ns)
'transact (sci/copy-var njdbc/transact next-ns)
'with-transaction (sci/copy-var with-transaction next-ns)})
(def sns (sci/create-ns 'next.jdbc.sql nil))
(def next-sql-namespace
{'insert-multi! (sci/copy-var sql/insert-multi! sns)})
(def rsns (sci/create-ns 'next.jdbc.result-set nil))
(def result-set-namespace
{'as-maps (sci/copy-var rs/as-maps rsns)
'as-unqualified-maps (sci/copy-var rs/as-unqualified-maps rsns)
'as-modified-maps (sci/copy-var rs/as-modified-maps rsns)
'as-unqualified-modified-maps (sci/copy-var rs/as-unqualified-modified-maps rsns)
'as-lower-maps (sci/copy-var rs/as-lower-maps rsns)
'as-unqualified-lower-maps (sci/copy-var rs/as-unqualified-lower-maps rsns)
'as-maps-adapter (sci/copy-var rs/as-maps-adapter rsns)})
| null | https://raw.githubusercontent.com/babashka/babashka/ee85685334fddda28afee71da85de90312f7e606/feature-jdbc/babashka/impl/jdbc.clj | clojure | (ns babashka.impl.jdbc
{:no-doc true}
(:require
[next.jdbc :as njdbc]
[next.jdbc.result-set :as rs]
[next.jdbc.sql :as sql]
[sci.core :as sci]))
(def next-ns (sci/create-ns 'next.jdbc nil))
(defn with-transaction
"Given a transactable object, gets a connection and binds it to `sym`,
then executes the `body` in that context, committing any changes if the body
completes successfully, otherwise rolling back any changes made.
The options map supports:
* `:isolation` -- `:none`, `:read-committed`, `:read-uncommitted`,
`:repeatable-read`, `:serializable`,
* `:read-only` -- `true` / `false`,
* `:rollback-only` -- `true` / `false`."
[_ _ [sym transactable opts] & body]
(let [con (vary-meta sym assoc :tag 'java.sql.Connection)]
`(njdbc/transact ~transactable (^{:once true} fn* [~con] ~@body) ~(or opts {}))))
(def njdbc-namespace
{'get-datasource (sci/copy-var njdbc/get-datasource next-ns)
'execute! (sci/copy-var njdbc/execute! next-ns)
'execute-one! (sci/copy-var njdbc/execute-one! next-ns)
'get-connection (sci/copy-var njdbc/get-connection next-ns)
'plan (sci/copy-var njdbc/plan next-ns)
'prepare (sci/copy-var njdbc/prepare next-ns)
'transact (sci/copy-var njdbc/transact next-ns)
'with-transaction (sci/copy-var with-transaction next-ns)})
(def sns (sci/create-ns 'next.jdbc.sql nil))
(def next-sql-namespace
{'insert-multi! (sci/copy-var sql/insert-multi! sns)})
(def rsns (sci/create-ns 'next.jdbc.result-set nil))
(def result-set-namespace
{'as-maps (sci/copy-var rs/as-maps rsns)
'as-unqualified-maps (sci/copy-var rs/as-unqualified-maps rsns)
'as-modified-maps (sci/copy-var rs/as-modified-maps rsns)
'as-unqualified-modified-maps (sci/copy-var rs/as-unqualified-modified-maps rsns)
'as-lower-maps (sci/copy-var rs/as-lower-maps rsns)
'as-unqualified-lower-maps (sci/copy-var rs/as-unqualified-lower-maps rsns)
'as-maps-adapter (sci/copy-var rs/as-maps-adapter rsns)})
| |
3508e0795dbdf705e0a9d54729877eccc632f08f006df309df17add8b38a4bd8 | HealthSamurai/stresty | matcho.clj | (ns stresty.matchers.matcho
(:require [clojure.string :as s]
[zen.core :as zen]))
(defn template [conf template]
(s/replace
template
#"\{([a-zA-Z0-9-_\.]+)\}"
#(let [template-segments (-> % second (s/split #"\."))]
(->> template-segments
(mapv keyword)
(get-in conf)
str))))
(def fns
{"2xx?" #(and (>= % 200) (< % 300))
"4xx?" #(and (>= % 400) (< % 500))
"5xx?" #(and (>= % 500) (< % 600))})
(defn- built-in-fn [fn-name]
(if-let [func (ns-resolve 'clojure.core (symbol fn-name))]
#(func %)))
(defmulti predicate (fn [model _] (:zen/name model)))
(defmethod predicate 'sty/string?
[_ x]
(when-not (string? x)
{:expected "string" :but x}))
(defmethod predicate 'sty/distinct?
[_ x]
(when-not (distinct? x)
{:expected "distinct" :but x}))
(defmethod predicate 'sty/number?
[_ x]
(when-not (number? x)
{:expected "number" :but x}))
(defmethod predicate 'sty/integer?
[_ x]
(when-not (integer? x)
{:expected "integer" :but x}))
(defmethod predicate 'sty/ok?
[_ x]
(if-not (integer? x)
{:expected "integer" :but x}
(when-not (and (>= x 200) (< x 300))
{:expected "expected >= 200 and <= 300" :but x})))
(defmethod predicate 'sty/any?
[_ _])
{ " 2xx ? " #
" 4xx ? " # ( and ( > = % 400 ) ( < % 500 ) )
" 5xx ? " # ( and ( > = % 500 ) ( < % 600 ) ) }
(defmethod predicate 'sty/double?
[_ x]
(when-not (double? x)
{:expected "double" :but x}))
(defmethod predicate 'sty/empty?
[_ x]
(when-not (empty? x)
{:expected "empty" :but x}))
(defmethod predicate 'sty/even?
[_ x]
(when-not (even? x)
{:expected "even" :but x}))
(defn- smart-explain-data
([ztx ctx p x]
(smart-explain-data ztx ctx p x {}))
([ztx ctx p x m]
(cond
(and (string? p) (s/starts-with? p "#"))
(smart-explain-data ztx ctx (java.util.regex.Pattern/compile (subs p 1)) x)
(string? p)
(let [p* (template ctx p)]
(when-not (= p* x)
{:expected p* :but x}))
(symbol? p)
(if-let [model (zen/get-symbol ztx p)]
(when-let [error (predicate model x)]
error)
{:syntax (str "Unrecognized symbol " p)})
:else
(when-not (= p x)
{:expected p :but x}))))
(defn- match-recur [ztx ctx errors path x pattern]
(cond
(and (map? x)
(map? pattern))
(reduce (fn [errors [k v]]
(let [path (conj path k)
ev (get x k)]
(match-recur ztx ctx errors path ev v)))
errors pattern)
(and (sequential? pattern)
(sequential? x))
(reduce (fn [errors [k v]]
(let [path (conj path k)
ev (nth (vec x) k nil)]
(match-recur ztx ctx errors path ev v)))
errors
(map (fn [x i] [i x]) pattern (range)))
:else (let [err (smart-explain-data ztx ctx pattern x)]
(if err
(conj errors (assoc err :path path))
errors))))
(defn match
"Match against each pattern"
[ztx ctx x & patterns]
(reduce (fn [acc pattern] (match-recur ztx ctx acc [] x pattern)) [] patterns))
(comment
(def ctx* {:user {:data {:patient_id "pt-1"}}})
(match {:user {:data {:patient_id "new-patient"}}}
{:status 200,
:body
{:id "new-patient",
:resourceType "Patient",
:meta
{:lastUpdated "2020-11-19T10:15:36.124398Z",
:createdAt "2020-11-19T10:15:36.124398Z",
:versionId "483"}}}
{:status 200
:body {:id 'stresty/string?}}
)
)
| null | https://raw.githubusercontent.com/HealthSamurai/stresty/f87f92c05c4813e954ad9fec7901a975384d9704/src/stresty/matchers/matcho.clj | clojure | (ns stresty.matchers.matcho
(:require [clojure.string :as s]
[zen.core :as zen]))
(defn template [conf template]
(s/replace
template
#"\{([a-zA-Z0-9-_\.]+)\}"
#(let [template-segments (-> % second (s/split #"\."))]
(->> template-segments
(mapv keyword)
(get-in conf)
str))))
(def fns
{"2xx?" #(and (>= % 200) (< % 300))
"4xx?" #(and (>= % 400) (< % 500))
"5xx?" #(and (>= % 500) (< % 600))})
(defn- built-in-fn [fn-name]
(if-let [func (ns-resolve 'clojure.core (symbol fn-name))]
#(func %)))
(defmulti predicate (fn [model _] (:zen/name model)))
(defmethod predicate 'sty/string?
[_ x]
(when-not (string? x)
{:expected "string" :but x}))
(defmethod predicate 'sty/distinct?
[_ x]
(when-not (distinct? x)
{:expected "distinct" :but x}))
(defmethod predicate 'sty/number?
[_ x]
(when-not (number? x)
{:expected "number" :but x}))
(defmethod predicate 'sty/integer?
[_ x]
(when-not (integer? x)
{:expected "integer" :but x}))
(defmethod predicate 'sty/ok?
[_ x]
(if-not (integer? x)
{:expected "integer" :but x}
(when-not (and (>= x 200) (< x 300))
{:expected "expected >= 200 and <= 300" :but x})))
(defmethod predicate 'sty/any?
[_ _])
{ " 2xx ? " #
" 4xx ? " # ( and ( > = % 400 ) ( < % 500 ) )
" 5xx ? " # ( and ( > = % 500 ) ( < % 600 ) ) }
(defmethod predicate 'sty/double?
[_ x]
(when-not (double? x)
{:expected "double" :but x}))
(defmethod predicate 'sty/empty?
[_ x]
(when-not (empty? x)
{:expected "empty" :but x}))
(defmethod predicate 'sty/even?
[_ x]
(when-not (even? x)
{:expected "even" :but x}))
(defn- smart-explain-data
([ztx ctx p x]
(smart-explain-data ztx ctx p x {}))
([ztx ctx p x m]
(cond
(and (string? p) (s/starts-with? p "#"))
(smart-explain-data ztx ctx (java.util.regex.Pattern/compile (subs p 1)) x)
(string? p)
(let [p* (template ctx p)]
(when-not (= p* x)
{:expected p* :but x}))
(symbol? p)
(if-let [model (zen/get-symbol ztx p)]
(when-let [error (predicate model x)]
error)
{:syntax (str "Unrecognized symbol " p)})
:else
(when-not (= p x)
{:expected p :but x}))))
(defn- match-recur [ztx ctx errors path x pattern]
(cond
(and (map? x)
(map? pattern))
(reduce (fn [errors [k v]]
(let [path (conj path k)
ev (get x k)]
(match-recur ztx ctx errors path ev v)))
errors pattern)
(and (sequential? pattern)
(sequential? x))
(reduce (fn [errors [k v]]
(let [path (conj path k)
ev (nth (vec x) k nil)]
(match-recur ztx ctx errors path ev v)))
errors
(map (fn [x i] [i x]) pattern (range)))
:else (let [err (smart-explain-data ztx ctx pattern x)]
(if err
(conj errors (assoc err :path path))
errors))))
(defn match
"Match against each pattern"
[ztx ctx x & patterns]
(reduce (fn [acc pattern] (match-recur ztx ctx acc [] x pattern)) [] patterns))
(comment
(def ctx* {:user {:data {:patient_id "pt-1"}}})
(match {:user {:data {:patient_id "new-patient"}}}
{:status 200,
:body
{:id "new-patient",
:resourceType "Patient",
:meta
{:lastUpdated "2020-11-19T10:15:36.124398Z",
:createdAt "2020-11-19T10:15:36.124398Z",
:versionId "483"}}}
{:status 200
:body {:id 'stresty/string?}}
)
)
| |
df42cdaafb3c00cdf5b2ab6c7f845e597607e9ad9ec5356aba2a841a966dcbc6 | kaoskorobase/mescaline | looper.hs | # LANGUAGE ScopedTypeVariables #
import Language.Haskell.Interpreter (InterpreterError(..), GhcError(..))
import Control.Concurrent
import Control.Concurrent.Chan
import Control.Concurrent.MVar
import Control.Monad (unless)
import Control.Monad.Trans (liftIO)
import Data.Accessor
import Data.IORef
import qualified Mescaline.Database.FlatFile as DB
import Mescaline.Database.SourceFile as SourceFile
import Mescaline.Database.Unit as Unit
import Mescaline.Synth.Concat
import qualified Mescaline.Synth.Pattern as P
import Mescaline.Synth.Pattern.Load as P
import qualified Mescaline.Sampler.GUI as GUI
import qualified Mescaline.Sampler.Keyboard as GUI
import qualified Mescaline.Sampler.MIDI as MIDI
import qualified Mescaline.Sampler.Looper as L
import System.Environment (getArgs)
import Control.Exception
import Sound.SC3
import Sound.OpenSoundControl (utcr)
import Sound.OpenSoundControl.Transport
import Sound.OpenSoundControl.Transport.UDP (UDP)
import System.Exit (ExitCode(..), exitWith)
import System.FilePath
import Prelude hiding (catch)
import Graphics.UI.GLUT
playSampler :: Chan (Double, P.Event) -> IO ()
playSampler = bracket newSampler freeSampler . flip runSampler
initialSize :: Int
initialSize = 256
keyChars = [
'z' , 'a' , 'q'
, 'x' , 's' , 'w'
, 'c' , 'd' , 'e'
, 'v' , 'f' , 'r'
, 'b' , 'g' , 't'
, 'n' , 'h' , 'y'
, 'm' , 'j' , 'u'
]
tr505_notes = concat [
[ 43 .. 50 ]
, [ 35 .. 42 ]
]
latency :: Double
latency = 0.015
mkEvent :: Unit.Unit -> P.Event
mkEvent = setVal (P.synth.>P.latency) latency . P.event
midiCallback :: Chan (Double, P.Event) -> [(Int, Unit.Unit)] -> MIDI.MidiEvent -> IO ()
midiCallback c us (MIDI.MidiEvent _ (MIDI.MidiMessage _ (MIDI.NoteOn n _))) =
case lookup n us of
Nothing -> return ()
Just u -> do
t <- utcr
let e = (t, mkEvent u)
-- print e
writeChan c e
midiCallback _ _ _ = return ()
main_midi [dbDir, pattern, thatMany] = do
db <- DB.open dbDir
let us' = DB.query (DB.pathMatch pattern) db
let us = cycle tr505_notes `zip` drop (read thatMany) (cycle us')
Just midiSource <- MIDI.findSource (\"RME" _ "Port 1" -> True)
midi <- newChan
midiConn <- MIDI.openSource midiSource (Just $ midiCallback midi us)
MIDI.start midiConn
playSampler midi
writeLooperEvent : : ( Double , ) - > EM.EventM EM.EKey ( )
--writeLooperEvent c e = liftIO $ do
-- t <- utcr
-- writeChan c (t, e)
--
--main_gui_looper db us' = do
let us = cycle ` zip ` cycle us '
--
-- unsafeInitGUIForThreadedRTS
--
-- window <- windowNew
-- -- windowSetDecorated window False
-- windowSetResizable window True
windowSetPosition window WinPosCenterAlways
--
-- widgetSetAppPaintable window True
-- windowSetTitle window "Fucking hell"
-- windowSetDefaultSize window initialSize initialSize
window ( Just window )
( Just ( 32 , 32 ) ) ( Just ( 512 , 512 ) )
Nothing Nothing ( Just ( 1,1 ) )
--
--
-- window `on` keyPressEvent $ do
-- keyName <- EM.eventKeyName
-- case keyName of
-- "Return" -> do
writeLooperEvent looperInput L.ERecord
-- return True
-- "space" -> do
writeLooperEvent looperInput L.EStart
-- return True
-- "BackSpace" -> do
-- writeLooperEvent looperInput L.EStop
-- return True
" Escape " - > do
liftIO mainQuit
-- return True
-- c -> if elem c keyChars
-- then let Just u = lookup c us
-- in do
writeLooperEvent looperInput ( ( mkEvent u ) )
-- return True
-- else return False
forkIO $ L.run ( looperInput , )
-- forkIO $ playSampler looperOutput
--
-- widgetShowAll window
-- mainGUI
--
writePlayerEvent : : ( Double , ) - > P.Event - > EM.EventM EM.EKey ( )
--writePlayerEvent c e = liftIO $ do
-- t <- utcr
-- writeChan c (t, e)
--
getEvents : : WidgetClass w = > w - > IO ( Chan Event )
getEvents w = do
-- prevEventRef <- newIORef Nothing
-- output <- newChan
onKeyPress w $ \e - > do
-- prevEvent <- readIORef prevEventRef
-- case prevEvent of
-- Nothing -> do
-- write prevEventRef (eventKeyVal e, eventModifier e)
-- writeChan output e
-- return True
-- Just (val, mods) -> do
if = = eventKeyVal e & & mods = = eventModifier e
-- then return False
-- else do
-- write prevEventRef (eventKeyVal e, eventModifier e)
-- writeChan output e
-- return True
-- onKeyRelease w $ \e -> do
-- writeIORef prevEventRef Nothing
-- writeChan output e
-- return True
-- return output
-- where
-- write r x = writeIORef r $ Just x
--
mapEvents :: [(Char, Unit.Unit)] -> Chan Key -> Chan (Double, P.Event) -> IO ()
mapEvents us iChan oChan = do
i <- readChan iChan
case i of
Char c -> do
case lookup c us of
Nothing -> return ()
Just u -> do
t <- utcr
writeChan oChan (t, mkEvent u)
_ -> return ()
mapEvents us iChan oChan
main_gui db us' = do
let us = keyChars `zip` cycle us'
events <- newChan
playerInput <- newChan
keyboardMouseCallback $= Just (keyboardMouseHandler events)
forkIO $ mapEvents us events playerInput
forkIO $ playSampler playerInput
mainLoop
main_ :: [String] -> IO ()
main_ [dbDir, pattern] = do
db <- DB.open dbDir
let us = DB.query (DB.pathMatch pattern) db
main_gui db us
keyboardMouseHandler :: Chan Key -> KeyboardMouseCallback
keyboardMouseHandler _ (Char '\27') Down _ _ = safeExitWith ExitSuccess
keyboardMouseHandler c e Down _ _ = writeChan c e
keyboardMouseHandler _ _ _ _ _ = return ()
safeExitWith :: ExitCode -> IO a
safeExitWith code = do
-- gma <- get gameModeActive
when gma leaveGameMode
exitWith code
render :: DisplayCallback
render = do
-- clear screen and depth buffer
clear [ ColorBuffer, DepthBuffer ]
loadIdentity
setupProjection :: ReshapeCallback
setupProjection (Size width height) = do
do n't want a divide by zero
let h = max 1 height
-- reset the viewport to new dimensions
viewport $= (Position 0 0, Size width h)
-- set projection matrix as the current matrix
matrixMode $= Projection
-- reset projection matrix
loadIdentity
-- calculate aspect ratio of window
perspective 52 (fromIntegral width / fromIntegral h) 1 1000
-- set modelview matrix
matrixMode $= Modelview 0
-- reset modelview matrix
loadIdentity
--fullscreenMode :: Options -> IO ()
--fullscreenMode opts = do
let addCapability c = maybe i d ( \x - > ( Where ' c IsEqualTo x :))
-- gameModeCapabilities $=
( addCapability GameModeWidth ( Just ( windowWidth opts ) ) .
addCapability GameModeHeight ( Just ( opts ) ) .
addCapability GameModeBitsPerPlane ( bpp opts ) .
addCapability GameModeRefreshRate ( opts ) ) [ ]
-- enterGameMode
-- maybeWin <- get currentWindow
if isJust maybeWin
-- then cursor $= None
-- else do
-- hPutStr stderr "Could not enter fullscreen mode, using windowed mode\n"
-- windowedMode (opts { useFullscreen = False } )
windowedMode :: IO ()
windowedMode = do
initialWindowSize $= Size (fromIntegral 200) (fromIntegral 200)
createWindow "Fucking Hell"
return ()
main_glut :: IO ()
main_glut = do
Setup the basic GLUT stuff
(_, args) <- getArgsAndInitialize
initialDisplayMode $= [ DoubleBuffered, RGBMode, WithDepthBuffer ]
windowedMode
-- Register the event callback functions
displayCallback $= do { render ; swapBuffers }
reshapeCallback $= Just setupProjection
-- idleCallback $= Just (do prepare state; postRedisplay Nothing)
perWindowKeyRepeat $= PerWindowKeyRepeatOff
main_ args
main :: IO ()
main = getArgs >>= main_midi
| null | https://raw.githubusercontent.com/kaoskorobase/mescaline/13554fc4826d0c977d0010c0b4fb74ba12ced6b9/tools/looper.hs | haskell | print e
writeLooperEvent c e = liftIO $ do
t <- utcr
writeChan c (t, e)
main_gui_looper db us' = do
unsafeInitGUIForThreadedRTS
window <- windowNew
-- windowSetDecorated window False
windowSetResizable window True
widgetSetAppPaintable window True
windowSetTitle window "Fucking hell"
windowSetDefaultSize window initialSize initialSize
window `on` keyPressEvent $ do
keyName <- EM.eventKeyName
case keyName of
"Return" -> do
return True
"space" -> do
return True
"BackSpace" -> do
writeLooperEvent looperInput L.EStop
return True
return True
c -> if elem c keyChars
then let Just u = lookup c us
in do
return True
else return False
forkIO $ playSampler looperOutput
widgetShowAll window
mainGUI
writePlayerEvent c e = liftIO $ do
t <- utcr
writeChan c (t, e)
prevEventRef <- newIORef Nothing
output <- newChan
prevEvent <- readIORef prevEventRef
case prevEvent of
Nothing -> do
write prevEventRef (eventKeyVal e, eventModifier e)
writeChan output e
return True
Just (val, mods) -> do
then return False
else do
write prevEventRef (eventKeyVal e, eventModifier e)
writeChan output e
return True
onKeyRelease w $ \e -> do
writeIORef prevEventRef Nothing
writeChan output e
return True
return output
where
write r x = writeIORef r $ Just x
gma <- get gameModeActive
clear screen and depth buffer
reset the viewport to new dimensions
set projection matrix as the current matrix
reset projection matrix
calculate aspect ratio of window
set modelview matrix
reset modelview matrix
fullscreenMode :: Options -> IO ()
fullscreenMode opts = do
gameModeCapabilities $=
enterGameMode
maybeWin <- get currentWindow
then cursor $= None
else do
hPutStr stderr "Could not enter fullscreen mode, using windowed mode\n"
windowedMode (opts { useFullscreen = False } )
Register the event callback functions
idleCallback $= Just (do prepare state; postRedisplay Nothing) | # LANGUAGE ScopedTypeVariables #
import Language.Haskell.Interpreter (InterpreterError(..), GhcError(..))
import Control.Concurrent
import Control.Concurrent.Chan
import Control.Concurrent.MVar
import Control.Monad (unless)
import Control.Monad.Trans (liftIO)
import Data.Accessor
import Data.IORef
import qualified Mescaline.Database.FlatFile as DB
import Mescaline.Database.SourceFile as SourceFile
import Mescaline.Database.Unit as Unit
import Mescaline.Synth.Concat
import qualified Mescaline.Synth.Pattern as P
import Mescaline.Synth.Pattern.Load as P
import qualified Mescaline.Sampler.GUI as GUI
import qualified Mescaline.Sampler.Keyboard as GUI
import qualified Mescaline.Sampler.MIDI as MIDI
import qualified Mescaline.Sampler.Looper as L
import System.Environment (getArgs)
import Control.Exception
import Sound.SC3
import Sound.OpenSoundControl (utcr)
import Sound.OpenSoundControl.Transport
import Sound.OpenSoundControl.Transport.UDP (UDP)
import System.Exit (ExitCode(..), exitWith)
import System.FilePath
import Prelude hiding (catch)
import Graphics.UI.GLUT
playSampler :: Chan (Double, P.Event) -> IO ()
playSampler = bracket newSampler freeSampler . flip runSampler
initialSize :: Int
initialSize = 256
keyChars = [
'z' , 'a' , 'q'
, 'x' , 's' , 'w'
, 'c' , 'd' , 'e'
, 'v' , 'f' , 'r'
, 'b' , 'g' , 't'
, 'n' , 'h' , 'y'
, 'm' , 'j' , 'u'
]
tr505_notes = concat [
[ 43 .. 50 ]
, [ 35 .. 42 ]
]
latency :: Double
latency = 0.015
mkEvent :: Unit.Unit -> P.Event
mkEvent = setVal (P.synth.>P.latency) latency . P.event
midiCallback :: Chan (Double, P.Event) -> [(Int, Unit.Unit)] -> MIDI.MidiEvent -> IO ()
midiCallback c us (MIDI.MidiEvent _ (MIDI.MidiMessage _ (MIDI.NoteOn n _))) =
case lookup n us of
Nothing -> return ()
Just u -> do
t <- utcr
let e = (t, mkEvent u)
writeChan c e
midiCallback _ _ _ = return ()
main_midi [dbDir, pattern, thatMany] = do
db <- DB.open dbDir
let us' = DB.query (DB.pathMatch pattern) db
let us = cycle tr505_notes `zip` drop (read thatMany) (cycle us')
Just midiSource <- MIDI.findSource (\"RME" _ "Port 1" -> True)
midi <- newChan
midiConn <- MIDI.openSource midiSource (Just $ midiCallback midi us)
MIDI.start midiConn
playSampler midi
writeLooperEvent : : ( Double , ) - > EM.EventM EM.EKey ( )
let us = cycle ` zip ` cycle us '
windowSetPosition window WinPosCenterAlways
window ( Just window )
( Just ( 32 , 32 ) ) ( Just ( 512 , 512 ) )
Nothing Nothing ( Just ( 1,1 ) )
writeLooperEvent looperInput L.ERecord
writeLooperEvent looperInput L.EStart
" Escape " - > do
liftIO mainQuit
writeLooperEvent looperInput ( ( mkEvent u ) )
forkIO $ L.run ( looperInput , )
writePlayerEvent : : ( Double , ) - > P.Event - > EM.EventM EM.EKey ( )
getEvents : : WidgetClass w = > w - > IO ( Chan Event )
getEvents w = do
onKeyPress w $ \e - > do
if = = eventKeyVal e & & mods = = eventModifier e
mapEvents :: [(Char, Unit.Unit)] -> Chan Key -> Chan (Double, P.Event) -> IO ()
mapEvents us iChan oChan = do
i <- readChan iChan
case i of
Char c -> do
case lookup c us of
Nothing -> return ()
Just u -> do
t <- utcr
writeChan oChan (t, mkEvent u)
_ -> return ()
mapEvents us iChan oChan
main_gui db us' = do
let us = keyChars `zip` cycle us'
events <- newChan
playerInput <- newChan
keyboardMouseCallback $= Just (keyboardMouseHandler events)
forkIO $ mapEvents us events playerInput
forkIO $ playSampler playerInput
mainLoop
main_ :: [String] -> IO ()
main_ [dbDir, pattern] = do
db <- DB.open dbDir
let us = DB.query (DB.pathMatch pattern) db
main_gui db us
keyboardMouseHandler :: Chan Key -> KeyboardMouseCallback
keyboardMouseHandler _ (Char '\27') Down _ _ = safeExitWith ExitSuccess
keyboardMouseHandler c e Down _ _ = writeChan c e
keyboardMouseHandler _ _ _ _ _ = return ()
safeExitWith :: ExitCode -> IO a
safeExitWith code = do
when gma leaveGameMode
exitWith code
render :: DisplayCallback
render = do
clear [ ColorBuffer, DepthBuffer ]
loadIdentity
setupProjection :: ReshapeCallback
setupProjection (Size width height) = do
do n't want a divide by zero
let h = max 1 height
viewport $= (Position 0 0, Size width h)
matrixMode $= Projection
loadIdentity
perspective 52 (fromIntegral width / fromIntegral h) 1 1000
matrixMode $= Modelview 0
loadIdentity
let addCapability c = maybe i d ( \x - > ( Where ' c IsEqualTo x :))
( addCapability GameModeWidth ( Just ( windowWidth opts ) ) .
addCapability GameModeHeight ( Just ( opts ) ) .
addCapability GameModeBitsPerPlane ( bpp opts ) .
addCapability GameModeRefreshRate ( opts ) ) [ ]
if isJust maybeWin
windowedMode :: IO ()
windowedMode = do
initialWindowSize $= Size (fromIntegral 200) (fromIntegral 200)
createWindow "Fucking Hell"
return ()
main_glut :: IO ()
main_glut = do
Setup the basic GLUT stuff
(_, args) <- getArgsAndInitialize
initialDisplayMode $= [ DoubleBuffered, RGBMode, WithDepthBuffer ]
windowedMode
displayCallback $= do { render ; swapBuffers }
reshapeCallback $= Just setupProjection
perWindowKeyRepeat $= PerWindowKeyRepeatOff
main_ args
main :: IO ()
main = getArgs >>= main_midi
|
7e335abc554feb46d7d873d7682ceae9f3a56ed94ce0a3de4094812309776515 | pusher/stronghold | SQLiteInterface.hs | # LANGUAGE OverloadedStrings , GADTs #
module SQLiteInterface where
import Control.Concurrent.STM (TVar, STM, atomically, retry)
import Control.Monad (when)
import Control.Monad.Operational (ProgramViewT (..), view)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe (MaybeT (..))
import Crypto.Hash.SHA1 (hash)
import Data.ByteString (ByteString)
import Data.Maybe (isJust, listToMaybe )
import Data.Serialize (decode, encode)
import StoredData (StoreOp)
import qualified Control.Concurrent.STM as STM
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as Base16
import qualified Database.SQLite.Simple as SQL
import qualified StoredData as SD
data SQLiteInterface = SQLiteInterface (TVar ByteString) SQL.Connection
nilNode = encode (SD.HistoryNode SD.Nil)
nilHash = (Base16.encode . hash) nilNode
populateEmpty :: SQL.Connection -> IO ByteString
populateEmpty conn = do
mapM_
(SQL.execute conn "INSERT INTO refs values (?, ?)")
[("head", nilHash), (nilHash, nilNode)]
return nilHash
newSQLiteInterface :: FilePath -> IO SQLiteInterface
newSQLiteInterface filename = do
conn <- SQL.open filename
SQL.execute_
conn
"CREATE TABLE IF NOT EXISTS refs (key string primary key, value string)"
head <-
SQL.query
conn
"SELECT value from refs where key=?"
(SQL.Only ("head" :: ByteString))
head' <- maybe (populateEmpty conn) (return . SQL.fromOnly) (listToMaybe head)
var <- STM.newTVarIO head'
return (SQLiteInterface var conn)
getHeadSTM :: SQLiteInterface -> STM ByteString
getHeadSTM (SQLiteInterface var _) = STM.readTVar var
getHead :: SQLiteInterface -> MaybeT IO B.ByteString
getHead sql = lift $ atomically $ getHeadSTM sql
getHeadBlockIfEq :: SQLiteInterface -> B.ByteString -> MaybeT IO B.ByteString
getHeadBlockIfEq sql ref = lift $ atomically $ do
head <- getHeadSTM sql
if head == ref then
retry
else
return head
updateHead :: SQLiteInterface -> ByteString -> ByteString -> MaybeT IO Bool
updateHead (SQLiteInterface var conn) old new = lift $ do
b <- atomically $ do
head <- STM.readTVar var
if head == old then do
STM.writeTVar var new
return True
else
return False
when b $
SQL.execute
conn
"UPDATE refs set value=? where key=?"
(new, "head" :: ByteString)
return b
loadData :: SQLiteInterface -> ByteString -> MaybeT IO ByteString
loadData (SQLiteInterface var conn) ref = MaybeT $ do
value <- SQL.query conn "SELECT value from refs where key=?" (SQL.Only ref)
(return . fmap SQL.fromOnly . listToMaybe) value
storeData :: SQLiteInterface -> ByteString -> MaybeT IO ByteString
storeData (SQLiteInterface var conn) value = lift $ do
let ref = (Base16.encode . hash) value
SQL.execute conn "INSERT OR IGNORE INTO refs values (?, ?)" (ref, value)
return ref
hasReference :: SQLiteInterface -> ByteString -> MaybeT IO Bool
hasReference sql ref =
(fmap isJust . lift . runMaybeT) (loadData sql ref)
runStoreOp' :: SQLiteInterface -> SD.StoreOp a -> MaybeT IO a
runStoreOp' sql op =
case view op of
Return x -> return x
SD.Store d :>>= rest -> do
let d' = encode d
ref <- storeData sql d'
runStoreOp' sql (rest (SD.makeRef ref))
SD.Load r :>>= rest -> do
dat <- loadData sql (SD.unref r)
either fail (runStoreOp' sql . rest) (decode dat)
SD.GetHead :>>= rest -> do
head <- getHead sql
runStoreOp' sql (rest (SD.makeRef head))
SD.GetHeadBlockIfEq ref :>>= rest -> do
head <- getHeadBlockIfEq sql (SD.unref ref)
runStoreOp' sql (rest (SD.makeRef head))
SD.UpdateHead old new :>>= rest -> do
b <- updateHead sql (SD.unref old) (SD.unref new)
runStoreOp' sql (rest b)
SD.CreateRef r :>>= rest -> do
b <- hasReference sql r
if b then
runStoreOp' sql (rest (Just (SD.makeRef r)))
else
runStoreOp' sql (rest Nothing)
runStoreOp :: SQLiteInterface -> StoreOp a -> IO (Maybe a)
runStoreOp sql op = runMaybeT (runStoreOp' sql op)
| null | https://raw.githubusercontent.com/pusher/stronghold/b5ec314425d9492f881f46d14b78d76de7b9429b/src/SQLiteInterface.hs | haskell | # LANGUAGE OverloadedStrings , GADTs #
module SQLiteInterface where
import Control.Concurrent.STM (TVar, STM, atomically, retry)
import Control.Monad (when)
import Control.Monad.Operational (ProgramViewT (..), view)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe (MaybeT (..))
import Crypto.Hash.SHA1 (hash)
import Data.ByteString (ByteString)
import Data.Maybe (isJust, listToMaybe )
import Data.Serialize (decode, encode)
import StoredData (StoreOp)
import qualified Control.Concurrent.STM as STM
import qualified Data.ByteString as B
import qualified Data.ByteString.Base16 as Base16
import qualified Database.SQLite.Simple as SQL
import qualified StoredData as SD
data SQLiteInterface = SQLiteInterface (TVar ByteString) SQL.Connection
nilNode = encode (SD.HistoryNode SD.Nil)
nilHash = (Base16.encode . hash) nilNode
populateEmpty :: SQL.Connection -> IO ByteString
populateEmpty conn = do
mapM_
(SQL.execute conn "INSERT INTO refs values (?, ?)")
[("head", nilHash), (nilHash, nilNode)]
return nilHash
newSQLiteInterface :: FilePath -> IO SQLiteInterface
newSQLiteInterface filename = do
conn <- SQL.open filename
SQL.execute_
conn
"CREATE TABLE IF NOT EXISTS refs (key string primary key, value string)"
head <-
SQL.query
conn
"SELECT value from refs where key=?"
(SQL.Only ("head" :: ByteString))
head' <- maybe (populateEmpty conn) (return . SQL.fromOnly) (listToMaybe head)
var <- STM.newTVarIO head'
return (SQLiteInterface var conn)
getHeadSTM :: SQLiteInterface -> STM ByteString
getHeadSTM (SQLiteInterface var _) = STM.readTVar var
getHead :: SQLiteInterface -> MaybeT IO B.ByteString
getHead sql = lift $ atomically $ getHeadSTM sql
getHeadBlockIfEq :: SQLiteInterface -> B.ByteString -> MaybeT IO B.ByteString
getHeadBlockIfEq sql ref = lift $ atomically $ do
head <- getHeadSTM sql
if head == ref then
retry
else
return head
updateHead :: SQLiteInterface -> ByteString -> ByteString -> MaybeT IO Bool
updateHead (SQLiteInterface var conn) old new = lift $ do
b <- atomically $ do
head <- STM.readTVar var
if head == old then do
STM.writeTVar var new
return True
else
return False
when b $
SQL.execute
conn
"UPDATE refs set value=? where key=?"
(new, "head" :: ByteString)
return b
loadData :: SQLiteInterface -> ByteString -> MaybeT IO ByteString
loadData (SQLiteInterface var conn) ref = MaybeT $ do
value <- SQL.query conn "SELECT value from refs where key=?" (SQL.Only ref)
(return . fmap SQL.fromOnly . listToMaybe) value
storeData :: SQLiteInterface -> ByteString -> MaybeT IO ByteString
storeData (SQLiteInterface var conn) value = lift $ do
let ref = (Base16.encode . hash) value
SQL.execute conn "INSERT OR IGNORE INTO refs values (?, ?)" (ref, value)
return ref
hasReference :: SQLiteInterface -> ByteString -> MaybeT IO Bool
hasReference sql ref =
(fmap isJust . lift . runMaybeT) (loadData sql ref)
runStoreOp' :: SQLiteInterface -> SD.StoreOp a -> MaybeT IO a
runStoreOp' sql op =
case view op of
Return x -> return x
SD.Store d :>>= rest -> do
let d' = encode d
ref <- storeData sql d'
runStoreOp' sql (rest (SD.makeRef ref))
SD.Load r :>>= rest -> do
dat <- loadData sql (SD.unref r)
either fail (runStoreOp' sql . rest) (decode dat)
SD.GetHead :>>= rest -> do
head <- getHead sql
runStoreOp' sql (rest (SD.makeRef head))
SD.GetHeadBlockIfEq ref :>>= rest -> do
head <- getHeadBlockIfEq sql (SD.unref ref)
runStoreOp' sql (rest (SD.makeRef head))
SD.UpdateHead old new :>>= rest -> do
b <- updateHead sql (SD.unref old) (SD.unref new)
runStoreOp' sql (rest b)
SD.CreateRef r :>>= rest -> do
b <- hasReference sql r
if b then
runStoreOp' sql (rest (Just (SD.makeRef r)))
else
runStoreOp' sql (rest Nothing)
runStoreOp :: SQLiteInterface -> StoreOp a -> IO (Maybe a)
runStoreOp sql op = runMaybeT (runStoreOp' sql op)
| |
6540589adc227e51cf6fe473fdcf19ec2d3549d837f5bef65875ea684642e5d6 | WorksHub/client | core.cljs | (ns wh.blogs.core
(:require
[cljs.loader :as loader]
[re-frame.core :refer [dispatch dispatch-sync reg-event-db]]
[wh.blogs.blog.db :as blog-db]
[wh.blogs.blog.views :as blog]
[wh.blogs.blog.events]
[wh.blogs.learn.views :as learn]
[wh.blogs.learn.events]
[wh.blogs.liked.views :as liked]
[wh.blogs.liked.events]
[wh.db :as db]))
(def page-mapping
{:blog blog/page
:learn learn/page
:learn-search learn/page
:learn-by-tag learn/page
:liked-blogs liked/page})
(reg-event-db
::initialize-page-mapping
(fn [db _]
(update db ::db/page-mapping merge page-mapping)))
(swap! db/sub-dbs conj ::blog-db/sub-db)
(dispatch-sync [::initialize-page-mapping])
;; don't unset loader here; too early
(db/redefine-app-db-spec!)
(loader/set-loaded! :blogs)
| null | https://raw.githubusercontent.com/WorksHub/client/77e4212a69dad049a9e784143915058acd918982/client/src/wh/blogs/core.cljs | clojure | don't unset loader here; too early | (ns wh.blogs.core
(:require
[cljs.loader :as loader]
[re-frame.core :refer [dispatch dispatch-sync reg-event-db]]
[wh.blogs.blog.db :as blog-db]
[wh.blogs.blog.views :as blog]
[wh.blogs.blog.events]
[wh.blogs.learn.views :as learn]
[wh.blogs.learn.events]
[wh.blogs.liked.views :as liked]
[wh.blogs.liked.events]
[wh.db :as db]))
(def page-mapping
{:blog blog/page
:learn learn/page
:learn-search learn/page
:learn-by-tag learn/page
:liked-blogs liked/page})
(reg-event-db
::initialize-page-mapping
(fn [db _]
(update db ::db/page-mapping merge page-mapping)))
(swap! db/sub-dbs conj ::blog-db/sub-db)
(dispatch-sync [::initialize-page-mapping])
(db/redefine-app-db-spec!)
(loader/set-loaded! :blogs)
|
738ca6831eaac48ff749cea0cfd73b99a23e60543808bc613e16bfcb38c928b8 | Dasudian/DSDIN | dsdct_utils.erl |
-module(dsdct_utils).
-export([hex_bytes/1, hex_byte/1, check_balance/3, check/2]).
-spec hex_byte(byte()) -> string().
hex_byte(N) ->
hex_bytes(<<N:8>>).
-spec hex_bytes(binary()) -> string().
hex_bytes(Bin) ->
lists:flatten("0x" ++ [io_lib:format("~2.16.0B", [B]) || <<B:8>> <= Bin]).
-spec check_balance(dsdc_keys:pubkey(), dsdc_trees:trees(), non_neg_integer()) ->
ok | {error, term()}.
check_balance(ContractKey, Trees, Amount) ->
AccountsTree = dsdc_trees:accounts(Trees),
case dsdc_accounts_trees:lookup(ContractKey, AccountsTree) of
{value, Account} ->
check(dsdc_accounts:balance(Account) >= Amount, insufficient_funds);
none -> {error, contract_not_found}
end.
check(true, _) -> ok;
check(false, Err) -> {error, Err}.
| null | https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/dsdcontract/src/dsdct_utils.erl | erlang |
-module(dsdct_utils).
-export([hex_bytes/1, hex_byte/1, check_balance/3, check/2]).
-spec hex_byte(byte()) -> string().
hex_byte(N) ->
hex_bytes(<<N:8>>).
-spec hex_bytes(binary()) -> string().
hex_bytes(Bin) ->
lists:flatten("0x" ++ [io_lib:format("~2.16.0B", [B]) || <<B:8>> <= Bin]).
-spec check_balance(dsdc_keys:pubkey(), dsdc_trees:trees(), non_neg_integer()) ->
ok | {error, term()}.
check_balance(ContractKey, Trees, Amount) ->
AccountsTree = dsdc_trees:accounts(Trees),
case dsdc_accounts_trees:lookup(ContractKey, AccountsTree) of
{value, Account} ->
check(dsdc_accounts:balance(Account) >= Amount, insufficient_funds);
none -> {error, contract_not_found}
end.
check(true, _) -> ok;
check(false, Err) -> {error, Err}.
| |
c723203016bc1d3544eff2611e5251ab28ab6564d05c90343b1f590f8ce7332e | infi-nl/alibi | entry_page.cljs | (ns alibi.entry-page
(:require
[alibi.logging :refer [log log-cljs]]
[alibi.post-new-entry-bar :as post-new-entry-bar]
[alibi.post-entry-form :as post-entry-form]
[alibi.activity-graphic :as activity-graphic]
[alibi.activity-graphic-data-source :as ag-ds]
[alibi.day-entry-table :as day-entry-table]
[cljs.reader]
[om.core :as om]
[om.dom :as dom]
[alibi.entry-page-state :as state]
[alibi.actions :as actions]))
(defonce state (atom state/initial-state))
(enable-console-print!)
(defn dispatch! [action]
(if (fn? action)
(action dispatch! @state)
(swap! state state/reducer action)))
(let [current-state @state]
(when-not (seq (state/entries current-state))
(dispatch! (actions/entries-load-data
(state/selected-date current-state)))))
(def component-state {:dispatch! dispatch!
:get-state (constantly state)})
; if you wonder why we introduce an itermediate IRender here: it seems Om
ref - cursors only work if there is at least one om / root that binds to the root
atom , so we do that here even though it is not passed on to om / build
see also
(om/root
(fn [_ owner]
(reify
om/IRender
(render [_]
(om/build post-new-entry-bar/entry-bar-form component-state))))
state
{:target (js/document.getElementById "post-new-entry-bar-container")})
(om/root
post-entry-form/om-component
component-state
{:target (js/document.getElementById "entry-form-react-container")})
(om/root
activity-graphic/render-html
component-state
{:target (js/document.getElementById "activity-graphic")})
(om/root
activity-graphic/render-tooltip
component-state
{:target (js/document.getElementById "activity-graphic-tooltip-container")})
(defn render-day-entry-table!
[for-state]
(let [new-date (state/selected-date for-state)]
(day-entry-table/render "day-entry-table" new-date)))
(add-watch
state :renderer
(fn [_ _ _ new-state]
;(log "new-state %o" new-state)
(render-day-entry-table! new-state)))
(reset! state @state)
| null | https://raw.githubusercontent.com/infi-nl/alibi/00e97340ebff483f0ecbb3eef929a4052adbc78b/src/frontend/cljs/alibi/entry_page.cljs | clojure | if you wonder why we introduce an itermediate IRender here: it seems Om
(log "new-state %o" new-state) | (ns alibi.entry-page
(:require
[alibi.logging :refer [log log-cljs]]
[alibi.post-new-entry-bar :as post-new-entry-bar]
[alibi.post-entry-form :as post-entry-form]
[alibi.activity-graphic :as activity-graphic]
[alibi.activity-graphic-data-source :as ag-ds]
[alibi.day-entry-table :as day-entry-table]
[cljs.reader]
[om.core :as om]
[om.dom :as dom]
[alibi.entry-page-state :as state]
[alibi.actions :as actions]))
(defonce state (atom state/initial-state))
(enable-console-print!)
(defn dispatch! [action]
(if (fn? action)
(action dispatch! @state)
(swap! state state/reducer action)))
(let [current-state @state]
(when-not (seq (state/entries current-state))
(dispatch! (actions/entries-load-data
(state/selected-date current-state)))))
(def component-state {:dispatch! dispatch!
:get-state (constantly state)})
ref - cursors only work if there is at least one om / root that binds to the root
atom , so we do that here even though it is not passed on to om / build
see also
(om/root
(fn [_ owner]
(reify
om/IRender
(render [_]
(om/build post-new-entry-bar/entry-bar-form component-state))))
state
{:target (js/document.getElementById "post-new-entry-bar-container")})
(om/root
post-entry-form/om-component
component-state
{:target (js/document.getElementById "entry-form-react-container")})
(om/root
activity-graphic/render-html
component-state
{:target (js/document.getElementById "activity-graphic")})
(om/root
activity-graphic/render-tooltip
component-state
{:target (js/document.getElementById "activity-graphic-tooltip-container")})
(defn render-day-entry-table!
[for-state]
(let [new-date (state/selected-date for-state)]
(day-entry-table/render "day-entry-table" new-date)))
(add-watch
state :renderer
(fn [_ _ _ new-state]
(render-day-entry-table! new-state)))
(reset! state @state)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.